diff --git a/.clomonitor.yml b/.clomonitor.yml new file mode 100644 index 00000000000..b5ccb7e3e6d --- /dev/null +++ b/.clomonitor.yml @@ -0,0 +1,8 @@ +# see https://github.com/cncf/clomonitor/blob/main/docs/checks.md#exemptions +exemptions: + - check: artifacthub_badge + reason: "Artifact Hub doesn't support Java packages" + - check: signed_releases + reason: "Maven central releases are signed and there are no GitHub release artifacts" + - check: openssf_badge + reason: "ETOOMANYBADGES, but the work has been done: https://www.bestpractices.dev/projects/9991" diff --git a/.codecov.yaml b/.codecov.yaml index 3d9d63306b2..1a61103a0bc 100644 --- a/.codecov.yaml +++ b/.codecov.yaml @@ -11,17 +11,17 @@ coverage: status: project: default: - target: 90% + target: 89% paths: - "!opencensus-shim/" - "!opentracing-shim/" - - "!sdk-extensions/zpages/" + # exclude declarative config generated POJOs + - "!sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/" unmaintained: target: 80% paths: - "opencensus-shim/" - "opentracing-shim/" - - "sdk-extensions/zpages/" patch: default: target: 80% diff --git a/.editorconfig b/.editorconfig index 0e0c24da729..3e9889f6c8b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -3,7 +3,7 @@ charset = utf-8 end_of_line = lf indent_size = 2 indent_style = space -insert_final_newline = false +insert_final_newline = true max_line_length = 100 tab_width = 2 ij_continuation_indent_size = 4 diff --git a/.fossa.yml b/.fossa.yml new file mode 100644 index 00000000000..87c35f5bcae --- /dev/null +++ b/.fossa.yml @@ -0,0 +1,40 @@ +version: 3 + +targets: + only: + - type: gradle + exclude: + # these modules are not published and so consumers will not be exposed to them + - type: gradle + path: ./ + target: ':api:testing-internal' + - type: gradle + path: ./ + target: ':exporters:otlp:testing-internal' + - type: gradle + path: ./ + target: ':integration-tests' + - type: gradle + path: ./ + target: ':integration-tests:graal' + - type: gradle + path: ./ + target: ':integration-tests:graal-incubating' + - type: gradle + path: ./ + target: ':integration-tests:otlp' + - type: gradle + path: ./ + target: ':integration-tests:tracecontext' + - type: gradle + path: ./ + target: ':perf-harness' + - type: gradle + path: ./ + target: ':testing-internal' + +experimental: + gradle: + configurations-only: + # consumer will only be exposed to these dependencies + - runtimeClasspath diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5ce1713aee2..fcae66867e3 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,5 +1,6 @@ -# Code owners file. -# This file controls who is tagged for review for any given pull request. +# +# Learn about membership in OpenTelemetry community: +# https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md +# - # For anything not explicitly taken by someone else: -* @anuraaga @jack-berg @jkwatson @jsuereth @kubawach @Oberon00 +* @open-telemetry/java-approvers diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 2190f784e40..1bafe4e7d71 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -25,10 +25,12 @@ Version: (e.g., `v0.4.0`, `1eb551b`, etc) How did you reference these artifacts? (excerpt from your `build.gradle`, `pom.xml`, etc) **Environment** -Compiler: (e.g., "AdoptOpenJDK 11.0.6") +Compiler: (e.g., "Temurin 17.0.7") OS: (e.g., "Ubuntu 20.04") Runtime (if different from JDK above): (e.g., "Oracle JRE 8u251") OS (if different from OS compiled on): (e.g., "Windows Server 2019") **Additional context** Add any other context about the problem here. + +**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with πŸ‘ to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/). diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index 7b124ce80f0..d212bc8bedc 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -18,3 +18,5 @@ A clear and concise description of any alternative solutions or features you've **Additional context** Add any other context or screenshots about the feature request here. + +**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with πŸ‘ to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/). diff --git a/.github/config/flint.toml b/.github/config/flint.toml new file mode 100644 index 00000000000..d1d7d128746 --- /dev/null +++ b/.github/config/flint.toml @@ -0,0 +1,2 @@ +[checks.lychee] +check_all_local = true diff --git a/.github/config/lychee.toml b/.github/config/lychee.toml new file mode 100644 index 00000000000..e10e9c1b403 --- /dev/null +++ b/.github/config/lychee.toml @@ -0,0 +1,22 @@ +# Lychee configuration file +# See https://lychee.cli.rs/config/ + +timeout = 30 +retry_wait_time = 5 +max_retries = 6 +max_concurrency = 4 + +# Check link anchors. Lychee 0.24+ expects a mode string here. +include_fragments = "full" + +# Type anchors are generated by JavaScript. Check the page without its fragment. +remap = [ + '^https://opentelemetry\.io/docs/specs/otel-config/types/#.*$ https://opentelemetry.io/docs/specs/otel-config/types/', +] + +# excluding links to pull requests and issues is done for performance +exclude = [ + "^https://github.com/open-telemetry/opentelemetry-java/(issues|pull)/\\d+$", + "^https://www.javadoc.io/badge/(.*?)/(.*?).svg$", # returns 522 + "^https://cloud-native.slack.com/", # slack requires auth +] diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index 123014908be..00000000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,6 +0,0 @@ -version: 2 -updates: - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "daily" diff --git a/.github/renovate.json5 b/.github/renovate.json5 new file mode 100644 index 00000000000..d0d4e163a0b --- /dev/null +++ b/.github/renovate.json5 @@ -0,0 +1,221 @@ +{ + $schema: 'https://docs.renovatebot.com/renovate-schema.json', + extends: [ + 'config:best-practices', + 'helpers:pinGitHubActionDigestsToSemver', + ], + ignorePaths: [], // overwrite default ignore which includes **/test/** + // used to update docker image versions used in Java test files + packageRules: [ + + // ── Scheduling & grouping ────────────────────────────────────────── + + { + // group all patch updates into a single weekly PR + groupName: 'all patch and minor versions', + matchUpdateTypes: [ + 'patch', + 'minor', + ], + schedule: [ + '* 0-7 * * 2', // weekly, before 8am on Tuesday + ], + }, + { + // group GitHub Actions and dockerfile updates into a single weekly PR + // (must be after patch rule so that it wins for GH Action patches) + matchManagers: [ + 'github-actions', + 'dockerfile', + ], + schedule: [ + '* 0-7 * * 2', // weekly, before 8am on Tuesday + ], + groupName: 'weekly update', + }, + { + // keep Kotlin Gradle plugin updates out of the catch-all patch PR because CodeQL often + // fails on them, which blocks unrelated patch updates + matchDepNames: [ + 'org.jetbrains.kotlin.jvm', + 'org.jetbrains.kotlin:kotlin-gradle-plugin', + ], + schedule: [ + '* 0-7 * * 2', // weekly, before 8am on Tuesday + ], + groupName: 'kotlin plugin updates', + }, + + // ── Version constraints ──────────────────────────────────────────── + + { + matchPackageNames: [ + 'io.opentelemetry.contrib:opentelemetry-aws-xray-propagator', + 'io.opentelemetry.proto:opentelemetry-proto', + 'io.opentelemetry.semconv:opentelemetry-semconv-incubating', + ], + // Renovate's default behavior is only to update from unstable -> unstable if it's for the + // major.minor.patch, under the assumption that you would want to update to the stable version + // of that release instead of the unstable version for a future release + // (TODO remove once the artifacts above release stable versions) + ignoreUnstable: false, + allowedVersions: '!/\\-SNAPSHOT$/', + }, + + // ── Package family groups ────────────────────────────────────────── + + { + groupName: 'spotless packages', + matchPackageNames: [ + 'com.diffplug.spotless', + 'com.diffplug.spotless:**', + ], + }, + // Disable prometheus minor updates while working out translation strategy + // https://github.com/open-telemetry/opentelemetry-java/pull/8346 + { + matchPackageNames: [ + 'io.prometheus:**', + ], + matchUpdateTypes: [ + 'minor', + ], + enabled: false, + }, + // ── Disabled updates (Java version compatibility) ────────────────── + { + // junit 6+ requires Java 17+ + matchPackageNames: [ + 'org.junit:**', + 'org.junit.jupiter:**', + 'org.junit.platform:**', + ], + matchUpdateTypes: [ + 'major', + ], + enabled: false, + }, + { + // junit-pioneer 2+ requires Java 11+ + matchPackageNames: [ + 'org.junit-pioneer:junit-pioneer', + ], + matchUpdateTypes: [ + 'major', + ], + enabled: false, + }, + { + // mockito 5+ requires Java 11+ + matchUpdateTypes: [ + 'major', + ], + enabled: false, + matchPackageNames: [ + 'org.mockito:**', + ], + }, + { + // snakeyaml-engine 3+ requires Java 11+ + matchUpdateTypes: [ + 'major', + ], + enabled: false, + matchPackageNames: [ + 'org.snakeyaml:snakeyaml-engine' + ], + }, + { + // jqf-fuzz version 1.8+ requires Java 11+ + matchPackageNames: [ + 'edu.berkeley.cs.jqf:jqf-fuzz', + ], + matchUpdateTypes: [ + 'major', + 'minor', + ], + enabled: false, + }, + { + // pinned version for compatibility + matchPackageNames: [ + 'org.jetbrains.kotlinx:kotlinx-coroutines-core', + ], + matchCurrentVersion: '1.5.2', + enabled: false, + }, + { + // equalsverifier v4+ requires Java 17+ + // https://github.com/jqno/equalsverifier/blob/HEAD/CHANGELOG.md#changed-13 + matchPackageNames: ['nl.jqno.equalsverifier:equalsverifier'], + matchUpdateTypes: ['major'], + enabled: false, + }, + { + // mockserver-netty 6+ requires Java 11+ + matchPackageNames: ['org.mock-server:mockserver-netty'], + matchUpdateTypes: ['major'], + enabled: false, + }, + ], + customDatasources: { + 'azul-zulu': { + // The Docker datasource scans thousands of tags and can hit Docker Hub rate limits. + // This filtered datasource returns only major versions for scalar Java markers. + defaultRegistryUrlTemplate: 'https://hub.docker.com/v2/repositories/library/azul-zulu/tags?page_size=100&name=-jdk-debian', + transformTemplates: [ + '{"releases": results[$match(name, /^\\d+-jdk-debian$/)].{"version": $substringBefore(name, "-jdk-debian")}}', + ], + }, + }, + customManagers: [ + { + // keep SHA-pinned raw.githubusercontent.com URLs in mise.toml up to date + customType: 'regex', + datasourceTemplate: 'github-tags', + managerFilePatterns: [ + '/^mise\\.toml$/', + ], + matchStrings: [ + 'https://raw\\.githubusercontent\\.com/(?[^/]+/[^/]+)/(?[a-f0-9]{40})/.*#\\s*(?v\\S+)', + ], + }, + { + customType: 'regex', + datasourceTemplate: 'custom.azul-zulu', + managerFilePatterns: [ + '.github/workflows/**', + ], + matchStrings: [ + '(?\\d+) # renovate\\(java-version\\)', + ], + // Zulu publishes new feature releases quickly. + depNameTemplate: 'azul-zulu', + versioningTemplate: 'regex:^(?\\d+)$', + }, + { + customType: 'regex', + datasourceTemplate: 'docker', + managerFilePatterns: [ + '.github/workflows/**', + ], + matchStrings: [ + '(?\\d+) # renovate\\(graal-java-version\\)', + ], + // gates updates on GraalVM Community actually publishing support for a Java version + depNameTemplate: 'ghcr.io/graalvm/graalvm-community', + }, + { + customType: 'regex', + datasourceTemplate: 'docker', + managerFilePatterns: [ + '**/*.java', + ], + matchStrings: [ + '"(?otel/opentelemetry-collector-contrib):(?[^@"]+)(?:@(?sha256:[a-f0-9]+))?"', + ], + autoReplaceStringTemplate: '"{{depName}}:{{newValue}}{{#if newDigest}}@{{newDigest}}{{/if}}"', + versioningTemplate: 'docker', + }, + ], +} diff --git a/.github/repository-settings.md b/.github/repository-settings.md new file mode 100644 index 00000000000..74b3af521f6 --- /dev/null +++ b/.github/repository-settings.md @@ -0,0 +1,33 @@ +# Repository settings + +This document describes any changes that have been made to the +settings in this repository outside the settings tracked in the +private admin repo. + + +## Environments + +### `protected` environment + +Deployment branches: `main`, `release/*` + +Secrets: + +- `GPG_PASSWORD` - stored in OpenTelemetry-Java 1Password +- `GPG_PRIVATE_KEY` - stored in OpenTelemetry-Java 1Password +- `SONATYPE_GUIDE_PAT` - owned by [@jack-berg](https://github.com/jack-berg) +- `SONATYPE_KEY` - owned by [@jack-berg](https://github.com/jack-berg) +- `SONATYPE_USER` - owned by [@jack-berg](https://github.com/jack-berg) + +## Secrets and variables > Actions + +### Organization secrets + +- `CODECOV_TOKEN` +- `DEVELOCITY_ACCESS_KEY` (scoped only to Java repos) +- `FOSSA_API_KEY` +- `OTELBOT_PRIVATE_KEY` + +### Organization variables + +- `OTELBOT_APP_ID` diff --git a/.github/scripts/draft-change-log-entries.sh b/.github/scripts/draft-change-log-entries.sh new file mode 100755 index 00000000000..72e943b4f24 --- /dev/null +++ b/.github/scripts/draft-change-log-entries.sh @@ -0,0 +1,34 @@ +#!/bin/bash -e + +version=$("$(dirname "$0")/get-version.sh") + +if [[ $version =~ ([0-9]+)\.([0-9]+)\.0 ]]; then + major="${BASH_REMATCH[1]}" + minor="${BASH_REMATCH[2]}" +else + echo "unexpected version: $version" + exit 1 +fi + +if [[ $minor == 0 ]]; then + prior_major=$((major - 1)) + prior_minor=$(sed -n "s/^## Version $prior_major\.\([0-9]\+\)\..*/\1/p" CHANGELOG.md | head -1) + if [[ -z $prior_minor ]]; then + # assuming this is the first release + range= + else + range="v$prior_major.$prior_minor.0..HEAD" + fi +else + range="v$major.$((minor - 1)).0..HEAD" +fi + +echo "## Unreleased" +echo + +git log --reverse \ + --perl-regexp \ + --author='^(?!renovate\[bot\] )' \ + --pretty=format:"* %s" \ + "$range" \ + | sed -E 's,\(#([0-9]+)\)$,\n ([#\1](https://github.com/open-telemetry/opentelemetry-java/pull/\1)),' diff --git a/.github/scripts/generate-release-contributors.sh b/.github/scripts/generate-release-contributors.sh index c6526c8f3a0..c506447a323 100755 --- a/.github/scripts/generate-release-contributors.sh +++ b/.github/scripts/generate-release-contributors.sh @@ -1,14 +1,16 @@ #!/bin/bash -e -# shellcheck disable=SC2016 -# shellcheck disable=SC2086 - # this should be run on the release branch +# NOTE if you need to run this script locally, you will need to first: +# git fetch upstream main +# git push origin upstream/main:main +# export GITHUB_REPOSITORY=open-telemetry/opentelemetry-java + from_version=$1 # get the date of the first commit that was not in the from_version -from=$(git log --reverse --pretty=format:"%cI" $from_version..HEAD | head -1) +from=$(git log --reverse --pretty=format:"%cI" "$from_version..HEAD" | head -1) # get the last commit on main that was included in the release to=$(git merge-base origin/main HEAD | xargs git log -1 --pretty=format:"%cI") @@ -50,6 +52,8 @@ query($q: String!, $endCursor: String) { # this query captures authors of issues which have had PRs in the current range reference the issue # but not necessarily through closingIssuesReferences (e.g. addressing just a part of an issue) +# +# note: [^0-9<&#;] below excludes HTML entity markers to avoid matching Ӓ as issue #1234 contributors2=$(gh api graphql --paginate -F q="repo:$GITHUB_REPOSITORY is:pr base:main is:merged merged:$from..$to" -f query=' query($q: String!, $endCursor: String) { search(query: $q, type: ISSUE, first: 100, after: $endCursor) { @@ -67,18 +71,22 @@ query($q: String!, $endCursor: String) { } } ' --jq '.data.search.edges.[].node.body' \ - | grep -oE "#[0-9]{4,}|$GITHUB_REPOSITORY/issues/[0-9]{4,}" \ - | grep -oE "[0-9]{4,}" \ + | grep -oE "#[0-9]{3,}$|#[0-9]{3,}[^0-9<&#;]|$GITHUB_REPOSITORY/issues/[0-9]{3,}" \ + | grep -oE "[0-9]{3,}" \ | xargs -I{} gh issue view {} --json 'author,url' --jq '[.author.login,.url]' \ | grep -v '/pull/' \ | sed 's/^\["//' \ | sed 's/".*//') -echo $contributors1 $contributors2 \ +echo "$contributors1" "$contributors2" \ | sed 's/ /\n/g' \ | sort -uf \ - | grep -v linux-foundation-easycla \ - | grep -v github-actions \ - | grep -v dependabot \ | grep -v codecov \ + | grep -v copilot-pull-request-reviewer \ + | grep -v copilot-swe-agent \ + | grep -v github-actions \ + | grep -v github-advanced-security \ + | grep -v linux-foundation-easycla \ + | grep -v otelbot \ + | grep -v renovate \ | sed 's/^/@/' diff --git a/.github/scripts/get-prior-version.sh b/.github/scripts/get-prior-version.sh new file mode 100755 index 00000000000..ca4987f09ac --- /dev/null +++ b/.github/scripts/get-prior-version.sh @@ -0,0 +1,22 @@ +version=$(.github/scripts/get-version.sh) +if [[ $version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then + major="${BASH_REMATCH[1]}" + minor="${BASH_REMATCH[2]}" + patch="${BASH_REMATCH[3]}" +else + echo "unexpected version: $version" + exit 1 +fi +if [[ $patch == 0 ]]; then + if [[ $minor == 0 ]]; then + prior_major=$((major - 1)) + prior_minor=$(grep -Po "^## Version $prior_major.\K[0-9]+" CHANGELOG.md | head -1) + prior_version="$prior_major.$prior_minor" + else + prior_version="$major.$((minor - 1)).0" + fi +else + prior_version="$major.$minor.$((patch - 1))" +fi + +echo $prior_version diff --git a/.github/scripts/get-version.sh b/.github/scripts/get-version.sh index e4863e93e32..3efbd7754ec 100755 --- a/.github/scripts/get-version.sh +++ b/.github/scripts/get-version.sh @@ -1,3 +1,3 @@ #!/bin/bash -e -grep -Eo "[0-9]+.[0-9]+.0" version.gradle.kts +grep "var ver = " version.gradle.kts | grep -Eo "[0-9]+\.[0-9]+\.[0-9]+" diff --git a/.github/scripts/markdown-link-check-config.json b/.github/scripts/markdown-link-check-config.json deleted file mode 100644 index a458029d5d9..00000000000 --- a/.github/scripts/markdown-link-check-config.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "retryOn429": true, - "aliveStatusCodes": [ - 200, - 403 - ] -} diff --git a/.github/scripts/markdown-link-check-with-retry.sh b/.github/scripts/markdown-link-check-with-retry.sh deleted file mode 100755 index 109146abfec..00000000000 --- a/.github/scripts/markdown-link-check-with-retry.sh +++ /dev/null @@ -1,17 +0,0 @@ -#!/bin/bash -e - -# this script helps to reduce sporadic link check failures by retrying at a file-by-file level - -retry_count=3 - -for file in "$@"; do - for i in $(seq 1 $retry_count); do - if markdown-link-check --config "$(dirname "$0")/markdown-link-check-config.json" \ - "$file"; then - break - elif [[ $i -eq $retry_count ]]; then - exit 1 - fi - sleep 5 - done -done diff --git a/.github/scripts/merge-change-log-after-release.sh b/.github/scripts/merge-change-log-after-release.sh new file mode 100755 index 00000000000..1b95eeb8cb4 --- /dev/null +++ b/.github/scripts/merge-change-log-after-release.sh @@ -0,0 +1,44 @@ +#!/bin/bash -e + +# this script merges release notes for $VERSION into CHANGELOG.md +# the release date for $VERSION should be available in $RELEASE_DATE +# and the release notes for $VERSION should be available in /tmp/changelog-section.md + +if [[ $VERSION =~ ^[0-9]+\.[0-9]+\.0 ]]; then + # this was not a patch release, so the version exists already in the CHANGELOG.md + + # update the release date + sed -Ei "s/## Version $VERSION .*/## Version $VERSION ($RELEASE_DATE)/" CHANGELOG.md + + # the entries are copied over from the release branch to support workflows + # where change log entries may be updated after preparing the release branch + + { + # copy the portion above the release, up to and including the heading + sed -n "0,/^## Version $VERSION /p" CHANGELOG.md + # copy the release notes for $VERSION + cat /tmp/changelog-section.md + # copy the portion below the release + sed -n "0,/^## Version $VERSION /d;0,/^## Version /{/^## Version/!d};p" CHANGELOG.md + } > /tmp/CHANGELOG.md + + # update the real CHANGELOG.md + cp /tmp/CHANGELOG.md CHANGELOG.md + +else + # this was a patch release, so the version does not exist already in the CHANGELOG.md + + { + # copy the portion above the top-most release, not including the heading + sed -n "0,/^## Version /{ /^## Version /!p }" CHANGELOG.md + # add the heading + echo "## Version $VERSION ($RELEASE_DATE)" + # copy the release notes for $VERSION + cat /tmp/changelog-section.md + # copy the portion starting from the top-most release + sed -n "/^## Version /,\$p" CHANGELOG.md + } > /tmp/CHANGELOG.md + + # update the real CHANGELOG.md + cp /tmp/CHANGELOG.md CHANGELOG.md +fi diff --git a/.github/scripts/set-git-user.sh b/.github/scripts/set-git-user.sh deleted file mode 100755 index 17f2c07ad34..00000000000 --- a/.github/scripts/set-git-user.sh +++ /dev/null @@ -1,4 +0,0 @@ -#!/bin/bash -e - -git config user.name opentelemetry-java-bot -git config user.email 97938252+opentelemetry-java-bot@users.noreply.github.com diff --git a/.github/scripts/update-version.sh b/.github/scripts/update-version.sh new file mode 100755 index 00000000000..8d95cac9327 --- /dev/null +++ b/.github/scripts/update-version.sh @@ -0,0 +1,8 @@ +#!/bin/bash -e + +version=$1 +versionWithSnapshot="$version-SNAPSHOT" + +sed -Ei "s/var ver = \"[^\"]*\"/var ver = \"$version\"/" version.gradle.kts + +sed -Ei "1 s/(Comparing source compatibility of [a-z-]+)-[0-9]+\.[0-9]+\.[0-9]+(-SNAPSHOT)?.jar/\1-$versionWithSnapshot.jar/" docs/apidiffs/current_vs_latest/*.txt diff --git a/.github/scripts/use-cla-approved-bot.sh b/.github/scripts/use-cla-approved-bot.sh new file mode 100755 index 00000000000..149a13d9b93 --- /dev/null +++ b/.github/scripts/use-cla-approved-bot.sh @@ -0,0 +1,4 @@ +#!/bin/bash -e + +git config user.name otelbot +git config user.email 197425009+otelbot@users.noreply.github.com diff --git a/.github/workflows/backport.yml b/.github/workflows/backport.yml index 31c73b755cc..cf59e0de39e 100644 --- a/.github/workflows/backport.yml +++ b/.github/workflows/backport.yml @@ -6,33 +6,53 @@ on: description: "The pull request # to backport" required: true +permissions: + contents: read + jobs: backport: + permissions: + contents: write # for git push to PR branch runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - run: | + if [[ ! $GITHUB_REF_NAME =~ ^release/v[0-9]+\.[0-9]+\.x$ ]]; then + echo this workflow should only be run against release branches + exit 1 + fi + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: # history is needed to run git cherry-pick below fetch-depth: 0 + # zizmor: ignore[artipacked] Credentials are required by the branch push below. + persist-credentials: true - - name: Set git user - run: .github/scripts/set-git-user.sh + - name: Use CLA approved github bot + run: .github/scripts/use-cla-approved-bot.sh + + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: otelbot-token + with: + client-id: ${{ vars.OTELBOT_CLIENT_ID }} + private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }} + permission-pull-requests: write - name: Create pull request env: NUMBER: ${{ github.event.inputs.number }} - # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} + # pull requests from secrets.GITHUB_TOKEN do not run workflows + GH_TOKEN: ${{ steps.otelbot-token.outputs.token }} run: | commit=$(gh pr view $NUMBER --json mergeCommit --jq .mergeCommit.oid) title=$(gh pr view $NUMBER --json title --jq .title) - url=$(gh pr view $NUMBER --json url --jq .url) - branch="backport-${NUMBER}-to-${GITHUB_REF_NAME//\//-}" + branch="otelbot/backport-${NUMBER}-to-${GITHUB_REF_NAME//\//-}" + git checkout -b $branch git cherry-pick $commit - git push origin HEAD:$branch - gh pr create --title "[$GITHUB_REF_NAME] $title" \ - --body "Clean cherry-pick of #$NUMBER to the \`$GITHUB_REF_NAME\` branch." \ - --head $branch \ - --base $GITHUB_REF_NAME + git push --set-upstream origin $branch + gh pr create \ + --title "[$GITHUB_REF_NAME] $title" \ + --body "Clean cherry-pick of #$NUMBER to the \`$GITHUB_REF_NAME\` branch." \ + --base $GITHUB_REF_NAME diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml new file mode 100644 index 00000000000..13315006df3 --- /dev/null +++ b/.github/workflows/benchmark.yml @@ -0,0 +1,81 @@ +name: Benchmark Main + +on: + push: + branches: [ main ] + workflow_dispatch: + +permissions: + contents: read + +jobs: + sdk-benchmark: + if: github.repository == 'open-telemetry/opentelemetry-java' + permissions: + contents: write # for git push to benchmarks branch + name: Benchmark SDK + runs-on: oracle-bare-metal-64cpu-1024gb-x86-64-ubuntu-24 + container: + image: ubuntu:26.04@sha256:6a06111c3b0a8600feadb270aec771dc239bf407b25625f93f44ab00e11f4d3c + timeout-minutes: 120 # since there is only a single bare metal runner across all repos + steps: + - name: Install Git + run: | + apt-get update + apt-get install -y git + + - name: Configure Git safe directory + run: git config --global --add safe.directory "$GITHUB_WORKSPACE" + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - id: setup-java + name: Set up Java for build + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Set up gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: true + - name: Run jmh + run: ./gradlew jmhJar + env: + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + + # TODO (jack-berg): Select or build appropriate benchmarks for other key areas: + # - Log SDK export + # - Trace SDK export + # - Metric SDK export + # - Noop implementation + - name: Run Benchmark + run: | + cd sdk/all/build + java -jar libs/opentelemetry-sdk-*-jmh.jar -rf json MetricRecordBenchmark SpanRecordBenchmark LogRecordBenchmark + + - name: Use CLA approved github bot + run: .github/scripts/use-cla-approved-bot.sh + + - name: Store benchmark results + uses: benchmark-action/github-action-benchmark@4322e5726e6334590d251fc4f92bec0efafc45dc # v1.22.2 + with: + tool: 'jmh' + output-file-path: sdk/all/build/jmh-result.json + gh-pages-branch: benchmarks + github-token: ${{ secrets.GITHUB_TOKEN }} + benchmark-data-dir-path: "benchmarks" + auto-push: true + + workflow-notification: + permissions: + issues: write + needs: + - sdk-benchmark + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.sdk-benchmark.result == 'success' }} diff --git a/.github/workflows/build-daily.yml b/.github/workflows/build-daily.yml new file mode 100644 index 00000000000..bbfa3049019 --- /dev/null +++ b/.github/workflows/build-daily.yml @@ -0,0 +1,60 @@ +name: Build (daily) + +on: + schedule: + # daily at 3:24 UTC + - cron: "24 3 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + link-check: + if: github.repository == 'open-telemetry/opentelemetry-java' + uses: $/.github/workflows/reusable-link-check.yml + + publish-snapshots: + if: github.repository == 'open-telemetry/opentelemetry-java' + environment: protected + runs-on: ubuntu-26.04 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Java + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Set up gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: true + + - name: Publish to Sonatype + run: ./gradlew assemble publishToSonatype + env: + SONATYPE_USER: ${{ secrets.SONATYPE_USER }} + SONATYPE_KEY: ${{ secrets.SONATYPE_KEY }} + GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} + GPG_PASSWORD: ${{ secrets.GPG_PASSWORD }} + # disable gradle build cache, ensuring we're building from source to mitigate supply chain risk + DISABLE_REMOTE_BUILD_CACHE: true + + workflow-notification: + permissions: + issues: write + needs: + - link-check + - publish-snapshots + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: >- + ${{ + needs.link-check.result == 'success' && + needs.publish-snapshots.result == 'success' + }} diff --git a/.github/workflows/build-tracecontext-testsuite.yml b/.github/workflows/build-tracecontext-testsuite.yml index 89c4410f037..617e8a8e472 100644 --- a/.github/workflows/build-tracecontext-testsuite.yml +++ b/.github/workflows/build-tracecontext-testsuite.yml @@ -9,22 +9,41 @@ on: - main workflow_dispatch: +permissions: + contents: read + jobs: publish: + if: github.repository == 'open-telemetry/opentelemetry-java' + permissions: + contents: read + packages: write runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false - name: Login to GitHub package registry - uses: docker/login-action@v2 + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 with: registry: ghcr.io username: ${{ github.repository_owner }} password: ${{ secrets.GITHUB_TOKEN }} - name: Build and push - uses: docker/build-push-action@v3.0.0 + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 with: context: integration-tests/tracecontext/docker push: true tags: ghcr.io/open-telemetry/java-test-containers:w3c-tracecontext-testsuite + + workflow-notification: + permissions: + issues: write + needs: + - publish + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.publish.result == 'success' }} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ef961e9ca20..e6048ae7ff3 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -12,6 +12,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: true +permissions: + contents: read + jobs: build: name: Build @@ -21,107 +24,141 @@ jobs: matrix: os: - macos-latest - - ubuntu-20.04 + - ubuntu-latest + - windows-latest test-java-version: - 8 - 11 - 17 - - 18 + - 21 + - 25 + # When this release becomes LTS, keep it and add the next feature release as the marked row. + - 27 # renovate(java-version) # Collect coverage on latest LTS include: - - os: ubuntu-20.04 - test-java-version: 17 + - os: ubuntu-latest + test-java-version: 25 coverage: true + jmh-based-tests: true steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - fetch-depth: 0 + persist-credentials: false - id: setup-java-test name: Set up Java ${{ matrix.test-java-version }} for tests - uses: actions/setup-java@v3 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: - distribution: temurin + # Zulu publishes new feature releases quickly. + distribution: zulu java-version: ${{ matrix.test-java-version }} - id: setup-java name: Set up Java for build - uses: actions/setup-java@v3 + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin - java-version: 17 + java-version: 25 - - uses: gradle/gradle-build-action@v2 + - name: Set up gradle + # zizmor: ignore[cache-poisoning] This tests release branches but does not + # publish release artifacts. + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 with: - arguments: | - build + # Keep one writer per OS because Gradle User Home caches are platform-specific. + cache-read-only: ${{ github.ref_name != github.event.repository.default_branch || matrix.test-java-version != 25 }} + gradle-home-cache-excludes: >- + ${{ secrets.DEVELOCITY_ACCESS_KEY != '' && github.ref_name == github.event.repository.default_branch && matrix.test-java-version == 25 && 'caches/build-cache-1' || '' }} + - name: Build + shell: bash + run: > + ./gradlew build ${{ matrix.coverage && 'jacocoTestReport' || '' }} -PtestJavaVersion=${{ matrix.test-java-version }} - -Porg.gradle.java.installations.paths=${{ steps.setup-java-test.outputs.path }},${{ steps.setup-java.outputs.path }} + "-Porg.gradle.java.installations.paths=${TEST_JAVA_PATH}" + "-Porg.gradle.java.installations.auto-download=false" + env: + TEST_JAVA_PATH: ${{ steps.setup-java-test.outputs.path }} + # JMH-based tests run only if this environment variable is set to true + RUN_JMH_BASED_TESTS: ${{ matrix.jmh-based-tests }} + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + + - name: Check for diff + # The jApiCmp diff compares current to latest, which isn't appropriate for release branches + # this fails on windows because of the bash-specific if/then/else syntax, but that's ok + # because we only need to run this validation once (on any platform) + if: ${{ matrix.os != 'windows-latest' && !startsWith(github.ref_name, 'release/') && !startsWith(github.base_ref, 'release/') }} + run: | + # need to "git add" in case any generated files did not already exist + git add docs/apidiffs + if git diff --cached --quiet + then + echo "No diff detected." + else + echo "Diff detected - did you run './gradlew jApiCmp'?" + echo $(git diff --cached --name-only) + echo $(git diff --cached) + exit 1 + fi - - uses: codecov/codecov-action@v3 + - uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 if: ${{ matrix.coverage }} + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 if: ${{ matrix.coverage }} with: name: coverage-report path: all/build/reports/jacoco/test/html markdown-link-check: - # release branches are excluded to avoid unnecessary maintenance if external links break - if: ${{ !startsWith(github.ref_name, 'release/') }} - uses: ./.github/workflows/reusable-markdown-link-check.yml - - misspell-check: - # release branches are excluded to avoid unnecessary maintenance if new misspellings are added - # to the misspell dictionary + # release branches are excluded to avoid unnecessary maintenance if: ${{ !startsWith(github.ref_name, 'release/') }} - uses: ./.github/workflows/reusable-misspell-check.yml + uses: $/.github/workflows/reusable-link-check.yml - publish-snapshots: - # the condition is on the steps below instead of here on the job, because skipping the job - # causes the job to show up as canceled in the GitHub UI which prevents the build section from - # collapsing when everything (else) is green - # - # and the name is updated when the steps below are skipped which makes what's happening clearer - # in the GitHub UI - name: publish-snapshots${{ github.ref_name == 'main' && github.repository == 'open-telemetry/opentelemetry-java' && '' || ' (skipped)' }} - # intentionally not blocking snapshot publishing on markdown-link-check or misspell-check - needs: build - runs-on: ubuntu-20.04 + build-graal: + name: Build GraalVM + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + test-graal-version: + - 21 + - 25 # renovate(graal-java-version) steps: - - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - id: setup-java - name: Set up Java - uses: actions/setup-java@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - distribution: temurin - java-version: 17 - - - uses: gradle/gradle-build-action@v2 - # skipping release branches because the versions in those branches are not snapshots - # (also this skips pull requests) - if: ${{ github.ref_name == 'main' && github.repository == 'open-telemetry/opentelemetry-java' }} + persist-credentials: false + - uses: graalvm/setup-graalvm@f70bc8032f90a104502824a54bcb94b6f01715bc # v1.6.8 with: - arguments: assemble publishToSonatype + java-version: ${{ matrix.test-graal-version }} + distribution: 'graalvm' + components: 'native-image' + github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Running test + run: | + echo "GRAALVM_HOME: $GRAALVM_HOME" + echo "JAVA_HOME: $JAVA_HOME" + java --version + native-image --version + # Both flags required due to https://github.com/graalvm/native-build-tools/issues/477: + # --no-parallel prevents a race where the plugin's shared build service creates project-scoped + # detached configurations that are concurrently accessed during task fingerprinting. + # --no-configuration-cache prevents the cache store phase from adding additional concurrency. + ./gradlew nativeTest --no-configuration-cache --no-parallel env: - SONATYPE_USER: ${{ secrets.SONATYPE_USER }} - SONATYPE_KEY: ${{ secrets.SONATYPE_KEY }} - GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} - GPG_PASSWORD: ${{ secrets.GPG_PASSWORD }} + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} required-status-check: - # markdown-link-check is not required so that pull requests will not be blocked if external - # links break - # similarly misspell-check is not required so that pull requests will not be blocked if new - # misspellings are added to the misspell dictionary - needs: build + # markdown-link-check is not required so pull requests are not blocked if external links break + needs: + - build + - build-graal runs-on: ubuntu-latest if: always() steps: - - if: needs.build.result != 'success' + - if: | + needs.build.result != 'success' || + needs.build-graal.result != 'success' run: exit 1 diff --git a/.github/workflows/codeql-daily.yml b/.github/workflows/codeql-daily.yml deleted file mode 100644 index bb1ef7afe51..00000000000 --- a/.github/workflows/codeql-daily.yml +++ /dev/null @@ -1,38 +0,0 @@ -name: CodeQL (daily) - -on: - schedule: - - cron: '30 1 * * *' - workflow_dispatch: - -jobs: - analyze: - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v3 - - - name: Set up Java 17 - uses: actions/setup-java@v3 - with: - distribution: temurin - java-version: 17 - - - name: Initialize CodeQL - uses: github/codeql-action/init@v2 - with: - languages: java - - - uses: gradle/gradle-build-action@v2 - with: - # skipping build cache is needed so that all modules will be analyzed - arguments: assemble --no-build-cache - - - name: Perform CodeQL analysis - uses: github/codeql-action/analyze@v2 - - open-issue-on-failure: - # open an issue on failure because it can be easy to miss CI failure notifications - needs: analyze - if: failure() - uses: ./.github/workflows/reusable-open-issue-on-failure.yml diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000000..7aded5be302 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,83 @@ +name: CodeQL + +on: + pull_request: + branches: + - main + - release/* + - benchmarks + push: + branches: + - main + - release/* + - benchmarks + schedule: + - cron: "23 16 * * 2" # weekly at 16:23 UTC on Tuesday + +permissions: + contents: read + +jobs: + analyze: + permissions: + contents: read + actions: read # for github/codeql-action/init to get workflow details + security-events: write # for github/codeql-action/analyze to upload SARIF results + strategy: + fail-fast: false + matrix: + include: + - language: actions + - language: java + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up Java + if: matrix.language == 'java' + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Set up gradle + # zizmor: ignore[cache-poisoning] This workflow analyzes release branches + # but does not build or publish release artifacts. + if: matrix.language == 'java' + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: true + + - name: Initialize CodeQL + uses: github/codeql-action/init@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + languages: ${{ matrix.language }} + # using "linked" helps to keep up with the latest Kotlin support + # see https://github.com/github/codeql-action/issues/1555#issuecomment-1452228433 + tools: linked + + - name: Assemble + if: matrix.language == 'java' + # --no-build-cache is required for codeql to analyze all modules + # --no-daemon is required for codeql to observe the compilation + # (see https://docs.github.com/en/code-security/codeql-cli/getting-started-with-the-codeql-cli/preparing-your-code-for-codeql-analysis#specifying-build-commands) + run: ./gradlew assemble --no-build-cache --no-daemon + env: + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + + - name: Perform CodeQL analysis + uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + category: "/language:${{matrix.language}}" + + workflow-notification: + permissions: + issues: write + needs: + - analyze + if: always() && github.event_name == 'schedule' + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.analyze.result == 'success' }} diff --git a/.github/workflows/dependency-submission.yml b/.github/workflows/dependency-submission.yml new file mode 100644 index 00000000000..bd9f81a3e31 --- /dev/null +++ b/.github/workflows/dependency-submission.yml @@ -0,0 +1,42 @@ +name: Dependency submission + +on: + push: + branches: + - main + workflow_dispatch: + +permissions: + contents: read + +jobs: + submit: + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up JDK for running Gradle + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Generate and submit dependency graph + uses: gradle/actions/dependency-submission@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + dependency-graph: generate-and-submit + dependency-graph-include-configurations: "runtimeClasspath" + + workflow-notification: + permissions: + issues: write + needs: + - submit + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.submit.result == 'success' }} diff --git a/.github/workflows/detect-api-changes.yml b/.github/workflows/detect-api-changes.yml new file mode 100644 index 00000000000..0b79dadc7e6 --- /dev/null +++ b/.github/workflows/detect-api-changes.yml @@ -0,0 +1,99 @@ +name: Detect API Changes + +on: + # pull_request_target is used instead of pull_request so that the workflow has write access + # (to post comments and apply labels) even when triggered by fork PRs. + # + pull_request_target: + # zizmor: ignore[dangerous-triggers] Required to label and comment on fork PRs; + # no PR code is checked out, and the PR number and head ref are passed through env + # and treated only as data. + types: [opened, synchronize, reopened, ready_for_review] + +permissions: {} + +jobs: + detect-api-changes: + name: Detect API surface area changes + if: github.repository == 'open-telemetry/opentelemetry-java' + runs-on: ubuntu-latest + steps: + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: otelbot-token + with: + client-id: ${{ vars.OTELBOT_CLIENT_ID }} + private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }} + permission-pull-requests: write + + - name: Check for API changes and update PR + env: + GH_TOKEN: ${{ steps.otelbot-token.outputs.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + REPO: ${{ github.repository }} + HEAD_REF: ${{ github.event.pull_request.head.ref }} + run: | + MARKER="" + + # Get list of apidiff files changed in this PR. + # otelbot/* PRs (release version bumps, post-release updates) only change the version + # header in apidiff files β€” treat them as having no API changes so the cleanup path below runs. + if [[ "$HEAD_REF" == otelbot/* ]]; then + api_files="" + else + api_files=$(gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" --paginate \ + --jq '.[] | select(.filename | startswith("docs/apidiffs/current_vs_latest/")) | .filename') + fi + + # Find existing bot comment (if any) + comment_id=$(gh api "repos/${REPO}/issues/${PR_NUMBER}/comments" --paginate \ + --jq ".[] | select(.body | startswith(\"${MARKER}\")) | .id" | head -1) + + if [[ -z "$api_files" ]]; then + echo "No API diff files changed." + + # Remove label if present (ok to fail if label doesn't exist on PR) + gh pr edit "$PR_NUMBER" --repo "$REPO" --remove-label "api-change" 2>/dev/null || true + + # Delete existing comment if present + if [[ -n "$comment_id" ]]; then + gh api --method DELETE "repos/${REPO}/issues/comments/${comment_id}" + echo "Removed stale API change comment." + fi + exit 0 + fi + + echo "API diff files changed:" + echo "$api_files" + + # Add label + gh pr edit "$PR_NUMBER" --repo "$REPO" --add-label "api-change" + + # Build bulleted module list + modules=$(echo "$api_files" \ + | sed 's|docs/apidiffs/current_vs_latest/||' \ + | sed 's|\.txt$||' \ + | sort \ + | sed 's/^/- /') + + BODY=$(cat < + contains(github.event.issue.labels.*.name, 'needs author feedback') && + github.event.comment.user.login == github.event.issue.user.login + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Remove labels + env: + ISSUE_NUMBER: ${{ github.event.issue.number }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + gh issue edit --remove-label "needs author feedback" $ISSUE_NUMBER + gh issue edit --remove-label "stale" $ISSUE_NUMBER diff --git a/.github/workflows/issue-management-stale-action.yml b/.github/workflows/issue-management-stale-action.yml new file mode 100644 index 00000000000..39e4d8a158f --- /dev/null +++ b/.github/workflows/issue-management-stale-action.yml @@ -0,0 +1,70 @@ +name: Issue management - run stale action + +on: + schedule: + # hourly at minute 23 + - cron: "23 * * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + stale: + permissions: + contents: read + actions: write # because actions/stale deletes its old cache before saving new one + issues: write # for actions/stale to close stale issues + pull-requests: write # for actions/stale to close stale PRs + runs-on: ubuntu-latest + steps: + - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 + with: + only-labels: "needs author feedback" + days-before-stale: 7 + days-before-close: 7 + stale-issue-label: stale + stale-issue-message: > + This issue has been labeled as stale due to lack of activity and needing author feedback. + It will be automatically closed if there is no further activity over the next 7 days. + stale-pr-label: stale + stale-pr-message: > + This PR has been labeled as stale due to lack of activity and needing author feedback. + It will be automatically closed if there is no further activity over the next 7 days. + operations-per-run: 1000 + + - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 + with: + only-labels: "Feature Request" + exempt-issue-labels: "needs author feedback" + days-before-pr-stale: -1 + days-before-pr-close: -1 + days-before-issue-stale: 365 + days-before-issue-close: 0 + stale-issue-label: stale + close-issue-message: > + Since there has been no activity on this enhancement for the past year we are closing it to help maintain our backlog. + Anyone who would like to work on it is still welcome to do so, and we can re-open it at that time. + operations-per-run: 1000 + + - uses: actions/stale@4391f3da665fdf50b6810c1a66712fb9ba21aa93 # v11.0.0 + with: + days-before-issue-stale: -1 + days-before-issue-close: -1 + days-before-pr-stale: 90 + days-before-pr-close: 14 + stale-pr-label: stale + stale-pr-message: > + This PR has been labeled as stale due to lack of activity. + It will be automatically closed if there is no further activity over the next 14 days. + operations-per-run: 1000 + + workflow-notification: + permissions: + issues: write + needs: + - stale + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.stale.result == 'success' }} diff --git a/.github/workflows/javadoc-crawler.yml b/.github/workflows/javadoc-crawler.yml new file mode 100644 index 00000000000..4a6a20c51fb --- /dev/null +++ b/.github/workflows/javadoc-crawler.yml @@ -0,0 +1,43 @@ +name: Javadoc.io site crawler (daily) + +on: + schedule: + - cron: "30 1 * * *" # daily at 1:30 UTC + workflow_dispatch: + +permissions: + contents: read + +jobs: + crawl: + if: github.repository == 'open-telemetry/opentelemetry-java' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Set up gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: true + + - name: Run crawler + run: ./gradlew :javadoc-crawler:crawl + env: + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + + workflow-notification: + permissions: + issues: write + needs: + - crawl + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.crawl.result == 'success' }} diff --git a/.github/workflows/merge-change-log-to-main.yml b/.github/workflows/merge-change-log-to-main.yml deleted file mode 100644 index 4668d7303e9..00000000000 --- a/.github/workflows/merge-change-log-to-main.yml +++ /dev/null @@ -1,36 +0,0 @@ -name: Merge change log to main -on: - workflow_dispatch: - -jobs: - create-pull-request: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - with: - # this workflow is run against the release branch (see usage of GITHUB_REF_NAME below) - # but it is creating a pull request against main - ref: main - # history is needed to run format-patch below - fetch-depth: 0 - - - name: Set git user - run: .github/scripts/set-git-user.sh - - # this will fail if there have been conflicting change log updates introduced in main - - name: Create pull request against main - env: - # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} - run: | - message="Merge change log updates from $GITHUB_REF_NAME" - body="Merge change log updates from \`$GITHUB_REF_NAME\`." - branch="merge-change-log-updates-from-${GITHUB_REF_NAME//\//-}" - - git format-patch --stdout HEAD..origin/$GITHUB_REF_NAME CHANGELOG.md | git apply --3way - git commit -a -m "$message" - git push origin HEAD:$branch - gh pr create --title "$message" \ - --body "$body" \ - --head $branch \ - --base main diff --git a/.github/workflows/ossf-scorecard.yml b/.github/workflows/ossf-scorecard.yml new file mode 100644 index 00000000000..47cdb06596f --- /dev/null +++ b/.github/workflows/ossf-scorecard.yml @@ -0,0 +1,30 @@ +name: OSSF Scorecard + +on: + push: + branches: + - main + schedule: + - cron: "43 6 * * 5" # weekly at 06:43 (UTC) on Friday + workflow_dispatch: + +permissions: {} + +jobs: + analysis: + if: github.repository == 'open-telemetry/opentelemetry-java' + permissions: + contents: read # for actions/checkout + id-token: write # for Scorecard to publish results + security-events: write # for the SARIF upload to code scanning + uses: open-telemetry/shared-workflows/.github/workflows/scorecard.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + + workflow-notification: + permissions: + issues: write + needs: + - analysis + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.analysis.result == 'success' }} diff --git a/.github/workflows/prepare-patch-release.yml b/.github/workflows/prepare-patch-release.yml index 6e68c6ad1a7..76d850c0382 100644 --- a/.github/workflows/prepare-patch-release.yml +++ b/.github/workflows/prepare-patch-release.yml @@ -2,16 +2,35 @@ name: Prepare patch release on: workflow_dispatch: +permissions: + contents: read + jobs: prepare-patch-release: + permissions: + contents: write # for git push to PR branch runs-on: ubuntu-latest steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # zizmor: ignore[artipacked] Credentials are required by the branch push below. + persist-credentials: true + + - run: | + if [[ ! $GITHUB_REF_NAME =~ ^release/v[0-9]+\.[0-9]+\.x$ ]]; then + echo this workflow should only be run against release branches + exit 1 + fi + + if ! grep --quiet "^## Unreleased$" CHANGELOG.md; then + echo the change log is missing an \"Unreleased\" section + exit 1 + fi - name: Set environment variables run: | version=$(.github/scripts/get-version.sh) - if [[ $version =~ ([0-9]+\.[0-9]+)\.([0-9]+) ]]; then + if [[ $version =~ ^([0-9]+\.[0-9]+)\.([0-9]+)$ ]]; then major_minor="${BASH_REMATCH[1]}" patch="${BASH_REMATCH[2]}" else @@ -21,23 +40,35 @@ jobs: echo "VERSION=$major_minor.$((patch + 1))" >> $GITHUB_ENV - name: Update version + run: .github/scripts/update-version.sh $VERSION + + - name: Update the change log with the approximate release date run: | - sed -Ei "s/[0-9]+\.[0-9]+\.[0-9]+/$VERSION/" version.gradle.kts + date=$(date "+%Y-%m-%d") + sed -Ei "s/^## Unreleased$/## Version $VERSION ($date)/" CHANGELOG.md + + - name: Use CLA approved github bot + run: .github/scripts/use-cla-approved-bot.sh - - name: Set git user - run: .github/scripts/set-git-user.sh + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: otelbot-token + with: + client-id: ${{ vars.OTELBOT_CLIENT_ID }} + private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }} + permission-pull-requests: write - name: Create pull request env: - # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} + # pull requests from secrets.GITHUB_TOKEN do not run workflows + GH_TOKEN: ${{ steps.otelbot-token.outputs.token }} run: | message="Prepare release $VERSION" - branch="prepare-release-${VERSION}" + branch="otelbot/prepare-release-${VERSION}" + git checkout -b $branch git commit -a -m "$message" - git push origin HEAD:$branch - gh pr create --title "[$GITHUB_REF_NAME] $message" \ - --body "$message." \ - --head $branch \ - --base $GITHUB_REF_NAME + git push --set-upstream origin $branch + gh pr create \ + --title "[$GITHUB_REF_NAME] $message" \ + --body "$message." \ + --base $GITHUB_REF_NAME diff --git a/.github/workflows/prepare-release-branch.yml b/.github/workflows/prepare-release-branch.yml index d77794fd978..3866a5e6a3a 100644 --- a/.github/workflows/prepare-release-branch.yml +++ b/.github/workflows/prepare-release-branch.yml @@ -2,18 +2,54 @@ name: Prepare release branch on: workflow_dispatch: +permissions: + contents: read + jobs: + prereqs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Verify prerequisites + run: | + if [[ $GITHUB_REF_NAME != main ]]; then + echo this workflow should only be run against main + exit 1 + fi + + if ! grep --quiet "^## Unreleased$" CHANGELOG.md; then + echo the change log is missing an \"Unreleased\" section + exit 1 + fi + create-pull-request-against-release-branch: + permissions: + contents: write # for git push to PR branch runs-on: ubuntu-latest + needs: + - prereqs steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # history is needed to allow fast-forward push below in case + # re-running this workflow after merging additional PRs to main + fetch-depth: 0 + # zizmor: ignore[artipacked] Credentials are required by the branch pushes below. + persist-credentials: true - name: Create release branch - id: create-release-branch run: | version=$(.github/scripts/get-version.sh) version=${version//-SNAPSHOT/} - release_branch_name=$(echo $version | sed -E 's/([0-9]+)\.([0-9]+)\.0/release\/v\1.\2.x/') + if [[ $version =~ ^([0-9]+)\.([0-9]+)\.0$ ]]; then + release_branch_name=$(echo $version | sed -E 's/([0-9]+)\.([0-9]+)\.0/release\/v\1.\2.x/') + else + echo "unexpected version: $version" + exit 1 + fi git push origin HEAD:$release_branch_name @@ -21,64 +57,97 @@ jobs: echo "RELEASE_BRANCH_NAME=$release_branch_name" >> $GITHUB_ENV - name: Update version + run: sed -Ei "s/val snapshot = true/val snapshot = false/" version.gradle.kts + + - name: Update the change log with the approximate release date run: | - sed -Ei "s/val snapshot = true/val snapshot = false/" version.gradle.kts + date=$(date "+%Y-%m-%d") + sed -Ei "s/^## Unreleased$/## Version $VERSION ($date)/" CHANGELOG.md + + - name: Use CLA approved github bot + run: .github/scripts/use-cla-approved-bot.sh - - name: Set git user - run: .github/scripts/set-git-user.sh + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: otelbot-token + with: + client-id: ${{ vars.OTELBOT_CLIENT_ID }} + private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }} + permission-pull-requests: write - name: Create pull request against the release branch env: - # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} + # pull requests from secrets.GITHUB_TOKEN do not run workflows + GH_TOKEN: ${{ steps.otelbot-token.outputs.token }} run: | message="Prepare release $VERSION" - branch="prepare-release-${VERSION}" + branch="otelbot/prepare-release-${VERSION}" + git checkout -b $branch git commit -a -m "$message" - git push origin HEAD:$branch - gh pr create --title "[$RELEASE_BRANCH_NAME] $message" \ - --body "$message." \ - --head $branch \ - --base $RELEASE_BRANCH_NAME + git push --set-upstream origin $branch + gh pr create \ + --title "[$RELEASE_BRANCH_NAME] $message" \ + --body "$message." \ + --base $RELEASE_BRANCH_NAME create-pull-request-against-main: + permissions: + contents: write # for git push to PR branch runs-on: ubuntu-latest + needs: + - prereqs steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # zizmor: ignore[artipacked] Credentials are required by the branch push below. + persist-credentials: true - name: Set environment variables run: | version=$(.github/scripts/get-version.sh) - if [[ $version =~ ([0-9]+)\.([0-9]+)\.0 ]]; then + if [[ $version =~ ^([0-9]+)\.([0-9]+)\.0$ ]]; then major="${BASH_REMATCH[1]}" minor="${BASH_REMATCH[2]}" + next_version="$major.$((minor + 1)).0" else echo "unexpected version: $version" exit 1 fi - next_version="$major.$((minor + 1)).0" - echo "NEXT_VERSION=$next_version" >> $GITHUB_ENV + echo "NEXT_VERSION=${next_version}" >> $GITHUB_ENV + echo "VERSION=$version" >> $GITHUB_ENV - name: Update version + run: .github/scripts/update-version.sh $NEXT_VERSION + + - name: Update the change log on main run: | - sed -Ei "s/[0-9]+\.[0-9]+\.[0-9]+/$NEXT_VERSION/" version.gradle.kts + # the actual release date on main will be updated at the end of the release workflow + date=$(date "+%Y-%m-%d") + sed -Ei "s/^## Unreleased$/## Unreleased\n\n## Version $VERSION ($date)/" CHANGELOG.md + + - name: Use CLA approved github bot + run: .github/scripts/use-cla-approved-bot.sh - - name: Set git user - run: .github/scripts/set-git-user.sh + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: otelbot-token + with: + client-id: ${{ vars.OTELBOT_CLIENT_ID }} + private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }} + permission-pull-requests: write - name: Create pull request against main env: - # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} + # pull requests from secrets.GITHUB_TOKEN do not run workflows + GH_TOKEN: ${{ steps.otelbot-token.outputs.token }} run: | message="Update version to $NEXT_VERSION" body="Update version to \`$NEXT_VERSION\`." - branch="update-version-to-${NEXT_VERSION}" + branch="otelbot/update-version-to-${NEXT_VERSION}" + git checkout -b $branch git commit -a -m "$message" - git push origin HEAD:$branch - gh pr create --title "$message" \ - --body "$body" \ - --head $branch \ - --base main + git push --set-upstream origin $branch + gh pr create \ + --title "$message" \ + --body "$body" \ + --base main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b62d404648c..a9f71664f1e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -2,40 +2,53 @@ name: Release on: workflow_dispatch: +permissions: + contents: read + jobs: release: - runs-on: ubuntu-20.04 + environment: protected + permissions: + contents: write # for creating the release + runs-on: ubuntu-26.04 + outputs: + version: ${{ steps.create-github-release.outputs.version }} + prior-version: ${{ steps.create-github-release.outputs.prior-version }} steps: - run: | if [[ $GITHUB_REF_NAME != release/* ]]; then - echo the release workflow should only be run against release branches + echo this workflow should only be run against release branches exit 1 fi - - uses: actions/checkout@v3 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - # tags are needed for the generate-release-contributors.sh script - fetch-depth: 0 + persist-credentials: false - - uses: actions/setup-java@v3 + - uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 with: distribution: temurin - java-version: 17 + java-version: 25 - - name: Build and publish artifacts - uses: gradle/gradle-build-action@v2 + - name: Set up gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 with: - arguments: assemble publishToSonatype closeAndReleaseSonatypeStagingRepository + cache-read-only: true + + - name: Build and publish artifacts + run: ./gradlew assemble publishToSonatype closeAndReleaseSonatypeStagingRepository env: SONATYPE_USER: ${{ secrets.SONATYPE_USER }} SONATYPE_KEY: ${{ secrets.SONATYPE_KEY }} GPG_PRIVATE_KEY: ${{ secrets.GPG_PRIVATE_KEY }} GPG_PASSWORD: ${{ secrets.GPG_PASSWORD }} + # disable gradle build cache, ensuring we're building from source to mitigate supply chain risk + DISABLE_REMOTE_BUILD_CACHE: true - name: Set environment variables run: | version=$(.github/scripts/get-version.sh) - if [[ $version =~ ([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then + if [[ $version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+) ]]; then major="${BASH_REMATCH[1]}" minor="${BASH_REMATCH[2]}" patch="${BASH_REMATCH[3]}" @@ -57,72 +70,197 @@ jobs: echo "VERSION=$version" >> $GITHUB_ENV echo "PRIOR_VERSION=$prior_version" >> $GITHUB_ENV + # check out main branch to verify there won't be problems with merging the change log + # at the end of this workflow + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + persist-credentials: false + + - name: Check that change log update was merged to main + run: | + if [[ $VERSION == *.0 ]]; then + # not making a patch release + if ! grep --quiet "^## Version $VERSION " CHANGELOG.md; then + echo the pull request generated by prepare-release-branch.yml needs to be merged first + exit 1 + fi + fi + + # back to the release branch + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # tags are needed for the generate-release-contributors.sh script + fetch-depth: 0 + persist-credentials: false + - name: Generate release notes env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | # conditional blocks not indented because of the heredoc - if [[ $VERSION == *.0 ]]; then - cat > release-notes.txt << EOF - This release targets the OpenTelemetry SDK $VERSION. - - EOF - else - cat > release-notes.txt << EOF + if [[ $VERSION != *.0 ]]; then + cat > /tmp/release-notes.txt << EOF This is a patch release on the previous $PRIOR_VERSION release, fixing the issue(s) below. EOF fi + # CHANGELOG_SECTION.md is also used at the end of the release workflow + # for copying the change log updates to main + sed -n "0,/^## Version $VERSION /d;/^## Version /q;p" CHANGELOG.md \ + > /tmp/CHANGELOG_SECTION.md + # the complex perl regex is needed because markdown docs render newlines as soft wraps # while release notes render them as line breaks - sed -n "0,/^## Version $VERSION/d;/^## Version /q;p" CHANGELOG.md \ - | perl -0pe 's/(?> release-notes.txt + perl -0pe 's/(?> /tmp/release-notes.txt # conditional block not indented because of the heredoc if [[ $VERSION == *.0 ]]; then - cat >> release-notes.txt << EOF + cat >> /tmp/release-notes.txt << EOF ### πŸ™‡ Thank you This release was possible thanks to the following contributors who shared their brilliant ideas and awesome pull requests: EOF - .github/scripts/generate-release-contributors.sh v$PRIOR_VERSION >> release-notes.txt + .github/scripts/generate-release-contributors.sh v$PRIOR_VERSION >> /tmp/release-notes.txt fi - - name: Create GitHub release + - id: create-github-release + name: Create GitHub release env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: | gh release create --target $GITHUB_REF_NAME \ --title "Version $VERSION" \ - --notes-file release-notes.txt \ - --discussion-category announcements \ + --notes-file /tmp/release-notes.txt \ v$VERSION - - name: Update the change log with the release date + # these are used as job outputs + echo "version=$VERSION" >> $GITHUB_OUTPUT + echo "prior-version=$PRIOR_VERSION" >> $GITHUB_OUTPUT + + post-release-updates: + permissions: + contents: write # for git push to PR branch + runs-on: ubuntu-latest + needs: + - release + steps: + # add change log sync (if any) into this PR since the apidiff update + # is required before any other PR can be merged anyway + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Copy change log section from release branch env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + VERSION: ${{ needs.release.outputs.version }} run: | - date=$(gh release view v$VERSION --json publishedAt --jq .publishedAt | sed 's/T.*//') - sed -Ei "s/## Version $VERSION .*/## Version $VERSION ($date)/" CHANGELOG.md + sed -n "0,/^## Version $VERSION /d;/^## Version /q;p" CHANGELOG.md \ + > /tmp/changelog-section.md + + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: main + # zizmor: ignore[artipacked] Credentials are required by the branch push below. + persist-credentials: true - - name: Set git user - run: .github/scripts/set-git-user.sh + - name: Merge change log to main + env: + VERSION: ${{ needs.release.outputs.version }} + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + release_date=$(gh release view v$VERSION --json publishedAt --jq .publishedAt | sed 's/T.*//') + RELEASE_DATE=$release_date .github/scripts/merge-change-log-after-release.sh + git add CHANGELOG.md + + - name: Wait for release to be available in maven central + env: + VERSION: ${{ needs.release.outputs.version }} + run: | + until curl --silent \ + --show-error \ + --output /dev/null \ + --head \ + --fail \ + https://repo1.maven.org/maven2/io/opentelemetry/opentelemetry-api/$VERSION/opentelemetry-api-$VERSION.jar + do + sleep 60 + done + + - name: Set up JDK for running Gradle + uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Set up Gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: true - - name: Create pull request against the release branch + - name: Update apidiff baseline env: - # not using the default GITHUB_TOKEN because pull requests generated by it do not run any workflows - GITHUB_TOKEN: ${{ secrets.BOT_TOKEN }} + VERSION: ${{ needs.release.outputs.version }} + PRIOR_VERSION: ${{ needs.release.outputs.prior-version }} + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} run: | - message="Add the release date for $VERSION to the change log" - branch="add-release-date-for-${VERSION}" - - git commit -a -m "$message" - git push origin HEAD:$branch - gh pr create --title "[$GITHUB_REF_NAME] $message" \ - --body "$message." \ - --head $branch \ - --base $GITHUB_REF_NAME + # Retry to tolerate Maven Central per-artifact indexing lag: the earlier + # wait step only polls opentelemetry-api, but this task resolves every + # published module at $VERSION and will fail if any sibling artifact has + # not yet propagated. + for attempt in 1 2 3 4 5; do + if ./gradlew japicmp --refresh-dependencies -PapiBaseVersion=$PRIOR_VERSION -PapiNewVersion=$VERSION; then + break + fi + if [ $attempt -eq 5 ]; then + echo "japicmp failed after 5 attempts" + exit 1 + fi + echo "japicmp attempt $attempt failed, retrying in 60s" + sleep 60 + done + # Pin the apidiff baseline to the just-released version. + sed -i "s/^val apidiffBaselineVersion = .*/val apidiffBaselineVersion = \"$VERSION\"/" version.gradle.kts + ./gradlew --refresh-dependencies japicmp + git add docs/apidiffs + git add version.gradle.kts + + - name: Update versions in README.md + env: + VERSION: ${{ needs.release.outputs.version }} + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + run: | + ./gradlew updateVersionInDocs -Prelease.version=$VERSION + git add README.md + + - name: Use CLA approved bot + run: .github/scripts/use-cla-approved-bot.sh + + - uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + id: otelbot-token + with: + client-id: ${{ vars.OTELBOT_CLIENT_ID }} + private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }} + permission-pull-requests: write + + - name: Create pull request against main + env: + VERSION: ${{ needs.release.outputs.version }} + # pull requests from secrets.GITHUB_TOKEN do not run workflows + GH_TOKEN: ${{ steps.otelbot-token.outputs.token }} + run: | + message="Post-release updates for $VERSION" + body="Post-release updates for \`$VERSION\`." + branch="otelbot/post-release-updates-${VERSION}" + + git checkout -b $branch + git commit -m "$message" + git push --set-upstream origin $branch + gh pr create \ + --title "$message" \ + --body "$body" \ + --base main diff --git a/.github/workflows/reusable-link-check.yml b/.github/workflows/reusable-link-check.yml new file mode 100644 index 00000000000..7ed9d957606 --- /dev/null +++ b/.github/workflows/reusable-link-check.yml @@ -0,0 +1,34 @@ +name: Reusable - Link check + +on: + workflow_call: + +permissions: + contents: read + +jobs: + link-check: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 0 # needed for merge-base used in modified-files mode + persist-credentials: false + + - uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b # v5.2.7 + + - name: Link check for pull requests + if: github.event_name == 'pull_request' + env: + GITHUB_TOKEN: ${{ github.token }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_BASE_REF: ${{ github.base_ref }} + GITHUB_HEAD_REF: ${{ github.head_ref }} + PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }} + run: mise run lint:links + + - name: Link check for pushes and scheduled workflows + if: github.event_name != 'pull_request' + env: + GITHUB_TOKEN: ${{ github.token }} + run: mise run lint:links --full diff --git a/.github/workflows/reusable-markdown-link-check.yml b/.github/workflows/reusable-markdown-link-check.yml deleted file mode 100644 index 97282477879..00000000000 --- a/.github/workflows/reusable-markdown-link-check.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Reusable - Markdown link check - -on: - workflow_call: - -jobs: - markdown-link-check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Install markdown-link-check - run: npm install -g markdown-link-check - - - name: Run markdown-link-check - run: | - find . -type f \ - -name '*.md' \ - -not -path './CHANGELOG.md' \ - | xargs .github/scripts/markdown-link-check-with-retry.sh diff --git a/.github/workflows/reusable-misspell-check.yml b/.github/workflows/reusable-misspell-check.yml deleted file mode 100644 index 24f3a2c71be..00000000000 --- a/.github/workflows/reusable-misspell-check.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Reusable - Misspell check - -on: - workflow_call: - -jobs: - misspell-check: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Install misspell - run: | - curl -L -o ./install-misspell.sh https://git.io/misspell - sh ./install-misspell.sh - - - name: Run misspell - run: bin/misspell -error . diff --git a/.github/workflows/reusable-open-issue-on-failure.yml b/.github/workflows/reusable-open-issue-on-failure.yml deleted file mode 100644 index 31f81f979d4..00000000000 --- a/.github/workflows/reusable-open-issue-on-failure.yml +++ /dev/null @@ -1,18 +0,0 @@ -name: Reusable - Open issue on failure - -on: - workflow_call: - -jobs: - open-issue: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v3 - - - name: Open issue - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: | - gh issue create --title "$GITHUB_WORKFLOW #$GITHUB_RUN_NUMBER failed" \ - --label bug \ - --body "See [$GITHUB_WORKFLOW #$GITHUB_RUN_NUMBER](https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID)." diff --git a/.github/workflows/sonatype-guide-dependency-audit-daily.yml b/.github/workflows/sonatype-guide-dependency-audit-daily.yml new file mode 100644 index 00000000000..103fe53f5a9 --- /dev/null +++ b/.github/workflows/sonatype-guide-dependency-audit-daily.yml @@ -0,0 +1,56 @@ +# the benefit of this over renovate is that this also analyzes transitive dependencies +# while renovate (at least currently) only analyzes top-level dependencies +name: Sonatype Guide dependency audit (daily) + +on: + schedule: + - cron: "30 1 * * *" # daily at 1:30 UTC + workflow_dispatch: + +permissions: + contents: read + +jobs: + analyze: + if: github.repository == 'open-telemetry/opentelemetry-java' + environment: protected + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: actions/setup-java@77dd5b2ce225ea11469928ac317850245a74ae78 # v6.2.0 + with: + distribution: temurin + java-version: 25 + + - name: Set up gradle + uses: gradle/actions/setup-gradle@8da46b539cd8fe6ab27ca75128919a18d757604c # v6.4.1 + with: + cache-read-only: true + + # --no-parallel is needed to avoid OverlappingFileLockException on the shared OSS Index cache + - run: ./gradlew ossIndexAudit --no-configuration-cache --no-parallel --info + id: audit + continue-on-error: true + env: + SONATYPE_GUIDE_PAT: ${{ secrets.SONATYPE_GUIDE_PAT }} + DEVELOCITY_ACCESS_KEY: ${{ secrets.DEVELOCITY_ACCESS_KEY }} + + - name: Print vulnerability report + if: steps.audit.outcome == 'failure' + run: | + echo "=== Sonatype Guide Vulnerability Report ===" + find . -name "oss-index-cyclonedx-bom.json" | xargs cat + exit 1 + + workflow-notification: + permissions: + issues: write + needs: + - analyze + if: always() + uses: open-telemetry/shared-workflows/.github/workflows/workflow-failure-issue.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + success: ${{ needs.analyze.result == 'success' }} diff --git a/.github/workflows/survey-on-merged-pr.yml b/.github/workflows/survey-on-merged-pr.yml new file mode 100644 index 00000000000..de75e900923 --- /dev/null +++ b/.github/workflows/survey-on-merged-pr.yml @@ -0,0 +1,18 @@ +name: Survey on Merged PR by Non-Member + +on: + pull_request_target: + # zizmor: ignore[dangerous-triggers] This only calls the trusted reusable + # workflow; no PR code is checked out or executed. + types: [closed] + branches: [main] + +permissions: {} + +jobs: + survey: + uses: open-telemetry/shared-workflows/.github/workflows/survey-on-merged-pr.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 + with: + client_id: ${{ vars.OTELBOT_CLIENT_ID }} + secrets: + private_key: ${{ secrets.OTELBOT_PRIVATE_KEY }} diff --git a/.github/workflows/zizmor.yml b/.github/workflows/zizmor.yml new file mode 100644 index 00000000000..4668b65cdb0 --- /dev/null +++ b/.github/workflows/zizmor.yml @@ -0,0 +1,20 @@ +name: Zizmor + +on: + push: + branches: + - main + - release/* + pull_request: + schedule: + - cron: '43 18 * * 5' # weekly at 18:43 UTC on Friday + workflow_dispatch: + +permissions: {} + +jobs: + zizmor: + permissions: + contents: read # for actions/checkout + security-events: write # for zizmor to upload SARIF results + uses: open-telemetry/shared-workflows/.github/workflows/zizmor.yml@efc55838c9769c5476e0a5cf7183a8c5b4ae70a5 # v0.24.0 diff --git a/.gitignore b/.gitignore index 69c5f8b7cf9..bafac41ca50 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # Gradle build .gradle +.kotlin local.properties out/ @@ -33,3 +34,6 @@ bin # Vim .swp + +# scan-gradle-plugin +oss-index-cyclonedx-bom.json diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000..f0b4dd87691 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,11 @@ +# AGENTS.md + +Start with [docs/knowledge/README.md](docs/knowledge/README.md). It is the entry point for +coding patterns, build conventions, testing guidance, and API stability rules. Load documents +based on the scope of your work β€” the README contains a table mapping topics to load conditions. + +For project scope, PR process, and CLA requirements, see [CONTRIBUTING.md](CONTRIBUTING.md). + +## Additional guidance + +* Prefer small, localized changes over broad refactors. diff --git a/CHANGELOG.md b/CHANGELOG.md index 08f9eb54159..d10010bdddb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,3498 @@ # Changelog +## Unreleased + +## Version 1.68.0 (2026-11-06) + +### API + +* Add null guards and API usage logging for tracing, metrics, propagation, and context APIs + ([#8913](https://github.com/open-telemetry/opentelemetry-java/pull/8913), [#8968](https://github.com/open-telemetry/opentelemetry-java/pull/8968)) +* Add stable `io.opentelemetry.api.impl.Base16EncodingUtils` and `TemporaryBuffers` utilities + ([#8929](https://github.com/open-telemetry/opentelemetry-java/pull/8929), [#8955](https://github.com/open-telemetry/opentelemetry-java/pull/8955)) +* Fix uncompilable Javadoc examples in context APIs + ([#8934](https://github.com/open-telemetry/opentelemetry-java/pull/8934)) + +#### Incubating + +* Avoid false type warnings in `DeclarativeConfigProperties.toMap()` + ([#8921](https://github.com/open-telemetry/opentelemetry-java/pull/8921)) + +#### Extensions + +* Trace propagators: Handle malformed URL escapes in Jaeger headers + ([#8912](https://github.com/open-telemetry/opentelemetry-java/pull/8912)) +* Trace propagators: Include the B3 debug header in multi-header propagation fields + ([#8930](https://github.com/open-telemetry/opentelemetry-java/pull/8930)) +* Trace propagators: Fix hexadecimal flag parsing in Jaeger headers + ([#8975](https://github.com/open-telemetry/opentelemetry-java/pull/8975)) + +### SDK + +* Remove cross-module internal utility dependencies from resource and retry code + ([#8916](https://github.com/open-telemetry/opentelemetry-java/pull/8916)) +* Add experimental `SdkResourceProvider` support shared by tracer, meter, and logger providers + ([#8865](https://github.com/open-telemetry/opentelemetry-java/pull/8865)) + +#### Traces + +* Retain invalid span links with attributes or trace state + ([#8917](https://github.com/open-telemetry/opentelemetry-java/pull/8917)) + +#### Metrics + +* Use a dedicated export worker in `PeriodicMetricReader`, queue concurrent flushes, and add `setExporterTimeout()` with a default equal to the export interval + ([#8827](https://github.com/open-telemetry/opentelemetry-java/pull/8827)) + +#### Exporters + +* Logging: Fall back to the observed timestamp in `SystemOutLogRecordExporter` when the timestamp is unset + ([#8944](https://github.com/open-telemetry/opentelemetry-java/pull/8944)) +* OTLP: Close the JDK HTTP response body on unsupported `Content-Encoding` + ([#8962](https://github.com/open-telemetry/opentelemetry-java/pull/8962)) +* OTLP: Match the `Host` header case-insensitively in the managed-channel gRPC sender + ([#8957](https://github.com/open-telemetry/opentelemetry-java/pull/8957)) +* OTLP: Fix exporter metric server attributes for hosts that `java.net.URI` cannot parse + ([#8941](https://github.com/open-telemetry/opentelemetry-java/pull/8941)) +* OTLP: Pass the original exception to the JDK HTTP sender's error callback + ([#8963](https://github.com/open-telemetry/opentelemetry-java/pull/8963)) +* OTLP: Retry OkHttp gRPC exports on the current thread to avoid rejection by bounded executors + ([#8965](https://github.com/open-telemetry/opentelemetry-java/pull/8965)) +* OTLP: Restore per-attempt retry logging in the OkHttp gRPC sender + ([#8967](https://github.com/open-telemetry/opentelemetry-java/pull/8967)) +* OTLP: Correct exporter builder Javadoc + ([#8996](https://github.com/open-telemetry/opentelemetry-java/pull/8996)) +* OTLP: Accept `0` as no limit for maximum request body and message sizes + ([#8945](https://github.com/open-telemetry/opentelemetry-java/pull/8945)) +* OTLP: gRPC exporter internal telemetry uses `rpc.status_code` instead of + `rpc.response.status.code` when `InternalTelemetryVersion` is set to `LATEST` + ([#9007](https://github.com/open-telemetry/opentelemetry-java/pull/9007)) +* Prometheus: Give exemplar `trace_id` and `span_id` precedence over filtered attributes + ([#8959](https://github.com/open-telemetry/opentelemetry-java/pull/8959)) + +#### Extensions + +* **BREAKING** Incubator: Change `SamplingIntent.create()` and `getTraceStateUpdater()` from `Function` to `BiFunction` accepting the final `SamplingDecision`, and fix consistent sampling corner cases + ([#8952](https://github.com/open-telemetry/opentelemetry-java/pull/8952)) +* Autoconfigure: Match environment variables for configuration keys containing underscores + ([#8933](https://github.com/open-telemetry/opentelemetry-java/pull/8933), [#8951](https://github.com/open-telemetry/opentelemetry-java/pull/8951)) +* Autoconfigure: Support `PeriodicMetricReader` batch sizes through `otel.metric.export.max.batch.size` + ([#8935](https://github.com/open-telemetry/opentelemetry-java/pull/8935)) +* Autoconfigure: Correct SPI Javadoc + ([#8900](https://github.com/open-telemetry/opentelemetry-java/pull/8900)) + +#### Testing + +* Add fluent metric point assertions to `MetricAssert` + ([#8994](https://github.com/open-telemetry/opentelemetry-java/pull/8994)) +* Add a builder supporting aggregation temporality selectors to `InMemoryMetricExporter` + ([#8993](https://github.com/open-telemetry/opentelemetry-java/pull/8993)) + +## Version 1.67.0 (2026-10-09) + +### API + +* Deprecate `TextMapGetter.keys()` and make `TextMapGetter` a functional interface + ([#8531](https://github.com/open-telemetry/opentelemetry-java/pull/8531)) +* Add null guards and API usage logging for tracing, baggage, attributes, logging, and metrics + ([#8803](https://github.com/open-telemetry/opentelemetry-java/pull/8803), [#8863](https://github.com/open-telemetry/opentelemetry-java/pull/8863), [#8864](https://github.com/open-telemetry/opentelemetry-java/pull/8864)) +* Fix [GHSA-ccrj-gw8r-854m](https://github.com/open-telemetry/opentelemetry-java/security/advisories/GHSA-ccrj-gw8r-854m): Bound allocations and avoid regex backtracking when parsing W3C `tracestate` + ([#8817](https://github.com/open-telemetry/opentelemetry-java/pull/8817), [#8914](https://github.com/open-telemetry/opentelemetry-java/pull/8914)) + +#### Incubating + +* Add type introspection methods to `DeclarativeConfigProperties` + ([#8883](https://github.com/open-telemetry/opentelemetry-java/pull/8883)) + +#### Extensions + +* Trace propagators: Bound allocations when parsing Jaeger baggage and B3 single-header propagation + ([#8817](https://github.com/open-telemetry/opentelemetry-java/pull/8817)) + +### SDK + +* Run `CompletableResultCode` completion actions outside internal locks to avoid deadlocks + ([#8773](https://github.com/open-telemetry/opentelemetry-java/pull/8773)) +* Do not count attribute overwrites as dropped attributes + ([#8833](https://github.com/open-telemetry/opentelemetry-java/pull/8833)) +* Avoid regex backtracking in glob matching + ([#8909](https://github.com/open-telemetry/opentelemetry-java/pull/8909)) +* Add experimental resource entity support, OTLP export, and configuration through `otel.entities` + and declarative resource detectors + ([#8464](https://github.com/open-telemetry/opentelemetry-java/pull/8464)) + +#### Traces + +* Return noop tracers when no span processors are configured + ([#8815](https://github.com/open-telemetry/opentelemetry-java/pull/8815)) +* Catch `Throwable` in `SimpleSpanProcessor` and `MultiSpanExporter` + ([#8848](https://github.com/open-telemetry/opentelemetry-java/pull/8848)) +* Use `{span}` units for span processor self-observability metrics + ([#8873](https://github.com/open-telemetry/opentelemetry-java/pull/8873)) + +#### Metrics + +* Stabilize `PeriodicMetricReaderBuilder.setMaxExportBatchSize(int)` + ([#8829](https://github.com/open-telemetry/opentelemetry-java/pull/8829)) +* Delete experimental metric attribute / baggage processing + ([#8818](https://github.com/open-telemetry/opentelemetry-java/pull/8818)) +* Fix: Reset exemplar span context when a reservoir cell is overwritten outside a span + ([#8871](https://github.com/open-telemetry/opentelemetry-java/pull/8871)) + +#### Logs + +* Return noop loggers from `SdkLoggerProvider.get()` when no log record processors are configured + ([#8838](https://github.com/open-telemetry/opentelemetry-java/pull/8838)) +* Catch `Throwable` in `SimpleLogRecordProcessor` and `MultiLogRecordExporter` + ([#8848](https://github.com/open-telemetry/opentelemetry-java/pull/8848)) + +#### Profiles + +* Fix `KeyValueAndUnitData.create()` to return the public `KeyValueAndUnitData` interface + ([#8875](https://github.com/open-telemetry/opentelemetry-java/pull/8875)) + +#### Exporters + +* OTLP: Fix missing request size limits, defaulting to 64 MiB, configurable through + `setMaxRequestBodySize(long)` and `setMaxRequestMessageSize(long)` and through declarative config + `OtlpGrpcExporter`, `OtlpHttpExporter` (see full schema docs [here](https://opentelemetry.io/docs/specs/otel-config/types/#type-otlpgrpcexporter)) + ([#8446](https://github.com/open-telemetry/opentelemetry-java/pull/8446)) +* OTLP: Reduce failure logs to `FINE` after shutdown + ([#8819](https://github.com/open-telemetry/opentelemetry-java/pull/8819)) +* OTLP: retry gRPC based on response status codes in trailer headers + ([#8854](https://github.com/open-telemetry/opentelemetry-java/pull/8854)) +* Prometheus: Avoid regex backtracking when removing unit annotations + ([#8910](https://github.com/open-telemetry/opentelemetry-java/pull/8910)) + +#### Extensions + +* Autoconfigure: Stabilize `ServiceInstanceIdResourceProvider` and generate `service.instance.id` by default + ([#8770](https://github.com/open-telemetry/opentelemetry-java/pull/8770)) +* Autoconfigure: Preserve unencoded non-ASCII characters when decoding resource attributes + ([#8893](https://github.com/open-telemetry/opentelemetry-java/pull/8893)) +* Autoconfigure: Add missing artifact hints for `experimental-otlp/stdout` span and metric exporters + ([#8897](https://github.com/open-telemetry/opentelemetry-java/pull/8897)) +* Declarative config: Update to schema v1.2.0 and support the `always_record` sampler + ([#8801](https://github.com/open-telemetry/opentelemetry-java/pull/8801)) +* Declarative config: Ignore resource attributes with null values + ([#8889](https://github.com/open-telemetry/opentelemetry-java/pull/8889)) +* Declarative config: Match array attributes element-wise in the `rule_based` sampler + ([#8895](https://github.com/open-telemetry/opentelemetry-java/pull/8895)) +* Jaeger remote sampler: Reduce failure logs to `FINE` after shutdown + ([#8819](https://github.com/open-telemetry/opentelemetry-java/pull/8819)) +* Jaeger remote sampler: Preserve per-operation sampling strategies when the rate limit is zero + ([#8888](https://github.com/open-telemetry/opentelemetry-java/pull/8888)) +* Incubator: Make `OnEndSpanProcessor.create()` public + ([#8892](https://github.com/open-telemetry/opentelemetry-java/pull/8892)) +* Incubator: Fix the class name in `ComposableProbabilitySampler` descriptions + ([#8891](https://github.com/open-telemetry/opentelemetry-java/pull/8891)) + +#### Testing + +* Fix assertion failure messages reporting the wrong value or type + ([#8872](https://github.com/open-telemetry/opentelemetry-java/pull/8872)) + +### Shims + +* OpenCensus: Skip W3C multi-tenant `tracestate` keys when converting spans + ([#8810](https://github.com/open-telemetry/opentelemetry-java/pull/8810)) +* OpenTracing: Propagate baggage to the parent context in `SpanBuilderShim` + ([#8812](https://github.com/open-telemetry/opentelemetry-java/pull/8812)) + +### Project tooling + +* Kotlin extension: Raise the minimum Kotlin version to 2.2 + ([#8804](https://github.com/open-telemetry/opentelemetry-java/pull/8804)) + +## Version 1.66.0 (2026-09-11) + +### API + +* Fix `Baggage.fromContext()` and `Baggage.fromContextOrNull()` to handle a `null` context + ([#8667](https://github.com/open-telemetry/opentelemetry-java/pull/8667)) +* Do not percent-encode W3C baggage metadata + ([#8682](https://github.com/open-telemetry/opentelemetry-java/pull/8682)) +* Fix `ArrayIndexOutOfBoundsException` in `OtelEncodingUtils` for invalid hex characters + ([#8748](https://github.com/open-telemetry/opentelemetry-java/pull/8748)) + +### SDK + +#### Traces + +* Record processed spans before export completes and reject new spans on shutdown in + `SpanProcessor` self-observability instrumentation + ([#8735](https://github.com/open-telemetry/opentelemetry-java/pull/8735)) + +#### Metrics + +* Improve explicit bucket histogram contention performance + ([#8717](https://github.com/open-telemetry/opentelemetry-java/pull/8717)) + +#### Logs + +* Record processed logs before export completes and reject new logs on shutdown in + `LogRecordProcessor` self-observability instrumentation + ([#8698](https://github.com/open-telemetry/opentelemetry-java/pull/8698)) + +#### Exporters + +* OTLP: Respect `Retry-After` in OTLP HTTP senders + ([#8633](https://github.com/open-telemetry/opentelemetry-java/pull/8633)) +* OTLP: Add `setEnabledProtocols` option to OTLP HTTP exporter builders + ([#8610](https://github.com/open-telemetry/opentelemetry-java/pull/8610)) +* OTLP: Reject mixing `keyManager` and `sslContext` in `TlsConfigHelper` + ([#8710](https://github.com/open-telemetry/opentelemetry-java/pull/8710)) +* OTLP: Fix `OkHttpGrpcSender` mTLS when using the platform default trust store + ([#8758](https://github.com/open-telemetry/opentelemetry-java/pull/8758)) +* OTLP: Suppress instrumentation of exporter requests in `JdkHttpSender` + ([#8757](https://github.com/open-telemetry/opentelemetry-java/pull/8757)) +* OTLP: Accept RFC 1123 hostnames in `EndpointUtil.validateEndpoint` for OkHttp senders + ([#8746](https://github.com/open-telemetry/opentelemetry-java/pull/8746)) +* OTLP: Include the number of affected items in exporter error logging + ([#8780](https://github.com/open-telemetry/opentelemetry-java/pull/8780)) +* OTLP: Add `toString` to `OtlpJsonLogging{Span,Metric,LogRecord}Exporter` + ([#8725](https://github.com/open-telemetry/opentelemetry-java/pull/8725)) +* OTLP Profiles: Improve JFR export example and align `LinkData` null-element handling with the + spec ([#8349](https://github.com/open-telemetry/opentelemetry-java/pull/8349)) +* Prometheus: Remove default host log warning in `PrometheusHttpServerBuilder` + ([#8679](https://github.com/open-telemetry/opentelemetry-java/pull/8679)) +* Prometheus: Align UCUM byte unit conversions with the specification table + ([#8752](https://github.com/open-telemetry/opentelemetry-java/pull/8752)) + +#### Extensions + +* **BREAKING** Declarative config: Rename generated model POJO setters from `with` to + `set` ([#8742](https://github.com/open-telemetry/opentelemetry-java/pull/8742)) +* Declarative config: Resolve experimental properties on stable APIs in generated model POJOs + ([#8654](https://github.com/open-telemetry/opentelemetry-java/pull/8654)) +* Declarative config: Fix inverted `scope_info_enabled` and `target_info_enabled` flags in the + Prometheus component provider + ([#8750](https://github.com/open-telemetry/opentelemetry-java/pull/8750)) +* Declarative config: Support `output_stream` in `otlp_file/development` + ([#8676](https://github.com/open-telemetry/opentelemetry-java/pull/8676)) +* Incubator: Add `toString` to `ComposableAnnotatingSampler` + ([#8645](https://github.com/open-telemetry/opentelemetry-java/pull/8645)) + +### Project tooling + +* Remediate `zizmor` findings in GitHub Actions workflows + ([#8592](https://github.com/open-telemetry/opentelemetry-java/pull/8592)) + +## Version 1.65.0 (2026-08-07) + +**NOTE:** The `opentelemetry-exporter-zipkin` artifact has stopped being published. It was +deprecated in a prior release. Users should migrate to OTLP or use a Zipkin-compatible collector +exporter. + +### API + +* Ignore empty baggage keys in `ImmutableBaggage.put` + ([#8658](https://github.com/open-telemetry/opentelemetry-java/pull/8658)) +* Use `NumberFormatException` in baggage decoder + ([#8593](https://github.com/open-telemetry/opentelemetry-java/pull/8593)) +* Fix `TraceStateBuilder.remove` corrupting the builder when the same key is removed twice + ([#8613](https://github.com/open-telemetry/opentelemetry-java/pull/8613)) + +#### Incubating + +* Add bound instrument APIs (`BoundLongCounter`, `BoundDoubleCounter`, `BoundLongHistogram`, + `BoundDoubleHistogram`, `BoundLongUpDownCounter`, `BoundDoubleUpDownCounter`, `BoundLongGauge`, + `BoundDoubleGauge`) to the incubator metrics API + ([#8527](https://github.com/open-telemetry/opentelemetry-java/pull/8527)) + +#### Extensions + +* Trace propagators: Fix `JaegerPropagator` baggage header key case sensitivity + ([#8496](https://github.com/open-telemetry/opentelemetry-java/pull/8496)) +* Trace propagators: Do not overwrite existing baggage with empty baggage in `JaegerPropagator` + ([#8632](https://github.com/open-telemetry/opentelemetry-java/pull/8632)) +* Trace propagators: Skip empty baggage keys in `OtTracePropagator` extract + ([#8631](https://github.com/open-telemetry/opentelemetry-java/pull/8631)) +* Trace propagators: Stop parsing a `jaeger-baggage` header after 64 tokens, including malformed + tokens ([#8702](https://github.com/open-telemetry/opentelemetry-java/pull/8702)) + +### SDK + +* Update SDK attributes implementation (`AttributesMap`) to enforce last-value-win semantics based + on string value of `AttributeKey.getKey()` + ([#8548](https://github.com/open-telemetry/opentelemetry-java/pull/8548)) + +#### Traces + +* Add `Sampler` shutdown lifecycle: `Sampler` now extends `Closeable` and exposes a default + `shutdown()` invoked when the `SdkTracerProvider` is shut down; `JaegerRemoteSampler` implements + it to stop its polling executor + ([#8574](https://github.com/open-telemetry/opentelemetry-java/pull/8574)) + +#### Metrics + +* Gate `PeriodicMetricReader` self-observability metrics by internal telemetry version + ([#8597](https://github.com/open-telemetry/opentelemetry-java/pull/8597)) +* Record `error.type` on failed collections in `PeriodicMetricReader` + ([#8650](https://github.com/open-telemetry/opentelemetry-java/pull/8650)) +* Testing: Fix `LongExemplarAssert.hasFilteredAttributesSatisfyingExactly` to enforce exact + attribute matching + ([#8518](https://github.com/open-telemetry/opentelemetry-java/pull/8518)) + +#### Logs + +* Fix `ReadWriteLogRecord` default `getObservedTimestampEpochNanos` returning the record timestamp + ([#8504](https://github.com/open-telemetry/opentelemetry-java/pull/8504)) + +#### Profiles + +* Fix profiles data model attribute count parameter name and timestamp doc unit + ([#8514](https://github.com/open-telemetry/opentelemetry-java/pull/8514)) + +#### Exporters + +* **WARNING** Zipkin: Delete `opentelemetry-exporter-zipkin`; the artifact is no longer published + ([#8677](https://github.com/open-telemetry/opentelemetry-java/pull/8677)) +* OTLP: Use HTTP error response bodies in `HttpExporter` warning logs + ([#8428](https://github.com/open-telemetry/opentelemetry-java/pull/8428)) +* OTLP: Fix `OkHttpHttpSender` mTLS when using the platform default trust store + ([#8565](https://github.com/open-telemetry/opentelemetry-java/pull/8565)) +* OTLP: Fix sign extension on `LogRecord` flags in the low-allocation log marshaler + ([#8493](https://github.com/open-telemetry/opentelemetry-java/pull/8493)) +* OTLP: Standardize `OkHttpHttpSender`, `JdkHttpSender`, and `UpstreamGrpcSender` shutdown to + await executor/channel termination + ([#8495](https://github.com/open-telemetry/opentelemetry-java/pull/8495), + [#8627](https://github.com/open-telemetry/opentelemetry-java/pull/8627), + [#8624](https://github.com/open-telemetry/opentelemetry-java/pull/8624)) +* OTLP: Log the underlying except/ion when a gRPC response frame is invalid + ([#8626](https://github.com/open-telemetry/opentelemetry-java/pull/8626)) +* OTLP: Avoid the unsafe string encoder on Android + ([#8637](https://github.com/open-telemetry/opentelemetry-java/pull/8637)) +* Prometheus: Merge colliding Prometheus label values + ([#8364](https://github.com/open-telemetry/opentelemetry-java/pull/8364)) +* Prometheus: Fix `PrometheusHttpServer.toBuilder()` dropping the configured default handler + ([#8619](https://github.com/open-telemetry/opentelemetry-java/pull/8619)) +* Logging: Output event name in `SystemOutLogRecordExporter` + ([#8609](https://github.com/open-telemetry/opentelemetry-java/pull/8609)) +* Logging: Include aggregation temporality in `LoggingMetricExporter` `toString` + ([#8623](https://github.com/open-telemetry/opentelemetry-java/pull/8623)) + +#### Extensions + +* Autoconfigure: Avoid exposing configuration values in error messages + ([#8669](https://github.com/open-telemetry/opentelemetry-java/pull/8669)) +* Declarative config: Fix Jaeger sampler polling interval configuration + ([#8668](https://github.com/open-telemetry/opentelemetry-java/pull/8668)) +* Declarative config: Remove duplicate `getStringList` resolver in `DeclarativeConfigPropertyUtil` + ([#8572](https://github.com/open-telemetry/opentelemetry-java/pull/8572)) +* Declarative config: Replace `jsonschema2pojo` with a hand-rolled POJO generator + ([#8600](https://github.com/open-telemetry/opentelemetry-java/pull/8600)) +* Incubator: Restore compliance between composite samplers code and the spec + ([#8450](https://github.com/open-telemetry/opentelemetry-java/pull/8450)) + +### Shims + +* **DEPRECATION** Deprecate the OpenCensus shim public API + ([#8674](https://github.com/open-telemetry/opentelemetry-java/pull/8674)) +* OpenCensus: Preserve OpenCensus status description when converting to OpenTelemetry + ([#8511](https://github.com/open-telemetry/opentelemetry-java/pull/8511)) +* OpenCensus: Add links to the OpenTelemetry span instead of logging a warning and dropping them + ([#8635](https://github.com/open-telemetry/opentelemetry-java/pull/8635)) +* OpenTracing: Return `null` from `TracerShim` extract when the carrier has no span context + ([#8505](https://github.com/open-telemetry/opentelemetry-java/pull/8505)) +* OpenTracing: Return the extracted `SpanContext` when it is sampled but invalid + ([#8634](https://github.com/open-telemetry/opentelemetry-java/pull/8634)) + +### Project tooling + +* Pin japicmp baseline in `version.gradle.kts` + ([#8591](https://github.com/open-telemetry/opentelemetry-java/pull/8591)) +* Update contributing guide in response to feedback + ([#8655](https://github.com/open-telemetry/opentelemetry-java/pull/8655)) + +## Version 1.64.0 (2026-07-10) + +### API + +* Fix `W3CBaggagePropagator` to allow empty baggage values per W3C spec + ([#8468](https://github.com/open-telemetry/opentelemetry-java/pull/8468)) +* Fix baggage parsing for invalid percent-encoded members + ([#8480](https://github.com/open-telemetry/opentelemetry-java/pull/8480)) + +#### Incubating + +* **BREAKING** Remove deprecated `InstrumentationConfigUtil.peerServiceMapping` + ([#8542](https://github.com/open-telemetry/opentelemetry-java/pull/8542)) +* Fix `EnvironmentGetter`/`EnvironmentSetter` to not enumerate or normalize carrier entries, and + normalize empty names consistently + ([#8474](https://github.com/open-telemetry/opentelemetry-java/pull/8474), + [#8481](https://github.com/open-telemetry/opentelemetry-java/pull/8481)) + +### SDK + +#### Traces + +* Add `BatchSpanProcessor.create(SpanExporter)` convenience factory to mirror + `SimpleSpanProcessor.create(SpanExporter)` + ([#8564](https://github.com/open-telemetry/opentelemetry-java/pull/8564)) +* Fix `BatchSpanProcessor` benchmark aux counters (`exportedSpans`/`droppedSpans`) always + reporting zero + ([#8539](https://github.com/open-telemetry/opentelemetry-java/pull/8539)) + +#### Metrics + +* Fix `PooledHashMap` dropping live entries when an entry is removed during `forEach` + ([#8499](https://github.com/open-telemetry/opentelemetry-java/pull/8499)) +* Safely initialize exemplar reservoir storage in `FixedSizeExemplarReservoir` + ([#8524](https://github.com/open-telemetry/opentelemetry-java/pull/8524)) +* Use `failExceptionally` in `PeriodicMetricReader` when the exporter is busy + ([#8525](https://github.com/open-telemetry/opentelemetry-java/pull/8525)) +* Only set `valuesRecorded` in `AggregatorHandle` when false + ([#8559](https://github.com/open-telemetry/opentelemetry-java/pull/8559)) +* Use `volatile` instead of atomics in `Double`/`LongLastValueAggregator` + ([#8560](https://github.com/open-telemetry/opentelemetry-java/pull/8560)) +* Randomize per-thread recording order in metric benchmarks to avoid concurrency hotspots + ([#8550](https://github.com/open-telemetry/opentelemetry-java/pull/8550)) + +#### Logs + +* Fix `BatchLogRecordProcessor` worker thread being killed by non-runtime exceptions + ([#8529](https://github.com/open-telemetry/opentelemetry-java/pull/8529)) + +#### Exporters + +* **BREAKING** Prometheus: Drop deprecated `PrometheusMetricReader` constructors + ([#8541](https://github.com/open-telemetry/opentelemetry-java/pull/8541)) +* OTLP: Reject host-less endpoints in `EndpointUtil.validateEndpoint` + ([#8489](https://github.com/open-telemetry/opentelemetry-java/pull/8489)) +* OTLP: Replace Jackson OTLP JSON serialization with a hand-rolled implementation + ([#8545](https://github.com/open-telemetry/opentelemetry-java/pull/8545)) +* OTLP Profiles: Fix `OtlpGrpcProfileExporter` `toString` class name + ([#8492](https://github.com/open-telemetry/opentelemetry-java/pull/8492)) +* Prometheus: Add translation strategy support + ([#8346](https://github.com/open-telemetry/opentelemetry-java/pull/8346)) +* Prometheus: Fix serialization of array-valued scope and resource attributes to JSON strings + ([#8497](https://github.com/open-telemetry/opentelemetry-java/pull/8497)) + +#### Extensions + +* **BREAKING** Declarative config: Move experimental types to internal package + ([#8530](https://github.com/open-telemetry/opentelemetry-java/pull/8530)) +* Declarative config: Commit generated schema POJOs to git + ([#8408](https://github.com/open-telemetry/opentelemetry-java/pull/8408)) +* Declarative config: Update to `opentelemetry-configuration` v1.1.0 + ([#8451](https://github.com/open-telemetry/opentelemetry-java/pull/8451)) +* Declarative config: Adjust POJO `toString`/`hashCode`/`equals` to match AutoValue semantics + ([#8526](https://github.com/open-telemetry/opentelemetry-java/pull/8526)) +* Declarative config: Add ref descriptions to generated model classes + ([#8540](https://github.com/open-telemetry/opentelemetry-java/pull/8540)) +* Declarative config: Emit consistent `@JsonProperty` annotations on generated models + ([#8563](https://github.com/open-telemetry/opentelemetry-java/pull/8563)) +* Declarative config: Remove duplicate resolver in `DeclarativeConfigPropertyUtil` + ([#8579](https://github.com/open-telemetry/opentelemetry-java/pull/8579)) + +### Project tooling + +* Add configuration policy guidance + ([#8429](https://github.com/open-telemetry/opentelemetry-java/pull/8429)) +* Exclude certain GitHub Actions from running on forks + ([#8466](https://github.com/open-telemetry/opentelemetry-java/pull/8466)) +* Add guidance to prefer parameterized tests + ([#8469](https://github.com/open-telemetry/opentelemetry-java/pull/8469)) +* Make benchmark path configurable + ([#8557](https://github.com/open-telemetry/opentelemetry-java/pull/8557)) + +## Version 1.63.0 (2026-06-05) + +### API + +* Add missing `setAttribute` shortcuts to `Span` and `LogRecordBuilder` + ([#8255](https://github.com/open-telemetry/opentelemetry-java/pull/8255)) +* Promote `InstrumentationUtil` to public class in `io.opentelemetry.api.impl` package + ([#8413](https://github.com/open-telemetry/opentelemetry-java/pull/8413)) +* Fix index-out-of-bounds in `StrictContextStorage` + ([#8294](https://github.com/open-telemetry/opentelemetry-java/pull/8294)) + +#### Incubating + +* **BREAKING** Remove deprecated `ExtendedAttributes` and related code + ([#8395](https://github.com/open-telemetry/opentelemetry-java/pull/8395)) + +### SDK + +#### Metrics + +* Collect async exemplars when exemplar filter is `always_on` + ([#8363](https://github.com/open-telemetry/opentelemetry-java/pull/8363)) +* Move delta record/collect coordination from instrument to series level + ([#8313](https://github.com/open-telemetry/opentelemetry-java/pull/8313)) + +#### Exporters + +* Add `noop()` factory method to `SpanExporter` and `LogRecordExporter` + ([#8435](https://github.com/open-telemetry/opentelemetry-java/pull/8435)) +* **BREAKING** OTLP: Remove support for deprecated `GrpcSenderProvider` and `HttpSenderProvider` SPI + property names (use `io.opentelemetry.sdk.common.export.GrpcSenderProvider` / + `io.opentelemetry.sdk.common.export.HttpSenderProvider` instead) + ([#8392](https://github.com/open-telemetry/opentelemetry-java/pull/8392)) +* OTLP: Bound OkHttp sender dispatchers and surface rejections + ([#8422](https://github.com/open-telemetry/opentelemetry-java/pull/8422)) +* Prometheus: Limit exemplar label characters to conform to Prometheus limits + ([#8362](https://github.com/open-telemetry/opentelemetry-java/pull/8362)) +* Logging: Fix `LoggingSpanExporter.flush()` to preserve flush failures + ([#8361](https://github.com/open-telemetry/opentelemetry-java/pull/8361)) +* Zipkin: Make exporter self-contained by removing shared internal code dependencies + ([#8413](https://github.com/open-telemetry/opentelemetry-java/pull/8413)) + +#### Extensions + +* **BREAKING** Autoconfigure: Remove deprecated `otel.experimental.config.file` property + ([#8393](https://github.com/open-telemetry/opentelemetry-java/pull/8393)) +* **BREAKING** Incubator: Remove deprecated `ViewConfig`/`ViewConfigCustomizer` view file config mechanism + ([#8394](https://github.com/open-telemetry/opentelemetry-java/pull/8394)) +* Declarative config: Fix model package + ([#8403](https://github.com/open-telemetry/opentelemetry-java/pull/8403)) +* Declarative config: Fix Java module name to `io.opentelemetry.sdk.autoconfigure.declarativeconfig` + ([#8452](https://github.com/open-telemetry/opentelemetry-java/pull/8452)) + +### Shims + +* Deprecate OpenTracing shim public API + ([#8373](https://github.com/open-telemetry/opentelemetry-java/pull/8373)) + +### Project tooling + +* Finish adding OSGi support across all modules + ([#8401](https://github.com/open-telemetry/opentelemetry-java/pull/8401), + [#8417](https://github.com/open-telemetry/opentelemetry-java/pull/8417)) +* Force `io.zipkin.zipkin2:zipkin:3.6.1` to avoid problematic gson version + ([#8430](https://github.com/open-telemetry/opentelemetry-java/pull/8430)) + +## Version 1.62.0 (2026-05-08) + +### API + +#### Context + +* Fix [GHSA-rcgg-9c38-7xpx](https://github.com/open-telemetry/opentelemetry-java/security/advisories/GHSA-rcgg-9c38-7xpx): Apply limits to baggage entries for `W3CBaggagePropagator`, `OtTracePropagator`, `JaegerPropagator` + ([#8378](https://github.com/open-telemetry/opentelemetry-java/pull/8378)) + +### SDK + +#### Traces + +* Avoid `parentContext` allocation on span start for the common case + ([#8332](https://github.com/open-telemetry/opentelemetry-java/pull/8332)) + +#### Metrics + +* Add `setMaxExportBatchSize` to `PeriodicMetricReaderBuilder` + ([#8296](https://github.com/open-telemetry/opentelemetry-java/pull/8296)) +* Fix `PeriodicMetricReader` shutdown race that could drop the final flush + ([#8299](https://github.com/open-telemetry/opentelemetry-java/pull/8299)) + +#### Exporters + +* **BREAKING** Prometheus: Change default server host from `0.0.0.0` to `localhost` + ([#8298](https://github.com/open-telemetry/opentelemetry-java/pull/8298)) +* **BREAKING** Prometheus: Stop converting unit `"1"` to `"ratio"` + ([#8252](https://github.com/open-telemetry/opentelemetry-java/pull/8252)) +* OTLP: Fix null input handling in `StringEncoder` + ([#8312](https://github.com/open-telemetry/opentelemetry-java/pull/8312)) +* OTLP: Align proto field types and wire tag names in marshalers + ([#8293](https://github.com/open-telemetry/opentelemetry-java/pull/8293)) +* OTLP: Fix `MarshalerUtil` `sizeRepeatedString` calculation + ([#8284](https://github.com/open-telemetry/opentelemetry-java/pull/8284)) +* OTLP: Bound `JdkHttpSender` thread pool size to prevent unbounded thread creation + ([#8276](https://github.com/open-telemetry/opentelemetry-java/pull/8276)) +* OTLP Profiles: Split profiles data model into separate `sdk-profiles` and JFR shim modules + ([#8207](https://github.com/open-telemetry/opentelemetry-java/pull/8207)) +* OTLP Profiles: Publish alpha release of `opentelemetry-sdk-profiles` and + `opentelemetry-exporter-otlp-profiles` + ([#8351](https://github.com/open-telemetry/opentelemetry-java/pull/8351)) + +#### Extensions + +* **BREAKING** Declarative config: Extract to new `opentelemetry-sdk-extension-declarative-config` + artifact with new package `io.opentelemetry.sdk.autoconfigure.declarativeconfig` + ([#8265](https://github.com/open-telemetry/opentelemetry-java/pull/8265)) +* Autoconfigure: Add file size validation in `OtlpConfigUtil` to avoid unsafe cast to `int` + ([#8287](https://github.com/open-telemetry/opentelemetry-java/pull/8287)) +* Declarative config: Fix collection fields to not be initialized to empty by default + ([#8356](https://github.com/open-telemetry/opentelemetry-java/pull/8356)) +* Incubator: Add `EventToSpanEventBridge` to bridge log-based events to span events + ([#8372](https://github.com/open-telemetry/opentelemetry-java/pull/8372)) + +#### Testing + +* Add `@Nullable` to `equalTo` value argument in `OpenTelemetryAssertions` + ([#8301](https://github.com/open-telemetry/opentelemetry-java/pull/8301)) +* Add `hasValueSatisfying` to `LongPointAssert` and `DoublePointAssert` for fuzzy value matching + ([#8328](https://github.com/open-telemetry/opentelemetry-java/pull/8328)) +* Add `containsPointsSatisfying` to metric data asserts for "each given assertion must be + satisfied by at least one point, extras allowed" checks on sum, gauge, histogram, exponential + histogram, and summary data + ([#8329](https://github.com/open-telemetry/opentelemetry-java/pull/8329)) + +### Project tooling + +* Add initial OSGi support + ([#7964](https://github.com/open-telemetry/opentelemetry-java/pull/7964)) +* Promote `ApiUsageLogger` to `opentelemetry-common` public API + ([#8318](https://github.com/open-telemetry/opentelemetry-java/pull/8318)) +* Establish exception logging guidelines and fix inconsistent patterns across exporters and SDK + ([#8231](https://github.com/open-telemetry/opentelemetry-java/pull/8231)) +* Add `*.impl.*` package naming convention for internal code with japicmp compatibility + ([#8325](https://github.com/open-telemetry/opentelemetry-java/pull/8325)) +* Add Sonatype dependency audit to build + ([#8365](https://github.com/open-telemetry/opentelemetry-java/pull/8365)) + +## Version 1.61.0 (2026-04-10) + +### API + +* Stabilize `isEnabled()` on `Tracer`, `Logger`, and metric instruments + ([#8200](https://github.com/open-telemetry/opentelemetry-java/pull/8200)) + +#### Incubating + +* **BREAKING** Update `EnvironmentGetter` and `EnvironmentSetter` key normalization to reflect spec + changes + ([#8233](https://github.com/open-telemetry/opentelemetry-java/pull/8233)) + +### SDK + +#### Traces + +* Retain propagated context when generating random trace IDs + ([#8263](https://github.com/open-telemetry/opentelemetry-java/pull/8263)) +* Add rate-limited warning log when `BatchSpanProcessor` drops spans + ([#8167](https://github.com/open-telemetry/opentelemetry-java/pull/8167)) + +#### Metrics + +* Track series start time per aggregator rather than at `SdkMeterProvider` creation time + ([#8180](https://github.com/open-telemetry/opentelemetry-java/pull/8180)) +* Capture context class loader during async callback registration + ([#8091](https://github.com/open-telemetry/opentelemetry-java/pull/8091)) +* Make include/exclude work correctly with empty (but non-null) lists + ([#8185](https://github.com/open-telemetry/opentelemetry-java/pull/8185)) + +#### Logs + +* Fix condition for recording successful log processing metrics + ([#8226](https://github.com/open-telemetry/opentelemetry-java/pull/8226)) + +#### Exporters + +* OTLP: add configurable bounds to response body reading + ([#8224](https://github.com/open-telemetry/opentelemetry-java/pull/8224), [#8277](https://github.com/open-telemetry/opentelemetry-java/pull/8277)) +* OTLP: only throw invalid response exception when gRPC response size < 5 bytes + ([#8194](https://github.com/open-telemetry/opentelemetry-java/pull/8194)) +* OTLP: remove duplicate FINEST-level error logging in gRPC exporter + ([#8216](https://github.com/open-telemetry/opentelemetry-java/pull/8216)) +* OTLP Profiles: clean up profile signal exporters for consistency + ([#8172](https://github.com/open-telemetry/opentelemetry-java/pull/8172)) + +#### Extensions + +* **BREAKING** Autoconfigure: remove deprecated `ComponentLoader` class (use + `io.opentelemetry.common.ComponentLoader` instead) + ([#8243](https://github.com/open-telemetry/opentelemetry-java/pull/8243)) +* Declarative config: fix `DeclarativeConfigProperties` javadoc to not throw exceptions + ([#8079](https://github.com/open-telemetry/opentelemetry-java/pull/8079)) +* Declarative config: resource attribute filtering should include attributes by default + ([#8177](https://github.com/open-telemetry/opentelemetry-java/pull/8177)) +* Declarative config: enforce IncludedExcludeModel .included and .excluded are not empty + ([#8266](https://github.com/open-telemetry/opentelemetry-java/pull/8266)) +* Autoconfigure: restructure SDK incubator to not depend on autoconfigure internals + ([#8242](https://github.com/open-telemetry/opentelemetry-java/pull/8242)) + +### Project tooling + +* Disable Gradle build cache on releases to mitigate supply chain risk + ([#8254](https://github.com/open-telemetry/opentelemetry-java/pull/8254)) + +## Version 1.60.1 (2026-03-08) + +### SDK + +#### Extensions + +* Autoconfigure: fix warning always emitted + ([#8157](https://github.com/open-telemetry/opentelemetry-java/pull/8157)) + +## Version 1.60.0 (2026-03-06) + +### API + +* Support W3C trace context random flag + ([#8012](https://github.com/open-telemetry/opentelemetry-java/pull/8012)) +* Clarify that `SpanBuilder.setAttribute` allows null values + ([#8072](https://github.com/open-telemetry/opentelemetry-java/pull/8072)) + +#### Incubating + +* Implement environment variable context propagation carriers + ([#8074](https://github.com/open-telemetry/opentelemetry-java/pull/8074)) +* Deprecate `ExtendedAttributes`, `ExtendedAttributeKey`, `ExtendedAttributeType`, + `ExtendedAttributesBuilder` + ([#8060](https://github.com/open-telemetry/opentelemetry-java/pull/8060)) +* Deprecate `peerServiceMapping` accessor from `InstrumentationConfigUtil` + ([#8088](https://github.com/open-telemetry/opentelemetry-java/pull/8088)) + +### SDK + +#### Traces + +* Disable warning when using `TraceIdRatioBasedSampler` as root sampler + ([#8065](https://github.com/open-telemetry/opentelemetry-java/pull/8065)) +* User-supplied attributes take precedence over exception-derived attributes + ([#7993](https://github.com/open-telemetry/opentelemetry-java/pull/7993)) +* Exclude META-INF/maven from traces SDK shaded dependencies + ([#8096](https://github.com/open-telemetry/opentelemetry-java/pull/8096)) +* Fix inverted condition in LegacySpanProcessorInstrumentation#finishSpans + ([#8145](https://github.com/open-telemetry/opentelemetry-java/pull/8145)) + +#### Metrics + +* Split out cumulative vs. delta storage + ([#8015](https://github.com/open-telemetry/opentelemetry-java/pull/8015)) +* Add metrics for `PeriodicMetricReader` + ([#8038](https://github.com/open-telemetry/opentelemetry-java/pull/8038)) +* Allow configuring min/max in histograms + ([#8095](https://github.com/open-telemetry/opentelemetry-java/pull/8095)) +* Remove deprecated `otel.experimental.metrics.cardinality.limit` property + ([#8124](https://github.com/open-telemetry/opentelemetry-java/pull/8124)) +* **BREAKING** bug fix: `GlobUtil` and `IncludePatternMatching`, used in views and declarative + config matching, previously were inconsistent in case sensitivity. If a glob char (* or ?) was + present, it was evaluated with case sensitivity. If no glob chars were present, it was evaluated + with case insensitivity. Now, all are consistently evaluated with case sensitivity. + ([#8152](https://github.com/open-telemetry/opentelemetry-java/pull/8152)) + +#### Logs + +* Stabilize `LogRecordBuilder.setException` + ([#8089](https://github.com/open-telemetry/opentelemetry-java/pull/8089)) +* Clarify `setTimestamp` javadoc for event timestamp behavior + ([#8104](https://github.com/open-telemetry/opentelemetry-java/pull/8104)) + +#### Exporters + +* OTLP: Fix marshaling for empty string attributes + ([#8014](https://github.com/open-telemetry/opentelemetry-java/pull/8014)) +* Prometheus: Update Prometheus client to 1.5.0 + ([#8080](https://github.com/open-telemetry/opentelemetry-java/pull/8080)) +* OTLP: Serialize exponential histogram sum as optional double + ([#8107](https://github.com/open-telemetry/opentelemetry-java/pull/8107)) +* OTLP: Use `KeyManagerFactory.getDefaultAlgorithm()` in `TlsUtil.keyManager()` + ([#8122](https://github.com/open-telemetry/opentelemetry-java/pull/8122)) +* OTLP: Ensure proto serializer idCache is cleared when exception is thrown + ([#8147](https://github.com/open-telemetry/opentelemetry-java/pull/8147)) + +#### Extensions + +* Autoconfigure: Decode plus sign in resource attributes + ([#8059](https://github.com/open-telemetry/opentelemetry-java/pull/8059)) +* Declarative config: update to 1.0 schema + ([#8123](https://github.com/open-telemetry/opentelemetry-java/pull/8123)) +* Declarative config: add support for setting schema URL + ([#8028](https://github.com/open-telemetry/opentelemetry-java/pull/8028)) +* Declarative config: add version mismatch warning + ([#8069](https://github.com/open-telemetry/opentelemetry-java/pull/8069)) +* Declarative config: cache component providers in `DeclarativeConfigContext` + ([#8070](https://github.com/open-telemetry/opentelemetry-java/pull/8070)) +* Declarative config: add system property substitution + ([#8073](https://github.com/open-telemetry/opentelemetry-java/pull/8073)) +* Declarative config: add exporter customizers + ([#8081](https://github.com/open-telemetry/opentelemetry-java/pull/8081)) +* Declarative config: add support for setting internal telemetry version + ([#8045](https://github.com/open-telemetry/opentelemetry-java/pull/8045)) +* Deprecate View File Configuration mechanism + ([#8133](https://github.com/open-telemetry/opentelemetry-java/pull/8133)) +* Autoconfigure: add property to allow autoconfiguration of SDK telemetry version + ([#8037](https://github.com/open-telemetry/opentelemetry-java/pull/8037)) +* Jaeger remote sampler: refactor to leverage senders + ([#8046](https://github.com/open-telemetry/opentelemetry-java/pull/8046)) +* Declarative config: document ObjectMapper config + ([#8075](https://github.com/open-telemetry/opentelemetry-java/pull/8075)) +* Declarative config: Remove unchecked warning + ([#8090](https://github.com/open-telemetry/opentelemetry-java/pull/8090)) + +### Project tooling + +* Add architecture test to detect usage of shared internal code + ([#6978](https://github.com/open-telemetry/opentelemetry-java/pull/6978)) +* Replace Xlint deprecation check with custom error-prone check + ([#8061](https://github.com/open-telemetry/opentelemetry-java/pull/8061)) +* Enable error-prone's UnnecessarilyFullyQualified check + ([#8078](https://github.com/open-telemetry/opentelemetry-java/pull/8078)) +* Small refactoring to make safety clearer + ([#8083](https://github.com/open-telemetry/opentelemetry-java/pull/8083)) +* Rework span record benchmark and publish results + ([#8031](https://github.com/open-telemetry/opentelemetry-java/pull/8031)) +* Add `LogRecordBenchmark` + ([#8106](https://github.com/open-telemetry/opentelemetry-java/pull/8106), + [#8117](https://github.com/open-telemetry/opentelemetry-java/pull/8117)) + +## Version 1.59.0 (2026-02-06) + +### API + +* Stabilize complex attributes + ([#7973](https://github.com/open-telemetry/opentelemetry-java/pull/7973)) +* Limit init valid hex array to range that can be true + ([#7809](https://github.com/open-telemetry/opentelemetry-java/pull/7809)) + +#### Extensions + +* Trace propagators: Deprecate OtTracePropagator + ([#8020](https://github.com/open-telemetry/opentelemetry-java/pull/8020)) +* Trace propagators: Deprecate JaegerPropagator + ([#8019](https://github.com/open-telemetry/opentelemetry-java/pull/8019)) + +### SDK + +* Move io.opentelemetry.sdk.internal to io.opentelemetry.sdk.common.internal + ([#8003](https://github.com/open-telemetry/opentelemetry-java/pull/8003)) +* Always return ExtendedOpenTelemetry when incubator is available + ([#7991](https://github.com/open-telemetry/opentelemetry-java/pull/7991)) + +#### Traces + +* Fix memory leak in SdkSpan#spanEndingThread + ([#7984](https://github.com/open-telemetry/opentelemetry-java/pull/7984)) + +#### Metrics + +* Rework and publish metric benchmarks + ([#8000](https://github.com/open-telemetry/opentelemetry-java/pull/8000)) +* Update LongLastValueAggregator algo to avoid allocations + ([#8017](https://github.com/open-telemetry/opentelemetry-java/pull/8017)) + +#### Testing + +* Fix OTel JUnit5 Extension cleanup when using Nested test classes + ([#7999](https://github.com/open-telemetry/opentelemetry-java/pull/7999)) +* Add assertion support for Span hasException(null) + ([#8033](https://github.com/open-telemetry/opentelemetry-java/pull/8033)) + +#### Exporters + +* **DEPRECATION**: `opentelemetry-exporter-zipkin` is now deprecated with the + last release planned for 1.65.0 (August 2026) + ([#7974](https://github.com/open-telemetry/opentelemetry-java/pull/7974)) +* Refactor http, grpc senders and promote to public API + ([#7782](https://github.com/open-telemetry/opentelemetry-java/pull/7782)) + +#### Extensions + +* Jaeger remote sampler: Remove unused code + ([#7970](https://github.com/open-telemetry/opentelemetry-java/pull/7970)) +* Incubator: Add AlwaysRecordSampler + ([#7877](https://github.com/open-telemetry/opentelemetry-java/pull/7877)) + +### Project tooling + +* Align generate release contributors + ([#8023](https://github.com/open-telemetry/opentelemetry-java/pull/8023)) + +## Version 1.58.0 (2026-01-09) + +### API + +#### Incubator + +* Delete GlobalConfigProvider in favor of access via ExtendedOpenTelemetry + ([#7914](https://github.com/open-telemetry/opentelemetry-java/pull/7914)) +* Add DeclarativeConfigProperties#get method + ([#7923](https://github.com/open-telemetry/opentelemetry-java/pull/7923)) +* Update ConfigProvider#getInstrumentationConfig response to be non-null + ([#7954](https://github.com/open-telemetry/opentelemetry-java/pull/7954)) +* Add declarative config utility methods for common operations + ([#7927](https://github.com/open-telemetry/opentelemetry-java/pull/7927)) + +### SDK + +#### Traces + +* Implement SDK metrics for trace + ([#7895](https://github.com/open-telemetry/opentelemetry-java/pull/7895), + [#7930](https://github.com/open-telemetry/opentelemetry-java/pull/7930)) +* Emit warning when TraceIdRatioBasedSampler is used as child sampler + ([#7937](https://github.com/open-telemetry/opentelemetry-java/pull/7937)) + +#### Logs + +* Implement SDK metrics for logs + ([#7931](https://github.com/open-telemetry/opentelemetry-java/pull/7931)) + +#### Exporters + +* Prom exporter update + ([#7934](https://github.com/open-telemetry/opentelemetry-java/pull/7934)) + +#### Extensions + +* Declarative config: update to opentelemetry-configuration 1.0.0-rc.3 + ([#7861](https://github.com/open-telemetry/opentelemetry-java/pull/7861)) +* Declarative config: update jaeger remote sampler to require endpoint, initial_sampler + ([#7943](https://github.com/open-telemetry/opentelemetry-java/pull/7943)) +* Declarative config: add support for view unit + ([#7942](https://github.com/open-telemetry/opentelemetry-java/pull/7942)) +* Declarative config: add support for new logger config minimum_severity and trace_based properties + ([#7940](https://github.com/open-telemetry/opentelemetry-java/pull/7940)) +* Declarative config: add support for composable parent threshold sampler + ([#7941](https://github.com/open-telemetry/opentelemetry-java/pull/7941)) +* Declarative config: improve pattern for validating and loading SDK extension plugins + ([#7947](https://github.com/open-telemetry/opentelemetry-java/pull/7947)) + +### Project tooling + +* Use develocity build cache in PRs and local builds + ([#7906](https://github.com/open-telemetry/opentelemetry-java/pull/7906)) +* Configure japicmp classpath to avoid false positives + ([#7945](https://github.com/open-telemetry/opentelemetry-java/pull/7945)) + +## Version 1.57.0 (2025-12-05) + +### API + +* Add `GlobalOpenTelemetry#getOrNoop`, `#isSet`. Update `#get` to always returns obfuscated instance + ([#7819](https://github.com/open-telemetry/opentelemetry-java/pull/7819)) + +#### Incubating + +* Logs: Complex attributes incubating implementation + ([#7814](https://github.com/open-telemetry/opentelemetry-java/pull/7814)) + +### SDK + +#### Logs + +* Add minimum severity and trace-based logger configuration (incubating API) + ([#7529](https://github.com/open-telemetry/opentelemetry-java/pull/7529)) + +#### Exporters + +* OTLP: VarHandle string encoder + ([#7701](https://github.com/open-telemetry/opentelemetry-java/pull/7701)) +* OTLP: Fix OkHttpGrpcSender to properly await executor shutdown + ([#7840](https://github.com/open-telemetry/opentelemetry-java/pull/7840)) +* OTLP: avoid auto-config warning + ([#7881](https://github.com/open-telemetry/opentelemetry-java/pull/7881)) +* OTLP: update error message for missing GrpcSenderProvider dependency + ([#7884](https://github.com/open-telemetry/opentelemetry-java/pull/7884)) + +#### Extensions + +* Declarative config: add runtime hints for graal VM + ([#7866](https://github.com/open-telemetry/opentelemetry-java/pull/7866)) +* Declarative config: add missing warning about discarded value + ([#7821](https://github.com/open-telemetry/opentelemetry-java/pull/7821)) + +### Project tooling + +* Update macos version to latest and switch to corretto for testing + ([#7841](https://github.com/open-telemetry/opentelemetry-java/pull/7841)) +* Sync Java worflows: Allow re-running prepare release branch workflow + ([#7845](https://github.com/open-telemetry/opentelemetry-java/pull/7845)) +* Simplify and standardize renovate custom managers across Java repos + ([#7846](https://github.com/open-telemetry/opentelemetry-java/pull/7846)) +* Remove misspell workflow + ([#7852](https://github.com/open-telemetry/opentelemetry-java/pull/7852)) +* Fix link checks on main + ([#7867](https://github.com/open-telemetry/opentelemetry-java/pull/7867)) +* Add zeitlinger as approver + ([#7868](https://github.com/open-telemetry/opentelemetry-java/pull/7868)) +* Move snapshot publishing to daily build + ([#7886](https://github.com/open-telemetry/opentelemetry-java/pull/7886)) + +## Version 1.56.0 (2025-11-07) + +### API + +#### Incubator + +* Support ExtendedOpenTelemetry in GlobalOpenTelemetry + ([#7799](https://github.com/open-telemetry/opentelemetry-java/pull/7799)) + +### SDK + +* Changes to MeterConfig, LoggerConfig, TracerConfig are guaranteed to be eventually visible + ([#7706](https://github.com/open-telemetry/opentelemetry-java/pull/7706)) + +#### Metrics + +* Stabilize ExemplarFilter + ([#7768](https://github.com/open-telemetry/opentelemetry-java/pull/7768)) +* Type specific exemplar reservoirs + ([#7758](https://github.com/open-telemetry/opentelemetry-java/pull/7758)) + +#### Extensions + +* SDK incubator: Add incubator ComposableRuleBasedSampler + ([#7787](https://github.com/open-telemetry/opentelemetry-java/pull/7787)) +* SDK incubator: Add incubator ComposableAnnotatingSampler + ([#7804](https://github.com/open-telemetry/opentelemetry-java/pull/7804)) +* SDK incubator: Rename ComposableTraceIdRatioBased to ComposableProbability + ([#7786](https://github.com/open-telemetry/opentelemetry-java/pull/7786)) +* Declarative config: **BREAKING** Remove component provider generic type + ([#7606](https://github.com/open-telemetry/opentelemetry-java/pull/7606)) +* Declarative config: Add declarative config support for ExemplarFilter + ([#7769](https://github.com/open-telemetry/opentelemetry-java/pull/7769)) +* Declarative config: Fix a few declarative configuration bugs + ([#7807](https://github.com/open-telemetry/opentelemetry-java/pull/7807)) + +### Project tooling + +* Move to oracle bare metal benchmark runner + ([#7740](https://github.com/open-telemetry/opentelemetry-java/pull/7740)) +* Enable Develocity build scans + ([#7776](https://github.com/open-telemetry/opentelemetry-java/pull/7776)) +* Document GPG signing key + ([#7783](https://github.com/open-telemetry/opentelemetry-java/pull/7783)) +* Update build to use java 21 + ([#7784](https://github.com/open-telemetry/opentelemetry-java/pull/7784)) +* Sync repository-settings.md documentation + ([#7791](https://github.com/open-telemetry/opentelemetry-java/pull/7791)) +* Fix gradle deprecation warning + ([#7780](https://github.com/open-telemetry/opentelemetry-java/pull/7780)) +* Small alignments of workflows across the 6 Java repos + ([#7806](https://github.com/open-telemetry/opentelemetry-java/pull/7806)) +* Implement min java version gradle tooling from instrumentation repo + ([#7801](https://github.com/open-telemetry/opentelemetry-java/pull/7801)) + +## Version 1.55.0 (2025-10-13) + +### API + +#### Common + +* Improve GraalVM native image compatibility + ([#7160](https://github.com/open-telemetry/opentelemetry-java/pull/7160)) + +#### Traces + +* Fix `TraceState` key validation limits to match W3C specification + ([#7575](https://github.com/open-telemetry/opentelemetry-java/pull/7575)) + +#### Incubator + +* Add `ExtendedOpenTelemetry` API + ([#7496](https://github.com/open-telemetry/opentelemetry-java/pull/7496)) +* Add incubator implementation of composite sampling specification + ([#7626](https://github.com/open-telemetry/opentelemetry-java/pull/7626)) + +### SDK + +#### Traces + +* Proactively avoid `Unsafe` on Java 23+ to avoid triggering JVM warning message + ([#7691](https://github.com/open-telemetry/opentelemetry-java/pull/7691)) + +#### Metrics + +* Add `setMeterConfigurator()` support to `MeterProvider` (incubating API) + ([#7346](https://github.com/open-telemetry/opentelemetry-java/pull/7346)) + +#### Exporters + +* OTLP: Configure metric exporter to use SDK's `MeterProvider` for internal metrics + ([#7541](https://github.com/open-telemetry/opentelemetry-java/pull/7541)) +* OTLP: Suppress logging of `InterruptedException` from managed OkHttp threads + ([#7565](https://github.com/open-telemetry/opentelemetry-java/pull/7565)) +* OTLP: Update dependency from `okhttp-jvm` back to `okhttp` for Gradle users, + preserving `okhttp-jvm` for Maven users + ([#7681](https://github.com/open-telemetry/opentelemetry-java/pull/7681)) +* Prometheus: Remove separate `otel_scope_info` metric and always add scope labels to data points + ([#7398](https://github.com/open-telemetry/opentelemetry-java/pull/7398)) +* Prometheus: Update exporter dependencies to use protobuf-free formats + ([#7664](https://github.com/open-telemetry/opentelemetry-java/pull/7664)) + +#### Profiling + +* Update profiles exporter to support proto v1.8.0-alpha changes + ([#7638](https://github.com/open-telemetry/opentelemetry-java/pull/7638)) +* Add abstractions to assist with dictionary table assembly + ([#7717](https://github.com/open-telemetry/opentelemetry-java/pull/7717)) +* Add abstractions to assist with sample composition + ([#7727](https://github.com/open-telemetry/opentelemetry-java/pull/7727)) + +#### Extensions + +* Autoconfigure: Improve exception logging when running in Maven + ([#7336](https://github.com/open-telemetry/opentelemetry-java/pull/7336)) +* Declarative configuration: Return `Resource` + ([#7639](https://github.com/open-telemetry/opentelemetry-java/pull/7639)) +* Declarative configuration: Invoke auto-configure listeners + ([#7654](https://github.com/open-telemetry/opentelemetry-java/pull/7654)) +* Declarative configuration: Add logging when incompatible types are found + ([#7693](https://github.com/open-telemetry/opentelemetry-java/pull/7693)) + +### Shims + +#### OpenTracing Shim + +* Improve log levels in error scenarios + ([#6832](https://github.com/open-telemetry/opentelemetry-java/pull/6832)) + +### Project tooling + +* Respect `testJavaVersion` property when running JMH benchmarks + ([#7697](https://github.com/open-telemetry/opentelemetry-java/pull/7697)) + +## Version 1.54.1 (2025-09-18) + +### SDK + +#### Exporters + +* Prometheus: Fix regression in protobuf format export + ([#7664](https://github.com/open-telemetry/opentelemetry-java/pull/7664)) + +## Version 1.54.0 (2025-09-05) + +### API + +#### Baggage + +* Fix guard against ArrayIndexOutOfBoundsException in BaggageCodec + ([#7239](https://github.com/open-telemetry/opentelemetry-java/pull/7239)) + +### SDK + +#### Metrics + +* Fix MetricData.getDoubleSumData() ClassCastException with custom implementations + ([#7597](https://github.com/open-telemetry/opentelemetry-java/pull/7597)) + +#### Exporters + +* Fix HttpExporterBuilder.copy() and GrpcExporterBuilder.copy() to preserve component loader + ([#7596](https://github.com/open-telemetry/opentelemetry-java/pull/7596)) + +#### Extensions + +* Autoconfigure: Remove support for old EnvironmentResourceProvider package name + ([#7622](https://github.com/open-telemetry/opentelemetry-java/pull/7622)) +* Declarative config: Add DeclarativeConfigurationProvider SPI + ([#7472](https://github.com/open-telemetry/opentelemetry-java/pull/7472)) +* Declarative config: Pass meter provider to avoid using the global OpenTelemetry instance + ([#7475](https://github.com/open-telemetry/opentelemetry-java/pull/7475)) + +### Project tooling + +* Update to Gradle v9 + ([#7590](https://github.com/open-telemetry/opentelemetry-java/pull/7590)) + +## Version 1.53.0 (2025-08-08) + +### SDK + +* File based config will log the wrong file format, when applicable. + ([#7498](https://github.com/open-telemetry/opentelemetry-java/pull/7498)) + +#### Exporters + +* Change `okhttp` dependency to `okhttp-jvm`, which fixes missing class failures in + transitive dependencies. + ([#7517](https://github.com/open-telemetry/opentelemetry-java/pull/7517)) + +## Version 1.52.0 (2025-07-11) + +### API + +#### Common + +* Promote `ComponentLoader` to new `opentelemetry-common` artifact, + standardize SPI loading + ([#7446](https://github.com/open-telemetry/opentelemetry-java/pull/7446)) + +#### Context + +* LazyStorage passes its ClassLoader when loading ContextStorageProvider SPI + ([#7424](https://github.com/open-telemetry/opentelemetry-java/pull/7424)) + +#### Incubator + +* Add context and severity params to ExtendedLogger#isEnabled + ([#7268](https://github.com/open-telemetry/opentelemetry-java/pull/7268)) +* Add new convenience methods for converting DeclarativeConfigProperties to config model + ([#7453](https://github.com/open-telemetry/opentelemetry-java/pull/7453)) + +### SDK + +* Add custom stacktrace renderer which is length limit aware + ([#7281](https://github.com/open-telemetry/opentelemetry-java/pull/7281)) + +#### Metrics + +* Propagate flush to PeriodicMetricReader's metricExporter. + ([#7410](https://github.com/open-telemetry/opentelemetry-java/pull/7410)) + +#### Exporters + +* OTLP - JdkHttpSender: ensure proper closure of HttpClient in shutdown method + ([#7390](https://github.com/open-telemetry/opentelemetry-java/pull/7390)) +* OTLP: profile exporters fix and test improvements + ([#7442](https://github.com/open-telemetry/opentelemetry-java/pull/7442)) +* OTLP: Loading Compressor SPI via ComponentLoader configured through setComponentLoader + ([#7428](https://github.com/open-telemetry/opentelemetry-java/pull/7428)) +* Prometheus: add scope schema URL and attributes + ([#7356](https://github.com/open-telemetry/opentelemetry-java/pull/7356)) +* Prometheus: extend prometheus declarative config support to include without_scope_info, + with_resource_constant_labels + ([#6840](https://github.com/open-telemetry/opentelemetry-java/pull/6840)) + +#### Extensions + +* Autoconfigure: fix race condition of `GlobalOpenTelemetry` initialization with + `AutoConfiguredOpenTelemetrySdkBuilder` + ([#7365](https://github.com/open-telemetry/opentelemetry-java/pull/7365)) +* Declarative config: update to declarative config 1.0-rc.1 + ([#7436](https://github.com/open-telemetry/opentelemetry-java/pull/7436)) +* Declarative config: resolve environment variable substitution for mixed quotes + ([#7433](https://github.com/open-telemetry/opentelemetry-java/pull/7433)) + +## Version 1.51.0 (2025-06-06) + +### API + +#### Context + +* Fix context storage provider property name in log message + ([#7342](https://github.com/open-telemetry/opentelemetry-java/pull/7342)) + +### SDK + +* Experimental configurable exception.* attribute resolution for SdkTracerProvider, + SdkLoggerProvider + ([#7266](https://github.com/open-telemetry/opentelemetry-java/pull/7266)) + +#### Exporters + +* All exporters: implement new SemConv exporter health metrics, with configuration API for selecting + schema version + ([#7265](https://github.com/open-telemetry/opentelemetry-java/pull/7265)) +* OTLP: Add gRPC export for profiles signal type. + ([#7301](https://github.com/open-telemetry/opentelemetry-java/pull/7301)) +* OTLP: Run JDK HTTP sender on non-daemon threads. + ([#7322](https://github.com/open-telemetry/opentelemetry-java/pull/7322)) +* Prometheus: fix serialization of arrays + ([#7291](https://github.com/open-telemetry/opentelemetry-java/pull/7291)) +* OTLP: exporter tolerates instances of LogRecordData when incubator is present + ([#7393](https://github.com/open-telemetry/opentelemetry-java/pull/7393)) + +#### Extensions + +* Declarative config: Handle instrumentation node changes in yaml config file format 0.4 + ([#7357](https://github.com/open-telemetry/opentelemetry-java/pull/7357)) + +## Version 1.50.0 (2025-05-09) + +### API + +* Clarify that AttributesBuilder.put allows nulls + ([#7271](https://github.com/open-telemetry/opentelemetry-java/pull/7271)) +* Stabilize log record event name + ([#7277](https://github.com/open-telemetry/opentelemetry-java/pull/7277)) + +#### Context + +* Fix duplicated ExecutorService wrap + ([#7245](https://github.com/open-telemetry/opentelemetry-java/pull/7245)) +* Promote getAll to TextMapGetter stable API + ([#7267](https://github.com/open-telemetry/opentelemetry-java/pull/7267)) + +#### Incubator + +* Add ExtendedLogRecordBuilder#setException + ([#7182](https://github.com/open-telemetry/opentelemetry-java/pull/7182)) +* Add experimental support for log extended attributes + ([#7123](https://github.com/open-telemetry/opentelemetry-java/pull/7123)) + +### SDK + +* Remove Java9VersionSpecific clock implementation + ([#7221](https://github.com/open-telemetry/opentelemetry-java/pull/7221)) +* Add addProcessorFirst to SdkTracerProviderBuilder, SdkLoggerProviderBuilder + ([#7243](https://github.com/open-telemetry/opentelemetry-java/pull/7243)) + +#### Logs + +* Add `setLoggerConfigurator` support to `LoggerProvider` + ([#7332](https://github.com/open-telemetry/opentelemetry-java/pull/7332)) + +#### Metrics + +* Add DelegatingMetricData + ([#7229](https://github.com/open-telemetry/opentelemetry-java/pull/7229)) +* Spatial aggregation for async instruments with filtering views + ([#7264](https://github.com/open-telemetry/opentelemetry-java/pull/7264)) + +#### Exporters + +* Prometheus: Add Authenticator support for PrometheusHttpServer + ([#7225](https://github.com/open-telemetry/opentelemetry-java/pull/7225)) +* OTLP: Fix OTLP metric exporter toBuilder() loosing temporality + ([#7280](https://github.com/open-telemetry/opentelemetry-java/pull/7280)) +* OTLP: Allow Otlp*MetricExporter's to publish export stats + ([#7255](https://github.com/open-telemetry/opentelemetry-java/pull/7255)) + +#### Extensions + +* Declarative config: Add support for escaping env var substitution + ([#7033](https://github.com/open-telemetry/opentelemetry-java/pull/7033)) +* Declarative config: update to opentelemetry-configuration 0.4 + ([#7064](https://github.com/open-telemetry/opentelemetry-java/pull/7064)) +* Declarativeconfig: Refactor internals to add DeclarativeConfigContext + ([#7293](https://github.com/open-telemetry/opentelemetry-java/pull/7293)) + +### Project tooling + +* Kotlin extension: Update min kotlin version to 1.8 + ([#7155](https://github.com/open-telemetry/opentelemetry-java/pull/7155)) +* Add javadoc site crawler + ([#7300](https://github.com/open-telemetry/opentelemetry-java/pull/7300), + [#7316](https://github.com/open-telemetry/opentelemetry-java/pull/7316)) + +## Version 1.49.0 (2025-04-04) + +### SDK + +#### Trace + +* Avoid linear queue.size() calls in span producers by storing queue size separately + ([#7141](https://github.com/open-telemetry/opentelemetry-java/pull/7141)) + +#### Exporters + +* OTLP: Add support for setting exporter executor service + ([#7152](https://github.com/open-telemetry/opentelemetry-java/pull/7152)) +* OTLP: Refine delay jitter for exponential backoff + ([#7206](https://github.com/open-telemetry/opentelemetry-java/pull/7206)) + +#### Extensions + +* Autoconfigure: Remove support for otel.experimental.exporter.otlp.retry.enabled + ([#7200](https://github.com/open-telemetry/opentelemetry-java/pull/7200)) +* Autoconfigure: Add stable cardinality limit property otel.java.metrics.cardinality.limit + ([#7199](https://github.com/open-telemetry/opentelemetry-java/pull/7199)) +* Incubator: Add declarative config model customizer SPI + ([#7118](https://github.com/open-telemetry/opentelemetry-java/pull/7118)) + +## Version 1.48.0 (2025-03-07) + +### API + +* Add some helpful logging attribute methods to `LogRecordBuilder` + ([#7089](https://github.com/open-telemetry/opentelemetry-java/pull/7089)) + +#### Incubator + +* Introduce ConfigProvider API. Rename `StructuredConfigProperties` to `DeclarativeConfigProperties` + and move to `opentelemetry-api-incubator`. Rename `FileConfiguration` + to `DeclarativeConfiguration`. + ([#6549](https://github.com/open-telemetry/opentelemetry-java/pull/6549)) + +### SDK + +* Log warning and adjust when BatchLogRecordProcessor, BatchSpanProcessor `maxExportBatchSize` + exceeds `maxQueueSize`. + ([#7045](https://github.com/open-telemetry/opentelemetry-java/pull/7045), + [#7148](https://github.com/open-telemetry/opentelemetry-java/pull/7148)) +* Fix bug causing `ThrottlingLogger` to log more than once per minute + ([#7156](https://github.com/open-telemetry/opentelemetry-java/pull/7156)) + +#### Metrics + +* Remove obsolete `SdkMeterProviderUtil#setCardinalitylimit` API + ([#7169](https://github.com/open-telemetry/opentelemetry-java/pull/7169)) + +#### Traces + +* Fix bug preventing accurate reporting of span event dropped attribute count + ([#7142](https://github.com/open-telemetry/opentelemetry-java/pull/7142)) + +#### Exporters + +* OTLP: remove support for `otel.java.experimental.exporter.memory_mode` + which was previously replaced by `otel.java.exporter.memory_mode` + ([#7127](https://github.com/open-telemetry/opentelemetry-java/pull/7127)) +* OTLP: Extract sender parameters to config carrier class + (incubating API) + ([#7151](https://github.com/open-telemetry/opentelemetry-java/pull/7151)) +* OTLP: Add support for setting OTLP exporter service class loader + ([#7150](https://github.com/open-telemetry/opentelemetry-java/pull/7150)) + +### Tooling + +* Update android animalsniffer min API version to 23 + ([#7153](https://github.com/open-telemetry/opentelemetry-java/pull/7153)) + +## Version 1.47.0 (2025-02-07) + +### API + +#### Incubator + +* Make `ExtendedTracer` easier to use + ([#6943](https://github.com/open-telemetry/opentelemetry-java/pull/6943)) +* Add `ExtendedLogRecordBuilder#setEventName` and corresponding SDK and OTLP serialization + ([#7012](https://github.com/open-telemetry/opentelemetry-java/pull/7012)) +* BREAKING: Drop event API / SDK + ([#7053](https://github.com/open-telemetry/opentelemetry-java/pull/7053)) + +### SDK + +* Remove -alpha artifacts from runtime classpath of stable components + ([#6944](https://github.com/open-telemetry/opentelemetry-java/pull/6944)) + +#### Traces + +* Bugfix: Follow spec on span limits, batch processors + ([#7030](https://github.com/open-telemetry/opentelemetry-java/pull/7030)) +* Add experimental `SdkTracerProvider.setScopeConfigurator(ScopeConfigurator)` for + updating `TracerConfig` at runtime + ([#7021](https://github.com/open-telemetry/opentelemetry-java/pull/7021)) + +#### Profiles + +* Add AttributeKeyValue abstraction to common otlp exporters + ([#7026](https://github.com/open-telemetry/opentelemetry-java/pull/7026)) +* Improve profiles attribute table handling + ([#7031](https://github.com/open-telemetry/opentelemetry-java/pull/7031)) + +#### Exporters + +* Interpret timeout zero value as no limit + ([#7023](https://github.com/open-telemetry/opentelemetry-java/pull/7023)) +* Bugfix - OTLP: Fix concurrent span reusable data marshaler + ([#7041](https://github.com/open-telemetry/opentelemetry-java/pull/7041)) +* OTLP: Add ability to customize retry exception predicate + ([#6991](https://github.com/open-telemetry/opentelemetry-java/pull/6991)) +* OTLP: Expand default OkHttp sender retry exception predicate + ([#7047](https://github.com/open-telemetry/opentelemetry-java/pull/7047), + [#7057](https://github.com/open-telemetry/opentelemetry-java/pull/7057)) + +#### Extensions + +* Autoconfigure: Consistent application of exporter customizers when otel.{signal}.exporter=none + ([#7017](https://github.com/open-telemetry/opentelemetry-java/pull/7017)) +* Autoconfigure: Promote EnvironmentResourceProvider to public API + ([#7052](https://github.com/open-telemetry/opentelemetry-java/pull/7052)) +* Autoconfigure: Ensure `OTEL_PROPAGATORS` still works when `OTEL_SDK_DISABLED=true`. + ([#7062](https://github.com/open-telemetry/opentelemetry-java/pull/7062))% + +#### Testing + +* Add W3CBaggagePropagator to `OpenTelemetryRule`, `OpenTelemetryExtension`. + ([#7056](https://github.com/open-telemetry/opentelemetry-java/pull/7056)) + +## Version 1.46.0 (2025-01-10) + +### SDK + +* Remove unused dependencies, cleanup code after stabilizing Value + ([#6948](https://github.com/open-telemetry/opentelemetry-java/pull/6948)) +* Explicitly allow null into CompletableResultCode.failExceptionally() + ([#6963](https://github.com/open-telemetry/opentelemetry-java/pull/6963)) + +#### Traces + +* Fix span setStatus + ([#6990](https://github.com/open-telemetry/opentelemetry-java/pull/6990)) + +#### Logs + +* Add getters/accessors for readable fields in ReadWriteLogRecord. + ([#6924](https://github.com/open-telemetry/opentelemetry-java/pull/6924)) + +#### Exporters + +* OTLP: Update to opentelemetry-proto 1.5 + ([#6999](https://github.com/open-telemetry/opentelemetry-java/pull/6999)) +* Bugfix - OTLP: Ensure Serializer runtime exceptions are rethrown as IOException + ([#6969](https://github.com/open-telemetry/opentelemetry-java/pull/6969)) +* BREAKING - OTLP: Delete experimental OTLP authenticator concept. + See [OTLP authentication docs](https://opentelemetry.io/docs/languages/java/sdk/#authentication) + for supported solutions. + ([#6984](https://github.com/open-telemetry/opentelemetry-java/pull/6984)) + +#### Extensions + +* BREAKING - Autoconfigure: Remove support for deprecated otel.experimental.resource.disabled.keys + ([#6931](https://github.com/open-telemetry/opentelemetry-java/pull/6931)) + +## Version 1.45.0 (2024-12-06) + +### API + +* Add convenience method `setAttribute(Attribute, int)` to SpanBuilder (matching the existing + convenience method in Span) + ([#6884](https://github.com/open-telemetry/opentelemetry-java/pull/6884)) +* Extends TextMapGetter with experimental GetAll() method, implement usage in W3CBaggagePropagator + ([#6852](https://github.com/open-telemetry/opentelemetry-java/pull/6852)) + +### SDK + +#### Traces + +* Add synchronization to SimpleSpanProcessor to ensure thread-safe export of spans + ([#6885](https://github.com/open-telemetry/opentelemetry-java/pull/6885)) + +#### Metrics + +* Lazily initialize ReservoirCells + ([#6851](https://github.com/open-telemetry/opentelemetry-java/pull/6851)) + +#### Logs + +* Add synchronization to SimpleLogRecordProcessor to ensure thread-safe export of logs + ([#6885](https://github.com/open-telemetry/opentelemetry-java/pull/6885)) + +#### Exporters + +* OTLP: Update opentelementry-proto to 1.4 + ([#6906](https://github.com/open-telemetry/opentelemetry-java/pull/6906)) +* OTLP: Rename internal Marshaler#writeJsonToGenerator method to allow jackson runtimeOnly dependency + ([#6896](https://github.com/open-telemetry/opentelemetry-java/pull/6896)) +* OTLP: Fix repeated string serialization for JSON. + ([#6888](https://github.com/open-telemetry/opentelemetry-java/pull/6888)) +* OTLP: Fix missing unsafe available check + ([#6920](https://github.com/open-telemetry/opentelemetry-java/pull/6920)) + +#### Extensions + +* Declarative config: Don't require empty objects when referencing custom components + ([#6891](https://github.com/open-telemetry/opentelemetry-java/pull/6891)) + +### Tooling + +* Add javadoc boilerplate internal comment v2 for experimental classes + ([#6886](https://github.com/open-telemetry/opentelemetry-java/pull/6886)) +* Update develocity configuration + ([#6903](https://github.com/open-telemetry/opentelemetry-java/pull/6903)) + +## Version 1.44.1 (2024-11-10) + +### SDK + +#### Traces + +* Fix regression in event attributes + ([#6865](https://github.com/open-telemetry/opentelemetry-java/pull/6865)) + +## Version 1.44.0 (2024-11-08) + +### API + +* Fix ConfigUtil#getString ConcurrentModificationException + ([#6841](https://github.com/open-telemetry/opentelemetry-java/pull/6841)) + +### SDK + +#### Traces + +* Stabilize ExceptionEventData + ([#6795](https://github.com/open-telemetry/opentelemetry-java/pull/6795)) + +#### Metrics + +* Stabilize metric cardinality limits + ([#6794](https://github.com/open-telemetry/opentelemetry-java/pull/6794)) +* Refactor metrics internals to remove MeterSharedState + ([#6845](https://github.com/open-telemetry/opentelemetry-java/pull/6845)) + +#### Exporters + +* Add memory mode option to stdout exporters + ([#6774](https://github.com/open-telemetry/opentelemetry-java/pull/6774)) +* Log a warning if OTLP endpoint port is likely incorrect given the protocol + ([#6813](https://github.com/open-telemetry/opentelemetry-java/pull/6813)) +* Fix OTLP gRPC retry mechanism for unsuccessful HTTP responses + ([#6829](https://github.com/open-telemetry/opentelemetry-java/pull/6829)) +* Add ByteBuffer field type marshaling support + ([#6686](https://github.com/open-telemetry/opentelemetry-java/pull/6686)) +* Fix stdout exporter format by adding newline after each export + ([#6848](https://github.com/open-telemetry/opentelemetry-java/pull/6848)) +* Enable `reusuable_data` memory mode by default for `OtlpGrpc{Signal}Exporter`, + `OtlpHttp{Signal}Exporter`, `OtlpStdout{Signal}Exporter`, and `PrometheusHttpServer` + ([#6799](https://github.com/open-telemetry/opentelemetry-java/pull/6799)) + +#### Extension + +* Rebrand file configuration to declarative configuration in documentation + ([#6812](https://github.com/open-telemetry/opentelemetry-java/pull/6812)) +* Fix declarative config `file_format` validation + ([#6786](https://github.com/open-telemetry/opentelemetry-java/pull/6786)) +* Fix declarative config env substitution by disallowing '}' in default value + ([#6793](https://github.com/open-telemetry/opentelemetry-java/pull/6793)) +* Set declarative config default OTLP protocol to http/protobuf + ([#6800](https://github.com/open-telemetry/opentelemetry-java/pull/6800)) +* Stabilize autoconfigure disabling of resource keys via `otel.resource.disabled.keys` + ([#6809](https://github.com/open-telemetry/opentelemetry-java/pull/6809)) + +### Tooling + +* Run tests on Java 23 + ([#6825](https://github.com/open-telemetry/opentelemetry-java/pull/6825)) +* Test Windows in CI + ([#6824](https://github.com/open-telemetry/opentelemetry-java/pull/6824)) +* Add error prone checks for internal javadoc and private constructors + ([#6844](https://github.com/open-telemetry/opentelemetry-java/pull/6844)) + +## Version 1.43.0 (2024-10-11) + +### API + +* Add helper class to capture context using ScheduledExecutorService + ([#6712](https://github.com/open-telemetry/opentelemetry-java/pull/6712)) +* Adds Baggage.getEntry(String key) + ([#6765](https://github.com/open-telemetry/opentelemetry-java/pull/6765)) + +#### Extensions + +* Fix ottracepropagation for short span ids + ([#6734](https://github.com/open-telemetry/opentelemetry-java/pull/6734)) + +### SDK + +#### Metrics + +* Optimize advice with FilteredAttributes + ([#6633](https://github.com/open-telemetry/opentelemetry-java/pull/6633)) + +#### Exporters + +* Add experimental stdout log, metric, trace exporters for printing records to stdout in standard + OTLP JSON format. + ([#6675](https://github.com/open-telemetry/opentelemetry-java/pull/6675), [#6750](https://github.com/open-telemetry/opentelemetry-java/pull/6750)) +* Add Marshalers for profiling signal type + ([#6680](https://github.com/open-telemetry/opentelemetry-java/pull/6680)) + +#### Extensions + +* Add `*Model` suffix to declarative config generated classes. + ([#6721](https://github.com/open-telemetry/opentelemetry-java/pull/6721)) +* Use autoconfigured ClassLoader to load declarative config + ([#6725](https://github.com/open-telemetry/opentelemetry-java/pull/6725)) +* Update declarative config to use opentelemetry-configuration v0.3.0 + ([#6733](https://github.com/open-telemetry/opentelemetry-java/pull/6733)) +* Add `StructuredConfigProperties#getStructured` default method, + add `StructuredConfigProperties.empty()` + ([#6759](https://github.com/open-telemetry/opentelemetry-java/pull/6759)) + +#### Testing + +* Add context info about wrong span or trace. + ([#6703](https://github.com/open-telemetry/opentelemetry-java/pull/6703)) + +## Version 1.42.1 (2024-09-10) + +### API + +* Revert `java-test-fixtures` plugin to remove test dependencies from `pom.xml`. + ([#6695](https://github.com/open-telemetry/opentelemetry-java/pull/6695)) + +## Version 1.42.0 (2024-09-06) + +### API + +* BREAKING: Stabilize log support for AnyValue bodies. Rename `AnyValue` to `Value`, promote + from `opentelemetry-api-incubator` to `opentelemetry-api`, change package + from `io.opentelemetry.api.incubator.logs` to `io.opentelemetry.api.common`. + ([#6591](https://github.com/open-telemetry/opentelemetry-java/pull/6591)) +* Noop implementations detect when `opentelemetry-api-incubator` is present and return extended noop + implementations. + ([#6617](https://github.com/open-telemetry/opentelemetry-java/pull/6617))% + +### SDK + +#### Traces + +* Added experimental support for SpanProcessor OnEnding callback + ([#6367](https://github.com/open-telemetry/opentelemetry-java/pull/6367)) +* Remove final modifier from SdkTracer.tracerEnabled + ([#6687](https://github.com/open-telemetry/opentelemetry-java/pull/6687)) + +#### Exporters + +* Suppress zipkin exporter instrumentation + ([#6552](https://github.com/open-telemetry/opentelemetry-java/pull/6552)) +* OTLP exporters return status code exceptions via CompletableResultCode in GrpcExporter and + HttpExporter. + ([#6645](https://github.com/open-telemetry/opentelemetry-java/pull/6645)) +* Align GrpcSender contract with HttpSender + ([#6658](https://github.com/open-telemetry/opentelemetry-java/pull/6658)) + +#### Extensions + +* Add autoconfigure support for ns and us durations + ([#6654](https://github.com/open-telemetry/opentelemetry-java/pull/6654)) +* Add declarative configuration ComponentProvider support for resources + ([#6625](https://github.com/open-telemetry/opentelemetry-java/pull/6625)) +* Add declarative configuration ComponentProvider support for processors + ([#6623](https://github.com/open-telemetry/opentelemetry-java/pull/6623)) +* Add declarative configuration ComponentProvider support for samplers + ([#6494](https://github.com/open-telemetry/opentelemetry-java/pull/6494)) +* Add declarative configuration ComponentProvider support for propagators + ([#6624](https://github.com/open-telemetry/opentelemetry-java/pull/6624)) +* Add declarative configuration missing pieces + ([#6677](https://github.com/open-telemetry/opentelemetry-java/pull/6677)) +* Change jaeger remote sampler autoconfigure property from `pollingInterval` to `pollingIntervalMs` + to match spec. + ([#6672](https://github.com/open-telemetry/opentelemetry-java/pull/6672)) + +#### Testing + +* Add asserts for log record body fields + ([#6509](https://github.com/open-telemetry/opentelemetry-java/pull/6509)) + +## Version 1.41.0 (2024-08-09) + +### API + +* Move experimental suppress instrumentation context key to api internal package + ([#6546](https://github.com/open-telemetry/opentelemetry-java/pull/6546)) + +#### Incubator + +* Fix bug in `ExtendedContextPropagators` preventing context extraction when case is incorrect. + ([#6569](https://github.com/open-telemetry/opentelemetry-java/pull/6569)) + +### SDK + +* Extend `CompletableResultCode` with `failExceptionally(Throwable)`. + ([#6348](https://github.com/open-telemetry/opentelemetry-java/pull/6348)) + +#### Metrics + +* Avoid allocations when experimental advice doesn't remove any attributes. + ([#6629](https://github.com/open-telemetry/opentelemetry-java/pull/6629)) + +#### Exporter + +* Enable retry by default for OTLP exporters. + ([#6588](https://github.com/open-telemetry/opentelemetry-java/pull/6588)) +* Retry ConnectException, add retry logging. + ([#6614](https://github.com/open-telemetry/opentelemetry-java/pull/6614)) +* Extend `PrometheusHttpServer` with ability to configure default aggregation as function of + instrument kind, including experimental env var support. + ([#6541](https://github.com/open-telemetry/opentelemetry-java/pull/6541)) +* Add exporter data model impl for profiling signal type. + ([#6498](https://github.com/open-telemetry/opentelemetry-java/pull/6498)) +* Add Marshalers for profiling signal type. + ([#6565](https://github.com/open-telemetry/opentelemetry-java/pull/6565)) +* Use generateCertificates() of CertificateFactory to process certificates. + ([#6579](https://github.com/open-telemetry/opentelemetry-java/pull/6579)) + +#### Extensions + +* Add file configuration ComponentProvider support for exporters. + ([#6493](https://github.com/open-telemetry/opentelemetry-java/pull/6493)) +* Remove nullable from file config Factory contract. + ([#6612](https://github.com/open-telemetry/opentelemetry-java/pull/6612)) + +## Version 1.40.0 (2024-07-05) + +### API + +#### Incubator + +* Narrow ExtendedSpanBuilder return types for chaining + ([#6514](https://github.com/open-telemetry/opentelemetry-java/pull/6514)) +* Add APIs to determine if tracer, logger, instruments are enabled + ([#6502](https://github.com/open-telemetry/opentelemetry-java/pull/6502)) + +### SDK + +#### Extensions + +* Move autoconfigure docs to opentelemetry.io + ([#6491](https://github.com/open-telemetry/opentelemetry-java/pull/6491)) + +## Version 1.39.0 (2024-06-07) + +### API + +#### Incubator + +* BREAKING: Refactor ExtendedTracer, ExtendedSpanBuilder to reflect incubating API conventions + ([#6497](https://github.com/open-telemetry/opentelemetry-java/pull/6497)) + +### SDK + +#### Exporter + +* BREAKING: Serve prometheus metrics only on `/metrics` by default. To restore the previous behavior + and serve metrics on all paths, override the default handler + as [demonstrated here](https://github.com/open-telemetry/opentelemetry-java/blob/main/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java#L251-L259). + ([#6476](https://github.com/open-telemetry/opentelemetry-java/pull/6476)) +* Make OTLP exporter memory mode API public + ([#6469](https://github.com/open-telemetry/opentelemetry-java/pull/6469)) +* Speed up OTLP string marshaling using sun.misc.Unsafe + ([#6433](https://github.com/open-telemetry/opentelemetry-java/pull/6433)) +* Add exporter data classes for experimental profiling signal type. + ([#6374](https://github.com/open-telemetry/opentelemetry-java/pull/6374)) +* Start prometheus http server with daemon thread + ([#6472](https://github.com/open-telemetry/opentelemetry-java/pull/6472)) +* Update the Prometheus metrics library and improve how units are included in metric names. + ([#6473](https://github.com/open-telemetry/opentelemetry-java/pull/6473)) +* Remove android animalsniffer check from prometheus exporter + ([#6478](https://github.com/open-telemetry/opentelemetry-java/pull/6478)) + +#### Extensions + +* Load file config YAML using core schema, ensure that env var substitution retains string types. + ([#6436](https://github.com/open-telemetry/opentelemetry-java/pull/6436)) +* Define dedicated file configuration SPI ComponentProvider + ([#6457](https://github.com/open-telemetry/opentelemetry-java/pull/6457)) + +### Tooling + +* Normalize timestamps and file ordering in jars, making the outputs reproducible + ([#6471](https://github.com/open-telemetry/opentelemetry-java/pull/6471)) +* GHA for generating the post-release pull request + ([#6449](https://github.com/open-telemetry/opentelemetry-java/pull/6449)) + +## Version 1.38.0 (2024-05-10) + +### API + +* Stabilize synchronous gauge + ([#6419](https://github.com/open-telemetry/opentelemetry-java/pull/6419)) + +#### Incubator + +* Add put(AttributeKey, T) overload to EventBuilder + ([#6331](https://github.com/open-telemetry/opentelemetry-java/pull/6331)) + +#### Baggage + +* Baggage filters space-only keys + ([#6431](https://github.com/open-telemetry/opentelemetry-java/pull/6431)) + +### SDK + +* Add experimental scope config to enable / disable scopes (i.e. meter, logger, tracer) + ([#6375](https://github.com/open-telemetry/opentelemetry-java/pull/6375)) + +#### Traces + +* Add ReadableSpan#getAttributes + ([#6382](https://github.com/open-telemetry/opentelemetry-java/pull/6382)) +* Use standard ArrayList size rather than max number of links for initial span links allocation + ([#6252](https://github.com/open-telemetry/opentelemetry-java/pull/6252)) + +#### Metrics + +* Use low precision Clock#now when computing timestamp for exemplars + ([#6417](https://github.com/open-telemetry/opentelemetry-java/pull/6417)) +* Update invalid instrument name log message now that forward slash `/` is valid + ([#6343](https://github.com/open-telemetry/opentelemetry-java/pull/6343)) + +#### Exporters + +* Introduce low allocation OTLP marshalers. If using autoconfigure, opt in + via `OTEL_JAVA_EXPERIMENTAL_EXPORTER_MEMORY_MODE=REUSABLE_DATA`. + * Low allocation OTLP logs marshaler + ([#6429](https://github.com/open-telemetry/opentelemetry-java/pull/6429)) + * Low allocation OTLP metrics marshaler + ([#6422](https://github.com/open-telemetry/opentelemetry-java/pull/6422)) + * Low allocation OTLP trace marshaler + ([#6410](https://github.com/open-telemetry/opentelemetry-java/pull/6410)) + * Add memory mode support to OTLP exporters + ([#6430](https://github.com/open-telemetry/opentelemetry-java/pull/6430)) + * Marshal span status description without allocation + ([#6423](https://github.com/open-telemetry/opentelemetry-java/pull/6423)) + * Add private constructors for stateless marshalers + ([#6434](https://github.com/open-telemetry/opentelemetry-java/pull/6434)) +* Mark opentelemetry-exporter-sender-jdk stable + ([#6357](https://github.com/open-telemetry/opentelemetry-java/pull/6357)) +* PrometheusHttpServer prevent concurrent reads when reusable memory mode + ([#6371](https://github.com/open-telemetry/opentelemetry-java/pull/6371)) +* Ignore TLS components (SSLContext, TrustManager, KeyManager) if plain HTTP protocol is used for + exporting + ([#6329](https://github.com/open-telemetry/opentelemetry-java/pull/6329)) +* Add is_remote_parent span flags to OTLP exported Spans and SpanLinks + ([#6388](https://github.com/open-telemetry/opentelemetry-java/pull/6388)) +* Add missing fields to OTLP metric exporters `toString()` + ([#6402](https://github.com/open-telemetry/opentelemetry-java/pull/6402)) + +#### Extensions + +* Rename otel.config.file to otel.experimental.config.file for autoconfigure + ([#6396](https://github.com/open-telemetry/opentelemetry-java/pull/6396)) + +### OpenCensus Shim + +* Fix opencensus shim spanBuilderWithRemoteParent behavior + ([#6415](https://github.com/open-telemetry/opentelemetry-java/pull/6415)) + +### Tooling + +* Add additional API incubator docs + ([#6356](https://github.com/open-telemetry/opentelemetry-java/pull/6356)) +* Run build on java 21 + ([#6370](https://github.com/open-telemetry/opentelemetry-java/pull/6370)) +* Fix running tests with java 8 on macos + ([#6411](https://github.com/open-telemetry/opentelemetry-java/pull/6411)) +* Move away from deprecated gradle enterprise APIs + ([#6363](https://github.com/open-telemetry/opentelemetry-java/pull/6363)) + +## Version 1.37.0 (2024-04-05) + +**NOTICE:** This release contains a significant restructuring of the experimental event API and the API incubator artifact. Please read the notes in the `API -> Incubator` section carefully. + +### API + +* Promote `Span#addLink` to stable API + ([#6317](https://github.com/open-telemetry/opentelemetry-java/pull/6317)) + +#### Incubator + +* BREAKING: Rename `opentelemetry-extension-incubator` to `opentelemetry-api-incubator`, + merge `opentelemetry-api-events` into `opentelemetry-api-incubator`. + ([#6289](https://github.com/open-telemetry/opentelemetry-java/pull/6289)) +* BREAKING: Remove domain from event api. `EventEmitterProvider#setEventDomain` has been removed. + The `event.name` field should now be namespaced to avoid collisions. + See [Semantic Conventions for Event Attributes](https://opentelemetry.io/docs/specs/semconv/general/events/) + for more details. + ([#6253](https://github.com/open-telemetry/opentelemetry-java/pull/6253)) +* BREAKING: Rename `EventEmitter` and related classes to `EventLogger`. + ([#6316](https://github.com/open-telemetry/opentelemetry-java/pull/6316)) +* BREAKING: Refactor Event API to reflect spec changes. Restructure API to put fields in + the `AnyValue` log record body. Add setters for timestamp, context, and severity. Set default + severity to `INFO=9`. + ([#6318](https://github.com/open-telemetry/opentelemetry-java/pull/6318)) + +### SDK + +* Add `get{Signal}Exporter` methods to `Simple{Signal}Processor`, `Batch{Signal}Processor`. + ([#6078](https://github.com/open-telemetry/opentelemetry-java/pull/6078)) + +#### Metrics + +* Use synchronized instead of reentrant lock in explicit bucket histogram + ([#6309](https://github.com/open-telemetry/opentelemetry-java/pull/6309)) + +#### Exporters + +* Fix typo in OTLP javadoc + ([#6311](https://github.com/open-telemetry/opentelemetry-java/pull/6311)) +* Add `PrometheusHttpServer#toBuilder()` + ([#6333](https://github.com/open-telemetry/opentelemetry-java/pull/6333)) +* Bugfix: Use `getPrometheusName` for Otel2PrometheusConverter map keys to avoid metric name + conflicts + ([#6308](https://github.com/open-telemetry/opentelemetry-java/pull/6308)) + +#### Extensions + +* Add Metric exporter REUSABLE_DATA memory mode configuration options, including autoconfigure + support via env var `OTEL_JAVA_EXPERIMENTAL_EXPORTER_MEMORY_MODE=REUSABLE_DATA`. + ([#6304](https://github.com/open-telemetry/opentelemetry-java/pull/6304)) +* Add autoconfigure console alias for logging exporter + ([#6027](https://github.com/open-telemetry/opentelemetry-java/pull/6027)) +* Update jaeger autoconfigure docs to point to OTLP + ([#6307](https://github.com/open-telemetry/opentelemetry-java/pull/6307)) +* Add `ServiceInstanceIdResourceProvider` implementation for generating `service.instance.id` UUID + if not already provided by user. Included in `opentelemetry-sdk-extension-incubator`. + ([#6226](https://github.com/open-telemetry/opentelemetry-java/pull/6226)) +* Add GCP resource detector to list of resource providers in autoconfigure docs + ([#6336](https://github.com/open-telemetry/opentelemetry-java/pull/6336)) + +### Tooling + +* Check for Java 17 toolchain and fail if not found + ([#6303](https://github.com/open-telemetry/opentelemetry-java/pull/6303)) + +## Version 1.36.0 (2024-03-08) + +### SDK + +#### Traces + +* Lazily initialize the container for events in the SDK Span implementation + ([#6244](https://github.com/open-telemetry/opentelemetry-java/pull/6244)) + +#### Exporters + +* Add basic proxy configuration to OtlpHttp{Signal}Exporters + ([#6270](https://github.com/open-telemetry/opentelemetry-java/pull/6270)) +* Add connectTimeout configuration option OtlpGrpc{Signal}Exporters + ([#6079](https://github.com/open-telemetry/opentelemetry-java/pull/6079)) + +#### Extensions + +* Add ComponentLoader to autoconfigure support more scenarios + ([#6217](https://github.com/open-telemetry/opentelemetry-java/pull/6217)) +* Added MetricReader customizer for AutoConfiguredOpenTelemetrySdkBuilder + ([#6231](https://github.com/open-telemetry/opentelemetry-java/pull/6231)) +* Return AutoConfiguredOpenTelemetrySdkBuilder instead of the base type + ([#6248](https://github.com/open-telemetry/opentelemetry-java/pull/6248)) + +### Tooling + +* Add note about draft PRs to CONTRIBUTING.md + ([#6247](https://github.com/open-telemetry/opentelemetry-java/pull/6247)) + +## Version 1.35.0 (2024-02-09) + +**NOTE:** The `opentelemetry-exporter-jaeger` and `opentelemetry-exporter-jaeger-thift` artifacts +have stopped being published. Jaeger +has [native support for OTLP](https://opentelemetry.io/blog/2022/jaeger-native-otlp/), and users +should export to jaeger +using OTLP +instead. + +### API + +#### Incubator + +* Add Span#addLink, for adding a link after span start + ([#6084](https://github.com/open-telemetry/opentelemetry-java/pull/6084)) + +### SDK + +#### Traces + +* Bugfix: Ensure span status cannot be updated after set to StatusCode.OK + ([#6209](https://github.com/open-telemetry/opentelemetry-java/pull/6209) + +#### Metrics + +* Reusable memory Mode: Adding support for exponential histogram aggregation + ([#6058](https://github.com/open-telemetry/opentelemetry-java/pull/6058), + [#6136](https://github.com/open-telemetry/opentelemetry-java/pull/6136)) +* Reusable memory mode: Adding support for explicit histogram aggregation + ([#6153](https://github.com/open-telemetry/opentelemetry-java/pull/6153)) +* Reusable memory mode: Adding support for sum aggregation + ([#6182](https://github.com/open-telemetry/opentelemetry-java/pull/6182)) +* Reusable memory mode: Adding support for last value aggregation + ([#6196](https://github.com/open-telemetry/opentelemetry-java/pull/6196)) + +#### Exporters + +* Recreate / fix graal issue detecting RetryPolicy class + ([#6139](https://github.com/open-telemetry/opentelemetry-java/pull/6139), + [#6134](https://github.com/open-telemetry/opentelemetry-java/pull/6134)) +* Restore prometheus metric name mapper tests, fix regressions + ([#6138](https://github.com/open-telemetry/opentelemetry-java/pull/6138)) +* WARNING: Remove jaeger exporters + ([#6119](https://github.com/open-telemetry/opentelemetry-java/pull/6119)) +* Update dependency `io.zipkin.reporter2:zipkin-reporter-bom` to 3.2.1. + Note: `ZipkinSpanExporterBuilder#setEncoder(zipkin2.codec.BytesEncoder)` has been deprecated in + favor of `ZipkinSpanExporterBuilder#setEncoder(zipkin2.reporter.BytesEncoder)`. + `ZipkinSpanExporterBuilder#setSender(zipkin2.reporter.Sender)` has been deprecated in favor + of `ZipkinSpanExporterBuilder#setSender(zipkin2.reporter.BytesMessageSender)`. + ([#6129](https://github.com/open-telemetry/opentelemetry-java/pull/6129), + [#6151](https://github.com/open-telemetry/opentelemetry-java/pull/6151)) +* Include trace flags in otlp marshaller + ([#6167](https://github.com/open-telemetry/opentelemetry-java/pull/6167)) +* Add Compressor SPI support to OtlpGrpc{Signal}Exporters + ([#6103](https://github.com/open-telemetry/opentelemetry-java/pull/6103)) +* Allow Prometheus exporter to add resource attributes to metric attributes + ([#6179](https://github.com/open-telemetry/opentelemetry-java/pull/6179)) + +#### Extension + +* Autoconfigure accepts encoded header values for OTLP exporters + ([#6164](https://github.com/open-telemetry/opentelemetry-java/pull/6164)) +* Return implementation type from `AutoConfiguredOpenTelemetrySdkBuilder.addLogRecordProcessorCustomizer` + ([#6248](https://github.com/open-telemetry/opentelemetry-java/pull/6248)) + +#### Incubator + +* Align file configuration with latest changes to spec + ([#6088](https://github.com/open-telemetry/opentelemetry-java/pull/6088)) + +### Tooling + +* Stop including old artifacts in bom + ([#6157](https://github.com/open-telemetry/opentelemetry-java/pull/6157)) +* Define CODECOV token + ([#6186](https://github.com/open-telemetry/opentelemetry-java/pull/6186)) + +## Version 1.34.1 (2024-01-11) + +* Fix prometheus exporter regressions + ([#6138](https://github.com/open-telemetry/opentelemetry-java/pull/6138)) +* Fix native image regression + ([#6134](https://github.com/open-telemetry/opentelemetry-java/pull/6134)) + +## Version 1.34.0 (2024-01-05) + +**NOTE:** This is the LAST release for `opentelemetry-exporter-jaeger` +and `opentelemetry-exporter-jaeger-thift`. Jaeger +has [native support for OTLP](https://opentelemetry.io/blog/2022/jaeger-native-otlp/), and users +should export to jaeger +using OTLP +instead. + +### API + +* Ability to access version.properties API file with GraalVM native + ([#6095](https://github.com/open-telemetry/opentelemetry-java/pull/6095)) + +### SDK + +#### Traces + +* Only call SpanProcessor onStart / onEnd if required + ([#6112](https://github.com/open-telemetry/opentelemetry-java/pull/6112)) +* Add option to export unsampled spans from span processors + ([#6057](https://github.com/open-telemetry/opentelemetry-java/pull/6057)) + +#### Metrics + +* Memory Mode: Adding first part support for synchronous instruments - storage + ([#5998](https://github.com/open-telemetry/opentelemetry-java/pull/5998)) +* Base2ExponentialHistogramAggregation maxBuckets must be >= 2 + ([#6093](https://github.com/open-telemetry/opentelemetry-java/pull/6093)) +* Convert histogram measurements to double before passing recording exemplar reservoir + ([#6024](https://github.com/open-telemetry/opentelemetry-java/pull/6024)) + +#### Exporters + +* Add compressor SPI to support additional compression algos + ([#5990](https://github.com/open-telemetry/opentelemetry-java/pull/5990)) +* Test OTLP exporters with different OkHttp versions + ([#6045](https://github.com/open-telemetry/opentelemetry-java/pull/6045)) +* Refactor prometheus exporter to use `io.prometheus:prometheus-metrics-exporter-httpserver`, add + exponential Histogram support + ([#6015](https://github.com/open-telemetry/opentelemetry-java/pull/6015)) +* UpstreamGrpcSenderProvider uses minimal fallback managed channel when none is specified + ([#6110](https://github.com/open-telemetry/opentelemetry-java/pull/6110)) +* OTLP exporters propagate serialization IOException instead of rethrowing as runtime + ([#6082](https://github.com/open-telemetry/opentelemetry-java/pull/6082)) + +#### Extensions + +* Autoconfigure reads normalized otel.config.file property + ([#6105](https://github.com/open-telemetry/opentelemetry-java/pull/6105)) + +## Version 1.33.0 (2023-12-08) + +### API + +* Fix issue where wrapping "invalid" SpanContexts in Span does not preserve SpanContext + ([#6044](https://github.com/open-telemetry/opentelemetry-java/pull/6044)) + +#### Incubator + +* Refactor and add to ExtendedTracer, add ExtendedContextPropagators + ([#6017](https://github.com/open-telemetry/opentelemetry-java/pull/6017)) +* Base64 encode AnyValue bytes in string representation + ([#6003](https://github.com/open-telemetry/opentelemetry-java/pull/6003)) + +### SDK + +#### Exporters + +* Add connectTimeout configuration option OtlpHttp{Signal}Exporters + ([#5941](https://github.com/open-telemetry/opentelemetry-java/pull/5941)) +* Add ability for Otlp{Protocol}LogRecordExporter to serialize log body any value + ([#5938](https://github.com/open-telemetry/opentelemetry-java/pull/5938)) +* Android environments can now handle base64 encoded PEM keys, remove exception handling in + TlsUtil#decodePem + ([#6034](https://github.com/open-telemetry/opentelemetry-java/pull/6034)) +* Add header supplier configuration option to OTLP exporters + ([#6004](https://github.com/open-telemetry/opentelemetry-java/pull/6004)) + + +#### Extensions + +* Add autoconfigure option for customizing SpanProcessor, LogRecordProcessor + ([#5986](https://github.com/open-telemetry/opentelemetry-java/pull/5986)) +* Incubator allows for simpler creation of start-only and end-only SpanProcessors. + ([#5923](https://github.com/open-telemetry/opentelemetry-java/pull/5923)) + +#### Testing + +* Add hasAttributesSatisfying overload to AbstractPointAssert + ([#6048](https://github.com/open-telemetry/opentelemetry-java/pull/6048)) + +### Project Tooling + +* Building animal sniffer signatures directly from android corelib + ([#5973](https://github.com/open-telemetry/opentelemetry-java/pull/5973)) +* Target kotlin 1.6 in kotlin extension + ([#5910](https://github.com/open-telemetry/opentelemetry-java/pull/5910)) +* Define language version compatibility requirements + ([#5983](https://github.com/open-telemetry/opentelemetry-java/pull/5983)) + +## Version 1.32.0 (2023-11-13) + +### API + +* Stabilize explicit bucket boundaries advice API + ([#5897](https://github.com/open-telemetry/opentelemetry-java/pull/5897)) +* Allow events to be emitted with timestamp + ([#5928](https://github.com/open-telemetry/opentelemetry-java/pull/5928)) + +#### Context + +* Add null check to StrictContextStorage + ([#5954](https://github.com/open-telemetry/opentelemetry-java/pull/5954)) + +#### Incubator + +* Experimental support for Log AnyValue body + ([#5880](https://github.com/open-telemetry/opentelemetry-java/pull/5880)) + +### SDK + +#### Metrics + +* Dismantle AbstractInstrumentBuilder inheritance hierarchy + ([#5820](https://github.com/open-telemetry/opentelemetry-java/pull/5820)) +* Fix delta metric storage concurrency bug that allows for lost writes when record operations occur + during collection. The fix introduces additional work on record threads to ensure correctness. The + additional overhead is non-blocking and should be small according to performance testing. Still, + there may be an opportunity for further optimization. + ([#5932](https://github.com/open-telemetry/opentelemetry-java/pull/5932), + [#5976](https://github.com/open-telemetry/opentelemetry-java/pull/5976)) + + +#### Exporters + +* Prometheus exporter: omit empty otel_scope_info and otel_target_info metrics + ([#5887](https://github.com/open-telemetry/opentelemetry-java/pull/5887)) +* JdkHttpSender should retry on connect exceptions + ([#5867](https://github.com/open-telemetry/opentelemetry-java/pull/5867)) +* Expand the set of retryable exceptions in JdkHttpSender + ([#5942](https://github.com/open-telemetry/opentelemetry-java/pull/5942)) +* Identify OTLP export calls with context key used for instrumentation suppression + ([#5918](https://github.com/open-telemetry/opentelemetry-java/pull/5918)) + +#### Testing + +* Add log support to junit extensions + ([#5966](https://github.com/open-telemetry/opentelemetry-java/pull/5966)) + +#### SDK Extensions + +* Add file configuration to autoconfigure + ([#5831](https://github.com/open-telemetry/opentelemetry-java/pull/5831)) +* Update to file configuration to use opentelemetry-configuration v0.1.0 + ([#5899](https://github.com/open-telemetry/opentelemetry-java/pull/5899)) +* Add env var substitution support to file configuration + ([#5914](https://github.com/open-telemetry/opentelemetry-java/pull/5914)) +* Stop setting Resource schemaUrl in autoconfigure + ([#5911](https://github.com/open-telemetry/opentelemetry-java/pull/5911)) +* Add AutoConfigureListener to provide components with autoconfigured SDK + ([#5931](https://github.com/open-telemetry/opentelemetry-java/pull/5931)) + +### OpenCensus Shim + +* Clean up OpenCensus shim + ([#5858](https://github.com/open-telemetry/opentelemetry-java/pull/5858)) + +### OpenTracing Shim + +* Fix OpenTracing header name issue + ([#5840](https://github.com/open-telemetry/opentelemetry-java/pull/5840)) + +## Version 1.31.0 (2023-10-06) + +### API + +#### Incubator + +* Refactor advice API to simplify usage + ([#5848](https://github.com/open-telemetry/opentelemetry-java/pull/5848)) + +### SDK + +* BatchLogRecordProcessor and BatchSpanProcessor unify `queueSize` metric + description and attribute name for `processorType` + ([#5836](https://github.com/open-telemetry/opentelemetry-java/pull/5836)) + +#### Metrics + +* Allow instrument names to contain a forward slash + ([#5824](https://github.com/open-telemetry/opentelemetry-java/pull/5824)) +* Memory Mode support: Adding memory mode, and implementing it for Asynchronous Instruments + ([#5709](https://github.com/open-telemetry/opentelemetry-java/pull/5709), + [#5855](https://github.com/open-telemetry/opentelemetry-java/pull/5855)) +* Stabilize MetricProducer, allow custom MetricReaders + ([#5835](https://github.com/open-telemetry/opentelemetry-java/pull/5835)) +* Drop NaN measurements to metric instruments + ([#5859](https://github.com/open-telemetry/opentelemetry-java/pull/5859)) +* Fix flaky MetricExporterConfigurationTest + ([#5877](https://github.com/open-telemetry/opentelemetry-java/pull/5877)) + +#### Logs + +* Add addAllAttributes() to ReadWriteLogRecord. + ([#5825](https://github.com/open-telemetry/opentelemetry-java/pull/5825)) + +#### Exporters + +* Prometheus exporter: handle colliding metric attribute keys + ([#5717](https://github.com/open-telemetry/opentelemetry-java/pull/5717)) + +#### SDK Extensions + +* File configuration ConfigurationReader handles null values as empty + ([#5829](https://github.com/open-telemetry/opentelemetry-java/pull/5829)) + +#### Semantic conventions + +* BREAKING: Stop publishing `io.opentelemetry:opentelemetry-semconv`. Please use + `io.opentelemetry.semconv:opentelemetry-semconv:1.21.0-alpha` instead, which is published + from [open-telemetry/semantic-conventions-java](https://github.com/open-telemetry/semantic-conventions-java). + The new repository is published in lockstep + with [open-telemetry/semantic-conventions](https://github.com/open-telemetry/semantic-conventions). + ([#5807](https://github.com/open-telemetry/opentelemetry-java/pull/5807)) + +### Project Tooling + +* Add Benchmark workflows + ([#5842](https://github.com/open-telemetry/opentelemetry-java/pull/5842), + [#5874](https://github.com/open-telemetry/opentelemetry-java/pull/5874)) +* Add clearer docs around coroutine support with an example + ([#5799](https://github.com/open-telemetry/opentelemetry-java/pull/5799)) + +## Version 1.30.1 (2023-09-11) + +* Fix autoconfigure bug creating multiple `PrometheusHttpServer` instances with same port + ([#5811](https://github.com/open-telemetry/opentelemetry-java/pull/5811)) + +## Version 1.30.0 (2023-09-08) + +### API + +#### Incubator + +* Add experimental synchronous gauge + ([#5506](https://github.com/open-telemetry/opentelemetry-java/pull/5506)) + +### SDK + +#### Metrics + +* Add attributes advice API + ([#5677](https://github.com/open-telemetry/opentelemetry-java/pull/5677), + [#5722](https://github.com/open-telemetry/opentelemetry-java/pull/5722)) +* Add AttributesProcessor toString, add attribute filter helper + ([#5765](https://github.com/open-telemetry/opentelemetry-java/pull/5765)) +* Increase metric name maximum length from 63 to 255 characters + ([#5697](https://github.com/open-telemetry/opentelemetry-java/pull/5697)) + +#### Exporter + +* Prometheus exporter: remove non-ucum units from conversion + ([#5719](https://github.com/open-telemetry/opentelemetry-java/pull/5719)) +* Prometheus exporter: add units to metric names in TYPE and HELP comments + ([#5718](https://github.com/open-telemetry/opentelemetry-java/pull/5718)) + +#### SDK Extensions + +* Add support for file based configuration to incubator + ([#5687](https://github.com/open-telemetry/opentelemetry-java/pull/5687), + [#5751](https://github.com/open-telemetry/opentelemetry-java/pull/5751), + [#5758](https://github.com/open-telemetry/opentelemetry-java/pull/5758), + [#5757](https://github.com/open-telemetry/opentelemetry-java/pull/5757), + [#5755](https://github.com/open-telemetry/opentelemetry-java/pull/5755), + [#5763](https://github.com/open-telemetry/opentelemetry-java/pull/5763), + [#5766](https://github.com/open-telemetry/opentelemetry-java/pull/5766), + [#5773](https://github.com/open-telemetry/opentelemetry-java/pull/5773), + [#5771](https://github.com/open-telemetry/opentelemetry-java/pull/5771), + [#5779](https://github.com/open-telemetry/opentelemetry-java/pull/5779)) +* Autoconfigure ConfigProperties#getMap filters entries with blank values instead of throwing + ([#5784](https://github.com/open-telemetry/opentelemetry-java/pull/5784)) + +### Semantic conventions + +* DEPRECATION: `io.opentelemetry:opentelemetry-semconv` is deprecated for removal. Please use + `io.opentelemetry.semconv:opentelemetry-semconv:1.21.0-alpha` instead, which is published + from [open-telemetry/semantic-conventions-java](https://github.com/open-telemetry/semantic-conventions-java). + The new repository is published in lockstep + with [open-telemetry/semantic-conventions](https://github.com/open-telemetry/semantic-conventions). + ([#5786](https://github.com/open-telemetry/opentelemetry-java/pull/5786)) + +### Project Tooling + +* Update Gradle Wrapper from 8.2.1 to 8.3 + ([#5728](https://github.com/open-telemetry/opentelemetry-java/pull/5728)) +* Remove dependabot and `update-gradle-wrapper` task in favor of renovate + ([#5746](https://github.com/open-telemetry/opentelemetry-java/pull/5746)) + +## Version 1.29.0 (2023-08-11) + +### API + +* Update Span javadoc to allow null/empty attr values + ([#5616](https://github.com/open-telemetry/opentelemetry-java/pull/5616)) + +### SDK + +* Add Sdk{Signal}ProviderBuilder#addResource(Resource) method to merge Resource + with current + ([#5619](https://github.com/open-telemetry/opentelemetry-java/pull/5619)) + +#### Metrics + +* Add LongHistogramAdviceConfigurer to improve api surface types + ([#5689](https://github.com/open-telemetry/opentelemetry-java/pull/5689)) +* Instruments with names which are case-insensitive equal contribute to same + metric, advice is not part of instrument identity. + ([#5701](https://github.com/open-telemetry/opentelemetry-java/pull/5701)) + +#### Exporter + +* Add OtlpHttp{Signal}Exporter#toBuilder() methods + ([#5652](https://github.com/open-telemetry/opentelemetry-java/pull/5652)) +* Add OtlpGrpc{Signal}Exporter#toBuilder() methods + ([#5680](https://github.com/open-telemetry/opentelemetry-java/pull/5680)) +* Add #toString to OTLP exporters + ([#5686](https://github.com/open-telemetry/opentelemetry-java/pull/5686)) +* Break out GrpcSender, GrpcSenderProvider + ([#5617](https://github.com/open-telemetry/opentelemetry-java/pull/5617)) + +#### SDK Extensions + +* BREAKING: Delete zpages + ([#5611](https://github.com/open-telemetry/opentelemetry-java/pull/5611)) +* Initialize file configuration with generated model classes and parse method + ([#5399](https://github.com/open-telemetry/opentelemetry-java/pull/5399)) +* Refactor SpiUtil to improve mocking + ([#5679](https://github.com/open-telemetry/opentelemetry-java/pull/5679)) +* Switch from snakeyaml to snakeyaml engine + ([#5691](https://github.com/open-telemetry/opentelemetry-java/pull/5691)) +* Add experimental autoconfigure support for customizing cardinality limit + ([#5659](https://github.com/open-telemetry/opentelemetry-java/pull/5659)) +* Reorganize autoconfigure docs by signal + ([#5665](https://github.com/open-telemetry/opentelemetry-java/pull/5665)) + +#### Testing + +* Add hasResourceSatisfying to LogRecordDataAssert + ([#5690](https://github.com/open-telemetry/opentelemetry-java/pull/5690)) + +### OpenCensus Shim + +* Change OpenCensus shim default sampling to defer to OpenTelemetry + ([#5604](https://github.com/open-telemetry/opentelemetry-java/pull/5604)) + +### Project Tooling + +* Update Gradle Wrapper from 8.2 to 8.2.1 + ([#5618](https://github.com/open-telemetry/opentelemetry-java/pull/5618)) +* Fix gradle java version requirement warning + ([#5624](https://github.com/open-telemetry/opentelemetry-java/pull/5624)) +* Refer to Adoptium/Temurin instead of AdoptOpenJDK + ([#5636](https://github.com/open-telemetry/opentelemetry-java/pull/5636)) +* Use OtelVersionClassPlugin instead of reading version from resource + ([#5622](https://github.com/open-telemetry/opentelemetry-java/pull/5622)) +* Enforce build-graal success in required status check + ([#5696](https://github.com/open-telemetry/opentelemetry-java/pull/5696)) + +## Version 1.28.0 (2023-07-07) + +[opentelemetry-sdk-extension-autoconfigure](./sdk-extensions/autoconfigure) is now stable! See "SDK +Extension" notes below for changes made prior to stabilization. + +### SDK + +#### Metrics + +* Make Advice proper immutable class + ([#5532](https://github.com/open-telemetry/opentelemetry-java/pull/5532)) +* Show attributes when async instruments record duplicate measurements + ([#5542](https://github.com/open-telemetry/opentelemetry-java/pull/5542)) +* After cardinality limit exceeded record measurements to overflow series + ([#5560](https://github.com/open-telemetry/opentelemetry-java/pull/5560)) + +#### Exporter + +* Add HttpSender abstraction with OkHttp implementation + ([#5505](https://github.com/open-telemetry/opentelemetry-java/pull/5505)) +* Add HttpSenderProvider SPI + ([#5533](https://github.com/open-telemetry/opentelemetry-java/pull/5533)) +* Add JDK 11+ HttpClient HttpSender implementation + ([#5557](https://github.com/open-telemetry/opentelemetry-java/pull/5557)) +* Remove unnecessary :exporter:otlp:common dependencies + ([#5535](https://github.com/open-telemetry/opentelemetry-java/pull/5535)) +* Fix OTLP exporter artifact name in an error message + ([#5541](https://github.com/open-telemetry/opentelemetry-java/pull/5541)) +* Stabilize RetryPolicy API for OTLP exporters + ([#5524](https://github.com/open-telemetry/opentelemetry-java/pull/5524)) +* DEPRECATION: `opentelemetry-exporter-jaeger` and `opentelemetry-exporter-jaeger-thrift` are now + deprecated with the last release planned for 1.34.0 (January 2024) + ([#5190](https://github.com/open-telemetry/opentelemetry-java/pull/5190)) + +#### SDK Extensions + +* Mark opentelemetry-sdk-extension-autoconfigure as stable + ([#5577](https://github.com/open-telemetry/opentelemetry-java/pull/5577)) +* Refactor autoconfigure registerShutdownHook(boolean) to disableShutdownHook() + ([#5565](https://github.com/open-telemetry/opentelemetry-java/pull/5565)) +* AutoConfiguredOpenTelemetrySdkBuilder does not set GlobalOpenTelemetry by default + ([#5564](https://github.com/open-telemetry/opentelemetry-java/pull/5564)) +* Add public API to autoconfigure to access environment resource + ([#5554](https://github.com/open-telemetry/opentelemetry-java/pull/5554)) +* Move autoconfigure getConfig to internal, remove getResource + ([#5467](https://github.com/open-telemetry/opentelemetry-java/pull/5467)) +* Add autoconfigure support for low memory metric temporality setting + ([#5558](https://github.com/open-telemetry/opentelemetry-java/pull/5558)) +* DEPRECATION: zpages extension from opentelemetry-sdk-extension-incubator + is now deprecated + ([#5578](https://github.com/open-telemetry/opentelemetry-java/pull/5578)) + +### Project tooling + +* Publish build scans to ge.opentelemetry.io + ([#5510](https://github.com/open-telemetry/opentelemetry-java/pull/5510)) +* Update Gradle Wrapper from 8.0.1 to 8.1.1 + ([#5531](https://github.com/open-telemetry/opentelemetry-java/pull/5531)) +* Add action to auto update gradle wrapper + ([#5511](https://github.com/open-telemetry/opentelemetry-java/pull/5511)) + +## Version 1.27.0 (2023-06-09) + +The log bridge API / SDK are now stable! Some important notes: + +* The contents of `opentelemetry-api-logs` have been merged into `opentelemetry-api`. +* The contents of `opentelemetry-exporter-otlp-logs` have been merged + into `opentelemetry-exporter-otlp`. +* The contents of `opentelemetry-sdk-logs-testing` have been merged into `opentelemetry-sdk-testing`. +* The `opentelemetry-sdk-logs` artifact has been marked stable. +* `opentelemetry-sdk-extension-autoconfigure` has changed the default value + of `otel.logs.exporter` from `none` to `otlp`. + +NOTE: reminder that +the [Logs Bridge API](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.21.0/specification/logs/bridge-api.md) +is _not_ meant for end users. Log appenders use the API to bridge logs from existing log +frameworks (e.g. JUL, Log4j, SLf4J, Logback) into OpenTelemetry. Users configure the Log SDK to +dictate how logs are processed and exported. +See [opentelemetry.io](https://opentelemetry.io/docs/languages/java/api/#loggerprovider) for +documentation on usage. + +### API + +* Promote log API to stable + ([#5341](https://github.com/open-telemetry/opentelemetry-java/pull/5341)) +* fix doc for OpenTelemetry class + ([#5454](https://github.com/open-telemetry/opentelemetry-java/pull/5454)) + +### SDK + +* Ensure correct compiled output and sources are included in multi version jar + ([#5487](https://github.com/open-telemetry/opentelemetry-java/pull/5487)) + +#### Logs + +* Fix broken link + ([#5451](https://github.com/open-telemetry/opentelemetry-java/pull/5451)) +* Add meaningful `.toString` to `NoopLogRecordProcessor` and `DefaultOpenTelemetry` + ([#5493](https://github.com/open-telemetry/opentelemetry-java/pull/5493)) +* Promote log SDK to stable + ([#5341](https://github.com/open-telemetry/opentelemetry-java/pull/5341)) + +#### Metrics + +* Reset exponential aggregator scale after collection + ([#5496](https://github.com/open-telemetry/opentelemetry-java/pull/5496)) +* Experimental metric reader and view cardinality limits + ([#5494](https://github.com/open-telemetry/opentelemetry-java/pull/5494)) + +#### Exporter + +* Merge otlp logs + ([#5432](https://github.com/open-telemetry/opentelemetry-java/pull/5432)) +* Append unit to prometheus metric names + ([#5400](https://github.com/open-telemetry/opentelemetry-java/pull/5400)) + +#### Testing + +* Merge sdk logs testing + ([#5431](https://github.com/open-telemetry/opentelemetry-java/pull/5431)) +* Add a `hasBucketBoundaries()` variant that allows specifying precision + ([#5457](https://github.com/open-telemetry/opentelemetry-java/pull/5457)) + +### SDK Extensions + +* Enable otlp logs by default in autoconfigure + ([#5433](https://github.com/open-telemetry/opentelemetry-java/pull/5433)) + +### Semantic Conventions + +* Update to semconv 1.20.0 + ([#5497](https://github.com/open-telemetry/opentelemetry-java/pull/5497)) + +## Version 1.26.0 (2023-05-05) + +This release represents the release candidate ("RC") release for the Logs Bridge API / SDK. In the +next release (1.27.0), `opentelemetry-api-logs` will be merged into `opentelemetry-api`, +`opentelemetry-sdk-logs` will be marked as stable, `opentelemetry-exporter-otlp-logs` will be +merged into `opentelemetry-exporter-otlp`, `opentelemetry-sdk-logs-testing` will be merged +into `opentelemetry-sdk-testing`, `opentelemetry-sdk-extension-autoconfigure` will enable `otlp` +log exporter by default (i.e. `otel.logs.exporter=otlp`). For more details, see tracking +issue [#5340](https://github.com/open-telemetry/opentelemetry-java/issues/5340). NOTE: reminder that +the [Logs Bridge API](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.21.0/specification/logs/bridge-api.md) +is _not_ meant for end users. Log appenders use the API to bridge logs from existing log +frameworks (e.g. JUL, Log4j, SLf4J, Logback) into OpenTelemetry. Users configure the Log SDK to +dictate how logs are processed and exported. + +`opentelemetry-opentracing-shim` is now stable! + +### SDK + +* Create OtelVersion class at build time which is used to resolve artifact version in `Resource`. + ([#5365](https://github.com/open-telemetry/opentelemetry-java/pull/5365)) + +#### Metrics + +* Add prototype histogram advice API (i.e. Hints). + ([#5217](https://github.com/open-telemetry/opentelemetry-java/pull/5217)) + +#### Logs + +* Add LogRecord observed timestamp field. + ([#5370](https://github.com/open-telemetry/opentelemetry-java/pull/5370)) +* Remove log record timestamp default. + ([#5374](https://github.com/open-telemetry/opentelemetry-java/pull/5374)) +* Align BatchLogRecordProcessor defaults with specification. + ([#5364](https://github.com/open-telemetry/opentelemetry-java/pull/5364)) +* Rename setEpoch to setTimestamp. + ([#5368](https://github.com/open-telemetry/opentelemetry-java/pull/5368)) +* Log SDK cleanup. Move `InMemoryLogRecordExporter` to `opentelemetry-sdk-logs-testing`. + Rename `InMemoryLogRecordExporter#getFinishedLogItems` to `getFinishedLogRecordItems`. + Move `SdkEventEmitterProvder` to internal package. + ([#5368](https://github.com/open-telemetry/opentelemetry-java/pull/5368)) + +### Exporters + +* Add scaffolding for low level exporter TLS API. + ([#5362](https://github.com/open-telemetry/opentelemetry-java/pull/5362)) +* Add new low level TLS APIs on OTLP and Jaeger gRPC exporter builders. + ([#5280](https://github.com/open-telemetry/opentelemetry-java/pull/5280), + [#5422](https://github.com/open-telemetry/opentelemetry-java/pull/5422)) +* OTLP LogRecord exporters serialize observed timestamp. + ([#5382](https://github.com/open-telemetry/opentelemetry-java/pull/5382)) +* Update prometheus test to reflect new collector behavior. + ([#5417](https://github.com/open-telemetry/opentelemetry-java/pull/5417)) +* Prometheus exporter checks metrics name to prevent add duplicated _total suffix. + ([#5308](https://github.com/open-telemetry/opentelemetry-java/pull/5308)) +* Add additional OTLP test for authenticator. + ([#5391](https://github.com/open-telemetry/opentelemetry-java/pull/5391)) + +### OpenTracing Shim + +* Mark opentracing-shim as stable. + ([#5371](https://github.com/open-telemetry/opentelemetry-java/pull/5371)) + +### SDK Extensions + +* Fixes jaeger remote sampler service strategies bug resolving service name. + ([#5418](https://github.com/open-telemetry/opentelemetry-java/pull/5418)) +* Fix flaky JaegerRemoteSamplerGrpcNettyTest. + ([#5385](https://github.com/open-telemetry/opentelemetry-java/pull/5385)) +* Add new log level TLS APIs on JaegerRemoteSamplerBuilder. + ([#5422](https://github.com/open-telemetry/opentelemetry-java/pull/5422)) +* Fix a parameter name typo in autoconfigure-spi module. + ([#5409](https://github.com/open-telemetry/opentelemetry-java/pull/5409)) + +### Semantic Conventinos + +* Add missing links to deprecated constants in SemanticAttributes. + ([#5406](https://github.com/open-telemetry/opentelemetry-java/pull/5406)) + +### Project Tooling + +* Update stale workflow. + ([#5381](https://github.com/open-telemetry/opentelemetry-java/pull/5381)) +* Skip OWASP dependencyCheck on test modules. + ([#5383](https://github.com/open-telemetry/opentelemetry-java/pull/5383)) +* Skip OWASP dependencyCheck on jmh tasks. + ([#5384](https://github.com/open-telemetry/opentelemetry-java/pull/5384)) +* Drop create website pull request release step + ([#5361](https://github.com/open-telemetry/opentelemetry-java/pull/5361)) + +## Version 1.25.0 (2023-04-07) + +### API + +* Cache ImmutableKeyValuePairs#hashCode + ([#5307](https://github.com/open-telemetry/opentelemetry-java/pull/5307)) + +#### Propagators + +* Remove streams from B3Propagator + ([#5326](https://github.com/open-telemetry/opentelemetry-java/pull/5326)) + +### SDK + +#### Metrics + +* Stop validating instrument unit + ([#5279](https://github.com/open-telemetry/opentelemetry-java/pull/5279)) +* Make the Executor for PrometheusHttpServer configurable + ([#5296](https://github.com/open-telemetry/opentelemetry-java/pull/5296)) + +#### Exporter + +* Fix marshaler self suppression error + ([#5318](https://github.com/open-telemetry/opentelemetry-java/pull/5318)) +* Add sdk dependency to Logging OTLP exporter + ([#5291](https://github.com/open-telemetry/opentelemetry-java/pull/5291)) + +#### Testing + +* Fixing up javadoc to reflect how to create a junit4 OpenTelemetryRule + ([#5299](https://github.com/open-telemetry/opentelemetry-java/pull/5299)) + +### SDK Extensions + +* BREAKING: Autoconfigure drops support + for `otel.exporter.otlp.metrics.default.histogram.aggregation=EXPONENTIAL_BUCKET_HISTOGRAM`. + Use `BASE2_EXPONENTIAL_BUCKET_HISTOGRAM` instead. + ([#5290](https://github.com/open-telemetry/opentelemetry-java/pull/5290)) +* JaegerRemoteSampler use upstream grpc implementation if ManagedChannel is set + ([#5287](https://github.com/open-telemetry/opentelemetry-java/pull/5287)) + +### OpenTracing Shim + +* Adds version to otel tracer instrumentation scope + ([#5336](https://github.com/open-telemetry/opentelemetry-java/pull/5336)) + +### OpenCensus Shim + +* Adds version to otel tracer instrumentation scope + ([#5336](https://github.com/open-telemetry/opentelemetry-java/pull/5336)) + +### Semantic Conventions + +* Update semconv to 1.19.0 and related build tool changes + ([#5311](https://github.com/open-telemetry/opentelemetry-java/pull/5311)) + +## Version 1.24.0 (2023-03-10) + +### SDK + +#### Metrics + +* Optimize DefaultSynchronousMetricStorage iteration to reduce allocations + ([#5183](https://github.com/open-telemetry/opentelemetry-java/pull/5183)) +* Avoid exemplar allocations if there are no measurements + ([#5182](https://github.com/open-telemetry/opentelemetry-java/pull/5182)) +* Remove boxed primitives from aggregations to reduce allocations + ([#5184](https://github.com/open-telemetry/opentelemetry-java/pull/5184)) +* Stop ignoring long measurements in HistogramExemplarReservoir + ([#5216](https://github.com/open-telemetry/opentelemetry-java/pull/5216)) +* Remove validations for noop instrument names and units + ([#5146](https://github.com/open-telemetry/opentelemetry-java/pull/5146)) +* Allow views to select on instrument unit + ([#5255](https://github.com/open-telemetry/opentelemetry-java/pull/5255)) + +#### Exporter + +* Add (internal) TlsConfigHelper for additional TLS configurability + ([#5246](https://github.com/open-telemetry/opentelemetry-java/pull/5246)) + +#### SDK Extensions + +* Introduce mTLS support for JaegerRemoteSamplerBuilder (#5209) + ([#5248](https://github.com/open-telemetry/opentelemetry-java/pull/5248)) + +### OpenTracing Shim + +* OpenTracing Shim: Update Tracer.close() + ([#5151](https://github.com/open-telemetry/opentelemetry-java/pull/5151)) + +* Update version to 1.24.0 + ([#5198](https://github.com/open-telemetry/opentelemetry-java/pull/5198)) +* Post release 1.23.0 + ([#5202](https://github.com/open-telemetry/opentelemetry-java/pull/5202)) + +### OpenCensus Shim + +* Addresses opencensus-shim trace issues under otel javaagent + ([#4900](https://github.com/open-telemetry/opentelemetry-java/pull/4900)) + +### Project tooling + +* Cleanup readmes + ([#5263](https://github.com/open-telemetry/opentelemetry-java/pull/5263)) +* Upgrade to gradle 8.0.1 + ([#5256](https://github.com/open-telemetry/opentelemetry-java/pull/5256)) +* Fixed example resource provider classname. + ([#5235](https://github.com/open-telemetry/opentelemetry-java/pull/5235)) +* Fix case of bug label in open issue workflow + ([#5268](https://github.com/open-telemetry/opentelemetry-java/pull/5268)) + +### Semantic Conventions + +* Update semconv to 1.19.0 + ([#5311](https://github.com/open-telemetry/opentelemetry-java/pull/5311)) + +## Version 1.23.1 (2023-02-15) + +* Fix bug that broke `AutoConfiguredOpenTelemetrySdk`'s shutdown hook. + ([#5221](https://github.com/open-telemetry/opentelemetry-java/pull/5221)) + +## Version 1.23.0 (2023-02-10) + +This release is a notable release for metrics: + +* The base2 exponential histogram aggregation has been marked as stable. To use, configure + your `MetricExporter` with a default aggregation + of `Aggregation.base2ExponentialBucketHistogram()` for histogram instruments. If using OTLP + exporter with autoconfigure, + set `OTEL_EXPORTER_OTLP_METRICS_DEFAULT_HISTOGRAM_AGGREGATION=BASE2_EXPONENTIAL_BUCKET_HISTOGRAM`. + If using configuring OTLP programatically, + use `Otlp*MetricExporterBuilder#setDefaultAggregationSelector(DefaultAggregationSelector)`. +* The metrics SDK undergone significant internal refactoring which results in reduced complexity and + significantly reduced memory allocation during metric collection / export. + +### API + +#### Logs + +* WARNING: Split out Event API from Log API. Event API is now published in `opentelemetry-api-events`. + API / SDK usage has also changed - see PR for details. + ([#5049](https://github.com/open-telemetry/opentelemetry-java/pull/5049)) + +### SDK + +* Add shutdown / close to `OpenTelemetrySdk` + ([#5100](https://github.com/open-telemetry/opentelemetry-java/pull/5100)) + +#### Metrics + +* Base2 exponential histogram aggregations are now stable. Add `base2ExponentialBucketHistogram()` + to `Aggregation`. + ([#5143](https://github.com/open-telemetry/opentelemetry-java/pull/5143)) +* Promote exponential histogram data interfaces to stable package + ([#5120](https://github.com/open-telemetry/opentelemetry-java/pull/5120)) +* Add Base2 prefix to internal exponential histogram classes + ([#5179](https://github.com/open-telemetry/opentelemetry-java/pull/5179)) +* Add MaxScale config parameter to `Base2ExponentialBucketHistogram` + ([#5044](https://github.com/open-telemetry/opentelemetry-java/pull/5044)) +* Add close method to `MetricReader` + ([#5109](https://github.com/open-telemetry/opentelemetry-java/pull/5109)) +* Reuse `AggregatorHandle` with cumulative temporality to reduce allocations + ([#5142](https://github.com/open-telemetry/opentelemetry-java/pull/5142)) +* Delete notion of accumulation to reduce allocations + ([#5154](https://github.com/open-telemetry/opentelemetry-java/pull/5154)) +* Delete bound instruments + ([#5157](https://github.com/open-telemetry/opentelemetry-java/pull/5157)) +* Reuse aggregation handles for delta temporality to reduce allocations + ([#5176](https://github.com/open-telemetry/opentelemetry-java/pull/5176)) + +#### Exporter + +* Add proper shutdown implementations for all exporters + ([#5113](https://github.com/open-telemetry/opentelemetry-java/pull/5113)) + +#### SDK Extensions + +* WARNING: Remove deprecated autoconfigure exemplar filter names. Previous names `none`, `all` + , `with_sampled_trace` have been removed. Use `always_off`, `always_on`, `trace_based` instead. + ([#5098](https://github.com/open-telemetry/opentelemetry-java/pull/5098)) +* Add autoconfigure support for "none" option for propagator value + ([#5121](https://github.com/open-telemetry/opentelemetry-java/pull/5121)) +* Add autoconfigure support for `parentbased_jaeger_remote` sampler + ([#5123](https://github.com/open-telemetry/opentelemetry-java/pull/5123)) +* Autoconfigure closes up autoconfigured resources in case of exception + ([#5117](https://github.com/open-telemetry/opentelemetry-java/pull/5117)) +* View file based config has switched from snakeyaml to snakeyaml-engine for YAML parsing. + ([#5138](https://github.com/open-telemetry/opentelemetry-java/pull/5138)) +* Fix autoconfigure resource providers property docs + ([#5135](https://github.com/open-telemetry/opentelemetry-java/pull/5135)) + +#### Testing + +* WARNING: Merge `opentelemetry-sdk-metrics-testing` into `opentelemetry-sdk-testing`. Stop + publishing `opentelemetry-sdk-metrics-testing`. + ([#5144](https://github.com/open-telemetry/opentelemetry-java/pull/5144)) +* Sort spans by start time (parents before children as tiebreaker) to avoid common causes for flaky + tests + ([#5026](https://github.com/open-telemetry/opentelemetry-java/pull/5026)) +* Add resource assertion methods to `SpanDataAssert` and `MetricAssert` + ([#5160](https://github.com/open-telemetry/opentelemetry-java/pull/5160)) + + +### Semantic Conventions + +* Update semconv to 1.18.0 + ([#5188](https://github.com/open-telemetry/opentelemetry-java/pull/5188)) + ([#5134](https://github.com/open-telemetry/opentelemetry-java/pull/5134)) + +### OpenTracing Shim + +* Refactor to remove internal objects `BaseShimObject` and `TelemetryInfo` + ([#5087](https://github.com/open-telemetry/opentelemetry-java/pull/5087)) +* WARNING: Minimize public surface area of OpenTracingShim. Remove `createTracerShim()` + , `createTracerShim(Tracer)`, `createTracerShim(Tracer, OpenTracingPropagators)`. + Add `createTracerShim(TracerProvder,TextMapPropagator,TextMapPropagator)`. + ([#5110](https://github.com/open-telemetry/opentelemetry-java/pull/5110)) + +### Project tooling + +* Add OWASP dependency check + ([#5177](https://github.com/open-telemetry/opentelemetry-java/pull/5177)) + +## Version 1.22.0 (2023-01-06) + +### API + +* WARNING: GlobalOpenTelemetry trigger of autoconfiguration is now opt-in. + Previously, `GlobalOpenTelemetry.get` triggered autoconfiguration + if `opentelemetry-sdk-extension-autoconfigure` was detected on the classpath. That behavior is now + opt-in by setting environment variable `OTEL_JAVA_GLOBAL_AUTOCONFIGURE_ENABLED=true`. + ([#5010](https://github.com/open-telemetry/opentelemetry-java/pull/5010)) +* Update LoggerBuilder, MeterBuilder, TracerBuilder javadoc + ([#5050](https://github.com/open-telemetry/opentelemetry-java/pull/5050)) + +#### Context + +* Make closing scope idempotent and non-operational when corresponding context is not current. + [(#5061)](https://github.com/open-telemetry/opentelemetry-java/pull/5061) + +### SDK + +* Standardize internal usage of `ConfigUtil` for reading environment variables and system properties + ([#5048](https://github.com/open-telemetry/opentelemetry-java/pull/5048)) + +#### Metrics + +* Lazily initialize exponential histogram buckets + ([#5023](https://github.com/open-telemetry/opentelemetry-java/pull/5023)) +* Delete MapCounter alternative exponential histogram implementation + ([#5047](https://github.com/open-telemetry/opentelemetry-java/pull/5047)) +* Add toString to SdkMeter, SdkObservableInstrument, AbstractInstrumentBuilder + ([#5072](https://github.com/open-telemetry/opentelemetry-java/pull/5072)) + +#### Exporter + +* `OtlpGrpcSpanExporter`, `OtlpHttpSpanExporter`, `OtlpGrpcLogRecordExporter`, + `OtlpHttpLogRecordExporter`, `ZipkinSpanExporter`, and `JaegerGrpcSpanExporter` are now + instrumented with `GlobalOpenTelemetry` by default. Instrumentation initializes lazily to prevent + ordering issue of accessing `GlobalOpenTelemetry.get` before `GlobalOpenTelemetry.set` is called. + ([#4993](https://github.com/open-telemetry/opentelemetry-java/pull/4993)) +* Add `ConfigurableSpanExporterProvider` implementation for `JaegerGrpcSpanExporter` + ([#5002](https://github.com/open-telemetry/opentelemetry-java/pull/5002)) +* Add `ConfigurableSpanExporterProvider`, `ConfigurableMetricExporterProvider`, + `ConfigurableLogRecordExporterProvider` for `OtlpGrpc{Signal}Exporter`s + and `OtlpHttp{SignalExporter`s + ([#5003](https://github.com/open-telemetry/opentelemetry-java/pull/5003)) +* Replace OTLP User-Agent spaces with dashes + ([#5080](https://github.com/open-telemetry/opentelemetry-java/pull/5080)) +* Add `AutoConfigurationCustomizerProvider` implementation for `PrometheusHttpServer` + ([#5053](https://github.com/open-telemetry/opentelemetry-java/pull/5053)) +* Add resource `target_info` and scope `target_info` metrics to `PrometheusHttpServer` in compliance + with spec + ([#5039](https://github.com/open-telemetry/opentelemetry-java/pull/5039)) +* Drop delta metrics in `PrometheusHttpServer` + ([#5062](https://github.com/open-telemetry/opentelemetry-java/pull/5062)) +* PrometheusHttpServer drops metrics with same name and different type + ([#5078](https://github.com/open-telemetry/opentelemetry-java/pull/5078)) + +#### SDK Extensions + +* DEPRECATION: Align autoconfigure exemplar filter names with spec. Previous names `none`, `all`, + `with_sampled_trace` are deprecated. Use `always_off`, `always_on`, `trace_based` instead. + ([#5063](https://github.com/open-telemetry/opentelemetry-java/pull/5063)) + +### OpenTracing Shim + +* Add createTracerShim function + ([#4988](https://github.com/open-telemetry/opentelemetry-java/pull/4988)) + +## Version 1.21.0 (2022-12-09) + +### API + +### API Extensions + +* WARNING: `opentelemetry-extension-aws` has been removed following its relocation + to [opentelemetry-java-contrib/aws-xray-propagator](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/aws-xray-propagator), + which is published under + coordinates `io.opentelemetry.contrib:opentelemetry-aws-xray-propagator:{version}`. + We will push security patches to `1.20.x` as needed. The latest `opentelemetry-bom` will point + to the latest published version, currently `1.20.1`. + ([#4945](https://github.com/open-telemetry/opentelemetry-java/pull/4945)) +* Add toString implementation to various propagator components + ([#4996](https://github.com/open-telemetry/opentelemetry-java/pull/4996)) + +### SDK + +#### Logs + +* Add toString implementation to various log SDK components + ([#4979](https://github.com/open-telemetry/opentelemetry-java/pull/4979)) + +#### Metrics + +* Add histogram collection benchmark + ([#4912](https://github.com/open-telemetry/opentelemetry-java/pull/4912)) +* Add ExponentialHistogramIndexerBenchmark + ([#4989](https://github.com/open-telemetry/opentelemetry-java/pull/4989)) +* Stop extra copy of exponential histogram buckets + ([#5020](https://github.com/open-telemetry/opentelemetry-java/pull/5020)) + +#### Exporter + +* Zipkin exporter serializes EventData attributes as JSON + ([#4934](https://github.com/open-telemetry/opentelemetry-java/pull/4934)) +* Add support for EC mTLS keys (applies to `OtlpHttp{Signal}Exporter`, `OtlpGrpc{Signal}Exporter`, + `JaegerGrpcSpanExporter`, `JaegerRemoteSampler`) + ([#4920](https://github.com/open-telemetry/opentelemetry-java/pull/4920)) +* Add `Configurable{Signal}ExporterProvider` implementations for `Logging{Signal}Exporter`s + ([#4950](https://github.com/open-telemetry/opentelemetry-java/pull/4950)) +* Add `ConfigurableSpanExporterProvider` implementation for `ZipkinSpanExporter` + ([#4991](https://github.com/open-telemetry/opentelemetry-java/pull/4991)) +* Add `Configurable{Signal}ExporterProvider` implementations for `OtlpJsonLogging{Signal}Exporter`s + ([#4992](https://github.com/open-telemetry/opentelemetry-java/pull/4992)) +* `ZipkinSpanExporter` populates remoteEndpoint + ([#4933](https://github.com/open-telemetry/opentelemetry-java/pull/4933)) + +#### SDK Extensions + +* BREAKING: Remove support for otel.experimental.sdk.enabled from autoconfigure + ([#4973](https://github.com/open-telemetry/opentelemetry-java/pull/4973)) +* De-singleton ZPageServer implementation + ([#4935](https://github.com/open-telemetry/opentelemetry-java/pull/4935)) +* Add auto-configure support for logging-otlp exporters + ([#4879](https://github.com/open-telemetry/opentelemetry-java/pull/4879)) +* Move DefaultConfigProperties to internal package in `opentelemetry-sdk-extension-autoconfigure-spi` + ([#5001](https://github.com/open-telemetry/opentelemetry-java/pull/5001)) + +#### Testing + +* Make APIs for asserting attributes consistent + ([#4882](https://github.com/open-telemetry/opentelemetry-java/pull/4882)) +* Attribute assertions error messages always contain the attr key + ([#5027](https://github.com/open-telemetry/opentelemetry-java/pull/5027)) + +### Semantic Conventions + +* Update semantic and resource attributes for spec v1.16.0 + ([#4938](https://github.com/open-telemetry/opentelemetry-java/pull/4938), + [#5033](https://github.com/open-telemetry/opentelemetry-java/pull/5033)) + +### OpenTracing Shim + +* Handle unsupported types when setting Attributes + ([#4939](https://github.com/open-telemetry/opentelemetry-java/pull/4939)) +* Properly set the status based on the error tag + ([#4962](https://github.com/open-telemetry/opentelemetry-java/pull/4962)) +* Handle `io.opentracing.noop.NoopSpan` correctly + ([#4968](https://github.com/open-telemetry/opentelemetry-java/pull/4968)) +* Log invalid arguments rather than throwing exceptions. + ([#5012](https://github.com/open-telemetry/opentelemetry-java/pull/5012)) +* Stop mapping semconv values from OpenTracing to OTel. + ([#5016](https://github.com/open-telemetry/opentelemetry-java/pull/5016)) + +## Version 1.20.1 (2022-11-15) + +### Bugfixes + +* Fix bug in `ComponentRegistry` that produces `ConcurrentModificationException` when reading + metrics at the same time as obtaining a meter. + [(#4951)](https://github.com/open-telemetry/opentelemetry-java/pull/4951) + +## Version 1.20.0 (2022-11-11) + +### API + +- Fix bug in `W3CBaggagePropagator` that caused `+` characters to be decoded as whitespace ` `. + [(#4898)](https://github.com/open-telemetry/opentelemetry-java/pull/4898) + +#### API Extensions + +* DEPRECATION: the `opentelemetry-extension-aws` module containing + various `AwsXrayPropagator` implementations has been deprecated for removal in next minor version. + A copy of the code will instead be maintained + in [opentelemetry-java-contrib/aws-xray-propagator](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/aws-xray-propagator) + and published under + coordinates `io.opentelemetry.contrib:opentelemetry-aws-xray-propagator:{version}`. + [(#4862)](https://github.com/open-telemetry/opentelemetry-java/pull/4862) + +### SDK + +#### Traces + +* Add graal hints for shaded dependencies, allowing `JcTools` queue to be used in graal environment. + [(#4832)](https://github.com/open-telemetry/opentelemetry-java/pull/4832) +* `Sampler#getDescription()` implementations are now locale independent. + [(#4877)](https://github.com/open-telemetry/opentelemetry-java/pull/4887) +* Allow SDK to run in environments prohibiting use of `sun.misc.Unsafe`. + [(#4902)](https://github.com/open-telemetry/opentelemetry-java/pull/4902) + +#### Metrics + +* Add `toString` to `AbstractInstrument`. + [(#4833)](https://github.com/open-telemetry/opentelemetry-java/pull/4883) +* Add zero bucket boundary to default explicit bucket histogram aggregation. + [(#4819)](https://github.com/open-telemetry/opentelemetry-java/pull/4819) + +#### Logs + +* Optimize log hot path, reducing allocations significantly. + [(#4913)](https://github.com/open-telemetry/opentelemetry-java/pull/4913) +* BREAKING: Add `Context` argument to `LogRecordProcessor#onEmit`. + [(#4889)](https://github.com/open-telemetry/opentelemetry-java/pull/4889) + +#### Exporter + +* `OtlpLogging{Signal}Exporter`s encode enums as numbers. + [(#4783)](https://github.com/open-telemetry/opentelemetry-java/pull/4783) +* Add `User-Agent` header of `OTel OTLP Exporter Java/{version}` to OTLP export requests. + [(#4784)](https://github.com/open-telemetry/opentelemetry-java/pull/4784) + +#### SDK Extensions + +* WARNING: `opentelemetry-sdk-extension-aws` has been removed following its relocation + to [opentelemetry-java-contrib/instrumentation-aws-xray](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/aws-xray), + which is published under + coordinates `io.opentelemetry.contrib:opentelemetry-aws-resources:{version}`. + We will push security patches to `1.19.x` as needed. The latest `opentelemetry-bom` will point + to the latest published version, currently `1.19.0`. + [(#4830)](https://github.com/open-telemetry/opentelemetry-java/pull/4830) +* WARNING: `opentelemetry-sdk-extension-resources` has been removed following its relocation + to [opentelemetry-java-instrumentation/instrumentation/resources/library](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/resources/library), + which is published under + coordinates `io.opentelemetry.instrumentation:opentelemetry-resources:{version}`. + We will push security patches to `1.19.x` as needed. The latest `opentelemetry-bom` will point + to the latest published version, currently `1.19.0`. + [(#4828)](https://github.com/open-telemetry/opentelemetry-java/pull/4828) +* Add autoconfigure support for `BatchLogRecordProcessor`. + [(#4811)](https://github.com/open-telemetry/opentelemetry-java/pull/4811) +* Autoconfigure performs percent decoding on `otel.resource.attributes` values. + [(#4653)](https://github.com/open-telemetry/opentelemetry-java/issues/4653) +* Unify compression configuration for exporters including + [(#4775)](https://github.com/open-telemetry/opentelemetry-java/pull/4775): + * Fix handling of `none` in OTLP exporters. + * Add `JaegerGrpcSpanExporterBuilder#setCompression(String)`. + * Add `ZipkinSpanExporterBuilder#setCompression(String)`. + +### Semantic Conventions + +* Add migration notes to deprecated attributes + [(#4840)](https://github.com/open-telemetry/opentelemetry-java/pull/4840) + +### OpenTracing Shim + +* Use `opentracing-shim` as instrumentation scope name. + [(#4890)](https://github.com/open-telemetry/opentelemetry-java/pull/4890) +* Add full support for multiple parents. + [(#4916)](https://github.com/open-telemetry/opentelemetry-java/pull/4916) + +## Version 1.19.0 (2022-10-07) + +This release contains a large number of changes to the log signal following a series of significant +changes to +the [log specification](https://github.com/open-telemetry/opentelemetry-specification/tree/main/specification/logs). +The changes include renaming key classes like `LogExporter` to `LogRecordExporter`, +and `LogProcessor` to `LogRecordProcessor`, and `LogEmitter` to `Logger`, and more. Additionally, a +log API component has been added for emitting events and for writing log appenders. Note, the log +API is not a substitute for traditional log frameworks like Log4j, JUL, SLF4J, or Logback. While the +event portion of the API is intended for instrumentation authors and end users, the API for emitting +LogRecords is not. +See [LoggerProvider](./api/all/src/main/java/io/opentelemetry/api/logs/LoggerProvider.java) +and [Logger](./api/all/src/main/java/io/opentelemetry/api/logs/Logger.java) javadoc for more +details. + +### General + +* Add `opentelemetry-bom` as a dependency to `opentelemetry-bom-alpha`, ensuring synchronization + between alpha and stable artifact versions. + +### API + +#### API Extensions + +* WARNING: `opentelemetry-extension-annotations` has been removed following its relocation + to [opentelemetry-java-instrumentation/instrumentation-annotations](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation-annotations), + which is published under + coordinates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-annotations:{version}`. + We will push security patches to `1.18.x` as needed. The latest `opentelemetry-bom` will point + to the latest published version, currently `1.18.0`. + +#### Logs + +* Introduce log API for emitting events and writing log appenders. The artifact is available at + coordinates `io.opentelemetry:opentelemetry-api-logs:1.19.0-alpha`. + +### SDK + +#### Metrics + +* Change exponential histogram bucket boundaries to be lower exclusive / upper inclusive, instead of + lower inclusive / upper exclusive. + +#### Logs + +* BREAKING: Rename `SdkLogEmitterProvider` to `SdkLoggerProvider`. + `OpenTelemetrySdkBuilder#setLogEmitterProvider` has changed + to `OpenTelemetrySdkBuilder#setLoggerProvider`. `OpenTelemetrySdk#getSdkLogEmitterProvider` has + changed to `OpenTelemetrySdk#getSdkLoggerProvider`. + `AutoConfigurationCustomizer#addLogEmitterProviderCustomizer` has changed + to `AutoConfigurationCustomizer#addLoggerProviderCustomizer`. +* BREAKING: Rename `LogEmitter` to `Logger`. +* BREAKING: Rename `LogExporter` to `LogRecordExporter`. `SystemOutLogExporter` has changed + to `SystemOutLogRecordExporter`. `OtlpJsonLoggingLogExporter` has changed + to `OtlpJsonLoggingLogRecordExporter`. `OtlpHttpLogExporter` has changed + to `OtlpHttpLogRecordExporter`. `OtlpGrpcLogExporter` has changed to `OtlpGrpcLogRecordExporter`. + `InMemoryLogExporter` has changed to `InMemoryLogRecordExporter`. + ConfigurableLogExporterProvider` has changed to `ConfigurableLogRecordExporterProvider`. +* BREAKING: Rename `LogData` to `LogRecordData`. `TestLogData` has changed to `TestLogRecordData`. +* BREAKING: Rename `LogProcessor` to `LogRecordProcessor`. `BatchLogProcessor` has changed + to `BatchLogRecordProcessor`. `SimpleLogProcessor` has changed to `SimpleLogRecordProcessor`. + +#### Exporter + +* OTLP log record exporters now + include [dropped_attributes_count](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/logs/v1/logs.proto#L157). + +#### SDK Extensions + +* Autoconfigure now supports an option to disable the SDK. If `otel.sdk.disabled=true`, + `AutoConfiguredOpenTelemetrySdk#getOpenTelemetrySdk()` returns a minimal (but not + noop) `OpenTelemetrySdk` with noop tracing, metric and logging providers. The same minimal + instance is set to `GlobalOpenTelemetry`. The now deprecated + property `otel.experimental.sdk.enabled` will continue to work in the same way during a transition + period. +* Fix `ProcessResource` directory separator to use `/` or `\` instead of `:` or `;`. +* DEPRECATION: the `opentelemetry-sdk-extension-resource` module containing + various `ResourceProvider` implementations has been deprecated for removal in next major version. + A copy of the code will instead be maintained + in [opentelemetry-java-instrumentation/instrumentation/resources/library](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/resources/library) + and published under + coordinates `io.opentelemetry.instrumentation:opentelemetry-resources:{version}`. +* DEPRECATION: the `opentelemetry-sdk-extension-aws` module containing AWS `ResourceProvider` + implementations has been deprecated for removal in next major version. A copy of the code will + instead be maintained + in [opentelemetry-java-contrib/aws-resources](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/aws-resources) + and published under coordinates `io.opentelemetry.contrib:opentelemetry-aws-resources:{version}`. + +### OpenTracing Shim + +* Fully support Baggage-only propagation. + +### Semantic conventions + +* The semantic conventions have been updated to 1.13.0. + +## Version 1.18.0 (2022-09-09) + +### SDK + +* Added scope attributes to `InstrumentationScopeInfo` accessible + via `InstrumentationScopeInfo#getAttributes()`. Will add the ability to specify scope attributes + in Meter, Tracer, and Logger in a future version. +* DEPRECATION: The `InstrumentationScopeInfo#create(String, String, String)` method has been + deprecated in favor of + `InstrumentationScopeInfo#builer(String).setVersion(String).setSchemaUrl(String).build()`. +* Optimize `Resource#merge(Resource)` by returning early if the other resource is empty. + +#### Logs + +* Fix module name of `opentelemetry-sdk-logs` by changing + from `io.opentelemetry.sdk.extension.logging` to `io.opentelemetry.sdk.logs`. + +#### Testing + +* Add methods to assert attributes do not contain keys via `AttributeAssert#doesNotContainKey()`. + +#### Exporter + +* Added ability to specify local IP address in `ZipkinSpanExporter` + via `ZipkinSpanExporterBuilder#setLocalIpAddressSupplier(Supplier)`. +* Upgrade to OTLP protobuf version 0.19.0. +* OTLP exporters now serialize `InstrumentationScopeInfo#getAttributes()`. +* Stop publishing `opentelemetry-exporter-jaeger-proto`. The `opentelemetry-bom` will include a + constraint on the last published version `1.17.0`. If security issues are discovered, patches will + be published to `1.17.x`. + +#### SDK Extensions + +* BREAKING: `opentelemetry-sdk-extension-metric-incubator`, + `opentelemetry-sdk-extension-tracing-incubator`, and `opentelemetry-sdk-extension-zpages` merged + into `opentelemetry-sdk-extension-incubator`. +* BREAKING: Move `opentelemetry-sdk-extension-jfr-events` + to [opentelemetry-java-contrib/jfr-events](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/jfr-events). + It will now be published under the + coordinates `io.opentelemetry.contrib:opentelemetry-jfr-events:{version}`. +* BREAKING: Move `opentelemetry-extension-noop-api` + to [opentelemetry-java-contrib/noop-api](https://github.com/open-telemetry/opentelemetry-java-contrib/tree/main/noop-api). + It will now be published under the + coordinates `io.opentelemetry.contrib:opentelemetry-noop-api:{version}`. +* Improve ECS resource detection to include `aws.ecs.container.arn`, `container.image.name`, + `container.image.tag`, `aws.ecs.container.image.id`, `aws.log.group.arns`, `aws.log.group.names`, + `aws.log.steam.names`, `aws.ecs.task.arn`, `aws.ecs.task.family`, and `aws.ecs.task.revision`. +* Fix resource `container.id` detection when using k8s with containerd v1.5.0+. +* Add experimental `ConditionalResourceProvider` SPI, for conditionally applying resource providers + based on current config and resource. + +### Micrometer shim + +* BREAKING: Move `opentelemetry-micrometer1-shim` + to [opentelemetry-java-instrumentation/instrumentation/micrometer/micrometer-1.5/library](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation/micrometer/micrometer-1.5/library). + It will now be published under the + coordinates `io.opentelemetry.instrumentation:opentelemetry-micrometer-1.5:{version}`. + +## Version 1.17.0 (2022-08-12) + +### API + +#### API Extensions + +* DEPRECATION: the `opentelemetry-extension-annotations` module containing `@WithSpan` + and `@SpanAttribute` annotations has been deprecated for removal in next major version. A copy of + the code will instead be maintained + in [opentelemetry-java-instrumentation/instrumentation-annotations](https://github.com/open-telemetry/opentelemetry-java-instrumentation/tree/main/instrumentation-annotations) + and published under + coordinates `io.opentelemetry.instrumentation:opentelemetry-instrumentation-annotations:{version}`. + +### SDK + +#### Traces + +* Add default implementation for `SpanData#getInstrumentationScopeInfo()` + and `ReadableSpan#getInstrumentationScopeInfo()`. This fixes a previous mistake where those + interfaces were extended without default implementation, a breaking change for source + compatibility. Stricter checks have been added to ensure this mistake is not repeated. + +#### Logs + +* BREAKING: delete `LogDataBuilder`. A similar implementation of `LogData` called `TestLogData` has + been added to `opentelemetry-sdk-logs-testing`. +* BREAKING: rename `LogProcessor#emit(LogData)` to `LogProcessor#onEmit(ReadWriteLogRecord)`. The + argument change from `LogData` to `ReadWriteLogRecord` allows implementations to mutate logs. To + obtain `LogData`, call `ReadWriteLogRecord#toLogData()`. +* Optimize `SdkLogEmitterProvider` to return noop `LogEmitter` when no `LogProcessor`s are + registered. + +#### Exporter + +* Split out shared and internal exporter classes from `opentelemetry-exporter-otlp-common` + to `opentelemetry-exporter-common`. +* Add experimental support for OTLP header based authentication. To use, add a dependency + on `opentelemetry-exporter-common` and + call `io.opentelemetry.exporter.internal.auth.Authenticator#setAuthenticatorOnDelegate(OtlpHttp{Signal}Builder, Authenticator)`. +* Add ability to collect export metrics on `ZipkinSpanExporter` + via `ZipkinSpanExporter#setMeterProvider(MeterProvider)`. +* Minor optimization to OkHttp based exporters to cache endpoint URLs. Applies + to `OtlpHttp{Signal}Exporter`, `OtlpGrpc{Signal}Exporter`, and more. +* Fix diagnostic log message in `OtlpGrpc{Signal}Exporter` to include correct environment variables. + +#### SDK Extensions + +* Extend View file based configuration with support for specifying explicit bucket histogram bucket + boundaries and exponential bucket counts. +* Extend autoconfigure SPI `AutoConfigurationCustomizerProvider` and `ResourceProvider` with option + to specify ordering. +* Add autoconfigure SPI with `ConfigurableLogExporterProvider`, allowing custom named log exporters + to be provided and selected via autoconfigure. +* Extend autoconfigure SPI with `AutoConfigurationCustomizer#addPropertiesCustomizer`, providing the + ability examine current configuration properties and add / overwrite properties. + +## Version 1.16.0 (2022-07-13) + +### API + +* Fix bug `ImmutableKeyValuePairs` implementation that causes `ArrayIndexOutOfBoundsException` to be + thrown under certain conditions. + +### SDK + +#### Traces + +* Optimize `BatchSpanProcessor` using JcTools. + +#### Metrics + +* Tighten up exponential histogram implementation for alignment with specification: Default to 160 + positive and negative buckets. Remove ability to configure starting scale. Minimum number of + buckets is one instead of zero. +* Allow `MetricExporter` and `MetricReader` to influence default aggregation. The default + aggregation is used when no registered views match an instrument. + +#### Exporter + +* Fix handling of client keys in PEM format. +* For OTLP exporters, change behavior to use `OkHttpGrpcExporter` (OkHttp implementation that + doesn't use any gRPC dependencies) unless `OtlpGrpc{Signal}Builder#setChannel(ManagedChannel)` is + called by user. Previously, `OkHttpGrpcExporter` was used if no gRPC implementation was found on + classpath. +* Add support to configure default aggregation on OTLP metric exporters + via `Otlp{Protocol}MetricExporterBuilder#setDefaultAggregationSelector(DefaultAggregationSelector)`. + +#### Testing + +* Add span status assertions. + +#### SDK Extensions + +* Autoconfigure properly handles non-string system properties. +* Autoconfigure normalizes hyphens `-` to periods `.` when accessing `ConfigProperties`. + +### OpenTracing Shim + +* Add support for span wrappers. +* Store OpenTracing `SpanContext` in OpenTracing `Span` wrapper. +* Use `Baggage` of active span. + +## Version 1.15.0 (2022-06-10) + +### API + +* Add batch callback API, allowing a single callback to record measurements to multiple metric + instruments. + +### SDK + +#### Metrics + +* `SdkMeterProvider#toString()` now returns a useful string describing configuration. +* Fix bug preventing proper function of Metrics SDK when multiple readers are + present ([#4436](https://github.com/open-telemetry/opentelemetry-java/pull/4436)). +* Fix reporting intervals for metrics for delta + readers ([#4400](https://github.com/open-telemetry/opentelemetry-java/issues/4400)). + +#### Exporter + +* BREAKING: merge all stable OTLP exporters into `opentelemetry-exporter-otlp`. + `opentelemetry-exporter-otlp-trace`, `opentelemetry-exporter-otlp-metrics`, + `opentelemetry-exporter-otlp-http-trace`, and `opentelemetry-exporter-otlp-http-metrics` are no + longer published and their contents have been merged into a single artifact. +* BREAKING: merge log OTLP exporters into `opentelemetry-exporter-otlp-logs`. + `opentelemetry-exporter-otlp-http-logs` is no longer published and its contents have been merged + into a single artifact. +* Upgrade to OTLP protobuf version 0.18.0. +* RetryInterceptor retries on `SocketTimeoutException` with no message. +* Added `JaegerGrpcSpanExporterBuilder#setMeterProvider()`, enabling support of experimental jaeger + span export metrics. +* DEPRECATION: the `opentelemetry-exporter-jaeger-proto` module containing jaeger proto definitions + and corresponding generated classes is deprecated for removal in next major version. +* OTLP gRPC exporters support overriding `:authority` + via `OtlpGrpc*ExporterBuilder#addHeader("host", "my-authority-override")`. + +#### SDK Extensions + +* BREAKING: Move `ConfigureableMetricExporterProvider` + from `opentelemetry-sdk-extension-autoconfigure` to + stable `opentelemetry-sdk-extension-autoconfigure-spi`. +* Autoconfigure now supports multiple values for `otel.metrics.exporter`. +* Autoconfigure now + supports [general attribute limits](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#attribute-limits), + applicable to span attributes, span event attributes, span link attributes, and log attributes. +* Autoconfigure now supports an experimental option to disable the SDK. + If `otel.experimental.sdk.enabled=true`, `AutoConfiguredOpenTelemetrySdk#getOpenTelemetrySdk()` + returns a minimal (but not noop) `OpenTelemetrySdk`. The same minimal instance is set + to `GlobalOpenTelemetry`. +* New "get or default" methods have been added to `ConfigProperties`. + E.g. `ConfigProperties#getString("otel.metrics.exporter", "otlp")` fetches the value for the + property `otel.metrics.exporter` and returns `otlp` if it is not set. +* Fix bug in `ContainerResource` provider that caused it to throw an exception in some instances + when containerd is used. + +### Micrometer shim + +* Cache descriptions such that metrics with the same name use the first seen description. + ## Version 1.14.0 (2022-05-09) The metrics SDK is stable! New stable artifacts include: @@ -234,7 +3727,7 @@ should not be many. Thanks for bearing with us on this. ### General * Examples moved - to [opentelemetry-java-docs](https://github.com/open-telemetry/opentelemetry-java-docs) + to [opentelemetry-java-examples](https://github.com/open-telemetry/opentelemetry-java-examples) ### SDK @@ -444,7 +3937,7 @@ should not be many. Thanks for bearing with us on this. This provides improved ergonomics and control around autoconfigure customization. - Added experimental support for enabling OTLP retry support for the `grpc` exporters. If enabled via `otel.experimental.exporter.otlp.retry.enabled`, - a [default retry policy](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure#otlp-exporter-retry) + a [default retry policy](https://opentelemetry.io/docs/languages/java/configuration/#properties-exporters) will be used. - The metric export interval of `PeriodicMetricReader` is now configured via `otel.metric.export.interval`. The existing `otel.imr.export.interval` property has been @@ -1544,7 +5037,7 @@ See the `opentelemetry-extension-kotlin` module for details. #### Breaking changes -- There have been many updates to the semantic conventions constants. The constants are now auto-generated from the YAML specification files, so the names will now be consistent across languages. For more information, see the [YAML Model for Semantic Conventions](https://github.com/open-telemetry/opentelemetry-specification/tree/master/semantic_conventions). +- There have been many updates to the semantic conventions constants. The constants are now auto-generated from the YAML specification files, so the names will now be consistent across languages. For more information, see the [YAML Model for Semantic Conventions](https://github.com/open-telemetry/semantic-conventions/blob/main/model/README.md#yaml-model-for-semantic-conventions). - All API classes have been moved into the `io.opentelemetry.api.` prefix to support JPMS users. - The API no longer uses the `grpc-context` as the context implementation. It now uses `io.opentelemetry.context.Context`. This is published in the `opentelemetry-context` artifact. Interactions with the context were mostly moved to static methods in the `Span` and `Baggage` interfaces. - The Baggage API has been reworked to more closely match the specification. This includes the removal of the `BaggageManager`. Baggage is fully functional within the API, without needing to install an SDK. @@ -1575,7 +5068,7 @@ See the `opentelemetry-extension-kotlin` module for details. #### Breaking changes -- `TraceConfig` configuration option names (environment variables and system properties) were renamed to match the OpenTelemetery Specification. For more information, see [TraceConfig](./QUICKSTART.md#TraceConfig). +- `TraceConfig` configuration option names (environment variables and system properties) were renamed to match the OpenTelemetery Specification. - The Jaeger gRPC exporter was updated to match the OpenTelemetry Specification. The `message` log entry attribute has been renamed to `event` and a new `dropped attributes count` attribute was added. For more information, see the [Overview](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/overview.md). - The `SpanData.getHasRemoteParent()` and `SpanData.getHasEnded()` methods were renamed to `hasRemoteParent()` and `hasEnded()`, respectively. - The `IdsGenerator` interface has been renamed to `IdGenerator`, and all implementations and relevant factory methods were similarly renamed. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 19a7580fc75..31a27583c30 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,222 +1,95 @@ # Contributing -Welcome to OpenTelemetry Java repository! +Welcome to the OpenTelemetry Java repository! -Before you start - see OpenTelemetry general -[contributing](https://github.com/open-telemetry/community/blob/main/CONTRIBUTING.md) +Before you start, see the OpenTelemetry general +[contributing](https://github.com/open-telemetry/community/blob/main/guides/contributor/README.md) requirements and recommendations. -If you want to add new features or change behavior, please make sure your changes follow the -[OpenTelemetry Specification](https://github.com/open-telemetry/opentelemetry-specification). -Otherwise file an issue or submit a PR to the specification repo first. +## CLA and license -Make sure to review the projects [license](LICENSE) and sign the -[CNCF CLA](https://identity.linuxfoundation.org/projects/cncf). A signed CLA will be enforced by an -automatic check once you submit a PR, but you can also sign it after opening your PR. +Review the project [license](LICENSE) and sign the +[CNCF CLA](https://identity.linuxfoundation.org/projects/cncf). A signed CLA will be enforced by +an automatic check once you submit a PR, but you can also sign it after opening your PR. -## Requirements +## Build and coding patterns -Java 11 or higher is required to build the projects in this repository. The built artifacts can be -used on Java 8 or higher. +See [docs/knowledge/README.md](docs/knowledge/README.md) for coding patterns, build conventions, +testing guidance, and API stability rules. Build requirements and common commands are in +[docs/knowledge/build.md](docs/knowledge/build.md). -## Building opentelemetry-java +## PR review -Continuous integration builds the project, runs the tests, and runs multiple types of static -analysis. - -1. Note: Currently, to run the full suite of tests, you'll need to be running a docker daemon. The - tests that require docker are disabled if docker is not present. If you wish to run them, you - must run a local docker daemon. - -2. Clone the repository +After you submit a PR, it will be reviewed by the project maintainers and approvers. Not all +maintainers need to review a particular PR, but merging to the base branch is authorized to +restricted members (administrators). - `git clone https://github.com/open-telemetry/opentelemetry-java.git` +Contributors without an official project role are encouraged to review PRs. This is a +useful signal for maintainers and is a requirement if you are interested in joining the project +in an official capacity. -3. Run the following commands to build, run tests and most static analysis, and check formatting: +This repository sits at the base of a large ecosystem: widely deployed, a target for attackers, +and sensitive to performance regressions. Expect a high level of scrutiny on API surface, +security, performance, and maintainability, including on small changes. This reflects the +project's position, not distrust of contributors. Back-and-forth during review is normal. - `./gradlew build` +### Draft PRs -4. If you are a Windows user, use the alternate command mentioned below to run tests and check - formatting: +Draft PRs are welcome, especially when exploring new ideas or experimenting with a hypothesis. +However, draft PRs may not receive the same degree of attention, feedback, or scrutiny unless +requested directly. In order to help keep the PR backlog maintainable, drafts older than 6 months +will be closed by the project maintainers. This should not be interpreted as a rejection. Closed +PRs may be reopened by the author when time or interest allows. - `gradlew.bat` +### Test coverage -## Checks +CI reports a code coverage delta on every PR. The threshold is a signal for reviewer attention, +not a merge gate. Above it, coverage is not something reviewers will dwell on. Below it, +reviewers will look more closely at what is uncovered, and the outcome may be adding tests, +agreeing that more coverage is impractical, or restructuring the code for testability. A red +coverage check alone does not block a PR. -Before submitting a PR, you should make sure the style checks and unit tests pass. You can run these -with the `check` task. +### Build failures -```bash -$ ./gradlew check -``` +Transient CI failures happen on a build matrix of a size this project uses. A red check does not, by itself, +affect how your PR is reviewed. -Note: this gradle task will potentially generate changes to files in -the `docs/apidiffs/current_vs_latest` -directory. Please make sure to include any changes to these files in your pull request. +* Failing across all Java versions and operating systems: likely a real issue in the change, + worth fixing before requesting review. +* Only one or a handful of jobs failing: probably transient. Most required jobs cannot be + re-run by contributors, so a maintainer will re-run them, and these failures are not held + against the contribution. +* If re-runs are slow, a friendly ping on the PR is welcome. -## PR Review +## Project scope -After you submit a PR, it will be reviewed by the project maintainers and approvers. Not all -maintainers need to review a particular PR, but merging to the base branch is authorized to -restricted members (administrators). +`opentelemetry-java` contains the core components upon which instrumentation and extensions are +built. Its scope is limited to components which implement concepts defined in the +[OpenTelemetry Specification](https://github.com/open-telemetry/opentelemetry-specification). New +features or behavior changes should follow the specification β€” if the specification doesn't cover +your change, file an issue or submit a PR there first. Exceptions to strict spec alignment include: -## Style guideline +* The [API incubator](./api/incubator) and [SDK incubator](./sdk-extensions/incubator) contain + prototypes discussed in the specification or + [oteps](https://github.com/open-telemetry/oteps) with a reasonable chance of becoming part of + the specification, subject to maintainers' discretion. +* Components like the [Kotlin Extension](./extensions/kotlin) are included when required for the + API / SDK to function in key areas of the Java ecosystem, subject to maintainers' discretion. +* As a general rule, components which implement semantic conventions belong elsewhere. -We follow the [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html). Our -build will fail if source code is not formatted according to that style. To fix any style failures -the above [checks](#checks) show, automatically apply the formatting with: +For an overview of the other repositories in the OpenTelemetry Java ecosystem, see +[opentelemetry.io/docs/languages/java/intro/#repositories](https://opentelemetry.io/docs/languages/java/intro/#repositories). -```bash -$ ./gradlew spotlessApply -``` +## Benchmarks -To verify code style manually run the following command, which -uses [google-java-format](https://github.com/google/google-java-format) library: +JMH benchmark instructions live in [docs/knowledge/other-tasks.md#benchmarks-jmh](docs/knowledge/other-tasks.md#benchmarks-jmh). +If you are submitting a performance-sensitive PR, include JMH output (number of threads, +iterations, scores with error margins) so reviewers can evaluate the change. -`./gradlew spotlessCheck` - -### Best practices that we follow - -* This project uses [semantic versioning](https://semver.org/). Except for major versions, a user - should be able to update their dependency version on this project and have nothing break. This - means we do not make breaking changes to the API (e.g., remove a public method) or to the ABI ( - e.g., change return type from void to non-void). -* Avoid exposing publicly any class/method/variable that don't need to be public. -* By default, all arguments/members are treated as non-null. Every argument/member that can - be `null` must be annotated with `@Nullable`. -* The project aims to provide a consistent experience across all the public APIs. It is important to - ensure consistency (same look and feel) across different public packages. -* Use `final` for public classes everywhere it is possible, this ensures that these classes cannot - be extended when the API does not intend to offer that functionality. -* In general, we use the following ordering of class members: - * Static fields (final before non-final) - * Instance fields (final before non-final) - * Constructors - * In static utility classes (where all members are static), the private constructor - (used to prevent construction) should be ordered after methods instead of before methods. - * Methods - * If methods call each other, it's nice if the calling method is ordered (somewhere) above the - method that it calls. So, for one example, a private method would be ordered (somewhere) below - the non-private methods that use it. - * Nested classes -* Adding `toString()` overrides on classes is encouraged, but we only use `toString()` to provide - debugging assistance. The implementations of all `toString()` methods should be considered to be - unstable unless explicitly documented otherwise. - -If you notice any practice being applied in the project consistently that isn't listed here, please -consider a pull request to add it. - -### Pre-commit hook - -To completely delegate code style formatting to the machine, you can -add [git pre-commit hook](https://git-scm.com/docs/githooks). We provide an example script -in `buildscripts/pre-commit` file. Just copy or symlink it into `.git/hooks` folder. - -### Editorconfig - -As additional convenience for IntelliJ Idea users, we provide `.editorconfig` file. Idea will -automatically use it to adjust its code formatting settings. It does not support all required rules, -so you still have to run `spotlessApply` from time to time. - -### Javadoc - -* All public classes and their public and protected methods MUST have javadoc. It MUST be complete ( - all params documented etc.) Everything else - (package-protected classes, private) MAY have javadoc, at the code writer's whim. It does not have - to be complete, and reviewers are not allowed to require or disallow it. -* Each API element should have a `@since` tag specifying the minor version when it was released (or - the next minor version). -* There MUST be NO javadoc errors. -* - -See [section 7.3.1](https://google.github.io/styleguide/javaguide.html#s7.3.1-javadoc-exception-self-explanatory) -in the guide for exceptions to the Javadoc requirement. - -* Reviewers may request documentation for any element that doesn't require Javadoc, though the style - of documentation is up to the author. -* Try to do the least amount of change when modifying existing documentation. Don't change the style - unless you have a good reason. -* We do not use `@author` tags in our javadoc. -* Our javadoc is available via [ - javadoc.io}(https://javadoc.io/doc/io.opentelemetry/opentelemetry-api) - -### AutoValue - -* Use [AutoValue](https://github.com/google/auto/tree/master/value), when possible, for any new - value classes. Remember to add package-private constructors to all AutoValue classes to prevent - classes in other packages from extending them. - -### Unit Tests - -* Unit tests target Java 8, so language features such as lambda and streams can be used in tests. - -## Specific tasks - -### Updating the Snapshot build number - -The overall version number for opentelemetry-java is determined from git tags, and not fixed in any -file. - -This means it will not update, even if you `git pull` from the repo tip. It will still produce a set -of libraries with the old version number. - -To update it, you must fetch the tags, via `git fetch --all --tags` - which should work, even if you -have forked the repo, as long as the trunk repo is set as an upstream remote. - -### Composing builds - -Beware that this section is only meant for developers of opentelemetry-java, or closely related -projects. The steps described here could change at any time and what you do for one version (commit) -may break with the next one already. - -Gradle provides a feature -called ["composite builds"](https://docs.gradle.org/current/userguide/composite_builds.html) -that allows to replace some normally externally provided dependencies with a project that is built -(included) in the same Gradle invocation. This can be useful to quickly test a new feature or bug -fix you are developing in opentelemetry-java with the examples or the app or instrumentation library -where you need the feature or run into the bug. Unfortunately, opentelemetry-java does not work out -of the box with this feature because Gradle is unable to map the project names to the customized -artifact coordinates (see e.g. [gradle/gradle#18291](https://github.com/gradle/gradle/issues/18291) -and related issues. However, gradle supports manually declaring the mapping between ("substitution -of") -artifact coordinates and project names. To ease this tedious task, opentelemetry-java provides a -gradle task `:generateBuildSubstitutions` that generates a code snippet with these substitutions in -kts (Kotlin Script) format. - -Example usage could be as follows: - -1. Run `./gradlew generateBuildSubstitutions` -2. Two files named `build/substitutions.gradle.kts` are generated in the bom and bom-alpha project's - directory, containing substitutions for the stable and alpha projects respectively. -3. Copy & paste the content of these files to a new `settings.gradle.kts` or the one where you want - to include the opentelemetry build into, so that it contains something like the following: - - ```kotlin - includeBuild("PATH/TO/OPENTELEMETRY-JAVA/ROOT/DIRECTORY") { - // Copy & paste following block from the generated substitutions.gradle.kts, *not* from here! - dependencySubstitution { - substitute(module("io.opentelemetry:opentelemetry-api")).using(project(":api:all")) - substitute(module("io.opentelemetry:opentelemetry-sdk")).using(project(":sdk:all")) - // ... - } - } - ``` +## User-facing documentation - See [the Gradle documentation](https://docs.gradle.org/current/userguide/composite_builds.html#included_build_declaring_substitutions) - for more information. - -4. If you now build your project, it will use the included build to supply the opentelemetry-java - artifacts, ignoring any version declarations. Use the prefix `:DIRECTORY:` to refer to - tasks/projects within the included build, where DIRECTORY is the name of the directory in the - included build (only the part after the last `/`). - -### Updating the OTLP protobufs - -OTLP protobuf Java bindings are published via -the [opentelemetry-proto-java](https://github.com/open-telemetry/opentelemetry-proto-java) -repository. This project does not use the java bindings, but does use the `.proto` files that are -published in the binding jar by that project. - -To update the OTLP protobuf version, -first [release a new version of the java bindings](https://github.com/open-telemetry/opentelemetry-proto-java/blob/main/RELEASING.md) -then simply update the dependency version that this project has on that jar. +End-user documentation for the Java SDK lives at +[opentelemetry.io/docs/languages/java/](https://opentelemetry.io/docs/languages/java/), with +source in [github.com/open-telemetry/opentelemetry.io](https://github.com/open-telemetry/opentelemetry.io). +If your change affects user-visible behavior β€” configuration options, new features, changed +defaults β€” please update or open an issue against the documentation there. diff --git a/README.md b/README.md index 5784b9619b5..4d1b5c244f3 100644 --- a/README.md +++ b/README.md @@ -1,333 +1,321 @@ -# OpenTelemetry for Java -[![Continuous Build][ci-image]][ci-url] +# OpenTelemetry Java + +[![Release](https://img.shields.io/github/v/release/open-telemetry/opentelemetry-java?include_prereleases&style=)](https://github.com/open-telemetry/opentelemetry-java/releases/) [![Coverage Status][codecov-image]][codecov-url] -[![Maven Central][maven-image]][maven-url] +[![FOSSA License Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-java.svg?type=shield&issueType=license)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-java?ref=badge_shield&issueType=license) +[![FOSSA Security Status](https://app.fossa.com/api/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-java.svg?type=shield&issueType=security)](https://app.fossa.com/projects/custom%2B162%2Fgithub.com%2Fopen-telemetry%2Fopentelemetry-java?ref=badge_shield&issueType=security) +[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/open-telemetry/opentelemetry-java/badge)](https://scorecard.dev/viewer/?uri=github.com/open-telemetry/opentelemetry-java) +[![Reproducible Builds](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/jvm-repo-rebuild/reproducible-central/master/content/io/opentelemetry/java/badge.json)](https://github.com/jvm-repo-rebuild/reproducible-central/blob/master/content/io/opentelemetry/java/README.md) -## Getting Started +`opentelemetry-java` is the home of the Java implementation of the OpenTelemetry API for recording +telemetry, and SDK for managing telemetry recorded by the API. -If you are looking for an all-in-one, easy-to-install **auto-instrumentation -javaagent**, see [opentelemetry-java-instrumentation][]. +See [opentelemetry.io Java Documentation](https://opentelemetry.io/docs/languages/java/intro/) for: -If you are looking for **examples** on how to use the OpenTelemetry API to -write your own **manual instrumentation**, or how to set up the OpenTelemetry -Java SDK, see [Manual instrumentation][]. Fully-functional examples -are available in [opentelemetry-java-docs][]. +* An overview of the OpenTelemetry Java ecosystem and key repositories +* Detailed documentation on the components published from this repository +* Review of instrumentation ecosystem, including OpenTelemetry Java agent +* End-to-end working code examples +* And more -For a general overview of OpenTelemetry, visit [opentelemetry.io][]. +> [!IMPORTANT] +> We are currently seeking additional contributors! See [help wanted](#help-wanted) for details. -Would you like to get involved with the project? Read our [contributing guide](CONTRIBUTING.md). We welcome -contributions! +## Requirements -## Contacting us +Unless otherwise noted, all published artifacts support Java 8 or higher. +See [language version compatibility](VERSIONING.md#language-version-compatibility) for complete +details. -We hold regular meetings. See details at [community page](https://github.com/open-telemetry/community#java-sdk). +**Android Disclaimer:** For compatibility +reasons, [library desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring) +must be enabled. -We use [GitHub Discussions](https://github.com/open-telemetry/opentelemetry-java/discussions) -for support or general questions. Feel free to drop us a line. +See [contributing](#contributing) for details on building this project locally. -We are also present in the `#otel-java` channel in the [CNCF slack](https://slack.cncf.io/). -Please join us for more informal discussions. +## Releases -## Overview +Releases are published to maven central. We +publish [minor releases monthly](RELEASING.md#release-cadence) +and [patch releases as needed](RELEASING.md#preparing-a-new-patch-release). + +See [releases](https://github.com/open-telemetry/opentelemetry-java/releases) for a listing of +released versions and notes (see also [changelog](CHANGELOG.md)). + +## Artifacts + +The artifacts published by this repository are summarized below in tables, organized in collapsible +sections by topic. + +As discussed in [compatibility](#compatibility), artifact versions must be kept in sync, for which +we strongly recommend [using one of our BOMs][dependencies-and-boms]. + +
+ Bill of Materials (BOMs) -OpenTelemetry is the merging of OpenCensus and OpenTracing into a single project. +A bill of materials (or BOM) helps sync dependency versions of related artifacts. -This project contains the following top level components: +| Component | Description | Artifact ID | Version | Javadoc | +|----------------------------------------------|----------------------------------------|---------------------------|-------------------------------------------------------------|---------| +| [Bill of Materials (BOM)](./bom) | Bill of materials for stable artifacts | `opentelemetry-bom` | 1.68.0 | N/A | +| [Alpha Bill of Materials (BOM)](./bom-alpha) | Bill of materials for alpha artifacts | `opentelemetry-bom-alpha` | 1.68.0-alpha | N/A | +
-* [OpenTelemetry API](api/): - * [stable apis](api/all/src/main/java/io/opentelemetry/api/) including `Tracer`, `Span`, `SpanContext`, `Meter`, and `Baggage` - * [semantic conventions](semconv/) Generated code for the OpenTelemetry semantic conventions. - * [context api](context/src/main/java/io/opentelemetry/context/) The OpenTelemetry Context implementation. -* [extensions](extensions/) define additional API extensions, which are not part of the core API. -* [sdk](sdk/) defines the implementation of the OpenTelemetry API. -* [sdk-extensions](sdk-extensions/) defines additional SDK extensions, which are not part of the core SDK. -* [OpenTracing shim](opentracing-shim/) defines a bridge layer from OpenTracing to the OpenTelemetry API. -* [OpenCensus shim](opencensus-shim/) defines a bridge layer from OpenCensus to the OpenTelemetry API. -* [Micrometer shim](micrometer1-shim/) defines a bridge layer from Micrometer to the OpenTelemetry API. +
+ API -This project publishes a lot of artifacts, listed in [releases](#releases). -[`opentelemetry-bom`](https://mvnrepository.com/artifact/io.opentelemetry/opentelemetry-bom) (BOM = -Bill of Materials) is provided to assist with synchronizing versions of -dependencies. [`opentelemetry-bom-alpha`](https://mvnrepository.com/artifact/io.opentelemetry/opentelemetry-bom-alpha) -provides the same function for unstable artifacts. See [published releases](#published-releases) for -instructions on using the BOMs. +The OpenTelemetry API for recording telemetry. -We would love to hear from the larger community: please provide feedback proactively. +| Component | Description | Artifact ID | Version | Javadoc | +|-----------------------------------|--------------------------------------------------------------------------------------|-------------------------------|-------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [API](./api/all) | OpenTelemetry API, including metrics, traces, baggage, context | `opentelemetry-api` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-api.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-api) | +| [API Incubator](./api/incubator) | API incubator, including pass through propagator and extended tracer | `opentelemetry-api-incubator` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-api-incubator.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-api-incubator) | +| [Context API](./context) | OpenTelemetry context API | `opentelemetry-context` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-context.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-context) | +| [Common](./common) | Common utility methods used across API components | `opentelemetry-common` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-common.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-common) | +
-## Requirements +
+ API Extensions -Unless otherwise noted, all published artifacts support Java 8 or higher. +Extensions to the OpenTelemetry API. -**Android Disclaimer:** For compatibility reasons, [library desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring) must be enabled. +| Component | Description | Artifact ID | Version | Javadoc | +|---------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------|-------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [Kotlin Extension](./extensions/kotlin) | Context extension for coroutines | `opentelemetry-extension-kotlin` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-kotlin.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-kotlin) | +| [Trace Propagators Extension](./extensions/trace-propagators) | Trace propagators, including B3, Jaeger, OT Trace | `opentelemetry-extension-trace-propagators` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-trace-propagators.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-trace-propagators) | +
-See [CONTRIBUTING.md](./CONTRIBUTING.md) for additional instructions for building this project for development. +
+ SDK -### Note about extensions +The OpenTelemetry SDK for managing telemetry producing by the API. -Both API and SDK extensions consist of various additional components which are excluded from the core artifacts -to keep them from growing too large. +| Component | Description | Artifact ID | Version | Javadoc | +|------------------------------|--------------------------------------------------------|-----------------------------|---------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [SDK](./sdk/all) | OpenTelemetry SDK, including metrics, traces, and logs | `opentelemetry-sdk` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk) | +| [Metrics SDK](./sdk/metrics) | OpenTelemetry metrics SDK | `opentelemetry-sdk-metrics` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-metrics.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-metrics) | +| [Trace SDK](./sdk/trace) | OpenTelemetry trace SDK | `opentelemetry-sdk-trace` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-trace.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-trace) | +| [Log SDK](./sdk/logs) | OpenTelemetry log SDK | `opentelemetry-sdk-logs` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-logs.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-logs) | +| [Profiles SDK](./sdk/profiles) | OpenTelemetry profiles SDK | `opentelemetry-sdk-profiles` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-profiles.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-profiles) | +| [SDK Common](./sdk/common) | Shared SDK components | `opentelemetry-sdk-common` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-common.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-common) | +| [SDK Testing](./sdk/testing) | Components for testing OpenTelemetry instrumentation | `opentelemetry-sdk-testing` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-testing.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-testing) | +
-We still aim to provide the same level of quality and guarantee for them as for the core components. -Please don't hesitate to use them if you find them useful. +
+ SDK Exporters -## Project setup and contributing +SDK exporters for shipping traces, metrics, and logs out of process. -Please refer to the [contribution guide](CONTRIBUTING.md) on how to set up for development and contribute! +| Component | Description | Artifact ID | Version | Javadoc | +|-----------------------------------------------------------------------|------------------------------------------------------------------------------|------------------------------------------------------|-------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [OTLP Exporters](./exporters/otlp/all) | OTLP gRPC & HTTP exporters, including traces, metrics, and logs | `opentelemetry-exporter-otlp` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp) | +| [OTLP Profiles Exporter](./exporters/otlp/profiles) | OTLP profiles exporter | `opentelemetry-exporter-otlp-profiles` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-profiles.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-profiles) | +| [OTLP Logging Exporters](./exporters/logging-otlp) | Logging exporters in OTLP JSON encoding, including traces, metrics, and logs | `opentelemetry-exporter-logging-otlp` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-logging-otlp.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-logging-otlp) | +| [OTLP Common](./exporters/otlp/common) | Shared OTLP components (internal) | `opentelemetry-exporter-otlp-common` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-common.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-common) | +| [Logging Exporter](./exporters/logging) | Logging exporters, including metrics, traces, and logs | `opentelemetry-exporter-logging` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-logging.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-logging) | +| [Prometheus Exporter](./exporters/prometheus) | Prometheus metric exporter | `opentelemetry-exporter-prometheus` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-prometheus.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-prometheus) | +| [Exporter Common](./exporters/common) | Shared exporter components (internal) | `opentelemetry-exporter-common` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-common.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-common) | +| [OkHttp Sender](./exporters/sender/okhttp) | OkHttp implementation of HttpSender (internal) | `opentelemetry-exporter-sender-okhttp` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-sender-okhttp.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-sender-okhttp) | +| [JDK Sender](./exporters/sender/jdk) | Java 11+ native HttpClient implementation of HttpSender (internal) | `opentelemetry-exporter-sender-jdk` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-sender-jdk.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-sender-jdk) | | +| [gRPC ManagedChannel Sender](./exporters/sender/grpc-managed-channel) | gRPC ManagedChannel implementation of GrpcSender (internal) | `opentelemetry-exporter-sender-grpc-managed-channel` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-sender-grpc-managed-channel.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-sender-grpc-managed-channel) | | +
-## Published Releases +
+ SDK Extensions -Published releases are available on maven central. We strongly recommend using our published BOM to keep all -dependency versions in sync. +Extensions to the OpenTelemetry SDK. -### Maven +| Component | Description | Artifact ID | Version | Javadoc | +|-------------------------------------------------------------------------------|------------------------------------------------------------------------------------|-----------------------------------------------------|-------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [SDK Autoconfigure](./sdk-extensions/autoconfigure) | Autoconfigure OpenTelemetry SDK from env vars, system properties, and SPI | `opentelemetry-sdk-extension-autoconfigure` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure) | +| [SDK Autoconfigure SPI](./sdk-extensions/autoconfigure-spi) | Service Provider Interface (SPI) definitions for autoconfigure | `opentelemetry-sdk-extension-autoconfigure-spi` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure-spi.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure-spi) | +| [SDK Declarative Config](./sdk-extensions/declarative-config) | Declarative config implementation for YAML-based SDK configuration | `opentelemetry-sdk-extension-declarative-config` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-declarative-config.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-declarative-config) | +| [SDK Declarative Config Jackson 2 Mapper](./sdk-extensions/declarative-config-jackson2) | Jackson 2 model mapper for declarative config | `opentelemetry-sdk-extension-declarative-config-jackson2` | TODO | TODO | +| [SDK Declarative Config SnakeYAML Engine 2 Parser](./sdk-extensions/declarative-config-snakeyaml-engine2) | SnakeYAML Engine 2 YAML parser for declarative config | `opentelemetry-sdk-extension-declarative-config-snakeyaml-engine2` | TODO | TODO | +| [SDK Jaeger Remote Sampler Extension](./sdk-extensions/jaeger-remote-sampler) | Sampler which obtains sampling configuration from remote Jaeger server | `opentelemetry-sdk-extension-jaeger-remote-sampler` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-jaeger-remote-sampler.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-jaeger-remote-sampler) | +| [SDK Incubator](./sdk-extensions/incubator) | SDK incubator, including YAML based view configuration, LeakDetectingSpanProcessor | `opentelemetry-sdk-extension-incubator` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-incubator.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-incubator) | +
-```xml - - - - - io.opentelemetry - opentelemetry-bom - 1.14.0 - pom - import - - - - - - io.opentelemetry - opentelemetry-api - - - -``` +
+ Shims -### Gradle +Shims for bridging data from one observability library to another. + +| Component | Description | Artifact ID | Version | Javadoc | +|----------------------------------------|--------------------------------------------------------------|----------------------------------|-------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| [OpenCensus Shim](./opencensus-shim) | **DEPRECATED** Bridge opencensus metrics into the OpenTelemetry metrics SDK | `opentelemetry-opencensus-shim` | 1.68.0-alpha | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-opencensus-shim.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-opencensus-shim) | +| [OpenTracing Shim](./opentracing-shim) | **DEPRECATED** Bridge opentracing spans into the OpenTelemetry trace API | `opentelemetry-opentracing-shim` | 1.68.0 | [![Javadocs](https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-opentracing-shim.svg)](https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-opentracing-shim) | +
+ +### Verifying Artifacts + +All artifacts published to Maven Central are signed with GPG key [`17A27CE7A60FF5F0`](https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x17A27CE7A60FF5F0) (fingerprint: `3F05 DDA9 F317 301E 9271 36D4 17A2 7CE7 A60F F5F0`). + +## Dependencies + +To take a dependency, [include a BOM][dependencies-and-boms] and specify the dependency as follows, +replacing `{{artifact-id}}` with the value from the "Artifact ID" column +from [artifacts](#artifacts): + +
+ Gradle ```groovy -dependencies { - implementation platform("io.opentelemetry:opentelemetry-bom:1.14.0") - implementation('io.opentelemetry:opentelemetry-api') -} + implementation('io.opentelemetry:{{artifact-id}}') ``` +
-Note that if you want to use any artifacts that have not fully stabilized yet (such as metrics), then you will need to add an entry for the Alpha BOM as well, e.g. +
+ Maven + +```xml + + io.opentelemetry + {{artifact-id}} + +``` +
+ +### Snapshots + +Snapshots of the `main` branch are available as follows: + +
+ Gradle ```groovy -dependencies { - implementation platform("io.opentelemetry:opentelemetry-bom:1.14.0") - implementation platform('io.opentelemetry:opentelemetry-bom-alpha:1.14.0-alpha') +repositories { + maven { url 'https://central.sonatype.com/repository/maven-snapshots/' } +} +dependencies { + implementation platform("io.opentelemetry:opentelemetry-bom:1.69.0-SNAPSHOT") implementation('io.opentelemetry:opentelemetry-api') - implementation('io.opentelemetry:opentelemetry-api-metrics') } ``` +
-## Snapshots - -Snapshots based out the `main` branch are available for `opentelemetry-api`, `opentelemetry-sdk` and the rest of the artifacts. -We strongly recommend using our published BOM to keep all dependency versions in sync. - -### Maven +
+ Maven ```xml - - - - oss.sonatype.org-snapshot - https://oss.sonatype.org/content/repositories/snapshots - - - + + + + sonatype-snapshot-repository + https://central.sonatype.com/repository/maven-snapshots/ + + + + + + io.opentelemetry + opentelemetry-bom + 1.69.0-SNAPSHOT + pom + import + + + io.opentelemetry - opentelemetry-bom - 1.15.0-SNAPSHOT - pom - import + opentelemetry-api - - - - io.opentelemetry - opentelemetry-api - - - + ``` +
-### Gradle +## Compatibility -```groovy -repositories { - maven { url 'https://oss.sonatype.org/content/repositories/snapshots' } -} +Artifacts from this repository follow semantic versioning. -dependencies { - implementation platform("io.opentelemetry:opentelemetry-bom:1.15.0-SNAPSHOT") - implementation('io.opentelemetry:opentelemetry-api') -} -``` +Stable artifacts (i.e. artifacts without `-alpha` version suffix) come with strong backwards +compatibility guarantees for public APIs. + +Artifacts may depend on other artifacts from this repository, and may depend on internal APIs (i.e. +non-public APIs) which are subject to change across minor versions. Therefore, it's critical to keep +artifact versions in sync in order to avoid possible runtime exceptions. We strongly +recommend [using one of our BOMs][dependencies-and-boms] to assist in keeping artifacts in sync. -Libraries will usually only need `opentelemetry-api`, while applications -will want to use the `opentelemetry-sdk` module which contains our standard implementation -of the APIs. +See the [VERSIONING.md](VERSIONING.md) for complete details on compatibility policy. -## Gradle composite builds +## Contacting us -For opentelemetry-java developers that need to test the latest source code with another -project, composite builds can be used as an alternative to `publishToMavenLocal`. This -requires some setup which is explained [here](CONTRIBUTING.md#composing-builds). +We hold regular meetings. See details at [community page](https://github.com/open-telemetry/community#implementation-sigs). -## Releases +The meeting is open for all to join. We invite everyone to join our meeting, +regardless of your experience level. Whether you're a seasoned OpenTelemetry +developer, just starting your journey, or simply curious about the work we do, +you're more than welcome to participate! + +To report a bug, or request a new feature, +please [open an issue](https://github.com/open-telemetry/opentelemetry-java/issues/new/choose). + +We use [GitHub Discussions](https://github.com/open-telemetry/opentelemetry-java/discussions) +for support or general questions. Feel free to drop us a line. -See the [VERSIONING.md](VERSIONING.md) document for our policies for releases and compatibility -guarantees. +We are also present in the [`#otel-java`](https://cloud-native.slack.com/archives/C014L2KCTE3) channel in the [CNCF slack](https://slack.cncf.io/). +Please join us for more informal discussions. -Check out information about the [latest release](https://github.com/open-telemetry/opentelemetry-java/releases). +## Contributing -See the project [milestones](https://github.com/open-telemetry/opentelemetry-java/milestones) -for details on upcoming releases. The dates and features described in issues -and milestones are estimates, and subject to change. +See [CONTRIBUTING.md](CONTRIBUTING.md) for: -The following tables describe the artifacts published by this project. To take a dependency, follow -the instructions in [Published Released](#published-releases) to include the BOM, and specify the -dependency as follows, replacing `{{artifact-id}}` with the value from the "Artifact ID" column: +* Details on building locally +* Project scope +* Keys to successful PRs +* Guide to using gradle composite builds -```xml - - io.opentelemetry - {{artifact-id}} - -``` +### Maintainers -```groovy - implementation('io.opentelemetry:{{artifact-id}}') -``` +- [Jack Berg](https://github.com/jack-berg), Grafana Labs +- [John Watson](https://github.com/jkwatson), Sublime Security -### Bill of Material - -| Component | Description | Artifact ID | Version | -|----------------------------------------------|----------------------------------------|---------------------------|-------------------------------------------------------------| -| [Bill of Materials (BOM)](./bom) | Bill of materials for stable artifacts | `opentelemetry-bom` | 1.14.0 | -| [Alpha Bill of Materials (BOM)](./bom-alpha) | Bill of materials for alpha artifacts | `opentelemetry-bom-alpha` | 1.14.0-alpha | - -### API - -| Component | Description | Artifact ID | Version | -|-----------------------------------|----------------------------------------------------------------|-------------------------|-------------------------------------------------------------| -| [API](./api/all) | OpenTelemetry API, including metrics, traces, baggage, context | `opentelemetry-api` | 1.14.0 | -| [Context API](./context) | OpenTelemetry context API | `opentelemetry-context` | 1.14.0 | -| [Semantic Conventions](./semconv) | Generated code for OpenTelemetry semantic conventions | `opentelemetry-semconv` | 1.14.0-alpha | - -### API Extensions - -| Component | Description | Artifact ID | Version | -|---------------------------------------------------------------|--------------------------------------------------------------------------------|---------------------------------------------|-------------------------------------------------------------| -| [Annotations Extension](./extensions/annotations) | Instrumentation annotations, used in conjunction with OpenTelemetry java agent | `opentelemetry-extension-annotations` | 1.14.0 | -| [AWS Extension](./extensions/aws) | AWS Xray propagator | `opentelemetry-extension-aws` | 1.14.0 | -| [Kotlin Extension](./extensions/kotlin) | Context extension for coroutines | `opentelemetry-extension-kotlin` | 1.14.0 | -| [Trace Propagators Extension](./extensions/trace-propagators) | Trace propagators, including B3, Jaeger, OT Trace | `opentelemetry-extension-trace-propagators` | 1.14.0 | -| [Incubator Extension](./extensions/incubator) | API incubator, including pass through propagator, and extended tracer | `opentelemetry-extension-incubator` | 1.14.0-alpha | -| [Noop API Extension](./extensions/noop-api) | A noop OpenTelemetry implementation which ignores context | `opentelemetry-extension-noop-api` | 1.14.0-alpha | - -### SDK - -| Component | Description | Artifact ID | Version | -|----------------------------------------|--------------------------------------------------------|----------------------------------|-------------------------------------------------------------| -| [SDK](./sdk/all) | OpenTelemetry SDK, including metrics, traces, and logs | `opentelemetry-sdk` | 1.14.0 | -| [Metrics SDK](./sdk/metrics) | OpenTelemetry metrics SDK | `opentelemetry-sdk-metrics` | 1.14.0 | -| [Trace SDK](./sdk/trace) | OpenTelemetry trace SDK | `opentelemetry-sdk-trace` | 1.14.0 | -| [Log SDK](./sdk/logs) | OpenTelemetry log SDK | `opentelemetry-sdk-logs` | 1.14.0-alpha | -| [SDK Common](./sdk/common) | Shared SDK components | `opentelemetry-sdk-common` | 1.14.0 | -| [SDK Testing](./sdk/testing) | Components for testing OpenTelemetry instrumentation | `opentelemetry-sdk-testing` | 1.14.0 | -| [SDK Logs Testing](./sdk/logs-testing) | Components for testing OpenTelemetry logs | `opentelemetry-sdk-logs-testing` | 1.14.0-alpha | - -### SDK Exporters - -| Component | Description | Artifact ID | Version | -|-------------------------------------------------------------|-------------------------------------------------------------------------------------|--------------------------------------------|-------------------------------------------------------------| -| [OTLP gRPC Exporter](./exporters/otlp/all) | OTLP gRPC exporters, including metrics and trace | `opentelemetry-exporter-otlp` | 1.14.0 | -| [OTLP gRPC Trace Exporter](./exporters/otlp/trace) | OTLP gRPC trace exporter | `opentelemetry-exporter-otlp-trace` | 1.14.0 | -| [OTLP gRPC Metrics Exporter](./exporters/otlp/metrics) | OTLP gRPC metrics exporter | `opentelemetry-exporter-otlp-metrics` | 1.14.0 | -| [OTLP gRPC Logs Exporter](./exporters/otlp/logs) | OTLP gRPC log exporter | `opentelemetry-exporter-otlp-logs` | 1.14.0-alpha | -| [OTLP HTTP Trace Exporter](./exporters/otlp-http/trace) | OTLP http/protobuf trace exporter | `opentelemetry-exporter-otlp-http-trace` | 1.14.0 | -| [OTLP HTTP Metrics Exporter](./exporters/otlp-http/metrics) | OTLP http/protobuf metrics exporter | `opentelemetry-exporter-otlp-http-metrics` | 1.14.0 | -| [OTLP HTTP Logs Exporter](./exporters/otlp-http/logs) | OTLP http/protobuf logs exporter | `opentelemetry-exporter-otlp-http-logs` | 1.14.0-alpha | -| [OTLP Common](./exporters/otlp/common) | Shared OTLP components (internal) | `opentelemetry-exporter-otlp-common` | 1.14.0 | -| [Jaeger gRPC Exporter](./exporters/jaeger) | Jaeger gRPC trace exporter | `opentelemetry-exporter-jaeger` | 1.14.0 | -| [Jaeger Thrift Exporter](./exporters/jaeger-thrift) | Jaeger thrift trace exporter | `opentelemetry-exporter-jaeger-thift` | 1.14.0 | -| [Jaeger Proto](./exporters/jaeger-proto) | Jaeger gRPC protobuf definitions (internal) | `opentelemetry-exporter-jaeger-proto` | 1.14.0 | -| [Logging Exporter](./exporters/logging) | Logging exporters, includings metrics, traces, and logs | `opentelemetry-exporter-logging` | 1.14.0 | -| [OTLP Logging Exporter](./exporters/logging-otlp) | Logging exporters in OTLP protobuf JSON format, including metrics, traces, and logs | `opentelemetry-exporter-logging-otlp` | 1.14.0 | -| [Zipkin Exporter](./exporters/zipkin) | Zipkin trace exporter | `opentelemetry-exporter-zipkin` | 1.14.0 | -| [Prometheus Exporter](./exporters/prometheus) | Prometheus metric exporter | `opentelemetry-exporter-prometheus` | 1.14.0-alpha | - -### SDK Extensions - -| Component | Description | Artifact ID | Version | -|-------------------------------------------------------------------------------|---------------------------------------------------------------------------|-----------------------------------------------------|-------------------------------------------------------------| -| [SDK Autoconfigure Extension](./sdk-extensions/autoconfigure) | Autoconfigure OpenTelemetry SDK from env vars, system properties, and SPI | `opentelemetry-sdk-extension-autoconfigure` | 1.14.0-alpha | -| [SDK Autoconfigure SPI](./sdk-extensions/autoconfigure-spi) | Service Provider Interface (SPI) definitions for autoconfigure | `opentelemetry-sdk-extension-autoconfigure-spi` | 1.14.0 | -| [SDK Resources Extension](./sdk-extensions/resources) | Resource providers, including container, host, os, and process | `opentelemetry-sdk-extension-resources` | 1.14.0 | -| [SDK AWS Extension](./sdk-extensions/aws) | AWS resource providers, including beanstalk, ec2, ecs, eks, and lambda | `opentelemetry-sdk-extension-aws` | 1.14.0 | -| [SDK Jaeger Remote Sampler Extension](./sdk-extensions/jaeger-remote-sampler) | Sampler which obtains sampling configuration from remote Jaeger server | `opentelemetry-sdk-extension-jaeger-remote-sampler` | 1.14.0 | -| [SDK JFR Events Extension](./sdk-extensions/jfr-events) | SpanProcessor which records spans as JFR events | `opentelemetry-sdk-extension-jfr-events` | 1.14.0-alpha | -| [SDK Metric Incubator Extension](./sdk-extensions/metric-incubator) | Metrics incubator, including YAML based view configuration | `opentelemetry-sdk-extension-metric-incubator` | 1.14.0-alpha | -| [SDK Tracing Incubator Extension](./sdk-extensions/tracing-incubator) | Trace incubator, including leak detecting SpanProcessor | `opentelemetry-sdk-extension-tracing-incubator` | 1.14.0-alpha | -| [SDK zPages Extension](./sdk-extensions/zpages) | SpanProcessor which exposes spans with zPages | `opentelemetry-sdk-extension-zpages` | 1.14.0-alpha | - -### Shims - -| Component | Description | Artifact ID | Version | -|----------------------------------------|--------------------------------------------------------------|----------------------------------|-------------------------------------------------------------| -| [Micrometer Shim](./micrometer1-shim) | Bridge micrometer metrics into the OpenTelemetry metrics API | `opentelemetry-micrometer1-shim` | 1.14.0-alpha | -| [OpenCensus Shim](./opencensus-shim) | Bridge opencensus metrics into the OpenTelemetry metrics SDK | `opentelemetry-opencensus-shim` | 1.14.0-alpha | -| [OpenTracing Shim](./opentracing-shim) | Bridge opentracing spans into the OpenTelemetry trace API | `opentelemetry-opentracing-shim` | 1.14.0-alpha | +For more information about the maintainer role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#maintainer). -## Contributing +### Approvers + +- [Gregor Zeitlinger](https://github.com/zeitlinger), Grafana Labs +- [Jason Plumb](https://github.com/breedx-splk), Splunk +- [Jay DeLuca](https://github.com/jaydeluca), Grafana Labs +- [Lauri Tulmin](https://github.com/laurit), Splunk +- [Pranav Sharma](https://github.com/psx95), Google +- [Trask Stalnaker](https://github.com/trask), Microsoft -See [CONTRIBUTING.md](CONTRIBUTING.md) +For more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver). -Approvers ([@open-telemetry/java-approvers](https://github.com/orgs/open-telemetry/teams/java-approvers)): +### Triagers -- [Christian NeumΓΌller](https://github.com/Oberon00), Dynatrace -- [Jakub Wach](https://github.com/kubawach), Splunk -- [Josh Suereth](https://github.com/jsuereth), Google +None. -*Find more about the approver role in [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#approver).* +For more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#triager). -Maintainers ([@open-telemetry/java-maintainers](https://github.com/orgs/open-telemetry/teams/java-maintainers)): +### Emeritus -- [Anuraag Agrawal](https://github.com/anuraaga), AWS -- [Jack Berg](https://github.com/jack-berg), New Relic -- [John Watson](https://github.com/jkwatson), Splunk +- [Bogdan Drutu](https://github.com/BogdanDrutu), Maintainer +- [Carlos Alberto](https://github.com/carlosalberto), Maintainer +- [Josh Suereth](https://github.com/jsuereth), Approver +- [Mateusz Rzeszutek](https://github.com/mateuszrzeszutek), Approver -Maintainers Emeritus: +For more information about the emeritus role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager). -- [Bogdan Drutu](https://github.com/BogdanDrutu), Splunk -- [Carlos Alberto](https://github.com/carlosalberto), LightStep +### Help wanted -*Find more about the maintainer role in [community repository](https://github.com/open-telemetry/community/blob/master/community-membership.md#maintainer).* +We are currently resource constrained and are actively seeking new contributors interested in working towards [approver](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver) / [maintainer](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#maintainer) roles. In addition to the documentation for approver / maintainer roles and the [contributing](./CONTRIBUTING.md) guide, here are some additional notes on engaging: -### Thanks to all the people who have contributed +- [Pull request](https://github.com/open-telemetry/opentelemetry-java/pulls) reviews are equally or more helpful than code contributions. Comments and approvals are valuable with or without a formal project role. They're also a great forcing function to explore a fairly complex codebase. +- Attending the [Java: SDK + Automatic Instrumentation](https://github.com/open-telemetry/community?tab=readme-ov-file#implementation-sigs) Special Interest Group (SIG) is a great way to get to know community members and learn about project priorities. +- Issues labeled [help wanted](https://github.com/open-telemetry/opentelemetry-java/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22) are project priorities. Code contributions (or pull request reviews when a PR is linked) for these issues are particularly important. +- Triaging / responding to new issues and discussions is a great way to engage with the project. + +### Thanks to all of our contributors! - + Repo contributors -Made with [contrib.rocks](https://contrib.rocks). - -[ci-image]: https://github.com/open-telemetry/opentelemetry-java/workflows/Continuous%20Build/badge.svg -[ci-url]: https://github.com/open-telemetry/opentelemetry-java/actions?query=workflow%3Aci+branch%3Amain [codecov-image]: https://codecov.io/gh/open-telemetry/opentelemetry-java/branch/main/graph/badge.svg -[codecov-url]: https://codecov.io/gh/open-telemetry/opentelemetry-java/branch/main/ -[Manual instrumentation]: https://opentelemetry.io/docs/java/manual_instrumentation/ -[maven-image]: https://maven-badges.herokuapp.com/maven-central/io.opentelemetry/opentelemetry-api/badge.svg -[maven-url]: https://maven-badges.herokuapp.com/maven-central/io.opentelemetry/opentelemetry-api -[opentelemetry-java-instrumentation]: https://github.com/open-telemetry/opentelemetry-java-instrumentation -[opentelemetry-java-docs]: https://github.com/open-telemetry/opentelemetry-java-docs -[opentelemetry.io]: https://opentelemetry.io +[codecov-url]: https://app.codecov.io/gh/open-telemetry/opentelemetry-java/branch/main/ +[dependencies-and-boms]: https://opentelemetry.io/docs/languages/java/intro/#dependencies-and-boms diff --git a/RELEASING.md b/RELEASING.md index 6e2e0931dcd..bb93f4a7e46 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -1,29 +1,38 @@ # OpenTelemetry Release Process -Before releasing, it is a good idea to run `./gradlew japicmp` on the main branch -and verify that there are no unexpected public API changes seen in the `docs/apidiffs/current_vs_latest` -directory. +Before releasing, it is a good idea to run `./gradlew japicmp` on the main branch and verify that +there are no unexpected public API changes seen in the `docs/apidiffs/current_vs_latest` +directory. Additionally, ensure that appropriate `@since` annotations are added to any additions to +the public APIs. When preparing the change log, you can use -`git log upstream/v$MAJOR.$((MINOR-1)).x..upstream/v$MAJOR.$MINOR.x --graph --first-parent` -or the Github [compare tool](https://github.com/open-telemetry/opentelemetry-java/compare/) -to view a summary of all commits since last release as a reference. +the [draft-change-log-entries.sh](./.github/scripts/draft-change-log-entries.sh) script to assist +with drafting. Alternatively, +use `git log upstream/v$MAJOR.$((MINOR-1)).x..upstream/v$MAJOR.$MINOR.x --graph --first-parent` or +the Github [compare tool](https://github.com/open-telemetry/opentelemetry-java/compare/) to view a +summary of all commits since last release as a reference. + +## Release cadence + +This repository roughly targets monthly minor releases from the `main` branch on the Friday after +the first Monday of the month. ## Preparing a new major or minor release * Close the release milestone if there is one. * Merge a pull request to `main` updating the `CHANGELOG.md`. - * The heading for the release should include the release version but not the release date, e.g. - `## Version 1.9.0 (Unreleased)`. + * The heading for the unreleased entries should be `## Unreleased`. * Run the [Prepare release branch workflow](https://github.com/open-telemetry/opentelemetry-java/actions/workflows/prepare-release-branch.yml). -* Review and merge the two pull requests that it creates - (one is targeted to the release branch and one is targeted to the `main` branch). + * Press the "Run workflow" button, and leave the default branch `main` selected. + * Review and merge the two pull requests that it creates + (one is targeted to the release branch and one is targeted to `main`). ## Preparing a new patch release All patch releases should include only bug-fixes, and must avoid adding/modifying the public APIs. -In general, patch releases are only made for regressions, memory leaks and deadlocks. +In general, patch releases are only made for regressions, security vulnerabilities, memory leaks +and deadlocks. * Backport pull request(s) to the release branch. * Run the [Backport workflow](https://github.com/open-telemetry/opentelemetry-java/actions/workflows/backport.yml). @@ -32,67 +41,57 @@ In general, patch releases are only made for regressions, memory leaks and deadl then click the "Run workflow" button below that. * Review and merge the backport pull request that it generates. * Merge a pull request to the release branch updating the `CHANGELOG.md`. - * The heading for the release should include the release version but not the release date, e.g. - `## Version 1.9.1 (Unreleased)`. + * The heading for the unreleased entries should be `## Unreleased`. * Run the [Prepare patch release workflow](https://github.com/open-telemetry/opentelemetry-java/actions/workflows/prepare-patch-release.yml). * Press the "Run workflow" button, then select the release branch from the dropdown list, e.g. `release/v1.9.x`, and click the "Run workflow" button below that. -* Review and merge the pull request that it creates. + * Review and merge the pull request that it creates for updating the version. ## Making the release -Run the [Release workflow](https://github.com/open-telemetry/opentelemetry-java/actions/workflows/release.yml). - -* Press the "Run workflow" button, then select the release branch from the dropdown list, - e.g. `release/v1.9.x`, and click the "Run workflow" button below that. -* This workflow will publish the artifacts to maven central and will publish a GitHub release - with release notes based on the change log. -* Review and merge the pull request that the release workflow creates against the release branch - which adds the release date to the change log. - -## After the release - -Run the [Merge change log to main workflow](https://github.com/open-telemetry/opentelemetry-java/actions/workflows/merge-change-log-to-main.yml). - -* Press the "Run workflow" button, then select the release branch from the dropdown list, - e.g. `release/v1.9.x`, and click the "Run workflow" button below that. -* This will create a pull request that merges the change log updates from the release branch - back to main. -* Review and merge the pull request that it creates. -* This workflow will fail if there have been conflicting change log updates introduced in main, - in which case you will need to merge the change log updates manually and send your own pull - request against main. - -## Update release versions in documentations - -After releasing is done, you need to first update the docs. This needs to happen after artifacts have propagated -to Maven Central so should probably be done an hour or two after the release workflow finishes. - -``` -./gradlew updateVersionInDocs -Prelease.version=x.y.z -./gradlew japicmp -PapiBaseVersion=a.b.c -PapiNewVersion=x.y.z -./gradlew --refresh-dependencies japicmp -``` - -Where `x.y.z` is the version just released and `a.b.c` is the previous version. - -Create a PR to mark the new release in README.md on the main branch. - -Finally, update the [website docs][] to refer to the newly released version. - -[website docs]: https://github.com/open-telemetry/opentelemetry.io/tree/main/content/en/docs/instrumentation/java +* Run the [Release workflow](https://github.com/open-telemetry/opentelemetry-java/actions/workflows/release.yml). + * Press the "Run workflow" button, then select the release branch from the dropdown list, + e.g. `release/v1.9.x`, and click the "Run workflow" button below that. + * This workflow will publish the artifacts to maven central and will publish a GitHub release + with release notes based on the change log. + * Review and merge the pull request that it creates for updating the change log in main + (note that if this is not a patch release then the change log on main may already be up-to-date, + in which case no pull request will be created). + * Once the release artifacts become available on Maven Central, the system will automatically + generate a new pull request titled `Update apidiff baseline and documentation versions to + released version $VERSION`. This pull request will contain updates to both the API diff baseline + and version references in the documentation files (README.md). Please review and merge this + automated pull request. + * The [website](https://github.com/open-telemetry/opentelemetry.io) contains automation to update + to the newly released version. Review and approve the pull request when available. + * The [website](https://opentelemetry.io/docs/languages/java/configuration/#zero-code-sdk-autoconfigure) + contains documentation on autoconfiguration properties. If the release has updated or modified any + properties, open and merge a pull request to update the documentation. ## Credentials -The following credentials are required for publishing (and automatically set in Circle CI): - -* `GPG_PRIVATE_KEY` and `GPG_PASSWORD`: GPG private key and password for signing - - Note, currently only @anuraaga has this and we need to find a way to safely share secrets in the - OpenTelemetry project, for example with a password manager. In the worst case if you need to - release manually and cannot get a hold of it, you can generate a new key but don't forget to - upload the public key to keyservers. +The following credentials are required for building or publishing (and automatically set in Github Actions): +* `GPG_PRIVATE_KEY` and `GPG_PASSWORD`: GPG private key and password for signing. * `SONATYPE_USER` and `SONATYPE_KEY`: Sonatype username and password. + * Each maintainer will have their own set of Sonotype credentials with permission to publish to + the `io.opentelemetry` group prefix. + * [Register to publish](https://central.sonatype.org/register/central-portal/#publishing) + and ask an existing maintainer to invite you to the OpenTelemetry organization and grant you + access to the `io.opentelemetry` namespace (see + [organization management](https://central.sonatype.org/publish/publish-portal-organizations/)). + * To obtain `SONATYPE_USER` and `SONATYPE_KEY` for your account, log in + to [central.sonatype.com](https://central.sonatype.com/) and navigate to Profile -> View User Tokens + (see [detailed instructions](https://central.sonatype.org/publish/generate-portal-token/)). + +Additionally, credentials are stored with maintainers via +the [OpenTelemetry 1Password](https://opentelemetry.1password.com/signin) account. The following +defines the mapping from Github Action secret keys to 1Password keys: + +| Github Actions Key | 1Password Key | +|--------------------|---------------| +| `GPG_PASSWORD` | `opentelemetry-java GPG_PASSWORD` | +| `GPG_PRIVATE_KEY` | `opentelemetry-java GPG_PRIVATE_KEY` | ## Releasing from the local setup diff --git a/VERSIONING.md b/VERSIONING.md index 3346bad0d36..39587e32229 100644 --- a/VERSIONING.md +++ b/VERSIONING.md @@ -18,7 +18,7 @@ changes are: reordering parameters, adding a method to an interface or abstract class without adding a default implementation. -- ABI changes that could require code using the artifact to be recompiled, but not changed, e.g., +- [ABI](https://wikipedia.org/wiki/Application_binary_interface) changes that could require code using the artifact to be recompiled, but not changed, e.g., changing the return type of a method from `void` to non-`void`, changing a `class` to an `interface`. The [JLS](https://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html) has more information on what constitutes compatible changes. @@ -31,6 +31,17 @@ changes are: Such changes will be avoided - if they must be made, the `MAJOR` version of the artifact will be incremented. +A stable artifact may depend on an `-alpha` artifact, and expose classes, interfaces, enums, etc. of +the `-alpha` artifact as part of its public API. In these cases, the stable artifact will place +an [implementation](https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation) +dependency (as opposed to an api dependency) on the `-alpha` artifact. In order to consume the +portions of the API related to the `-alpha` artifact, a user must place their own implementation +dependency on it. In adding the implementation dependency, the user has opted into to using +an `-alpha` artifact, and we reserve the right to change the portions of the API pertaining to +the `-alpha` artifact. This includes changing the names of methods, return types, argument types, etc. +We will use this technique sparingly and only when there is some significant reduction in friction +by including the `-alpha` artifact. + Backwards incompatible changes to `internal` packages are expected. Versions of published artifacts are expected to be aligned by using BOMs we publish. We will always provide BOMs to allow alignment of versions. @@ -39,11 +50,31 @@ Changes may be made that require changes to the an app's dependency declarations incrementing the version on `MINOR` version updates. For example, code may be separated out to a new artifact which requires adding the new artifact to dependency declarations. +On rare occasions we may deprecate an entire stable artifact, with the intent of stopping functional +changes or enhancements. In these situations we may stop publishing additional `MINOR` or `MAJOR` +versions of the artifact. However, if necessary, we'll publish security fixes via `PATCH` releases. +The API of the last published version will remain stable. + As a user, if you always depend on the latest version of the BOM for a given `MAJOR` version, and you do not use classes in the `internal` package (which you MUST NOT do), you can be assured that your app will always function and have access to the latest features of OpenTelemetry without needing any changes to code. +## Language Version Compatibility + +The artifacts published by this codebase are compatible with certain language levels of tooling in +the Java ecosystem. For example, all artifacts (except where otherwise noted) support Java language +level 8 or higher, and the many artifacts intended to be used in Android environments adhere to a +particular [Android API level](https://developer.android.com/tools/releases/build-tools). The +following table defines the minimum language levels we adhere to, and how each is considered with +respect to semantic versioning. + +| Language | Minimum Version | Applicability | Semconv Notes | +|----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| Java | 8+ | All artifacts, unless otherwise noted | Changing requires major version bump. | +| Android | 23+ (NOTE: [desugaring](https://developer.android.com/studio/write/java8-support#library-desugaring) is required. We stay up to date with the latest version of [desugar_jdk_libs](https://github.com/google/desugar_jdk_libs).) | Artifacts using `otel.animalsniffer-conventions` plugin | Kept in sync with minimum requirements for [Google Play services](https://developers.google.com/android/guides/setup). Subject to change in minor version. | +| Kotlin | 2.2+ | Only applies to `opentelemetry-extension-kotlin` | Kept in sync with [minimum non-deprecated](https://github.com/JetBrains/kotlin/blob/master/libraries/tools/kotlin-gradle-compiler-types/src/generated/kotlin/org/jetbrains/kotlin/gradle/dsl/KotlinVersion.kt) version. Subject to change in minor versions. | + ## API vs SDK This codebase is broadly split into two large pieces, the OpenTelemetry API and the OpenTelemetry SDK, diff --git a/all/build.gradle.kts b/all/build.gradle.kts index cbbf93d7eff..609ca565ced 100644 --- a/all/build.gradle.kts +++ b/all/build.gradle.kts @@ -1,28 +1,22 @@ +import org.gradle.api.JavaVersion + plugins { id("otel.java-conventions") } description = "OpenTelemetry All" otelJava.moduleName.set("io.opentelemetry.all") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) +otelJava.minJavaVersionSupported.set(JavaVersion.VERSION_25) -tasks { - // We don't compile much here, just some API boundary tests. This project is mostly for - // aggregating jacoco reports and it doesn't work if this isn't at least as high as the - // highest supported Java version in any of our projects. Most of our projects target - // Java 8, except for jfr-events. - withType(JavaCompile::class) { - options.release.set(11) - } - - val testJavaVersion: String? by project - if (testJavaVersion == "8") { - test { - enabled = false - } - } +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false } val testTasks = mutableListOf() +val jarTasks = mutableListOf() dependencies { rootProject.subprojects.forEach { subproject -> @@ -35,16 +29,62 @@ dependencies { subproject.tasks.withType().configureEach { testTasks.add(this) } + subproject.tasks.withType().forEach { + if (it.archiveClassifier.get().isEmpty() && !it.name.contains("jmh")) { + jarTasks.add(it) + } + } } } } + testImplementation("com.tngtech.archunit:archunit-junit5") } +// Custom task type for writing artifacts and jars - configuration cache compatible +abstract class WriteArtifactsAndJars : DefaultTask() { + @get:Input + abstract val artifactData: MapProperty + + @get:OutputFile + abstract val outputFile: RegularFileProperty + + @TaskAction + fun writeFile() { + val file = outputFile.get().asFile + file.parentFile.mkdirs() + val content = artifactData.get().entries.joinToString("\n") { (baseName, filePath) -> + "$baseName:$filePath" + } + file.writeText(content) + } +} + +val artifactsAndJarsFile = layout.buildDirectory.file("artifacts_and_jars.txt") + +val writeArtifactsAndJars = tasks.register("writeArtifactsAndJars") { + // Set up task dependencies + dependsOn(jarTasks) + + // Configure the task inputs and outputs using providers + artifactData.set(provider { + jarTasks.associate { jar -> + jar.archiveBaseName.get() to jar.archiveFile.get().asFile.absolutePath + } + }) + outputFile.set(artifactsAndJarsFile) +} + +tasks { + test { + dependsOn(writeArtifactsAndJars) + environment("ARTIFACTS_AND_JARS", artifactsAndJarsFile.get().asFile.absolutePath) + } +} + // https://docs.gradle.org/current/samples/sample_jvm_multi_project_with_code_coverage.html -val sourcesPath by configurations.creating { - isVisible = false +val sourcesPath = configurations.create("sourcesPath") { isCanBeResolved = true isCanBeConsumed = false extendsFrom(configurations.implementation.get()) @@ -55,8 +95,7 @@ val sourcesPath by configurations.creating { } } -val coverageDataPath by configurations.creating { - isVisible = false +val coverageDataPath = configurations.create("coverageDataPath") { isCanBeResolved = true isCanBeConsumed = false extendsFrom(configurations.implementation.get()) @@ -78,15 +117,9 @@ tasks.named("jacocoTestReport") { // Exclude mrjar (jacoco complains), shaded, and generated code !it.absolutePath.contains("META-INF/versions/") && !it.absolutePath.contains("/internal/shaded/") && - !it.absolutePath.contains("io/opentelemetry/proto/") && - !it.absolutePath.contains("io/opentelemetry/exporter/jaeger/proto/") && - !it.absolutePath.contains("io/opentelemetry/exporter/jaeger/internal/protobuf/") && !it.absolutePath.contains("io/opentelemetry/sdk/extension/trace/jaeger/proto/") && - !it.absolutePath.contains("io/opentelemetry/semconv/trace/attributes/") && - !it.absolutePath.contains("AutoValue_") && - // TODO(anuraaga): Remove exclusion after enabling coverage for jfr-events - !it.absolutePath.contains("io/opentelemetry/sdk/extension/jfr") - } + !it.absolutePath.contains("AutoValue_") + }, ) } additionalSourceDirs(sourcesPath.incoming.artifactView { lenient(true) }.files) diff --git a/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java b/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java new file mode 100644 index 00000000000..d89b587a5c0 --- /dev/null +++ b/all/src/test/java/io/opentelemetry/all/NoGuavaTest.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.all; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +import com.tngtech.archunit.core.importer.ClassFileImporter; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.jar.JarFile; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Prevents Guava API usage in published code, even when Guava is available transitively. + * + *

This replaces the narrower Guava beta-API check, whose annotation inspection fails with javac + * 25 and {@code --release 8}. Only published JARs are scanned: tests may use Guava, and transitive + * dependencies are not prohibited. + */ +class NoGuavaTest { + + @ParameterizedTest + @MethodSource("artifactsAndJars") + void noGuavaReferences(String artifactId, String absolutePath) throws IOException { + try (JarFile jarFile = new JarFile(new File(absolutePath))) { + noClasses() + .that() + // futureUnaryCall exposes ListenableFuture. Retain its existing completion semantics. + .doNotBelongToAnyOf(UpstreamGrpcSender.class) + .and() + // Generated into main alongside the test server API; this unused stub returns + // ListenableFuture. Moving generation to test-only sources is a separate cleanup. + .doNotHaveFullyQualifiedName( + "io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2." + + "SamplingManagerGrpc$SamplingManagerFutureStub") + .should() + .dependOnClassesThat() + .resideInAPackage("com.google.common..") + .as(artifactId + " should not reference Guava except in gRPC future adapters") + .check(new ClassFileImporter().importJar(jarFile)); + } + } + + private static Stream artifactsAndJars() throws IOException { + return Files.readAllLines(Path.of(System.getenv("ARTIFACTS_AND_JARS"))).stream() + .map(line -> { + String[] parts = line.split(":", 2); + return Arguments.argumentSet(parts[0], parts[0], parts[1]); + }); + } +} diff --git a/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java b/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java new file mode 100644 index 00000000000..07adde611d9 --- /dev/null +++ b/all/src/test/java/io/opentelemetry/all/NoSharedInternalCodeTest.java @@ -0,0 +1,120 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.all; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; + +import com.tngtech.archunit.base.DescribedPredicate; +import com.tngtech.archunit.core.domain.JavaClass; +import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.lang.syntax.elements.ClassesShouldConjunction; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.jar.JarFile; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@SuppressLogger(NoSharedInternalCodeTest.class) +class NoSharedInternalCodeTest { + + private static final Set exemptions = + Set.of( + "opentelemetry-exporter-common", + "opentelemetry-exporter-logging-otlp", + "opentelemetry-exporter-prometheus", + "opentelemetry-extension-trace-propagators", + "opentelemetry-opencensus-shim", + "opentelemetry-sdk", + "opentelemetry-sdk-logs", + "opentelemetry-sdk-metrics", + "opentelemetry-sdk-testing", + "opentelemetry-sdk-trace", + "opentelemetry-sdk-extension-autoconfigure", + "opentelemetry-sdk-extension-declarative-config", + "opentelemetry-sdk-extension-declarative-config-jackson2", + "opentelemetry-sdk-extension-declarative-config-snakeyaml-engine2", + "opentelemetry-sdk-extension-incubator", + "opentelemetry-sdk-extension-jaeger-remote-sampler", + "opentelemetry-sdk-processcontext", + "opentelemetry-exporter-otlp", + "opentelemetry-exporter-otlp-common", + "opentelemetry-exporter-otlp-profiles", + "opentelemetry-exporter-sender-grpc-managed-channel", + "opentelemetry-exporter-sender-jdk", + "opentelemetry-exporter-sender-okhttp"); + + private static final String OTEL_BASE_PACKAGE = "io.opentelemetry"; + private static final Logger logger = Logger.getLogger(NoSharedInternalCodeTest.class.getName()); + + @ParameterizedTest + @MethodSource("artifactsAndJars") + void noSharedInternalCode(String artifactId, String absolutePath) throws IOException { + try (JarFile jarFile = new JarFile(new File(absolutePath))) { + JavaClasses artifactClasses = new ClassFileImporter().importJar(jarFile); + + Set artifactOtelPackages = + artifactClasses.stream() + .map(JavaClass::getPackageName) + .filter(packageName -> packageName.startsWith(OTEL_BASE_PACKAGE)) + .collect(Collectors.toSet()); + + ClassesShouldConjunction noSharedInternalCodeRule = + noClasses() + .that() + .resideInAnyPackage(artifactOtelPackages.toArray(new String[0])) + .should() + .dependOnClassesThat( + new DescribedPredicate<>( + "are in internal modules of other opentelemetry artifacts") { + @Override + public boolean test(JavaClass javaClass) { + String packageName = javaClass.getPackageName(); + return packageName.startsWith(OTEL_BASE_PACKAGE) + && packageName.contains(".internal") + && !artifactOtelPackages.contains(packageName); + } + }); + + try { + noSharedInternalCodeRule + .as(artifactId + " should not use internal code from other artifacts") + .check(artifactClasses); + // To view artifacts which do not contain shared internal code, change test log level or + // increase log level of this statement to WARNING + logger.log(Level.INFO, artifactId + " does not contain shared internal code"); + } catch (AssertionError e) { + if (exemptions.contains(artifactId)) { + // To view details, remove from exemptions list + logger.log( + Level.WARNING, + artifactId + " contains shared internal code but is temporarily exempt"); + } else { + throw e; + } + } + } + } + + private static Stream artifactsAndJars() throws IOException { + List lines = Files.readAllLines(Path.of(System.getenv("ARTIFACTS_AND_JARS"))); + return lines.stream() + .map(line -> { + String[] parts = line.split(":", 2); + return Arguments.argumentSet(parts[0], parts[0], parts[1]); + }); + } +} diff --git a/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java b/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java new file mode 100644 index 00000000000..01ad07589ef --- /dev/null +++ b/all/src/test/java/io/opentelemetry/all/NullGuardsTest.java @@ -0,0 +1,711 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.all; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.common.impl.ApiUsageLogger; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.classfile.Annotation; +import java.lang.classfile.Attributes; +import java.lang.classfile.ClassFile; +import java.lang.classfile.ClassModel; +import java.lang.classfile.CodeElement; +import java.lang.classfile.Instruction; +import java.lang.classfile.MethodModel; +import java.lang.classfile.Opcode; +import java.lang.classfile.TypeKind; +import java.lang.classfile.instruction.BranchInstruction; +import java.lang.classfile.instruction.InvokeInstruction; +import java.lang.classfile.instruction.LabelTarget; +import java.lang.classfile.instruction.LoadInstruction; +import java.lang.constant.ClassDesc; +import java.lang.constant.MethodTypeDesc; +import java.lang.reflect.AccessFlag; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.ScheduledExecutorService; +import java.util.function.BiConsumer; +import java.util.function.BiFunction; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Structural test that public API entry points guard non-{@code @Nullable} reference parameters + * against {@code null}, per {@code docs/knowledge/api-design.md#null-guards}. + * + *

Each method is classified as either {@code RUNTIME} (needs {@code ApiUsageLogger}-style + * graceful degradation) or {@code FAIL_FAST} (needs {@code Objects.requireNonNull}): + * + *

    + *
  1. Default per artifact: {@code opentelemetry-api*} and {@code opentelemetry-context} default + * to {@code RUNTIME}, everything else to {@code FAIL_FAST}. + *
  2. Structural override: any method that overrides or implements a method declared on a + * supertype whose package starts with {@code io.opentelemetry.api.} or {@code + * io.opentelemetry.context.} is classified {@code RUNTIME}. This picks up SDK implementations + * of runtime API types ({@code SdkSpan}, {@code SdkLongCounter}, ...) without an enumeration. + *
  3. Explicit per-method overrides in {@link #METHOD_STYLE_OVERRIDES} handle config-time methods + * and runtime methods without type-safe fallbacks. + *
+ * + *

Detection is intentionally lenient: it looks for the guard pattern anywhere in the method + * body, not just at the top. This trades a small false-negative rate for far fewer false positives + * while a module is being brought into compliance. + */ +@SuppressLogger(NullGuardsTest.class) +class NullGuardsTest { + + private static final Logger logger = Logger.getLogger(NullGuardsTest.class.getName()); + + private static final String OTEL_BASE_PACKAGE = "io.opentelemetry"; + private static final String EQUALS_DESC = + MethodTypeDesc.of(ClassDesc.ofDescriptor("Z"), ClassDesc.of("java.lang.Object")) + .descriptorString(); + private static final String OBJECT_INTERNAL_NAME = Object.class.getName().replace('.', '/'); + + /** + * Runtime API scope: the artifacts and packages that constitute the runtime instrumentation API. + * Keys are artifact base names; values are the corresponding base packages. Both are matched as + * "equal-to or has-{@code -} / has-{@code .} suffix", so {@code opentelemetry-api} covers {@code + * opentelemetry-api-incubator} and {@code io.opentelemetry.api} covers {@code + * io.opentelemetry.api.trace} etc. + * + *

Methods in these artifacts, and methods anywhere that override methods declared in these + * packages, default to {@code RUNTIME} null-guard semantics. Everything else defaults to {@code + * FAIL_FAST}. + */ + private static final Map RUNTIME_SCOPE = + Map.of( + "opentelemetry-api", "io.opentelemetry.api", + "opentelemetry-context", "io.opentelemetry.context"); + + /** + * Per-method style overrides for config-time methods and runtime methods without type-safe + * fallbacks in runtime-defaulted artifacts. + */ + private static final Map METHOD_STYLE_OVERRIDES = + Map.ofEntries( + Map.entry( + overrideKey(GlobalOpenTelemetry.class, "set", void.class, OpenTelemetry.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(GlobalOpenTelemetry.class, "set", void.class, Supplier.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey( + OpenTelemetry.class, + "propagating", + OpenTelemetry.class, + ContextPropagators.class), + GuardStyle.FAIL_FAST), + // Context wrappers are setup-time adapters. Fail fast rather than defer an NPE until use + // or substitute a noop that could discard application work or return an invalid result. + Map.entry( + overrideKey(Context.class, "taskWrapping", Executor.class, Executor.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey( + Context.class, "taskWrapping", ExecutorService.class, ExecutorService.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey( + Context.class, + "taskWrapping", + ScheduledExecutorService.class, + ScheduledExecutorService.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrap", Executor.class, Executor.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrap", ExecutorService.class, ExecutorService.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey( + Context.class, + "wrap", + ScheduledExecutorService.class, + ScheduledExecutorService.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrap", Runnable.class, Runnable.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrap", Callable.class, Callable.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrapFunction", Function.class, Function.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrapFunction", BiFunction.class, BiFunction.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrapConsumer", Consumer.class, Consumer.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrapConsumer", BiConsumer.class, BiConsumer.class), + GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Context.class, "wrapSupplier", Supplier.class, Supplier.class), + GuardStyle.FAIL_FAST), + // Value.empty() cannot preserve these generic return types. We may reevaluate in future. + Map.entry( + overrideKey(Value.class, "of", Value.class, String.class), GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Value.class, "of", Value.class, byte[].class), GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Value.class, "of", Value.class, Value[].class), GuardStyle.FAIL_FAST), + Map.entry(overrideKey(Value.class, "of", Value.class, List.class), GuardStyle.FAIL_FAST), + Map.entry( + overrideKey(Value.class, "of", Value.class, KeyValue[].class), GuardStyle.FAIL_FAST), + Map.entry(overrideKey(Value.class, "of", Value.class, Map.class), GuardStyle.FAIL_FAST)); + + private static String overrideKey( + Class owner, String name, Class returnType, Class... paramTypes) { + ClassDesc[] params = + Arrays.stream(paramTypes) + .map(type -> ClassDesc.ofDescriptor(type.descriptorString())) + .toArray(ClassDesc[]::new); + return owner.getName().replace('.', '/') + + "#" + + name + + ":" + + MethodTypeDesc.of(ClassDesc.ofDescriptor(returnType.descriptorString()), params) + .descriptorString(); + } + + /** + * Artifacts that have not yet been audited for null-guard compliance. Remove an entry once a + * per-module PR has landed all guards for it. + */ + private static final Set exemptions = + Set.of( + "opentelemetry-api", + "opentelemetry-api-incubator", + "opentelemetry-context", + "opentelemetry-common", + "opentelemetry-exporter-common", + "opentelemetry-exporter-logging", + "opentelemetry-exporter-logging-otlp", + "opentelemetry-exporter-otlp", + "opentelemetry-exporter-otlp-common", + "opentelemetry-exporter-otlp-profiles", + "opentelemetry-exporter-prometheus", + "opentelemetry-exporter-sender-grpc-managed-channel", + "opentelemetry-exporter-sender-jdk", + "opentelemetry-exporter-sender-okhttp", + "opentelemetry-extension-kotlin", + "opentelemetry-extension-trace-propagators", + "opentelemetry-opencensus-shim", + "opentelemetry-opentracing-shim", + "opentelemetry-opentelemetry-jfr-profiles-shim", + "opentelemetry-sdk", + "opentelemetry-sdk-common", + "opentelemetry-sdk-logs", + "opentelemetry-sdk-metrics", + "opentelemetry-sdk-profiles", + "opentelemetry-sdk-testing", + "opentelemetry-sdk-trace", + "opentelemetry-sdk-extension-autoconfigure", + "opentelemetry-sdk-extension-autoconfigure-spi", + "opentelemetry-sdk-extension-declarative-config", + "opentelemetry-sdk-extension-incubator", + "opentelemetry-sdk-extension-jaeger-remote-sampler"); + + enum GuardStyle { + RUNTIME, // ApiUsageLogger + graceful degradation + FAIL_FAST // Objects.requireNonNull + } + + /** Cross-artifact registry loaded once. Key is internal class name (slashes). */ + private static Map classRegistry; + + @BeforeAll + static void loadClassRegistry() throws IOException { + if (classRegistry != null) { + return; + } + Map registry = new HashMap<>(); + for (String[] entry : readArtifactsAndJars()) { + loadJarInto(entry[1], registry); + } + classRegistry = registry; + } + + @ParameterizedTest + @MethodSource("artifactsAndJars") + void nullGuards(String artifactId, String absolutePath) throws IOException { + Map artifactClasses = new LinkedHashMap<>(); + loadJarInto(absolutePath, artifactClasses); + GuardStyle artifactDefault = defaultStyleFor(artifactId); + + List findings = new ArrayList<>(); + for (ClassModel cls : artifactClasses.values()) { + if (!isInAuditablePackage(cls)) { + continue; + } + for (MethodModel method : cls.methods()) { + if (!isMethodPubliclyReachable(cls, method)) { + continue; + } + GuardStyle style = guardStyleFor(cls, method, artifactDefault); + findGuardViolations(cls, method, style, findings); + } + } + + try { + if (!findings.isEmpty()) { + throw new AssertionError( + artifactId + " has null-guard findings:\n" + renderReport(artifactId, findings)); + } + logger.log(Level.INFO, artifactId + " is null-guard compliant"); + } catch (AssertionError e) { + if (exemptions.contains(artifactId)) { + // To view details, remove from exemptions list. + logger.log( + Level.WARNING, artifactId + " has null-guard findings but is temporarily exempt"); + } else { + throw e; + } + } + } + + private static void loadJarInto(String jarPath, Map out) throws IOException { + try (JarFile jar = new JarFile(new File(jarPath))) { + Enumeration entries = jar.entries(); + while (entries.hasMoreElements()) { + JarEntry entry = entries.nextElement(); + String name = entry.getName(); + if (!name.endsWith(".class") || name.startsWith("META-INF/")) { + continue; + } + try (InputStream in = jar.getInputStream(entry)) { + ClassModel model = ClassFile.of().parse(in.readAllBytes()); + out.put(model.thisClass().asInternalName(), model); + } + } + } + } + + private static GuardStyle defaultStyleFor(String artifactId) { + return isRuntimeApiArtifact(artifactId) ? GuardStyle.RUNTIME : GuardStyle.FAIL_FAST; + } + + private static boolean isRuntimeApiArtifact(String artifactId) { + return RUNTIME_SCOPE.keySet().stream() + .anyMatch(base -> artifactId.equals(base) || artifactId.startsWith(base + "-")); + } + + private static boolean isRuntimeApiPackage(String internalName) { + String pkg = packageOf(internalName); + return RUNTIME_SCOPE.values().stream() + .anyMatch(base -> pkg.equals(base) || pkg.startsWith(base + ".")); + } + + private static GuardStyle guardStyleFor( + ClassModel cls, MethodModel method, GuardStyle artifactDefault) { + String key = + cls.thisClass().asInternalName() + + "#" + + method.methodName().stringValue() + + ":" + + method.methodType().stringValue(); + GuardStyle explicit = METHOD_STYLE_OVERRIDES.get(key); + if (explicit != null) { + return explicit; + } + if (overridesRuntimeApiMethod(cls, method)) { + return GuardStyle.RUNTIME; + } + return artifactDefault; + } + + /** + * True iff {@code method} overrides or implements a method with the same name+descriptor declared + * on any supertype whose package is under {@code io.opentelemetry.api.} or {@code + * io.opentelemetry.context.}. Static and private methods cannot override. + */ + private static boolean overridesRuntimeApiMethod(ClassModel cls, MethodModel method) { + if (method.flags().has(AccessFlag.STATIC) || method.flags().has(AccessFlag.PRIVATE)) { + return false; + } + String name = method.methodName().stringValue(); + if ("".equals(name) || "".equals(name)) { + return false; + } + return anySupertypeMatches( + cls, + sup -> + isRuntimeApiPackage(sup.thisClass().asInternalName()) + && declaresMethod(sup, name, method.methodType().stringValue())); + } + + /** + * Walks {@code cls}'s superclass chain and interface graph (not including {@code cls} itself), + * returning true if {@code match} accepts any visited supertype. Cycle-safe. + */ + private static boolean anySupertypeMatches(ClassModel cls, Predicate match) { + Set visited = new LinkedHashSet<>(); + visited.add(cls.thisClass().asInternalName()); + return walkSupertypes(cls, visited, match); + } + + private static boolean walkSupertypes( + ClassModel cls, Set visited, Predicate match) { + if (cls.superclass().isPresent()) { + String superName = cls.superclass().get().asInternalName(); + if (!OBJECT_INTERNAL_NAME.equals(superName) + && visitSupertype(classRegistry.get(superName), visited, match)) { + return true; + } + } + for (var iface : cls.interfaces()) { + if (visitSupertype(classRegistry.get(iface.asInternalName()), visited, match)) { + return true; + } + } + return false; + } + + private static boolean visitSupertype( + ClassModel cls, Set visited, Predicate match) { + if (cls == null || !visited.add(cls.thisClass().asInternalName())) { + return false; + } + if (match.test(cls)) { + return true; + } + return walkSupertypes(cls, visited, match); + } + + private static boolean declaresMethod(ClassModel cls, String name, String desc) { + return cls.methods().stream() + .filter(m -> !m.flags().has(AccessFlag.STATIC) && !m.flags().has(AccessFlag.PRIVATE)) + .anyMatch(m -> + name.equals(m.methodName().stringValue()) && desc.equals(m.methodType().stringValue())); + } + + private static boolean isInAuditablePackage(ClassModel cls) { + if (cls.flags().has(AccessFlag.SYNTHETIC)) { + return false; + } + if (isAutoValueGenerated(cls)) { + return false; + } + return isAuditableOtelPackage(cls.thisClass().asInternalName()); + } + + /** Auto-generated; not editable. */ + private static boolean isAutoValueGenerated(ClassModel cls) { + String name = cls.thisClass().asInternalName(); + int lastSep = Math.max(name.lastIndexOf('/'), name.lastIndexOf('$')); + return name.startsWith("AutoValue_", lastSep + 1); + } + + /** + * True iff a caller in another package can dispatch to this method via some publicly-visible + * reference type. Either (a) the declaring class is itself public, or (b) the method overrides a + * method declared on a public supertype in a non-internal {@code io.opentelemetry.*} package + * (typical for package-private SDK impls of API interfaces like {@code SdkSpan implements Span}). + */ + private static boolean isMethodPubliclyReachable(ClassModel cls, MethodModel method) { + if (!method.flags().has(AccessFlag.PUBLIC) && !method.flags().has(AccessFlag.PROTECTED)) { + return false; + } + if (cls.flags().has(AccessFlag.PUBLIC)) { + return true; + } + if (method.flags().has(AccessFlag.STATIC) || method.flags().has(AccessFlag.PRIVATE)) { + return false; + } + String name = method.methodName().stringValue(); + if ("".equals(name) || "".equals(name)) { + return false; + } + return anySupertypeMatches( + cls, + sup -> + sup.flags().has(AccessFlag.PUBLIC) + && isAuditableOtelPackage(sup.thisClass().asInternalName()) + && declaresMethod(sup, name, method.methodType().stringValue())); + } + + private static boolean isAuditableOtelPackage(String internalName) { + String pkg = packageOf(internalName); + if (!pkg.startsWith(OTEL_BASE_PACKAGE)) { + return false; + } + return !pkg.contains(".internal") && !pkg.endsWith(".impl") && !pkg.contains(".impl."); + } + + private static void findGuardViolations( + ClassModel cls, MethodModel method, GuardStyle style, List findings) { + if (method.flags().has(AccessFlag.ABSTRACT) + || method.flags().has(AccessFlag.SYNTHETIC) + || method.flags().has(AccessFlag.BRIDGE)) { + return; + } + if (isKnownNullAcceptingSignature(method)) { + return; + } + List paramTypes = method.methodTypeSymbol().parameterList(); + if (paramTypes.isEmpty()) { + return; + } + + boolean isStatic = method.flags().has(AccessFlag.STATIC); + int slot = isStatic ? 0 : 1; + for (int i = 0; i < paramTypes.size(); i++) { + ClassDesc pt = paramTypes.get(i); + int paramSlot = slot; + int paramIndex = i; + slot += TypeKind.from(pt).slotSize(); + if (pt.isPrimitive()) { + continue; + } + Consumer report = + msg -> + findings.add( + new Finding( + cls.thisClass().asInternalName(), + method.methodName().stringValue(), + method.methodType().stringValue(), + paramIndex, + msg)); + boolean nullable = isParamNullable(method, paramIndex); + boolean requireNonNullGuard = GuardScanner.hasRequireNonNullGuard(method, paramSlot); + boolean apiUsageLoggerGuard = GuardScanner.hasApiUsageLoggerGuard(method, paramSlot); + + if (nullable) { + if (requireNonNullGuard) { + report.accept("@Nullable but guarded with requireNonNull (contradicts contract)"); + } + continue; + } + + boolean hasAnyGuard = requireNonNullGuard || apiUsageLoggerGuard; + if (!hasAnyGuard) { + report.accept( + style == GuardStyle.RUNTIME + ? "missing ApiUsageLogger.logNullParam guard" + : "missing Objects.requireNonNull guard"); + continue; + } + if (style == GuardStyle.RUNTIME && requireNonNullGuard && !apiUsageLoggerGuard) { + report.accept("wrong style: uses requireNonNull; expected ApiUsageLogger.logNullParam"); + } else if (style == GuardStyle.FAIL_FAST && apiUsageLoggerGuard && !requireNonNullGuard) { + report.accept("wrong style: uses ApiUsageLogger; expected Objects.requireNonNull"); + } + } + } + + private static boolean isKnownNullAcceptingSignature(MethodModel method) { + return "equals".equals(method.methodName().stringValue()) + && EQUALS_DESC.equals(method.methodType().stringValue()); + } + + private static boolean isParamNullable(MethodModel method, int paramIndex) { + return method + .findAttribute(Attributes.runtimeVisibleParameterAnnotations()) + .map(a -> containsNullable(a.parameterAnnotations(), paramIndex)) + .orElse(false) + || method + .findAttribute(Attributes.runtimeInvisibleParameterAnnotations()) + .map(a -> containsNullable(a.parameterAnnotations(), paramIndex)) + .orElse(false); + } + + private static boolean containsNullable(List> paramAnnos, int paramIndex) { + return paramIndex < paramAnnos.size() + && paramAnnos.get(paramIndex).stream() + .anyMatch(a -> a.className().stringValue().endsWith("/Nullable;")); + } + + /** Bytecode-level detection of the two null-guard shapes on a given parameter slot. */ + private static final class GuardScanner { + + private static final ClassDesc OBJECTS = ClassDesc.of(Objects.class.getName()); + private static final ClassDesc API_USAGE_LOGGER = ClassDesc.of(ApiUsageLogger.class.getName()); + + private GuardScanner() {} + + /** True iff {@code paramSlot} is passed as the first arg to {@code Objects.requireNonNull}. */ + static boolean hasRequireNonNullGuard(MethodModel method, int paramSlot) { + List instructions = + method.code().stream() + .flatMap(code -> code.elementStream()) + .filter(Instruction.class::isInstance) + .map(Instruction.class::cast) + .toList(); + for (int i = 0; i < instructions.size(); i++) { + if (!(instructions.get(i) instanceof InvokeInstruction invoke) + || invoke.opcode() != Opcode.INVOKESTATIC + || !invoke.owner().matches(OBJECTS) + || !"requireNonNull".equals(invoke.name().stringValue())) { + continue; + } + // Skip the trailing message argument for two-argument overloads. + int argumentIndex = i - invoke.typeSymbol().parameterCount(); + if (argumentIndex >= 0 && isReferenceLoad(instructions.get(argumentIndex), paramSlot)) { + return true; + } + } + return false; + } + + /** + * True iff the method contains {@code if (paramSlot == null) { ... ApiUsageLogger.log*(...); + * ...; return; }}: an {@code IFNONNULL} on the param whose fall-through branch contains a call + * to {@code ApiUsageLogger} before the jump target. + */ + static boolean hasApiUsageLoggerGuard(MethodModel method, int paramSlot) { + List elements = + method.code().stream().flatMap(code -> code.elementStream()).toList(); + for (int i = 0; i < elements.size(); i++) { + if (!isReferenceLoad(elements.get(i), paramSlot)) { + continue; + } + int next = i + 1; + while (next < elements.size() && !(elements.get(next) instanceof Instruction)) { + next++; + } + if (next >= elements.size() + || !(elements.get(next) instanceof BranchInstruction jump) + || jump.opcode() != Opcode.IFNONNULL) { + continue; + } + for (int cursor = next + 1; cursor < elements.size(); cursor++) { + CodeElement element = elements.get(cursor); + if (element instanceof LabelTarget target && target.label().equals(jump.target())) { + break; + } + if (element instanceof InvokeInstruction invoke + && invoke.owner().matches(API_USAGE_LOGGER)) { + return true; + } + } + } + return false; + } + + private static boolean isReferenceLoad(CodeElement element, int paramSlot) { + return element instanceof LoadInstruction load + && load.typeKind() == TypeKind.REFERENCE + && load.slot() == paramSlot; + } + } + + private static String renderReport(String artifactId, List findings) { + Map> byClass = + findings.stream() + .collect( + Collectors.groupingBy(f -> f.className, LinkedHashMap::new, Collectors.toList())); + StringBuilder sb = new StringBuilder(); + sb.append("Artifact: ") + .append(artifactId) + .append(" (") + .append(findings.size()) + .append(" findings)\n"); + for (Map.Entry> e : byClass.entrySet()) { + sb.append(" ").append(e.getKey().replace('/', '.')).append('\n'); + for (Finding f : e.getValue()) { + sb.append(" ") + .append(f.methodName) + .append(prettyParams(f.methodDesc)) + .append(" param #") + .append(f.paramIndex) + .append(" (") + .append(prettyParamType(f.methodDesc, f.paramIndex)) + .append("): ") + .append(f.message) + .append('\n'); + } + } + return sb.toString(); + } + + private static String prettyParams(String methodDesc) { + return MethodTypeDesc.ofDescriptor(methodDesc).parameterList().stream() + .map(ClassDesc::displayName) + .collect(Collectors.joining(", ", "(", ")")); + } + + private static String prettyParamType(String methodDesc, int paramIndex) { + MethodTypeDesc type = MethodTypeDesc.ofDescriptor(methodDesc); + if (paramIndex < 0 || paramIndex >= type.parameterCount()) { + return "?"; + } + return type.parameterType(paramIndex).displayName(); + } + + private static String packageOf(String internalName) { + int slash = internalName.lastIndexOf('/'); + return slash < 0 ? "" : internalName.substring(0, slash).replace('/', '.'); + } + + private static List readArtifactsAndJars() throws IOException { + List lines = Files.readAllLines(Path.of(System.getenv("ARTIFACTS_AND_JARS"))); + List out = new ArrayList<>(); + for (String line : lines) { + out.add(line.split(":", 2)); + } + return out; + } + + private static Stream artifactsAndJars() throws IOException { + return readArtifactsAndJars().stream() + .map(parts -> Arguments.argumentSet(parts[0], parts[0], parts[1])); + } + + private static final class Finding { + final String className; + final String methodName; + final String methodDesc; + final int paramIndex; + final String message; + + Finding( + String className, String methodName, String methodDesc, int paramIndex, String message) { + this.className = className; + this.methodName = methodName; + this.methodDesc = methodDesc; + this.paramIndex = paramIndex; + this.message = message; + } + } +} diff --git a/all/src/test/java/io/opentelemetry/all/OsgiServiceLoaderManifestTest.java b/all/src/test/java/io/opentelemetry/all/OsgiServiceLoaderManifestTest.java new file mode 100644 index 00000000000..6d67ee67101 --- /dev/null +++ b/all/src/test/java/io/opentelemetry/all/OsgiServiceLoaderManifestTest.java @@ -0,0 +1,117 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.all; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import org.junit.jupiter.api.Test; + +/** + * Verifies that every OSGi bundle whose {@code META-INF/services/} directory registers SPI + * implementations also declares the corresponding {@code Provide-Capability: + * osgi.serviceloader;osgi.serviceloader=""} in its manifest. + */ +class OsgiServiceLoaderManifestTest { + + @Test + void allOsgiBundlesAdvertiseTheirServiceLoaderRegistrations() throws IOException { + List lines = Files.readAllLines(Path.of(System.getenv("ARTIFACTS_AND_JARS"))); + // violations: ": META-INF/services/ not in Provide-Capability" + List violations = new ArrayList<>(); + + for (String line : lines) { + String[] parts = line.split(":", 2); + String baseName = parts[0]; + String absolutePath = parts[1]; + + try (JarFile jar = new JarFile(new File(absolutePath))) { + Manifest manifest = jar.getManifest(); + if (manifest == null) { + continue; + } + Attributes mainAttrs = manifest.getMainAttributes(); + + // Only check OSGi bundles. + String bundleManifestVersion = mainAttrs.getValue("Bundle-ManifestVersion"); + if (bundleManifestVersion == null) { + continue; + } + + // Collect all SPI interface names from META-INF/services/. + List registeredSpis = new ArrayList<>(); + jar.stream() + .map(JarEntry::getName) + .filter(name -> name.startsWith("META-INF/services/") && !name.endsWith("/")) + .forEach(name -> registeredSpis.add(name.substring("META-INF/services/".length()))); + + if (registeredSpis.isEmpty()) { + continue; + } + + // Parse Provide-Capability for osgi.serviceloader entries. + String provideCapability = mainAttrs.getValue("Provide-Capability"); + List advertisedSpis = parseOsgiServiceLoaderCapabilities(provideCapability); + + for (String spi : registeredSpis) { + if (!advertisedSpis.contains(spi)) { + violations.add(baseName + ": META-INF/services/" + spi + " not in Provide-Capability"); + } + } + } + } + + assertThat(violations) + .as( + "OSGi bundles with META-INF/services registrations missing from Provide-Capability.\n" + + "Add the missing SPI to osgiServiceLoaderProvides in the module's build.gradle.kts.") + .isEmpty(); + } + + /** + * Parses the {@code Provide-Capability} manifest header and returns all {@code + * osgi.serviceloader} service type names. + * + *

Example: {@code osgi.serviceloader;osgi.serviceloader="com.example.Foo", + * osgi.serviceloader;osgi.serviceloader="com.example.Bar"} β†’ {@code ["com.example.Foo", + * "com.example.Bar"]} + */ + private static List parseOsgiServiceLoaderCapabilities(String provideCapability) { + List result = new ArrayList<>(); + if (provideCapability == null || provideCapability.isEmpty()) { + return result; + } + // JarFile already unfolds line-folded headers. Split into individual capability clauses + // on commas immediately followed by an OSGi namespace (osgi.*). + String[] clauses = provideCapability.split(",(?=\\s*osgi\\.)"); + for (String clause : clauses) { + clause = clause.trim(); + if (!clause.startsWith("osgi.serviceloader")) { + continue; + } + // Extract osgi.serviceloader="" + int eq = clause.indexOf("osgi.serviceloader=\""); + if (eq < 0) { + continue; + } + int start = eq + "osgi.serviceloader=\"".length(); + int end = clause.indexOf('"', start); + if (end > start) { + result.add(clause.substring(start, end)); + } + } + return result; + } +} diff --git a/all/src/test/java/io/opentelemetry/all/SdkDesignTest.java b/all/src/test/java/io/opentelemetry/all/SdkDesignTest.java index 4fc4d37da2f..fe2fb0045ea 100644 --- a/all/src/test/java/io/opentelemetry/all/SdkDesignTest.java +++ b/all/src/test/java/io/opentelemetry/all/SdkDesignTest.java @@ -6,17 +6,17 @@ package io.opentelemetry.all; import com.tngtech.archunit.base.DescribedPredicate; -import com.tngtech.archunit.base.Optional; -import com.tngtech.archunit.base.PackageMatcher; import com.tngtech.archunit.core.domain.JavaClass; import com.tngtech.archunit.core.domain.JavaClasses; import com.tngtech.archunit.core.domain.JavaMethod; +import com.tngtech.archunit.core.domain.PackageMatcher; import com.tngtech.archunit.core.importer.ClassFileImporter; import com.tngtech.archunit.lang.syntax.ArchRuleDefinition; import com.tngtech.archunit.lang.syntax.elements.MethodsShouldConjunction; import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Optional; import org.junit.jupiter.api.Test; class SdkDesignTest { @@ -28,7 +28,7 @@ class SdkDesignTest { * Ensures that all SDK methods that: - are defined in classes that extend or implement API model * and are public (to exclude protected builders) - are public (avoids issues with protected * methods returning classes unavailable to test's CL) - override or implement parent method - * return only API, Context or generic Java type. + * return only API, Context, Common, or generic Java type. */ @Test void sdkImplementationOfApiClassesShouldReturnApiTypeOnly() { @@ -45,7 +45,11 @@ void sdkImplementationOfApiClassesShouldReturnApiTypeOnly() { .and(implementOrOverride()) .should() .haveRawReturnType( - inPackage("io.opentelemetry.api..", "io.opentelemetry.context..", "java..")) + inPackage( + "io.opentelemetry.api..", + "io.opentelemetry.context..", + "io.opentelemetry.common..", + "java..")) .orShould() .haveRawReturnType("void"); @@ -53,9 +57,9 @@ void sdkImplementationOfApiClassesShouldReturnApiTypeOnly() { } static DescribedPredicate implementOrOverride() { - return new DescribedPredicate<>("implement or override a method") { + return new DescribedPredicate("implement or override a method") { @Override - public boolean apply(JavaMethod input) { + public boolean test(JavaMethod input) { List params = input.getRawParameterTypes(); Class[] paramsType = new Class[params.size()]; for (int i = 0, n = params.size(); i < n; i++) { @@ -78,9 +82,9 @@ public boolean apply(JavaMethod input) { } static DescribedPredicate inPackage(String... requiredPackages) { - return new DescribedPredicate<>("are in " + Arrays.toString(requiredPackages)) { + return new DescribedPredicate("are in " + Arrays.toString(requiredPackages)) { @Override - public boolean apply(JavaClass member) { + public boolean test(JavaClass member) { for (String requiredPackage : requiredPackages) { if (PackageMatcher.of(requiredPackage).matches(member.getPackageName())) { return true; diff --git a/all/src/test/java/io/opentelemetry/extension/noopapi/NoopOpenTelemetryTest.java b/all/src/test/java/io/opentelemetry/extension/noopapi/NoopOpenTelemetryTest.java deleted file mode 100644 index 422373a9878..00000000000 --- a/all/src/test/java/io/opentelemetry/extension/noopapi/NoopOpenTelemetryTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.noopapi; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanBuilder; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.Scope; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class NoopOpenTelemetryTest { - - private static final SpanContext SPAN_CONTEXT = - SpanContext.create( - "00000000000000000000000000000061", - "0000000000000061", - TraceFlags.getDefault(), - TraceState.getDefault()); - - @Test - void contextNoOp() { - // Context.root() is not a no-op Context, so the default context is never root. - Context context = Context.current(); - assertThat(context).isNotSameAs(Context.root()); - // No allocations - assertThat(context.with(Span.wrap(SPAN_CONTEXT))).isSameAs(context); - assertThat(SPAN_CONTEXT.isValid()).isTrue(); - try (Scope ignored = Context.current().with(Span.wrap(SPAN_CONTEXT)).makeCurrent()) { - // No context mounted, so always an invalid span. - assertThat(Span.fromContext(Context.current()).getSpanContext().isValid()).isFalse(); - } - } - - @Test - void tracerNoOp() { - SpanBuilder span1 = NoopOpenTelemetry.getInstance().getTracer("test").spanBuilder("test"); - SpanBuilder span2 = NoopOpenTelemetry.getInstance().getTracer("test").spanBuilder("test"); - // No allocations - assertThat(span1).isSameAs(span2); - - // No crash - span1.setParent(Context.current()); - span1.setNoParent(); - span1.addLink(SPAN_CONTEXT); - span1.addLink(SPAN_CONTEXT, Attributes.empty()); - span1.setAttribute("key", "value"); - span1.setAttribute("key", 1L); - span1.setAttribute("key", 1.0); - span1.setAttribute("key", true); - span1.setAttribute(AttributeKey.stringKey("key"), "value"); - span1.setSpanKind(SpanKind.CLIENT); - span1.setStartTimestamp(1, TimeUnit.DAYS); - - // No allocations - assertThat(span1.startSpan()).isSameAs(Span.getInvalid()); - } -} diff --git a/animal-sniffer-signature/build.gradle.kts b/animal-sniffer-signature/build.gradle.kts new file mode 100644 index 00000000000..57962a6ca2d --- /dev/null +++ b/animal-sniffer-signature/build.gradle.kts @@ -0,0 +1,51 @@ +import ru.vyarus.gradle.plugin.animalsniffer.info.SignatureInfoTask +import ru.vyarus.gradle.plugin.animalsniffer.signature.BuildSignatureTask + +plugins { + id("otel.java-conventions") + id("ru.vyarus.animalsniffer") +} + +description = "Build tool to generate the Animal Sniffer Android signature" +otelJava.moduleName.set("io.opentelemetry.internal.animalsniffer") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) + +val signatureJar = configurations.create("signatureJar") { + isCanBeConsumed = false + isCanBeResolved = false +} +val signatureJarClasspath = configurations.create("signatureJarClasspath") { + isCanBeConsumed = false + isCanBeResolved = true + extendsFrom(signatureJar) +} +val generatedSignature = configurations.create("generatedSignature") { + isCanBeConsumed = true + isCanBeResolved = false +} + +dependencies { + signature("com.toasttab.android:gummy-bears-api-23:0.16.0@signature") + signatureJar("com.android.tools:desugar_jdk_libs") +} + +val signatureSimpleName = "android.signature" +val signatureBuilderTask = tasks.register("buildSignature", BuildSignatureTask::class.java) { + files(signatureJarClasspath) // All the jar files here will be added to the signature file. + signatures(configurations.signature) // We'll extend from the existing signatures added to this config. + outputName = signatureSimpleName // Name for the generated signature file. +} + +// Exposing the "generatedSignature" consumable config to be used in other subprojects +artifacts { + add("generatedSignature", project.provider { File(signatureBuilderTask.get().outputs.files.singleFile, signatureSimpleName) }) { + builtBy(signatureBuilderTask) + } +} + +// Utility task to show what's in the signature file +tasks.register("printSignature", SignatureInfoTask::class.java) { + signature = signatureBuilderTask.get().outputFiles + depth = 1 +} diff --git a/api/all/README.md b/api/all/README.md index a8093e10002..86c14664fdd 100644 --- a/api/all/README.md +++ b/api/all/README.md @@ -1,22 +1,7 @@ # OpenTelemetry API -[![Javadocs][javadoc-image]][javadoc-url] +#### API Misuse Logging -* The code in this module is the implementation of stable OpenTelemetry signals. -* Semantic Conventions for OpenTelemetry are in the `opentelemetry-semconv` module. -* The default implementation of the interfaces in this module is in the OpenTelemetry SDK module. -* The interfaces in this directory can be implemented to create alternative - implementations of the OpenTelemetry library. +API misuse information is logged under logger named `io.opentelemetry.ApiUsageLogging`. -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-api.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-api - ---- -#### Running micro-benchmarks -From the root of the repo run `./gradlew clean :api:jmh` to run all the benchmarks -or run `./gradlew clean :api:jmh -PjmhIncludeSingleClass=` -to run a specific benchmark class. - ---- -#### Logging API mis-use -Define `logging.level.io.opentelemetry.ApiUsageLogging=TRACE` to enable TRACE logging for invalid API calls. +To access, enable `FINEST` level logs. diff --git a/api/all/build.gradle.kts b/api/all/build.gradle.kts index 4ad64f607d3..8dfd98c3748 100644 --- a/api/all/build.gradle.kts +++ b/api/all/build.gradle.kts @@ -8,13 +8,20 @@ plugins { description = "OpenTelemetry API" otelJava.moduleName.set("io.opentelemetry.api") +otelJava.requireSuppressWarningsExplanation.set(false) base.archivesName.set("opentelemetry-api") +// These packages cannot be compileOnly dependencies (api:incubator depends on api:all, creating a +// circular dependency; sdk:autoconfigure is in a different module family). Declare them as optional +// imports without a version constraint so OSGi wires them if present but does not require them. +otelJava.osgiUnversionedOptionalPackages.set(listOf("io.opentelemetry.sdk.autoconfigure", "io.opentelemetry.api.incubator", "io.opentelemetry.api.incubator.internal")) dependencies { api(project(":context")) annotationProcessor("com.google.auto.value:auto-value") + testImplementation(project(":api:testing-internal")) + testImplementation("edu.berkeley.cs.jqf:jqf-fuzz") testImplementation("com.google.guava:guava-testlib") } diff --git a/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java b/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java index 5f24acee5b5..a348e69e19e 100644 --- a/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java +++ b/api/all/src/jmh/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorBenchmark.java @@ -34,19 +34,18 @@ public class W3CBaggagePropagatorBenchmark { static { List baggages = IntStream.range(0, 100) - .mapToObj( - i -> - "key" - + i - + " = value" - + i - + ";metaKey" - + i - + "=\tmetaVal" - + i - + ",broken)key" - + i - + "=value") + .mapToObj(i -> + "key" + + i + + " = value" + + i + + ";metaKey" + + i + + "=\tmetaVal" + + i + + ",broken)key" + + i + + "=value") .collect(Collectors.toList()); SMALL_BAGGAGE = Collections.singletonMap("baggage", String.join(",", baggages.subList(0, 5))); LARGE_BAGGAGE = Collections.singletonMap("baggage", String.join(",", baggages)); diff --git a/api/all/src/jmh/java/io/opentelemetry/api/common/AttributesBenchmark.java b/api/all/src/jmh/java/io/opentelemetry/api/common/AttributesBenchmark.java index e0c7de41bf5..8b3d16425fc 100644 --- a/api/all/src/jmh/java/io/opentelemetry/api/common/AttributesBenchmark.java +++ b/api/all/src/jmh/java/io/opentelemetry/api/common/AttributesBenchmark.java @@ -25,11 +25,30 @@ public class AttributesBenchmark { // pre-allocate the keys & values to remove one possible confounding factor private static final List> keys = new ArrayList<>(10); private static final List values = new ArrayList<>(10); + private static final List attributes = new ArrayList<>(); static { for (int i = 0; i < 10; i++) { keys.add(AttributeKey.stringKey("key" + i)); values.add("value" + i); + AttributesBuilder builder = Attributes.builder(); + for (int j = 0; j <= i; j++) { + builder.put(keys.get(j), values.get(j)); + } + attributes.add(builder.build()); + } + } + + @Benchmark + @BenchmarkMode({Mode.AverageTime}) + @Fork(1) + @Measurement(iterations = 15, time = 1) + @OutputTimeUnit(TimeUnit.NANOSECONDS) + @Warmup(iterations = 5, time = 1) + @SuppressWarnings("ReturnValueIgnored") + public void computeHashCode() { + for (Attributes attributes : attributes) { + attributes.hashCode(); } } diff --git a/api/all/src/main/java/io/opentelemetry/api/DefaultOpenTelemetry.java b/api/all/src/main/java/io/opentelemetry/api/DefaultOpenTelemetry.java index 6267a612933..137a805b73e 100644 --- a/api/all/src/main/java/io/opentelemetry/api/DefaultOpenTelemetry.java +++ b/api/all/src/main/java/io/opentelemetry/api/DefaultOpenTelemetry.java @@ -46,4 +46,9 @@ public MeterProvider getMeterProvider() { public ContextPropagators getPropagators() { return propagators; } + + @Override + public String toString() { + return "DefaultOpenTelemetry{" + "propagators=" + propagators + "}"; + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/GlobalOpenTelemetry.java b/api/all/src/main/java/io/opentelemetry/api/GlobalOpenTelemetry.java index 43f2c7454bd..33e8a3a89df 100644 --- a/api/all/src/main/java/io/opentelemetry/api/GlobalOpenTelemetry.java +++ b/api/all/src/main/java/io/opentelemetry/api/GlobalOpenTelemetry.java @@ -6,50 +6,76 @@ package io.opentelemetry.api; import io.opentelemetry.api.internal.GuardedBy; +import io.opentelemetry.api.internal.IncubatingUtil; +import io.opentelemetry.api.logs.LoggerProvider; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.MeterBuilder; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerBuilder; import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.common.impl.ApiUsageLogger; +import io.opentelemetry.common.impl.ConfigUtil; import io.opentelemetry.context.propagation.ContextPropagators; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.Objects; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** - * A global singleton for the entrypoint to telemetry functionality for tracing, metrics and - * baggage. + * Provides access to a global singleton {@link OpenTelemetry} instance. * - *

If using the OpenTelemetry SDK, you may want to instantiate the {@link OpenTelemetry} to - * provide configuration, for example of {@code Resource} or {@code Sampler}. See {@code - * OpenTelemetrySdk} and {@code OpenTelemetrySdk.builder} for information on how to construct the - * SDK's {@link OpenTelemetry} implementation. + *

WARNING: To avoid inherent complications around initialization ordering, it's best-practice to + * pass around instances of {@link OpenTelemetry} rather than using {@link GlobalOpenTelemetry}. + * However, the OpenTelemetry javagent makes the {@link OpenTelemetry} instance it installs + * available via {@link GlobalOpenTelemetry}. As a result, {@link GlobalOpenTelemetry} plays an + * important role in native instrumentation and application custom instrumentation. * - *

WARNING: Due to the inherent complications around initialization order involving this class - * and its single global instance, we strongly recommend *not* using GlobalOpenTelemetry unless you - * have a use-case that absolutely requires it. Please favor using instances of OpenTelemetry - * wherever possible. + *

Native instrumentation should use {@link #getOrNoop()} as the default {@link OpenTelemetry} + * instance, and expose APIs for setting a custom instance. This results in the following behavior: * - *

If you are using the OpenTelemetry javaagent, it is generally best to only call - * GlobalOpenTelemetry.get() once, and then pass the resulting reference where you need to use it. + *

    + *
  • If the OpenTelemetry javaagent is installed, the native instrumentation will default to the + * {@link OpenTelemetry} it installs. + *
  • If the OpenTelemetry javaagent is not installed, the native instrumentation will default to + * a noop instance. + *
  • If the user explicitly sets a custom instance, it will be used, regardless of whether or + * not the OpenTelemetry javaagent is installed. + *
* - * @see TracerProvider - * @see ContextPropagators + *

Applications with custom instrumentation should call {@link #isSet()} once during + * initialization to access the javaagent instance or initialize (e.g. {@code isSet() ? + * GlobalOpenTelemetry.get() : initializeSdk()}), and pass the resulting instance around manually + * (or with dependency injection) to install custom instrumentation. This results in the following + * behavior: + * + *

    + *
  • If the OpenTelemetry javaagent is installed, custom instrumentation will use the {@link + * OpenTelemetry} it installs. + *
  • If the OpenTelemetry javaagent is not installed, custom instrumentation will use an {@link + * OpenTelemetry} instance initialized by the application. + *
*/ -// We intentionally assign to be use for error reporting. +// We intentionally assign for error reporting. @SuppressWarnings("StaticAssignmentOfThrowable") public final class GlobalOpenTelemetry { + private static final String GLOBAL_AUTOCONFIGURE_ENABLED_PROPERTY = + "otel.java.global-autoconfigure.enabled"; + private static final Logger logger = Logger.getLogger(GlobalOpenTelemetry.class.getName()); private static final Object mutex = new Object(); - @Nullable private static volatile ObfuscatedOpenTelemetry globalOpenTelemetry; + @SuppressWarnings("NonFinalStaticField") + @Nullable + private static volatile OpenTelemetry globalOpenTelemetry; + @SuppressWarnings("NonFinalStaticField") @GuardedBy("mutex") @Nullable private static Throwable setGlobalCaller; @@ -57,10 +83,60 @@ public final class GlobalOpenTelemetry { private GlobalOpenTelemetry() {} /** - * Returns the registered global {@link OpenTelemetry}. + * Returns the registered global {@link OpenTelemetry} if set, or else {@link + * OpenTelemetry#noop()}. + * + *

NOTE: if the global instance is set, the response is obfuscated to prevent callers from + * casting to SDK implementation instances and inappropriately accessing non-instrumentation APIs. + * + *

NOTE: This does not result in the {@link #set(OpenTelemetry)} side effects of {@link + * #get()}. + * + *

Native instrumentation should use this method to initialize their default {@link + * OpenTelemetry} instance. See class javadoc for more details. + * + * @since 1.57.0 + */ + public static OpenTelemetry getOrNoop() { + synchronized (mutex) { + return globalOpenTelemetry != null ? globalOpenTelemetry : OpenTelemetry.noop(); + } + } + + /** + * Returns {@code true} if {@link GlobalOpenTelemetry} is set, otherwise {@code false}. + * + *

Application custom instrumentation should use this method during initialization. See class + * javadoc for more details. + * + * @since 1.57.0 + */ + public static boolean isSet() { + synchronized (mutex) { + return globalOpenTelemetry != null; + } + } + + /** + * Returns the registered global {@link OpenTelemetry} if set, else calls {@link + * GlobalOpenTelemetry#set(OpenTelemetry)} with a no-op {@link OpenTelemetry} instance and returns + * that. + * + *

NOTE: all returned instanced are obfuscated to prevent callers from casting to SDK + * implementation instances and inappropriately accessing non-instrumentation APIs. + * + *

Native instrumentations should use {@link #getOrNoop()} instead. See class javadoc for more + * details. + * + *

Application custom instrumentation should use {@link #isSet()} and only call this if the + * response is {@code true}. See class javadoc for more details. + * + *

If the global instance has not been set, and {@code + * io.opentelemetry:opentelemetry-sdk-extension-autoconfigure} is present, and {@value + * GLOBAL_AUTOCONFIGURE_ENABLED_PROPERTY} is {@code true}, the global instance will be set to an + * autoconfigured instance instead of {@link OpenTelemetry#noop()}. * - * @throws IllegalStateException if a provider has been specified by system property using the - * interface FQCN but the specified provider cannot be found. + * @throws IllegalStateException if autoconfigure initialization is triggered and fails. */ public static OpenTelemetry get() { OpenTelemetry openTelemetry = globalOpenTelemetry; @@ -75,7 +151,7 @@ public static OpenTelemetry get() { } set(OpenTelemetry.noop()); - return OpenTelemetry.noop(); + openTelemetry = Objects.requireNonNull(globalOpenTelemetry); } } } @@ -94,6 +170,7 @@ public static OpenTelemetry get() { * OpenTelemetrySdk.builder().buildAndRegisterGlobal()} instead of calling this method directly. */ public static void set(OpenTelemetry openTelemetry) { + Objects.requireNonNull(openTelemetry, "openTelemetry"); synchronized (mutex) { if (globalOpenTelemetry != null) { throw new IllegalStateException( @@ -103,11 +180,27 @@ public static void set(OpenTelemetry openTelemetry) { + "instead. Previous invocation set to cause of this exception.", setGlobalCaller); } - globalOpenTelemetry = new ObfuscatedOpenTelemetry(openTelemetry); + globalOpenTelemetry = obfuscatedOpenTelemetry(openTelemetry); setGlobalCaller = new Throwable(); } } + /** + * Sets the {@link OpenTelemetry} that should be the global instance. + * + *

This method calls the given {@code supplier} and calls {@link #set(OpenTelemetry)}, all + * while holding the {@link GlobalOpenTelemetry} mutex. + * + * @since 1.52.0 + */ + public static void set(Supplier supplier) { + Objects.requireNonNull(supplier, "supplier"); + synchronized (mutex) { + OpenTelemetry openTelemetry = supplier.get(); + set(openTelemetry); + } + } + /** Returns the globally registered {@link TracerProvider}. */ public static TracerProvider getTracerProvider() { return get().getTracerProvider(); @@ -123,6 +216,10 @@ public static TracerProvider getTracerProvider() { * @return a tracer instance. */ public static Tracer getTracer(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getTracer", "instrumentationScopeName"); + return OpenTelemetry.noop().getTracer("otel.global.opentelemetry"); + } return get().getTracer(instrumentationScopeName); } @@ -140,6 +237,14 @@ public static Tracer getTracer(String instrumentationScopeName) { */ public static Tracer getTracer( String instrumentationScopeName, String instrumentationScopeVersion) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getTracer", "instrumentationScopeName"); + return OpenTelemetry.noop().getTracer("otel.global.opentelemetry"); + } + if (instrumentationScopeVersion == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getTracer", "instrumentationScopeVersion"); + return OpenTelemetry.noop().getTracer("otel.global.opentelemetry"); + } return get().getTracer(instrumentationScopeName, instrumentationScopeVersion); } @@ -154,6 +259,10 @@ public static Tracer getTracer( * @since 1.4.0 */ public static TracerBuilder tracerBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "tracerBuilder", "instrumentationScopeName"); + return TracerProvider.noop().tracerBuilder("otel.global.opentelemetry"); + } return get().tracerBuilder(instrumentationScopeName); } @@ -177,6 +286,10 @@ public static MeterProvider getMeterProvider() { * @since 1.10.0 */ public static Meter getMeter(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getMeter", "instrumentationScopeName"); + return MeterProvider.noop().get("otel.global.opentelemetry"); + } return get().getMeter(instrumentationScopeName); } @@ -191,6 +304,10 @@ public static Meter getMeter(String instrumentationScopeName) { * @since 1.10.0 */ public static MeterBuilder meterBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "meterBuilder", "instrumentationScopeName"); + return MeterProvider.noop().meterBuilder("otel.global.opentelemetry"); + } return get().meterBuilder(instrumentationScopeName); } @@ -219,15 +336,28 @@ private static OpenTelemetry maybeAutoConfigureAndSetGlobal() { return null; } + // If autoconfigure module is present but global autoconfigure disabled log a warning and return + boolean globalAutoconfigureEnabled = + Boolean.parseBoolean(ConfigUtil.getString(GLOBAL_AUTOCONFIGURE_ENABLED_PROPERTY, "false")); + if (!globalAutoconfigureEnabled) { + logger.log( + Level.INFO, + "AutoConfiguredOpenTelemetrySdk found on classpath but automatic configuration is disabled." + + " To enable, run your JVM with -D" + + GLOBAL_AUTOCONFIGURE_ENABLED_PROPERTY + + "=true"); + return null; + } + try { Method initialize = openTelemetrySdkAutoConfiguration.getMethod("initialize"); Object autoConfiguredSdk = initialize.invoke(null); Method getOpenTelemetrySdk = openTelemetrySdkAutoConfiguration.getMethod("getOpenTelemetrySdk"); - return (OpenTelemetry) getOpenTelemetrySdk.invoke(autoConfiguredSdk); + return obfuscatedOpenTelemetry((OpenTelemetry) getOpenTelemetrySdk.invoke(autoConfiguredSdk)); } catch (NoSuchMethodException | IllegalAccessException e) { throw new IllegalStateException( - "OpenTelemetrySdkAutoConfiguration detected on classpath " + "AutoConfiguredOpenTelemetrySdk detected on classpath " + "but could not invoke initialize method. This is a bug in OpenTelemetry.", e); } catch (InvocationTargetException t) { @@ -239,6 +369,14 @@ private static OpenTelemetry maybeAutoConfigureAndSetGlobal() { } } + private static OpenTelemetry obfuscatedOpenTelemetry(OpenTelemetry openTelemetry) { + OpenTelemetry incubating = IncubatingUtil.obfuscatedOpenTelemetryIfIncubating(openTelemetry); + if (incubating != null) { + return incubating; + } + return new ObfuscatedOpenTelemetry(openTelemetry); + } + /** * Static global instances are obfuscated when they are returned from the API to prevent users * from casting them to their SDK-specific implementation. For example, we do not want users to @@ -263,6 +401,11 @@ public MeterProvider getMeterProvider() { return delegate.getMeterProvider(); } + @Override + public LoggerProvider getLogsBridge() { + return delegate.getLogsBridge(); + } + @Override public ContextPropagators getPropagators() { return delegate.getPropagators(); @@ -270,6 +413,11 @@ public ContextPropagators getPropagators() { @Override public TracerBuilder tracerBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam( + OpenTelemetry.class, "tracerBuilder", "instrumentationScopeName"); + return TracerProvider.noop().tracerBuilder("otel.global.opentelemetry"); + } return delegate.tracerBuilder(instrumentationScopeName); } } diff --git a/api/all/src/main/java/io/opentelemetry/api/OpenTelemetry.java b/api/all/src/main/java/io/opentelemetry/api/OpenTelemetry.java index 9dbe5c7da3d..f0a52712474 100644 --- a/api/all/src/main/java/io/opentelemetry/api/OpenTelemetry.java +++ b/api/all/src/main/java/io/opentelemetry/api/OpenTelemetry.java @@ -5,13 +5,16 @@ package io.opentelemetry.api; +import io.opentelemetry.api.logs.LoggerProvider; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.MeterBuilder; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerBuilder; import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.propagation.ContextPropagators; +import java.util.Objects; /** * The entrypoint to telemetry functionality for tracing, metrics and baggage. @@ -36,6 +39,7 @@ static OpenTelemetry noop() { * otherwise. */ static OpenTelemetry propagating(ContextPropagators propagators) { + Objects.requireNonNull(propagators, "propagators"); return DefaultOpenTelemetry.getPropagating(propagators); } @@ -51,6 +55,10 @@ static OpenTelemetry propagating(ContextPropagators propagators) { * @return a tracer instance. */ default Tracer getTracer(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getTracer", "instrumentationScopeName"); + return OpenTelemetry.noop().getTracer("otel.global.opentelemetry"); + } return getTracerProvider().get(instrumentationScopeName); } @@ -64,6 +72,14 @@ default Tracer getTracer(String instrumentationScopeName) { * @return a tracer instance. */ default Tracer getTracer(String instrumentationScopeName, String instrumentationScopeVersion) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getTracer", "instrumentationScopeName"); + return OpenTelemetry.noop().getTracer("otel.global.opentelemetry"); + } + if (instrumentationScopeVersion == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getTracer", "instrumentationScopeVersion"); + return OpenTelemetry.noop().getTracer("otel.global.opentelemetry"); + } return getTracerProvider().get(instrumentationScopeName, instrumentationScopeVersion); } @@ -76,6 +92,10 @@ default Tracer getTracer(String instrumentationScopeName, String instrumentation * @since 1.4.0 */ default TracerBuilder tracerBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "tracerBuilder", "instrumentationScopeName"); + return OpenTelemetry.noop().tracerBuilder("otel.global.opentelemetry"); + } return getTracerProvider().tracerBuilder(instrumentationScopeName); } @@ -98,11 +118,15 @@ default MeterProvider getMeterProvider() { * @since 1.10.0 */ default Meter getMeter(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "getMeter", "instrumentationScopeName"); + return OpenTelemetry.noop().getMeter("otel.global.opentelemetry"); + } return getMeterProvider().get(instrumentationScopeName); } /** - * Creates a {@link MeterBuilder} for a named {@link Tracer} instance. + * Creates a {@link MeterBuilder} for a named {@link Meter} instance. * * @param instrumentationScopeName A name uniquely identifying the instrumentation scope, such as * the instrumentation library, package, or fully qualified class name. Must not be null. @@ -110,9 +134,26 @@ default Meter getMeter(String instrumentationScopeName) { * @since 1.10.0 */ default MeterBuilder meterBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(OpenTelemetry.class, "meterBuilder", "instrumentationScopeName"); + return OpenTelemetry.noop().meterBuilder("otel.global.opentelemetry"); + } return getMeterProvider().meterBuilder(instrumentationScopeName); } + /** + * Returns the {@link LoggerProvider} for bridging logs into OpenTelemetry. + * + *

The OpenTelemetry logs bridge API exists to enable bridging logs from other log frameworks + * (e.g. SLF4J, Log4j, JUL, Logback, etc) into OpenTelemetry and is NOT a replacement log + * API. + * + * @since 1.27.0 + */ + default LoggerProvider getLogsBridge() { + return LoggerProvider.noop(); + } + /** Returns the {@link ContextPropagators} for this {@link OpenTelemetry}. */ ContextPropagators getPropagators(); } diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java b/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java index 5dd2924d432..3b6ae74710f 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/Baggage.java @@ -5,6 +5,7 @@ package io.opentelemetry.api.baggage; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.Context; import io.opentelemetry.context.ImplicitContextKeyed; import java.util.Map; @@ -52,6 +53,10 @@ static Baggage current() { * Baggage} if there is no baggage in the context. */ static Baggage fromContext(Context context) { + if (context == null) { + ApiUsageLogger.logNullParam(Baggage.class, "fromContext", "context"); + return empty(); + } Baggage baggage = context.get(BaggageContextKey.KEY); return baggage != null ? baggage : empty(); } @@ -62,11 +67,19 @@ static Baggage fromContext(Context context) { */ @Nullable static Baggage fromContextOrNull(Context context) { + if (context == null) { + ApiUsageLogger.logNullParam(Baggage.class, "fromContextOrNull", "context"); + return null; + } return context.get(BaggageContextKey.KEY); } @Override default Context storeInContext(Context context) { + if (context == null) { + ApiUsageLogger.logNullParam(Baggage.class, "storeInContext", "context"); + return Context.root(); + } return context.with(BaggageContextKey.KEY, this); } @@ -99,4 +112,26 @@ default boolean isEmpty() { * be set to not use an implicit parent, so any parent assignment must be done manually. */ BaggageBuilder toBuilder(); + + /** + * Returns the {@code BaggageEntry} associated with the given key. + * + * @param entryKey entry key to return the {@code BaggageEntry} for, or {@code null} if no {@code + * Entry} with the given {@code entryKey} is in this {@code Baggage}. + * @since 1.43.0 + */ + @Nullable + default BaggageEntry getEntry(String entryKey) { + if (entryKey == null) { + ApiUsageLogger.logNullParam(Baggage.class, "getEntry", "entryKey"); + return null; + } + BaggageEntry[] result = new BaggageEntry[] {null}; + forEach((key, entry) -> { + if (entryKey.equals(key)) { + result[0] = entry; + } + }); + return result[0]; + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageBuilder.java b/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageBuilder.java index 5cf6c7891b3..97268d8db34 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageBuilder.java @@ -5,6 +5,8 @@ package io.opentelemetry.api.baggage; +import io.opentelemetry.common.impl.ApiUsageLogger; + /** * A builder of {@link Baggage}. * @@ -15,6 +17,10 @@ public interface BaggageBuilder { /** * Adds the key/value pair and metadata regardless of whether the key is present. * + *

Per the W3C Baggage spec, a + * baggage-name must be a non-empty token. Calls with a {@code null} or empty {@code key}, a + * {@code null} {@code value}, or a {@code null} {@code entryMetadata} are silently ignored. + * * @param key the {@code String} key which will be set. * @param value the {@code String} value to set for the given key. * @param entryMetadata the {@code BaggageEntryMetadata} metadata to set for the given key. @@ -30,6 +36,14 @@ public interface BaggageBuilder { * @return this */ default BaggageBuilder put(String key, String value) { + if (key == null) { + ApiUsageLogger.logNullParam(BaggageBuilder.class, "put", "key"); + return this; + } + if (value == null) { + ApiUsageLogger.logNullParam(BaggageBuilder.class, "put", "value"); + return this; + } return put(key, value, BaggageEntryMetadata.empty()); } diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageEntryMetadata.java b/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageEntryMetadata.java index 56da2b95a06..70867ce11fb 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageEntryMetadata.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/BaggageEntryMetadata.java @@ -5,6 +5,7 @@ package io.opentelemetry.api.baggage; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.Immutable; /** @@ -19,8 +20,18 @@ static BaggageEntryMetadata empty() { return ImmutableEntryMetadata.EMPTY; } - /** Returns a new {@link BaggageEntryMetadata} with the given value. */ + /** + * Returns a new {@link BaggageEntryMetadata} with the given value. + * + *

For W3C baggage propagation, {@code metadata} must contain only tab (0x09) or printable + * ASCII (0x20-0x7E) excluding {@code "}, {@code ,}, and {@code \}. Entries whose metadata + * contains other characters are dropped on inject. + */ static BaggageEntryMetadata create(String metadata) { + if (metadata == null) { + ApiUsageLogger.logNullParam(BaggageEntryMetadata.class, "create", "metadata"); + return BaggageEntryMetadata.empty(); + } return ImmutableEntryMetadata.create(metadata); } diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableBaggage.java b/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableBaggage.java index 7faf4152fe7..f6f86973778 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableBaggage.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableBaggage.java @@ -6,6 +6,7 @@ package io.opentelemetry.api.baggage; import io.opentelemetry.api.internal.ImmutableKeyValuePairs; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.ArrayList; import java.util.Comparator; import java.util.List; @@ -33,10 +34,25 @@ static BaggageBuilder builder() { @Nullable @Override public String getEntryValue(String entryKey) { + if (entryKey == null) { + ApiUsageLogger.logNullParam(Baggage.class, "getEntryValue", "entryKey"); + return null; + } BaggageEntry entry = get(entryKey); return entry != null ? entry.getValue() : null; } + // Overrides the default implementation to provide a more performant implementation. + @Nullable + @Override + public BaggageEntry getEntry(String entryKey) { + if (entryKey == null) { + ApiUsageLogger.logNullParam(Baggage.class, "getEntry", "entryKey"); + return null; + } + return get(entryKey); + } + @Override public BaggageBuilder toBuilder() { return new Builder(new ArrayList<>(data())); @@ -62,7 +78,19 @@ static class Builder implements BaggageBuilder { @Override public BaggageBuilder put(String key, String value, BaggageEntryMetadata entryMetadata) { - if ((key == null) || (value == null) || (entryMetadata == null)) { + if (key == null) { + ApiUsageLogger.logNullParam(BaggageBuilder.class, "put", "key"); + return this; + } + if (value == null) { + ApiUsageLogger.logNullParam(BaggageBuilder.class, "put", "value"); + return this; + } + if (entryMetadata == null) { + ApiUsageLogger.logNullParam(BaggageBuilder.class, "put", "entryMetadata"); + return this; + } + if (key.isEmpty()) { return this; } data.add(key); @@ -74,6 +102,7 @@ public BaggageBuilder put(String key, String value, BaggageEntryMetadata entryMe @Override public BaggageBuilder remove(String key) { if (key == null) { + ApiUsageLogger.logNullParam(BaggageBuilder.class, "remove", "key"); return this; } data.add(key); diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableEntryMetadata.java b/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableEntryMetadata.java index a367e288a1c..8225ff87dc9 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableEntryMetadata.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/ImmutableEntryMetadata.java @@ -6,7 +6,7 @@ package io.opentelemetry.api.baggage; import com.google.auto.value.AutoValue; -import io.opentelemetry.api.internal.ValidationUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.Immutable; @Immutable @@ -25,7 +25,7 @@ abstract class ImmutableEntryMetadata implements BaggageEntryMetadata { */ static ImmutableEntryMetadata create(String metadata) { if (metadata == null) { - ValidationUtil.log("metadata is null"); + ApiUsageLogger.logNullParam(BaggageEntryMetadata.class, "create", "metadata"); return EMPTY; } return new AutoValue_ImmutableEntryMetadata(metadata); diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/package-info.java b/api/all/src/main/java/io/opentelemetry/api/baggage/package-info.java index 7cf942a9129..d119efa9a03 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/package-info.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/package-info.java @@ -13,7 +13,6 @@ *

Note that entries are independent of the tracing data that is propagated in the {@link * io.opentelemetry.context.Context}, such as trace ID. */ -// TODO: Add code examples. @ParametersAreNonnullByDefault package io.opentelemetry.api.baggage; diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/BaggageCodec.java b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/BaggageCodec.java new file mode 100644 index 00000000000..71c8bd875fb --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/BaggageCodec.java @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.baggage.propagation; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * Note: This class is based on code from Apache Commons Codec. It is comprised of code from these + * classes: + * + *

+ * + *

Implements baggage-octet decoding in accordance with th Baggage header content specification. All + * US-ASCII characters excluding CTLs, whitespace, DQUOTE, comma, semicolon and backslash are + * encoded in `www-form-urlencoded` encoding scheme. + */ +class BaggageCodec { + + private static final byte ESCAPE_CHAR = '%'; + private static final int RADIX = 16; + + private BaggageCodec() {} + + /** + * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped + * characters are converted back to their original representation. + * + * @param bytes array of URL safe characters + * @return array of original bytes + */ + private static byte[] decode(byte[] bytes) { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + for (int i = 0; i < bytes.length; i++) { + int b = bytes[i]; + if (b == ESCAPE_CHAR) { + if (i + 1 >= bytes.length) { + return buffer.toByteArray(); + } + int u = digit16(bytes[++i]); + + if (i + 1 >= bytes.length) { + return buffer.toByteArray(); + } + int l = digit16(bytes[++i]); + + buffer.write((char) ((u << 4) + l)); + } else { + buffer.write(b); + } + } + return buffer.toByteArray(); + } + + /** + * Decodes an array of URL safe 7-bit characters into an array of original bytes. Escaped + * characters are converted back to their original representation. + * + * @param value string of URL safe characters + * @param charset encoding of given string + * @return decoded value + */ + static String decode(String value, Charset charset) { + byte[] bytes = decode(value.getBytes(StandardCharsets.US_ASCII)); + return new String(bytes, charset); + } + + /** + * Returns the numeric value of the character {@code b} in radix 16. + * + * @param b The byte to be converted. + * @return The numeric value represented by the character in radix 16. + */ + private static int digit16(byte b) { + int i = Character.digit((char) b, RADIX); + if (i == -1) { + throw new NumberFormatException( + "Invalid URL encoding: not a valid digit (radix " + + RADIX + + "): byte=" + + b + + ", char='" + + (char) (b & 0xff) + + "'"); + } + return i; + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Element.java b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Element.java index f6bdaec9eb3..d59ca10ecb3 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Element.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Element.java @@ -31,6 +31,7 @@ class Element { } private final BitSet excluded; + private final boolean allowEmpty; private boolean leadingSpace; private boolean readingValue; @@ -40,11 +41,11 @@ class Element { @Nullable private String value; static Element createKeyElement() { - return new Element(EXCLUDED_KEY_CHARS); + return new Element(EXCLUDED_KEY_CHARS, /* allowEmpty= */ false); } static Element createValueElement() { - return new Element(EXCLUDED_VALUE_CHARS); + return new Element(EXCLUDED_VALUE_CHARS, /* allowEmpty= */ true); } /** @@ -52,8 +53,9 @@ static Element createValueElement() { * * @param excluded characters that are not allowed for this type of an element */ - private Element(BitSet excluded) { + private Element(BitSet excluded, boolean allowEmpty) { this.excluded = excluded; + this.allowEmpty = allowEmpty; reset(0); } @@ -77,8 +79,11 @@ boolean tryTerminating(int index, String header) { if (this.trailingSpace) { setValue(header); return true; + } else if (allowEmpty) { + // no content: empty value is valid (e.g. "key=" or "key= "), empty key is not + this.value = ""; + return true; } else { - // leading spaces - no content, invalid return false; } } diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Parser.java b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Parser.java index 345fb177a5c..a5f58717412 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Parser.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/Parser.java @@ -7,21 +7,23 @@ import io.opentelemetry.api.baggage.BaggageBuilder; import io.opentelemetry.api.baggage.BaggageEntryMetadata; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; import java.nio.charset.StandardCharsets; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.annotation.Nullable; /** * Implements single-pass Baggage parsing in accordance with https://w3c.github.io/baggage/ Key / - * value are restricted in accordance with https://www.ietf.org/rfc/rfc2616.txt + * value are restricted in accordance with https://www.ietf.org/rfc/rfc2616.txt. * *

Note: following aspects are not specified in RFC: - some invalid elements (key or value) - * parser will include valid ones, disregard invalid - empty "value" is regarded as invalid - meta - - * anything besides element terminator (comma) + * anything besides element terminator (comma). */ class Parser { + private static final Logger LOGGER = Logger.getLogger(Parser.class.getName()); + private enum State { KEY, VALUE, @@ -29,6 +31,7 @@ private enum State { } private final String baggageHeader; + private final int maxEntries; private final Element key = Element.createKeyElement(); private final Element value = Element.createValueElement(); @@ -38,14 +41,19 @@ private enum State { private int metaStart; private boolean skipToNext; + private int entriesAdded; - public Parser(String baggageHeader) { + Parser(String baggageHeader, int maxEntries) { this.baggageHeader = baggageHeader; + this.maxEntries = maxEntries; reset(0); } - void parseInto(BaggageBuilder baggageBuilder) { + int parseInto(BaggageBuilder baggageBuilder) { for (int i = 0, n = baggageHeader.length(); i < n; i++) { + if (entriesAdded >= maxEntries) { + break; + } char current = baggageHeader.charAt(i); if (skipToNext) { @@ -64,6 +72,8 @@ void parseInto(BaggageBuilder baggageBuilder) { } else { skipToNext = true; } + } else if (state == State.VALUE) { + skipToNext = !value.tryNextChar(current, i); } break; } @@ -123,21 +133,35 @@ void parseInto(BaggageBuilder baggageBuilder) { } } } + return entriesAdded; } - private static void putBaggage( + private void putBaggage( BaggageBuilder baggage, @Nullable String key, @Nullable String value, @Nullable String metadataValue) { - String decodedValue = decodeValue(value); - metadataValue = decodeValue(metadataValue); + if (entriesAdded >= maxEntries) { + return; + } + String decodedValue; + try { + decodedValue = decodeValue(value); + } catch (IllegalArgumentException e) { + LOGGER.log(Level.WARNING, "Skipping invalid baggage member", e); + return; + } + if (!W3CBaggagePropagator.isValidBaggageMetadata(metadataValue)) { + LOGGER.log(Level.WARNING, "Skipping baggage member with invalid metadata"); + return; + } BaggageEntryMetadata baggageEntryMetadata = metadataValue != null ? BaggageEntryMetadata.create(metadataValue) : BaggageEntryMetadata.empty(); if (key != null && decodedValue != null) { baggage.put(key, decodedValue, baggageEntryMetadata); + entriesAdded++; } } @@ -146,11 +170,7 @@ private static String decodeValue(@Nullable String value) { if (value == null) { return null; } - try { - return URLDecoder.decode(value, StandardCharsets.UTF_8.name()); - } catch (UnsupportedEncodingException e) { - return null; - } + return BaggageCodec.decode(value, StandardCharsets.UTF_8); } /** diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java index 386de4985de..227c0f4b62b 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java +++ b/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagator.java @@ -9,14 +9,18 @@ import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.baggage.BaggageBuilder; -import io.opentelemetry.api.baggage.BaggageEntry; +import io.opentelemetry.api.internal.PercentEscaper; import io.opentelemetry.api.internal.StringUtils; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.context.propagation.TextMapSetter; import java.util.Collection; +import java.util.Iterator; import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.annotation.Nullable; /** @@ -24,10 +28,15 @@ */ public final class W3CBaggagePropagator implements TextMapPropagator { + // Limits from https://www.w3.org/TR/baggage/#limits + private static final int MAX_BAGGAGE_ENTRIES = 64; + private static final int MAX_BAGGAGE_BYTES = 8192; + private static final String FIELD = "baggage"; private static final List FIELDS = singletonList(FIELD); private static final W3CBaggagePropagator INSTANCE = new W3CBaggagePropagator(); private static final PercentEscaper URL_ESCAPER = PercentEscaper.create(); + private static final Logger LOGGER = Logger.getLogger(W3CBaggagePropagator.class.getName()); /** Singleton instance of the W3C Baggage Propagator. */ public static W3CBaggagePropagator getInstance() { @@ -43,7 +52,12 @@ public Collection fields() { @Override public void inject(Context context, @Nullable C carrier, TextMapSetter setter) { - if (context == null || setter == null) { + if (context == null) { + ApiUsageLogger.logNullParam(Context.class, "inject", "context"); + return; + } + if (setter == null) { + ApiUsageLogger.logNullParam(TextMapSetter.class, "inject", "setter"); return; } Baggage baggage = Baggage.fromContext(context); @@ -59,18 +73,40 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se private static String baggageToString(Baggage baggage) { StringBuilder headerContent = new StringBuilder(); - baggage.forEach( - (key, baggageEntry) -> { - if (baggageIsInvalid(key, baggageEntry)) { - return; - } - headerContent.append(key).append("=").append(encodeValue(baggageEntry.getValue())); - String metadataValue = baggageEntry.getMetadata().getValue(); - if (metadataValue != null && !metadataValue.isEmpty()) { - headerContent.append(";").append(encodeValue(metadataValue)); - } - headerContent.append(","); - }); + int[] entryCount = {0}; + baggage.forEach((key, baggageEntry) -> { + if (!isValidBaggageKey(key)) { + LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid key"); + return; + } + if (!isValidBaggageValue(baggageEntry.getValue())) { + LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid value"); + return; + } + if (!isValidBaggageMetadata(baggageEntry.getMetadata().getValue())) { + LOGGER.log(Level.WARNING, "Skipping baggage entry with invalid metadata"); + return; + } + if (entryCount[0] >= MAX_BAGGAGE_ENTRIES) { + return; + } + String encodedValue = encodeValue(baggageEntry.getValue()); + String metadataValue = baggageEntry.getMetadata().getValue(); + String metadata = (metadataValue != null && !metadataValue.isEmpty()) ? metadataValue : null; + // Exit early if adding this entry causes the total length to exceed the limit + // encodedEntryLength includes a trailing comma; the final string trims exactly one, + // so the net contribution to the final length is entryLength - 1. + if (headerContent.length() + encodedEntryLength(key, encodedValue, metadata) - 1 + > MAX_BAGGAGE_BYTES) { + return; + } + headerContent.append(key).append("=").append(encodedValue); + if (metadata != null) { + headerContent.append(";").append(metadata); + } + headerContent.append(","); + entryCount[0]++; + }); if (headerContent.length() == 0) { return ""; @@ -85,38 +121,73 @@ private static String encodeValue(String value) { return URL_ESCAPER.escape(value); } + /** + * Returns the length of the serialized entry as it would appear in the baggage header, including + * the trailing comma used by the trailing-comma pattern in {@link #baggageToString}. The length + * accounts for {@code "key=encodedValue,"} plus {@code ";metadata"} when metadata is present. + */ + private static int encodedEntryLength( + String key, String encodedValue, @Nullable String metadata) { + int length = key.length() + 1 + encodedValue.length() + 1; // "key=value," + if (metadata != null) { + length += 1 + metadata.length(); // ";metadata" + } + return length; + } + @Override public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { if (context == null) { + ApiUsageLogger.logNullParam(Context.class, "extract", "context"); return Context.root(); } if (getter == null) { + ApiUsageLogger.logNullParam(TextMapGetter.class, "extract", "getter"); return context; } - String baggageHeader = getter.get(carrier, FIELD); - if (baggageHeader == null) { - return context; - } - if (baggageHeader.isEmpty()) { + return extractMulti(context, carrier, getter); + } + + private static Context extractMulti( + Context context, @Nullable C carrier, TextMapGetter getter) { + Iterator baggageHeaders = getter.getAll(carrier, FIELD); + if (baggageHeaders == null) { return context; } + boolean extracted = false; BaggageBuilder baggageBuilder = Baggage.builder(); - try { - extractEntries(baggageHeader, baggageBuilder); - } catch (RuntimeException e) { - return context; + int totalBytes = 0; + int totalEntries = 0; + + while (baggageHeaders.hasNext()) { + String header = baggageHeaders.next(); + if (header.isEmpty()) { + continue; + } + + totalBytes += header.length(); + if (totalBytes > MAX_BAGGAGE_BYTES || totalEntries >= MAX_BAGGAGE_ENTRIES) { + LOGGER.fine("Baggage header exceeded W3C limits, dropping remaining entries"); + break; + } + + try { + int added = extractEntries(header, baggageBuilder, MAX_BAGGAGE_ENTRIES - totalEntries); + extracted = true; + totalEntries += added; + } catch (RuntimeException expected) { + // invalid baggage header, continue + } } - return context.with(baggageBuilder.build()); - } - private static void extractEntries(String baggageHeader, BaggageBuilder baggageBuilder) { - new Parser(baggageHeader).parseInto(baggageBuilder); + return extracted ? context.with(baggageBuilder.build()) : context; } - private static boolean baggageIsInvalid(String key, BaggageEntry baggageEntry) { - return !isValidBaggageKey(key) || !isValidBaggageValue(baggageEntry.getValue()); + private static int extractEntries( + String baggageHeader, BaggageBuilder baggageBuilder, int maxEntries) { + return new Parser(baggageHeader, maxEntries).parseInto(baggageBuilder); } /** @@ -126,7 +197,7 @@ private static boolean baggageIsInvalid(String key, BaggageEntry baggageEntry) { * @return whether the name is valid. */ private static boolean isValidBaggageKey(String name) { - return name != null && !name.isEmpty() && StringUtils.isPrintableString(name); + return name != null && !name.trim().isEmpty() && StringUtils.isPrintableString(name); } /** @@ -138,4 +209,32 @@ private static boolean isValidBaggageKey(String name) { private static boolean isValidBaggageValue(String value) { return value != null; } + + /** + * Determines whether the given {@code String} is valid W3C baggage metadata. + * + * @param metadata the metadata to be validated. + * @return whether the metadata is valid. + */ + static boolean isValidBaggageMetadata(@Nullable String metadata) { + if (metadata == null || metadata.isEmpty()) { + return true; + } + for (int i = 0; i < metadata.length(); i++) { + if (!isValidMetadataChar(metadata.charAt(i))) { + return false; + } + } + return true; + } + + // tab or printable ASCII except " , \ + private static boolean isValidMetadataChar(char c) { + return c == '\t' || (c >= ' ' && c <= '~' && c != '"' && c != ',' && c != '\\'); + } + + @Override + public String toString() { + return "W3CBaggagePropagator"; + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributes.java b/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributes.java index 165c9ffe2e2..fea9c8fced3 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributes.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributes.java @@ -6,8 +6,11 @@ package io.opentelemetry.api.common; import io.opentelemetry.api.internal.ImmutableKeyValuePairs; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.ArrayList; +import java.util.Collections; import java.util.Comparator; +import java.util.List; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @@ -41,13 +44,122 @@ public AttributesBuilder toBuilder() { return new ArrayBackedAttributesBuilder(new ArrayList<>(data())); } - @SuppressWarnings("unchecked") + @SuppressWarnings("unchecked") // safe cast: values are stored internally keyed by AttributeKey @Override @Nullable public T get(AttributeKey key) { + if (key == null) { + ApiUsageLogger.logNullParam(Attributes.class, "get", "key"); + return null; + } + if (key.getType() == AttributeType.VALUE) { + return (T) getAsValue(key.getKey()); + } + // Check if we're looking for an array type but have a VALUE with empty array + if (isArrayType(key.getType())) { + T value = (T) super.get(key); + if (value == null) { + // Check if there's a VALUE with the same key that contains an empty array + Value valueAttr = getValueAttribute(key.getKey()); + if (valueAttr != null && isEmptyArray(valueAttr)) { + return (T) Collections.emptyList(); + } + } + return value; + } return (T) super.get(key); } + private static boolean isArrayType(AttributeType type) { + return type == AttributeType.STRING_ARRAY + || type == AttributeType.LONG_ARRAY + || type == AttributeType.DOUBLE_ARRAY + || type == AttributeType.BOOLEAN_ARRAY; + } + + @Nullable + private Value getValueAttribute(String keyName) { + List data = data(); + for (int i = 0; i < data.size(); i += 2) { + AttributeKey currentKey = (AttributeKey) data.get(i); + if (currentKey.getKey().equals(keyName) && currentKey.getType() == AttributeType.VALUE) { + return (Value) data.get(i + 1); + } + } + return null; + } + + private static boolean isEmptyArray(Value value) { + if (value.getType() != ValueType.ARRAY) { + return false; + } + @SuppressWarnings("unchecked") + List> arrayValues = (List>) value.getValue(); + return arrayValues.isEmpty(); + } + + @Nullable + private Value getAsValue(String keyName) { + // Find any attribute with the same key name and convert it to Value + List data = data(); + for (int i = 0; i < data.size(); i += 2) { + AttributeKey currentKey = (AttributeKey) data.get(i); + if (currentKey.getKey().equals(keyName)) { + Object value = data.get(i + 1); + return asValue(currentKey.getType(), value); + } + } + return null; + } + + @SuppressWarnings("unchecked") + @Nullable + private static Value asValue(AttributeType type, Object value) { + switch (type) { + case STRING: + return Value.of((String) value); + case LONG: + return Value.of((Long) value); + case DOUBLE: + return Value.of((Double) value); + case BOOLEAN: + return Value.of((Boolean) value); + case STRING_ARRAY: + List stringList = (List) value; + Value[] stringValues = new Value[stringList.size()]; + for (int i = 0; i < stringList.size(); i++) { + stringValues[i] = Value.of(stringList.get(i)); + } + return Value.of(stringValues); + case LONG_ARRAY: + List longList = (List) value; + Value[] longValues = new Value[longList.size()]; + for (int i = 0; i < longList.size(); i++) { + longValues[i] = Value.of(longList.get(i)); + } + return Value.of(longValues); + case DOUBLE_ARRAY: + List doubleList = (List) value; + Value[] doubleValues = new Value[doubleList.size()]; + for (int i = 0; i < doubleList.size(); i++) { + doubleValues[i] = Value.of(doubleList.get(i)); + } + return Value.of(doubleValues); + case BOOLEAN_ARRAY: + List booleanList = (List) value; + Value[] booleanValues = new Value[booleanList.size()]; + for (int i = 0; i < booleanList.size(); i++) { + booleanValues[i] = Value.of(booleanList.get(i)); + } + return Value.of(booleanValues); + case VALUE: + // Already a Value + return (Value) value; + } + // Should not reach here + return null; + } + static Attributes sortAndFilterToAttributes(Object... data) { // null out any empty keys or keys with null values // so they will then be removed by the sortAndFilter method. diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java b/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java index 30df86d7700..7fabcf990d0 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/ArrayBackedAttributesBuilder.java @@ -5,10 +5,21 @@ package io.opentelemetry.api.common; +import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; +import static io.opentelemetry.api.common.AttributeKey.doubleKey; +import static io.opentelemetry.api.common.AttributeKey.longArrayKey; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; +import javax.annotation.Nullable; class ArrayBackedAttributesBuilder implements AttributesBuilder { private final List data; @@ -33,12 +44,24 @@ public Attributes build() { @Override public AttributesBuilder put(AttributeKey key, int value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } return put(key, (long) value); } @Override - public AttributesBuilder put(AttributeKey key, T value) { - if (key == null || key.getKey().isEmpty() || value == null) { + public AttributesBuilder put(AttributeKey key, @Nullable T value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } + if (key.getKey().isEmpty() || value == null) { + return this; + } + if (key.getType() == AttributeType.VALUE && value instanceof Value) { + putValue(key, (Value) value); return this; } data.add(key); @@ -46,31 +69,134 @@ public AttributesBuilder put(AttributeKey key, T value) { return this; } + @SuppressWarnings("unchecked") + private void putValue(AttributeKey key, Value valueObj) { + // Convert VALUE type to narrower type when possible + String keyName = key.getKey(); + switch (valueObj.getType()) { + case STRING: + put(stringKey(keyName), ((Value) valueObj).getValue()); + return; + case LONG: + put(longKey(keyName), ((Value) valueObj).getValue()); + return; + case DOUBLE: + put(doubleKey(keyName), ((Value) valueObj).getValue()); + return; + case BOOLEAN: + put(booleanKey(keyName), ((Value) valueObj).getValue()); + return; + case ARRAY: + List> arrayValues = (List>) valueObj.getValue(); + AttributeType attributeType = attributeType(arrayValues); + switch (attributeType) { + case STRING_ARRAY: + List strings = new ArrayList<>(arrayValues.size()); + for (Value v : arrayValues) { + strings.add((String) v.getValue()); + } + put(stringArrayKey(keyName), strings); + return; + case LONG_ARRAY: + List longs = new ArrayList<>(arrayValues.size()); + for (Value v : arrayValues) { + longs.add((Long) v.getValue()); + } + put(longArrayKey(keyName), longs); + return; + case DOUBLE_ARRAY: + List doubles = new ArrayList<>(arrayValues.size()); + for (Value v : arrayValues) { + doubles.add((Double) v.getValue()); + } + put(doubleArrayKey(keyName), doubles); + return; + case BOOLEAN_ARRAY: + List booleans = new ArrayList<>(arrayValues.size()); + for (Value v : arrayValues) { + booleans.add((Boolean) v.getValue()); + } + put(booleanArrayKey(keyName), booleans); + return; + case VALUE: + // Not coercible (empty, non-homogeneous, or unsupported element type) + data.add(key); + data.add(valueObj); + return; + default: + throw new IllegalArgumentException("Unexpected array attribute type: " + attributeType); + } + case KEY_VALUE_LIST: + case BYTES: + case EMPTY: + // Keep as VALUE type + data.add(key); + data.add(valueObj); + } + } + + /** + * Returns the AttributeType for a homogeneous array (STRING_ARRAY, LONG_ARRAY, DOUBLE_ARRAY, or + * BOOLEAN_ARRAY), or VALUE if the array is empty, non-homogeneous, or contains unsupported + * element types. + */ + private static AttributeType attributeType(List> arrayValues) { + if (arrayValues.isEmpty()) { + return AttributeType.VALUE; + } + ValueType elementType = arrayValues.get(0).getType(); + for (Value v : arrayValues) { + if (v.getType() != elementType) { + return AttributeType.VALUE; + } + } + switch (elementType) { + case STRING: + return AttributeType.STRING_ARRAY; + case LONG: + return AttributeType.LONG_ARRAY; + case DOUBLE: + return AttributeType.DOUBLE_ARRAY; + case BOOLEAN: + return AttributeType.BOOLEAN_ARRAY; + case ARRAY: + case KEY_VALUE_LIST: + case BYTES: + case EMPTY: + return AttributeType.VALUE; + } + throw new IllegalArgumentException("Unsupported element type: " + elementType); + } + @Override @SuppressWarnings({"unchecked", "rawtypes"}) + // Safe: Attributes guarantees iteration over matching AttributeKey / value pairs. public AttributesBuilder putAll(Attributes attributes) { if (attributes == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "putAll", "attributes"); return this; } - // Attributes must iterate over their entries with matching types for key / value, so this - // downcast to the raw type is safe. attributes.forEach((key, value) -> put((AttributeKey) key, value)); return this; } @Override public AttributesBuilder remove(AttributeKey key) { - if (key == null || key.getKey().isEmpty()) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "remove", "key"); + return this; + } + if (key.getKey().isEmpty()) { return this; } - return removeIf( - entryKey -> - key.getKey().equals(entryKey.getKey()) && key.getType().equals(entryKey.getType())); + return removeIf(entryKey -> + key.getKey().equals(entryKey.getKey()) && key.getType().equals(entryKey.getType())); } @Override public AttributesBuilder removeIf(Predicate> predicate) { if (predicate == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "removeIf", "predicate"); return this; } for (int i = 0; i < data.size() - 1; i += 2) { diff --git a/api/all/src/main/java/io/opentelemetry/api/common/AttributeKey.java b/api/all/src/main/java/io/opentelemetry/api/common/AttributeKey.java index 7743c315c50..f1fe7fbe324 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/AttributeKey.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/AttributeKey.java @@ -6,6 +6,7 @@ package io.opentelemetry.api.common; import io.opentelemetry.api.internal.InternalAttributeKeyImpl; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.List; import javax.annotation.concurrent.Immutable; @@ -28,41 +29,94 @@ public interface AttributeKey { /** Returns a new AttributeKey for String valued attributes. */ static AttributeKey stringKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "stringKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.STRING); + } return InternalAttributeKeyImpl.create(key, AttributeType.STRING); } /** Returns a new AttributeKey for Boolean valued attributes. */ static AttributeKey booleanKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "booleanKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.BOOLEAN); + } return InternalAttributeKeyImpl.create(key, AttributeType.BOOLEAN); } /** Returns a new AttributeKey for Long valued attributes. */ static AttributeKey longKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "longKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.LONG); + } return InternalAttributeKeyImpl.create(key, AttributeType.LONG); } /** Returns a new AttributeKey for Double valued attributes. */ static AttributeKey doubleKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "doubleKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.DOUBLE); + } return InternalAttributeKeyImpl.create(key, AttributeType.DOUBLE); } /** Returns a new AttributeKey for List<String> valued attributes. */ static AttributeKey> stringArrayKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "stringArrayKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.STRING_ARRAY); + } return InternalAttributeKeyImpl.create(key, AttributeType.STRING_ARRAY); } /** Returns a new AttributeKey for List<Boolean> valued attributes. */ static AttributeKey> booleanArrayKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "booleanArrayKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.BOOLEAN_ARRAY); + } return InternalAttributeKeyImpl.create(key, AttributeType.BOOLEAN_ARRAY); } /** Returns a new AttributeKey for List<Long> valued attributes. */ static AttributeKey> longArrayKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "longArrayKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.LONG_ARRAY); + } return InternalAttributeKeyImpl.create(key, AttributeType.LONG_ARRAY); } /** Returns a new AttributeKey for List<Double> valued attributes. */ static AttributeKey> doubleArrayKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "doubleArrayKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.DOUBLE_ARRAY); + } return InternalAttributeKeyImpl.create(key, AttributeType.DOUBLE_ARRAY); } + + /** + * Returns a new AttributeKey for {@link Value} valued attributes. + * + *

Simple attributes ({@link AttributeType#STRING}, {@link AttributeType#LONG}, {@link + * AttributeType#DOUBLE}, {@link AttributeType#BOOLEAN}, {@link AttributeType#STRING_ARRAY}, + * {@link AttributeType#LONG_ARRAY}, {@link AttributeType#DOUBLE_ARRAY}, {@link + * AttributeType#BOOLEAN_ARRAY}) should be used whenever possible. Instrumentations should assume + * that backends do not index individual properties of complex attributes, that querying or + * aggregating on such properties is inefficient and complicated, and that reporting complex + * attributes carries higher performance overhead. + * + * @since 1.59.0 + */ + static AttributeKey> valueKey(String key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "valueKey", "key"); + return InternalAttributeKeyImpl.create("", AttributeType.VALUE); + } + return InternalAttributeKeyImpl.create(key, AttributeType.VALUE); + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/common/AttributeType.java b/api/all/src/main/java/io/opentelemetry/api/common/AttributeType.java index 1c51e36d644..caf9b31e39c 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/AttributeType.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/AttributeType.java @@ -17,5 +17,11 @@ public enum AttributeType { STRING_ARRAY, BOOLEAN_ARRAY, LONG_ARRAY, - DOUBLE_ARRAY + DOUBLE_ARRAY, + /** + * {@link Value}-based attributes. + * + * @since 1.59.0 + */ + VALUE } diff --git a/api/all/src/main/java/io/opentelemetry/api/common/Attributes.java b/api/all/src/main/java/io/opentelemetry/api/common/Attributes.java index 2a9d43793a7..2b1aca414fa 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/Attributes.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/Attributes.java @@ -7,6 +7,7 @@ import static io.opentelemetry.api.common.ArrayBackedAttributes.sortAndFilterToAttributes; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.Map; import java.util.function.BiConsumer; import javax.annotation.Nullable; @@ -33,11 +34,58 @@ @Immutable public interface Attributes { - /** Returns the value for the given {@link AttributeKey}, or {@code null} if not found. */ + /** + * Returns the value for the given {@link AttributeKey}, or {@code null} if not found. + * + *

Note: this method will automatically return the corresponding {@link + * io.opentelemetry.api.common.Value} instance when passed a key of type {@link + * AttributeType#VALUE} and a simple attribute is found. This is the inverse of {@link + * AttributesBuilder#put(AttributeKey, Object)} when the key is {@link AttributeType#VALUE}. + * + *

    + *
  • If {@code put(AttributeKey.stringKey("key"), "a")} was called, then {@code + * get(AttributeKey.valueKey("key"))} returns {@code Value.of("a")}. + *
  • If {@code put(AttributeKey.longKey("key"), 1L)} was called, then {@code + * get(AttributeKey.valueKey("key"))} returns {@code Value.of(1L)}. + *
  • If {@code put(AttributeKey.doubleKey("key"), 1.0)} was called, then {@code + * get(AttributeKey.valueKey("key"))} returns {@code Value.of(1.0)}. + *
  • If {@code put(AttributeKey.booleanKey("key"), true)} was called, then {@code + * get(AttributeKey.valueKey("key"))} returns {@code Value.of(true)}. + *
  • If {@code put(AttributeKey.stringArrayKey("key"), Arrays.asList("a", "b"))} was called, + * then {@code get(AttributeKey.valueKey("key"))} returns {@code Value.of(Value.of("a"), + * Value.of("b"))}. + *
  • If {@code put(AttributeKey.longArrayKey("key"), Arrays.asList(1L, 2L))} was called, then + * {@code get(AttributeKey.valueKey("key"))} returns {@code Value.of(Value.of(1L), + * Value.of(2L))}. + *
  • If {@code put(AttributeKey.doubleArrayKey("key"), Arrays.asList(1.0, 2.0))} was called, + * then {@code get(AttributeKey.valueKey("key"))} returns {@code Value.of(Value.of(1.0), + * Value.of(2.0))}. + *
  • If {@code put(AttributeKey.booleanArrayKey("key"), Arrays.asList(true, false))} was + * called, then {@code get(AttributeKey.valueKey("key"))} returns {@code + * Value.of(Value.of(true), Value.of(false))}. + *
+ * + *

Further, if {@code put(AttributeKey.valueKey("key"), Value.of(emptyList()))} was called, + * then + * + *

    + *
  • {@code get(AttributeKey.stringArrayKey("key"))} + *
  • {@code get(AttributeKey.longArrayKey("key"))} + *
  • {@code get(AttributeKey.booleanArrayKey("key"))} + *
  • {@code get(AttributeKey.doubleArrayKey("key"))} + *
+ * + *

all return an empty list (as opposed to {@code null}). + */ @Nullable T get(AttributeKey key); - /** Iterates over all the key-value pairs of attributes contained by this instance. */ + /** + * Iterates over all the key-value pairs of attributes contained by this instance. + * + *

Note: {@link AttributeType#VALUE} attributes will be represented as simple attributes if + * possible. See {@link AttributesBuilder#put(AttributeKey, Object)} for more details. + */ void forEach(BiConsumer, ? super Object> consumer); /** The number of attributes contained in this. */ @@ -46,7 +94,12 @@ public interface Attributes { /** Whether there are any attributes contained in this. */ boolean isEmpty(); - /** Returns a read-only view of this {@link Attributes} as a {@link Map}. */ + /** + * Returns a read-only view of this {@link Attributes} as a {@link Map}. + * + *

Note: {@link AttributeType#VALUE} attributes will be represented as simple attributes in + * this map if possible. See {@link AttributesBuilder#put(AttributeKey, Object)} for more details. + */ Map, Object> asMap(); /** Returns a {@link Attributes} instance with no attributes. */ @@ -56,7 +109,15 @@ static Attributes empty() { /** Returns a {@link Attributes} instance with a single key-value pair. */ static Attributes of(AttributeKey key, T value) { - if (key == null || key.getKey().isEmpty() || value == null) { + if (key == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key"); + return empty(); + } + if (value == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value"); + return empty(); + } + if (key.getKey().isEmpty()) { return empty(); } return new ArrayBackedAttributes(new Object[] {key, value}); @@ -67,6 +128,18 @@ static Attributes of(AttributeKey key, T value) { * preserved. Duplicate keys will be removed. */ static Attributes of(AttributeKey key1, T value1, AttributeKey key2, U value2) { + if (key1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key1"); + } + if (value1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value1"); + } + if (key2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key2"); + } + if (value2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value2"); + } if (key1 == null || key1.getKey().isEmpty() || value1 == null) { return of(key2, value2); } @@ -94,6 +167,24 @@ static Attributes of( U value2, AttributeKey key3, V value3) { + if (key1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key1"); + } + if (value1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value1"); + } + if (key2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key2"); + } + if (value2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value2"); + } + if (key3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key3"); + } + if (value3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value3"); + } return sortAndFilterToAttributes(key1, value1, key2, value2, key3, value3); } @@ -110,6 +201,30 @@ static Attributes of( V value3, AttributeKey key4, W value4) { + if (key1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key1"); + } + if (value1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value1"); + } + if (key2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key2"); + } + if (value2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value2"); + } + if (key3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key3"); + } + if (value3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value3"); + } + if (key4 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key4"); + } + if (value4 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value4"); + } return sortAndFilterToAttributes(key1, value1, key2, value2, key3, value3, key4, value4); } @@ -129,6 +244,36 @@ static Attributes of( W value4, AttributeKey key5, X value5) { + if (key1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key1"); + } + if (value1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value1"); + } + if (key2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key2"); + } + if (value2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value2"); + } + if (key3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key3"); + } + if (value3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value3"); + } + if (key4 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key4"); + } + if (value4 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value4"); + } + if (key5 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key5"); + } + if (value5 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value5"); + } return sortAndFilterToAttributes( key1, value1, key2, value2, @@ -155,6 +300,42 @@ static Attributes of( X value5, AttributeKey key6, Y value6) { + if (key1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key1"); + } + if (value1 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value1"); + } + if (key2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key2"); + } + if (value2 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value2"); + } + if (key3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key3"); + } + if (value3 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value3"); + } + if (key4 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key4"); + } + if (value4 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value4"); + } + if (key5 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key5"); + } + if (value5 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value5"); + } + if (key6 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "key6"); + } + if (value6 == null) { + ApiUsageLogger.logNullParam(Attributes.class, "of", "value6"); + } return sortAndFilterToAttributes( key1, value1, key2, value2, diff --git a/api/all/src/main/java/io/opentelemetry/api/common/AttributesBuilder.java b/api/all/src/main/java/io/opentelemetry/api/common/AttributesBuilder.java index a7fe1be0ee0..6f41ab47261 100644 --- a/api/all/src/main/java/io/opentelemetry/api/common/AttributesBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/common/AttributesBuilder.java @@ -14,10 +14,13 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; +import javax.annotation.Nullable; /** A builder of {@link Attributes} supporting an arbitrary number of key-value pairs. */ public interface AttributesBuilder { @@ -35,18 +38,60 @@ public interface AttributesBuilder { // version. AttributesBuilder put(AttributeKey key, int value); - /** Puts a {@link AttributeKey} with associated value into this. */ - AttributesBuilder put(AttributeKey key, T value); + /** + * Puts an {@link AttributeKey} with an associated value into this if the value is non-null. + * Providing a null value does not remove or unset previously set values. + * + *

Simple attributes ({@link AttributeType#STRING}, {@link AttributeType#LONG}, {@link + * AttributeType#DOUBLE}, {@link AttributeType#BOOLEAN}, {@link AttributeType#STRING_ARRAY}, + * {@link AttributeType#LONG_ARRAY}, {@link AttributeType#DOUBLE_ARRAY}, {@link + * AttributeType#BOOLEAN_ARRAY}) should be used whenever possible. Instrumentations should assume + * that backends do not index individual properties of complex attributes, that querying or + * aggregating on such properties is inefficient and complicated, and that reporting complex + * attributes carries higher performance overhead. + * + *

Note: This method will automatically convert complex attributes ({@link + * AttributeType#VALUE}) to simple attributes when possible. + * + *

    + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of("a"))} is equivalent to calling + * {@code put(AttributeKey.stringKey("key"), "a")}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(1L))} is equivalent to calling + * {@code put(AttributeKey.longKey("key"), 1L)}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(1.0))} is equivalent to calling + * {@code put(AttributeKey.doubleKey("key"), 1.0)}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(true))} is equivalent to + * calling {@code put(AttributeKey.booleanKey("key"), true)}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(Value.of("a"), Value.of("b")))} + * is equivalent to calling {@code put(AttributeKey.stringArrayKey("key"), + * Arrays.asList("a", "b"))}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(Value.of(1L), Value.of(2L)))} + * is equivalent to calling {@code put(AttributeKey.longArrayKey("key"), Arrays.asList(1L, + * 2L))}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(Value.of(1.0), Value.of(2.0)))} + * is equivalent to calling {@code put(AttributeKey.doubleArrayKey("key"), + * Arrays.asList(1.0, 2.0))}. + *
  • Calling {@code put(AttributeKey.valueKey("key"), Value.of(Value.of(true), + * Value.of(false)))} is equivalent to calling {@code + * put(AttributeKey.booleanArrayKey("key"), Arrays.asList(true, false))}. + *
+ */ + AttributesBuilder put(AttributeKey key, @Nullable T value); /** - * Puts a String attribute into this. + * Puts a String attribute into this if the value is non-null. Providing a null value does not + * remove or unset previously set values. * *

Note: It is strongly recommended to use {@link #put(AttributeKey, Object)}, and pre-allocate * your keys, if possible. * * @return this Builder */ - default AttributesBuilder put(String key, String value) { + default AttributesBuilder put(String key, @Nullable String value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } return put(stringKey(key), value); } @@ -59,6 +104,10 @@ default AttributesBuilder put(String key, String value) { * @return this Builder */ default AttributesBuilder put(String key, long value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } return put(longKey(key), value); } @@ -71,6 +120,10 @@ default AttributesBuilder put(String key, long value) { * @return this Builder */ default AttributesBuilder put(String key, double value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } return put(doubleKey(key), value); } @@ -83,6 +136,10 @@ default AttributesBuilder put(String key, double value) { * @return this Builder */ default AttributesBuilder put(String key, boolean value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } return put(booleanKey(key), value); } @@ -95,7 +152,12 @@ default AttributesBuilder put(String key, boolean value) { * @return this Builder */ default AttributesBuilder put(String key, String... value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } if (value == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "value"); return this; } return put(stringArrayKey(key), Arrays.asList(value)); @@ -108,7 +170,12 @@ default AttributesBuilder put(String key, String... value) { */ @SuppressWarnings("unchecked") default AttributesBuilder put(AttributeKey> key, T... value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } if (value == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "value"); return this; } return put(key, Arrays.asList(value)); @@ -123,7 +190,12 @@ default AttributesBuilder put(AttributeKey> key, T... value) { * @return this Builder */ default AttributesBuilder put(String key, long... value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } if (value == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "value"); return this; } return put(longArrayKey(key), toList(value)); @@ -138,7 +210,12 @@ default AttributesBuilder put(String key, long... value) { * @return this Builder */ default AttributesBuilder put(String key, double... value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } if (value == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "value"); return this; } return put(doubleArrayKey(key), toList(value)); @@ -153,12 +230,40 @@ default AttributesBuilder put(String key, double... value) { * @return this Builder */ default AttributesBuilder put(String key, boolean... value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } if (value == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "value"); return this; } return put(booleanArrayKey(key), toList(value)); } + /** + * Puts a {@link Value} attribute into this. See {@link #put(AttributeKey, Object)} for details on + * how this method will automatically convert {@link Value} attributes to simple attributes when + * possible. + * + *

Note: It is strongly recommended to use {@link #put(AttributeKey, Object)}, and pre-allocate + * your keys, if possible. + * + * @return this Builder + * @since 1.59.0 + */ + default AttributesBuilder put(String key, Value value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "key"); + return this; + } + if (value == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "put", "value"); + return this; + } + return put(valueKey(key), value); + } + /** * Puts all the provided attributes into this Builder. * @@ -173,6 +278,10 @@ default AttributesBuilder put(String key, boolean... value) { * @return this Builder */ default AttributesBuilder remove(AttributeKey key) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "remove", "key"); + return this; + } // default implementation is no-op return this; } @@ -184,6 +293,10 @@ default AttributesBuilder remove(AttributeKey key) { * @return this Builder */ default AttributesBuilder removeIf(Predicate> filter) { + if (filter == null) { + ApiUsageLogger.logNullParam(AttributesBuilder.class, "removeIf", "filter"); + return this; + } // default implementation is no-op return this; } diff --git a/api/all/src/main/java/io/opentelemetry/api/common/Empty.java b/api/all/src/main/java/io/opentelemetry/api/common/Empty.java new file mode 100644 index 00000000000..b619eed6268 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/Empty.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +/** + * A singleton class representing an empty value, used as the generic type parameter for {@link + * Value} when representing empty values. + * + * @since 1.59.0 + */ +public final class Empty { + + private static final Empty INSTANCE = new Empty(); + + private Empty() {} + + public static Empty getInstance() { + return INSTANCE; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof Empty; + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public String toString() { + return "Empty"; + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/JsonEncoding.java b/api/all/src/main/java/io/opentelemetry/api/common/JsonEncoding.java new file mode 100644 index 00000000000..721e8fc5021 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/JsonEncoding.java @@ -0,0 +1,134 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.nio.ByteBuffer; +import java.util.Base64; +import java.util.List; + +final class JsonEncoding { + + private static final char[] HEX_DIGITS = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + @SuppressWarnings("unchecked") + static void append(StringBuilder sb, Value value) { + switch (value.getType()) { + case STRING: + appendString(sb, (String) value.getValue()); + break; + case LONG: + sb.append(value.getValue()); + break; + case DOUBLE: + appendDouble(sb, (Double) value.getValue()); + break; + case BOOLEAN: + sb.append(value.getValue()); + break; + case ARRAY: + appendArray(sb, (List>) value.getValue()); + break; + case KEY_VALUE_LIST: + appendMap(sb, (List) value.getValue()); + break; + case BYTES: + appendBytes(sb, (Value) value); + break; + case EMPTY: + sb.append("null"); + break; + } + } + + private static void appendString(StringBuilder sb, String value) { + sb.append('"'); + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + if (c < 0x20) { + // Control characters must be escaped as \\uXXXX + sb.append("\\u"); + sb.append(HEX_DIGITS[(c >> 12) & 0xF]); + sb.append(HEX_DIGITS[(c >> 8) & 0xF]); + sb.append(HEX_DIGITS[(c >> 4) & 0xF]); + sb.append(HEX_DIGITS[c & 0xF]); + } else { + sb.append(c); + } + } + } + sb.append('"'); + } + + private static void appendDouble(StringBuilder sb, double value) { + if (Double.isNaN(value)) { + sb.append("\"NaN\""); + } else if (Double.isInfinite(value)) { + sb.append(value > 0 ? "\"Infinity\"" : "\"-Infinity\""); + } else { + sb.append(value); + } + } + + private static void appendBytes(StringBuilder sb, Value value) { + ByteBuffer buf = value.getValue(); + byte[] bytes = new byte[buf.remaining()]; + // getValue() above returns a new ByteBuffer, so mutating its position here is safe + buf.get(bytes); + sb.append('"').append(Base64.getEncoder().encodeToString(bytes)).append('"'); + } + + private static void appendArray(StringBuilder sb, List> values) { + sb.append('['); + for (int i = 0; i < values.size(); i++) { + if (i > 0) { + sb.append(','); + } + append(sb, values.get(i)); + } + sb.append(']'); + } + + private static void appendMap(StringBuilder sb, List values) { + sb.append('{'); + for (int i = 0; i < values.size(); i++) { + if (i > 0) { + sb.append(','); + } + KeyValue kv = values.get(i); + appendString(sb, kv.getKey()); + sb.append(':'); + append(sb, kv.getValue()); + } + sb.append('}'); + } + + private JsonEncoding() {} +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/KeyValue.java b/api/all/src/main/java/io/opentelemetry/api/common/KeyValue.java new file mode 100644 index 00000000000..e5286015e91 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/KeyValue.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +/** + * Key-value pair of {@link String} key and {@link Value} value. + * + * @see Value#of(KeyValue...) + * @since 1.42.0 + */ +public interface KeyValue { + + /** Returns a {@link KeyValue} for the given {@code key} and {@code value}. */ + static KeyValue of(String key, Value value) { + return KeyValueImpl.create(key, value); + } + + /** Returns the key. */ + String getKey(); + + /** Returns the value. */ + Value getValue(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/KeyValueImpl.java b/api/all/src/main/java/io/opentelemetry/api/common/KeyValueImpl.java new file mode 100644 index 00000000000..1525c3f3c69 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/KeyValueImpl.java @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import com.google.auto.value.AutoValue; + +@AutoValue +abstract class KeyValueImpl implements KeyValue { + + KeyValueImpl() {} + + static KeyValueImpl create(String key, Value value) { + return new AutoValue_KeyValueImpl(key, value); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/KeyValueList.java b/api/all/src/main/java/io/opentelemetry/api/common/KeyValueList.java new file mode 100644 index 00000000000..06c257837e5 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/KeyValueList.java @@ -0,0 +1,71 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +final class KeyValueList implements Value> { + + private final List value; + + private KeyValueList(List value) { + this.value = value; + } + + static Value> create(KeyValue... value) { + List list = new ArrayList<>(value.length); + list.addAll(Arrays.asList(value)); + return new KeyValueList(Collections.unmodifiableList(list)); + } + + static Value> createFromMap(Map> value) { + KeyValue[] array = + value.entrySet().stream() + .map(entry -> KeyValue.of(entry.getKey(), entry.getValue())) + .toArray(KeyValue[]::new); + return create(array); + } + + @Override + public ValueType getType() { + return ValueType.KEY_VALUE_LIST; + } + + @Override + public List getValue() { + return value; + } + + @Override + public String asString() { + StringBuilder sb = new StringBuilder(); + JsonEncoding.append(sb, this); + return sb.toString(); + } + + @Override + public String toString() { + return "KeyValueList{" + asString() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof Value) && Objects.equals(this.value, ((Value) o).getValue()); + } + + @Override + public int hashCode() { + return value.hashCode(); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/Value.java b/api/all/src/main/java/io/opentelemetry/api/common/Value.java new file mode 100644 index 00000000000..308ad0c78fe --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/Value.java @@ -0,0 +1,159 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.nio.ByteBuffer; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * Value mirrors the proto AnyValue + * message type, and is used to model any type. + * + *

It can be used to represent: + * + *

    + *
  • Primitive values via {@link #of(long)}, {@link #of(String)}, {@link #of(boolean)}, {@link + * #of(double)}. + *
  • String-keyed maps (i.e. associative arrays, dictionaries) via {@link #of(KeyValue...)}, + * {@link #of(Map)}. Note, because map values are type {@link Value}, maps can be nested + * within other maps. + *
  • Arrays (heterogeneous or homogeneous) via {@link #of(Value[])}. Note, because array values + * are type {@link Value}, arrays can contain primitives, complex types like maps or arrays, + * or any combination. + *
  • Raw bytes via {@link #of(byte[])} + *
  • An empty value via {@link #empty()} + *
+ * + *

Currently, Value is only used as an argument for {@link + * io.opentelemetry.api.logs.LogRecordBuilder#setBody(Value)}. + * + * @param the type. See {@link #getValue()} for description of types. + * @since 1.42.0 + */ +public interface Value { + + /** Returns an {@link Value} for the {@link String} value. */ + static Value of(String value) { + Objects.requireNonNull(value, "value must not be null"); + return ValueString.create(value); + } + + /** Returns an {@link Value} for the {@code boolean} value. */ + static Value of(boolean value) { + return ValueBoolean.create(value); + } + + /** Returns an {@link Value} for the {@code long} value. */ + static Value of(long value) { + return ValueLong.create(value); + } + + /** Returns an {@link Value} for the {@code double} value. */ + static Value of(double value) { + return ValueDouble.create(value); + } + + /** Returns an {@link Value} for the {@code byte[]} value. */ + static Value of(byte[] value) { + Objects.requireNonNull(value, "value must not be null"); + return ValueBytes.create(value); + } + + /** Returns an {@link Value} for the array of {@link Value} values. */ + static Value>> of(Value... value) { + Objects.requireNonNull(value, "value must not be null"); + return ValueArray.create(value); + } + + /** Returns an {@link Value} for the list of {@link Value} values. */ + static Value>> of(List> value) { + Objects.requireNonNull(value, "value must not be null"); + return ValueArray.create(value); + } + + /** + * Returns an {@link Value} for the array of {@link KeyValue} values. {@link KeyValue#getKey()} + * values should not repeat - duplicates may be dropped. + */ + static Value> of(KeyValue... value) { + Objects.requireNonNull(value, "value must not be null"); + return KeyValueList.create(value); + } + + /** Returns an {@link Value} for the {@link Map} of key, {@link Value}. */ + static Value> of(Map> value) { + Objects.requireNonNull(value, "value must not be null"); + return KeyValueList.createFromMap(value); + } + + /** + * Returns an empty {@link Value}. + * + * @since 1.59.0 + */ + static Value empty() { + return ValueEmpty.create(); + } + + /** Returns the type of this {@link Value}. Useful for building switch statements. */ + ValueType getType(); + + /** + * Returns the value for this {@link Value}. + * + *

The return type varies by {@link #getType()} as described below: + * + *

    + *
  • {@link ValueType#STRING} returns {@link String} + *
  • {@link ValueType#BOOLEAN} returns {@code boolean} + *
  • {@link ValueType#LONG} returns {@code long} + *
  • {@link ValueType#DOUBLE} returns {@code double} + *
  • {@link ValueType#ARRAY} returns {@link List} of {@link Value} + *
  • {@link ValueType#KEY_VALUE_LIST} returns {@link List} of {@link KeyValue} + *
  • {@link ValueType#BYTES} returns read only {@link ByteBuffer}. See {@link + * ByteBuffer#asReadOnlyBuffer()}. + *
  • {@link ValueType#EMPTY} returns {@link Empty} + *
+ */ + T getValue(); + + /** + * Returns a string representation of this {@link Value}. + * + *

The output follows the + * string representation guidance for complex attribute value types: + * + *

    + *
  • {@link ValueType#STRING} String as-is without surrounding quotes. Examples: {@code hello + * world}, (empty string) + *
  • {@link ValueType#BOOLEAN} JSON boolean. Examples: {@code true}, {@code false} + *
  • {@link ValueType#LONG} JSON number. Examples: {@code 42}, {@code -123} + *
  • {@link ValueType#DOUBLE} JSON number, or {@code NaN}, {@code Infinity}, {@code -Infinity} + * for special values (without surrounding quotes). Examples: {@code 3.14159}, {@code + * 1.23e10}, {@code NaN}, {@code -Infinity} + *
  • {@link ValueType#ARRAY} JSON array. Nested byte arrays are encoded as Base64-encoded JSON + * strings. Nested empty values are encoded as JSON {@code null}. The special floating point + * values NaN and Infinity are encoded as JSON strings {@code "NaN"}, {@code "Infinity"}, + * and {@code "-Infinity"}. Examples: {@code []}, {@code [1, "-Infinity", "a", true, + * {"nested": "aGVsbG8gd29ybGQ="}]} + *
  • {@link ValueType#KEY_VALUE_LIST} JSON object. Nested byte arrays are encoded as + * Base64-encoded JSON strings. Nested empty values are encoded as JSON {@code null}. The + * special floating point values NaN and Infinity are encoded as JSON strings {@code "NaN"}, + * {@code "Infinity"}, and {@code "-Infinity"}. Examples: {@code {}}, {@code {"a": + * "-Infinity", "b": 2, "c": [3, null]}} + *
  • {@link ValueType#BYTES} Base64-encoded bytes without surrounding quotes. Example: {@code + * aGVsbG8gd29ybGQ=} + *
  • {@link ValueType#EMPTY} The empty string. + *
+ * + * @return a string representation of this value + */ + String asString(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueArray.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueArray.java new file mode 100644 index 00000000000..2b44310e243 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueArray.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +final class ValueArray implements Value>> { + + private final List> value; + + private ValueArray(List> value) { + this.value = value; + } + + static Value>> create(Value... value) { + List> list = new ArrayList<>(value.length); + list.addAll(Arrays.asList(value)); + return new ValueArray(Collections.unmodifiableList(list)); + } + + static Value>> create(List> value) { + return new ValueArray(Collections.unmodifiableList(value)); + } + + @Override + public ValueType getType() { + return ValueType.ARRAY; + } + + @Override + public List> getValue() { + return value; + } + + @Override + public String asString() { + StringBuilder sb = new StringBuilder(); + JsonEncoding.append(sb, this); + return sb.toString(); + } + + @Override + public String toString() { + return "ValueArray{" + asString() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof Value) && Objects.equals(this.value, ((Value) o).getValue()); + } + + @Override + public int hashCode() { + return value.hashCode(); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueBoolean.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueBoolean.java new file mode 100644 index 00000000000..98caa7a27f4 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueBoolean.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.util.Objects; + +final class ValueBoolean implements Value { + + private final boolean value; + + private ValueBoolean(boolean value) { + this.value = value; + } + + static Value create(boolean value) { + return new ValueBoolean(value); + } + + @Override + public ValueType getType() { + return ValueType.BOOLEAN; + } + + @Override + public Boolean getValue() { + return value; + } + + @Override + public String asString() { + StringBuilder sb = new StringBuilder(); + JsonEncoding.append(sb, this); + return sb.toString(); + } + + @Override + public String toString() { + return "ValueBoolean{" + asString() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof Value) && Objects.equals(this.value, ((Value) o).getValue()); + } + + @Override + public int hashCode() { + return Boolean.hashCode(value); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueBytes.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueBytes.java new file mode 100644 index 00000000000..fe5bb072abf --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueBytes.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.Base64; + +final class ValueBytes implements Value { + + private final byte[] raw; + + private ValueBytes(byte[] value) { + this.raw = value; + } + + static Value create(byte[] value) { + return new ValueBytes(Arrays.copyOf(value, value.length)); + } + + @Override + public ValueType getType() { + return ValueType.BYTES; + } + + @Override + public ByteBuffer getValue() { + return ByteBuffer.wrap(raw).asReadOnlyBuffer(); + } + + @Override + public String asString() { + byte[] bytes = raw; + return Base64.getEncoder().encodeToString(bytes); + } + + @Override + public String toString() { + return "ValueBytes{" + asString() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof ValueBytes) && Arrays.equals(this.raw, ((ValueBytes) o).raw); + } + + @Override + public int hashCode() { + return Arrays.hashCode(raw); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueDouble.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueDouble.java new file mode 100644 index 00000000000..022a895b850 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueDouble.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.util.Objects; + +final class ValueDouble implements Value { + + private final double value; + + private ValueDouble(double value) { + this.value = value; + } + + static Value create(double value) { + return new ValueDouble(value); + } + + @Override + public ValueType getType() { + return ValueType.DOUBLE; + } + + @Override + public Double getValue() { + return value; + } + + @Override + public String asString() { + if (Double.isNaN(value)) { + return "NaN"; + } else if (Double.isInfinite(value)) { + return value > 0 ? "Infinity" : "-Infinity"; + } + return String.valueOf(value); + } + + @Override + public String toString() { + return "ValueDouble{" + asString() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof Value) && Objects.equals(this.value, ((Value) o).getValue()); + } + + @Override + public int hashCode() { + return Double.hashCode(value); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueEmpty.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueEmpty.java new file mode 100644 index 00000000000..47dc99ccd06 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueEmpty.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +final class ValueEmpty implements Value { + + private static final ValueEmpty INSTANCE = new ValueEmpty(); + + private ValueEmpty() {} + + static Value create() { + return INSTANCE; + } + + @Override + public ValueType getType() { + return ValueType.EMPTY; + } + + @Override + public Empty getValue() { + return Empty.getInstance(); + } + + @Override + public String asString() { + return ""; + } + + @Override + public String toString() { + return "ValueEmpty{}"; + } + + @Override + public boolean equals(Object o) { + return o instanceof ValueEmpty; + } + + @Override + public int hashCode() { + return 0; + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueLong.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueLong.java new file mode 100644 index 00000000000..6d99a6c4749 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueLong.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.util.Objects; + +final class ValueLong implements Value { + + private final long value; + + private ValueLong(long value) { + this.value = value; + } + + static Value create(long value) { + return new ValueLong(value); + } + + @Override + public ValueType getType() { + return ValueType.LONG; + } + + @Override + public Long getValue() { + return value; + } + + @Override + public String asString() { + StringBuilder sb = new StringBuilder(); + JsonEncoding.append(sb, this); + return sb.toString(); + } + + @Override + public String toString() { + return "ValueLong{" + asString() + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof Value) && Objects.equals(this.value, ((Value) o).getValue()); + } + + @Override + public int hashCode() { + return Long.hashCode(value); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueString.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueString.java new file mode 100644 index 00000000000..65886b140de --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueString.java @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import java.util.Objects; + +final class ValueString implements Value { + + private final String value; + + private ValueString(String value) { + this.value = value; + } + + static Value create(String value) { + return new ValueString(value); + } + + @Override + public ValueType getType() { + return ValueType.STRING; + } + + @Override + public String getValue() { + return value; + } + + @Override + public String asString() { + return value; + } + + @Override + public String toString() { + return "ValueString{" + value + "}"; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + return (o instanceof Value) && Objects.equals(this.value, ((Value) o).getValue()); + } + + @Override + public int hashCode() { + return value.hashCode(); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/common/ValueType.java b/api/all/src/main/java/io/opentelemetry/api/common/ValueType.java new file mode 100644 index 00000000000..8b259824b5e --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/common/ValueType.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +/** + * AnyValue type options, mirroring AnyValue#value + * options. + * + * @since 1.42.0 + */ +public enum ValueType { + STRING, + BOOLEAN, + LONG, + DOUBLE, + ARRAY, + KEY_VALUE_LIST, + BYTES, + /** + * Empty value. + * + * @since 1.59.0 + */ + EMPTY +} diff --git a/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigException.java b/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigException.java new file mode 100644 index 00000000000..2a9f221d59e --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigException.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +/** An exception that is thrown when errors occur with declarative configuration. */ +public class DeclarativeConfigException extends RuntimeException { + + private static final long serialVersionUID = 3036584181551130522L; + + /** Create a new configuration exception with specified {@code message} and without a cause. */ + public DeclarativeConfigException(String message) { + super(message); + } + + /** Create a new configuration exception with specified {@code message} and {@code cause}. */ + public DeclarativeConfigException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigProperties.java b/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigProperties.java new file mode 100644 index 00000000000..bcd17a98d9b --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigProperties.java @@ -0,0 +1,288 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +import io.opentelemetry.common.ComponentLoader; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * An interface for accessing declarative configuration data. + * + *

An instance of {@link DeclarativeConfigProperties} is equivalent to a YAML mapping node. It has accessors for + * reading scalar properties, {@link #getStructured(String)} for reading children which are + * themselves mappings, and {@link #getStructuredList(String)} for reading children which are + * sequences of mappings. + */ +public interface DeclarativeConfigProperties { + + /** + * Return an empty {@link DeclarativeConfigProperties} instance. + * + *

Useful for walking the tree without checking for null. For example, to access a string key + * nested at .foo.bar.baz, call: {@code config.getStructured("foo", empty()).getStructured("bar", + * empty()).getString("baz")}. + */ + static DeclarativeConfigProperties empty() { + return EmptyDeclarativeConfigProperties.getInstance(); + } + + /** Return a map representation of the {@code declarativeConfigProperties}. */ + static Map toMap(DeclarativeConfigProperties declarativeConfigProperties) { + return DeclarativeConfigPropertyUtil.toMap(declarativeConfigProperties); + } + + /** + * Returns a {@link String} configuration property. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * string + */ + @Nullable + String getString(String name); + + /** + * Returns a {@link String} configuration property. + * + * @return a {@link String} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar string + */ + default String getString(String name, String defaultValue) { + String value = getString(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Boolean} configuration property. Implementations should use the same rules as + * {@link Boolean#parseBoolean(String)} for handling the values. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * boolean + */ + @Nullable + Boolean getBoolean(String name); + + /** + * Returns a {@link Boolean} configuration property. + * + * @return a {@link Boolean} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar boolean + */ + default boolean getBoolean(String name, boolean defaultValue) { + Boolean value = getBoolean(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Integer} configuration property. + * + *

If the underlying config property is {@link Long}, it is converted to {@link Integer} with + * {@link Long#intValue()} which may result in loss of precision. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * integer + */ + @Nullable + Integer getInt(String name); + + /** + * Returns a {@link Integer} configuration property. + * + *

If the underlying config property is {@link Long}, it is converted to {@link Integer} with + * {@link Long#intValue()} which may result in loss of precision. + * + * @return a {@link Integer} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar integer + */ + default int getInt(String name, int defaultValue) { + Integer value = getInt(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Long} configuration property. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * long + */ + @Nullable + Long getLong(String name); + + /** + * Returns a {@link Long} configuration property. + * + * @return a {@link Long} configuration property or {@code defaultValue} if a property with {@code + * name} has not been configured or is not a valid scalar long + */ + default long getLong(String name, long defaultValue) { + Long value = getLong(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Double} configuration property. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * double + */ + @Nullable + Double getDouble(String name); + + /** + * Returns a {@link Double} configuration property. + * + * @return a {@link Double} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar double + */ + default double getDouble(String name, double defaultValue) { + Double value = getDouble(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link List} configuration property. Empty values and values which do not map to the + * {@code scalarType} will be removed. + * + * @param name the property name + * @param scalarType the scalar type, one of {@link String}, {@link Boolean}, {@link Long} or + * {@link Double} + * @return a {@link List} configuration property, or null if the property has not been configured + * or if the property is not a valid sequence of scalars + * @throws DeclarativeConfigException if {@code scalarType} is not supported + */ + @Nullable + List getScalarList(String name, Class scalarType); + + /** + * Returns a {@link List} configuration property. Empty values and values which do not map to the + * {@code scalarType} will be removed. + * + * @param name the property name + * @param scalarType the scalar type, one of {@link String}, {@link Boolean}, {@link Long} or + * {@link Double} + * @return a {@link List} configuration property or {@code defaultValue} if a property with {@code + * name} has not been configured or is not a valid sequence of scalars + */ + default List getScalarList(String name, Class scalarType, List defaultValue) { + List value = getScalarList(name, scalarType); + return value == null ? defaultValue : value; + } + + /** + * Returns whether the property with {@code name} holds a value which {@link #getString(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar string, + * false otherwise, including when the property is null + */ + boolean isString(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getBoolean(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar boolean, + * false otherwise, including when the property is null + */ + boolean isBoolean(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getInt(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar integer, + * false otherwise, including when the property is null + */ + boolean isInt(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getLong(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar long, + * false otherwise, including when the property is null + */ + boolean isLong(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getDouble(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar double, + * false otherwise, including when the property is null + */ + boolean isDouble(String name); + + /** + * Returns a {@link DeclarativeConfigProperties} configuration property. + * + * @return a map-valued configuration property, or {@code null} if {@code name} has not been + * configured or is not a mapping + */ + @Nullable + DeclarativeConfigProperties getStructured(String name); + + /** + * Returns a {@link DeclarativeConfigProperties} configuration property. + * + * @return a map-valued configuration property, or {@code defaultValue} if {@code name} has not + * been configured or is not a mapping + */ + default DeclarativeConfigProperties getStructured( + String name, DeclarativeConfigProperties defaultValue) { + DeclarativeConfigProperties value = getStructured(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link DeclarativeConfigProperties} configuration property, or {@link #empty()} if a + * property with {@code name} has not been configured. + * + *

This is syntactic sugar for the common operation of calling {@code + * config.getStructured(name, empty())}. If you need to distinguish between a property being set + * but empty vs. not set, use {@link #getStructured(String)}. + * + * @return a map-valued configuration property, or an empty {@link DeclarativeConfigProperties} + * instance if {@code name} has not been configured or is not a mapping + */ + default DeclarativeConfigProperties get(String name) { + return getStructured(name, empty()); + } + + /** + * Returns a list of {@link DeclarativeConfigProperties} configuration property. + * + * @return a list of map-valued configuration property, or {@code null} if {@code name} has not + * been configured or is not a sequence of mappings + */ + @Nullable + List getStructuredList(String name); + + /** + * Returns a list of {@link DeclarativeConfigProperties} configuration property. + * + * @return a list of map-valued configuration property, or {@code defaultValue} if {@code name} + * has not been configured or is not a sequence of mappings + */ + default List getStructuredList( + String name, List defaultValue) { + List value = getStructuredList(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a set of all configuration property keys. + * + * @return the configuration property keys + */ + Set getPropertyKeys(); + + /** Return a {@link ComponentLoader} that should be used to load SPIs. */ + ComponentLoader getComponentLoader(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigPropertyUtil.java b/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigPropertyUtil.java new file mode 100644 index 00000000000..f736e65ac13 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/config/DeclarativeConfigPropertyUtil.java @@ -0,0 +1,133 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +import static java.util.stream.Collectors.toList; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.BiFunction; +import javax.annotation.Nullable; + +final class DeclarativeConfigPropertyUtil { + + private DeclarativeConfigPropertyUtil() {} + + private static final List> + valueResolvers = + Arrays.asList( + DeclarativeConfigPropertyUtil::getString, + DeclarativeConfigPropertyUtil::getBoolean, + DeclarativeConfigPropertyUtil::getLong, + DeclarativeConfigPropertyUtil::getDouble, + DeclarativeConfigPropertyUtil::getStringList, + DeclarativeConfigPropertyUtil::getBooleanList, + DeclarativeConfigPropertyUtil::getLongList, + DeclarativeConfigPropertyUtil::getDoubleList, + DeclarativeConfigPropertyUtil::getStructuredList, + DeclarativeConfigPropertyUtil::getStructured); + + static Map toMap(DeclarativeConfigProperties declarativeConfigProperties) { + Set propertyKeys = declarativeConfigProperties.getPropertyKeys(); + Map result = new HashMap<>(propertyKeys.size()); + for (String key : declarativeConfigProperties.getPropertyKeys()) { + result.put(key, resolveValue(key, declarativeConfigProperties)); + } + return result; + } + + @Nullable + private static Object resolveValue( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + for (int i = 0; i < valueResolvers.size(); i++) { + try { + Object value = valueResolvers.get(i).apply(key, declarativeConfigProperties); + if (value != null) { + return value; + } + } catch (DeclarativeConfigException e) { + // Ignore and continue + } + } + return null; + } + + @Nullable + private static Object getString( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isString(key) + ? declarativeConfigProperties.getString(key) + : null; + } + + @Nullable + private static Object getBoolean( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isBoolean(key) + ? declarativeConfigProperties.getBoolean(key) + : null; + } + + @Nullable + private static Object getLong( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isLong(key) + ? declarativeConfigProperties.getLong(key) + : null; + } + + @Nullable + private static Object getDouble( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isDouble(key) + ? declarativeConfigProperties.getDouble(key) + : null; + } + + @Nullable + private static Object getStringList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, String.class); + } + + @Nullable + private static Object getBooleanList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, Boolean.class); + } + + @Nullable + private static Object getLongList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, Long.class); + } + + @Nullable + private static Object getDoubleList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, Double.class); + } + + @Nullable + private static Object getStructuredList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return Optional.ofNullable(declarativeConfigProperties.getStructuredList(key)) + .map(list -> list.stream().map(DeclarativeConfigPropertyUtil::toMap).collect(toList())) + .orElse(null); + } + + @Nullable + private static Object getStructured( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return Optional.ofNullable(declarativeConfigProperties.getStructured(key)) + .map(DeclarativeConfigPropertyUtil::toMap) + .orElse(null); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/config/EmptyDeclarativeConfigProperties.java b/api/all/src/main/java/io/opentelemetry/api/config/EmptyDeclarativeConfigProperties.java new file mode 100644 index 00000000000..4f4945c3c11 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/config/EmptyDeclarativeConfigProperties.java @@ -0,0 +1,110 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +import io.opentelemetry.common.ComponentLoader; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import javax.annotation.Nullable; + +/** Empty instance of {@link DeclarativeConfigProperties}. */ +final class EmptyDeclarativeConfigProperties implements DeclarativeConfigProperties { + + private static final EmptyDeclarativeConfigProperties INSTANCE = + new EmptyDeclarativeConfigProperties(); + private static final ComponentLoader COMPONENT_LOADER = + ComponentLoader.forClassLoader(EmptyDeclarativeConfigProperties.class.getClassLoader()); + + private EmptyDeclarativeConfigProperties() {} + + static EmptyDeclarativeConfigProperties getInstance() { + return INSTANCE; + } + + @Nullable + @Override + public String getString(String name) { + return null; + } + + @Nullable + @Override + public Boolean getBoolean(String name) { + return null; + } + + @Nullable + @Override + public Integer getInt(String name) { + return null; + } + + @Nullable + @Override + public Long getLong(String name) { + return null; + } + + @Nullable + @Override + public Double getDouble(String name) { + return null; + } + + @Nullable + @Override + public List getScalarList(String name, Class scalarType) { + return null; + } + + @Override + public boolean isString(String name) { + return false; + } + + @Override + public boolean isBoolean(String name) { + return false; + } + + @Override + public boolean isInt(String name) { + return false; + } + + @Override + public boolean isLong(String name) { + return false; + } + + @Override + public boolean isDouble(String name) { + return false; + } + + @Nullable + @Override + public DeclarativeConfigProperties getStructured(String name) { + return null; + } + + @Nullable + @Override + public List getStructuredList(String name) { + return null; + } + + @Override + public Set getPropertyKeys() { + return Collections.emptySet(); + } + + @Override + public ComponentLoader getComponentLoader() { + return COMPONENT_LOADER; + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/config/package-info.java b/api/all/src/main/java/io/opentelemetry/api/config/package-info.java new file mode 100644 index 00000000000..f80a20ca361 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/config/package-info.java @@ -0,0 +1,10 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** API for declarative configuration. */ +@ParametersAreNonnullByDefault +package io.opentelemetry.api.config; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/api/all/src/main/java/io/opentelemetry/api/impl/Base16EncodingUtils.java b/api/all/src/main/java/io/opentelemetry/api/impl/Base16EncodingUtils.java new file mode 100644 index 00000000000..d25e90208b9 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/impl/Base16EncodingUtils.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.impl; + +import io.opentelemetry.api.internal.OtelEncodingUtils; + +/** + * Base16 encoding and decoding utilities. + * + *

This class is not intended for use by application developers. Its API is stable and will not + * be changed or removed in a backwards-incompatible manner. + * + * @since 1.68.0 + */ +public final class Base16EncodingUtils { + + /** + * Returns the {@code long} value whose base16 representation is stored in the first 16 chars of + * {@code chars} starting from the {@code offset}. + * + * @param chars the base16 representation of the {@code long}. + * @param offset the starting offset in the {@code CharSequence}. + */ + public static long longFromBase16String(CharSequence chars, int offset) { + return OtelEncodingUtils.longFromBase16String(chars, offset); + } + + /** + * Appends the base16 encoding of the specified {@code value} to the {@code dest}. + * + * @param value the value to be converted. + * @param dest the destination char array. + * @param destOffset the starting offset in the destination char array. + */ + public static void longToBase16String(long value, char[] dest, int destOffset) { + OtelEncodingUtils.longToBase16String(value, dest, destOffset); + } + + /** Returns the {@code byte[]} decoded from the given hex {@link CharSequence}. */ + public static byte[] bytesFromBase16(CharSequence value, int length) { + return OtelEncodingUtils.bytesFromBase16(value, length); + } + + /** Fills {@code bytes} with bytes decoded from the given hex {@link CharSequence}. */ + public static void bytesFromBase16(CharSequence value, int length, byte[] bytes) { + OtelEncodingUtils.bytesFromBase16(value, length, bytes); + } + + /** Returns whether the {@link CharSequence} is a valid hex string. */ + public static boolean isValidBase16String(CharSequence value) { + return OtelEncodingUtils.isValidBase16String(value); + } + + private Base16EncodingUtils() {} +} diff --git a/api/all/src/main/java/io/opentelemetry/api/impl/InstrumentationUtil.java b/api/all/src/main/java/io/opentelemetry/api/impl/InstrumentationUtil.java new file mode 100644 index 00000000000..ab4ba5791eb --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/impl/InstrumentationUtil.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.impl; + +import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; +import java.util.Objects; + +/** + * Utility for suppressing instrumentation cycles between exporters which leverage various client + * libraries in their implementations and the otel java agent which instruments those client + * libraries. + * + *

This class is not intended for use by application developers. Its API is stable and will not + * be changed or removed in a backwards-incompatible manner. + * + * @since 1.63.0 + */ +public final class InstrumentationUtil { + private static final ContextKey SUPPRESS_INSTRUMENTATION_KEY = + ContextKey.named("suppress_instrumentation"); + + private InstrumentationUtil() {} + + /** + * Adds a Context boolean key that will allow to identify HTTP calls coming from OTel exporters. + * The key later be checked by an automatic instrumentation to avoid tracing OTel exporter's + * calls. + */ + public static void suppressInstrumentation(Runnable runnable) { + Context.current().with(SUPPRESS_INSTRUMENTATION_KEY, true).wrap(runnable).run(); + } + + /** + * Checks if an automatic instrumentation should be suppressed with the provided Context. + * + * @return TRUE to suppress the automatic instrumentation, FALSE to continue with the + * instrumentation. + */ + public static boolean shouldSuppressInstrumentation(Context context) { + return Objects.equals(context.get(SUPPRESS_INSTRUMENTATION_KEY), true); + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/TemporaryBuffers.java b/api/all/src/main/java/io/opentelemetry/api/impl/TemporaryBuffers.java similarity index 80% rename from api/all/src/main/java/io/opentelemetry/api/internal/TemporaryBuffers.java rename to api/all/src/main/java/io/opentelemetry/api/impl/TemporaryBuffers.java index 43a415fbee4..c3a6a1c2c82 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/TemporaryBuffers.java +++ b/api/all/src/main/java/io/opentelemetry/api/impl/TemporaryBuffers.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.api.internal; +package io.opentelemetry.api.impl; /** * {@link ThreadLocal} buffers for use when creating new derived objects such as {@link String}s. @@ -12,8 +12,10 @@ * should get a temporary buffer, fill it with data, and finish by converting into the derived * object within the same method to avoid multiple usages of the same buffer. * - *

This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. + *

This class is not intended for use by application developers. Its API is stable and will not + * be changed or removed in a backwards-incompatible manner. + * + * @since 1.68.0 */ public final class TemporaryBuffers { @@ -24,6 +26,9 @@ public final class TemporaryBuffers { * {@code len} as this buffer will remain for the lifetime of the thread. The returned buffer will * not be zeroed and may be larger than the requested size, you must make sure to fill the entire * content to the desired value and set the length explicitly when converting to a {@link String}. + * + * @param len the minimum buffer capacity + * @return a reusable thread-local character buffer with capacity of at least {@code len} */ public static char[] chars(int len) { char[] buffer = CHAR_ARRAY.get(); diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableKeyValuePairs.java b/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableKeyValuePairs.java index 333a9bdf91f..4e6b19cee36 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableKeyValuePairs.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableKeyValuePairs.java @@ -32,6 +32,7 @@ @Immutable public abstract class ImmutableKeyValuePairs { private final Object[] data; + private int hashcode; /** * Stores the raw object data directly. Does not do any de-duping or sorting. If you use this @@ -211,6 +212,12 @@ private static Object[] dedupe(Object[] data, Comparator keyComparator) { // Skip entries with null value, we do it here because we want them to overwrite and remove // entries with same key that we already added. if (value == null) { + // When the value is null, there are two cases: + // 1. next key is the same as the current one, it may cause ArrayIndexOutOfBoundsException, + // so we reset the previous key to null to avoid this + // 2. next key is different than the current one; In this case, whether the previous key is + // null or not will have no impact. + previousKey = null; continue; } previousKey = key; @@ -241,9 +248,13 @@ public boolean equals(@Nullable Object o) { @Override public int hashCode() { - int result = 1; - result *= 1000003; - result ^= Arrays.hashCode(data); + int result = hashcode; + if (result == 0) { + result = 1; + result *= 1000003; + result ^= Arrays.hashCode(data); + hashcode = result; + } return result; } @@ -263,4 +274,13 @@ public String toString() { sb.append("}"); return sb.toString(); } + + /** + * Return the backing data array for these attributes. This is only exposed for internal use by + * opentelemetry authors. The contents of the array MUST NOT be modified. + */ + @SuppressWarnings("AvoidObjectArrays") + public Object[] getData() { + return data; + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableSpanContext.java b/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableSpanContext.java index 886d67107de..13bfff66d99 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableSpanContext.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/ImmutableSpanContext.java @@ -54,6 +54,8 @@ private static AutoValue_ImmutableSpanContext createInternal( * @param traceFlags the trace flags of the {@code SpanContext}. * @param traceState the trace state for the {@code SpanContext}. * @param remote the remote flag for the {@code SpanContext}. + * @param skipIdValidation pass true to skip validation of trace ID and span ID as an optimization + * in cases where they are known to have been already validated. * @return a new {@code SpanContext} with the given identifiers and options. */ public static SpanContext create( diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/IncubatingUtil.java b/api/all/src/main/java/io/opentelemetry/api/internal/IncubatingUtil.java new file mode 100644 index 00000000000..e03b1e22f8c --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/internal/IncubatingUtil.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.internal; + +import io.opentelemetry.api.OpenTelemetry; +import java.lang.reflect.Method; +import javax.annotation.Nullable; + +/** + * Incubating utilities. + * + *

This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class IncubatingUtil { + private IncubatingUtil() {} + + @SuppressWarnings("unchecked") + public static T incubatingApiIfAvailable(T stableApi, String incubatingClassName) { + try { + Class incubatingClass = Class.forName(incubatingClassName); + Method getInstance = incubatingClass.getDeclaredMethod("getNoop"); + return (T) getInstance.invoke(null); + } catch (Exception e) { + return stableApi; + } + } + + @Nullable + public static OpenTelemetry obfuscatedOpenTelemetryIfIncubating(OpenTelemetry openTelemetry) { + try { + Class extendedClass = + Class.forName("io.opentelemetry.api.incubator.ExtendedOpenTelemetry"); + if (extendedClass.isInstance(openTelemetry)) { + Class incubatingClass = + Class.forName( + "io.opentelemetry.api.incubator.internal.ObfuscatedExtendedOpenTelemetry"); + return (OpenTelemetry) + incubatingClass + .getDeclaredConstructor(extendedClass) + .newInstance(extendedClass.cast(openTelemetry)); + } + } catch (Exception e) { + // incubator not available + } + return null; + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/InternalAttributeKeyImpl.java b/api/all/src/main/java/io/opentelemetry/api/internal/InternalAttributeKeyImpl.java index dfeca408c19..7d1e4486b55 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/InternalAttributeKeyImpl.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/InternalAttributeKeyImpl.java @@ -5,6 +5,8 @@ package io.opentelemetry.api.internal; +import static java.util.Objects.requireNonNull; + import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.AttributeType; import java.nio.charset.StandardCharsets; @@ -25,14 +27,8 @@ public final class InternalAttributeKeyImpl implements AttributeKey { @Nullable private byte[] keyUtf8; private InternalAttributeKeyImpl(AttributeType type, String key) { - if (type == null) { - throw new NullPointerException("Null type"); - } - this.type = type; - if (key == null) { - throw new NullPointerException("Null key"); - } - this.key = key; + this.type = requireNonNull(type, "Null type"); + this.key = requireNonNull(key, "Null key"); this.hashCode = buildHashCode(type, key); } diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/OtelEncodingUtils.java b/api/all/src/main/java/io/opentelemetry/api/internal/OtelEncodingUtils.java index ba8e99fe1c3..2b062a12bd3 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/OtelEncodingUtils.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/OtelEncodingUtils.java @@ -43,9 +43,12 @@ private static byte[] buildDecodingArray() { } private static boolean[] buildValidHexArray() { - boolean[] validHex = new boolean[Character.MAX_VALUE]; - for (int i = 0; i < Character.MAX_VALUE; i++) { - validHex[i] = (48 <= i && i <= 57) || (97 <= i && i <= 102); + boolean[] validHex = new boolean[Character.MAX_VALUE + 1]; + // Use the fact that the default initial boolean value is false + // and only explicitly init the values between the extreme HEX values + // This minimized impact during process startup esp. on mobile. + for (int i = 48; i < 103; i++) { + validHex[i] = i <= 57 || 97 <= i; } return validHex; } @@ -89,10 +92,15 @@ public static void longToBase16String(long value, char[] dest, int destOffset) { /** Returns the {@code byte[]} decoded from the given hex {@link CharSequence}. */ public static byte[] bytesFromBase16(CharSequence value, int length) { byte[] result = new byte[length / 2]; + bytesFromBase16(value, length, result); + return result; + } + + /** Fills {@code bytes} with bytes decoded from the given hex {@link CharSequence}. */ + public static void bytesFromBase16(CharSequence value, int length, byte[] bytes) { for (int i = 0; i < length; i += 2) { - result[i / 2] = byteFromBase16(value.charAt(i), value.charAt(i + 1)); + bytes[i / 2] = byteFromBase16(value.charAt(i), value.charAt(i + 1)); } - return result; } /** Fills {@code dest} with the hex encoding of {@code bytes}. */ diff --git a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/PercentEscaper.java b/api/all/src/main/java/io/opentelemetry/api/internal/PercentEscaper.java similarity index 97% rename from api/all/src/main/java/io/opentelemetry/api/baggage/propagation/PercentEscaper.java rename to api/all/src/main/java/io/opentelemetry/api/internal/PercentEscaper.java index d1c79bbc651..e8f3ca2dfdb 100644 --- a/api/all/src/main/java/io/opentelemetry/api/baggage/propagation/PercentEscaper.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/PercentEscaper.java @@ -18,9 +18,9 @@ * the License. */ -package io.opentelemetry.api.baggage.propagation; +package io.opentelemetry.api.internal; -import io.opentelemetry.api.internal.TemporaryBuffers; +import io.opentelemetry.api.impl.TemporaryBuffers; import javax.annotation.CheckForNull; /** @@ -59,10 +59,13 @@ *

Note: This escaper produces uppercase hexadecimal sequences. * + *

This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * * @author David Beaumont * @since 15.0 */ -final class PercentEscaper { +public final class PercentEscaper { /** The amount of padding (chars) to use when growing the escape buffer. */ private static final int DEST_PAD = 32; @@ -86,7 +89,7 @@ final class PercentEscaper { private static final boolean[] safeOctets = createSafeOctets(SAFE_CHARS); /** The default {@link PercentEscaper} which will *not* replace spaces with plus signs. */ - static PercentEscaper create() { + public static PercentEscaper create() { return new PercentEscaper(); } @@ -109,7 +112,7 @@ private static boolean[] createSafeOctets(String safeChars) { } /** Escape the provided String, using percent-style URL Encoding. */ - String escape(String s) { + public String escape(String s) { int slen = s.length(); for (int index = 0; index < slen; index++) { char c = s.charAt(index); diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/ReadOnlyArrayMap.java b/api/all/src/main/java/io/opentelemetry/api/internal/ReadOnlyArrayMap.java index 0d178e212b0..a1befa5a5e4 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/ReadOnlyArrayMap.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/ReadOnlyArrayMap.java @@ -72,7 +72,8 @@ public boolean containsKey(Object o) { @Override public boolean containsValue(Object o) { for (int i = 0; i < array.size(); i += 2) { - if (value(i + 1).equals(o)) { + V value = value(i + 1); + if (o == null ? value == null : o.equals(value)) { return true; } } diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/StringUtils.java b/api/all/src/main/java/io/opentelemetry/api/internal/StringUtils.java index d46a8b145cf..96616c92370 100644 --- a/api/all/src/main/java/io/opentelemetry/api/internal/StringUtils.java +++ b/api/all/src/main/java/io/opentelemetry/api/internal/StringUtils.java @@ -5,7 +5,6 @@ package io.opentelemetry.api.internal; -import java.util.Objects; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @@ -32,52 +31,6 @@ public static boolean isNullOrEmpty(@Nullable String string) { return string == null || string.isEmpty(); } - /** - * Pads a given string on the left with leading 0's up the length. - * - * @param value the string to pad - * @param minLength the minimum length the resulting padded string must have. Can be zero or - * negative, in which case the input string is always returned. - * @return the padded string - */ - public static String padLeft(String value, int minLength) { - return padStart(value, minLength, '0'); - } - - /** - * Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended - * with as many copies of {@code padChar} as are necessary to reach that length. For example, - * - *

    - *
  • {@code padStart("7", 3, '0')} returns {@code "007"} - *
  • {@code padStart("2010", 3, '0')} returns {@code "2010"} - *
- * - *

See {@link java.util.Formatter} for a richer set of formatting capabilities. - * - *

This method was copied almost verbatim from Guava library method - * com.google.common.base.Strings#padStart(java.lang.String, int, char). - * - * @param string the string which should appear at the end of the result - * @param minLength the minimum length the resulting string must have. Can be zero or negative, in - * which case the input string is always returned. - * @param padChar the character to insert at the beginning of the result until the minimum length - * is reached - * @return the padded string - */ - private static String padStart(String string, int minLength, char padChar) { - Objects.requireNonNull(string); - if (string.length() >= minLength) { - return string; - } - StringBuilder sb = new StringBuilder(minLength); - for (int i = string.length(); i < minLength; i++) { - sb.append(padChar); - } - sb.append(string); - return sb.toString(); - } - /** * Determines whether the {@code String} contains only printable characters. * diff --git a/api/all/src/main/java/io/opentelemetry/api/internal/ValidationUtil.java b/api/all/src/main/java/io/opentelemetry/api/internal/ValidationUtil.java deleted file mode 100644 index c512695344f..00000000000 --- a/api/all/src/main/java/io/opentelemetry/api/internal/ValidationUtil.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.api.internal; - -import java.nio.charset.StandardCharsets; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -/** - * General internal validation utility methods. - * - *

This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class ValidationUtil { - - public static final String API_USAGE_LOGGER_NAME = "io.opentelemetry.ApiUsageLogging"; - - private static final Logger API_USAGE_LOGGER = Logger.getLogger(API_USAGE_LOGGER_NAME); - - /** - * Instrument names MUST conform to the following syntax. - * - *

    - *
  • They are not null or empty strings. - *
  • They are case-insensitive, ASCII strings. - *
  • The first character must be an alphabetic character. - *
  • Subsequent characters must belong to the alphanumeric characters, '_', '.', and '-'. - *
  • They can have a maximum length of 63 characters. - *
- */ - private static final Pattern VALID_INSTRUMENT_NAME_PATTERN = - Pattern.compile("([A-Za-z]){1}([A-Za-z0-9\\_\\-\\.]){0,62}"); - - /** - * Log the {@code message} to the {@link #API_USAGE_LOGGER_NAME API Usage Logger}. - * - *

Log at {@link Level#FINEST} and include a stack trace. - */ - public static void log(String message) { - log(message, Level.FINEST); - } - - /** - * Log the {@code message} to the {@link #API_USAGE_LOGGER_NAME API Usage Logger}. - * - *

Log includes a stack trace. - */ - public static void log(String message, Level level) { - API_USAGE_LOGGER.log(level, message, new AssertionError()); - } - - /** Check if the instrument name is valid. If invalid, log a warning. */ - public static boolean checkValidInstrumentName(String name) { - return checkValidInstrumentName(name, ""); - } - - /** - * Check if the instrument name is valid. If invalid, log a warning with the {@code logSuffix} - * appended. - */ - public static boolean checkValidInstrumentName(String name, String logSuffix) { - if (name != null && VALID_INSTRUMENT_NAME_PATTERN.matcher(name).matches()) { - return true; - } - log( - "Instrument name \"" - + name - + "\" is invalid, returning noop instrument. Instrument names must consist of 63 or less characters including alphanumeric, _, ., -, and start with a letter." - + logSuffix, - Level.WARNING); - return false; - } - - /** Check if the instrument unit is valid. If invalid, log a warning. */ - public static boolean checkValidInstrumentUnit(String unit) { - return checkValidInstrumentUnit(unit, ""); - } - - /** - * Check if the instrument unit is valid. If invalid, log a warning with the {@code logSuffix} - * appended. - */ - public static boolean checkValidInstrumentUnit(String unit, String logSuffix) { - if (unit != null - && !unit.equals("") - && unit.length() < 64 - && StandardCharsets.US_ASCII.newEncoder().canEncode(unit)) { - return true; - } - log( - "Unit \"" - + unit - + "\" is invalid. Instrument unit must be 63 or less ASCII characters." - + logSuffix, - Level.WARNING); - return false; - } - - private ValidationUtil() {} -} diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/DefaultLogger.java b/api/all/src/main/java/io/opentelemetry/api/logs/DefaultLogger.java new file mode 100644 index 00000000000..38c9e6efa98 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/DefaultLogger.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.context.Context; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + +class DefaultLogger implements Logger { + + private static final Logger INSTANCE = new DefaultLogger(); + private static final LogRecordBuilder NOOP_LOG_RECORD_BUILDER = new NoopLogRecordBuilder(); + + private DefaultLogger() {} + + static Logger getInstance() { + return INSTANCE; + } + + @Override + public boolean isEnabled(Severity severity, Context context) { + return false; + } + + @Override + public LogRecordBuilder logRecordBuilder() { + return NOOP_LOG_RECORD_BUILDER; + } + + private static final class NoopLogRecordBuilder implements LogRecordBuilder { + + private NoopLogRecordBuilder() {} + + @Override + public LogRecordBuilder setTimestamp(long timestamp, TimeUnit unit) { + return this; + } + + @Override + public LogRecordBuilder setTimestamp(Instant instant) { + return this; + } + + @Override + public LogRecordBuilder setObservedTimestamp(long timestamp, TimeUnit unit) { + return this; + } + + @Override + public LogRecordBuilder setObservedTimestamp(Instant instant) { + return this; + } + + @Override + public LogRecordBuilder setContext(Context context) { + return this; + } + + @Override + public LogRecordBuilder setSeverity(Severity severity) { + return this; + } + + @Override + public LogRecordBuilder setSeverityText(String severityText) { + return this; + } + + @Override + public LogRecordBuilder setBody(String body) { + return this; + } + + @Override + public LogRecordBuilder setBody(Value body) { + return this; + } + + @Override + public LogRecordBuilder setAttribute(AttributeKey key, @Nullable T value) { + return this; + } + + @Override + public void emit() {} + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/DefaultLoggerProvider.java b/api/all/src/main/java/io/opentelemetry/api/logs/DefaultLoggerProvider.java new file mode 100644 index 00000000000..7d200715158 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/DefaultLoggerProvider.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import io.opentelemetry.common.impl.ApiUsageLogger; + +class DefaultLoggerProvider implements LoggerProvider { + + private static final LoggerProvider INSTANCE = new DefaultLoggerProvider(); + private static final LoggerBuilder NOOP_BUILDER = new NoopLoggerBuilder(); + + private DefaultLoggerProvider() {} + + static LoggerProvider getInstance() { + return INSTANCE; + } + + @Override + public LoggerBuilder loggerBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam( + LoggerProvider.class, "loggerBuilder", "instrumentationScopeName"); + return NOOP_BUILDER; + } + return NOOP_BUILDER; + } + + private static class NoopLoggerBuilder implements LoggerBuilder { + + @Override + public LoggerBuilder setSchemaUrl(String schemaUrl) { + if (schemaUrl == null) { + ApiUsageLogger.logNullParam(LoggerBuilder.class, "setSchemaUrl", "schemaUrl"); + return this; + } + return this; + } + + @Override + public LoggerBuilder setInstrumentationVersion(String instrumentationVersion) { + if (instrumentationVersion == null) { + ApiUsageLogger.logNullParam( + LoggerBuilder.class, "setInstrumentationVersion", "instrumentationVersion"); + return this; + } + return this; + } + + @Override + public Logger build() { + return DefaultLogger.getInstance(); + } + } +} diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/LogRecordBuilder.java b/api/all/src/main/java/io/opentelemetry/api/logs/LogRecordBuilder.java new file mode 100644 index 00000000000..57f20650de4 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/LogRecordBuilder.java @@ -0,0 +1,288 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.doubleKey; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.common.impl.ApiUsageLogger; +import io.opentelemetry.context.Context; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + +/** + * Used to construct and emit log records from a {@link Logger}. + * + *

Obtain a {@link Logger#logRecordBuilder()}, add properties using the setters, and emit the log + * record by calling {@link #emit()}. + * + * @since 1.27.0 + */ +public interface LogRecordBuilder { + + /** + * Set the epoch {@code timestamp}, using the timestamp and unit. + * + *

Note: If not set, the emitted log will not have a timestamp. + */ + LogRecordBuilder setTimestamp(long timestamp, TimeUnit unit); + + /** + * Set the epoch {@code timestamp}, using the instant. + * + *

Note: If not set, the emitted log will not have a timestamp. + */ + LogRecordBuilder setTimestamp(Instant instant); + + /** + * Set the epoch {@code observedTimestamp}, using the timestamp and unit. + * + *

The {@code observedTimestamp} is the time at which the log record was observed. If unset, it + * will be set to the {@code timestamp}. {@code observedTimestamp} may be different from {@code + * timestamp} if logs are being processed asynchronously (e.g. from a file or on a different + * thread). + */ + LogRecordBuilder setObservedTimestamp(long timestamp, TimeUnit unit); + + /** + * Set the {@code observedTimestamp}, using the instant. + * + *

The {@code observedTimestamp} is the time at which the log record was observed. If unset, it + * will be set to the {@code timestamp}. {@code observedTimestamp} may be different from {@code + * timestamp} if logs are being processed asynchronously (e.g. from a file or on a different + * thread). + */ + LogRecordBuilder setObservedTimestamp(Instant instant); + + /** Set the context. */ + LogRecordBuilder setContext(Context context); + + /** Set the severity. */ + LogRecordBuilder setSeverity(Severity severity); + + /** Set the severity text. */ + LogRecordBuilder setSeverityText(String severityText); + + /** + * Set the body string. + * + *

Shorthand for calling {@link #setBody(Value)} with {@link Value#of(String)}. + */ + LogRecordBuilder setBody(String body); + + /** + * Set the body {@link Value}. + * + * @since 1.42.0 + */ + default LogRecordBuilder setBody(Value body) { + if (body == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setBody", "body"); + return this; + } + setBody(body.asString()); + return this; + } + + /** + * Sets attributes. If the {@link LogRecordBuilder} previously contained a mapping for any of the + * keys, the old values are replaced by the specified values. + */ + @SuppressWarnings("unchecked") + default LogRecordBuilder setAllAttributes(Attributes attributes) { + if (attributes == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAllAttributes", "attributes"); + return this; + } + if (attributes.isEmpty()) { + return this; + } + attributes.forEach( + (attributeKey, value) -> setAttribute((AttributeKey) attributeKey, value)); + return this; + } + + /** + * Sets an attribute on the {@code LogRecord}. If the {@code LogRecord} previously contained a + * mapping for the key, the old value is replaced by the specified value. + * + *

Note: Providing a null value is a no-op and will not remove previously set values. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + */ + LogRecordBuilder setAttribute(AttributeKey key, @Nullable T value); + + /** + * Sets a String attribute on the {@code LogRecord}. If the {@code LogRecord} previously contained + * a mapping for the key, the old value is replaced by the specified value. + * + *

Note: Providing a null value is a no-op and will not remove previously set values. + * + *

Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.48.0 + */ + default LogRecordBuilder setAttribute(String key, @Nullable String value) { + if (key == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "key"); + return this; + } + return setAttribute(stringKey(key), value); + } + + /** + * Sets a Long attribute on the {@code LogRecord}. If the {@code LogRecord} previously contained a + * mapping for the key, the old value is replaced by the specified value. + * + *

Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.48.0 + */ + default LogRecordBuilder setAttribute(String key, long value) { + if (key == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "key"); + return this; + } + return setAttribute(longKey(key), value); + } + + /** + * Sets a Double attribute on the {@code LogRecord}. If the {@code LogRecord} previously contained + * a mapping for the key, the old value is replaced by the specified value. + * + *

Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.48.0 + */ + default LogRecordBuilder setAttribute(String key, double value) { + if (key == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "key"); + return this; + } + return setAttribute(doubleKey(key), value); + } + + /** + * Sets a Boolean attribute on the {@code LogRecord}. If the {@code LogRecord} previously + * contained a mapping for the key, the old value is replaced by the specified value. + * + *

Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.48.0 + */ + default LogRecordBuilder setAttribute(String key, boolean value) { + if (key == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "key"); + return this; + } + return setAttribute(booleanKey(key), value); + } + + /** + * Sets an Integer attribute on the {@code LogRecord}. If the {@code LogRecord} previously + * contained a mapping for the key, the old value is replaced by the specified value. + * + *

Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.48.0 + */ + default LogRecordBuilder setAttribute(String key, int value) { + if (key == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "key"); + return this; + } + return setAttribute(key, (long) value); + } + + /** + * Sets a {@link Value} attribute on the {@code LogRecord}. If the {@code LogRecord} previously + * contained a mapping for the key, the old value is replaced by the specified value. + * + *

Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + *

Instrumentations should assume that backends do not index individual properties of complex + * attributes, that querying or aggregating on such properties is inefficient and complicated, and + * that reporting complex attributes carries higher performance overhead. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.63.0 + */ + default LogRecordBuilder setAttribute(String key, Value value) { + if (key == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "key"); + return this; + } + if (value == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setAttribute", "value"); + return this; + } + return setAttribute(AttributeKey.valueKey(key), value); + } + + /** + * Sets the event name, which identifies the class / type of the Event. + * + *

This name should uniquely identify the event structure (both attributes and body). A log + * record with a non-empty event name is an Event. + * + * @since 1.50.0 + */ + default LogRecordBuilder setEventName(String eventName) { + if (eventName == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setEventName", "eventName"); + return this; + } + return this; + } + + /** + * Set {@code exception.type}, {@code exception.message}, and {@code exception.stacktrace} + * attributes based on the {@code throwable}. + * + * @since 1.60.0 + */ + default LogRecordBuilder setException(Throwable throwable) { + if (throwable == null) { + ApiUsageLogger.logNullParam(LogRecordBuilder.class, "setException", "throwable"); + return this; + } + return this; + } + + /** Emit the log record. */ + void emit(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/Logger.java b/api/all/src/main/java/io/opentelemetry/api/logs/Logger.java new file mode 100644 index 00000000000..3d29deca94e --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/Logger.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import io.opentelemetry.common.impl.ApiUsageLogger; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link Logger} is the entry point into a log pipeline. + * + *

Obtain a {@link #logRecordBuilder()}, add properties using the setters, and emit it via {@link + * LogRecordBuilder#emit()}. + * + *

The OpenTelemetry logs bridge API exists to enable bridging logs from other log frameworks + * (e.g. SLF4J, Log4j, JUL, Logback, etc) into OpenTelemetry and is NOT a replacement log + * API. + * + * @since 1.27.0 + */ +@ThreadSafe +public interface Logger { + + /** + * Returns {@code true} if the logger is enabled for the given {@code context} and {@code + * severity}. + * + *

This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #logRecordBuilder()}. + * + * @since 1.61.0 + */ + default boolean isEnabled(Severity severity, Context context) { + if (severity == null) { + ApiUsageLogger.logNullParam(Logger.class, "isEnabled", "severity"); + return false; + } + if (context == null) { + ApiUsageLogger.logNullParam(Logger.class, "isEnabled", "context"); + return false; + } + return true; + } + + /** + * Overload of {@link #isEnabled(Severity, Context)} assuming {@link Context#current()}. + * + * @since 1.61.0 + */ + default boolean isEnabled(Severity severity) { + if (severity == null) { + ApiUsageLogger.logNullParam(Logger.class, "isEnabled", "severity"); + return false; + } + return isEnabled(severity, Context.current()); + } + + /** + * Return a {@link LogRecordBuilder} to emit a log record. + * + *

IMPORTANT: this should be used to write appenders to bridge logs from logging + * frameworks (e.g. SLF4J, Log4j, JUL, Logback, etc). It is NOT a replacement for an + * application logging framework, and should not be used by application developers. + * + *

Build the log record using the {@link LogRecordBuilder} setters, and emit via {@link + * LogRecordBuilder#emit()}. + */ + LogRecordBuilder logRecordBuilder(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/LoggerBuilder.java b/api/all/src/main/java/io/opentelemetry/api/logs/LoggerBuilder.java new file mode 100644 index 00000000000..859315998bf --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/LoggerBuilder.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +/** + * Builder class for creating {@link Logger} instances. + * + *

{@link Logger}s are identified by their scope name, version, and schema URL. These identifying + * fields, along with attributes, combine to form the instrumentation scope, which is attached to + * all log records produced by the {@link Logger}. + * + * @since 1.27.0 + */ +public interface LoggerBuilder { + + /** + * Set the scope schema URL of the resulting {@link Logger}. Schema URL is part of {@link Logger} + * identity. + * + * @param schemaUrl The schema URL. + * @return this + */ + LoggerBuilder setSchemaUrl(String schemaUrl); + + /** + * Sets the instrumentation scope version of the resulting {@link Logger}. Version is part of + * {@link Logger} identity. + * + * @param instrumentationScopeVersion The instrumentation scope version. + * @return this + */ + LoggerBuilder setInstrumentationVersion(String instrumentationScopeVersion); + + /** + * Gets or creates a {@link Logger} instance. + * + * @return a {@link Logger} instance configured with the provided options. + */ + Logger build(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/LoggerProvider.java b/api/all/src/main/java/io/opentelemetry/api/logs/LoggerProvider.java new file mode 100644 index 00000000000..bbfd6404223 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/LoggerProvider.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import io.opentelemetry.api.internal.IncubatingUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A registry for creating scoped {@link Logger}s. The name Provider is for consistency with + * other languages and it is NOT loaded using reflection. + * + *

The OpenTelemetry logs bridge API exists to enable bridging logs from other log frameworks + * (e.g. SLF4J, Log4j, JUL, Logback, etc) into OpenTelemetry and is NOT a replacement log + * API. + * + * @since 1.27.0 + * @see Logger + */ +@ThreadSafe +public interface LoggerProvider { + + /** + * Gets or creates a named Logger instance. + * + * @param instrumentationScopeName A name uniquely identifying the instrumentation scope, such as + * the instrumentation library, package, or fully qualified class name. Must not be null. + * @return a Logger instance. + */ + default Logger get(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(LoggerProvider.class, "get", "instrumentationScopeName"); + return DefaultLogger.getInstance(); + } + return loggerBuilder(instrumentationScopeName).build(); + } + + /** + * Creates a LoggerBuilder for a named Logger instance. + * + * @param instrumentationScopeName A name uniquely identifying the instrumentation scope, such as + * the instrumentation library, package, or fully qualified class name. Must not be null. + * @return a LoggerBuilder instance. + */ + LoggerBuilder loggerBuilder(String instrumentationScopeName); + + /** Returns a no-op {@link LoggerProvider} which provides Loggers which do not record or emit. */ + static LoggerProvider noop() { + return IncubatingUtil.incubatingApiIfAvailable( + DefaultLoggerProvider.getInstance(), + "io.opentelemetry.api.incubator.logs.ExtendedDefaultLoggerProvider"); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Severity.java b/api/all/src/main/java/io/opentelemetry/api/logs/Severity.java similarity index 87% rename from sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Severity.java rename to api/all/src/main/java/io/opentelemetry/api/logs/Severity.java index bea09c2166e..95ea5bc3c20 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Severity.java +++ b/api/all/src/main/java/io/opentelemetry/api/logs/Severity.java @@ -3,8 +3,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.logs.data; +package io.opentelemetry.api.logs; +/** + * Log record severity options. + * + * @since 1.27.0 + */ public enum Severity { UNDEFINED_SEVERITY_NUMBER(0), TRACE(1), diff --git a/api/all/src/main/java/io/opentelemetry/api/logs/package-info.java b/api/all/src/main/java/io/opentelemetry/api/logs/package-info.java new file mode 100644 index 00000000000..fdeebc0e9a0 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/logs/package-info.java @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * API for writing log appenders. + * + *

The OpenTelemetry logging API exists to enable the creation of log appenders, which bridge + * logs from other log frameworks (e.g. SLF4J, Log4j, JUL, Logback, etc) into OpenTelemetry via + * {@link io.opentelemetry.api.logs.Logger#logRecordBuilder()}. It is NOT a replacement log + * framework. + */ +@ParametersAreNonnullByDefault +package io.opentelemetry.api.logs; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/BatchCallback.java b/api/all/src/main/java/io/opentelemetry/api/metrics/BatchCallback.java index b803d56f223..396b66cb44e 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/BatchCallback.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/BatchCallback.java @@ -8,6 +8,8 @@ /** * A reference to a batch callback registered via {@link Meter#batchCallback(Runnable, * ObservableMeasurement, ObservableMeasurement...)}. + * + * @since 1.15.0 */ public interface BatchCallback extends AutoCloseable { diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeter.java index 77c58a4977d..5caa7d829c2 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeter.java @@ -6,32 +6,14 @@ package io.opentelemetry.api.metrics; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.ValidationUtil; import io.opentelemetry.context.Context; import java.util.function.Consumer; import javax.annotation.concurrent.ThreadSafe; /** - * No-op implementations of {@link Meter}. + * No-op implementation of {@link Meter}. * *

This implementation should induce as close to zero overhead as possible. - * - *

A few notes from the specification on allowed behaviors leading to this design [Instrument - * Spec]: - * - *

    - *
  • Multiple Instruments with the same name under the same Meter MUST return an error - *
  • Different Meters MUST be treated as separate namespaces - *
  • Implementations MUST NOT require users to repeatedly obtain a Meter again with the same - * name+version+schema_url to pick up configuration changes. This can be achieved either by - * allowing to work with an outdated configuration or by ensuring that new configuration - * applies also to previously returned Meters. - *
  • A MeterProvider could also return a no-op Meter here if application owners configure the - * SDK to suppress telemetry produced by this library - *
  • In case an invalid name (null or empty string) is specified, a working Meter implementation - * MUST be returned as a fallback rather than returning null or throwing an exception, - *
*/ @ThreadSafe class DefaultMeter implements Meter { @@ -56,25 +38,21 @@ static Meter getInstance() { @Override public LongCounterBuilder counterBuilder(String name) { - ValidationUtil.checkValidInstrumentName(name); return NOOP_LONG_COUNTER_BUILDER; } @Override public LongUpDownCounterBuilder upDownCounterBuilder(String name) { - ValidationUtil.checkValidInstrumentName(name); return NOOP_LONG_UP_DOWN_COUNTER_BUILDER; } @Override public DoubleHistogramBuilder histogramBuilder(String name) { - ValidationUtil.checkValidInstrumentName(name); return NOOP_DOUBLE_HISTOGRAM_BUILDER; } @Override public DoubleGaugeBuilder gaugeBuilder(String name) { - ValidationUtil.checkValidInstrumentName(name); return NOOP_DOUBLE_GAUGE_BUILDER; } @@ -89,6 +67,11 @@ public BatchCallback batchCallback( private DefaultMeter() {} private static class NoopLongCounter implements LongCounter { + @Override + public boolean isEnabled() { + return false; + } + @Override public void add(long value, Attributes attributes, Context context) {} @@ -100,6 +83,11 @@ public void add(long value) {} } private static class NoopDoubleCounter implements DoubleCounter { + @Override + public boolean isEnabled() { + return false; + } + @Override public void add(double value, Attributes attributes, Context context) {} @@ -124,7 +112,6 @@ public LongCounterBuilder setDescription(String description) { @Override public LongCounterBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -161,7 +148,6 @@ public DoubleCounterBuilder setDescription(String description) { @Override public DoubleCounterBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -183,6 +169,11 @@ public ObservableDoubleMeasurement buildObserver() { } private static class NoopLongUpDownCounter implements LongUpDownCounter { + @Override + public boolean isEnabled() { + return false; + } + @Override public void add(long value, Attributes attributes, Context context) {} @@ -194,6 +185,11 @@ public void add(long value) {} } private static class NoopDoubleUpDownCounter implements DoubleUpDownCounter { + @Override + public boolean isEnabled() { + return false; + } + @Override public void add(double value, Attributes attributes, Context context) {} @@ -218,7 +214,6 @@ public LongUpDownCounterBuilder setDescription(String description) { @Override public LongUpDownCounterBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -257,7 +252,6 @@ public DoubleUpDownCounterBuilder setDescription(String description) { @Override public DoubleUpDownCounterBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -279,6 +273,11 @@ public ObservableDoubleMeasurement buildObserver() { } private static class NoopDoubleHistogram implements DoubleHistogram { + @Override + public boolean isEnabled() { + return false; + } + @Override public void record(double value, Attributes attributes, Context context) {} @@ -290,6 +289,11 @@ public void record(double value) {} } private static class NoopLongHistogram implements LongHistogram { + @Override + public boolean isEnabled() { + return false; + } + @Override public void record(long value, Attributes attributes, Context context) {} @@ -312,7 +316,6 @@ public DoubleHistogramBuilder setDescription(String description) { @Override public DoubleHistogramBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -337,7 +340,6 @@ public LongHistogramBuilder setDescription(String description) { @Override public LongHistogramBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -348,8 +350,10 @@ public LongHistogram build() { } private static class NoopDoubleGaugeBuilder implements DoubleGaugeBuilder { - private static final ObservableDoubleGauge NOOP = new ObservableDoubleGauge() {}; + private static final ObservableDoubleGauge NOOP_OBSERVABLE_GAUGE = + new ObservableDoubleGauge() {}; private static final LongGaugeBuilder NOOP_LONG_GAUGE_BUILDER = new NoopLongGaugeBuilder(); + private static final NoopDoubleGauge NOOP_GAUGE = new NoopDoubleGauge(); @Override public DoubleGaugeBuilder setDescription(String description) { @@ -358,7 +362,6 @@ public DoubleGaugeBuilder setDescription(String description) { @Override public DoubleGaugeBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @@ -369,17 +372,39 @@ public LongGaugeBuilder ofLongs() { @Override public ObservableDoubleGauge buildWithCallback(Consumer callback) { - return NOOP; + return NOOP_OBSERVABLE_GAUGE; } @Override public ObservableDoubleMeasurement buildObserver() { return NOOP_OBSERVABLE_DOUBLE_MEASUREMENT; } + + @Override + public DoubleGauge build() { + return NOOP_GAUGE; + } + } + + private static class NoopDoubleGauge implements DoubleGauge { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void set(double value) {} + + @Override + public void set(double value, Attributes attributes) {} + + @Override + public void set(double value, Attributes attributes, Context context) {} } private static class NoopLongGaugeBuilder implements LongGaugeBuilder { - private static final ObservableLongGauge NOOP = new ObservableLongGauge() {}; + private static final ObservableLongGauge NOOP_OBSERVABLE_GAUGE = new ObservableLongGauge() {}; + private static final NoopLongGauge NOOP_GAUGE = new NoopLongGauge(); @Override public LongGaugeBuilder setDescription(String description) { @@ -388,19 +413,39 @@ public LongGaugeBuilder setDescription(String description) { @Override public LongGaugeBuilder setUnit(String unit) { - ValidationUtil.checkValidInstrumentUnit(unit); return this; } @Override public ObservableLongGauge buildWithCallback(Consumer callback) { - return NOOP; + return NOOP_OBSERVABLE_GAUGE; } @Override public ObservableLongMeasurement buildObserver() { return NOOP_OBSERVABLE_LONG_MEASUREMENT; } + + @Override + public LongGauge build() { + return NOOP_GAUGE; + } + } + + private static class NoopLongGauge implements LongGauge { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void set(long value) {} + + @Override + public void set(long value, Attributes attributes) {} + + @Override + public void set(long value, Attributes attributes, Context context) {} } private static class NoopObservableDoubleMeasurement implements ObservableDoubleMeasurement { diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeterProvider.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeterProvider.java index 6d1a6de3d48..e009471bd5e 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeterProvider.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DefaultMeterProvider.java @@ -5,14 +5,24 @@ package io.opentelemetry.api.metrics; +import io.opentelemetry.api.internal.IncubatingUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; + /** A {@link MeterProvider} that does nothing. */ class DefaultMeterProvider implements MeterProvider { @Override public MeterBuilder meterBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(MeterProvider.class, "meterBuilder", "instrumentationScopeName"); + return BUILDER_INSTANCE; + } return BUILDER_INSTANCE; } - private static final DefaultMeterProvider INSTANCE = new DefaultMeterProvider(); + private static final MeterProvider INSTANCE = + IncubatingUtil.incubatingApiIfAvailable( + new DefaultMeterProvider(), + "io.opentelemetry.api.incubator.metrics.ExtendedDefaultMeterProvider"); private static final MeterBuilder BUILDER_INSTANCE = new NoopMeterBuilder(); static MeterProvider getInstance() { @@ -25,11 +35,20 @@ private static class NoopMeterBuilder implements MeterBuilder { @Override public MeterBuilder setSchemaUrl(String schemaUrl) { + if (schemaUrl == null) { + ApiUsageLogger.logNullParam(MeterBuilder.class, "setSchemaUrl", "schemaUrl"); + return this; + } return this; } @Override public MeterBuilder setInstrumentationVersion(String instrumentationScopeVersion) { + if (instrumentationScopeVersion == null) { + ApiUsageLogger.logNullParam( + MeterBuilder.class, "setInstrumentationVersion", "instrumentationScopeVersion"); + return this; + } return this; } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounter.java index a1068974ab1..467e21b67b2 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounter.java @@ -9,9 +9,28 @@ import io.opentelemetry.context.Context; import javax.annotation.concurrent.ThreadSafe; -/** A counter instrument that records {@code double} values. */ +/** + * A Counter instrument that records {@code double} values. + * + * @since 1.10.0 + */ @ThreadSafe public interface DoubleCounter { + + /** + * Returns {@code true} if the counter is enabled. + * + *

This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #add(double)}, {@link #add(double, Attributes)}, or {@link #add(double, + * Attributes, Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Records a value. * @@ -29,7 +48,7 @@ public interface DoubleCounter { * measurement. * * @param value The increment amount. MUST be non-negative. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. */ void add(double value, Attributes attributes); @@ -37,7 +56,7 @@ public interface DoubleCounter { * Records a value with a set of attributes. * * @param value The increment amount. MUST be non-negative. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. * @param context The explicit context to associate with this measurement. */ void add(double value, Attributes attributes, Context context); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounterBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounterBuilder.java index b75030084ce..3ba58c81536 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounterBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleCounterBuilder.java @@ -7,45 +7,52 @@ import java.util.function.Consumer; -/** Builder class for {@link DoubleCounter}. */ +/** + * Builder class for {@link DoubleCounter}. + * + * @since 1.10.0 + */ public interface DoubleCounterBuilder { /** * Sets the description for this instrument. * - *

Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ DoubleCounterBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ DoubleCounterBuilder setUnit(String unit); /** - * Builds and returns a {@code DoubleCounter} with the desired options. + * Builds and returns a Counter instrument with the configuration. * - * @return a {@code DoubleCounter} with the desired options. + * @return The Counter instrument. */ DoubleCounter build(); /** - * Builds this asynchronous instrument with the given callback. + * Builds an Asynchronous Counter instrument with the given callback. * - *

The callback will be called when the {@link Meter} is being observed. + *

The callback will be called when the instrument is being observed. * *

Callbacks are expected to abide by the following restrictions: * *

    *
  • Run in a finite amount of time. *
  • Safe to call repeatedly, across multiple threads. - *
  • Return positive, monotonically increasing values. *
* - * @param callback A state-capturing callback used to observe values on-demand. + * @param callback A callback which observes measurements when invoked. */ ObservableDoubleCounter buildWithCallback(Consumer callback); @@ -57,6 +64,7 @@ public interface DoubleCounterBuilder { * observed outside registered callbacks are ignored. * * @return an observable measurement that batch callbacks use to observe values. + * @since 1.15.0 */ default ObservableDoubleMeasurement buildObserver() { return DefaultMeter.getInstance().counterBuilder("noop").ofDoubles().buildObserver(); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGauge.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGauge.java new file mode 100644 index 00000000000..78a1124ddfa --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGauge.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A gauge instrument that synchronously records {@code double} values. + * + * @since 1.38.0 + */ +@ThreadSafe +public interface DoubleGauge { + + /** + * Returns {@code true} if the gauge is enabled. + * + *

This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #set(double)}, {@link #set(double, Attributes)}, or {@link #set(double, + * Attributes, Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + + /** + * Set the gauge value. + * + * @param value The current gauge value. + */ + void set(double value); + + /** + * Records a value with a set of attributes. + * + * @param value The current gauge value. + * @param attributes A set of attributes to associate with the value. + */ + void set(double value, Attributes attributes); + + /** + * Records a value with a set of attributes. + * + * @param value The current gauge value. + * @param attributes A set of attributes to associate with the value. + * @param context The explicit context to associate with this measurement. + */ + void set(double value, Attributes attributes, Context context); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGaugeBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGaugeBuilder.java index 2575fb9ceaf..b0ea8b939fa 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGaugeBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleGaugeBuilder.java @@ -7,31 +7,39 @@ import java.util.function.Consumer; -/** A builder for Gauge metric types. These can only be asynchronously collected. */ +/** + * A builder for Gauge metric types. These can only be asynchronously collected. + * + * @since 1.10.0 + */ public interface DoubleGaugeBuilder { /** * Sets the description for this instrument. * - *

Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ DoubleGaugeBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ DoubleGaugeBuilder setUnit(String unit); - /** Sets the gauge for recording {@code long} values. */ + /** Sets the Gauge for recording {@code long} values. */ LongGaugeBuilder ofLongs(); /** - * Builds this asynchronous instrument with the given callback. + * Builds an Asynchronous Gauge instrument with the given callback. * - *

The callback will be called when the {@link Meter} is being observed. + *

The callback will be called when the instrument is being observed. * *

Callbacks are expected to abide by the following restrictions: * @@ -40,7 +48,7 @@ public interface DoubleGaugeBuilder { *

  • Safe to call repeatedly, across multiple threads. * * - * @param callback A state-capturing callback used to observe values on-demand. + * @param callback A callback which observes measurements when invoked. */ ObservableDoubleGauge buildWithCallback(Consumer callback); @@ -52,8 +60,26 @@ public interface DoubleGaugeBuilder { * observed outside registered callbacks are ignored. * * @return an observable measurement that batch callbacks use to observe values. + * @since 1.15.0 */ default ObservableDoubleMeasurement buildObserver() { return DefaultMeter.getInstance().gaugeBuilder("noop").buildObserver(); } + + /** + * Builds and returns a DoubleGauge instrument with the configuration. + * + *

    NOTE: This produces a synchronous gauge which records gauge values as they occur. Most users + * will want to instead register an {@link #buildWithCallback(Consumer)} to asynchronously observe + * the value of the gauge when metrics are collected. + * + *

    If using the OpenTelemetry SDK, by default gauges use last value aggregation, such that only + * the value of the last recorded measurement is exported. + * + * @return The DoubleGauge instrument. + * @since 1.38.0 + */ + default DoubleGauge build() { + return DefaultMeter.getInstance().gaugeBuilder("noop").build(); + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogram.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogram.java index ccec350c28a..bdea93b66d9 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogram.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogram.java @@ -9,17 +9,35 @@ import io.opentelemetry.context.Context; import javax.annotation.concurrent.ThreadSafe; -/** A histogram instrument that records {@code long} values. */ +/** + * A Histogram instrument that records {@code double} values. + * + * @since 1.10.0 + */ @ThreadSafe public interface DoubleHistogram { + /** + * Returns {@code true} if the histogram is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #record(double)}, {@link #record(double, Attributes)}, or {@link #record(double, + * Attributes, Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Records a value. * *

    Note: This may use {@code Context.current()} to pull the context associated with this * measurement. * - * @param value The amount of the measurement. + * @param value The amount of the measurement. MUST be non-negative. */ void record(double value); @@ -29,16 +47,16 @@ public interface DoubleHistogram { *

    Note: This may use {@code Context.current()} to pull the context associated with this * measurement. * - * @param value The amount of the measurement. - * @param attributes A set of attributes to associate with the count. + * @param value The amount of the measurement. MUST be non-negative. + * @param attributes A set of attributes to associate with the value. */ void record(double value, Attributes attributes); /** * Records a value with a set of attributes. * - * @param value The amount of the measurement. - * @param attributes A set of attributes to associate with the count. + * @param value The amount of the measurement. MUST be non-negative. + * @param attributes A set of attributes to associate with the value. * @param context The explicit context to associate with this measurement. */ void record(double value, Attributes attributes, Context context); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogramBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogramBuilder.java index f31b7cbaa5e..8cd0772d86c 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogramBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleHistogramBuilder.java @@ -5,32 +5,62 @@ package io.opentelemetry.api.metrics; -/** Builder class for {@link DoubleHistogram}. */ +import io.opentelemetry.common.impl.ApiUsageLogger; +import java.util.List; + +/** + * Builder class for {@link DoubleHistogram}. + * + * @since 1.10.0 + */ public interface DoubleHistogramBuilder { /** * Sets the description for this instrument. * - *

    Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ DoubleHistogramBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

    Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ DoubleHistogramBuilder setUnit(String unit); - /** Sets the counter for recording {@code long} values. */ + /** + * Set the explicit bucket buckets boundaries advice, which suggests the recommended set of + * explicit bucket boundaries for this histogram. + * + * @param bucketBoundaries The explicit bucket boundaries advice. + * @see Explicit + * bucket boundaries advisory parameter + * @since 1.32.0 + */ + default DoubleHistogramBuilder setExplicitBucketBoundariesAdvice(List bucketBoundaries) { + if (bucketBoundaries == null) { + ApiUsageLogger.logNullParam( + List.class, "setExplicitBucketBoundariesAdvice", "bucketBoundaries"); + return this; + } + return this; + } + + /** Sets the Histogram for recording {@code long} values. */ LongHistogramBuilder ofLongs(); /** - * Builds and returns a {@code DoubleHistogram} with the desired options. + * Builds and returns a Histogram instrument with the configuration. * - * @return a {@code DoubleHistogram} with the desired options. + * @return The Histogram instrument. */ DoubleHistogram build(); } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounter.java index 270cc0b5f1f..d38a30f7395 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounter.java @@ -9,9 +9,28 @@ import io.opentelemetry.context.Context; import javax.annotation.concurrent.ThreadSafe; -/** An up-down-counter instrument that records {@code double} values. */ +/** + * An UpDownCounter instrument that records {@code double} values. + * + * @since 1.10.0 + */ @ThreadSafe public interface DoubleUpDownCounter { + + /** + * Returns {@code true} if the up down counter is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #add(double)}, {@link #add(double, Attributes)}, or {@link #add(double, + * Attributes, Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Records a value. * @@ -29,7 +48,7 @@ public interface DoubleUpDownCounter { * measurement. * * @param value The increment amount. May be positive, negative or zero. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. */ void add(double value, Attributes attributes); @@ -37,7 +56,7 @@ public interface DoubleUpDownCounter { * Records a value with a set of attributes. * * @param value The increment amount. May be positive, negative or zero. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. * @param context The explicit context to associate with this measurement. */ void add(double value, Attributes attributes, Context context); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounterBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounterBuilder.java index 227be14d309..360aeb19f43 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounterBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/DoubleUpDownCounterBuilder.java @@ -7,35 +7,43 @@ import java.util.function.Consumer; -/** Builder class for {@link DoubleUpDownCounter}. */ +/** + * Builder class for {@link DoubleUpDownCounter}. + * + * @since 1.10.0 + */ public interface DoubleUpDownCounterBuilder { /** * Sets the description for this instrument. * - *

    Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ DoubleUpDownCounterBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

    Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ DoubleUpDownCounterBuilder setUnit(String unit); /** - * Builds and returns a {@code DoubleUpDownCounter} with the desired options. + * Builds and returns an UpDownCounter instrument with the configuration. * - * @return a {@code DoubleUpDownCounter} with the desired options. + * @return The UpDownCounter instrument. */ DoubleUpDownCounter build(); /** - * Builds this asynchronous instrument with the given callback. + * Builds an Asynchronous UpDownCounter instrument with the given callback. * - *

    The callback will be called when the {@link Meter} is being observed. + *

    The callback will be called when the instrument is being observed. * *

    Callbacks are expected to abide by the following restrictions: * @@ -44,7 +52,7 @@ public interface DoubleUpDownCounterBuilder { *

  • Safe to call repeatedly, across multiple threads. * * - * @param callback A state-capturing callback used to observe values on-demand. + * @param callback A callback which observes measurements when invoked. */ ObservableDoubleUpDownCounter buildWithCallback(Consumer callback); @@ -56,6 +64,7 @@ public interface DoubleUpDownCounterBuilder { * observed outside registered callbacks are ignored. * * @return an observable measurement that batch callbacks use to observe values. + * @since 1.15.0 */ default ObservableDoubleMeasurement buildObserver() { return DefaultMeter.getInstance().upDownCounterBuilder("noop").ofDoubles().buildObserver(); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounter.java index e621a3731fc..93b6ffc2266 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounter.java @@ -10,14 +10,27 @@ import javax.annotation.concurrent.ThreadSafe; /** - * A counter instrument that records {@code long} values. + * A Counter instrument that records {@code long} values. * - *

    Counters only allow adding positive values, and guarantee the resulting metrics will be - * always-increasing monotonic sums. + * @since 1.10.0 */ @ThreadSafe public interface LongCounter { + /** + * Returns {@code true} if the counter is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #add(long)}, {@link #add(long, Attributes)}, or {@link #add(long, Attributes, + * Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Records a value. * @@ -35,7 +48,7 @@ public interface LongCounter { * measurement. * * @param value The increment amount. MUST be non-negative. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. */ void add(long value, Attributes attributes); @@ -43,7 +56,7 @@ public interface LongCounter { * Records a value with a set of attributes. * * @param value The increment amount. MUST be non-negative. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. * @param context The explicit context to associate with this measurement. */ void add(long value, Attributes attributes, Context context); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounterBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounterBuilder.java index 3b512fc0dc3..00ff9f84df1 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounterBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongCounterBuilder.java @@ -7,49 +7,56 @@ import java.util.function.Consumer; -/** Builder class for {@link LongCounter}. */ +/** + * Builder class for {@link LongCounter}. + * + * @since 1.10.0 + */ public interface LongCounterBuilder { /** * Sets the description for this instrument. * - *

    Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ LongCounterBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

    Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ LongCounterBuilder setUnit(String unit); - /** Sets the counter for recording {@code double} values. */ + /** Sets the Counter for recording {@code double} values. */ DoubleCounterBuilder ofDoubles(); /** - * Builds and returns a {@code LongCounter} with the desired options. + * Builds and returns a Counter instrument with the configuration. * - * @return a {@code LongCounter} with the desired options. + * @return The Counter instrument. */ LongCounter build(); /** - * Builds this asynchronous instrument with the given callback. + * Builds an Asynchronous Counter instrument with the given callback. * - *

    The callback will be called when the {@link Meter} is being observed. + *

    The callback will be called when the instrument is being observed. * *

    Callbacks are expected to abide by the following restrictions: * *

      *
    • Run in a finite amount of time. *
    • Safe to call repeatedly, across multiple threads. - *
    • Return positive, monotonically increasing values. *
    * - * @param callback A state-capturing callback used to observe values on-demand. + * @param callback A callback which observes measurements when invoked. */ ObservableLongCounter buildWithCallback(Consumer callback); @@ -61,6 +68,7 @@ public interface LongCounterBuilder { * observed outside registered callbacks are ignored. * * @return an observable measurement that batch callbacks use to observe values. + * @since 1.15.0 */ default ObservableLongMeasurement buildObserver() { return DefaultMeter.getInstance().counterBuilder("noop").buildObserver(); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongGauge.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongGauge.java new file mode 100644 index 00000000000..16b488f6df9 --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongGauge.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A gauge instrument that synchronously records {@code long} values. + * + * @since 1.38.0 + */ +@ThreadSafe +public interface LongGauge { + + /** + * Returns {@code true} if the gauge is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #set(long)}, {@link #set(long, Attributes)}, or {@link #set(long, Attributes, + * Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + + /** + * Set the gauge value. + * + * @param value The current gauge value. + */ + void set(long value); + + /** + * Records a value with a set of attributes. + * + * @param value The current gauge value. + * @param attributes A set of attributes to associate with the value. + */ + void set(long value, Attributes attributes); + + /** + * Records a value with a set of attributes. + * + * @param value The current gauge value. + * @param attributes A set of attributes to associate with the value. + * @param context The explicit context to associate with this measurement. + */ + void set(long value, Attributes attributes, Context context); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongGaugeBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongGaugeBuilder.java index 9daab1a156d..f33c53155e7 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongGaugeBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongGaugeBuilder.java @@ -7,28 +7,36 @@ import java.util.function.Consumer; -/** A builder for Gauge metric types. These can only be asynchronously collected. */ +/** + * A builder for Gauge metric types. These can only be asynchronously collected. + * + * @since 1.10.0 + */ public interface LongGaugeBuilder { /** * Sets the description for this instrument. * - *

    Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ LongGaugeBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

    Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ LongGaugeBuilder setUnit(String unit); /** - * Builds this asynchronous instrument with the given callback. + * Builds an Asynchronous Gauge instrument with the given callback. * - *

    The callback will be called when the {@link Meter} is being observed. + *

    The callback will be called when the instrument is being observed. * *

    Callbacks are expected to abide by the following restrictions: * @@ -37,7 +45,7 @@ public interface LongGaugeBuilder { *

  • Safe to call repeatedly, across multiple threads. * * - * @param callback A state-capturing callback used to observe values on-demand. + * @param callback A callback which observes measurements when invoked. */ ObservableLongGauge buildWithCallback(Consumer callback); @@ -49,8 +57,26 @@ public interface LongGaugeBuilder { * observed outside registered callbacks are ignored. * * @return an observable measurement that batch callbacks use to observe values. + * @since 1.15.0 */ default ObservableLongMeasurement buildObserver() { return DefaultMeter.getInstance().gaugeBuilder("noop").ofLongs().buildObserver(); } + + /** + * Builds and returns a LongGauge instrument with the configuration. + * + *

    NOTE: This produces a synchronous gauge which records gauge values as they occur. Most users + * will want to instead register an {@link #buildWithCallback(Consumer)} to asynchronously observe + * the value of the gauge when metrics are collected. + * + *

    If using the OpenTelemetry SDK, by default gauges use last value aggregation, such that only + * the value of the last recorded measurement is exported. + * + * @return The LongGauge instrument. + * @since 1.38.0 + */ + default LongGauge build() { + return DefaultMeter.getInstance().gaugeBuilder("noop").ofLongs().build(); + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogram.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogram.java index 639802fd939..82d886d37c1 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogram.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogram.java @@ -9,17 +9,35 @@ import io.opentelemetry.context.Context; import javax.annotation.concurrent.ThreadSafe; -/** A histogram instrument that records {@code long} values. */ +/** + * A Histogram instrument that records {@code long} values. + * + * @since 1.10.0 + */ @ThreadSafe public interface LongHistogram { + /** + * Returns {@code true} if the histogram is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #record(long)}, {@link #record(long, Attributes)}, or {@link #record(long, + * Attributes, Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Records a value. * *

    Note: This may use {@code Context.current()} to pull the context associated with this * measurement. * - * @param value The amount of the measurement. + * @param value The amount of the measurement. MUST be non-negative. */ void record(long value); @@ -29,16 +47,16 @@ public interface LongHistogram { *

    Note: This may use {@code Context.current()} to pull the context associated with this * measurement. * - * @param value The amount of the measurement. - * @param attributes A set of attributes to associate with the count. + * @param value The amount of the measurement. MUST be non-negative. + * @param attributes A set of attributes to associate with the value. */ void record(long value, Attributes attributes); /** * Records a value with a set of attributes. * - * @param value The amount of the measurement. - * @param attributes A set of attributes to associate with the count. + * @param value The amount of the measurement. MUST be non-negative. + * @param attributes A set of attributes to associate with the value. * @param context The explicit context to associate with this measurement. */ void record(long value, Attributes attributes, Context context); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogramBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogramBuilder.java index 3c389423e6d..22177bdc14d 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogramBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongHistogramBuilder.java @@ -5,28 +5,58 @@ package io.opentelemetry.api.metrics; -/** Builder class for {@link LongHistogram}. */ +import io.opentelemetry.common.impl.ApiUsageLogger; +import java.util.List; + +/** + * Builder class for {@link LongHistogram}. + * + * @since 1.10.0 + */ public interface LongHistogramBuilder { /** * Sets the description for this instrument. * - *

    Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ LongHistogramBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

    Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ LongHistogramBuilder setUnit(String unit); /** - * Builds and returns a {@code LongHistogram} with the desired options. + * Set the explicit bucket buckets boundaries advice, which suggests the recommended set of + * explicit bucket boundaries for this histogram. + * + * @param bucketBoundaries The explicit bucket boundaries advice. + * @see Explicit + * bucket boundaries advisory parameter + * @since 1.32.0 + */ + default LongHistogramBuilder setExplicitBucketBoundariesAdvice(List bucketBoundaries) { + if (bucketBoundaries == null) { + ApiUsageLogger.logNullParam( + List.class, "setExplicitBucketBoundariesAdvice", "bucketBoundaries"); + return this; + } + return this; + } + + /** + * Builds and returns a Histogram instrument with the configuration. * - * @return a {@code LongHistogram} with the desired options. + * @return The Histogram instrument. */ LongHistogram build(); } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounter.java index 140cae7c58d..f0cbc35f23f 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounter.java @@ -9,9 +9,28 @@ import io.opentelemetry.context.Context; import javax.annotation.concurrent.ThreadSafe; -/** An up-down-counter instrument that records {@code long} values. */ +/** + * An UpDownCounter instrument that records {@code long} values. + * + * @since 1.10.0 + */ @ThreadSafe public interface LongUpDownCounter { + + /** + * Returns {@code true} if the up down counter is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #add(long)}, {@link #add(long, Attributes)}, or {@link #add(long, Attributes, + * Context)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Records a value. * @@ -29,7 +48,7 @@ public interface LongUpDownCounter { * measurement. * * @param value The increment amount. May be positive, negative or zero. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. */ void add(long value, Attributes attributes); @@ -37,7 +56,7 @@ public interface LongUpDownCounter { * Records a value with a set of attributes. * * @param value The increment amount. May be positive, negative or zero. - * @param attributes A set of attributes to associate with the count. + * @param attributes A set of attributes to associate with the value. * @param context The explicit context to associate with this measurement. */ void add(long value, Attributes attributes, Context context); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounterBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounterBuilder.java index 95c4cc64732..33d514422bc 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounterBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/LongUpDownCounterBuilder.java @@ -7,38 +7,46 @@ import java.util.function.Consumer; -/** Builder class for {@link LongUpDownCounter}. */ +/** + * Builder class for {@link LongUpDownCounter}. + * + * @since 1.10.0 + */ public interface LongUpDownCounterBuilder { /** * Sets the description for this instrument. * - *

    Description strings should follow the instrument description rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-description + * @param description The description. + * @see Instrument + * Description */ LongUpDownCounterBuilder setDescription(String description); /** * Sets the unit of measure for this instrument. * - *

    Unit strings should follow the instrument unit rules: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#instrument-unit + * @param unit The unit. Instrument units must be 63 or fewer ASCII characters. + * @see Instrument + * Unit */ LongUpDownCounterBuilder setUnit(String unit); - /** Sets the counter for recording {@code double} values. */ + /** Sets the UpDownCounter for recording {@code double} values. */ DoubleUpDownCounterBuilder ofDoubles(); /** - * Builds and returns a {@code LongUpDownCounter} with the desired options. + * Builds and returns an UpDownCounter instrument with the configuration. * - * @return a {@code LongUpDownCounter} with the desired options. + * @return The UpDownCounter instrument. */ LongUpDownCounter build(); /** - * Builds this asynchronous instrument with the given callback. + * Builds an Asynchronous UpDownCounter instrument with the given callback. * - *

    The callback will be called when the {@link Meter} is being observed. + *

    The callback will be called when the instrument is being observed. * *

    Callbacks are expected to abide by the following restrictions: * @@ -47,7 +55,7 @@ public interface LongUpDownCounterBuilder { *

  • Safe to call repeatedly, across multiple threads. * * - * @param callback A state-capturing callback used to observe values on-demand. + * @param callback A callback which observes measurements when invoked. */ ObservableLongUpDownCounter buildWithCallback(Consumer callback); @@ -59,6 +67,7 @@ public interface LongUpDownCounterBuilder { * observed outside registered callbacks are ignored. * * @return an observable measurement that batch callbacks use to observe values. + * @since 1.15.0 */ default ObservableLongMeasurement buildObserver() { return DefaultMeter.getInstance().upDownCounterBuilder("noop").buildObserver(); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/Meter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/Meter.java index 1c12042a2a6..617c3dd9668 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/Meter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/Meter.java @@ -5,74 +5,115 @@ package io.opentelemetry.api.metrics; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.ThreadSafe; /** - * Provides instruments used to produce metrics. + * Provides instruments used to record measurements which are aggregated to metrics. * *

    Instruments are obtained through builders provided by this interface. Each builder has a - * default "type" associated with recordings that may be changed. - * - *

    A Meter is generally associated with an instrumentation scope, e.g. "I monitor apache - * httpclient". + * default measurement type (long or double) that may be changed. * *

    Choosing an instrument can be hard, but here's a rule of thumb for selecting the right * instrument: * *

      - *
    • I want to count something. + *
    • I want to count something (by recording a delta value): + *
        + *
      • If the value is monotonically increasing (the delta value is always non-negative) - + * use a Counter: + *
        meter.counterBuilder("my-counter").build()
        + *
      • If the value is NOT monotonically increasing (the delta value can be positive, + * negative, or zero)) - use an UpDownCounter: + *
        meter.upDownCounterBuilder("my-up-down-counter").build()
        + *
      + *
    • I want to record or time something, and the statistics about this + * thing are likely to be meaningful - use a Histogram: + *
      meter.histogramBuilder("my-histogram").build()
      + *
    • I want to measure something (by reporting an absolute value): *
        - *
      • The value is always increasing / I want to track its rate.
        - * Use {@link #counterBuilder(String)} - *
      • The value is not always increasing.
        - * Use {@link #upDownCounterBuilder(String)} + *
      • If it makes NO sense to add up the values across different sets of attributes, use an + * Asynchronous Gauge: + *
        + *             meter.gaugeBuilder("my-gauge").buildWithCallback(observableMeasurement -> observableMeasurement.record(..))
        + *             
        + *
      • If it makes sense to add up the values across different sets of attributes: + *
          + *
        • If the value is monotonically increasing - use an Asynchronous Counter: + *
          + *                   meter.counterBuilder("my-async-counter").buildWithCallback(observableMeasurement -> observableMeasurement.record(..))
          + *                   
          + *
        • If the value is NOT monotonically increasing - use an Asynchronous + * UpDownCounter: + *
          + *                   meter.upDownCounterBuilder("my-async-counter").buildWithCallback(observableMeasurement -> observableMeasurement.record(..))
          + *                   
          + *
        *
      - *
    • I want to time something, or record measurements where the statistics are important - * (e.g. latency).
      - * Use {@link #histogramBuilder(String)} - *
    • I want to measure something by sampling a value stored elsewhere.
      - * Use {@link #gaugeBuilder(String)} *
    + * + * @see Instrument + * Selection Guidelines + * @since 1.10.0 */ @ThreadSafe public interface Meter { /** - * Constructs a counter instrument. + * Constructs a Counter instrument. * - *

    This is used to build both synchronous (in-context) instruments and asynchronous (callback) - * instruments. + *

    This is used to build both synchronous instruments and asynchronous instruments (i.e. + * callbacks). * - * @param name the name used for the counter. - * @return a builder for configuring a new Counter instrument. Defaults to recording long values, - * but may be changed. + * @param name the name of the Counter. Instrument names must consist of 255 or fewer characters + * including alphanumeric, _, ., -, /, and start with a letter. + * @return a builder for configuring a Counter instrument. Defaults to recording long values, but + * may be changed. + * @see Instrument + * Naming Rule */ LongCounterBuilder counterBuilder(String name); /** - * Constructs an up-down-counter instrument. + * Constructs an UpDownCounter instrument. * - *

    This is used to build both synchronous (in-context) instruments and asynchronous (callback) - * instruments. + *

    This is used to build both synchronous instruments and asynchronous instruments (i.e. + * callbacks). * - * @param name the name used for the counter. - * @return a builder for configuring a new Counter synchronous instrument. Defaults to recording - * long values, but may be changed. + * @param name the name of the UpDownCounter. Instrument names must consist of 255 or fewer + * characters including alphanumeric, _, ., -, /, and start with a letter. + * @return a builder for configuring an UpDownCounter instrument. Defaults to recording long + * values, but may be changed. + * @see Instrument + * Naming Rule */ LongUpDownCounterBuilder upDownCounterBuilder(String name); /** * Constructs a Histogram instrument. * - * @param name the name used for the counter. - * @return a builder for configuring a new Histogram synchronous instrument. Defaults to recording + * @param name the name of the Histogram. Instrument names must consist of 255 or fewer characters + * including alphanumeric, _, ., -, /, and start with a letter. + * @return a builder for configuring a Histogram synchronous instrument. Defaults to recording * double values, but may be changed. + * @see Instrument + * Naming Rule */ DoubleHistogramBuilder histogramBuilder(String name); /** - * Constructs an asynchronous gauge. + * Constructs an Asynchronous Gauge instrument. * - * @return a builder used for configuring how to report gauge measurements on demand. + * @param name the name of the Gauge. Instrument names must consist of 255 or fewer characters + * including alphanumeric, _, ., -, /, and start with a letter. + * @return a builder used for configuring a Gauge instrument. Defaults to recording double values, + * but may be changed. + * @see Instrument + * Naming Rule */ DoubleGaugeBuilder gaugeBuilder(String name); @@ -82,7 +123,7 @@ public interface Meter { *

    Batch callbacks allow a single callback to observe measurements for multiple asynchronous * instruments. * - *

    The callback will be called when the {@link Meter} is being observed. + *

    The callback will be called when the instruments are being observed. * *

    Callbacks are expected to abide by the following restrictions: * @@ -96,11 +137,21 @@ public interface Meter { * @param callback a callback used to observe values on-demand. * @param observableMeasurement Instruments for which the callback may observe values. * @param additionalMeasurements Instruments for which the callback may observe values. + * @since 1.15.0 */ default BatchCallback batchCallback( Runnable callback, ObservableMeasurement observableMeasurement, ObservableMeasurement... additionalMeasurements) { + if (callback == null) { + ApiUsageLogger.logNullParam(Meter.class, "batchCallback", "callback"); + } + if (observableMeasurement == null) { + ApiUsageLogger.logNullParam(Meter.class, "batchCallback", "observableMeasurement"); + } + if (additionalMeasurements == null) { + ApiUsageLogger.logNullParam(Meter.class, "batchCallback", "additionalMeasurements"); + } return DefaultMeter.getInstance() .batchCallback(callback, observableMeasurement, additionalMeasurements); } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/MeterBuilder.java b/api/all/src/main/java/io/opentelemetry/api/metrics/MeterBuilder.java index 10914306a39..d095396e62a 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/MeterBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/MeterBuilder.java @@ -8,25 +8,28 @@ /** * Builder class for creating {@link Meter} instances. * - * @since 1.4.0 + *

    {@link Meter}s are identified by their scope name, version, and schema URL. These identifying + * fields, along with attributes, combine to form the instrumentation scope, which is attached to + * all metrics produced by the {@link Meter}. + * + * @since 1.10.0 */ public interface MeterBuilder { /** - * Assigns an OpenTelemetry schema URL to the resulting Meter. - * - *

    Schemas are used to identify expected metrics (semantic conventions) and allow backends to - * "automatically migrate" to supported versions. + * Set the scope schema URL of the resulting {@link Meter}. Schema URL is part of {@link Meter} + * identity. * - * @param schemaUrl The URL of the OpenTelemetry schema being used by this instrumentation scope. + * @param schemaUrl The schema URL. * @return this */ MeterBuilder setSchemaUrl(String schemaUrl); /** - * Assigns a version to the instrumentation scope that is using the resulting Meter. + * Sets the instrumentation scope version of the resulting {@link Meter}. Version is part of + * {@link Meter} identity. * - * @param instrumentationScopeVersion The version of the instrumentation scope. + * @param instrumentationScopeVersion The instrumentation scope version. * @return this */ MeterBuilder setInstrumentationVersion(String instrumentationScopeVersion); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/MeterProvider.java b/api/all/src/main/java/io/opentelemetry/api/metrics/MeterProvider.java index 6e88298a987..c9c0f79f599 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/MeterProvider.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/MeterProvider.java @@ -5,39 +5,40 @@ package io.opentelemetry.api.metrics; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.ThreadSafe; /** * A registry for creating named {@link Meter}s. * - *

    A MeterProvider represents a configured (or noop) Metric collection system that can be used to - * instrument code. - * *

    The name Provider is for consistency with other languages and it is NOT loaded * using reflection. * - * @see io.opentelemetry.api.metrics.Meter + * @see Meter + * @since 1.10.0 */ @ThreadSafe public interface MeterProvider { /** - * Gets or creates a named and versioned meter instance. + * Gets or creates a named Meter instance. * * @param instrumentationScopeName A name uniquely identifying the instrumentation scope, such as * the instrumentation library, package, or fully qualified class name. Must not be null. - * @return a meter instance. + * @return a Meter instance. */ default Meter get(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(MeterProvider.class, "get", "instrumentationScopeName"); + } return meterBuilder(instrumentationScopeName).build(); } /** - * Creates a MeterBuilder for a named meter instance. + * Creates a MeterBuilder for a named Meter instance. * * @param instrumentationScopeName A name uniquely identifying the instrumentation scope, such as * the instrumentation library, package, or fully qualified class name. Must not be null. * @return a MeterBuilder instance. - * @since 1.4.0 */ MeterBuilder meterBuilder(String instrumentationScopeName); diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleCounter.java index 24ff38d491d..9e228b8ae2e 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleCounter.java @@ -8,8 +8,10 @@ import java.util.function.Consumer; /** - * A reference to an observable metric registered with {@link + * A reference to an observable instrument registered with {@link * DoubleCounterBuilder#buildWithCallback(Consumer)}. + * + * @since 1.10.0 */ public interface ObservableDoubleCounter extends AutoCloseable { @@ -18,7 +20,9 @@ public interface ObservableDoubleCounter extends AutoCloseable { * After this is called, the callback won't be invoked on future collections. Subsequent calls to * {@link #close()} have no effect. * - *

    Note: other callbacks registered to the metric with the same identity are unaffected. + *

    Note: other callbacks registered to the instrument with the same identity are unaffected. + * + * @since 1.12.0 */ @Override default void close() {} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleGauge.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleGauge.java index ec5683a40e7..a69115b68e5 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleGauge.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleGauge.java @@ -8,8 +8,10 @@ import java.util.function.Consumer; /** - * A reference to an observable metric registered with {@link + * A reference to an observable instrument registered with {@link * DoubleGaugeBuilder#buildWithCallback(Consumer)}. + * + * @since 1.10.0 */ public interface ObservableDoubleGauge extends AutoCloseable { @@ -18,7 +20,9 @@ public interface ObservableDoubleGauge extends AutoCloseable { * After this is called, the callback won't be invoked on future collections. Subsequent calls to * {@link #close()} have no effect. * - *

    Note: other callbacks registered to the metric with the same identity are unaffected. + *

    Note: other callbacks registered to the instrument with the same identity are unaffected. + * + * @since 1.12.0 */ @Override default void close() {} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleMeasurement.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleMeasurement.java index 82f093cdf65..41d21db124e 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleMeasurement.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleMeasurement.java @@ -7,21 +7,25 @@ import io.opentelemetry.api.common.Attributes; -/** An interface for observing measurements with {@code double} values. */ +/** + * An interface for observing measurements with {@code double} values. + * + * @since 1.10.0 + */ public interface ObservableDoubleMeasurement extends ObservableMeasurement { /** * Records a measurement. * - * @param value The measurement amount. + * @param value The measurement value. */ void record(double value); /** * Records a measurement with a set of attributes. * - * @param value The measurement amount. - * @param attributes A set of attributes to associate with the count. + * @param value The measurement value. + * @param attributes A set of attributes to associate with the value. */ void record(double value, Attributes attributes); } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleUpDownCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleUpDownCounter.java index e193eb675c7..a2dfd3ccee7 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleUpDownCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableDoubleUpDownCounter.java @@ -8,8 +8,10 @@ import java.util.function.Consumer; /** - * A reference to an observable metric registered with {@link + * A reference to an observable instrument registered with {@link * DoubleUpDownCounterBuilder#buildWithCallback(Consumer)}. + * + * @since 1.10.0 */ public interface ObservableDoubleUpDownCounter extends AutoCloseable { @@ -18,7 +20,9 @@ public interface ObservableDoubleUpDownCounter extends AutoCloseable { * DoubleUpDownCounterBuilder#buildWithCallback(Consumer)}. After this is called, the callback * won't be invoked on future collections. Subsequent calls to {@link #close()} have no effect. * - *

    Note: other callbacks registered to the metric with the same identity are unaffected. + *

    Note: other callbacks registered to the instrument with the same identity are unaffected. + * + * @since 1.12.0 */ @Override default void close() {} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongCounter.java index c0553c226b7..c8611b1cc58 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongCounter.java @@ -8,8 +8,10 @@ import java.util.function.Consumer; /** - * A reference to an observable metric registered with {@link + * A reference to an observable instrument registered with {@link * LongCounterBuilder#buildWithCallback(Consumer)}. + * + * @since 1.10.0 */ public interface ObservableLongCounter extends AutoCloseable { @@ -18,7 +20,9 @@ public interface ObservableLongCounter extends AutoCloseable { * After this is called, the callback won't be invoked on future collections. Subsequent calls to * {@link #close()} have no effect. * - *

    Note: other callbacks registered to the metric with the same identity are unaffected. + *

    Note: other callbacks registered to the instrument with the same identity are unaffected. + * + * @since 1.12.0 */ @Override default void close() {} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongGauge.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongGauge.java index 19ca351c850..fabbd5c4da2 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongGauge.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongGauge.java @@ -8,8 +8,10 @@ import java.util.function.Consumer; /** - * A reference to an observable metric registered with {@link + * A reference to an observable instrument registered with {@link * LongGaugeBuilder#buildWithCallback(Consumer)}. + * + * @since 1.10.0 */ public interface ObservableLongGauge extends AutoCloseable { @@ -18,7 +20,9 @@ public interface ObservableLongGauge extends AutoCloseable { * this is called, the callback won't be invoked on future collections. Subsequent calls to {@link * #close()} have no effect. * - *

    Note: other callbacks registered to the metric with the same identity are unaffected. + *

    Note: other callbacks registered to the instrument with the same identity are unaffected. + * + * @since 1.12.0 */ @Override default void close() {} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongMeasurement.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongMeasurement.java index 0c909f8735f..98e070222ab 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongMeasurement.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongMeasurement.java @@ -7,21 +7,25 @@ import io.opentelemetry.api.common.Attributes; -/** An interface for observing measurements with {@code long} values. */ +/** + * An interface for observing measurements with {@code long} values. + * + * @since 1.10.0 + */ public interface ObservableLongMeasurement extends ObservableMeasurement { /** * Records a measurement. * - * @param value The measurement amount. + * @param value The measurement value. */ void record(long value); /** * Records a measurement with a set of attributes. * - * @param value The measurement amount. - * @param attributes A set of attributes to associate with the count. + * @param value The measurement value. + * @param attributes A set of attributes to associate with the value. */ void record(long value, Attributes attributes); } diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongUpDownCounter.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongUpDownCounter.java index 65d8b167816..9de21bb3e9a 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongUpDownCounter.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableLongUpDownCounter.java @@ -10,6 +10,8 @@ /** * A reference to an observable metric registered with {@link * LongUpDownCounterBuilder#buildWithCallback(Consumer)}. + * + * @since 1.10.0 */ public interface ObservableLongUpDownCounter extends AutoCloseable { @@ -19,6 +21,8 @@ public interface ObservableLongUpDownCounter extends AutoCloseable { * be invoked on future collections. Subsequent calls to {@link #close()} have no effect. * *

    Note: other callbacks registered to the metric with the same identity are unaffected. + * + * @since 1.12.0 */ @Override default void close() {} diff --git a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableMeasurement.java b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableMeasurement.java index efbe9ef3941..eee27e91e72 100644 --- a/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableMeasurement.java +++ b/api/all/src/main/java/io/opentelemetry/api/metrics/ObservableMeasurement.java @@ -10,5 +10,6 @@ * * @see ObservableLongMeasurement * @see ObservableDoubleMeasurement + * @since 1.15.0 */ public interface ObservableMeasurement {} diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceState.java b/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceState.java index 6da56f542f2..2a74f1c157c 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceState.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceState.java @@ -7,6 +7,7 @@ import com.google.auto.value.AutoValue; import io.opentelemetry.api.internal.ReadOnlyArrayMap; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.List; import java.util.Map; import java.util.function.BiConsumer; @@ -21,6 +22,7 @@ abstract class ArrayBasedTraceState implements TraceState { @Nullable public String get(String key) { if (key == null) { + ApiUsageLogger.logNullParam(TraceState.class, "get", "key"); return null; } List entries = getEntries(); @@ -45,6 +47,7 @@ public boolean isEmpty() { @Override public void forEach(BiConsumer consumer) { if (consumer == null) { + ApiUsageLogger.logNullParam(TraceState.class, "forEach", "consumer"); return; } List entries = getEntries(); diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceStateBuilder.java b/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceStateBuilder.java index 4b8836fe10c..9558fd765bf 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceStateBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/ArrayBasedTraceStateBuilder.java @@ -6,6 +6,7 @@ package io.opentelemetry.api.trace; import io.opentelemetry.api.internal.StringUtils; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -14,7 +15,7 @@ final class ArrayBasedTraceStateBuilder implements TraceStateBuilder { - private static final int MAX_VENDOR_ID_SIZE = 13; + private static final int MAX_VENDOR_ID_SIZE = 14; // Needs to be in this class to avoid initialization deadlock because super class depends on // subclass (the auto-value generate class). @@ -24,7 +25,7 @@ final class ArrayBasedTraceStateBuilder implements TraceStateBuilder { private static final int MAX_ENTRIES = 32; private static final int KEY_MAX_SIZE = 256; private static final int VALUE_MAX_SIZE = 256; - private static final int MAX_TENANT_ID_SIZE = 240; + private static final int MAX_TENANT_ID_SIZE = 241; // Later calls to put must be at the front of trace state. We append to the list and then reverse // when finished. @@ -66,6 +67,12 @@ static TraceState empty() { */ @Override public TraceStateBuilder put(String key, String value) { + if (key == null) { + ApiUsageLogger.logNullParam(TraceStateBuilder.class, "put", "key"); + } + if (value == null) { + ApiUsageLogger.logNullParam(TraceStateBuilder.class, "put", "value"); + } if (!isKeyValid(key) || !isValueValid(value) || numEntries >= MAX_ENTRIES) { return this; } @@ -88,12 +95,15 @@ public TraceStateBuilder put(String key, String value) { @Override public TraceStateBuilder remove(String key) { if (key == null) { + ApiUsageLogger.logNullParam(TraceStateBuilder.class, "remove", "key"); return this; } for (int i = 0; i < reversedEntries.size(); i += 2) { if (reversedEntries.get(i).equals(key)) { - reversedEntries.set(i + 1, null); - numEntries--; + if (reversedEntries.get(i + 1) != null) { + reversedEntries.set(i + 1, null); + numEntries--; + } return this; } } @@ -157,11 +167,11 @@ private static boolean isKeyValid(@Nullable String key) { return false; } isMultiTenantVendorKey = true; - // tenant id (the part to the left of the '@' sign) must be 240 characters or less + // tenant id (the part to the left of the '@' sign) must be 241 characters or less if (i > MAX_TENANT_ID_SIZE) { return false; } - // vendor id (the part to the right of the '@' sign) must be 1-13 characters long + // vendor id (the part to the right of the '@' sign) must be 1-14 characters long int remainingKeyChars = key.length() - i - 1; if (remainingKeyChars > MAX_VENDOR_ID_SIZE || remainingKeyChars == 0) { return false; diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracer.java b/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracer.java index 3e2cac2ac00..6ad983f24df 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracer.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracer.java @@ -7,13 +7,13 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.ValidationUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.Context; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; -/** No-op implementations of {@link Tracer}. */ +/** No-op implementation of {@link Tracer}. */ @ThreadSafe final class DefaultTracer implements Tracer { @@ -23,8 +23,16 @@ static Tracer getInstance() { return INSTANCE; } + @Override + public boolean isEnabled() { + return false; + } + @Override public SpanBuilder spanBuilder(String spanName) { + if (spanName == null) { + ApiUsageLogger.logNullParam(Tracer.class, "spanBuilder", "spanName"); + } return NoopSpanBuilder.create(); } @@ -50,7 +58,7 @@ public Span startSpan() { @Override public NoopSpanBuilder setParent(Context context) { if (context == null) { - ValidationUtil.log("context is null"); + ApiUsageLogger.logNullParam(SpanBuilder.class, "setParent", "context"); return this; } spanContext = Span.fromContext(context).getSpanContext(); @@ -74,7 +82,7 @@ public NoopSpanBuilder addLink(SpanContext spanContext, Attributes attributes) { } @Override - public NoopSpanBuilder setAttribute(String key, String value) { + public NoopSpanBuilder setAttribute(String key, @Nullable String value) { return this; } @@ -94,7 +102,7 @@ public NoopSpanBuilder setAttribute(String key, boolean value) { } @Override - public NoopSpanBuilder setAttribute(AttributeKey key, T value) { + public NoopSpanBuilder setAttribute(AttributeKey key, @Nullable T value) { return this; } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerBuilder.java b/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerBuilder.java index 543d9a8cf95..d270c46595c 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerBuilder.java @@ -5,6 +5,8 @@ package io.opentelemetry.api.trace; +import io.opentelemetry.common.impl.ApiUsageLogger; + class DefaultTracerBuilder implements TracerBuilder { private static final DefaultTracerBuilder INSTANCE = new DefaultTracerBuilder(); @@ -14,11 +16,18 @@ static TracerBuilder getInstance() { @Override public TracerBuilder setSchemaUrl(String schemaUrl) { + if (schemaUrl == null) { + ApiUsageLogger.logNullParam(TracerBuilder.class, "setSchemaUrl", "schemaUrl"); + } return this; } @Override public TracerBuilder setInstrumentationVersion(String instrumentationScopeVersion) { + if (instrumentationScopeVersion == null) { + ApiUsageLogger.logNullParam( + TracerBuilder.class, "setInstrumentationVersion", "instrumentationScopeVersion"); + } return this; } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerProvider.java b/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerProvider.java index 97ddbe0c7b8..7f953c4b1bb 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerProvider.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/DefaultTracerProvider.java @@ -5,12 +5,17 @@ package io.opentelemetry.api.trace; +import io.opentelemetry.api.internal.IncubatingUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.ThreadSafe; @ThreadSafe class DefaultTracerProvider implements TracerProvider { - private static final TracerProvider INSTANCE = new DefaultTracerProvider(); + private static final TracerProvider INSTANCE = + IncubatingUtil.incubatingApiIfAvailable( + new DefaultTracerProvider(), + "io.opentelemetry.api.incubator.trace.ExtendedDefaultTracerProvider"); static TracerProvider getInstance() { return INSTANCE; @@ -18,11 +23,20 @@ static TracerProvider getInstance() { @Override public Tracer get(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(TracerProvider.class, "get", "instrumentationScopeName"); + } return DefaultTracer.getInstance(); } @Override public Tracer get(String instrumentationScopeName, String instrumentationScopeVersion) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam(TracerProvider.class, "get", "instrumentationScopeName"); + } + if (instrumentationScopeVersion == null) { + ApiUsageLogger.logNullParam(TracerProvider.class, "get", "instrumentationScopeVersion"); + } return DefaultTracer.getInstance(); } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/ImmutableTraceFlags.java b/api/all/src/main/java/io/opentelemetry/api/trace/ImmutableTraceFlags.java index 7cd15f6077a..ca007995abe 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/ImmutableTraceFlags.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/ImmutableTraceFlags.java @@ -10,10 +10,13 @@ import javax.annotation.concurrent.Immutable; @Immutable -final class ImmutableTraceFlags implements TraceFlags { +final class ImmutableTraceFlags implements TraceFlags, TraceFlagsBuilder { private static final ImmutableTraceFlags[] INSTANCES = buildInstances(); // Bit to represent whether trace is sampled or not. private static final byte SAMPLED_BIT = 0x01; + // Bit to indicate that the lower 56 bits of the trace id have been randomly generated with + // uniform distribution + private static final byte RANDOM_TRACE_ID_BIT = 0x02; static final ImmutableTraceFlags DEFAULT = fromByte((byte) 0x00); static final ImmutableTraceFlags SAMPLED = fromByte(SAMPLED_BIT); @@ -55,6 +58,11 @@ public boolean isSampled() { return (this.byteRep & SAMPLED_BIT) != 0; } + @Override + public boolean isTraceIdRandom() { + return (this.byteRep & RANDOM_TRACE_ID_BIT) != 0; + } + @Override public String asHex() { return this.hexRep; @@ -65,6 +73,26 @@ public byte asByte() { return this.byteRep; } + @Override + public ImmutableTraceFlags setSampled(boolean isSampled) { + byte newByte = isSampled ? (byte) (asByte() | SAMPLED_BIT) : (byte) (asByte() & ~SAMPLED_BIT); + return fromByte(newByte); + } + + @Override + public ImmutableTraceFlags setRandomTraceId(boolean isRandomTraceId) { + byte newByte = + isRandomTraceId + ? (byte) (asByte() | RANDOM_TRACE_ID_BIT) + : (byte) (asByte() & ~RANDOM_TRACE_ID_BIT); + return fromByte(newByte); + } + + @Override + public TraceFlags build() { + return this; + } + @Override public String toString() { return asHex(); diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/PropagatedSpan.java b/api/all/src/main/java/io/opentelemetry/api/trace/PropagatedSpan.java index 24c145b05b5..d1e37b9543f 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/PropagatedSpan.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/PropagatedSpan.java @@ -7,7 +7,9 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** @@ -42,77 +44,140 @@ private PropagatedSpan(SpanContext spanContext) { } @Override - public Span setAttribute(String key, String value) { + public Span setAttribute(String key, @Nullable String value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + } return this; } @Override public Span setAttribute(String key, long value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + } return this; } @Override public Span setAttribute(String key, double value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + } return this; } @Override public Span setAttribute(String key, boolean value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + } return this; } @Override - public Span setAttribute(AttributeKey key, T value) { + public Span setAttribute(AttributeKey key, @Nullable T value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + } return this; } @Override public Span setAllAttributes(Attributes attributes) { + if (attributes == null) { + ApiUsageLogger.logNullParam(Span.class, "setAllAttributes", "attributes"); + } return this; } @Override public Span addEvent(String name) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + } return this; } @Override public Span addEvent(String name, long timestamp, TimeUnit unit) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + } + if (unit == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "unit"); + } return this; } @Override public Span addEvent(String name, Attributes attributes) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + } + if (attributes == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "attributes"); + } return this; } @Override public Span addEvent(String name, Attributes attributes, long timestamp, TimeUnit unit) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + } + if (attributes == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "attributes"); + } + if (unit == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "unit"); + } return this; } @Override public Span setStatus(StatusCode statusCode) { + if (statusCode == null) { + ApiUsageLogger.logNullParam(Span.class, "setStatus", "statusCode"); + } return this; } @Override public Span setStatus(StatusCode statusCode, String description) { + if (statusCode == null) { + ApiUsageLogger.logNullParam(Span.class, "setStatus", "statusCode"); + } + if (description == null) { + ApiUsageLogger.logNullParam(Span.class, "setStatus", "description"); + } return this; } @Override public Span recordException(Throwable exception) { + if (exception == null) { + ApiUsageLogger.logNullParam(Span.class, "recordException", "exception"); + } return this; } @Override public Span recordException(Throwable exception, Attributes additionalAttributes) { + if (exception == null) { + ApiUsageLogger.logNullParam(Span.class, "recordException", "exception"); + } + if (additionalAttributes == null) { + ApiUsageLogger.logNullParam(Span.class, "recordException", "additionalAttributes"); + } return this; } @Override public Span updateName(String name) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "updateName", "name"); + } return this; } @@ -120,7 +185,11 @@ public Span updateName(String name) { public void end() {} @Override - public void end(long timestamp, TimeUnit unit) {} + public void end(long timestamp, TimeUnit unit) { + if (unit == null) { + ApiUsageLogger.logNullParam(Span.class, "end", "unit"); + } + } @Override public SpanContext getSpanContext() { diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/Span.java b/api/all/src/main/java/io/opentelemetry/api/trace/Span.java index 878ab6693f0..b9f6b137819 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/Span.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/Span.java @@ -10,7 +10,8 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.ValidationUtil; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.Context; import io.opentelemetry.context.ImplicitContextKeyed; import java.time.Instant; @@ -43,7 +44,7 @@ static Span current() { */ static Span fromContext(Context context) { if (context == null) { - ValidationUtil.log("context is null"); + ApiUsageLogger.logNullParam(Span.class, "fromContext", "context"); return Span.getInvalid(); } Span span = context.get(SpanContextKey.KEY); @@ -57,7 +58,7 @@ static Span fromContext(Context context) { @Nullable static Span fromContextOrNull(Context context) { if (context == null) { - ValidationUtil.log("context is null"); + ApiUsageLogger.logNullParam(Span.class, "fromContextOrNull", "context"); return null; } return context.get(SpanContextKey.KEY); @@ -74,14 +75,11 @@ static Span getInvalid() { /** * Returns a non-recording {@link Span} that holds the provided {@link SpanContext} but has no * functionality. It will not be exported and all tracing operations are no-op, but it can be used - * to propagate a valid {@link SpanContext} downstream. + * to propagate a {@link SpanContext} downstream. */ static Span wrap(SpanContext spanContext) { if (spanContext == null) { - ValidationUtil.log("context is null"); - return getInvalid(); - } - if (!spanContext.isValid()) { + ApiUsageLogger.logNullParam(Span.class, "wrap", "spanContext"); return getInvalid(); } return PropagatedSpan.create(spanContext); @@ -91,8 +89,9 @@ static Span wrap(SpanContext spanContext) { * Sets an attribute to the {@code Span}. If the {@code Span} previously contained a mapping for * the key, the old value is replaced by the specified value. * - *

    If a null or empty String {@code value} is passed in, the behavior is undefined, and hence - * strongly discouraged. + *

    Empty String "" and null are valid attribute {@code value}s, but not valid keys. + * + *

    Note: Providing a null value is a no-op and will not remove previously set values. * *

    Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and * pre-allocate your keys, if possible. @@ -101,7 +100,11 @@ static Span wrap(SpanContext spanContext) { * @param value the value for this attribute. * @return this. */ - default Span setAttribute(String key, String value) { + default Span setAttribute(String key, @Nullable String value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + return this; + } return setAttribute(AttributeKey.stringKey(key), value); } @@ -117,6 +120,10 @@ default Span setAttribute(String key, String value) { * @return this. */ default Span setAttribute(String key, long value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + return this; + } return setAttribute(AttributeKey.longKey(key), value); } @@ -132,6 +139,10 @@ default Span setAttribute(String key, long value) { * @return this. */ default Span setAttribute(String key, double value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + return this; + } return setAttribute(AttributeKey.doubleKey(key), value); } @@ -147,20 +158,52 @@ default Span setAttribute(String key, double value) { * @return this. */ default Span setAttribute(String key, boolean value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + return this; + } return setAttribute(AttributeKey.booleanKey(key), value); } + /** + * Sets a {@link Value} attribute on the {@code Span}. If the {@code Span} previously contained a + * mapping for the key, the old value is replaced by the specified value. + * + *

    Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and + * pre-allocate your keys, if possible. + * + *

    Instrumentations should assume that backends do not index individual properties of complex + * attributes, that querying or aggregating on such properties is inefficient and complicated, and + * that reporting complex attributes carries higher performance overhead. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.63.0 + */ + default Span setAttribute(String key, Value value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + return this; + } + if (value == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "value"); + return this; + } + return setAttribute(AttributeKey.valueKey(key), value); + } + /** * Sets an attribute to the {@code Span}. If the {@code Span} previously contained a mapping for * the key, the old value is replaced by the specified value. * - *

    Note: the behavior of null values is undefined, and hence strongly discouraged. + *

    Note: Providing a null value is a no-op. * * @param key the key for this attribute. * @param value the value for this attribute. * @return this. */ - Span setAttribute(AttributeKey key, T value); + Span setAttribute(AttributeKey key, @Nullable T value); /** * Sets an attribute to the {@code Span}. If the {@code Span} previously contained a mapping for @@ -171,6 +214,10 @@ default Span setAttribute(String key, boolean value) { * @return this. */ default Span setAttribute(AttributeKey key, int value) { + if (key == null) { + ApiUsageLogger.logNullParam(Span.class, "setAttribute", "key"); + return this; + } return setAttribute(key, (long) value); } @@ -184,7 +231,11 @@ default Span setAttribute(AttributeKey key, int value) { */ @SuppressWarnings("unchecked") default Span setAllAttributes(Attributes attributes) { - if (attributes == null || attributes.isEmpty()) { + if (attributes == null) { + ApiUsageLogger.logNullParam(Span.class, "setAllAttributes", "attributes"); + return this; + } + if (attributes.isEmpty()) { return this; } attributes.forEach( @@ -199,6 +250,10 @@ default Span setAllAttributes(Attributes attributes) { * @return this. */ default Span addEvent(String name) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + return this; + } return addEvent(name, Attributes.empty()); } @@ -217,6 +272,14 @@ default Span addEvent(String name) { * @return this. */ default Span addEvent(String name, long timestamp, TimeUnit unit) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + return this; + } + if (unit == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "unit"); + return this; + } return addEvent(name, Attributes.empty(), timestamp, unit); } @@ -234,7 +297,12 @@ default Span addEvent(String name, long timestamp, TimeUnit unit) { * @return this. */ default Span addEvent(String name, Instant timestamp) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + return this; + } if (timestamp == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "timestamp"); return addEvent(name); } return addEvent( @@ -286,7 +354,16 @@ default Span addEvent(String name, Instant timestamp) { * @return this. */ default Span addEvent(String name, Attributes attributes, Instant timestamp) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + return this; + } + if (attributes == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "attributes"); + return this; + } if (timestamp == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "timestamp"); return addEvent(name, attributes); } return addEvent( @@ -309,6 +386,10 @@ default Span addEvent(String name, Attributes attributes, Instant timestamp) { * @return this. */ default Span setStatus(StatusCode statusCode) { + if (statusCode == null) { + ApiUsageLogger.logNullParam(Span.class, "setStatus", "statusCode"); + return this; + } return setStatus(statusCode, ""); } @@ -338,6 +419,10 @@ default Span setStatus(StatusCode statusCode) { * @return this. */ default Span recordException(Throwable exception) { + if (exception == null) { + ApiUsageLogger.logNullParam(Span.class, "recordException", "exception"); + return this; + } return recordException(exception, Attributes.empty()); } @@ -363,6 +448,63 @@ default Span recordException(Throwable exception) { */ Span updateName(String name); + /** + * Adds a link to this {@code Span}. + * + *

    Links are used to link {@link Span}s in different traces. Used (for example) in batching + * operations, where a single batch handler processes multiple requests from different traces or + * the same trace. + * + *

    Implementations should record links with an {@linkplain SpanContext#isValid() invalid span + * context} if its {@link TraceState} is nonempty. Implementations may ignore calls with an + * invalid span context and an empty {@link TraceState}. + * + *

    Callers should prefer to add links before starting the span via {@link + * SpanBuilder#addLink(SpanContext)} if possible. + * + * @param spanContext the context of the linked {@code Span}. + * @return this. + * @since 1.37.0 + */ + default Span addLink(SpanContext spanContext) { + if (spanContext == null) { + ApiUsageLogger.logNullParam(Span.class, "addLink", "spanContext"); + return this; + } + return addLink(spanContext, Attributes.empty()); + } + + /** + * Adds a link to this {@code Span}. + * + *

    Links are used to link {@link Span}s in different traces. Used (for example) in batching + * operations, where a single batch handler processes multiple requests from different traces or + * the same trace. + * + *

    Implementations should record links with an {@linkplain SpanContext#isValid() invalid span + * context} if the attributes or its {@link TraceState} are nonempty. Implementations may ignore + * calls with an invalid span context when both are empty. + * + *

    Callers should prefer to add links before starting the span via {@link + * SpanBuilder#addLink(SpanContext, Attributes)} if possible. + * + * @param spanContext the context of the linked {@code Span}. + * @param attributes the attributes of the {@code Link}. + * @return this. + * @since 1.37.0 + */ + default Span addLink(SpanContext spanContext, Attributes attributes) { + if (spanContext == null) { + ApiUsageLogger.logNullParam(Span.class, "addLink", "spanContext"); + return this; + } + if (attributes == null) { + ApiUsageLogger.logNullParam(Span.class, "addLink", "attributes"); + return this; + } + return this; + } + /** * Marks the end of {@code Span} execution. * @@ -400,6 +542,7 @@ default Span recordException(Throwable exception) { */ default void end(Instant timestamp) { if (timestamp == null) { + ApiUsageLogger.logNullParam(Span.class, "end", "timestamp"); end(); return; } @@ -423,6 +566,10 @@ default void end(Instant timestamp) { @Override default Context storeInContext(Context context) { + if (context == null) { + ApiUsageLogger.logNullParam(Span.class, "storeInContext", "context"); + return Context.root(); + } return context.with(SpanContextKey.KEY, this); } } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/SpanBuilder.java b/api/all/src/main/java/io/opentelemetry/api/trace/SpanBuilder.java index 3b1726933a8..0056f208dcb 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/SpanBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/SpanBuilder.java @@ -10,9 +10,11 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.Context; import java.time.Instant; import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; /** * {@link SpanBuilder} is used to construct {@link Span} instances which define arbitrary scopes of @@ -147,8 +149,9 @@ public interface SpanBuilder { * operations, where a single batch handler processes multiple requests from different traces or * the same trace. * - *

    Implementations may ignore calls with an {@linkplain SpanContext#isValid() invalid span - * context}. + *

    Implementations should record links with an {@linkplain SpanContext#isValid() invalid span + * context} if its {@link TraceState} is nonempty. Implementations may ignore calls with an + * invalid span context and an empty {@link TraceState}. * * @param spanContext the context of the linked {@code Span}. * @return this. @@ -162,8 +165,9 @@ public interface SpanBuilder { * operations, where a single batch handler processes multiple requests from different traces or * the same trace. * - *

    Implementations may ignore calls with an {@linkplain SpanContext#isValid() invalid span - * context}. + *

    Implementations should record links with an {@linkplain SpanContext#isValid() invalid span + * context} if the attributes or its {@link TraceState} are nonempty. Implementations may ignore + * calls with an invalid span context when both are empty. * * @param spanContext the context of the linked {@code Span}. * @param attributes the attributes of the {@code Link}. @@ -175,8 +179,7 @@ public interface SpanBuilder { * Sets an attribute to the newly created {@code Span}. If {@code SpanBuilder} previously * contained a mapping for the key, the old value is replaced by the specified value. * - *

    If a null or empty String {@code value} is passed in, the behavior is undefined, and hence - * strongly discouraged. + *

    Note: Providing a null value is a no-op and will not remove previously set values. * *

    Note: It is strongly recommended to use {@link #setAttribute(AttributeKey, Object)}, and * pre-allocate your keys, if possible. @@ -185,7 +188,7 @@ public interface SpanBuilder { * @param value the value for this attribute. * @return this. */ - SpanBuilder setAttribute(String key, String value); + SpanBuilder setAttribute(String key, @Nullable String value); /** * Sets an attribute to the newly created {@code Span}. If {@code SpanBuilder} previously @@ -230,13 +233,30 @@ public interface SpanBuilder { * Sets an attribute to the newly created {@code Span}. If {@code SpanBuilder} previously * contained a mapping for the key, the old value is replaced by the specified value. * - *

    Note: the behavior of null values is undefined, and hence strongly discouraged. + *

    Note: Providing a null value is a no-op. * * @param key the key for this attribute. * @param value the value for this attribute. * @return this. */ - SpanBuilder setAttribute(AttributeKey key, T value); + SpanBuilder setAttribute(AttributeKey key, @Nullable T value); + + /** + * Sets an attribute to the newly created {@code Span}. If {@code SpanBuilder} previously + * contained a mapping for the key, the old value is replaced by the specified value. + * + * @param key the key for this attribute. + * @param value the value for this attribute. + * @return this. + * @since 1.45.0 + */ + default SpanBuilder setAttribute(AttributeKey key, int value) { + if (key == null) { + ApiUsageLogger.logNullParam(AttributeKey.class, "setAttribute", "key"); + return this; + } + return setAttribute(key, (long) value); + } /** * Sets attributes to the {@link SpanBuilder}. If the {@link SpanBuilder} previously contained a @@ -248,7 +268,8 @@ public interface SpanBuilder { */ @SuppressWarnings("unchecked") default SpanBuilder setAllAttributes(Attributes attributes) { - if (attributes == null || attributes.isEmpty()) { + if (attributes == null) { + ApiUsageLogger.logNullParam(Attributes.class, "setAllAttributes", "attributes"); return this; } attributes.forEach( @@ -268,9 +289,8 @@ default SpanBuilder setAllAttributes(Attributes attributes) { /** * Sets an explicit start timestamp for the newly created {@code Span}. * - *

    LIRInstruction.Use this method to specify an explicit start timestamp. If not called, the - * implementation will use the timestamp value at {@link #startSpan()} time, which should be the - * default case. + *

    Use this method to specify an explicit start timestamp. If not called, the implementation + * will use the timestamp value at {@link #startSpan()} time, which should be the default case. * *

    Important this is NOT equivalent with System.nanoTime(). * @@ -295,6 +315,7 @@ default SpanBuilder setAllAttributes(Attributes attributes) { */ default SpanBuilder setStartTimestamp(Instant startTimestamp) { if (startTimestamp == null) { + ApiUsageLogger.logNullParam(Instant.class, "setStartTimestamp", "startTimestamp"); return this; } return setStartTimestamp( diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/SpanContext.java b/api/all/src/main/java/io/opentelemetry/api/trace/SpanContext.java index 2c19fc387a9..a67b4118f82 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/SpanContext.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/SpanContext.java @@ -7,14 +7,14 @@ import io.opentelemetry.api.internal.ImmutableSpanContext; import io.opentelemetry.api.internal.OtelEncodingUtils; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.Immutable; /** * A class that represents a span context. A span context contains the state that must propagate to * child {@link Span}s and across process boundaries. It contains the identifiers (a {@link TraceId - * trace_id} and {@link SpanId span_id}) associated with the {@link Span} and a set of options - * (currently only whether the context is sampled or not), as well as the {@link TraceState - * traceState} and the {@link boolean remote} flag. + * trace_id} and {@link SpanId span_id}) associated with the {@link Span}, {@link TraceFlags}, as + * well as the {@link TraceState traceState} and the {@code remote} flag. * *

    Implementations of this interface *must* be immutable and have well-defined value-based * equals/hashCode implementations. If an implementation does not strictly conform to these @@ -51,13 +51,29 @@ static SpanContext getInvalid() { */ static SpanContext create( String traceIdHex, String spanIdHex, TraceFlags traceFlags, TraceState traceState) { + if (traceIdHex == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "create", "traceIdHex"); + return SpanContext.getInvalid(); + } + if (spanIdHex == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "create", "spanIdHex"); + return SpanContext.getInvalid(); + } + if (traceFlags == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "create", "traceFlags"); + return SpanContext.getInvalid(); + } + if (traceState == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "create", "traceState"); + return SpanContext.getInvalid(); + } return ImmutableSpanContext.create( traceIdHex, spanIdHex, traceFlags, traceState, - /* remote=*/ false, - /* skipIdValidation=*/ false); + /* remote= */ false, + /* skipIdValidation= */ false); } /** @@ -77,13 +93,29 @@ static SpanContext create( */ static SpanContext createFromRemoteParent( String traceIdHex, String spanIdHex, TraceFlags traceFlags, TraceState traceState) { + if (traceIdHex == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "createFromRemoteParent", "traceIdHex"); + return SpanContext.getInvalid(); + } + if (spanIdHex == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "createFromRemoteParent", "spanIdHex"); + return SpanContext.getInvalid(); + } + if (traceFlags == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "createFromRemoteParent", "traceFlags"); + return SpanContext.getInvalid(); + } + if (traceState == null) { + ApiUsageLogger.logNullParam(SpanContext.class, "createFromRemoteParent", "traceState"); + return SpanContext.getInvalid(); + } return ImmutableSpanContext.create( traceIdHex, spanIdHex, traceFlags, traceState, - /* remote=*/ true, - /* skipIdValidation=*/ false); + /* remote= */ true, + /* skipIdValidation= */ false); } /** diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/SpanId.java b/api/all/src/main/java/io/opentelemetry/api/trace/SpanId.java index f153b6c9f22..b0f9bfff514 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/SpanId.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/SpanId.java @@ -5,9 +5,9 @@ package io.opentelemetry.api.trace; +import io.opentelemetry.api.impl.TemporaryBuffers; import io.opentelemetry.api.internal.OtelEncodingUtils; -import io.opentelemetry.api.internal.TemporaryBuffers; -import io.opentelemetry.api.internal.ValidationUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.Immutable; /** @@ -55,8 +55,11 @@ public static String getInvalid() { * @return {@code true} if the span identifier is valid. */ public static boolean isValid(CharSequence spanId) { - return spanId != null - && spanId.length() == HEX_LENGTH + if (spanId == null) { + ApiUsageLogger.logNullParam(SpanId.class, "isValid", "spanId"); + return false; + } + return spanId.length() == HEX_LENGTH && !INVALID.contentEquals(spanId) && OtelEncodingUtils.isValidBase16String(spanId); } @@ -72,9 +75,13 @@ public static boolean isValid(CharSequence spanId) { * @return the lowercase hex (base16) representation of the {@code SpanId}. */ public static String fromBytes(byte[] spanIdBytes) { - if (spanIdBytes == null || spanIdBytes.length < BYTES_LENGTH) { - ValidationUtil.log("spanIdBytes is null or too short"); - return INVALID; + if (spanIdBytes == null) { + ApiUsageLogger.logNullParam(SpanId.class, "fromBytes", "spanIdBytes"); + return getInvalid(); + } + if (spanIdBytes.length < BYTES_LENGTH) { + ApiUsageLogger.logUsageIssue(SpanId.class, "fromBytes", "spanIdBytes is too short"); + return getInvalid(); } char[] result = TemporaryBuffers.chars(HEX_LENGTH); OtelEncodingUtils.bytesToBase16(spanIdBytes, result, BYTES_LENGTH); diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlags.java b/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlags.java index 936a1a6e06c..c45921aa1b2 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlags.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlags.java @@ -5,6 +5,7 @@ package io.opentelemetry.api.trace; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.Immutable; /** @@ -54,6 +55,10 @@ static TraceFlags getSampled() { * @return the {@link TraceFlags} converted from the given lowercase hex (base16) representation. */ static TraceFlags fromHex(CharSequence src, int srcOffset) { + if (src == null) { + ApiUsageLogger.logNullParam(TraceFlags.class, "fromHex", "src"); + return getDefault(); + } return ImmutableTraceFlags.fromHex(src, srcOffset); } @@ -71,15 +76,28 @@ static TraceFlags fromByte(byte traceFlagsByte) { * Returns {@code true} if the sampling bit is on for this {@link TraceFlags}, otherwise {@code * false}. * - * @return {@code true} if the sampling bit is on for this {@link TraceFlags}, otherwise {@code * + * @return {@code true} if the sampling bit is on for this {@link TraceFlags}, otherwise {@code * false}. */ boolean isSampled(); + /** + * Returns {@code true} if the TraceId accompanying this {@link TraceFlags} is known to be + * generated by a truly random Id generator, otherwise {@code false}. Providing default + * implementation just to maintain compatibility. + * + * @return {@code true} if the randomTraceId bit is on for this {@link TraceFlags}, otherwise + * {@code false}. + * @since 1.60.0 + */ + default boolean isTraceIdRandom() { + return false; + } + /** * Returns the lowercase hex (base16) representation of this {@link TraceFlags}. * - * @return the byte representation of the {@link TraceFlags}. + * @return the lowercase hex (base16) representation of the {@link TraceFlags}. */ String asHex(); @@ -89,4 +107,13 @@ static TraceFlags fromByte(byte traceFlagsByte) { * @return the byte representation of the {@link TraceFlags}. */ byte asByte(); + + /** + * Returns an instance of {@link TraceFlagsBuilder} for {@link TraceFlags}. + * + * @since 1.60.0 + */ + static TraceFlagsBuilder builder() { + return ImmutableTraceFlags.DEFAULT; + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlagsBuilder.java b/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlagsBuilder.java new file mode 100644 index 00000000000..12e8e8d1c4c --- /dev/null +++ b/api/all/src/main/java/io/opentelemetry/api/trace/TraceFlagsBuilder.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.trace; + +/** + * {@link TraceFlagsBuilder} is used to construct {@link TraceFlags} instances which satisfy the + * https://www.w3.org/TR/trace-context-2/#trace-flags specification. + * + *

    This is a simple usage example: + * + *

    {@code
    + * TraceFlags traceFlags = TraceFlags.builder().setSampled(true).build();
    + * }
    + * + *

    Implementation note: no new objects are created by the methods defined by this interface when + * the default implementation, {@link ImmutableTraceFlags}, is used. + * + * @since 1.60.0 + */ +public interface TraceFlagsBuilder { + + /** + * Returns an instance of {@link TraceFlagsBuilder} which represents a {@link TraceFlags} object + * which has the SAMPLED bit set if the argument is {@code true} and the SAMPLED bit cleared when + * the argument is {@code false}. Other bits remain unchanged. The operation does not modify this + * object. + * + * @param isSampled the new value for the SAMPLED bit + * @return a {@link TraceFlagsBuilder} object representing the modified {@link TraceFlags} + */ + TraceFlagsBuilder setSampled(boolean isSampled); + + /** + * Returns an instance of {@link TraceFlagsBuilder} which represents a {@link TraceFlags} object + * which has the RANDOM_TRACE_ID bit set if the argument is {@code true} and the RANDOM_TRACE_ID + * bit cleared when the argument is {@code false}. Other bits remain unchanged. The operation does + * not modify this object. + * + * @param isRandomTraceId the new value for the RANDOM_TRACE_ID bit + * @return a {@link TraceFlagsBuilder} object representing the modified {@link TraceFlags} + */ + TraceFlagsBuilder setRandomTraceId(boolean isRandomTraceId); + + /** + * Returns {@link TraceFlags} represented by this object. + * + * @return a {@link TraceFlags} object with the bits set as configured + */ + TraceFlags build(); +} diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/TraceId.java b/api/all/src/main/java/io/opentelemetry/api/trace/TraceId.java index d68d81d9f3c..9386a5c21e0 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/TraceId.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/TraceId.java @@ -5,9 +5,9 @@ package io.opentelemetry.api.trace; +import io.opentelemetry.api.impl.TemporaryBuffers; import io.opentelemetry.api.internal.OtelEncodingUtils; -import io.opentelemetry.api.internal.TemporaryBuffers; -import io.opentelemetry.api.internal.ValidationUtil; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.Immutable; /** @@ -59,8 +59,11 @@ public static String getInvalid() { * @return {@code true} if the {@code TraceId} is valid. */ public static boolean isValid(CharSequence traceId) { - return traceId != null - && traceId.length() == HEX_LENGTH + if (traceId == null) { + ApiUsageLogger.logNullParam(TraceId.class, "isValid", "traceId"); + return false; + } + return traceId.length() == HEX_LENGTH && !INVALID.contentEquals(traceId) && OtelEncodingUtils.isValidBase16String(traceId); } @@ -70,14 +73,18 @@ public static boolean isValid(CharSequence traceId) { * given bytes representation, or {@link #getInvalid()} if input is {@code null} or the given byte * array is too short. * - *

    It converts the first 26 bytes of the given byte array. + *

    It converts the first 16 bytes of the given byte array. * * @param traceIdBytes the bytes (16-byte array) representation of the {@code TraceId}. * @return the lowercase hex (base16) representation of the {@code TraceId}. */ public static String fromBytes(byte[] traceIdBytes) { - if (traceIdBytes == null || traceIdBytes.length < BYTES_LENGTH) { - ValidationUtil.log("traceIdBytes is null or too short"); + if (traceIdBytes == null) { + ApiUsageLogger.logNullParam(TraceId.class, "fromBytes", "traceIdBytes"); + return INVALID; + } + if (traceIdBytes.length < BYTES_LENGTH) { + ApiUsageLogger.logUsageIssue(TraceId.class, "fromBytes", "traceIdBytes is too short"); return INVALID; } char[] result = TemporaryBuffers.chars(HEX_LENGTH); @@ -86,7 +93,7 @@ public static String fromBytes(byte[] traceIdBytes) { } /** - * Returns the bytes (16-byte array) representation of the {@code TraceId} converted from the + * Returns the lowercase hex (base16) representation of the {@code TraceId} converted from the * given two {@code long} values representing the lower and higher parts. * *

    There is no restriction on the specified values, other than the already established validity diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/Tracer.java b/api/all/src/main/java/io/opentelemetry/api/trace/Tracer.java index f3b0703b361..2be12fc94a4 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/Tracer.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/Tracer.java @@ -45,7 +45,8 @@ * openTelemetry.getTracer("instrumentation-library-name", "1.0.0"); * void doWork(Span parent) { * Span childSpan = tracer.spanBuilder("MyChildSpan") - * setParent(parent).startSpan(); + * .setParent(Context.current().with(parent)) + * .startSpan(); * childSpan.addEvent("Starting the work."); * try { * doSomeWork(childSpan); // Manually propagate the new span down the stack. @@ -60,6 +61,19 @@ @ThreadSafe public interface Tracer { + /** + * Returns {@code true} if the tracer is enabled. + * + *

    This allows callers to avoid unnecessary compute when nothing is consuming the data. Because + * the response is subject to change over the application, callers should call this before each + * call to {@link #spanBuilder(String)}. + * + * @since 1.61.0 + */ + default boolean isEnabled() { + return true; + } + /** * Returns a {@link SpanBuilder} to create and start a new {@link Span}. * diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/TracerBuilder.java b/api/all/src/main/java/io/opentelemetry/api/trace/TracerBuilder.java index ba814b3d3c4..63d9876870f 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/TracerBuilder.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/TracerBuilder.java @@ -8,22 +8,28 @@ /** * Builder class for creating {@link Tracer} instances. * + *

    {@link Tracer}s are identified by their scope name, version, and schema URL. These identifying + * fields, along with attributes, combine to form the instrumentation scope, which is attached to + * all spans produced by the {@link Tracer}. + * * @since 1.4.0 */ public interface TracerBuilder { /** - * Assign an OpenTelemetry schema URL to the resulting Tracer. + * Set the scope schema URL of the resulting {@link Tracer}. Schema URL is part of {@link Tracer} + * identity. * - * @param schemaUrl The URL of the OpenTelemetry schema being used by this instrumentation scope. + * @param schemaUrl The schema URL. * @return this */ TracerBuilder setSchemaUrl(String schemaUrl); /** - * Assign a version to the instrumentation scope that is using the resulting Tracer. + * Sets the instrumentation scope version of the resulting {@link Tracer}. Version is part of + * {@link Tracer} identity. * - * @param instrumentationScopeVersion The version of the instrumentation scope. + * @param instrumentationScopeVersion The instrumentation scope version. * @return this */ TracerBuilder setInstrumentationVersion(String instrumentationScopeVersion); diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/TracerProvider.java b/api/all/src/main/java/io/opentelemetry/api/trace/TracerProvider.java index 2ef9d12acfe..1c3dbb80407 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/TracerProvider.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/TracerProvider.java @@ -5,6 +5,7 @@ package io.opentelemetry.api.trace; +import io.opentelemetry.common.impl.ApiUsageLogger; import javax.annotation.concurrent.ThreadSafe; /** @@ -52,6 +53,11 @@ static TracerProvider noop() { * @since 1.4.0 */ default TracerBuilder tracerBuilder(String instrumentationScopeName) { + if (instrumentationScopeName == null) { + ApiUsageLogger.logNullParam( + TracerProvider.class, "tracerBuilder", "instrumentationScopeName"); + return DefaultTracerBuilder.getInstance(); + } return DefaultTracerBuilder.getInstance(); } } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/package-info.java b/api/all/src/main/java/io/opentelemetry/api/trace/package-info.java index 2970a7eeadf..1a6e4789fb7 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/package-info.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/package-info.java @@ -18,7 +18,6 @@ * io.opentelemetry.context.Context} and between process using one of the wire propagation formats * supported in the {@code opentelemetry.trace.propagation} package. */ -// TODO: Add code examples. @ParametersAreNonnullByDefault package io.opentelemetry.api.trace; diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagator.java b/api/all/src/main/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagator.java index 91414e9412a..393439518df 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagator.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagator.java @@ -8,14 +8,15 @@ import static io.opentelemetry.api.trace.propagation.internal.W3CTraceContextEncoding.decodeTraceState; import static io.opentelemetry.api.trace.propagation.internal.W3CTraceContextEncoding.encodeTraceState; +import io.opentelemetry.api.impl.TemporaryBuffers; import io.opentelemetry.api.internal.OtelEncodingUtils; -import io.opentelemetry.api.internal.TemporaryBuffers; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; @@ -94,7 +95,12 @@ public Collection fields() { @Override public void inject(Context context, @Nullable C carrier, TextMapSetter setter) { - if (context == null || setter == null) { + if (context == null) { + ApiUsageLogger.logNullParam(TextMapPropagator.class, "inject", "context"); + return; + } + if (setter == null) { + ApiUsageLogger.logNullParam(TextMapPropagator.class, "inject", "setter"); return; } @@ -132,9 +138,11 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se @Override public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { if (context == null) { + ApiUsageLogger.logNullParam(TextMapPropagator.class, "extract", "context"); return Context.root(); } if (getter == null) { + ApiUsageLogger.logNullParam(TextMapPropagator.class, "extract", "getter"); return context; } @@ -213,4 +221,9 @@ private static SpanContext extractContextFromTraceParent(String traceparent) { OtelEncodingUtils.byteFromBase16(firstTraceFlagsChar, secondTraceFlagsChar)); return SpanContext.createFromRemoteParent(traceId, spanId, traceFlags, TraceState.getDefault()); } + + @Override + public String toString() { + return "W3CTraceContextPropagator"; + } } diff --git a/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java b/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java index b6b0c6682e5..b21093b09e7 100644 --- a/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java +++ b/api/all/src/main/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncoding.java @@ -9,7 +9,6 @@ import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.api.trace.TraceStateBuilder; -import java.util.regex.Pattern; import javax.annotation.concurrent.Immutable; /** @@ -29,8 +28,6 @@ private W3CTraceContextEncoding() {} private static final int TRACESTATE_MAX_MEMBERS = 32; private static final char TRACESTATE_KEY_VALUE_DELIMITER = '='; private static final char TRACESTATE_ENTRY_DELIMITER = ','; - private static final Pattern TRACESTATE_ENTRY_DELIMITER_SPLIT_PATTERN = - Pattern.compile("[ \t]*" + TRACESTATE_ENTRY_DELIMITER + "[ \t]*"); /** * Decodes a trace state header into a {@link TraceState} object. @@ -40,38 +37,53 @@ private W3CTraceContextEncoding() {} */ public static TraceState decodeTraceState(String traceStateHeader) { TraceStateBuilder traceStateBuilder = TraceState.builder(); - String[] listMembers = TRACESTATE_ENTRY_DELIMITER_SPLIT_PATTERN.split(traceStateHeader); - checkArgument( - listMembers.length <= TRACESTATE_MAX_MEMBERS, "TraceState has too many elements."); - // Iterate in reverse order because when call builder set the elements is added in the - // front of the list. - for (int i = listMembers.length - 1; i >= 0; i--) { - String listMember = listMembers[i]; - int index = listMember.indexOf(TRACESTATE_KEY_VALUE_DELIMITER); - checkArgument(index != -1, "Invalid TraceState list-member format."); - traceStateBuilder.put(listMember.substring(0, index), listMember.substring(index + 1)); + int memberCount = 0; + int end = traceStateHeader.length(); + // Scan backwards because the builder prepends entries. Use literal comma searches to avoid + // backtracking. + while (end > 0) { + int start = traceStateHeader.lastIndexOf(TRACESTATE_ENTRY_DELIMITER, end - 1) + 1; + int nextEnd = start - 1; + while (start < end && isOptionalWhitespace(traceStateHeader.charAt(start))) { + start++; + } + while (end > start && isOptionalWhitespace(traceStateHeader.charAt(end - 1))) { + end--; + } + if (start < end) { + memberCount++; + checkArgument(memberCount <= TRACESTATE_MAX_MEMBERS, "TraceState has too many elements."); + int index = traceStateHeader.indexOf(TRACESTATE_KEY_VALUE_DELIMITER, start); + checkArgument(index != -1 && index < end, "Invalid TraceState list-member format."); + traceStateBuilder.put( + traceStateHeader.substring(start, index), traceStateHeader.substring(index + 1, end)); + } + end = nextEnd; } TraceState traceState = traceStateBuilder.build(); - if (traceState.size() != listMembers.length) { + if (traceState.size() != memberCount) { // Validation failure, drop the tracestate return TraceState.getDefault(); } return traceState; } + private static boolean isOptionalWhitespace(char character) { + return character == ' ' || character == '\t'; + } + /** Return the trace state encoded as a string according to the W3C specification. */ public static String encodeTraceState(TraceState traceState) { if (traceState.isEmpty()) { return ""; } StringBuilder builder = new StringBuilder(TRACESTATE_MAX_SIZE); - traceState.forEach( - (key, value) -> { - if (builder.length() != 0) { - builder.append(TRACESTATE_ENTRY_DELIMITER); - } - builder.append(key).append(TRACESTATE_KEY_VALUE_DELIMITER).append(value); - }); + traceState.forEach((key, value) -> { + if (builder.length() != 0) { + builder.append(TRACESTATE_ENTRY_DELIMITER); + } + builder.append(key).append(TRACESTATE_KEY_VALUE_DELIMITER).append(value); + }); return builder.toString(); } } diff --git a/api/all/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/native-image.properties b/api/all/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/native-image.properties new file mode 100644 index 00000000000..b6cdd754785 --- /dev/null +++ b/api/all/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/native-image.properties @@ -0,0 +1 @@ +Args=--initialize-at-build-time=io.opentelemetry.api.common.AttributeType diff --git a/api/all/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/resource-config.json b/api/all/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/resource-config.json new file mode 100644 index 00000000000..a8c57fbdb83 --- /dev/null +++ b/api/all/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/resource-config.json @@ -0,0 +1,10 @@ +{ + "resources": { + "includes": [ + { + "pattern":"\\Qio/opentelemetry/api/version.properties\\E" + } + ] + }, + "bundles": [] +} diff --git a/api/all/src/test/java/io/opentelemetry/api/OpenTelemetryTest.java b/api/all/src/test/java/io/opentelemetry/api/OpenTelemetryTest.java index b84b01561ee..f985cffe2ed 100644 --- a/api/all/src/test/java/io/opentelemetry/api/OpenTelemetryTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/OpenTelemetryTest.java @@ -5,88 +5,25 @@ package io.opentelemetry.api; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; - +import io.opentelemetry.api.logs.LoggerProvider; import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.testing.internal.AbstractOpenTelemetryTest; import io.opentelemetry.api.trace.TracerProvider; -import io.opentelemetry.context.propagation.ContextPropagators; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; - -class OpenTelemetryTest { - - @BeforeAll - static void beforeClass() { - GlobalOpenTelemetry.resetForTest(); - } - - @AfterEach - void after() { - GlobalOpenTelemetry.resetForTest(); - } - - @Test - void testDefault() { - assertThat(OpenTelemetry.noop().getTracerProvider()).isSameAs(TracerProvider.noop()); - assertThat(OpenTelemetry.noop().getPropagators()).isSameAs(ContextPropagators.noop()); - assertThat(OpenTelemetry.noop().getMeterProvider()).isSameAs(MeterProvider.noop()); - } - - @Test - void propagating() { - ContextPropagators contextPropagators = mock(ContextPropagators.class); - OpenTelemetry openTelemetry = OpenTelemetry.propagating(contextPropagators); - assertThat(openTelemetry.getTracerProvider()).isSameAs(TracerProvider.noop()); - assertThat(openTelemetry.getMeterProvider()).isSameAs(MeterProvider.noop()); - assertThat(openTelemetry.getPropagators()).isSameAs(contextPropagators); - } - - @Test - void testGlobalBeforeSet() { - assertThat(GlobalOpenTelemetry.getTracerProvider()).isSameAs(TracerProvider.noop()); - assertThat(GlobalOpenTelemetry.getTracerProvider()) - .isSameAs(GlobalOpenTelemetry.getTracerProvider()); - assertThat(GlobalOpenTelemetry.getPropagators()).isSameAs(GlobalOpenTelemetry.getPropagators()); - } - - @Test - void independentNonGlobalPropagators() { - ContextPropagators propagators1 = mock(ContextPropagators.class); - OpenTelemetry otel1 = OpenTelemetry.propagating(propagators1); - ContextPropagators propagators2 = mock(ContextPropagators.class); - OpenTelemetry otel2 = OpenTelemetry.propagating(propagators2); - - assertThat(otel1.getPropagators()).isSameAs(propagators1); - assertThat(otel2.getPropagators()).isSameAs(propagators2); - } - - @Test - void setThenSet() { - setOpenTelemetry(); - assertThatThrownBy(() -> GlobalOpenTelemetry.set(OpenTelemetry.noop())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("GlobalOpenTelemetry.set has already been called") - .hasStackTraceContaining("setOpenTelemetry"); - } +class OpenTelemetryTest extends AbstractOpenTelemetryTest { - @Test - void getThenSet() { - assertThat(getOpenTelemetry()).isInstanceOf(DefaultOpenTelemetry.class); - assertThatThrownBy(() -> GlobalOpenTelemetry.set(OpenTelemetry.noop())) - .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("GlobalOpenTelemetry.set has already been called") - .hasStackTraceContaining("getOpenTelemetry"); + @Override + protected TracerProvider getTracerProvider() { + return TracerProvider.noop(); } - private static void setOpenTelemetry() { - GlobalOpenTelemetry.set(OpenTelemetry.noop()); + @Override + protected MeterProvider getMeterProvider() { + return MeterProvider.noop(); } - private static OpenTelemetry getOpenTelemetry() { - return GlobalOpenTelemetry.get(); + @Override + protected LoggerProvider getLoggerProvider() { + return LoggerProvider.noop(); } } diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageContextTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageContextTest.java index b8dfd63e168..8d8800a3e77 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageContextTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageContextTest.java @@ -7,12 +7,21 @@ import static org.assertj.core.api.Assertions.assertThat; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.slf4j.event.Level; +@SuppressLogger(loggerName = "io.opentelemetry.usage") class BaggageContextTest { + @RegisterExtension + LogCapturer logCapturer = + LogCapturer.create().captureForLogger("io.opentelemetry.usage", Level.TRACE); + @Test void testGetCurrentBaggage_Default() { try (Scope s = Context.root().makeCurrent()) { @@ -42,6 +51,20 @@ void testGetBaggage_ExplicitContext() { assertThat(Baggage.fromContext(context)).isSameAs(baggage); } + @Test + void fromContext_null() { + Baggage result = Baggage.fromContext(null); + assertThat(result).isEqualTo(Baggage.empty()); + logCapturer.assertContains("context is null"); + } + + @Test + void fromContextOrNull_null() { + Baggage result = Baggage.fromContextOrNull(null); + assertThat(result).isNull(); + logCapturer.assertContains("context is null"); + } + @Test void testGetBaggageWithoutDefault_DefaultContext() { Baggage baggage = Baggage.fromContextOrNull(Context.root()); diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageEntryMetadataTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageEntryMetadataTest.java index be5dc952c8c..581af33d921 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageEntryMetadataTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageEntryMetadataTest.java @@ -8,6 +8,7 @@ import static org.assertj.core.api.Assertions.assertThat; import com.google.common.testing.EqualsTester; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import org.junit.jupiter.api.Test; class BaggageEntryMetadataTest { @@ -19,6 +20,7 @@ void getValue() { } @Test + @SuppressLogger(loggerName = "io.opentelemetry.usage") void nullValue() { assertThat(BaggageEntryMetadata.create(null)).isEqualTo(BaggageEntryMetadata.empty()); } diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageTest.java index 4c141276e1d..f30ee5703cc 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/BaggageTest.java @@ -9,6 +9,10 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; import org.junit.jupiter.api.Test; class BaggageTest { @@ -27,4 +31,45 @@ void current() { assertThat(result.getEntryValue("foo")).isEqualTo("bar"); } } + + @Test + void getEntryDefault() { + BaggageEntryMetadata metadata = BaggageEntryMetadata.create("flib"); + Map result = new HashMap<>(); + result.put("a", ImmutableEntry.create("b", metadata)); + // Implementation that only implements asMap() which is used by getEntry() + Baggage baggage = + new Baggage() { + + @Override + public Map asMap() { + return result; + } + + @Override + public int size() { + return 0; + } + + @Override + public void forEach(BiConsumer consumer) { + result.forEach(consumer); + } + + @Nullable + @Override + public String getEntryValue(String entryKey) { + return null; + } + + @Override + public BaggageBuilder toBuilder() { + return null; + } + }; + + BaggageEntry entry = baggage.getEntry("a"); + assertThat(entry.getValue()).isEqualTo("b"); + assertThat(entry.getMetadata().getValue()).isEqualTo("flib"); + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/ImmutableBaggageTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/ImmutableBaggageTest.java index 311c8bae337..041744f9850 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/ImmutableBaggageTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/ImmutableBaggageTest.java @@ -9,6 +9,8 @@ import static org.assertj.core.api.Assertions.entry; import com.google.common.testing.EqualsTester; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; import org.junit.jupiter.api.Test; /** @@ -112,8 +114,17 @@ void put_keyUnprintableChars() { @Test void put_keyEmpty() { BaggageBuilder builder = ONE_ENTRY.toBuilder(); + Baggage built = builder.build(); builder.put("", "value"); - assertThat(builder.build().getEntryValue("")).isEqualTo("value"); + assertThat(builder.build()).isEqualTo(built); + } + + @Test + void put_keyEmpty_withMetadata() { + BaggageBuilder builder = ONE_ENTRY.toBuilder(); + Baggage built = builder.build(); + builder.put("", "value", TMD); + assertThat(builder.build()).isEqualTo(built); } @Test @@ -190,4 +201,15 @@ void testEquals() { .addEqualityGroup(baggage2, baggage3) .testEquals(); } + + @Test + void getEntry() { + BaggageEntryMetadata metadata = BaggageEntryMetadata.create("flib"); + try (Scope scope = + Context.root().with(Baggage.builder().put("a", "b", metadata).build()).makeCurrent()) { + Baggage result = Baggage.current(); + assertThat(result.getEntry("a").getValue()).isEqualTo("b"); + assertThat(result.getEntry("a").getMetadata().getValue()).isEqualTo("flib"); + } + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/BaggageCodecTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/BaggageCodecTest.java new file mode 100644 index 00000000000..22b23cda0c3 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/BaggageCodecTest.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.baggage.propagation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class BaggageCodecTest { + + @ParameterizedTest + @CsvSource( + quoteCharacter = ';', // default is a quote character "'", which collides with %27 character. + value = { + "%21,!", "%23,#", "%24,$", "%25,%", "%26,&", "%27,'", "%28,(", "%29,)", "%2A,*", "%2B,+", + "%2D,-", "%2E,.", "%2F,/", "%30,0", "%31,1", "%32,2", "%33,3", "%34,4", "%35,5", "%36,6", + "%37,7", "%38,8", "%39,9", "%3A,:", "%3C,<", "%3D,=", "%3E,>", "%3F,?", "%40,@", "%41,A", + "%42,B", "%43,C", "%44,D", "%45,E", "%46,F", "%47,G", "%48,H", "%49,I", "%4A,J", "%4B,K", + "%4C,L", "%4D,M", "%4E,N", "%4F,O", "%50,P", "%51,Q", "%52,R", "%53,S", "%54,T", "%55,U", + "%56,V", "%57,W", "%58,X", "%59,Y", "%5A,Z", "%5B,[", "%5D,]", "%5E,^", "%5F,_", "%60,`", + "%61,a", "%62,b", "%63,c", "%64,d", "%65,e", "%66,f", "%67,g", "%68,h", "%69,i", "%6A,j", + "%6B,k", "%6C,l", "%6D,m", "%6E,n", "%6F,o", "%70,p", "%71,q", "%72,r", "%73,s", "%74,t", + "%75,u", "%76,v", "%77,w", "%78,x", "%79,y", "%7A,z", "%7B,{", "%7C,|", "%7D,}", "%7E,~", + }) + void shouldDecodePercentEncodedValues(String percentEncoded, String expectedDecoded) { + assertThat(BaggageCodec.decode(percentEncoded, StandardCharsets.UTF_8)) + .isEqualTo(expectedDecoded); + } + + @Test + void shouldIgnoreIfMalformedData() { + assertThat(BaggageCodec.decode("%", StandardCharsets.UTF_8)).isEqualTo(""); + assertThat(BaggageCodec.decode("%1", StandardCharsets.UTF_8)).isEqualTo(""); + } + + @Test + void shouldThrowNumberFormatExceptionForInvalidHexDigit() { + assertThatThrownBy(() -> BaggageCodec.decode("%G0", StandardCharsets.UTF_8)) + .isInstanceOf(NumberFormatException.class) + .hasMessageContaining("byte=71") + .hasMessageContaining("char='G'"); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/PercentEscaperFuzzTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/PercentEscaperFuzzTest.java index 6c4117d7953..11fbe0182f6 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/PercentEscaperFuzzTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/PercentEscaperFuzzTest.java @@ -11,7 +11,9 @@ import edu.berkeley.cs.jqf.fuzz.JQF; import edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing; import edu.berkeley.cs.jqf.fuzz.random.NoGuidance; +import io.opentelemetry.api.internal.PercentEscaper; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.Test; import org.junit.runner.Result; import org.junit.runner.RunWith; @@ -21,10 +23,11 @@ class PercentEscaperFuzzTest { public static class TestCases { private final PercentEscaper percentEscaper = new PercentEscaper(); + @SuppressWarnings("JdkObsolete") // Recommended alternative was introduced in java 10 @Fuzz public void roundTripWithUrlDecoder(String value) throws Exception { String escaped = percentEscaper.escape(value); - String decoded = URLDecoder.decode(escaped, "UTF-8"); + String decoded = URLDecoder.decode(escaped, StandardCharsets.UTF_8.name()); assertThat(decoded).isEqualTo(value); } } diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorFuzzTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorFuzzTest.java index 83e78ca0ec7..efca289f92b 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorFuzzTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorFuzzTest.java @@ -18,8 +18,11 @@ import io.opentelemetry.api.baggage.BaggageEntryMetadata; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; +import java.util.Arrays; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; import org.junit.runner.Result; @@ -33,11 +36,12 @@ public static class TestCases { private final W3CBaggagePropagator baggagePropagator = W3CBaggagePropagator.getInstance(); @Fuzz - public void roundTripRandomValues(String baggageValue, String metadataBlob) { + public void roundTripRandomValues( + String baggageValue, @From(MetadataGenerator.class) String metadataBlob) { + // Extract trims OWS around the metadata blob; match that so round-trip compares equal. + String metadata = metadataBlob.trim(); Baggage baggage = - Baggage.builder() - .put("b", baggageValue, BaggageEntryMetadata.create(metadataBlob)) - .build(); + Baggage.builder().put("b", baggageValue, BaggageEntryMetadata.create(metadata)).build(); Map carrier = new HashMap<>(); baggagePropagator.inject(Context.root().with(baggage), carrier, Map::put); Context extractedContext = @@ -50,11 +54,10 @@ public void roundTripRandomValues(String baggageValue, String metadataBlob) { @Fuzz public void roundTripAsciiValues( @From(AsciiGenerator.class) String baggageValue, - @From(AsciiGenerator.class) String metadataBlob) { + @From(MetadataGenerator.class) String metadataBlob) { + String metadata = metadataBlob.trim(); Baggage baggage = - Baggage.builder() - .put("b", baggageValue, BaggageEntryMetadata.create(metadataBlob)) - .build(); + Baggage.builder().put("b", baggageValue, BaggageEntryMetadata.create(metadata)).build(); Map carrier = new HashMap<>(); baggagePropagator.inject(Context.root().with(baggage), carrier, Map::put); Context extractedContext = @@ -62,6 +65,17 @@ public void roundTripAsciiValues( Baggage extractedBaggage = Baggage.fromContext(extractedContext); assertThat(extractedBaggage).isEqualTo(baggage); } + + @Fuzz + public void baggageOctet(@From(BaggageOctetGenerator.class) String baggageValue) { + Map carrier = new HashMap<>(); + carrier.put("baggage", "key=" + baggageValue); + Context context = + baggagePropagator.extract(Context.current(), carrier, new MapTextMapGetter()); + Baggage baggage = Baggage.fromContext(context); + String value = baggage.getEntryValue("key"); + assertThat(value).isEqualTo(baggageValue); + } } // driver methods to avoid having to use the vintage junit engine, and to enable increasing the @@ -79,9 +93,15 @@ void roundTripFuzzing() { assertThat(result.wasSuccessful()).isTrue(); } - private static Result runTestCase(String roundTripRandomValues) { + @Test + void baggageOctetFuzzing() { + Result result = runTestCase("baggageOctet"); + assertThat(result.wasSuccessful()).isTrue(); + } + + private static Result runTestCase(String testCaseName) { return GuidedFuzzing.run( - TestCases.class, roundTripRandomValues, new NoGuidance(10000, System.out), System.out); + TestCases.class, testCaseName, new NoGuidance(10000, System.out), System.out); } public static class AsciiGenerator extends AbstractStringGenerator { @@ -97,6 +117,28 @@ protected boolean codePointInRange(int codePoint) { } } + public static class MetadataGenerator extends AbstractStringGenerator { + + @Override + protected int nextCodePoint(SourceOfRandomness random) { + while (true) { + char c = random.nextChar(' ', '~'); + if (c != '"' && c != ',' && c != '\\') { + return c; + } + } + } + + @Override + protected boolean codePointInRange(int codePoint) { + return codePoint >= ' ' + && codePoint <= '~' + && codePoint != '"' + && codePoint != ',' + && codePoint != '\\'; + } + } + private static class MapTextMapGetter implements TextMapGetter> { @Override public Iterable keys(Map carrier) { @@ -109,4 +151,25 @@ public String get(Map carrier, String key) { return carrier.get(key); } } + + public static class BaggageOctetGenerator extends AbstractStringGenerator { + + private static final Set excluded = + new HashSet<>(Arrays.asList(' ', '"', ',', ';', '\\', '%')); + + @Override + protected int nextCodePoint(SourceOfRandomness random) { + while (true) { + char c = random.nextChar(' ', '~'); + if (!excluded.contains(c)) { + return c; + } + } + } + + @Override + protected boolean codePointInRange(int codePoint) { + return !excluded.contains((char) codePoint); + } + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorTest.java b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorTest.java index 44ba8ecd7bf..cecb94006ba 100644 --- a/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/baggage/propagation/W3CBaggagePropagatorTest.java @@ -8,17 +8,27 @@ import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.baggage.BaggageBuilder; import io.opentelemetry.api.baggage.BaggageEntryMetadata; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; +import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class W3CBaggagePropagatorTest { @@ -36,6 +46,28 @@ public String get(Map carrier, String key) { } }; + private static final TextMapGetter>> multiGetter = + new TextMapGetter>>() { + @Override + public Iterable keys(Map> carrier) { + return carrier.keySet(); + } + + @Nullable + @Override + public String get(Map> carrier, String key) { + return carrier.getOrDefault(key, Collections.emptyList()).stream() + .findFirst() + .orElse(null); + } + + @Override + public Iterator getAll(Map> carrier, String key) { + List values = carrier.get(key); + return values == null ? Collections.emptyIterator() : values.iterator(); + } + }; + @Test void fields() { assertThat(W3CBaggagePropagator.getInstance().fields()).containsExactly("baggage"); @@ -177,7 +209,8 @@ void extract_value_empty() { Context result = propagator.extract(Context.root(), ImmutableMap.of("baggage", "key1="), getter); - assertThat(Baggage.fromContext(result)).isEqualTo(Baggage.empty()); + Baggage expectedBaggage = Baggage.builder().put("key1", "").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); } @Test @@ -188,7 +221,9 @@ void extract_value_empty_withMetadata() { propagator.extract( Context.root(), ImmutableMap.of("baggage", "key1=;metakey=metaval"), getter); - assertThat(Baggage.fromContext(result)).isEqualTo(Baggage.empty()); + Baggage expectedBaggage = + Baggage.builder().put("key1", "", BaggageEntryMetadata.create("metakey=metaval")).build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); } @Test @@ -198,7 +233,8 @@ void extract_value_onlySpaces() { Context result = propagator.extract(Context.root(), ImmutableMap.of("baggage", "key1= "), getter); - assertThat(Baggage.fromContext(result)).isEqualTo(Baggage.empty()); + Baggage expectedBaggage = Baggage.builder().put("key1", "").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); } @Test @@ -408,6 +444,53 @@ void extract_member_someInvalid() { assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); } + @ParameterizedTest + @MethodSource + @SuppressLogger(Parser.class) + void extract_member_invalidPercentEncoding_preservesValidMembers( + String header, Baggage expectedBaggage) { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = propagator.extract(Context.root(), ImmutableMap.of("baggage", header), getter); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + static Stream extract_member_invalidPercentEncoding_preservesValidMembers() { + return Stream.of( + Arguments.argumentSet( + "invalid entry at beginning", + "bad=va%lue,key1=value1,encoded=value%202", + Baggage.builder().put("key1", "value1").put("encoded", "value 2").build()), + Arguments.argumentSet( + "invalid entry in middle", + "key1=value1,bad=va%lue,encoded=value%202,key2=value2", + Baggage.builder() + .put("key1", "value1") + .put("encoded", "value 2") + .put("key2", "value2") + .build()), + Arguments.argumentSet( + "invalid entry at end", + "key1=value1,encoded=value%202,bad=va%lue", + Baggage.builder().put("key1", "value1").put("encoded", "value 2").build()), + Arguments.argumentSet( + "multiple invalid entries", + "bad1=va%lue,key1=value1,bad2=value%GG,encoded=value%202,bad3=value;meta=%GG", + Baggage.builder() + .put("key1", "value1") + .put("encoded", "value 2") + .put("bad3", "value", BaggageEntryMetadata.create("meta=%GG")) + .build()), + Arguments.argumentSet( + "invalid metadata charset drops entry", + "key1=value1,bad=value;meta\u0001evil,key2=value2", + Baggage.builder().put("key1", "value1").put("key2", "value2").build()), + Arguments.argumentSet( + "invalid metadata charset at end drops entry", + "key1=value1,bad=value;meta\u0001evil", + Baggage.builder().put("key1", "value1").build())); + } + @Test void extract_nullContext() { assertThat(W3CBaggagePropagator.getInstance().extract(null, Collections.emptyMap(), getter)) @@ -421,6 +504,103 @@ void extract_nullGetter() { .isSameAs(context); } + @Test + void extract_multiple_headers() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", ImmutableList.of("k1=v1", "k2=v2")), + multiGetter); + + Baggage expectedBaggage = Baggage.builder().put("k1", "v1").put("k2", "v2").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + @Test + void extract_multiple_headers_duplicate_key() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", ImmutableList.of("k1=v1", "k1=v2")), + multiGetter); + + Baggage expectedBaggage = Baggage.builder().put("k1", "v2").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + @Test + void extract_multiple_headers_mixed_duplicates_non_duplicates() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", ImmutableList.of("k1=v1,k2=v0", "k2=v2,k3=v3")), + multiGetter); + + Baggage expectedBaggage = + Baggage.builder().put("k1", "v1").put("k2", "v2").put("k3", "v3").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + @Test + void extract_multiple_headers_all_empty() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), ImmutableMap.of("baggage", ImmutableList.of("", "")), multiGetter); + + Baggage expectedBaggage = Baggage.builder().build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + @Test + void extract_multiple_headers_some_empty() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), ImmutableMap.of("baggage", ImmutableList.of("", "k=v")), multiGetter); + + Baggage expectedBaggage = Baggage.builder().put("k", "v").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + @Test + @SuppressLogger(Parser.class) + void extract_multiple_headers_all_invalid() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", ImmutableList.of("!@#$%^", "key=va%lue")), + multiGetter); + + Baggage expectedBaggage = Baggage.builder().build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + @Test + @SuppressLogger(Parser.class) + void extract_multiple_headers_some_invalid() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", ImmutableList.of("k1=v1", "key=va%lue", "k2=v2")), + multiGetter); + + Baggage expectedBaggage = Baggage.builder().put("k1", "v1").put("k2", "v2").build(); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + @Test void inject_noBaggage() { W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); @@ -439,6 +619,7 @@ void inject_emptyBaggage() { } @Test + @SuppressLogger(W3CBaggagePropagator.class) void inject() { Baggage baggage = Baggage.builder() @@ -448,6 +629,7 @@ void inject() { .put("\2ab\3cd", "wacky key nonprintable") .put(null, "null key") .put("nullvalue", null) + .put(" ", "key is only space") .build(); W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); Map carrier = new HashMap<>(); @@ -456,7 +638,90 @@ void inject() { .containsExactlyInAnyOrderEntriesOf( singletonMap( "baggage", - "meta=meta-value;somemetadata%3B%20someother%3Dfoo,needsEncoding=blah%20blah%20blah,nometa=nometa-value")); + "meta=meta-value;somemetadata; someother=foo,needsEncoding=blah%20blah%20blah,nometa=nometa-value")); + } + + @Test + void inject_doesNotPercentEncodeMetadata() { + Baggage baggage = + Baggage.builder() + .put("SomeKey", "SomeValue", BaggageEntryMetadata.create("ValueProp \t = \t PropVal")) + .build(); + Map carrier = new HashMap<>(); + W3CBaggagePropagator.getInstance().inject(Context.root().with(baggage), carrier, Map::put); + assertThat(carrier) + .containsExactlyInAnyOrderEntriesOf( + singletonMap("baggage", "SomeKey=SomeValue;ValueProp \t = \t PropVal")); + } + + @ParameterizedTest + @MethodSource + @SuppressLogger(W3CBaggagePropagator.class) + void inject_invalidMetadata_skipsEntry(String metadata) { + Baggage baggage = + Baggage.builder() + .put("keep", "yes") + .put("drop", "no", BaggageEntryMetadata.create(metadata)) + .build(); + Map carrier = new HashMap<>(); + W3CBaggagePropagator.getInstance().inject(Context.root().with(baggage), carrier, Map::put); + assertThat(carrier).containsExactlyInAnyOrderEntriesOf(singletonMap("baggage", "keep=yes")); + } + + static Stream inject_invalidMetadata_skipsEntry() { + return Stream.of( + Arguments.argumentSet("comma", "a,b"), + Arguments.argumentSet("dquote", "a\"b"), + Arguments.argumentSet("backslash", "a\\b"), + Arguments.argumentSet("cr", "a\rb"), + Arguments.argumentSet("lf", "a\nb"), + Arguments.argumentSet("nul", "a\0b"), + Arguments.argumentSet("del", "a\u007fb"), + Arguments.argumentSet("non-ascii", "cafΓ©"), + Arguments.argumentSet("obs-text", "a\u0080b")); + } + + @Test + @SuppressLogger(W3CBaggagePropagator.class) + void inject_invalidMetadataOnly_omitsHeader() { + Baggage baggage = Baggage.builder().put("k", "v", BaggageEntryMetadata.create("a,b")).build(); + Map carrier = new HashMap<>(); + W3CBaggagePropagator.getInstance().inject(Context.root().with(baggage), carrier, Map::put); + assertThat(carrier).isEmpty(); + } + + @Test + void extract_metadataNotPercentDecoded() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", "SomeKey=SomeValue;ValueProp%20%09%20%3D%20%09%20PropVal"), + getter); + + assertThat(Baggage.fromContext(result)) + .isEqualTo( + Baggage.builder() + .put( + "SomeKey", + "SomeValue", + BaggageEntryMetadata.create("ValueProp%20%09%20%3D%20%09%20PropVal")) + .build()); + } + + @Test + void roundTrip_metadataPreservedOpaque() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + Baggage baggage = + Baggage.builder() + .put("SomeKey", "SomeValue", BaggageEntryMetadata.create("ValueProp \t = \t PropVal")) + .build(); + Map carrier = new HashMap<>(); + propagator.inject(baggage.storeInContext(Context.root()), carrier, Map::put); + assertThat(carrier.get("baggage")).isEqualTo("SomeKey=SomeValue;ValueProp \t = \t PropVal"); + + Baggage extracted = Baggage.fromContext(propagator.extract(Context.root(), carrier, getter)); + assertThat(extracted).isEqualTo(baggage); } @Test @@ -473,4 +738,121 @@ void inject_nullSetter() { W3CBaggagePropagator.getInstance().inject(context, carrier, null); assertThat(carrier).isEmpty(); } + + @ParameterizedTest + @MethodSource + void extract_limit_maxEntries(List headers, Baggage expectedBaggage) { + Context result = + W3CBaggagePropagator.getInstance() + .extract(Context.root(), ImmutableMap.of("baggage", headers), multiGetter); + assertThat(Baggage.fromContext(result)).isEqualTo(expectedBaggage); + } + + static Stream extract_limit_maxEntries() { + return Stream.of( + Arguments.argumentSet( + "exactly at limit, all 64 extracted", + ImmutableList.of(baggageHeader(0, 64)), + baggageWithEntries(0, 64)), + Arguments.argumentSet( + "one over limit, only first 64 extracted", + ImmutableList.of(baggageHeader(0, 65)), + baggageWithEntries(0, 64)), + Arguments.argumentSet( + "split across two headers, first 64 total extracted", + ImmutableList.of(baggageHeader(0, 32), baggageHeader(32, 33)), + baggageWithEntries(0, 64))); + } + + /** + * Builds a {@link Baggage} with entries {@code k{start}=v{start}} through {@code + * k{start+count-1}=v{start+count-1}}. + */ + private static Baggage baggageWithEntries(int start, int count) { + BaggageBuilder builder = Baggage.builder(); + for (int i = start; i < start + count; i++) { + builder.put("k" + i, "v" + i); + } + return builder.build(); + } + + /** Builds {@code "k{start}=v{start},...,k{start+count-1}=v{start+count-1}"}. */ + private static String baggageHeader(int start, int count) { + StringBuilder sb = new StringBuilder(); + for (int i = start; i < start + count; i++) { + if (i > start) { + sb.append(","); + } + sb.append("k").append(i).append("=v").append(i); + } + return sb.toString(); + } + + @Test + void extract_limit_maxBytes_exceedsLimit() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + // Single header over 8192 bytes β€” dropped entirely; partial values must not be extracted + String header = "k=" + fillChars('v', 8192); // 8194 bytes + Context result = propagator.extract(Context.root(), ImmutableMap.of("baggage", header), getter); + assertThat(Baggage.fromContext(result)).isEqualTo(Baggage.empty()); + } + + @Test + void extract_limit_maxBytes_acrossMultipleHeaders() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + // First header just under 8192 bytes is extracted; second header pushes total over the limit + String almostMax = "k=" + fillChars('v', 8189); // "k=vvv..." + String second = "k2=v2"; + Context result = + propagator.extract( + Context.root(), + ImmutableMap.of("baggage", ImmutableList.of(almostMax, second)), + multiGetter); + // Only the first header should have been extracted + assertThat(Baggage.fromContext(result).size()).isEqualTo(1); + assertThat(Baggage.fromContext(result).getEntryValue("k2")).isNull(); + } + + @Test + void inject_limit_maxEntries() { + Map carrier = new HashMap<>(); + W3CBaggagePropagator.getInstance() + .inject(Context.root().with(baggageWithEntries(0, 74)), carrier, Map::put); + String header = carrier.get("baggage"); + assertThat(header).isNotNull(); + long count = header.chars().filter(c -> c == '=').count(); + assertThat(count).isEqualTo(64); + } + + @Test + void inject_limit_maxBytes() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + // One entry whose encoded form alone exceeds the byte limit β€” should produce empty header + Baggage baggage = Baggage.builder().put("k", fillChars('v', 8192)).build(); + Map carrier = new HashMap<>(); + propagator.inject(Context.root().with(baggage), carrier, Map::put); + assertThat(carrier).doesNotContainKey("baggage"); + } + + @Test + void inject_limit_maxBytes_metadata() { + // Value alone fits easily (k=v is 3 bytes), but k=v;{metadata} exceeds 8192 bytes. + // Verifies that metadata length is included in the byte limit check. + Baggage baggage = + Baggage.builder().put("k", "v", BaggageEntryMetadata.create(fillChars('x', 8190))).build(); + Map carrier = new HashMap<>(); + W3CBaggagePropagator.getInstance().inject(Context.root().with(baggage), carrier, Map::put); + assertThat(carrier).doesNotContainKey("baggage"); + } + + private static String fillChars(char c, int count) { + char[] chars = new char[count]; + Arrays.fill(chars, c); + return new String(chars); + } + + @Test + void toString_Valid() { + assertThat(W3CBaggagePropagator.getInstance().toString()).isEqualTo("W3CBaggagePropagator"); + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/common/AttributesTest.java b/api/all/src/test/java/io/opentelemetry/api/common/AttributesTest.java index 6726b539713..d44eac6da8a 100644 --- a/api/all/src/test/java/io/opentelemetry/api/common/AttributesTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/common/AttributesTest.java @@ -13,6 +13,7 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; @@ -26,6 +27,7 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Nullable; import org.junit.jupiter.api.Test; /** Unit tests for {@link Attributes}s. */ @@ -105,8 +107,8 @@ void asMap() { .isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(map::clear).isInstanceOf(UnsupportedOperationException.class); - assertThat(map.keySet().contains(stringKey("key1"))).isTrue(); - assertThat(map.keySet().contains(stringKey("key3"))).isFalse(); + assertThat(map.containsKey(stringKey("key1"))).isTrue(); + assertThat(map.containsKey(stringKey("key3"))).isFalse(); assertThat(map.keySet().containsAll(Arrays.asList(stringKey("key1"), longKey("key2")))) .isTrue(); assertThat(map.keySet().containsAll(Arrays.asList(stringKey("key1"), longKey("key3")))) @@ -125,7 +127,7 @@ void asMap() { assertThat(keys).isEmpty(); // Didn't use input array. assertThatThrownBy(() -> map.keySet().iterator().remove()) .isInstanceOf(UnsupportedOperationException.class); - assertThat(map.keySet().containsAll(singletonList(stringKey("key1")))).isTrue(); + assertThat(map.containsKey(stringKey("key1"))).isTrue(); assertThat(map.keySet().containsAll(Arrays.asList(stringKey("key1"), stringKey("key3")))) .isFalse(); assertThat(map.keySet().isEmpty()).isFalse(); @@ -133,7 +135,7 @@ void asMap() { .isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> map.keySet().remove(stringKey("key1"))) .isInstanceOf(UnsupportedOperationException.class); - assertThatThrownBy(() -> map.keySet().addAll(Collections.singletonList(stringKey("key3")))) + assertThatThrownBy(() -> map.keySet().add(stringKey("key3"))) .isInstanceOf(UnsupportedOperationException.class); assertThatThrownBy(() -> map.keySet().retainAll(Collections.singletonList(stringKey("key3")))) .isInstanceOf(UnsupportedOperationException.class); @@ -142,8 +144,8 @@ void asMap() { assertThatThrownBy(() -> map.keySet().clear()) .isInstanceOf(UnsupportedOperationException.class); - assertThat(map.values().contains("value1")).isTrue(); - assertThat(map.values().contains("value3")).isFalse(); + assertThat(map.containsValue("value1")).isTrue(); + assertThat(map.containsValue("value3")).isFalse(); assertThat(map.toString()).isEqualTo("ReadOnlyArrayMap{key1=value1,key2=333}"); @@ -297,7 +299,7 @@ void builderWithAttributeKeyList() { .put(longKey("long"), 10) .put(stringArrayKey("anotherString"), "value1", "value2", "value3") .put(longArrayKey("anotherLong"), 10L, 20L, 30L) - .put(booleanArrayKey("anotherBoolean"), true, false, true) + .put(valueKey("value"), Value.of(new byte[] {1, 2, 3})) .build(); Attributes wantAttributes = @@ -310,8 +312,8 @@ void builderWithAttributeKeyList() { Arrays.asList("value1", "value2", "value3"), longArrayKey("anotherLong"), Arrays.asList(10L, 20L, 30L), - booleanArrayKey("anotherBoolean"), - Arrays.asList(true, false, true)); + valueKey("value"), + Value.of(new byte[] {1, 2, 3})); assertThat(attributes).isEqualTo(wantAttributes); AttributesBuilder newAttributes = attributes.toBuilder(); @@ -327,8 +329,8 @@ void builderWithAttributeKeyList() { Arrays.asList("value1", "value2", "value3"), longArrayKey("anotherLong"), Arrays.asList(10L, 20L, 30L), - booleanArrayKey("anotherBoolean"), - Arrays.asList(true, false, true), + valueKey("value"), + Value.of(new byte[] {1, 2, 3}), stringKey("newKey"), "newValue")); // Original not mutated. @@ -356,6 +358,352 @@ void builder_arrayTypes() { booleanArrayKey("boolean"), Arrays.asList(false, true))); } + @Test + void valueStoredAsString() { + // When putting a VALUE attribute with a string Value, it should be stored as STRING type + Attributes attributes = Attributes.builder().put(valueKey("key"), Value.of("test")).build(); + + // Should be stored as STRING type internally + assertThat(attributes.get(stringKey("key"))).isEqualTo("test"); + assertThat(attributes.get(valueKey("key"))).isEqualTo(Value.of("test")); + + // forEach should show STRING type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(stringKey("key"), "test")); + + // asMap should show STRING type + assertThat(attributes.asMap()).containsExactly(entry(stringKey("key"), "test")); + } + + @Test + void valueStoredAsLong() { + // When putting a VALUE attribute with a long Value, it should be stored as LONG type + Attributes attributes = Attributes.builder().put(valueKey("key"), Value.of(123L)).build(); + + // Should be stored as LONG type internally + assertThat(attributes.get(longKey("key"))).isEqualTo(123L); + assertThat(attributes.get(valueKey("key"))).isEqualTo(Value.of(123L)); + + // forEach should show LONG type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(longKey("key"), 123L)); + + // asMap should show LONG type + assertThat(attributes.asMap()).containsExactly(entry(longKey("key"), 123L)); + } + + @Test + void valueStoredAsDouble() { + // When putting a VALUE attribute with a double Value, it should be stored as DOUBLE type + Attributes attributes = Attributes.builder().put(valueKey("key"), Value.of(1.23)).build(); + + // Should be stored as DOUBLE type internally + assertThat(attributes.get(doubleKey("key"))).isEqualTo(1.23); + assertThat(attributes.get(valueKey("key"))).isEqualTo(Value.of(1.23)); + + // forEach should show DOUBLE type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(doubleKey("key"), 1.23)); + + // asMap should show DOUBLE type + assertThat(attributes.asMap()).containsExactly(entry(doubleKey("key"), 1.23)); + } + + @Test + void valueStoredAsBoolean() { + // When putting a VALUE attribute with a boolean Value, it should be stored as BOOLEAN type + Attributes attributes = Attributes.builder().put(valueKey("key"), Value.of(true)).build(); + + // Should be stored as BOOLEAN type internally + assertThat(attributes.get(booleanKey("key"))).isEqualTo(true); + assertThat(attributes.get(valueKey("key"))).isEqualTo(Value.of(true)); + + // forEach should show BOOLEAN type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(booleanKey("key"), true)); + + // asMap should show BOOLEAN type + assertThat(attributes.asMap()).containsExactly(entry(booleanKey("key"), true)); + } + + @Test + void valueStoredAsStringArray() { + // When putting a VALUE attribute with a homogeneous string array, it should be stored as + // STRING_ARRAY type + Attributes attributes = + Attributes.builder() + .put(valueKey("key"), Value.of(Arrays.asList(Value.of("a"), Value.of("b")))) + .build(); + + // Should be stored as STRING_ARRAY type internally + assertThat(attributes.get(stringArrayKey("key"))).containsExactly("a", "b"); + assertThat(attributes.get(valueKey("key"))) + .isEqualTo(Value.of(Arrays.asList(Value.of("a"), Value.of("b")))); + + // forEach should show STRING_ARRAY type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(stringArrayKey("key"), Arrays.asList("a", "b"))); + + // asMap should show STRING_ARRAY type + assertThat(attributes.asMap()) + .containsExactly(entry(stringArrayKey("key"), Arrays.asList("a", "b"))); + } + + @Test + void valueStoredAsLongArray() { + // When putting a VALUE attribute with a homogeneous long array, it should be stored as + // LONG_ARRAY type + Attributes attributes = + Attributes.builder() + .put(valueKey("key"), Value.of(Arrays.asList(Value.of(1L), Value.of(2L)))) + .build(); + + // Should be stored as LONG_ARRAY type internally + assertThat(attributes.get(longArrayKey("key"))).containsExactly(1L, 2L); + assertThat(attributes.get(valueKey("key"))) + .isEqualTo(Value.of(Arrays.asList(Value.of(1L), Value.of(2L)))); + + // forEach should show LONG_ARRAY type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(longArrayKey("key"), Arrays.asList(1L, 2L))); + + // asMap should show LONG_ARRAY type + assertThat(attributes.asMap()) + .containsExactly(entry(longArrayKey("key"), Arrays.asList(1L, 2L))); + } + + @Test + void valueStoredAsDoubleArray() { + // When putting a VALUE attribute with a homogeneous double array, it should be stored as + // DOUBLE_ARRAY type + Attributes attributes = + Attributes.builder() + .put(valueKey("key"), Value.of(Arrays.asList(Value.of(1.1), Value.of(2.2)))) + .build(); + + // Should be stored as DOUBLE_ARRAY type internally + assertThat(attributes.get(doubleArrayKey("key"))).containsExactly(1.1, 2.2); + assertThat(attributes.get(valueKey("key"))) + .isEqualTo(Value.of(Arrays.asList(Value.of(1.1), Value.of(2.2)))); + + // forEach should show DOUBLE_ARRAY type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(doubleArrayKey("key"), Arrays.asList(1.1, 2.2))); + + // asMap should show DOUBLE_ARRAY type + assertThat(attributes.asMap()) + .containsExactly(entry(doubleArrayKey("key"), Arrays.asList(1.1, 2.2))); + } + + @Test + void valueStoredAsBooleanArray() { + // When putting a VALUE attribute with a homogeneous boolean array, it should be stored as + // BOOLEAN_ARRAY type + Attributes attributes = + Attributes.builder() + .put(valueKey("key"), Value.of(Arrays.asList(Value.of(true), Value.of(false)))) + .build(); + + // Should be stored as BOOLEAN_ARRAY type internally + assertThat(attributes.get(booleanArrayKey("key"))).containsExactly(true, false); + assertThat(attributes.get(valueKey("key"))) + .isEqualTo(Value.of(Arrays.asList(Value.of(true), Value.of(false)))); + + // forEach should show BOOLEAN_ARRAY type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen) + .containsExactly(entry(booleanArrayKey("key"), Arrays.asList(true, false))); + + // asMap should show BOOLEAN_ARRAY type + assertThat(attributes.asMap()) + .containsExactly(entry(booleanArrayKey("key"), Arrays.asList(true, false))); + } + + @Test + void complexValueWithKeyValueList() { + // KEY_VALUE_LIST should be kept as VALUE type + Value kvListValue = Value.of(Collections.emptyMap()); + Attributes attributes = Attributes.builder().put(valueKey("key"), kvListValue).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(kvListValue); + + // forEach should show VALUE type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), kvListValue)); + } + + @Test + void complexValueWithBytes() { + // BYTES should be kept as VALUE type + Value bytesValue = Value.of(new byte[] {1, 2, 3}); + Attributes attributes = Attributes.builder().put(valueKey("key"), bytesValue).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(bytesValue); + + // forEach should show VALUE type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), bytesValue)); + } + + @Test + void complexValueWithNonHomogeneousArray() { + // Non-homogeneous array should be kept as VALUE type + Value mixedArray = Value.of(Arrays.asList(Value.of("string"), Value.of(123L))); + Attributes attributes = Attributes.builder().put(valueKey("key"), mixedArray).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(mixedArray); + + // forEach should show VALUE type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), mixedArray)); + } + + @Test + void complexValueWithNestedArray() { + // Array containing arrays should be kept as VALUE type + Value nestedArray = + Value.of( + Arrays.asList( + Value.of(Arrays.asList(Value.of("a"), Value.of("b"))), + Value.of(Arrays.asList(Value.of("c"), Value.of("d"))))); + Attributes attributes = Attributes.builder().put(valueKey("key"), nestedArray).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(nestedArray); + + // forEach should show VALUE type + Map, Object> entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), nestedArray)); + } + + @Test + void getNonExistentArrayType() { + // Test the code path where we look for an array type that doesn't exist + Attributes attributes = Attributes.builder().put("key", "value").build(); + + // Looking for an array type when only a string exists should return null + assertThat(attributes.get(stringArrayKey("key"))).isNull(); + assertThat(attributes.get(longArrayKey("key"))).isNull(); + assertThat(attributes.get(doubleArrayKey("key"))).isNull(); + assertThat(attributes.get(booleanArrayKey("key"))).isNull(); + } + + @Test + void simpleAttributeRetrievedAsValue() { + Attributes attributes = + Attributes.builder() + .put("string", "test") + .put("long", 123L) + .put("double", 1.23) + .put("boolean", true) + .put("stringArray", "a", "b") + .put("longArray", 1L, 2L) + .put("doubleArray", 1.1, 2.2) + .put("booleanArray", true, false) + .build(); + assertThat(attributes.get(valueKey("string"))).isEqualTo(Value.of("test")); + assertThat(attributes.get(valueKey("long"))).isEqualTo(Value.of(123L)); + assertThat(attributes.get(valueKey("double"))).isEqualTo(Value.of(1.23)); + assertThat(attributes.get(valueKey("boolean"))).isEqualTo(Value.of(true)); + assertThat(attributes.get(valueKey("stringArray"))) + .isEqualTo(Value.of(Arrays.asList(Value.of("a"), Value.of("b")))); + assertThat(attributes.get(valueKey("longArray"))) + .isEqualTo(Value.of(Arrays.asList(Value.of(1L), Value.of(2L)))); + assertThat(attributes.get(valueKey("doubleArray"))) + .isEqualTo(Value.of(Arrays.asList(Value.of(1.1), Value.of(2.2)))); + assertThat(attributes.get(valueKey("booleanArray"))) + .isEqualTo(Value.of(Arrays.asList(Value.of(true), Value.of(false)))); + } + + @Test + void emptyValueArrayRetrievedAsAnyArrayType() { + Attributes attributes = + Attributes.builder().put(valueKey("key"), Value.of(Collections.emptyList())).build(); + assertThat(attributes.get(stringArrayKey("key"))).isEmpty(); + assertThat(attributes.get(longArrayKey("key"))).isEmpty(); + assertThat(attributes.get(doubleArrayKey("key"))).isEmpty(); + assertThat(attributes.get(booleanArrayKey("key"))).isEmpty(); + } + + @Test + void valueWithKeyValueList() { + // KEY_VALUE_LIST should be kept as VALUE type + Value kvListValue = Value.of(Collections.emptyMap()); + Attributes attributes = Attributes.builder().put(valueKey("key"), kvListValue).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(kvListValue); + + // forEach should show VALUE type + Map entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), kvListValue)); + } + + @Test + void valueWithBytes() { + // BYTES should be kept as VALUE type + Value bytesValue = Value.of(new byte[] {1, 2, 3}); + Attributes attributes = Attributes.builder().put(valueKey("key"), bytesValue).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(bytesValue); + + // forEach should show VALUE type + Map entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), bytesValue)); + } + + @Test + void valueWithNonHomogeneousArray() { + // Non-homogeneous array should be kept as VALUE type + Value mixedArray = Value.of(Arrays.asList(Value.of("string"), Value.of(123L))); + Attributes attributes = Attributes.builder().put(valueKey("key"), mixedArray).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(mixedArray); + + // forEach should show VALUE type + Map entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), mixedArray)); + } + + @Test + void valueWithNestedArray() { + // Array containing arrays should be kept as VALUE type + Value nestedArray = + Value.of( + Arrays.asList( + Value.of(Arrays.asList(Value.of("a"), Value.of("b"))), + Value.of(Arrays.asList(Value.of("c"), Value.of("d"))))); + Attributes attributes = Attributes.builder().put(valueKey("key"), nestedArray).build(); + + // Should be stored as VALUE type + assertThat(attributes.get(valueKey("key"))).isEqualTo(nestedArray); + + // forEach should show VALUE type + Map entriesSeen = new HashMap<>(); + attributes.forEach(entriesSeen::put); + assertThat(entriesSeen).containsExactly(entry(valueKey("key"), nestedArray)); + } + @Test @SuppressWarnings("unchecked") void get_Null() { @@ -378,7 +726,7 @@ void get() { Attributes.of(stringKey("string"), "value", booleanKey("boolean"), true); assertThat(twoElements.get(booleanKey("boolean"))).isEqualTo(true); assertThat(twoElements.get(stringKey("string"))).isEqualTo("value"); - Attributes fourElements = + Attributes fiveElements = Attributes.of( stringKey("string"), "value", @@ -387,12 +735,16 @@ void get() { longKey("long"), 1L, stringArrayKey("array"), - Arrays.asList("one", "two", "three")); - assertThat(fourElements.get(stringArrayKey("array"))) + Arrays.asList("one", "two", "three"), + valueKey("value"), + Value.of(new byte[] {1, 2, 3})); + assertThat(fiveElements.get(stringArrayKey("array"))) .isEqualTo(Arrays.asList("one", "two", "three")); - assertThat(threeElements.get(booleanKey("boolean"))).isEqualTo(true); - assertThat(threeElements.get(stringKey("string"))).isEqualTo("value"); - assertThat(threeElements.get(longKey("long"))).isEqualTo(1L); + assertThat(fiveElements.get(booleanKey("boolean"))).isEqualTo(true); + assertThat(fiveElements.get(stringKey("string"))).isEqualTo("value"); + assertThat(fiveElements.get(longKey("long"))).isEqualTo(1L); + assertThat(fiveElements.get(valueKey("value"))).isEqualTo(Value.of(new byte[] {1, 2, 3})); + assertThat(fiveElements.get(valueKey("value")).getType()).isEqualTo(ValueType.BYTES); } @Test @@ -420,28 +772,34 @@ void nullsAreNoOps() { builder.put("long", 10); builder.put("double", 1.0); builder.put("bool", true); - builder.put("arrayString", new String[] {"string"}); - builder.put("arrayLong", new long[] {10L}); - builder.put("arrayDouble", new double[] {1.0}); - builder.put("arrayBool", new boolean[] {true}); - assertThat(builder.build().size()).isEqualTo(9); - - // note: currently these are no-op calls; that behavior is not required, so if it needs to - // change, that is fine. + String[] strings = {"string"}; + builder.put("arrayString", strings); + long[] longs = {10L}; + builder.put("arrayLong", longs); + double[] doubles = {1.0}; + builder.put("arrayDouble", doubles); + boolean[] booleans = {true}; + builder.put("arrayBool", booleans); + Value value = Value.of(new byte[] {1, 2, 3}); + builder.put(valueKey("value"), value); + assertThat(builder.build().size()).isEqualTo(10); + builder.put(stringKey("attrValue"), null); builder.put("string", (String) null); builder.put("arrayString", (String[]) null); builder.put("arrayLong", (long[]) null); builder.put("arrayDouble", (double[]) null); builder.put("arrayBool", (boolean[]) null); + builder.put(valueKey("value"), null); Attributes attributes = builder.build(); - assertThat(attributes.size()).isEqualTo(9); + assertThat(attributes.size()).isEqualTo(10); assertThat(attributes.get(stringKey("string"))).isEqualTo("string"); assertThat(attributes.get(stringArrayKey("arrayString"))).isEqualTo(singletonList("string")); assertThat(attributes.get(longArrayKey("arrayLong"))).isEqualTo(singletonList(10L)); assertThat(attributes.get(doubleArrayKey("arrayDouble"))).isEqualTo(singletonList(1.0d)); assertThat(attributes.get(booleanArrayKey("arrayBool"))).isEqualTo(singletonList(true)); + assertThat(attributes.get(valueKey("value"))).isEqualTo(Value.of(new byte[] {1, 2, 3})); } @Test @@ -565,7 +923,7 @@ public AttributesBuilder put(AttributeKey key, int value) { } @Override - public AttributesBuilder put(AttributeKey key, T value) { + public AttributesBuilder put(AttributeKey key, @Nullable T value) { return null; } @@ -578,4 +936,50 @@ public AttributesBuilder putAll(Attributes attributes) { assertThatCode(() -> myAttributesBuilder.remove(stringKey("foo"))).doesNotThrowAnyException(); assertThatCode(() -> myAttributesBuilder.removeIf(unused -> false)).doesNotThrowAnyException(); } + + @Test + void emptyValueIsValid() { + AttributeKey key = stringKey("anything"); + Attributes attributes = Attributes.of(key, ""); + assertThat(attributes.get(key)).isEqualTo(""); + } + + @Test + void getValueAttribute_KeyNameMatching() { + // Test the getValueAttribute method's key name matching logic + Attributes attributes = + Attributes.builder() + .put(valueKey("key1"), Value.of(new byte[] {1, 2, 3})) + .put("key2", "value2") + .put(valueKey("key3"), Value.of(Collections.emptyMap())) + .build(); + + // When looking for array type with key1, should not find it (it's VALUE with BYTES) + assertThat(attributes.get(stringArrayKey("key1"))).isNull(); + + // When looking for array type with key2, should not find it (it's STRING, not VALUE) + assertThat(attributes.get(longArrayKey("key2"))).isNull(); + + // Verify VALUE types can be retrieved + assertThat(attributes.get(valueKey("key1"))).isEqualTo(Value.of(new byte[] {1, 2, 3})); + assertThat(attributes.get(valueKey("key3"))).isEqualTo(Value.of(Collections.emptyMap())); + } + + @Test + void emptyArrayValueNotStoredAsTypedArray() { + // When empty array is stored as VALUE, it should not be found when looking for + // the VALUE attribute with non-empty array + Attributes attributes = + Attributes.builder().put(valueKey("empty"), Value.of(Collections.emptyList())).build(); + + // Should return empty list for typed array lookups (testing isEmptyArray branch) + assertThat(attributes.get(stringArrayKey("empty"))).isEmpty(); + assertThat(attributes.get(longArrayKey("empty"))).isEmpty(); + + // Non-array VALUE types should not trigger the empty array logic + Attributes nonArrayAttrs = + Attributes.builder().put(valueKey("bytes"), Value.of(new byte[] {1, 2})).build(); + assertThat(nonArrayAttrs.get(stringArrayKey("bytes"))).isNull(); + assertThat(nonArrayAttrs.get(longArrayKey("bytes"))).isNull(); + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/common/ValueAsStringTest.java b/api/all/src/test/java/io/opentelemetry/api/common/ValueAsStringTest.java new file mode 100644 index 00000000000..996333edbd5 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/common/ValueAsStringTest.java @@ -0,0 +1,274 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.common; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ValueAsStringTest { + + @ParameterizedTest + @MethodSource("stringValueProvider") + void valueString(String input, String expectedJson) { + assertThat(Value.of(input).asString()).isEqualTo(expectedJson); + } + + private static Stream stringValueProvider() { + return Stream.of( + Arguments.argumentSet("hello", "hello", "hello"), + Arguments.argumentSet("empty string", "", ""), + Arguments.argumentSet("newline and tab", "line1\nline2\ttab", "line1\nline2\ttab"), + Arguments.argumentSet("double quotes", "say \"hello\"", "say \"hello\""), + Arguments.argumentSet("backslash path", "path\\to\\file", "path\\to\\file"), + Arguments.argumentSet("control chars", "\u0000\u0001\u001F", "\u0000\u0001\u001F"), + Arguments.argumentSet("unicode", "Hello δΈ–η•Œ 🌍", "Hello δΈ–η•Œ 🌍")); + } + + @ParameterizedTest + @MethodSource("booleanValueProvider") + void valueBoolean(boolean input, String expectedJson) { + assertThat(Value.of(input).asString()).isEqualTo(expectedJson); + } + + private static Stream booleanValueProvider() { + return Stream.of( + Arguments.argumentSet("true", true, "true"), + Arguments.argumentSet("false", false, "false")); + } + + @ParameterizedTest + @MethodSource("longValueProvider") + void valueLong(long input, String expectedJson) { + assertThat(Value.of(input).asString()).isEqualTo(expectedJson); + } + + private static Stream longValueProvider() { + return Stream.of( + Arguments.argumentSet("Positive value", 42L, "42"), + Arguments.argumentSet("Negative value", -123L, "-123"), + Arguments.argumentSet("Zero case", 0L, "0"), + Arguments.argumentSet("Maximum possible", Long.MAX_VALUE, "9223372036854775807"), + Arguments.argumentSet("Minimum possible", Long.MIN_VALUE, "-9223372036854775808")); + } + + @ParameterizedTest + @MethodSource("doubleValueProvider") + void valueDouble(double input, String expectedJson) { + assertThat(Value.of(input).asString()).isEqualTo(expectedJson); + } + + private static Stream doubleValueProvider() { + return Stream.of( + Arguments.argumentSet("Positive value", 3.14, "3.14"), + Arguments.argumentSet("Negative value", -2.5, "-2.5"), + Arguments.argumentSet("Zero", 0.0, "0.0"), + Arguments.argumentSet("Negative zero", -0.0, "-0.0"), + Arguments.argumentSet("NaN", Double.NaN, "NaN"), + Arguments.argumentSet("Positive infinity", Double.POSITIVE_INFINITY, "Infinity"), + Arguments.argumentSet("Negative infinity", Double.NEGATIVE_INFINITY, "-Infinity"), + Arguments.argumentSet("Scientific notation positive exponent", 1.23e10, "1.23E10"), + Arguments.argumentSet("Scientific notation negative exponent", 1.23e-10, "1.23E-10")); + } + + @ParameterizedTest + @MethodSource("bytesValueProvider") + void valueBytes(byte[] input, String expectedJson) { + assertThat(Value.of(input).asString()).isEqualTo(expectedJson); + } + + private static Stream bytesValueProvider() { + byte[] regularBytes = new byte[] {0, 1, 2, Byte.MAX_VALUE, Byte.MIN_VALUE}; + return Stream.of( + Arguments.argumentSet("empty bytes", new byte[] {}, ""), + Arguments.argumentSet( + "regular bytes", regularBytes, Base64.getEncoder().encodeToString(regularBytes))); + } + + @Test + void valueEmpty() { + assertThat(Value.empty().asString()).isEqualTo(""); + } + + @ParameterizedTest + @MethodSource("arrayValueProvider") + @SuppressWarnings("ExplicitArrayForVarargs") + void valueArray(Value input, String expectedJson) { + assertThat(input.asString()).isEqualTo(expectedJson); + } + + @SuppressWarnings("ExplicitArrayForVarargs") + private static Stream arrayValueProvider() { + return Stream.of( + Arguments.argumentSet("empty array", Value.of(new Value[] {}), "[]"), + Arguments.argumentSet("single string", Value.of(Value.of("test")), "[\"test\"]"), + Arguments.argumentSet( + "string array", + Value.of(Value.of("a"), Value.of("b"), Value.of("c")), + "[\"a\",\"b\",\"c\"]"), + Arguments.argumentSet( + "long array", Value.of(Value.of(1L), Value.of(2L), Value.of(3L)), "[1,2,3]"), + Arguments.argumentSet( + "mixed types", + Value.of( + Value.of("string"), + Value.of(42L), + Value.of(3.14), + Value.of(true), + Value.of(false), + Value.empty()), + "[\"string\",42,3.14,true,false,null]"), + Arguments.argumentSet( + "nested array", + Value.of( + Value.of("outer"), Value.of(Value.of("inner1"), Value.of("inner2")), Value.of(42L)), + "[\"outer\",[\"inner1\",\"inner2\"],42]"), + Arguments.argumentSet( + "deeply nested", + Value.of(Value.of(Value.of(Value.of(Value.of(Value.of("deep"))))), Value.of("shallow")), + "[[[[[\"deep\"]]]],\"shallow\"]")); + } + + @ParameterizedTest + @MethodSource("keyValueListValueProvider") + @SuppressWarnings("ExplicitArrayForVarargs") + void valueKeyValueList(Value input, String expectedJson) { + assertThat(input.asString()).isEqualTo(expectedJson); + } + + @SuppressWarnings("ExplicitArrayForVarargs") + private static Stream keyValueListValueProvider() { + Map> map = new LinkedHashMap<>(); + map.put("key1", Value.of("value1")); + map.put("key2", Value.of(42L)); + + return Stream.of( + Arguments.argumentSet("empty kvlist", Value.of(new KeyValue[] {}), "{}"), + Arguments.argumentSet( + "single kv", Value.of(KeyValue.of("key", Value.of("value"))), "{\"key\":\"value\"}"), + Arguments.argumentSet( + "kv with mixed types", + Value.of( + KeyValue.of("name", Value.of("Alice")), + KeyValue.of("age", Value.of(30L)), + KeyValue.of("active", Value.of(true))), + "{\"name\":\"Alice\",\"age\":30,\"active\":true}"), + Arguments.argumentSet( + "nested kvlist", + Value.of( + KeyValue.of("outer", Value.of("value")), + KeyValue.of( + "inner", + Value.of( + KeyValue.of("nested1", Value.of("a")), + KeyValue.of("nested2", Value.of("b"))))), + "{\"outer\":\"value\",\"inner\":{\"nested1\":\"a\",\"nested2\":\"b\"}}"), + Arguments.argumentSet( + "kv with array value", + Value.of( + KeyValue.of("name", Value.of("test")), + KeyValue.of("items", Value.of(Value.of(1L), Value.of(2L), Value.of(3L)))), + "{\"name\":\"test\",\"items\":[1,2,3]}"), + Arguments.argumentSet( + "all value types", + Value.of( + KeyValue.of("string", Value.of("text")), + KeyValue.of("long", Value.of(42L)), + KeyValue.of("double", Value.of(3.14)), + KeyValue.of("bool", Value.of(true)), + KeyValue.of("empty", Value.empty()), + KeyValue.of("bytes", Value.of(new byte[] {1, 2})), + KeyValue.of("array", Value.of(Value.of("a"), Value.of("b")))), + "{\"string\":\"text\",\"long\":42,\"double\":3.14,\"bool\":true," + + "\"empty\":null,\"bytes\":\"AQI=\",\"array\":[\"a\",\"b\"]}"), + Arguments.argumentSet("map value", Value.of(map), "{\"key1\":\"value1\",\"key2\":42}"), + Arguments.argumentSet( + "keys with special chars", + Value.of( + KeyValue.of("key with spaces", Value.of("value1")), + KeyValue.of("key\"with\"quotes", Value.of("value2")), + KeyValue.of("key\nwith\nnewlines", Value.of("value3"))), + "{\"key with spaces\":\"value1\"," + + "\"key\\\"with\\\"quotes\":\"value2\"," + + "\"key\\nwith\\nnewlines\":\"value3\"}")); + } + + @Test + void complexNestedStructure() { + Value complexValue = + Value.of( + KeyValue.of("user", Value.of("Alice")), + KeyValue.of( + "scores", + Value.of( + Value.of(95L), + Value.of(87.5), + Value.of(92L), + Value.of(Double.NaN), + Value.of(Double.POSITIVE_INFINITY))), + KeyValue.of("passed", Value.of(true)), + KeyValue.of( + "metadata", + Value.of( + KeyValue.of("timestamp", Value.of(1234567890L)), + KeyValue.of( + "tags", + Value.of( + Value.of("important"), Value.of("reviewed"), Value.of("final")))))); + + assertThat(complexValue.asString()) + .isEqualTo( + "{\"user\":\"Alice\"," + + "\"scores\":[95,87.5,92,\"NaN\",\"Infinity\"]," + + "\"passed\":true," + + "\"metadata\":{\"timestamp\":1234567890," + + "\"tags\":[\"important\",\"reviewed\",\"final\"]}}"); + } + + @ParameterizedTest + @MethodSource("edgeCaseProvider") + @SuppressWarnings("ExplicitArrayForVarargs") + void edgeCases(Value input, String expectedJson) { + assertThat(input.asString()).isEqualTo(expectedJson); + } + + @SuppressWarnings("ExplicitArrayForVarargs") + private static Stream edgeCaseProvider() { + return Stream.of( + Arguments.argumentSet( + "empty key", Value.of(KeyValue.of("", Value.of("value"))), "{\"\":\"value\"}"), + Arguments.argumentSet( + "null values", + Value.of(Value.empty(), Value.empty(), Value.empty()), + "[null,null,null]"), + Arguments.argumentSet( + "array of kvlists", + Value.of( + Value.of(KeyValue.of("id", Value.of(1L)), KeyValue.of("name", Value.of("A"))), + Value.of(KeyValue.of("id", Value.of(2L)), KeyValue.of("name", Value.of("B"))), + Value.of(KeyValue.of("id", Value.of(3L)), KeyValue.of("name", Value.of("C")))), + "[{\"id\":1,\"name\":\"A\"},{\"id\":2,\"name\":\"B\"},{\"id\":3,\"name\":\"C\"}]"), + Arguments.argumentSet( + "kv with empty array", + Value.of( + KeyValue.of("data", Value.of("test")), + KeyValue.of("items", Value.of(new Value[] {}))), + "{\"data\":\"test\",\"items\":[]}"), + Arguments.argumentSet( + "kv with empty kvlist", + Value.of( + KeyValue.of("data", Value.of("test")), + KeyValue.of("metadata", Value.of(new KeyValue[] {}))), + "{\"data\":\"test\",\"metadata\":{}}")); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/config/DeclarativeConfigPropertiesTest.java b/api/all/src/test/java/io/opentelemetry/api/config/DeclarativeConfigPropertiesTest.java new file mode 100644 index 00000000000..17c9a213e93 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/config/DeclarativeConfigPropertiesTest.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class DeclarativeConfigPropertiesTest { + + @Test + void empty() { + DeclarativeConfigProperties empty = DeclarativeConfigProperties.empty(); + assertThat(empty).isNotNull(); + assertThat(empty.getString("str")).isNull(); + assertThat(empty.getBoolean("bool")).isNull(); + assertThat(empty.getInt("int")).isNull(); + assertThat(empty.getLong("long")).isNull(); + assertThat(empty.getDouble("double")).isNull(); + assertThat(empty.getScalarList("list", String.class)).isNull(); + assertThat(empty.getStructured("struct")).isNull(); + assertThat(empty.getStructuredList("structList")).isNull(); + assertThat(empty.getPropertyKeys()).isEmpty(); + assertThat(empty.getComponentLoader()).isNotNull(); + + // Default methods with fallback values + assertThat(empty.getString("str", "def")).isEqualTo("def"); + assertThat(empty.getBoolean("bool", true)).isTrue(); + assertThat(empty.getInt("int", 42)).isEqualTo(42); + assertThat(empty.getLong("long", 100L)).isEqualTo(100L); + assertThat(empty.getDouble("double", 3.14)).isEqualTo(3.14); + assertThat(empty.getScalarList("list", String.class, Collections.singletonList("d"))) + .containsExactly("d"); + assertThat(empty.getStructured("struct", empty)).isSameAs(empty); + assertThat(empty.get("struct")).isNotNull(); + assertThat(empty.getStructuredList("structList", Collections.singletonList(empty))) + .containsExactly(empty); + + // Default type check methods + assertThat(empty.isString("str")).isFalse(); + assertThat(empty.isBoolean("bool")).isFalse(); + assertThat(empty.isInt("int")).isFalse(); + assertThat(empty.isLong("long")).isFalse(); + assertThat(empty.isDouble("double")).isFalse(); + } + + @Test + void toMap() { + DeclarativeConfigProperties empty = DeclarativeConfigProperties.empty(); + assertThat(DeclarativeConfigProperties.toMap(empty)).isNotNull().isEmpty(); + } + + @Test + void declarativeConfigException() { + DeclarativeConfigException ex1 = new DeclarativeConfigException("test error"); + assertThat(ex1.getMessage()).isEqualTo("test error"); + + RuntimeException cause = new RuntimeException("cause"); + DeclarativeConfigException ex2 = new DeclarativeConfigException("error with cause", cause); + assertThat(ex2.getMessage()).isEqualTo("error with cause"); + assertThat(ex2.getCause()).isSameAs(cause); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/TemporaryBuffersTest.java b/api/all/src/test/java/io/opentelemetry/api/impl/TemporaryBuffersTest.java similarity index 93% rename from api/all/src/test/java/io/opentelemetry/api/internal/TemporaryBuffersTest.java rename to api/all/src/test/java/io/opentelemetry/api/impl/TemporaryBuffersTest.java index 15e2caedf9c..1692c5404d8 100644 --- a/api/all/src/test/java/io/opentelemetry/api/internal/TemporaryBuffersTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/impl/TemporaryBuffersTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.api.internal; +package io.opentelemetry.api.impl; import static org.assertj.core.api.Assertions.assertThat; diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/ImmutableKeyValuePairsTest.java b/api/all/src/test/java/io/opentelemetry/api/internal/ImmutableKeyValuePairsTest.java index 9e63ca39be5..e2dd0a159b8 100644 --- a/api/all/src/test/java/io/opentelemetry/api/internal/ImmutableKeyValuePairsTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/internal/ImmutableKeyValuePairsTest.java @@ -21,6 +21,17 @@ void get() { assertThat(new TestPairs(new Object[] {"one", 55, "two", "b"}).get("one")).isEqualTo(55); assertThat(new TestPairs(new Object[] {"one", 55, "two", "b"}).get("two")).isEqualTo("b"); assertThat(new TestPairs(new Object[] {"one", 55, "two", "b"}).get("three")).isNull(); + assertThat(new TestPairs(new Object[] {"one", 55, "one", null, "one", 66}).get("one")) + .isEqualTo(66); + assertThat( + new TestPairs(new Object[] {"one", 55, "one", null, "one", 66, "one", null}).get("two")) + .isNull(); + assertThat( + new TestPairs(new Object[] {"one", 55, "two", "b", "one", null, "one", 66}).get("one")) + .isEqualTo(66); + assertThat( + new TestPairs(new Object[] {"one", 55, "two", 66, "two", null, "two", 77}).get("two")) + .isEqualTo(77); } @Test @@ -28,6 +39,14 @@ void size() { assertThat(new TestPairs(new Object[0]).size()).isEqualTo(0); assertThat(new TestPairs(new Object[] {"one", 55}).size()).isEqualTo(1); assertThat(new TestPairs(new Object[] {"one", 55, "two", "b"}).size()).isEqualTo(2); + assertThat(new TestPairs(new Object[] {"one", 55, "one", null, "one", 66}).size()).isEqualTo(1); + assertThat(new TestPairs(new Object[] {"one", 55, "one", null, "one", 66, "one", null}).size()) + .isEqualTo(0); + assertThat(new TestPairs(new Object[] {"one", 55, "two", "b", "one", null, "one", 66}).size()) + .isEqualTo(2); + assertThat(new TestPairs(new Object[] {"one", 55, "two", 66, "two", null}).size()).isEqualTo(1); + assertThat(new TestPairs(new Object[] {"one", 55, "two", 66, "two", null, "two", 77}).size()) + .isEqualTo(2); } @Test diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/InstrumentationUtilTest.java b/api/all/src/test/java/io/opentelemetry/api/internal/InstrumentationUtilTest.java new file mode 100644 index 00000000000..fe235644692 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/internal/InstrumentationUtilTest.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.internal; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.opentelemetry.api.impl.InstrumentationUtil; +import io.opentelemetry.context.Context; +import org.junit.jupiter.api.Test; + +class InstrumentationUtilTest { + @Test + void verifySuppressInstrumentation() { + // Should be false by default. + assertFalse(InstrumentationUtil.shouldSuppressInstrumentation(Context.current())); + + // Should be true inside the Runnable passed to InstrumentationUtil.suppressInstrumentation. + InstrumentationUtil.suppressInstrumentation( + () -> assertTrue(InstrumentationUtil.shouldSuppressInstrumentation(Context.current()))); + + // Should be false after the runnable finishes. + assertFalse(InstrumentationUtil.shouldSuppressInstrumentation(Context.current())); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/OtelEncodingUtilsTest.java b/api/all/src/test/java/io/opentelemetry/api/internal/OtelEncodingUtilsTest.java index 7f75413caea..81d7d18200e 100644 --- a/api/all/src/test/java/io/opentelemetry/api/internal/OtelEncodingUtilsTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/internal/OtelEncodingUtilsTest.java @@ -65,6 +65,19 @@ void validHex() { assertThat(OtelEncodingUtils.isValidBase16String("abcdef1234567890B")).isFalse(); } + @Test + void isValidBase16Character_doesNotThrowForAnyChar() { + // Regression test: VALID_HEX must be indexable by every possible char value, + // including Character.MAX_VALUE, without throwing ArrayIndexOutOfBoundsException. + assertThat(OtelEncodingUtils.isValidBase16Character(Character.MAX_VALUE)).isFalse(); + for (int c = 0; c <= Character.MAX_VALUE; c++) { + boolean expected = (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'); + assertThat(OtelEncodingUtils.isValidBase16Character((char) c)) + .as("char 0x%04x", c) + .isEqualTo(expected); + } + } + @Test void longFromBase16String() { assertThat(OtelEncodingUtils.longFromBase16String(CharBuffer.wrap(FIRST_CHAR_ARRAY), 0)) diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/ReadOnlyArrayMapTest.java b/api/all/src/test/java/io/opentelemetry/api/internal/ReadOnlyArrayMapTest.java index 54313d24bf5..4a6117f7188 100644 --- a/api/all/src/test/java/io/opentelemetry/api/internal/ReadOnlyArrayMapTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/internal/ReadOnlyArrayMapTest.java @@ -5,6 +5,8 @@ package io.opentelemetry.api.internal; +import static org.assertj.core.api.Assertions.assertThat; + import com.google.common.testing.EqualsTester; import java.util.Arrays; import java.util.Collections; @@ -25,4 +27,14 @@ void equalsHashCode() { .addEqualityGroup(empty, empty) .testEquals(); } + + @Test + void containsValueNull() { + Map map = ReadOnlyArrayMap.wrap(Arrays.asList("a", null)); + Map mapWithoutNull = ReadOnlyArrayMap.wrap(Arrays.asList("a", "b")); + + assertThat(map.containsValue(null)).isTrue(); + assertThat(map.containsValue("b")).isFalse(); + assertThat(mapWithoutNull.containsValue(null)).isFalse(); + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/StringUtilsTest.java b/api/all/src/test/java/io/opentelemetry/api/internal/StringUtilsTest.java index cc214bc3236..0b16c51cca9 100644 --- a/api/all/src/test/java/io/opentelemetry/api/internal/StringUtilsTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/internal/StringUtilsTest.java @@ -6,7 +6,6 @@ package io.opentelemetry.api.internal; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; @@ -27,22 +26,4 @@ void isNullOrEmpty() { assertThat(StringUtils.isNullOrEmpty("hello")).isFalse(); assertThat(StringUtils.isNullOrEmpty(" ")).isFalse(); } - - @Test - void padLeft() { - assertThat(StringUtils.padLeft("value", 10)).isEqualTo("00000value"); - } - - @Test - void padLeft_throws_for_null_value() { - assertThatThrownBy(() -> StringUtils.padLeft(null, 10)) - .isInstanceOf(NullPointerException.class); - } - - @Test - void padLeft_length_does_not_exceed_length() { - assertThat(StringUtils.padLeft("value", 3)).isEqualTo("value"); - assertThat(StringUtils.padLeft("value", -10)).isEqualTo("value"); - assertThat(StringUtils.padLeft("value", 0)).isEqualTo("value"); - } } diff --git a/api/all/src/test/java/io/opentelemetry/api/internal/ValidationUtilTest.java b/api/all/src/test/java/io/opentelemetry/api/internal/ValidationUtilTest.java deleted file mode 100644 index 65be227f64a..00000000000 --- a/api/all/src/test/java/io/opentelemetry/api/internal/ValidationUtilTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.api.internal; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressLogger(loggerName = ValidationUtil.API_USAGE_LOGGER_NAME) -public class ValidationUtilTest { - - @RegisterExtension - LogCapturer apiUsageLogs = - LogCapturer.create().captureForLogger(ValidationUtil.API_USAGE_LOGGER_NAME); - - @Test - void checkValidInstrumentName_InvalidNameLogs() { - assertThat(ValidationUtil.checkValidInstrumentName("1", " suffix")).isFalse(); - apiUsageLogs.assertContains( - "Instrument name \"1\" is invalid, returning noop instrument. Instrument names must consist of 63 or less characters including alphanumeric, _, ., -, and start with a letter. suffix"); - } - - @Test - void checkValidInstrumentName() { - // Valid names - assertThat(ValidationUtil.checkValidInstrumentName("f")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("F")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("foo")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("a1")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("a.")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("abcdefghijklmnopqrstuvwxyz")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("ABCDEFGHIJKLMNOPQRSTUVWXYZ")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("a1234567890")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName("a_-.")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentName(new String(new char[63]).replace('\0', 'a'))) - .isTrue(); - - // Empty and null not allowed - assertThat(ValidationUtil.checkValidInstrumentName(null)).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("")).isFalse(); - // Must start with a letter - assertThat(ValidationUtil.checkValidInstrumentName("1")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName(".")).isFalse(); - // Illegal characters - assertThat(ValidationUtil.checkValidInstrumentName("a~")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a!")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a@")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a#")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a$")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a%")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a^")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a&")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a*")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a(")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a)")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a=")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a+")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a{")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a}")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a[")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a]")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a\\")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a|")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a<")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a>")).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentName("a?")).isFalse(); - // Must be 63 characters or less - assertThat(ValidationUtil.checkValidInstrumentName(new String(new char[64]).replace('\0', 'a'))) - .isFalse(); - } - - @Test - void checkValidInstrumentUnit_InvalidUnitLogs() { - assertThat(ValidationUtil.checkValidInstrumentUnit("ζ—₯", " suffix")).isFalse(); - apiUsageLogs.assertContains( - "Unit \"ζ—₯\" is invalid. Instrument unit must be 63 or less ASCII characters." + " suffix"); - } - - @Test - void checkValidInstrumentUnit() { - assertThat(ValidationUtil.checkValidInstrumentUnit("a")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentUnit("A")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentUnit("foo129")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentUnit("!@#$%^&*()")).isTrue(); - assertThat(ValidationUtil.checkValidInstrumentUnit(new String(new char[63]).replace('\0', 'a'))) - .isTrue(); - - // Empty and null not allowed - assertThat(ValidationUtil.checkValidInstrumentUnit(null)).isFalse(); - assertThat(ValidationUtil.checkValidInstrumentUnit("")).isFalse(); - // Non-ascii characters - assertThat(ValidationUtil.checkValidInstrumentUnit("ζ—₯")).isFalse(); - // Must be 63 characters or less - assertThat(ValidationUtil.checkValidInstrumentUnit(new String(new char[64]).replace('\0', 'a'))) - .isFalse(); - } -} diff --git a/api/all/src/test/java/io/opentelemetry/api/logs/DefaultLoggerTest.java b/api/all/src/test/java/io/opentelemetry/api/logs/DefaultLoggerTest.java new file mode 100644 index 00000000000..10b43897a3e --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/logs/DefaultLoggerTest.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import io.opentelemetry.api.testing.internal.AbstractDefaultLoggerTest; + +class DefaultLoggerTest extends AbstractDefaultLoggerTest { + + @Override + protected LoggerProvider getLoggerProvider() { + return DefaultLoggerProvider.getInstance(); + } + + @Override + protected Logger getLogger() { + return DefaultLogger.getInstance(); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/logs/ValueFuzzTest.java b/api/all/src/test/java/io/opentelemetry/api/logs/ValueFuzzTest.java new file mode 100644 index 00000000000..1f5e8c24e75 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/logs/ValueFuzzTest.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import edu.berkeley.cs.jqf.fuzz.Fuzz; +import edu.berkeley.cs.jqf.fuzz.JQF; +import edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing; +import edu.berkeley.cs.jqf.fuzz.random.NoGuidance; +import io.opentelemetry.api.common.Value; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import org.junit.jupiter.api.Test; +import org.junit.runner.Result; +import org.junit.runner.RunWith; + +public class ValueFuzzTest { + @RunWith(JQF.class) + public static class FuzzTestCases { + @Fuzz + public void valueByteAsStringFuzz(String randomString) { + String base64Encoded = Value.of(randomString.getBytes(StandardCharsets.UTF_8)).asString(); + byte[] decodedBytes = Base64.getDecoder().decode(base64Encoded); + assertThat(new String(decodedBytes, StandardCharsets.UTF_8)).isEqualTo(randomString); + } + } + + @SuppressWarnings("SystemOut") + @Test + void valueByteAsStringFuzzing() { + Result result = + GuidedFuzzing.run( + FuzzTestCases.class, + "valueByteAsStringFuzz", + new NoGuidance(10000, System.out), + System.out); + assertThat(result.wasSuccessful()).isTrue(); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java b/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java new file mode 100644 index 00000000000..1be1bc97700 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/logs/ValueTest.java @@ -0,0 +1,217 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.logs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.common.ValueType; +import java.nio.ByteBuffer; +import java.nio.ReadOnlyBufferException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; + +class ValueTest { + + @Test + void value_OfString() { + assertThat(Value.of("foo")) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.STRING); + assertThat(value.getValue()).isEqualTo("foo"); + assertThat(value).hasSameHashCodeAs(Value.of("foo")); + }); + } + + @Test + void value_OfBoolean() { + assertThat(Value.of(true)) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.BOOLEAN); + assertThat(value.getValue()).isEqualTo(true); + assertThat(value).hasSameHashCodeAs(Value.of(true)); + }); + } + + @Test + void value_OfLong() { + assertThat(Value.of(1L)) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.LONG); + assertThat(value.getValue()).isEqualTo(1L); + assertThat(value).hasSameHashCodeAs(Value.of(1L)); + }); + } + + @Test + void value_OfDouble() { + assertThat(Value.of(1.1)) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.DOUBLE); + assertThat(value.getValue()).isEqualTo(1.1); + assertThat(value).hasSameHashCodeAs(Value.of(1.1)); + }); + } + + @Test + void value_OfByteArray() { + assertThat(Value.of(new byte[] {'a', 'b'})) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.BYTES); + ByteBuffer buf = value.getValue(); + // ValueBytes returns read only view of ByteBuffer + assertThatThrownBy(buf::array).isInstanceOf(ReadOnlyBufferException.class); + byte[] bytes = new byte[buf.remaining()]; + buf.get(bytes); + assertThat(bytes).isEqualTo(new byte[] {'a', 'b'}); + assertThat(value).hasSameHashCodeAs(Value.of(new byte[] {'a', 'b'})); + }); + } + + @Test + void value_OfvalueArray() { + assertThat(Value.of(Value.of(true), Value.of(1L))) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.ARRAY); + assertThat(value.getValue()).isEqualTo(Arrays.asList(Value.of(true), Value.of(1L))); + assertThat(value).hasSameHashCodeAs(Value.of(Value.of(true), Value.of(1L))); + }); + } + + @Test + @SuppressWarnings("DoubleBraceInitialization") + void value_OfKeyValueList() { + assertThat(Value.of(KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); + assertThat(value.getValue()) + .isEqualTo( + Arrays.asList( + KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); + assertThat(value) + .hasSameHashCodeAs( + Value.of(KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); + }); + + assertThat( + Value.of( + new LinkedHashMap>() { + { + put("bool", Value.of(true)); + put("long", Value.of(1L)); + } + })) + .satisfies(value -> { + assertThat(value.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); + assertThat(value.getValue()) + .isEqualTo( + Arrays.asList( + KeyValue.of("bool", Value.of(true)), KeyValue.of("long", Value.of(1L)))); + assertThat(value) + .hasSameHashCodeAs( + Value.of( + new LinkedHashMap>() { + { + put("bool", Value.of(true)); + put("long", Value.of(1L)); + } + })); + }); + } + + @Test + void value_NullsNotAllowed() { + assertThatThrownBy(() -> Value.of((String) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("value must not be null"); + assertThatThrownBy(() -> Value.of((byte[]) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("value must not be null"); + assertThatThrownBy(() -> Value.of((Value[]) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("value must not be null"); + assertThatThrownBy(() -> Value.of((List>) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("value must not be null"); + assertThatThrownBy(() -> Value.of((KeyValue[]) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("value must not be null"); + assertThatThrownBy(() -> Value.of((Map>) null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("value must not be null"); + } + + @ParameterizedTest + @MethodSource("asStringArgs") + void asString(Value value, String expectedAsString) { + assertThat(value.asString()).isEqualTo(expectedAsString); + } + + @SuppressWarnings("DoubleBraceInitialization") + private static Stream asStringArgs() { + return Stream.of( + // primitives + arguments(Value.of("str"), "str"), + arguments(Value.of(true), "true"), + arguments(Value.of(1), "1"), + arguments(Value.of(1.1), "1.1"), + // heterogeneous array + arguments( + Value.of(Value.of("str"), Value.of(true), Value.of(1), Value.of(1.1)), + "[\"str\",true,1,1.1]"), + // key value list from KeyValue array + arguments( + Value.of(KeyValue.of("key1", Value.of("val1")), KeyValue.of("key2", Value.of(2))), + "{\"key1\":\"val1\",\"key2\":2}"), + // key value list from map + arguments( + Value.of( + new LinkedHashMap>() { + { + put("key1", Value.of("val1")); + put("key2", Value.of(2)); + } + }), + "{\"key1\":\"val1\",\"key2\":2}"), + // map of map + arguments( + Value.of( + Collections.singletonMap( + "child", Value.of(Collections.singletonMap("grandchild", Value.of("str"))))), + "{\"child\":{\"grandchild\":\"str\"}}"), + // bytes + arguments(Value.of("hello world".getBytes(StandardCharsets.UTF_8)), "aGVsbG8gd29ybGQ=")); + } + + @ParameterizedTest + @ValueSource( + strings = { + "standard string", + "special characters !@#$%^&*()", + "multi\nline\tstring", + "", + "emoji boundary test πŸš€πŸ‘©β€πŸ’»" + }) + void valueByteAsString(String inputStr) { + String base64 = Value.of(inputStr.getBytes(StandardCharsets.UTF_8)).asString(); + byte[] decoded = Base64.getDecoder().decode(base64); + assertThat(new String(decoded, StandardCharsets.UTF_8)).isEqualTo(inputStr); + } +} diff --git a/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterProviderTest.java b/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterProviderTest.java deleted file mode 100644 index 786d0a68a6e..00000000000 --- a/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterProviderTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.api.metrics; - -import org.junit.jupiter.api.Test; - -public class DefaultMeterProviderTest { - @Test - void noopMeterProvider_getDoesNotThrow() { - MeterProvider provider = MeterProvider.noop(); - provider.get("user-instrumentation"); - } - - @Test - void noopMeterProvider_builderDoesNotThrow() { - MeterProvider provider = MeterProvider.noop(); - provider.meterBuilder("user-instrumentation").build(); - provider.meterBuilder("advanced-instrumetnation").setInstrumentationVersion("1.0").build(); - provider.meterBuilder("schema-instrumentation").setSchemaUrl("myschema://url").build(); - provider - .meterBuilder("schema-instrumentation") - .setInstrumentationVersion("1.0") - .setSchemaUrl("myschema://url") - .build(); - } -} diff --git a/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterTest.java b/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterTest.java index 825e1ddd9e3..69b32d5ecc0 100644 --- a/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/metrics/DefaultMeterTest.java @@ -5,266 +5,17 @@ package io.opentelemetry.api.metrics; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static io.opentelemetry.api.internal.ValidationUtil.API_USAGE_LOGGER_NAME; -import static org.assertj.core.api.Assertions.assertThat; +import io.opentelemetry.api.testing.internal.AbstractDefaultMeterTest; -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.slf4j.event.LoggingEvent; +public class DefaultMeterTest extends AbstractDefaultMeterTest { -@SuppressLogger(loggerName = API_USAGE_LOGGER_NAME) -public class DefaultMeterTest { - private static final Meter METER = DefaultMeter.getInstance(); - private static final String NOOP_INSTRUMENT_NAME = "noop"; - - @RegisterExtension - LogCapturer apiUsageLogs = LogCapturer.create().captureForLogger(API_USAGE_LOGGER_NAME); - - @Test - void builder_InvalidName() { - // Counter - assertThat(METER.counterBuilder("1").build()) - .isSameAs(METER.counterBuilder(NOOP_INSTRUMENT_NAME).build()); - assertThat(METER.counterBuilder("1").ofDoubles().build()) - .isSameAs(METER.counterBuilder(NOOP_INSTRUMENT_NAME).ofDoubles().build()); - assertThat(METER.counterBuilder("1").buildWithCallback(unused -> {})) - .isSameAs(METER.counterBuilder(NOOP_INSTRUMENT_NAME).buildWithCallback(unused -> {})); - assertThat(METER.counterBuilder("1").ofDoubles().buildWithCallback(unused -> {})) - .isSameAs( - METER.counterBuilder(NOOP_INSTRUMENT_NAME).ofDoubles().buildWithCallback(unused -> {})); - - // UpDownCounter - assertThat(METER.upDownCounterBuilder("1").build()) - .isSameAs(METER.upDownCounterBuilder(NOOP_INSTRUMENT_NAME).build()); - assertThat(METER.upDownCounterBuilder("1").ofDoubles().build()) - .isSameAs(METER.upDownCounterBuilder(NOOP_INSTRUMENT_NAME).ofDoubles().build()); - assertThat(METER.upDownCounterBuilder("1").buildWithCallback(unused -> {})) - .isSameAs(METER.upDownCounterBuilder(NOOP_INSTRUMENT_NAME).buildWithCallback(unused -> {})); - assertThat(METER.upDownCounterBuilder("1").ofDoubles().buildWithCallback(unused -> {})) - .isSameAs( - METER - .upDownCounterBuilder(NOOP_INSTRUMENT_NAME) - .ofDoubles() - .buildWithCallback(unused -> {})); - - // Histogram - assertThat(METER.histogramBuilder("1").build()) - .isSameAs(METER.histogramBuilder(NOOP_INSTRUMENT_NAME).build()); - assertThat(METER.histogramBuilder("1").ofLongs().build()) - .isSameAs(METER.histogramBuilder(NOOP_INSTRUMENT_NAME).ofLongs().build()); - - // Gauage - assertThat(METER.gaugeBuilder("1").buildWithCallback(unused -> {})) - .isSameAs(METER.gaugeBuilder(NOOP_INSTRUMENT_NAME).buildWithCallback(unused -> {})); - assertThat(METER.gaugeBuilder("1").ofLongs().buildWithCallback(unused -> {})) - .isSameAs( - METER.gaugeBuilder(NOOP_INSTRUMENT_NAME).ofLongs().buildWithCallback(unused -> {})); - - assertThat(apiUsageLogs.getEvents()) - .extracting(LoggingEvent::getMessage) - .hasSize(12) - .allMatch( - log -> - log.equals( - "Instrument name \"1\" is invalid, returning noop instrument. Instrument names must consist of 63 or less characters including alphanumeric, _, ., -, and start with a letter.")); - } - - @Test - void builder_InvalidUnit() { - String unit = "ζ—₯"; - // Counter - METER.counterBuilder("my-instrument").setUnit(unit).build(); - METER.counterBuilder("my-instrument").setUnit(unit).buildWithCallback(unused -> {}); - METER.counterBuilder("my-instrument").setUnit(unit).ofDoubles().build(); - METER.counterBuilder("my-instrument").setUnit(unit).ofDoubles().buildWithCallback(unused -> {}); - - // UpDownCounter - METER.upDownCounterBuilder("my-instrument").setUnit(unit).build(); - METER.upDownCounterBuilder("my-instrument").setUnit(unit).buildWithCallback(unused -> {}); - METER.upDownCounterBuilder("my-instrument").setUnit(unit).ofDoubles().build(); - METER - .upDownCounterBuilder("my-instrument") - .setUnit(unit) - .ofDoubles() - .buildWithCallback(unused -> {}); - - // Histogram - METER.histogramBuilder("my-instrument").setUnit(unit).build(); - METER.histogramBuilder("my-instrument").setUnit(unit).ofLongs().build(); - - // Gauge - METER.gaugeBuilder("my-instrument").setUnit(unit).buildWithCallback(unused -> {}); - METER.gaugeBuilder("my-instrument").setUnit(unit).ofLongs().buildWithCallback(unused -> {}); - - assertThat(apiUsageLogs.getEvents()) - .hasSize(12) - .extracting(LoggingEvent::getMessage) - .allMatch( - log -> - log.equals( - "Unit \"ζ—₯\" is invalid. Instrument unit must be 63 or less ASCII characters.")); - } - - @Test - void noopLongCounter_doesNotThrow() { - LongCounter counter = - METER.counterBuilder("size").setDescription("The size I'm measuring").setUnit("1").build(); - counter.add(1); - counter.add(1, Attributes.of(stringKey("thing"), "car")); - counter.add(1, Attributes.of(stringKey("thing"), "car"), Context.current()); - } - - @Test - void noopDoubleCounter_doesNotThrow() { - DoubleCounter counter = - METER - .counterBuilder("size") - .ofDoubles() - .setDescription("The size I'm measuring") - .setUnit("1") - .build(); - counter.add(1.2); - counter.add(2.5, Attributes.of(stringKey("thing"), "car")); - counter.add(2.5, Attributes.of(stringKey("thing"), "car"), Context.current()); - } - - @Test - void noopLongUpDownCounter_doesNotThrow() { - LongUpDownCounter counter = - METER - .upDownCounterBuilder("size") - .setDescription("The size I'm measuring") - .setUnit("1") - .build(); - counter.add(-1); - counter.add(1, Attributes.of(stringKey("thing"), "car")); - counter.add(1, Attributes.of(stringKey("thing"), "car"), Context.current()); - } - - @Test - void noopDoubleUpDownCounter_doesNotThrow() { - DoubleUpDownCounter counter = - METER - .upDownCounterBuilder("size") - .ofDoubles() - .setDescription("The size I'm measuring") - .setUnit("1") - .build(); - counter.add(-2e4); - counter.add(1.0e-1, Attributes.of(stringKey("thing"), "car")); - counter.add(1.0e-1, Attributes.of(stringKey("thing"), "car"), Context.current()); - } - - @Test - void noopLongHistogram_doesNotThrow() { - LongHistogram histogram = - METER - .histogramBuilder("size") - .ofLongs() - .setDescription("The size I'm measuring") - .setUnit("1") - .build(); - histogram.record(-1); - histogram.record(1, Attributes.of(stringKey("thing"), "car")); - histogram.record(1, Attributes.of(stringKey("thing"), "car"), Context.current()); - } - - @Test - void noopDoubleHistogram_doesNotThrow() { - DoubleHistogram histogram = - METER - .histogramBuilder("size") - .setDescription("The size I'm measuring") - .setUnit("1") - .build(); - histogram.record(-2e4); - histogram.record(1.0e-1, Attributes.of(stringKey("thing"), "car")); - histogram.record(1.0e-1, Attributes.of(stringKey("thing"), "car"), Context.current()); - } - - @Test - void noopObservableLongGauage_doesNotThrow() { - METER - .gaugeBuilder("temperature") - .ofLongs() - .setDescription("The current temperature") - .setUnit("C") - .buildWithCallback( - m -> { - m.record(1); - m.record(2, Attributes.of(stringKey("thing"), "engine")); - }); - } - - @Test - void noopObservableDoubleGauage_doesNotThrow() { - METER - .gaugeBuilder("temperature") - .setDescription("The current temperature") - .setUnit("C") - .buildWithCallback( - m -> { - m.record(1.0e1); - m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); - }); - } - - @Test - void noopObservableLongCounter_doesNotThrow() { - METER - .counterBuilder("temperature") - .setDescription("The current temperature") - .setUnit("C") - .buildWithCallback( - m -> { - m.record(1); - m.record(2, Attributes.of(stringKey("thing"), "engine")); - }); - } - - @Test - void noopObservableDoubleCounter_doesNotThrow() { - METER - .counterBuilder("temperature") - .ofDoubles() - .setDescription("The current temperature") - .setUnit("C") - .buildWithCallback( - m -> { - m.record(1.0e1); - m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); - }); - } - - @Test - void noopObservableLongUpDownCounter_doesNotThrow() { - METER - .upDownCounterBuilder("temperature") - .setDescription("The current temperature") - .setUnit("C") - .buildWithCallback( - m -> { - m.record(1); - m.record(2, Attributes.of(stringKey("thing"), "engine")); - }); + @Override + protected Meter getMeter() { + return DefaultMeter.getInstance(); } - @Test - void noopObservableDoubleUpDownCounter_doesNotThrow() { - METER - .upDownCounterBuilder("temperature") - .ofDoubles() - .setDescription("The current temperature") - .setUnit("C") - .buildWithCallback( - m -> { - m.record(1.0e1); - m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); - }); + @Override + protected MeterProvider getMeterProvider() { + return DefaultMeterProvider.getInstance(); } } diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerProviderTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerProviderTest.java deleted file mode 100644 index 72a98f29f59..00000000000 --- a/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerProviderTest.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.api.trace; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class DefaultTracerProviderTest { - - @Test - void returnsDefaultTracer() { - assertThat(TracerProvider.noop().get("test")).isInstanceOf(DefaultTracer.class); - assertThat(TracerProvider.noop().get("test", "1.0")).isInstanceOf(DefaultTracer.class); - } -} diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerTest.java index e1379592062..b6736fa3843 100644 --- a/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/trace/DefaultTracerTest.java @@ -5,77 +5,17 @@ package io.opentelemetry.api.trace; -import static org.assertj.core.api.Assertions.assertThat; +import io.opentelemetry.api.testing.internal.AbstractDefaultTracerTest; -import io.opentelemetry.context.Context; -import org.junit.jupiter.api.Test; +class DefaultTracerTest extends AbstractDefaultTracerTest { -/** Unit tests for {@link DefaultTracer}. */ -// Need to suppress warnings for MustBeClosed because Android 14 does not support -// try-with-resources. -@SuppressWarnings("MustBeClosedChecker") -class DefaultTracerTest { - private static final Tracer defaultTracer = DefaultTracer.getInstance(); - private static final String SPAN_NAME = "MySpanName"; - private static final SpanContext spanContext = - SpanContext.create( - "00000000000000000000000000000061", - "0000000000000061", - TraceFlags.getDefault(), - TraceState.getDefault()); - - @Test - void defaultSpanBuilderWithName() { - assertThat(defaultTracer.spanBuilder(SPAN_NAME).startSpan().getSpanContext().isValid()) - .isFalse(); - } - - @Test - void testSpanContextPropagationExplicitParent() { - Span span = - defaultTracer - .spanBuilder(SPAN_NAME) - .setParent(Context.root().with(Span.wrap(spanContext))) - .startSpan(); - assertThat(span.getSpanContext()).isSameAs(spanContext); - } - - @Test - void testSpanContextPropagation() { - Span parent = Span.wrap(spanContext); - - Span span = - defaultTracer.spanBuilder(SPAN_NAME).setParent(Context.root().with(parent)).startSpan(); - assertThat(span.getSpanContext()).isSameAs(spanContext); - } - - @Test - void noSpanContextMakesInvalidSpans() { - Span span = defaultTracer.spanBuilder(SPAN_NAME).startSpan(); - assertThat(span.getSpanContext()).isSameAs(SpanContext.getInvalid()); + @Override + public Tracer getTracer() { + return DefaultTracer.getInstance(); } - @Test - void testSpanContextPropagation_fromContext() { - Context context = Context.current().with(Span.wrap(spanContext)); - - Span span = defaultTracer.spanBuilder(SPAN_NAME).setParent(context).startSpan(); - assertThat(span.getSpanContext()).isSameAs(spanContext); - } - - @Test - void testSpanContextPropagation_fromContextAfterNoParent() { - Context context = Context.current().with(Span.wrap(spanContext)); - - Span span = defaultTracer.spanBuilder(SPAN_NAME).setNoParent().setParent(context).startSpan(); - assertThat(span.getSpanContext()).isSameAs(spanContext); - } - - @Test - void testSpanContextPropagation_fromContextThenNoParent() { - Context context = Context.current().with(Span.wrap(spanContext)); - - Span span = defaultTracer.spanBuilder(SPAN_NAME).setParent(context).setNoParent().startSpan(); - assertThat(span.getSpanContext()).isEqualTo(SpanContext.getInvalid()); + @Override + public TracerProvider getTracerProvider() { + return DefaultTracerProvider.getInstance(); } } diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/PropagatedSpanTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/PropagatedSpanTest.java index 7c3807775c7..ea33c957b42 100644 --- a/api/all/src/test/java/io/opentelemetry/api/trace/PropagatedSpanTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/trace/PropagatedSpanTest.java @@ -15,6 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import java.time.Instant; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; @@ -40,16 +41,17 @@ void doNotCrash() { span.setAttribute(booleanKey("MyBooleanAttributeKey"), true); span.setAttribute(longKey("MyLongAttributeKey"), 123L); span.setAttribute(longKey("MyLongAttributeKey"), 123); - span.setAttribute("NullString", null); + span.setAttribute("NullString", (String) null); span.setAttribute("EmptyString", ""); span.setAttribute("long", 1); span.setAttribute("double", 1.0); span.setAttribute("boolean", true); + span.setAttribute("value", Value.of("val")); span.setAttribute(stringArrayKey("NullArrayString"), null); span.setAttribute(booleanArrayKey("NullArrayBoolean"), null); span.setAttribute(longArrayKey("NullArrayLong"), null); span.setAttribute(doubleArrayKey("NullArrayDouble"), null); - span.setAttribute((String) null, null); + span.setAttribute((String) null, (String) null); span.setAllAttributes(null); span.setAllAttributes(Attributes.empty()); span.setAllAttributes( diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/SpanBuilderTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/SpanBuilderTest.java deleted file mode 100644 index a7ed2dc27cb..00000000000 --- a/api/all/src/test/java/io/opentelemetry/api/trace/SpanBuilderTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.api.trace; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import java.time.Instant; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link SpanBuilder}. */ -class SpanBuilderTest { - private final Tracer tracer = DefaultTracer.getInstance(); - - @Test - void doNotCrash_NoopImplementation() { - assertThatCode( - () -> { - SpanBuilder spanBuilder = tracer.spanBuilder(null); - spanBuilder.setSpanKind(null); - spanBuilder.setParent(null); - spanBuilder.setNoParent(); - spanBuilder.addLink(null); - spanBuilder.addLink(null, Attributes.empty()); - spanBuilder.addLink(SpanContext.getInvalid(), null); - spanBuilder.setAttribute((String) null, "foo"); - spanBuilder.setAttribute("foo", null); - spanBuilder.setAttribute(null, 0L); - spanBuilder.setAttribute(null, 0.0); - spanBuilder.setAttribute(null, false); - spanBuilder.setAttribute((AttributeKey) null, "foo"); - spanBuilder.setAttribute(stringKey(null), "foo"); - spanBuilder.setAttribute(stringKey(""), "foo"); - spanBuilder.setAttribute(stringKey("foo"), null); - spanBuilder.setStartTimestamp(-1, TimeUnit.MILLISECONDS); - spanBuilder.setStartTimestamp(1, null); - spanBuilder.setParent(Context.root().with(Span.wrap(null))); - spanBuilder.setParent(Context.root()); - spanBuilder.setNoParent(); - spanBuilder.addLink(Span.getInvalid().getSpanContext()); - spanBuilder.addLink(Span.getInvalid().getSpanContext(), Attributes.empty()); - spanBuilder.setAttribute("key", "value"); - spanBuilder.setAttribute("key", 12345L); - spanBuilder.setAttribute("key", .12345); - spanBuilder.setAttribute("key", true); - spanBuilder.setAttribute(stringKey("key"), "value"); - spanBuilder.setAllAttributes(Attributes.of(stringKey("key"), "value")); - spanBuilder.setAllAttributes(Attributes.empty()); - spanBuilder.setAllAttributes(null); - spanBuilder.setStartTimestamp(12345L, TimeUnit.NANOSECONDS); - spanBuilder.setStartTimestamp(Instant.EPOCH); - spanBuilder.setStartTimestamp(null); - assertThat(spanBuilder.startSpan().getSpanContext().isValid()).isFalse(); - }) - .doesNotThrowAnyException(); - } -} diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/TraceFlagsTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/TraceFlagsTest.java index d6ef529f004..fc5c52e8ed5 100644 --- a/api/all/src/test/java/io/opentelemetry/api/trace/TraceFlagsTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/trace/TraceFlagsTest.java @@ -9,23 +9,59 @@ import org.junit.jupiter.api.Test; -/** Unit tests for {@link TraceFlags}. */ +/** Unit tests for {@link TraceFlags} and {@link TraceFlagsBuilder}. */ class TraceFlagsTest { @Test void defaultInstances() { assertThat(TraceFlags.getDefault().asHex()).isEqualTo("00"); - assertThat(TraceFlags.getSampled().asHex()).isEqualTo("01"); + assertThat(TraceFlags.builder().build().asHex()).isEqualTo("00"); + assertThat(TraceFlags.builder().setSampled(true).build().asHex()).isEqualTo("01"); + assertThat(TraceFlags.builder().setSampled(false).build().asHex()).isEqualTo("00"); + assertThat(TraceFlags.builder().setRandomTraceId(true).build().asHex()).isEqualTo("02"); + assertThat(TraceFlags.builder().setRandomTraceId(false).build().asHex()).isEqualTo("00"); + assertThat(TraceFlags.builder().setSampled(true).setRandomTraceId(true).build().asHex()) + .isEqualTo("03"); + assertThat(TraceFlags.builder().setRandomTraceId(true).setSampled(true).build().asHex()) + .isEqualTo("03"); + } + + @Test + void idempotency() { + assertThat(TraceFlags.builder().setRandomTraceId(true).setRandomTraceId(true).build().asHex()) + .isEqualTo("02"); + assertThat(TraceFlags.builder().setSampled(true).setSampled(true).build().asHex()) + .isEqualTo("01"); + } + + @Test + void setAndClear() { + assertThat(TraceFlags.builder().setRandomTraceId(true).setRandomTraceId(false).build().asHex()) + .isEqualTo("00"); + assertThat(TraceFlags.builder().setSampled(true).setSampled(false).build().asHex()) + .isEqualTo("00"); } @Test void isSampled() { assertThat(TraceFlags.fromByte((byte) 0xff).isSampled()).isTrue(); assertThat(TraceFlags.fromByte((byte) 0x01).isSampled()).isTrue(); + assertThat(TraceFlags.fromByte((byte) 0x02).isSampled()).isFalse(); + assertThat(TraceFlags.fromByte((byte) 0x03).isSampled()).isTrue(); assertThat(TraceFlags.fromByte((byte) 0x05).isSampled()).isTrue(); assertThat(TraceFlags.fromByte((byte) 0x00).isSampled()).isFalse(); } + @Test + void isTraceIdRandom() { + assertThat(TraceFlags.fromByte((byte) 0xff).isTraceIdRandom()).isTrue(); + assertThat(TraceFlags.fromByte((byte) 0x01).isTraceIdRandom()).isFalse(); + assertThat(TraceFlags.fromByte((byte) 0x02).isTraceIdRandom()).isTrue(); + assertThat(TraceFlags.fromByte((byte) 0x03).isTraceIdRandom()).isTrue(); + assertThat(TraceFlags.fromByte((byte) 0x05).isTraceIdRandom()).isFalse(); + assertThat(TraceFlags.fromByte((byte) 0x00).isTraceIdRandom()).isFalse(); + } + @Test void toFromHex() { for (int i = 0; i < 256; i++) { diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/TraceStateTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/TraceStateTest.java index d4d8f0fda3f..c7634c99e11 100644 --- a/api/all/src/test/java/io/opentelemetry/api/trace/TraceStateTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/trace/TraceStateTest.java @@ -17,8 +17,10 @@ class TraceStateTest { private static final String FIRST_KEY = "key_1"; private static final String SECOND_KEY = "key_2"; + private static final String THIRD_KEY = "key_3"; private static final String FIRST_VALUE = "value.1"; private static final String SECOND_VALUE = "value.2"; + private static final String THIRD_VALUE = "value.3"; private final TraceState firstTraceState = TraceState.builder().put(FIRST_KEY, FIRST_VALUE).build(); @@ -123,22 +125,39 @@ void testValidAtSignVendorNamePrefix() { } @Test - void testVendorIdLongerThan13Characters() { - assertThat(TraceState.builder().put("1@nrabcdefghijkl", FIRST_VALUE).build()) + void testVendorIdWith14Characters() { + String key = "1@nrabcdefghijkl"; + assertThat(TraceState.builder().put(key, FIRST_VALUE).build().get(key)).isEqualTo(FIRST_VALUE); + } + + @Test + void testVendorIdLongerThan14Characters() { + assertThat(TraceState.builder().put("1@nrabcdefghijklm", FIRST_VALUE).build()) .isEqualTo(TraceState.getDefault()); } @Test - void testVendorIdLongerThan13Characters_longTenantId() { - assertThat(TraceState.builder().put("12345678901234567890@nrabcdefghijkl", FIRST_VALUE).build()) + void testVendorIdLongerThan14Characters_longTenantId() { + assertThat( + TraceState.builder().put("12345678901234567890@nrabcdefghijklm", FIRST_VALUE).build()) .isEqualTo(TraceState.getDefault()); } @Test - void tenantIdLongerThan240Characters() { + void tenantIdWith241Characters() { char[] chars = new char[241]; Arrays.fill(chars, 'a'); String tenantId = new String(chars); + assertThat( + TraceState.builder().put(tenantId + "@nr", FIRST_VALUE).build().get(tenantId + "@nr")) + .isEqualTo(FIRST_VALUE); + } + + @Test + void tenantIdLongerThan241Characters() { + char[] chars = new char[242]; + Arrays.fill(chars, 'a'); + String tenantId = new String(chars); assertThat(TraceState.builder().put(tenantId + "@nr", FIRST_VALUE).build()) .isEqualTo(TraceState.getDefault()); } @@ -286,6 +305,32 @@ void removeNotPresent() { .isEqualTo(multiValueTraceState); } + @Test + void removeSameKeyTwice() { + assertThat(firstTraceState.toBuilder().remove(FIRST_KEY).remove(FIRST_KEY).build()) + .isEqualTo(TraceState.getDefault()); + } + + @Test + void removeSameKeyTwice_KeepsRemainingEntry() { + assertThat(multiValueTraceState.toBuilder().remove(FIRST_KEY).remove(FIRST_KEY).build().asMap()) + .containsExactly(entry(SECOND_KEY, SECOND_VALUE)); + } + + @Test + void removeSameKeyTwice_KeepsRemainingEntries() { + assertThat( + TraceState.builder() + .put(FIRST_KEY, FIRST_VALUE) + .put(SECOND_KEY, SECOND_VALUE) + .put(THIRD_KEY, THIRD_VALUE) + .remove(SECOND_KEY) + .remove(SECOND_KEY) + .build() + .asMap()) + .containsExactly(entry(THIRD_KEY, THIRD_VALUE), entry(FIRST_KEY, FIRST_VALUE)); + } + @Test void addAndRemoveEntry() { assertThat( diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagatorTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagatorTest.java index b394eb37061..851d278e73f 100644 --- a/api/all/src/test/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagatorTest.java +++ b/api/all/src/test/java/io/opentelemetry/api/trace/propagation/W3CTraceContextPropagatorTest.java @@ -18,14 +18,18 @@ import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.context.propagation.TextMapSetter; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** Unit tests for {@link W3CTraceContextPropagator}. */ class W3CTraceContextPropagatorTest { @@ -294,6 +298,36 @@ void extract_NotSampledContext_TraceStateWithSpaces() { TRACE_ID_BASE16, SPAN_ID_BASE16, TraceFlags.getDefault(), TRACE_STATE)); } + @ParameterizedTest + @MethodSource("tracestateWhitespaceCharacters") + @Timeout(5) + void extract_LargeTracestateWhitespace(char whitespace) { + char[] padding = new char[100_000]; + Arrays.fill(padding, whitespace); + Map carrier = new LinkedHashMap<>(); + carrier.put(W3CTraceContextPropagator.TRACE_PARENT, TRACEPARENT_HEADER_SAMPLED); + carrier.put(W3CTraceContextPropagator.TRACE_STATE, "foo=bar" + new String(padding) + "x"); + assertThat(getSpanContext(w3cTraceContextPropagator.extract(Context.root(), carrier, getter))) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID_BASE16, SPAN_ID_BASE16, TraceFlags.getSampled(), TraceState.getDefault())); + + carrier.put(W3CTraceContextPropagator.TRACE_STATE, "foo=bar" + new String(padding)); + assertThat(getSpanContext(w3cTraceContextPropagator.extract(Context.root(), carrier, getter))) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID_BASE16, + SPAN_ID_BASE16, + TraceFlags.getSampled(), + TraceState.builder().put("foo", "bar").build())); + } + + private static Stream tracestateWhitespaceCharacters() { + return Stream.of( + Arguments.argumentSet("long runs of spaces", ' '), + Arguments.argumentSet("long runs of tabs", '\t')); + } + @Test void extract_EmptyHeader() { Map invalidHeaders = new LinkedHashMap<>(); @@ -528,11 +562,15 @@ void extract_nullGetter() { .isSameAs(context); } + @Test + void toString_Valid() { + assertThat(w3cTraceContextPropagator.toString()).isEqualTo("W3CTraceContextPropagator"); + } + // Tests transplanted from the w3c test suite @ParameterizedTest - @ValueSource( - strings = {"foo@=1,bar=2", "@foo=1,bar=2", "foo@@bar=1,bar=2", "foo@bar@baz=1,bar=2"}) + @MethodSource("illegalVendorFormats") void test_tracestate_key_illegal_vendor_format(String traceState) { Map invalidHeaders = new HashMap<>(); invalidHeaders.put(W3CTraceContextPropagator.TRACE_PARENT, TRACEPARENT_HEADER_SAMPLED); @@ -541,4 +579,12 @@ void test_tracestate_key_illegal_vendor_format(String traceState) { W3CTraceContextPropagator.getInstance().extract(Context.root(), invalidHeaders, getter); assertThat(Span.fromContext(context).getSpanContext().getTraceState().get("bar")).isNull(); } + + private static Stream illegalVendorFormats() { + return Stream.of( + Arguments.argumentSet("empty vendor id", "foo@=1,bar=2"), + Arguments.argumentSet("empty tenant id", "@foo=1,bar=2"), + Arguments.argumentSet("consecutive at signs", "foo@@bar=1,bar=2"), + Arguments.argumentSet("multiple vendor separators", "foo@bar@baz=1,bar=2")); + } } diff --git a/api/all/src/test/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncodingTest.java b/api/all/src/test/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncodingTest.java new file mode 100644 index 00000000000..a2740ffa6b5 --- /dev/null +++ b/api/all/src/test/java/io/opentelemetry/api/trace/propagation/internal/W3CTraceContextEncodingTest.java @@ -0,0 +1,137 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.trace.propagation.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.trace.TraceState; +import java.util.Arrays; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class W3CTraceContextEncodingTest { + + @ParameterizedTest + @MethodSource("orderedMembers") + void decodePreservesOrderAndIgnoresOptionalWhitespace(String header) { + assertThat( + W3CTraceContextEncoding.encodeTraceState( + W3CTraceContextEncoding.decodeTraceState(header))) + .isEqualTo("a=b,c=d"); + } + + private static Stream orderedMembers() { + return Stream.of( + Arguments.argumentSet("members without whitespace", "a=b,c=d"), + Arguments.argumentSet("optional spaces and tabs around members", " \ta=b \t, \tc=d \t"), + Arguments.argumentSet( + "leading, intervening, and trailing empty members", ",,a=b, \t,c=d,,")); + } + + @ParameterizedTest + @MethodSource("emptyMembers") + void decodeEmptyMembers(String header) { + assertThat(W3CTraceContextEncoding.decodeTraceState(header).isEmpty()).isTrue(); + } + + private static Stream emptyMembers() { + return Stream.of( + Arguments.argumentSet("empty header", ""), + Arguments.argumentSet("whitespace-only header", " \t"), + Arguments.argumentSet("empty members without whitespace", ",,"), + Arguments.argumentSet("empty members with spaces and tabs", " ,\t, ")); + } + + @Test + void decodePreservesLeadingSpacesInValue() { + assertThat(W3CTraceContextEncoding.decodeTraceState(" \ta= b \t").get("a")).isEqualTo(" b"); + } + + @ParameterizedTest + @MethodSource("invalidMembers") + void decodeInvalidMembers(String header) { + assertThat(W3CTraceContextEncoding.decodeTraceState(header).isEmpty()).isTrue(); + } + + private static Stream invalidMembers() { + return Stream.of( + Arguments.argumentSet("duplicate key", "a=b,a=c"), + Arguments.argumentSet("empty value", "a="), + Arguments.argumentSet("empty key", "=b"), + Arguments.argumentSet("uppercase key", "A=b"), + Arguments.argumentSet("equals sign in value", "a=b=c"), + Arguments.argumentSet("tab in value", "a=b\tx"), + Arguments.argumentSet("newline in value", "a=b\nx")); + } + + @Test + void decodeMissingKeyValueDelimiter() { + assertThatThrownBy(() -> W3CTraceContextEncoding.decodeTraceState("a=b,invalid")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void decodeMemberCountLimit() { + String header = + IntStream.range(0, 32).mapToObj(i -> "key" + i + "=value").collect(Collectors.joining(",")); + assertThat(W3CTraceContextEncoding.decodeTraceState(header).size()).isEqualTo(32); + assertThat( + W3CTraceContextEncoding.decodeTraceState(",, " + header.replace(",", ", ,") + ",\t,")) + .isEqualTo(W3CTraceContextEncoding.decodeTraceState(header)); + assertThatThrownBy(() -> W3CTraceContextEncoding.decodeTraceState(header + ",extra=value")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("TraceState has too many elements."); + } + + @Test + void decodeDoesNotLimitCombinedLengthTo512() { + String key = repeat('a', 256); + String value = repeat('b', 256); + TraceState state = W3CTraceContextEncoding.decodeTraceState(key + "=" + value + ",c=d"); + assertThat(state.size()).isEqualTo(2); + assertThat(state.get(key)).isEqualTo(value); + } + + @ParameterizedTest + @MethodSource("whitespaceCharacters") + @Timeout(5) + void decodeLargeWhitespaceRuns(char whitespace) { + String padding = repeat(whitespace, 100_000); + TraceState expected = TraceState.builder().put("a", "b").build(); + assertThat(W3CTraceContextEncoding.decodeTraceState("a=b" + padding + "x").isEmpty()).isTrue(); + assertThat(W3CTraceContextEncoding.decodeTraceState("a=b" + padding)).isEqualTo(expected); + assertThat(W3CTraceContextEncoding.decodeTraceState(padding + "a=b" + padding)) + .isEqualTo(expected); + assertThat(W3CTraceContextEncoding.decodeTraceState("a=b," + padding)).isEqualTo(expected); + assertThat(W3CTraceContextEncoding.decodeTraceState(padding).isEmpty()).isTrue(); + } + + private static Stream whitespaceCharacters() { + return Stream.of( + Arguments.argumentSet("long runs of spaces", ' '), + Arguments.argumentSet("long runs of tabs", '\t')); + } + + @Test + @Timeout(5) + void decodeManyEmptyMembers() { + assertThat(W3CTraceContextEncoding.decodeTraceState(repeat(',', 100_000) + "a=b")) + .isEqualTo(TraceState.builder().put("a", "b").build()); + } + + private static String repeat(char character, int count) { + char[] characters = new char[count]; + Arrays.fill(characters, character); + return new String(characters); + } +} diff --git a/api/incubator/README.md b/api/incubator/README.md new file mode 100644 index 00000000000..1e93839a352 --- /dev/null +++ b/api/incubator/README.md @@ -0,0 +1,44 @@ +# API Incubator + +Experimental APIs, including extended Log Bridge APIs, extended Metrics APIs, extended ContextPropagator APIs, and extended Trace APIs. + +## Extended Log Bridge API + +Features: + +* Add extended attributes to log records to encode complex data structures + +See [ExtendedLogsBridgeApiUsageTest](./src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java). + +## Extended Metrics APIs + +Features: + +* Attributes advice +* Bound instruments + +See [ExtendedMetricsApiUsageTest](./src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java), [BoundInstrumentUsageTest](./src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java). + +## Extended ContextPropagator APIs + +Features: + +* Simplified injection / extraction of context + +See [ExtendedContextPropagatorsUsageTest](./src/test/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagatorsUsageTest.java). + +## Extended Trace APIs + +Features: + +* Utility methods to reduce boilerplate using span API, including extracting context, and wrapping runnables / callables with spans + +See [ExtendedTraceApiUsageTest](./src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java). + +## Context-Scoped Attributes + +Features: + +* Associate attributes with a context for automatic stamping across telemetry signals + +See [ContextAttributesUsageTest](./src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesUsageTest.java). diff --git a/api/incubator/build.gradle.kts b/api/incubator/build.gradle.kts new file mode 100644 index 00000000000..56046af9eeb --- /dev/null +++ b/api/incubator/build.gradle.kts @@ -0,0 +1,50 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.jmh-conventions") + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry API Incubator" +otelJava.moduleName.set("io.opentelemetry.api.incubator") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("com.fasterxml.jackson.databind")) + +dependencies { + api(project(":api:all")) + + // Supports optional InstrumentationConfigUtil#convertToModel + compileOnly("com.fasterxml.jackson.core:jackson-databind") + + annotationProcessor("com.google.auto.value:auto-value") + + // To use parsed config file as input for InstrumentationConfigUtilTest + testImplementation(project(":sdk-extensions:declarative-config")) + + testImplementation(project(":sdk:testing")) + testImplementation(project(":api:testing-internal")) + + testImplementation("io.opentelemetry.semconv:opentelemetry-semconv-incubating") + + testImplementation("com.google.guava:guava") +} + +testing { + suites { + register("testConvertToModel") { + dependencies { + implementation("com.fasterxml.jackson.core:jackson-databind") + implementation(project(":sdk-extensions:declarative-config")) + implementation(project(":sdk-extensions:autoconfigure")) + implementation("com.google.guava:guava") + } + } + } +} + +tasks { + check { + dependsOn(testing.suites) + } +} diff --git a/exporters/otlp-http/logs/gradle.properties b/api/incubator/gradle.properties similarity index 100% rename from exporters/otlp-http/logs/gradle.properties rename to api/incubator/gradle.properties diff --git a/extensions/incubator/src/jmh/java/io/opentelemetry/extension/incubator/PassThroughPropagatorBenchmark.java b/api/incubator/src/jmh/java/io/opentelemetry/extension/incubator/PassThroughPropagatorBenchmark.java similarity index 97% rename from extensions/incubator/src/jmh/java/io/opentelemetry/extension/incubator/PassThroughPropagatorBenchmark.java rename to api/incubator/src/jmh/java/io/opentelemetry/extension/incubator/PassThroughPropagatorBenchmark.java index 06b68e6d45c..8d340985ae3 100644 --- a/extensions/incubator/src/jmh/java/io/opentelemetry/extension/incubator/PassThroughPropagatorBenchmark.java +++ b/api/incubator/src/jmh/java/io/opentelemetry/extension/incubator/PassThroughPropagatorBenchmark.java @@ -5,6 +5,7 @@ package io.opentelemetry.extension.incubator; +import io.opentelemetry.api.incubator.propagation.PassThroughPropagator; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; @@ -13,7 +14,6 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; -import io.opentelemetry.extension.incubator.propagation.PassThroughPropagator; import java.util.Collections; import java.util.HashMap; import java.util.Map; diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/ExtendedOpenTelemetry.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/ExtendedOpenTelemetry.java new file mode 100644 index 00000000000..35730917f23 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/ExtendedOpenTelemetry.java @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; + +/** Extension to {@link OpenTelemetry} with experimental APIs. */ +public interface ExtendedOpenTelemetry extends OpenTelemetry { + /** Returns the {@link ConfigProvider} for this {@link OpenTelemetry}. */ + default ConfigProvider getConfigProvider() { + return ConfigProvider.noop(); + } + + /** + * Returns the {@link DeclarativeConfigProperties} for a specific instrumentation by name. If no + * configuration is available for the given name, an empty {@link DeclarativeConfigProperties} is + * returned. + * + *

    For example, {@code getInstrumentationConfig("foo")} returns the node: + * + *

    {@code
    +   * instrumentation/development:
    +   *   java:
    +   *     foo:
    +   * }
    + * + * @param name the name of the instrumentation + * @return the {@link DeclarativeConfigProperties} for the given instrumentation name + */ + default DeclarativeConfigProperties getInstrumentationConfig(String name) { + return getConfigProvider().getInstrumentationConfig(name); + } + + /** + * Returns the {@link DeclarativeConfigProperties} for general instrumentation configuration. + * + *
    {@code
    +   * instrumentation/development:
    +   *   general:
    +   * }
    + * + *

    If the general configuration is not available, an empty {@link DeclarativeConfigProperties} + * is returned. + * + * @return the {@link DeclarativeConfigProperties} for the general instrumentation configuration + */ + default DeclarativeConfigProperties getGeneralInstrumentationConfig() { + return getConfigProvider().getGeneralInstrumentationConfig(); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/common/ContextAttributes.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/common/ContextAttributes.java new file mode 100644 index 00000000000..9f55f984fa7 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/common/ContextAttributes.java @@ -0,0 +1,82 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.common; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.common.impl.ApiUsageLogger; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; + +// TODO (jack-berg): delete after 2027-07-01 if progress hasn't been made on +// https://github.com/open-telemetry/opentelemetry-specification/pull/4931 +/** + * Utility for associating {@link Attributes} with a {@link Context} for automatic propagation to + * telemetry signals produced within that context. + * + *

    SDKs can be configured to stamp context-scoped attributes across telemetry signals, with the + * ability to filter based on signal, instrumentation scope, and attribute key. + * + *

    Cardinality Considerations

    + * + *

    The cardinality of context-scoped attributes requires special consideration with metrics, + * since metric cardinality limits can quickly be exceeded by high-cardinality attributes, putting + * the metric into an error state. + * + *

    Bound Instruments

    + * + *

    Bound instruments do not inherit dynamic context-scoped attributes. + */ +public final class ContextAttributes { + + private static final ContextKey CONTEXT_ATTRIBUTES_KEY = + ContextKey.named("opentelemetry-context-attributes"); + + private ContextAttributes() {} + + /** + * Sets the {@link Attributes} on the given {@link Context}, completely replacing any previously + * associated context-scoped attributes. + * + * @param context the context to attach attributes to. + * @param attributes the authoritative attributes to associate. Pass {@link Attributes#empty()} to + * logically clear context-scoped attributes. + * @return a new context containing the specified attributes. + */ + public static Context set(Context context, Attributes attributes) { + if (context == null) { + ApiUsageLogger.logNullParam(ContextAttributes.class, "set", "context"); + return Context.root(); + } + if (attributes == null) { + ApiUsageLogger.logNullParam(ContextAttributes.class, "set", "attributes"); + return context; + } + if (attributes.isEmpty()) { + Attributes existing = context.get(CONTEXT_ATTRIBUTES_KEY); + if (existing == null || existing.isEmpty()) { + return context; + } + return context.with(CONTEXT_ATTRIBUTES_KEY, Attributes.empty()); + } + return context.with(CONTEXT_ATTRIBUTES_KEY, attributes); + } + + /** + * Returns the {@link Attributes} associated with the given {@code context}, or {@link + * Attributes#empty()} if none are present. + * + *

    This method is intended primarily for telemetry pipeline components such as SDKs, samplers, + * processors, and exporters. Application code should treat context-scoped attributes as + * write-only via {@link #set(Context, Attributes)}. + */ + public static Attributes get(Context context) { + if (context == null) { + return Attributes.empty(); + } + Attributes attributes = context.get(CONTEXT_ATTRIBUTES_KEY); + return attributes != null ? attributes : Attributes.empty(); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/ConfigProvider.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/ConfigProvider.java new file mode 100644 index 00000000000..a51b2eaea3b --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/ConfigProvider.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A registry for accessing declarative configuration. + * + *

    The name Provider is for consistency with other languages and it is NOT loaded + * using reflection. + * + *

    See {@link InstrumentationConfigUtil} for convenience methods for extracting config from + * {@link ConfigProvider}. + */ +@ThreadSafe +public interface ConfigProvider { + + /** + * Returns the {@link DeclarativeConfigProperties} corresponding to instrumentation + * config, or {@link DeclarativeConfigProperties#empty()} if unavailable. + * + * @return the instrumentation {@link DeclarativeConfigProperties} + */ + DeclarativeConfigProperties getInstrumentationConfig(); + + /** + * Returns the {@link DeclarativeConfigProperties} for a specific instrumentation by name. If no + * configuration is available for the given name, an empty {@link DeclarativeConfigProperties} is + * returned. + * + *

    For example, {@code getInstrumentationConfig("foo")} returns the node: + * + *

    {@code
    +   * instrumentation/development:
    +   *   java:
    +   *     foo:
    +   * }
    + * + * @param name the name of the instrumentation + * @return the {@link DeclarativeConfigProperties} for the given instrumentation name + */ + default DeclarativeConfigProperties getInstrumentationConfig(String name) { + return getInstrumentationConfig().get("java").get(name); + } + + /** + * Returns the {@link DeclarativeConfigProperties} for general instrumentation configuration. + * + *
    {@code
    +   * instrumentation/development:
    +   *   general:
    +   * }
    + * + *

    If the general configuration is not available, an empty {@link DeclarativeConfigProperties} + * is returned. + * + * @return the {@link DeclarativeConfigProperties} for the general instrumentation configuration + */ + default DeclarativeConfigProperties getGeneralInstrumentationConfig() { + return getInstrumentationConfig().get("general"); + } + + /** Returns a no-op {@link ConfigProvider}. */ + static ConfigProvider noop() { + return DeclarativeConfigProperties::empty; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigException.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigException.java new file mode 100644 index 00000000000..124020b574c --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigException.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +/** + * An exception that is thrown when errors occur with declarative configuration. + * + * @deprecated Use {@link io.opentelemetry.api.config.DeclarativeConfigException} instead. Scheduled + * for removal after 1.68.0. + */ +@Deprecated +public final class DeclarativeConfigException extends RuntimeException { + + private static final long serialVersionUID = 3036584181551130522L; + + /** Create a new configuration exception with specified {@code message} and without a cause. */ + public DeclarativeConfigException(String message) { + super(message); + } + + /** Create a new configuration exception with specified {@code message} and {@code cause}. */ + public DeclarativeConfigException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigProperties.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigProperties.java new file mode 100644 index 00000000000..3b64be6411f --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigProperties.java @@ -0,0 +1,295 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +import io.opentelemetry.common.ComponentLoader; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * An interface for accessing declarative configuration data. + * + *

    An instance of {@link DeclarativeConfigProperties} is equivalent to a YAML mapping node. It has accessors for + * reading scalar properties, {@link #getStructured(String)} for reading children which are + * themselves mappings, and {@link #getStructuredList(String)} for reading children which are + * sequences of mappings. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @deprecated Use {@link io.opentelemetry.api.config.DeclarativeConfigProperties} instead. + * Scheduled for removal after 1.68.0. + */ +@Deprecated +public interface DeclarativeConfigProperties { + + /** + * Return an empty {@link DeclarativeConfigProperties} instance. + * + *

    Useful for walking the tree without checking for null. For example, to access a string key + * nested at .foo.bar.baz, call: {@code config.getStructured("foo", empty()).getStructured("bar", + * empty()).getString("baz")}. + */ + static DeclarativeConfigProperties empty() { + return EmptyDeclarativeConfigProperties.getInstance(); + } + + /** Return a map representation of the {@code declarativeConfigProperties}. */ + static Map toMap(DeclarativeConfigProperties declarativeConfigProperties) { + return DeclarativeConfigPropertyUtil.toMap(declarativeConfigProperties); + } + + /** + * Returns a {@link String} configuration property. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * string + */ + @Nullable + String getString(String name); + + /** + * Returns a {@link String} configuration property. + * + * @return a {@link String} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar string + */ + default String getString(String name, String defaultValue) { + String value = getString(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Boolean} configuration property. Implementations should use the same rules as + * {@link Boolean#parseBoolean(String)} for handling the values. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * boolean + */ + @Nullable + Boolean getBoolean(String name); + + /** + * Returns a {@link Boolean} configuration property. + * + * @return a {@link Boolean} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar boolean + */ + default boolean getBoolean(String name, boolean defaultValue) { + Boolean value = getBoolean(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Integer} configuration property. + * + *

    If the underlying config property is {@link Long}, it is converted to {@link Integer} with + * {@link Long#intValue()} which may result in loss of precision. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * integer + */ + @Nullable + Integer getInt(String name); + + /** + * Returns a {@link Integer} configuration property. + * + *

    If the underlying config property is {@link Long}, it is converted to {@link Integer} with + * {@link Long#intValue()} which may result in loss of precision. + * + * @return a {@link Integer} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar integer + */ + default int getInt(String name, int defaultValue) { + Integer value = getInt(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Long} configuration property. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * long + */ + @Nullable + Long getLong(String name); + + /** + * Returns a {@link Long} configuration property. + * + * @return a {@link Long} configuration property or {@code defaultValue} if a property with {@code + * name} has not been configured or is not a valid scalar long + */ + default long getLong(String name, long defaultValue) { + Long value = getLong(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link Double} configuration property. + * + * @return null if the property has not been configured or if the property is not a valid scalar + * double + */ + @Nullable + Double getDouble(String name); + + /** + * Returns a {@link Double} configuration property. + * + * @return a {@link Double} configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured or is not a valid scalar double + */ + default double getDouble(String name, double defaultValue) { + Double value = getDouble(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link List} configuration property. Empty values and values which do not map to the + * {@code scalarType} will be removed. + * + * @param name the property name + * @param scalarType the scalar type, one of {@link String}, {@link Boolean}, {@link Long} or + * {@link Double} + * @return a {@link List} configuration property, or null if the property has not been configured + * or if the property is not a valid sequence of scalars + * @throws DeclarativeConfigException if {@code scalarType} is not supported + */ + @Nullable + List getScalarList(String name, Class scalarType); + + /** + * Returns a {@link List} configuration property. Empty values and values which do not map to the + * {@code scalarType} will be removed. + * + * @param name the property name + * @param scalarType the scalar type, one of {@link String}, {@link Boolean}, {@link Long} or + * {@link Double} + * @return a {@link List} configuration property or {@code defaultValue} if a property with {@code + * name} has not been configured or is not a valid sequence of scalars + */ + default List getScalarList(String name, Class scalarType, List defaultValue) { + List value = getScalarList(name, scalarType); + return value == null ? defaultValue : value; + } + + /** + * Returns whether the property with {@code name} holds a value which {@link #getString(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar string, + * false otherwise, including when the property is null + */ + boolean isString(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getBoolean(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar boolean, + * false otherwise, including when the property is null + */ + boolean isBoolean(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getInt(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar integer, + * false otherwise, including when the property is null + */ + boolean isInt(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getLong(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar long, + * false otherwise, including when the property is null + */ + boolean isLong(String name); + + /** + * Returns whether the property with {@code name} holds a value which {@link #getDouble(String)} + * accepts. + * + * @return true if a property with {@code name} has been configured and is a valid scalar double, + * false otherwise, including when the property is null + */ + boolean isDouble(String name); + + /** + * Returns a {@link DeclarativeConfigProperties} configuration property. + * + * @return a map-valued configuration property, or {@code null} if {@code name} has not been + * configured or is not a mapping + */ + @Nullable + DeclarativeConfigProperties getStructured(String name); + + /** + * Returns a {@link DeclarativeConfigProperties} configuration property. + * + * @return a map-valued configuration property, or {@code defaultValue} if {@code name} has not + * been configured or is not a mapping + */ + default DeclarativeConfigProperties getStructured( + String name, DeclarativeConfigProperties defaultValue) { + DeclarativeConfigProperties value = getStructured(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a {@link DeclarativeConfigProperties} configuration property, or {@link #empty()} if a + * property with {@code name} has not been configured. + * + *

    This is syntactic sugar for the common operation of calling {@code + * config.getStructured(name, empty())}. If you need to distinguish between a property being set + * but empty vs. not set, use {@link #getStructured(String)}. + * + * @return a map-valued configuration property, or an empty {@link DeclarativeConfigProperties} + * instance if {@code name} has not been configured or is not a mapping + */ + default DeclarativeConfigProperties get(String name) { + return getStructured(name, empty()); + } + + /** + * Returns a list of {@link DeclarativeConfigProperties} configuration property. + * + * @return a list of map-valued configuration property, or {@code null} if {@code name} has not + * been configured or is not a sequence of mappings + */ + @Nullable + List getStructuredList(String name); + + /** + * Returns a list of {@link DeclarativeConfigProperties} configuration property. + * + * @return a list of map-valued configuration property, or {@code defaultValue} if {@code name} + * has not been configured or is not a sequence of mappings + */ + default List getStructuredList( + String name, List defaultValue) { + List value = getStructuredList(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a set of all configuration property keys. + * + * @return the configuration property keys + */ + Set getPropertyKeys(); + + /** Return a {@link ComponentLoader} that should be used to load SPIs. */ + ComponentLoader getComponentLoader(); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigPropertyUtil.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigPropertyUtil.java new file mode 100644 index 00000000000..f546c72dbf2 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/DeclarativeConfigPropertyUtil.java @@ -0,0 +1,134 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +import static java.util.stream.Collectors.toList; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.BiFunction; +import javax.annotation.Nullable; + +@SuppressWarnings("deprecation") +final class DeclarativeConfigPropertyUtil { + + private DeclarativeConfigPropertyUtil() {} + + private static final List> + valueResolvers = + Arrays.asList( + DeclarativeConfigPropertyUtil::getString, + DeclarativeConfigPropertyUtil::getBoolean, + DeclarativeConfigPropertyUtil::getLong, + DeclarativeConfigPropertyUtil::getDouble, + DeclarativeConfigPropertyUtil::getStringList, + DeclarativeConfigPropertyUtil::getBooleanList, + DeclarativeConfigPropertyUtil::getLongList, + DeclarativeConfigPropertyUtil::getDoubleList, + DeclarativeConfigPropertyUtil::getStructuredList, + DeclarativeConfigPropertyUtil::getStructured); + + static Map toMap(DeclarativeConfigProperties declarativeConfigProperties) { + Set propertyKeys = declarativeConfigProperties.getPropertyKeys(); + Map result = new HashMap<>(propertyKeys.size()); + for (String key : declarativeConfigProperties.getPropertyKeys()) { + result.put(key, resolveValue(key, declarativeConfigProperties)); + } + return result; + } + + @Nullable + private static Object resolveValue( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + for (int i = 0; i < valueResolvers.size(); i++) { + try { + Object value = valueResolvers.get(i).apply(key, declarativeConfigProperties); + if (value != null) { + return value; + } + } catch (DeclarativeConfigException e) { + // Ignore and continue + } + } + return null; + } + + @Nullable + private static Object getString( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isString(key) + ? declarativeConfigProperties.getString(key) + : null; + } + + @Nullable + private static Object getBoolean( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isBoolean(key) + ? declarativeConfigProperties.getBoolean(key) + : null; + } + + @Nullable + private static Object getLong( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isLong(key) + ? declarativeConfigProperties.getLong(key) + : null; + } + + @Nullable + private static Object getDouble( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.isDouble(key) + ? declarativeConfigProperties.getDouble(key) + : null; + } + + @Nullable + private static Object getStringList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, String.class); + } + + @Nullable + private static Object getBooleanList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, Boolean.class); + } + + @Nullable + private static Object getLongList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, Long.class); + } + + @Nullable + private static Object getDoubleList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return declarativeConfigProperties.getScalarList(key, Double.class); + } + + @Nullable + private static Object getStructuredList( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return Optional.ofNullable(declarativeConfigProperties.getStructuredList(key)) + .map(list -> list.stream().map(DeclarativeConfigPropertyUtil::toMap).collect(toList())) + .orElse(null); + } + + @Nullable + private static Object getStructured( + String key, DeclarativeConfigProperties declarativeConfigProperties) { + return Optional.ofNullable(declarativeConfigProperties.getStructured(key)) + .map(DeclarativeConfigPropertyUtil::toMap) + .orElse(null); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/EmptyDeclarativeConfigProperties.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/EmptyDeclarativeConfigProperties.java new file mode 100644 index 00000000000..4141f6c8e52 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/EmptyDeclarativeConfigProperties.java @@ -0,0 +1,111 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +import io.opentelemetry.common.ComponentLoader; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import javax.annotation.Nullable; + +/** Empty instance of {@link DeclarativeConfigProperties}. */ +@SuppressWarnings("deprecation") +final class EmptyDeclarativeConfigProperties implements DeclarativeConfigProperties { + + private static final EmptyDeclarativeConfigProperties INSTANCE = + new EmptyDeclarativeConfigProperties(); + private static final ComponentLoader COMPONENT_LOADER = + ComponentLoader.forClassLoader(EmptyDeclarativeConfigProperties.class.getClassLoader()); + + private EmptyDeclarativeConfigProperties() {} + + static EmptyDeclarativeConfigProperties getInstance() { + return INSTANCE; + } + + @Nullable + @Override + public String getString(String name) { + return null; + } + + @Nullable + @Override + public Boolean getBoolean(String name) { + return null; + } + + @Nullable + @Override + public Integer getInt(String name) { + return null; + } + + @Nullable + @Override + public Long getLong(String name) { + return null; + } + + @Nullable + @Override + public Double getDouble(String name) { + return null; + } + + @Nullable + @Override + public List getScalarList(String name, Class scalarType) { + return null; + } + + @Override + public boolean isString(String name) { + return false; + } + + @Override + public boolean isBoolean(String name) { + return false; + } + + @Override + public boolean isInt(String name) { + return false; + } + + @Override + public boolean isLong(String name) { + return false; + } + + @Override + public boolean isDouble(String name) { + return false; + } + + @Nullable + @Override + public DeclarativeConfigProperties getStructured(String name) { + return null; + } + + @Nullable + @Override + public List getStructuredList(String name) { + return null; + } + + @Override + public Set getPropertyKeys() { + return Collections.emptySet(); + } + + @Override + public ComponentLoader getComponentLoader() { + return COMPONENT_LOADER; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/InstrumentationConfigUtil.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/InstrumentationConfigUtil.java new file mode 100644 index 00000000000..0cb2e31fc44 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/config/InstrumentationConfigUtil.java @@ -0,0 +1,165 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import javax.annotation.Nullable; + +/** + * A collection of convenience methods to extract instrumentation config from {@link + * ConfigProvider#getInstrumentationConfig()}. + */ +public class InstrumentationConfigUtil { + + /** + * Return {@code .instrumentation.general.http.client.request_captured_headers}, or null if none + * is configured. + * + * @throws DeclarativeConfigException if an unexpected type is encountered accessing the property + */ + @Nullable + public static List httpClientRequestCapturedHeaders(ConfigProvider configProvider) { + return getOrNull( + configProvider, + config -> config.getScalarList("request_captured_headers", String.class), + "general", + "http", + "client"); + } + + /** + * Return {@code .instrumentation.general.http.client.response_captured_headers}, or null if none + * is configured. + * + * @throws DeclarativeConfigException if an unexpected type is encountered accessing the property + */ + @Nullable + public static List httpClientResponseCapturedHeaders(ConfigProvider configProvider) { + return getOrNull( + configProvider, + config -> config.getScalarList("response_captured_headers", String.class), + "general", + "http", + "client"); + } + + /** + * Return {@code .instrumentation.general.http.server.request_captured_headers}, or null if none + * is configured. + * + * @throws DeclarativeConfigException if an unexpected type is encountered accessing the property + */ + @Nullable + public static List httpServerRequestCapturedHeaders(ConfigProvider configProvider) { + return getOrNull( + configProvider, + config -> config.getScalarList("request_captured_headers", String.class), + "general", + "http", + "server"); + } + + /** + * Return {@code .instrumentation.general.http.server.response_captured_headers}, or null if none + * is configured. + * + * @throws DeclarativeConfigException if an unexpected type is encountered accessing the property + */ + @Nullable + public static List httpServerResponseCapturedHeaders(ConfigProvider configProvider) { + return getOrNull( + configProvider, + config -> config.getScalarList("response_captured_headers", String.class), + "general", + "http", + "server"); + } + + /** + * Return {@code .instrumentation.java.}, or null if none is configured. + * + * @throws DeclarativeConfigException if an unexpected type is encountered accessing the property + */ + @Nullable + public static DeclarativeConfigProperties javaInstrumentationConfig( + ConfigProvider configProvider, String instrumentationName) { + return getOrNull(configProvider, config -> config.getStructured(instrumentationName), "java"); + } + + /** + * Walk down the {@code segments} of {@link ConfigProvider#getInstrumentationConfig()} and call + * {@code accessor} on the terminal node. Returns null if null is encountered walking the {@code + * segments}, or if {@code accessor} returns null. + * + *

    See other methods in {@link InstrumentationConfigUtil} for usage examples. + */ + @Nullable + public static T getOrNull( + ConfigProvider configProvider, + Function accessor, + String... segments) { + DeclarativeConfigProperties config = configProvider.getInstrumentationConfig(); + for (String segment : segments) { + config = config.getStructured(segment); + if (config == null) { + return null; + } + } + return accessor.apply(config); + } + + private InstrumentationConfigUtil() {} + + /** + * Return {@code .instrumentation.java.}, after converting it to the {@code + * modelType} using the {@code objectMapper}. If no configuration exists for the {@code + * instrumentationName}, returns {@code null}. + * + *

    This method is a convenience method for a common instrumentation library workflow: + * + *

      + *
    • During initialization, an instrumentation library is given an {@link ConfigProvider} and + * must initialize according to the relevant config + *
    • It checks if the user has provided configuration for it, and if so... + *
    • It converts the configuration to an in-memory model representing all of its relevant + * properties + *
    • It initializes using the strongly typed in-memory model + *
    + * + *

    Conversion is done using {@link ObjectMapper#convertValue(Object, Class)} from {@code + * com.fasterxml.jackson.databind}, and assumes the {@code modelType} is a POJO written / + * annotated to support jackson databinding. + * + *

    NOTE: callers MUST add their own dependency on {@code + * com.fasterxml.jackson.core:jackson-databind}. This module's dependency is {@code compileOnly} + * since jackson is a large dependency that many users will not require. It's very possible to + * convert between {@link DeclarativeConfigProperties} (or a map representation from {@link + * DeclarativeConfigProperties#toMap(DeclarativeConfigProperties)}) and a target model type + * without jackson. This method is provided as an optional convenience method. + * + * @throws IllegalArgumentException if conversion fails. See {@link + * ObjectMapper#convertValue(Object, Class)} for details. + */ + @Nullable + public static T getInstrumentationConfigModel( + ConfigProvider configProvider, + String instrumentationName, + ObjectMapper objectMapper, + Class modelType) { + DeclarativeConfigProperties properties = + javaInstrumentationConfig(configProvider, instrumentationName); + if (properties == null) { + return null; + } + Map configPropertiesMap = DeclarativeConfigProperties.toMap(properties); + return objectMapper.convertValue(configPropertiesMap, modelType); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/internal/ObfuscatedExtendedOpenTelemetry.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/internal/ObfuscatedExtendedOpenTelemetry.java new file mode 100644 index 00000000000..93a0b90ea91 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/internal/ObfuscatedExtendedOpenTelemetry.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.internal; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.incubator.ExtendedOpenTelemetry; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerBuilder; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.ContextPropagators; +import javax.annotation.concurrent.ThreadSafe; + +/** + * Static global instances are obfuscated when they are returned from the API to prevent users from + * casting them to their SDK-specific implementation. For example, we do not want users to use + * patterns like {@code (OpenTelemetrySdk) GlobalOpenTelemetry.get()}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@ThreadSafe +public final class ObfuscatedExtendedOpenTelemetry implements ExtendedOpenTelemetry { + + private final ExtendedOpenTelemetry delegate; + + /** + * This constructor is called via reflection from {@link + * io.opentelemetry.api.internal.IncubatingUtil#obfuscatedOpenTelemetryIfIncubating(OpenTelemetry)}. + */ + public ObfuscatedExtendedOpenTelemetry(ExtendedOpenTelemetry delegate) { + this.delegate = delegate; + } + + @Override + public TracerProvider getTracerProvider() { + return delegate.getTracerProvider(); + } + + @Override + public MeterProvider getMeterProvider() { + return delegate.getMeterProvider(); + } + + @Override + public LoggerProvider getLogsBridge() { + return delegate.getLogsBridge(); + } + + @Override + public ContextPropagators getPropagators() { + return delegate.getPropagators(); + } + + @Override + public TracerBuilder tracerBuilder(String instrumentationScopeName) { + return delegate.tracerBuilder(instrumentationScopeName); + } + + @Override + public ConfigProvider getConfigProvider() { + return delegate.getConfigProvider(); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLogger.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLogger.java new file mode 100644 index 00000000000..c9a163d0aec --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLogger.java @@ -0,0 +1,106 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.context.Context; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + +class ExtendedDefaultLogger implements ExtendedLogger { + + private static final Logger INSTANCE = new ExtendedDefaultLogger(); + private static final ExtendedLogRecordBuilder NOOP_LOG_RECORD_BUILDER = + new NoopExtendedLogRecordBuilder(); + + private ExtendedDefaultLogger() {} + + static Logger getNoop() { + return INSTANCE; + } + + @Override + public boolean isEnabled(Severity severity, Context context) { + return false; + } + + @Override + public ExtendedLogRecordBuilder logRecordBuilder() { + return NOOP_LOG_RECORD_BUILDER; + } + + private static final class NoopExtendedLogRecordBuilder implements ExtendedLogRecordBuilder { + + private NoopExtendedLogRecordBuilder() {} + + @Override + public ExtendedLogRecordBuilder setEventName(String eventName) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setException(Throwable throwable) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setAttribute(AttributeKey key, @Nullable T value) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setTimestamp(long timestamp, TimeUnit unit) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setTimestamp(Instant instant) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setObservedTimestamp(long timestamp, TimeUnit unit) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setObservedTimestamp(Instant instant) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setContext(Context context) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setSeverity(Severity severity) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setSeverityText(String severityText) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setBody(String body) { + return this; + } + + @Override + public ExtendedLogRecordBuilder setBody(Value body) { + return this; + } + + @Override + public void emit() {} + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLoggerProvider.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLoggerProvider.java new file mode 100644 index 00000000000..f46163ff954 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLoggerProvider.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.logs; + +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.LoggerBuilder; +import io.opentelemetry.api.logs.LoggerProvider; + +/** A no-op logger provider supporting the incubating logs API. */ +public class ExtendedDefaultLoggerProvider implements LoggerProvider { + + private static final LoggerProvider INSTANCE = new ExtendedDefaultLoggerProvider(); + private static final LoggerBuilder NOOP_BUILDER = new NoopLoggerBuilder(); + + private ExtendedDefaultLoggerProvider() {} + + public static LoggerProvider getNoop() { + return INSTANCE; + } + + @Override + public LoggerBuilder loggerBuilder(String instrumentationScopeName) { + return NOOP_BUILDER; + } + + private static class NoopLoggerBuilder implements LoggerBuilder { + + @Override + public LoggerBuilder setSchemaUrl(String schemaUrl) { + return this; + } + + @Override + public LoggerBuilder setInstrumentationVersion(String instrumentationVersion) { + return this; + } + + @Override + public Logger build() { + return ExtendedDefaultLogger.getNoop(); + } + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedLogRecordBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedLogRecordBuilder.java new file mode 100644 index 00000000000..740ca827622 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedLogRecordBuilder.java @@ -0,0 +1,90 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.context.Context; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + +/** Extended {@link LogRecordBuilder} with experimental APIs. */ +public interface ExtendedLogRecordBuilder extends LogRecordBuilder { + + // keep this class even if it is empty, since experimental methods may be added in the future. + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setTimestamp(long timestamp, TimeUnit unit); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setTimestamp(Instant instant); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setObservedTimestamp(long timestamp, TimeUnit unit); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setObservedTimestamp(Instant instant); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setContext(Context context); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setSeverity(Severity severity); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setSeverityText(String severityText); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setBody(String body); + + /** {@inheritDoc} */ + @Override + default ExtendedLogRecordBuilder setBody(Value body) { + setBody(body.asString()); + return this; + } + + /** + * Sets the event name, which identifies the class / type of the Event. + * + *

    This name should uniquely identify the event structure (both attributes and body). A log + * record with a non-empty event name is an Event. + */ + @Override + ExtendedLogRecordBuilder setEventName(String eventName); + + /** {@inheritDoc} */ + @SuppressWarnings("unchecked") + @Override + default ExtendedLogRecordBuilder setAllAttributes(Attributes attributes) { + if (attributes == null || attributes.isEmpty()) { + return this; + } + attributes.forEach( + (attributeKey, value) -> setAttribute((AttributeKey) attributeKey, value)); + return this; + } + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setAttribute(AttributeKey key, @Nullable T value); + + /** {@inheritDoc} */ + @Override + ExtendedLogRecordBuilder setException(Throwable throwable); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedLogger.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedLogger.java new file mode 100644 index 00000000000..b28259c31d8 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/logs/ExtendedLogger.java @@ -0,0 +1,15 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.logs; + +import io.opentelemetry.api.logs.Logger; + +/** Extended {@link Logger} with experimental APIs. */ +public interface ExtendedLogger extends Logger { + + @Override + ExtendedLogRecordBuilder logRecordBuilder(); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleCounter.java new file mode 100644 index 00000000000..624285e9758 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleCounter.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link DoubleCounter} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedDoubleCounter#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #add(double)} calls + * record directly without the per-recording attribute processing and map lookup that {@link + * DoubleCounter#add(double, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundDoubleCounter { + + /** + * Records a value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The increment amount. MUST be non-negative. + */ + void add(double value); + + /** + * Records a value against the bound attributes, with an explicit {@link Context}. + * + * @param value The increment amount. MUST be non-negative. + * @param context The explicit context to associate with this measurement. + */ + void add(double value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleGauge.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleGauge.java new file mode 100644 index 00000000000..b2c1d20c142 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleGauge.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleGauge; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link DoubleGauge} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedDoubleGauge#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #set(double)} calls + * record directly without the per-recording attribute processing and map lookup that {@link + * DoubleGauge#set(double, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundDoubleGauge { + + /** + * Records the gauge value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The current gauge value. + */ + void set(double value); + + /** + * Records the gauge value against the bound attributes, with an explicit {@link Context}. + * + * @param value The current gauge value. + * @param context The explicit context to associate with this measurement. + */ + void set(double value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleHistogram.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleHistogram.java new file mode 100644 index 00000000000..ae3d0d24b1d --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleHistogram.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link DoubleHistogram} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedDoubleHistogram#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #record(double)} calls + * record directly without the per-recording attribute processing and map lookup that {@link + * DoubleHistogram#record(double, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundDoubleHistogram { + + /** + * Records a value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The amount of the measurement. MUST be non-negative. + */ + void record(double value); + + /** + * Records a value against the bound attributes, with an explicit {@link Context}. + * + * @param value The amount of the measurement. MUST be non-negative. + * @param context The explicit context to associate with this measurement. + */ + void record(double value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleUpDownCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleUpDownCounter.java new file mode 100644 index 00000000000..44ac044a300 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundDoubleUpDownCounter.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link DoubleUpDownCounter} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedDoubleUpDownCounter#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #add(double)} calls + * record directly without the per-recording attribute processing and map lookup that {@link + * DoubleUpDownCounter#add(double, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundDoubleUpDownCounter { + + /** + * Records a value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The increment amount. May be positive, negative or zero. + */ + void add(double value); + + /** + * Records a value against the bound attributes, with an explicit {@link Context}. + * + * @param value The increment amount. May be positive, negative or zero. + * @param context The explicit context to associate with this measurement. + */ + void add(double value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongCounter.java new file mode 100644 index 00000000000..294b7d3de61 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongCounter.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link LongCounter} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedLongCounter#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #add(long)} calls record + * directly without the per-recording attribute processing and map lookup that {@link + * LongCounter#add(long, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundLongCounter { + + /** + * Records a value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The increment amount. MUST be non-negative. + */ + void add(long value); + + /** + * Records a value against the bound attributes, with an explicit {@link Context}. + * + * @param value The increment amount. MUST be non-negative. + * @param context The explicit context to associate with this measurement. + */ + void add(long value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongGauge.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongGauge.java new file mode 100644 index 00000000000..6e8fab07339 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongGauge.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongGauge; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link LongGauge} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedLongGauge#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #set(long)} calls record + * directly without the per-recording attribute processing and map lookup that {@link + * LongGauge#set(long, Attributes)} performs. This is useful when the set of attribute combinations + * is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundLongGauge { + + /** + * Records the gauge value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The current gauge value. + */ + void set(long value); + + /** + * Records the gauge value against the bound attributes, with an explicit {@link Context}. + * + * @param value The current gauge value. + * @param context The explicit context to associate with this measurement. + */ + void set(long value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongHistogram.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongHistogram.java new file mode 100644 index 00000000000..63a77a0bde7 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongHistogram.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link LongHistogram} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedLongHistogram#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #record(long)} calls + * record directly without the per-recording attribute processing and map lookup that {@link + * LongHistogram#record(long, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundLongHistogram { + + /** + * Records a value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The amount of the measurement. MUST be non-negative. + */ + void record(long value); + + /** + * Records a value against the bound attributes, with an explicit {@link Context}. + * + * @param value The amount of the measurement. MUST be non-negative. + * @param context The explicit context to associate with this measurement. + */ + void record(long value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongUpDownCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongUpDownCounter.java new file mode 100644 index 00000000000..85c2e5fbbb6 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/BoundLongUpDownCounter.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.context.Context; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A {@link LongUpDownCounter} bound to a fixed set of {@link Attributes}, obtained via {@link + * ExtendedLongUpDownCounter#bind(Attributes)}. + * + *

    Binding resolves the underlying timeseries once, so subsequent {@link #add(long)} calls record + * directly without the per-recording attribute processing and map lookup that {@link + * LongUpDownCounter#add(long, Attributes)} performs. This is useful when the set of attribute + * combinations is known ahead of time and the same series is recorded to repeatedly. + */ +@ThreadSafe +public interface BoundLongUpDownCounter { + + /** + * Records a value against the bound attributes. + * + *

    Note: This may use {@code Context.current()} to pull the context associated with this + * measurement. + * + * @param value The increment amount. May be positive, negative or zero. + */ + void add(long value); + + /** + * Records a value against the bound attributes, with an explicit {@link Context}. + * + * @param value The increment amount. May be positive, negative or zero. + * @param context The explicit context to associate with this measurement. + */ + void add(long value, Context context); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeter.java new file mode 100644 index 00000000000..e8ef921b202 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeter.java @@ -0,0 +1,606 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.BatchCallback; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.DoubleCounterBuilder; +import io.opentelemetry.api.metrics.DoubleGauge; +import io.opentelemetry.api.metrics.DoubleGaugeBuilder; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.DoubleHistogramBuilder; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; +import io.opentelemetry.api.metrics.DoubleUpDownCounterBuilder; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongCounterBuilder; +import io.opentelemetry.api.metrics.LongGauge; +import io.opentelemetry.api.metrics.LongGaugeBuilder; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.api.metrics.LongHistogramBuilder; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.LongUpDownCounterBuilder; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.ObservableDoubleCounter; +import io.opentelemetry.api.metrics.ObservableDoubleGauge; +import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; +import io.opentelemetry.api.metrics.ObservableDoubleUpDownCounter; +import io.opentelemetry.api.metrics.ObservableLongCounter; +import io.opentelemetry.api.metrics.ObservableLongGauge; +import io.opentelemetry.api.metrics.ObservableLongMeasurement; +import io.opentelemetry.api.metrics.ObservableLongUpDownCounter; +import io.opentelemetry.api.metrics.ObservableMeasurement; +import io.opentelemetry.context.Context; +import java.util.function.Consumer; +import javax.annotation.concurrent.ThreadSafe; + +/** + * No-op implementation of {@link Meter}. + * + *

    This implementation should induce as close to zero overhead as possible. + */ +@ThreadSafe +class ExtendedDefaultMeter implements Meter { + + private static final Meter INSTANCE = new ExtendedDefaultMeter(); + + private static final LongCounterBuilder NOOP_LONG_COUNTER_BUILDER = new NoopLongCounterBuilder(); + private static final LongUpDownCounterBuilder NOOP_LONG_UP_DOWN_COUNTER_BUILDER = + new NoopLongUpDownCounterBuilder(); + private static final DoubleHistogramBuilder NOOP_DOUBLE_HISTOGRAM_BUILDER = + new NoopDoubleHistogramBuilder(); + private static final DoubleGaugeBuilder NOOP_DOUBLE_GAUGE_BUILDER = new NoopDoubleGaugeBuilder(); + private static final BatchCallback NOOP_BATCH_CALLBACK = new BatchCallback() {}; + private static final ObservableDoubleMeasurement NOOP_OBSERVABLE_DOUBLE_MEASUREMENT = + new NoopObservableDoubleMeasurement(); + private static final ObservableLongMeasurement NOOP_OBSERVABLE_LONG_MEASUREMENT = + new NoopObservableLongMeasurement(); + + static Meter getNoop() { + return INSTANCE; + } + + @Override + public LongCounterBuilder counterBuilder(String name) { + return NOOP_LONG_COUNTER_BUILDER; + } + + @Override + public LongUpDownCounterBuilder upDownCounterBuilder(String name) { + return NOOP_LONG_UP_DOWN_COUNTER_BUILDER; + } + + @Override + public DoubleHistogramBuilder histogramBuilder(String name) { + return NOOP_DOUBLE_HISTOGRAM_BUILDER; + } + + @Override + public DoubleGaugeBuilder gaugeBuilder(String name) { + return NOOP_DOUBLE_GAUGE_BUILDER; + } + + @Override + public BatchCallback batchCallback( + Runnable callback, + ObservableMeasurement observableMeasurement, + ObservableMeasurement... additionalMeasurements) { + return NOOP_BATCH_CALLBACK; + } + + private ExtendedDefaultMeter() {} + + private static class NoopLongCounter implements ExtendedLongCounter { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void add(long value, Attributes attributes, Context context) {} + + @Override + public void add(long value, Attributes attributes) {} + + @Override + public void add(long value) {} + + @Override + public BoundLongCounter bind(Attributes attributes) { + return NOOP_BOUND_LONG_COUNTER; + } + } + + private static final BoundLongCounter NOOP_BOUND_LONG_COUNTER = + new BoundLongCounter() { + @Override + public void add(long value) {} + + @Override + public void add(long value, Context context) {} + }; + + private static final BoundDoubleCounter NOOP_BOUND_DOUBLE_COUNTER = + new BoundDoubleCounter() { + @Override + public void add(double value) {} + + @Override + public void add(double value, Context context) {} + }; + + private static final BoundLongUpDownCounter NOOP_BOUND_LONG_UP_DOWN_COUNTER = + new BoundLongUpDownCounter() { + @Override + public void add(long value) {} + + @Override + public void add(long value, Context context) {} + }; + + private static final BoundDoubleUpDownCounter NOOP_BOUND_DOUBLE_UP_DOWN_COUNTER = + new BoundDoubleUpDownCounter() { + @Override + public void add(double value) {} + + @Override + public void add(double value, Context context) {} + }; + + private static final BoundLongHistogram NOOP_BOUND_LONG_HISTOGRAM = + new BoundLongHistogram() { + @Override + public void record(long value) {} + + @Override + public void record(long value, Context context) {} + }; + + private static final BoundDoubleHistogram NOOP_BOUND_DOUBLE_HISTOGRAM = + new BoundDoubleHistogram() { + @Override + public void record(double value) {} + + @Override + public void record(double value, Context context) {} + }; + + private static final BoundLongGauge NOOP_BOUND_LONG_GAUGE = + new BoundLongGauge() { + @Override + public void set(long value) {} + + @Override + public void set(long value, Context context) {} + }; + + private static final BoundDoubleGauge NOOP_BOUND_DOUBLE_GAUGE = + new BoundDoubleGauge() { + @Override + public void set(double value) {} + + @Override + public void set(double value, Context context) {} + }; + + private static class NoopDoubleCounter implements ExtendedDoubleCounter { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void add(double value, Attributes attributes, Context context) {} + + @Override + public void add(double value, Attributes attributes) {} + + @Override + public void add(double value) {} + + @Override + public BoundDoubleCounter bind(Attributes attributes) { + return NOOP_BOUND_DOUBLE_COUNTER; + } + } + + private static class NoopLongCounterBuilder implements ExtendedLongCounterBuilder { + private static final LongCounter NOOP_COUNTER = new NoopLongCounter(); + private static final ObservableLongCounter NOOP_OBSERVABLE_COUNTER = + new ObservableLongCounter() {}; + private static final DoubleCounterBuilder NOOP_DOUBLE_COUNTER_BUILDER = + new NoopDoubleCounterBuilder(); + + @Override + public LongCounterBuilder setDescription(String description) { + return this; + } + + @Override + public LongCounterBuilder setUnit(String unit) { + return this; + } + + @Override + public DoubleCounterBuilder ofDoubles() { + return NOOP_DOUBLE_COUNTER_BUILDER; + } + + @Override + public LongCounter build() { + return NOOP_COUNTER; + } + + @Override + public ObservableLongCounter buildWithCallback(Consumer callback) { + return NOOP_OBSERVABLE_COUNTER; + } + + @Override + public ObservableLongMeasurement buildObserver() { + return NOOP_OBSERVABLE_LONG_MEASUREMENT; + } + } + + private static class NoopDoubleCounterBuilder implements ExtendedDoubleCounterBuilder { + private static final DoubleCounter NOOP_COUNTER = new NoopDoubleCounter(); + private static final ObservableDoubleCounter NOOP_OBSERVABLE_COUNTER = + new ObservableDoubleCounter() {}; + + @Override + public DoubleCounterBuilder setDescription(String description) { + return this; + } + + @Override + public DoubleCounterBuilder setUnit(String unit) { + return this; + } + + @Override + public DoubleCounter build() { + return NOOP_COUNTER; + } + + @Override + public ObservableDoubleCounter buildWithCallback( + Consumer callback) { + return NOOP_OBSERVABLE_COUNTER; + } + + @Override + public ObservableDoubleMeasurement buildObserver() { + return NOOP_OBSERVABLE_DOUBLE_MEASUREMENT; + } + } + + private static class NoopLongUpDownCounter implements ExtendedLongUpDownCounter { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void add(long value, Attributes attributes, Context context) {} + + @Override + public void add(long value, Attributes attributes) {} + + @Override + public void add(long value) {} + + @Override + public BoundLongUpDownCounter bind(Attributes attributes) { + return NOOP_BOUND_LONG_UP_DOWN_COUNTER; + } + } + + private static class NoopDoubleUpDownCounter implements ExtendedDoubleUpDownCounter { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void add(double value, Attributes attributes, Context context) {} + + @Override + public void add(double value, Attributes attributes) {} + + @Override + public void add(double value) {} + + @Override + public BoundDoubleUpDownCounter bind(Attributes attributes) { + return NOOP_BOUND_DOUBLE_UP_DOWN_COUNTER; + } + } + + private static class NoopLongUpDownCounterBuilder implements ExtendedLongUpDownCounterBuilder { + private static final LongUpDownCounter NOOP_UP_DOWN_COUNTER = new NoopLongUpDownCounter() {}; + private static final ObservableLongUpDownCounter NOOP_OBSERVABLE_UP_DOWN_COUNTER = + new ObservableLongUpDownCounter() {}; + private static final DoubleUpDownCounterBuilder NOOP_DOUBLE_UP_DOWN_COUNTER_BUILDER = + new NoopDoubleUpDownCounterBuilder(); + + @Override + public LongUpDownCounterBuilder setDescription(String description) { + return this; + } + + @Override + public LongUpDownCounterBuilder setUnit(String unit) { + return this; + } + + @Override + public DoubleUpDownCounterBuilder ofDoubles() { + return NOOP_DOUBLE_UP_DOWN_COUNTER_BUILDER; + } + + @Override + public LongUpDownCounter build() { + return NOOP_UP_DOWN_COUNTER; + } + + @Override + public ObservableLongUpDownCounter buildWithCallback( + Consumer callback) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER; + } + + @Override + public ObservableLongMeasurement buildObserver() { + return NOOP_OBSERVABLE_LONG_MEASUREMENT; + } + } + + private static class NoopDoubleUpDownCounterBuilder + implements ExtendedDoubleUpDownCounterBuilder { + private static final DoubleUpDownCounter NOOP_UP_DOWN_COUNTER = + new NoopDoubleUpDownCounter() {}; + private static final ObservableDoubleUpDownCounter NOOP_OBSERVABLE_UP_DOWN_COUNTER = + new ObservableDoubleUpDownCounter() {}; + + @Override + public DoubleUpDownCounterBuilder setDescription(String description) { + return this; + } + + @Override + public DoubleUpDownCounterBuilder setUnit(String unit) { + return this; + } + + @Override + public DoubleUpDownCounter build() { + return NOOP_UP_DOWN_COUNTER; + } + + @Override + public ObservableDoubleUpDownCounter buildWithCallback( + Consumer callback) { + return NOOP_OBSERVABLE_UP_DOWN_COUNTER; + } + + @Override + public ObservableDoubleMeasurement buildObserver() { + return NOOP_OBSERVABLE_DOUBLE_MEASUREMENT; + } + } + + private static class NoopDoubleHistogram implements ExtendedDoubleHistogram { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void record(double value, Attributes attributes, Context context) {} + + @Override + public void record(double value, Attributes attributes) {} + + @Override + public void record(double value) {} + + @Override + public BoundDoubleHistogram bind(Attributes attributes) { + return NOOP_BOUND_DOUBLE_HISTOGRAM; + } + } + + private static class NoopLongHistogram implements ExtendedLongHistogram { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void record(long value, Attributes attributes, Context context) {} + + @Override + public void record(long value, Attributes attributes) {} + + @Override + public void record(long value) {} + + @Override + public BoundLongHistogram bind(Attributes attributes) { + return NOOP_BOUND_LONG_HISTOGRAM; + } + } + + private static class NoopDoubleHistogramBuilder implements ExtendedDoubleHistogramBuilder { + private static final DoubleHistogram NOOP = new NoopDoubleHistogram(); + private static final LongHistogramBuilder NOOP_LONG_HISTOGRAM_BUILDER = + new NoopLongHistogramBuilder(); + + @Override + public DoubleHistogramBuilder setDescription(String description) { + return this; + } + + @Override + public DoubleHistogramBuilder setUnit(String unit) { + return this; + } + + @Override + public LongHistogramBuilder ofLongs() { + return NOOP_LONG_HISTOGRAM_BUILDER; + } + + @Override + public DoubleHistogram build() { + return NOOP; + } + } + + private static class NoopLongHistogramBuilder implements ExtendedLongHistogramBuilder { + private static final LongHistogram NOOP = new NoopLongHistogram(); + + @Override + public LongHistogramBuilder setDescription(String description) { + return this; + } + + @Override + public LongHistogramBuilder setUnit(String unit) { + return this; + } + + @Override + public LongHistogram build() { + return NOOP; + } + } + + private static class NoopDoubleGaugeBuilder implements ExtendedDoubleGaugeBuilder { + private static final ObservableDoubleGauge NOOP_OBSERVABLE_GAUGE = + new ObservableDoubleGauge() {}; + private static final LongGaugeBuilder NOOP_LONG_GAUGE_BUILDER = new NoopLongGaugeBuilder(); + private static final NoopDoubleGauge NOOP_GAUGE = new NoopDoubleGauge(); + + @Override + public DoubleGaugeBuilder setDescription(String description) { + return this; + } + + @Override + public DoubleGaugeBuilder setUnit(String unit) { + return this; + } + + @Override + public LongGaugeBuilder ofLongs() { + return NOOP_LONG_GAUGE_BUILDER; + } + + @Override + public ObservableDoubleGauge buildWithCallback(Consumer callback) { + return NOOP_OBSERVABLE_GAUGE; + } + + @Override + public ObservableDoubleMeasurement buildObserver() { + return NOOP_OBSERVABLE_DOUBLE_MEASUREMENT; + } + + @Override + public DoubleGauge build() { + return NOOP_GAUGE; + } + } + + private static class NoopDoubleGauge implements ExtendedDoubleGauge { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void set(double value) {} + + @Override + public void set(double value, Attributes attributes) {} + + @Override + public void set(double value, Attributes attributes, Context context) {} + + @Override + public BoundDoubleGauge bind(Attributes attributes) { + return NOOP_BOUND_DOUBLE_GAUGE; + } + } + + private static class NoopLongGaugeBuilder implements ExtendedLongGaugeBuilder { + private static final ObservableLongGauge NOOP_OBSERVABLE_GAUGE = new ObservableLongGauge() {}; + private static final NoopLongGauge NOOP_GAUGE = new NoopLongGauge(); + + @Override + public LongGaugeBuilder setDescription(String description) { + return this; + } + + @Override + public LongGaugeBuilder setUnit(String unit) { + return this; + } + + @Override + public ObservableLongGauge buildWithCallback(Consumer callback) { + return NOOP_OBSERVABLE_GAUGE; + } + + @Override + public ObservableLongMeasurement buildObserver() { + return NOOP_OBSERVABLE_LONG_MEASUREMENT; + } + + @Override + public LongGauge build() { + return NOOP_GAUGE; + } + } + + private static class NoopLongGauge implements ExtendedLongGauge { + @Override + public boolean isEnabled() { + return false; + } + + @Override + public void set(long value) {} + + @Override + public void set(long value, Attributes attributes) {} + + @Override + public void set(long value, Attributes attributes, Context context) {} + + @Override + public BoundLongGauge bind(Attributes attributes) { + return NOOP_BOUND_LONG_GAUGE; + } + } + + private static class NoopObservableDoubleMeasurement implements ObservableDoubleMeasurement { + @Override + public void record(double value) {} + + @Override + public void record(double value, Attributes attributes) {} + } + + private static class NoopObservableLongMeasurement implements ObservableLongMeasurement { + @Override + public void record(long value) {} + + @Override + public void record(long value, Attributes attributes) {} + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeterProvider.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeterProvider.java new file mode 100644 index 00000000000..3eeca2081f8 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeterProvider.java @@ -0,0 +1,45 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterBuilder; +import io.opentelemetry.api.metrics.MeterProvider; + +/** A {@link MeterProvider} that does nothing. */ +public class ExtendedDefaultMeterProvider implements MeterProvider { + @Override + public MeterBuilder meterBuilder(String instrumentationScopeName) { + return BUILDER_INSTANCE; + } + + private static final ExtendedDefaultMeterProvider INSTANCE = new ExtendedDefaultMeterProvider(); + private static final MeterBuilder BUILDER_INSTANCE = new NoopMeterBuilder(); + + public static MeterProvider getNoop() { + return INSTANCE; + } + + private ExtendedDefaultMeterProvider() {} + + private static class NoopMeterBuilder implements MeterBuilder { + + @Override + public MeterBuilder setSchemaUrl(String schemaUrl) { + return this; + } + + @Override + public MeterBuilder setInstrumentationVersion(String instrumentationScopeVersion) { + return this; + } + + @Override + public Meter build() { + return ExtendedDefaultMeter.getNoop(); + } + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleCounter.java new file mode 100644 index 00000000000..7853163c737 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleCounter.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleCounter; + +/** Extended {@link DoubleCounter} with experimental APIs. */ +public interface ExtendedDoubleCounter extends DoubleCounter { + + /** + * Binds this counter to the given {@code attributes}, returning a {@link BoundDoubleCounter} that + * records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #add(double, Attributes)}. Prefer this when the + * set of attribute combinations is known ahead of time and the same series is recorded to + * repeatedly. + */ + BoundDoubleCounter bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleCounterBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleCounterBuilder.java new file mode 100644 index 00000000000..d601318c87f --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleCounterBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.DoubleCounterBuilder; +import java.util.List; + +/** Extended {@link DoubleCounterBuilder} with experimental APIs. */ +public interface ExtendedDoubleCounterBuilder extends DoubleCounterBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this counter. + */ + default ExtendedDoubleCounterBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleGauge.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleGauge.java new file mode 100644 index 00000000000..17fe751a3dc --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleGauge.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleGauge; + +/** Extended {@link DoubleGauge} with experimental APIs. */ +public interface ExtendedDoubleGauge extends DoubleGauge { + + /** + * Binds this gauge to the given {@code attributes}, returning a {@link BoundDoubleGauge} that + * records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #set(double, Attributes)}. Prefer this when the + * set of attribute combinations is known ahead of time and the same series is recorded to + * repeatedly. + */ + BoundDoubleGauge bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleGaugeBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleGaugeBuilder.java new file mode 100644 index 00000000000..eb576559609 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleGaugeBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.DoubleGaugeBuilder; +import java.util.List; + +/** Extended {@link DoubleGaugeBuilder} with experimental APIs. */ +public interface ExtendedDoubleGaugeBuilder extends DoubleGaugeBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this gauge. + */ + default ExtendedDoubleGaugeBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleHistogram.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleHistogram.java new file mode 100644 index 00000000000..b717a835970 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleHistogram.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; + +/** Extended {@link DoubleHistogram} with experimental APIs. */ +public interface ExtendedDoubleHistogram extends DoubleHistogram { + + /** + * Binds this histogram to the given {@code attributes}, returning a {@link BoundDoubleHistogram} + * that records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #record(double, Attributes)}. Prefer this when + * the set of attribute combinations is known ahead of time and the same series is recorded to + * repeatedly. + */ + BoundDoubleHistogram bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleHistogramBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleHistogramBuilder.java new file mode 100644 index 00000000000..8caf8f372f0 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleHistogramBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.DoubleHistogramBuilder; +import java.util.List; + +/** Extended {@link DoubleHistogramBuilder} with experimental APIs. */ +public interface ExtendedDoubleHistogramBuilder extends DoubleHistogramBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this histogram. + */ + default ExtendedDoubleHistogramBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleUpDownCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleUpDownCounter.java new file mode 100644 index 00000000000..4c024d9aca2 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleUpDownCounter.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; + +/** Extended {@link DoubleUpDownCounter} with experimental APIs. */ +public interface ExtendedDoubleUpDownCounter extends DoubleUpDownCounter { + + /** + * Binds this counter to the given {@code attributes}, returning a {@link + * BoundDoubleUpDownCounter} that records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #add(double, Attributes)}. Prefer this when the + * set of attribute combinations is known ahead of time and the same series is recorded to + * repeatedly. + */ + BoundDoubleUpDownCounter bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleUpDownCounterBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleUpDownCounterBuilder.java new file mode 100644 index 00000000000..8262b448b13 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedDoubleUpDownCounterBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.DoubleUpDownCounterBuilder; +import java.util.List; + +/** Extended {@link DoubleUpDownCounterBuilder} with experimental APIs. */ +public interface ExtendedDoubleUpDownCounterBuilder extends DoubleUpDownCounterBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this up down counter. + */ + default ExtendedDoubleUpDownCounterBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongCounter.java new file mode 100644 index 00000000000..77073f05cef --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongCounter.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; + +/** Extended {@link LongCounter} with experimental APIs. */ +public interface ExtendedLongCounter extends LongCounter { + + /** + * Binds this counter to the given {@code attributes}, returning a {@link BoundLongCounter} that + * records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #add(long, Attributes)}. Prefer this when the set + * of attribute combinations is known ahead of time and the same series is recorded to repeatedly. + */ + BoundLongCounter bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongCounterBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongCounterBuilder.java new file mode 100644 index 00000000000..04b7ae6f633 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongCounterBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.LongCounterBuilder; +import java.util.List; + +/** Extended {@link LongCounterBuilder} with experimental APIs. */ +public interface ExtendedLongCounterBuilder extends LongCounterBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this counter. + */ + default ExtendedLongCounterBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongGauge.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongGauge.java new file mode 100644 index 00000000000..f283477bdd7 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongGauge.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongGauge; + +/** Extended {@link LongGauge} with experimental APIs. */ +public interface ExtendedLongGauge extends LongGauge { + + /** + * Binds this gauge to the given {@code attributes}, returning a {@link BoundLongGauge} that + * records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #set(long, Attributes)}. Prefer this when the set + * of attribute combinations is known ahead of time and the same series is recorded to repeatedly. + */ + BoundLongGauge bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongGaugeBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongGaugeBuilder.java new file mode 100644 index 00000000000..db05e0958f3 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongGaugeBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.LongGaugeBuilder; +import java.util.List; + +/** Extended {@link LongGaugeBuilder} with experimental APIs. */ +public interface ExtendedLongGaugeBuilder extends LongGaugeBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this gauge. + */ + default ExtendedLongGaugeBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongHistogram.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongHistogram.java new file mode 100644 index 00000000000..4c932126099 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongHistogram.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongHistogram; + +/** Extended {@link LongHistogram} with experimental APIs. */ +public interface ExtendedLongHistogram extends LongHistogram { + + /** + * Binds this histogram to the given {@code attributes}, returning a {@link BoundLongHistogram} + * that records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #record(long, Attributes)}. Prefer this when the + * set of attribute combinations is known ahead of time and the same series is recorded to + * repeatedly. + */ + BoundLongHistogram bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongHistogramBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongHistogramBuilder.java new file mode 100644 index 00000000000..9986443f143 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongHistogramBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.LongHistogramBuilder; +import java.util.List; + +/** Extended {@link LongHistogramBuilder} with experimental APIs. */ +public interface ExtendedLongHistogramBuilder extends LongHistogramBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this histogram. + */ + default ExtendedLongHistogramBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongUpDownCounter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongUpDownCounter.java new file mode 100644 index 00000000000..666c9f9b07f --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongUpDownCounter.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongUpDownCounter; + +/** Extended {@link LongUpDownCounter} with experimental APIs. */ +public interface ExtendedLongUpDownCounter extends LongUpDownCounter { + + /** + * Binds this counter to the given {@code attributes}, returning a {@link BoundLongUpDownCounter} + * that records to the corresponding timeseries directly. + * + *

    Binding resolves the underlying timeseries once, eliminating the per-recording attribute + * processing and map lookup performed by {@link #add(long, Attributes)}. Prefer this when the set + * of attribute combinations is known ahead of time and the same series is recorded to repeatedly. + */ + BoundLongUpDownCounter bind(Attributes attributes); + + // keep this class even if it is empty, since experimental methods may be added in the future. +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongUpDownCounterBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongUpDownCounterBuilder.java new file mode 100644 index 00000000000..b1d8c2f0b18 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/metrics/ExtendedLongUpDownCounterBuilder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.LongUpDownCounterBuilder; +import java.util.List; + +/** Extended {@link LongUpDownCounterBuilder} with experimental APIs. */ +public interface ExtendedLongUpDownCounterBuilder extends LongUpDownCounterBuilder { + + /** + * Specify the attribute advice, which suggests the recommended set of attribute keys to be used + * for this up down counter. + */ + default ExtendedLongUpDownCounterBuilder setAttributesAdvice(List> attributes) { + return this; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/CaseInsensitiveMap.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/CaseInsensitiveMap.java new file mode 100644 index 00000000000..64a33350508 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/CaseInsensitiveMap.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import javax.annotation.Nullable; + +class CaseInsensitiveMap extends HashMap { + + private static final long serialVersionUID = -4202518750189126871L; + + CaseInsensitiveMap() {} + + CaseInsensitiveMap(Map carrier) { + if (carrier != null) { + this.putAll(carrier); + } + } + + @Override + public String put(String key, String value) { + return super.put(getKeyLowerCase(key), value); + } + + @Override + public void putAll(Map m) { + m.forEach(this::put); + } + + private static String getKeyLowerCase(String key) { + return key.toLowerCase(Locale.ROOT); + } + + @Override + @Nullable + public String get(Object key) { + return super.get(getKeyLowerCase((String) key)); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/EnvironmentGetter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/EnvironmentGetter.java new file mode 100644 index 00000000000..9649afc01b4 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/EnvironmentGetter.java @@ -0,0 +1,100 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import io.opentelemetry.context.propagation.TextMapGetter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * A {@link TextMapGetter} that extracts context from a map carrier containing environment + * variables. + * + *

    This is useful when a child process extracts propagated context from environment variables + * that an application placed in the child process environment. For example: + * + *

    {@code
    + * Map env = System.getenv();
    + * Context context = contextPropagators.getTextMapPropagator()
    + *     .extract(Context.current(), env, EnvironmentGetter.getInstance());
    + * }
    + * + *

    This getter automatically normalizes keys as environment variable names: + * + *

      + *
    • Replaces an empty key with a single underscore ({@code _}) + *
    • Converts ASCII letters to uppercase (e.g., {@code traceparent} becomes {@code TRACEPARENT}) + *
    • Replaces every character that is not an ASCII letter, digit, or underscore with an + * underscore + *
    • Prepends an underscore if the result would otherwise start with an ASCII digit + *
    + * + *

    Values are treated as opaque strings. Any propagation-format-specific validation or parsing is + * the responsibility of the propagator, not this carrier. + * + *

    If the underlying carrier performs case-insensitive lookup, as Windows environment variable + * lookup does, reading a normalized key may resolve an entry whose stored name differs only by + * case. + * + * @see Environment + * Variable Format Restrictions + */ +public final class EnvironmentGetter implements TextMapGetter> { + + private static final AtomicBoolean LOG_KEYS_CALLED = new AtomicBoolean(false); + private static final Logger LOGGER = Logger.getLogger(EnvironmentGetter.class.getName()); + private static final EnvironmentGetter INSTANCE = new EnvironmentGetter(); + + private EnvironmentGetter() {} + + /** Returns the singleton instance of {@link EnvironmentGetter}. */ + public static EnvironmentGetter getInstance() { + return INSTANCE; + } + + @Override + public Iterable keys(Map carrier) { + if (LOG_KEYS_CALLED.compareAndSet(false, true)) { + LOGGER.log( + Level.WARNING, + "keys() called on EnvironmentGetter. " + + "This getter returns only normalized environment variable names, which may produce unexpected results with propagators that depend on original key casing or special characters.", + new Throwable()); + } + if (carrier == null) { + return Collections.emptyList(); + } + List result = new ArrayList<>(carrier.size()); + for (String key : carrier.keySet()) { + if (EnvironmentSetter.isNormalizedKey(key)) { + result.add(key); + } + } + return Collections.unmodifiableList(result); + } + + @Nullable + @Override + public String get(@Nullable Map carrier, String key) { + if (carrier == null || key == null) { + return null; + } + String normalizedKey = EnvironmentSetter.normalizeKey(key); + return carrier.get(normalizedKey); + } + + @Override + public String toString() { + return "EnvironmentGetter"; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/EnvironmentSetter.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/EnvironmentSetter.java new file mode 100644 index 00000000000..16faeb18e0f --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/EnvironmentSetter.java @@ -0,0 +1,129 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import io.opentelemetry.context.propagation.TextMapSetter; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * A {@link TextMapSetter} that injects context into a map carrier, intended for use with + * environment variables when applications spawn child processes. + * + *

    This is useful when an application needs to propagate context to a child process via its + * environment. For example, when using {@link ProcessBuilder}: + * + *

    {@code
    + * Map env = new HashMap<>();
    + * contextPropagators.getTextMapPropagator().inject(context, env, EnvironmentSetter.getInstance());
    + * ProcessBuilder processBuilder = new ProcessBuilder();
    + * processBuilder.environment().putAll(env);
    + * }
    + * + *

    This setter automatically normalizes keys as environment variable names: + * + *

      + *
    • An empty key is replaced with a single underscore ({@code _}) + *
    • ASCII letters are converted to uppercase + *
    • Any character that is not an ASCII letter, digit, or underscore is replaced with an + * underscore + *
    • If the result would start with a digit, an underscore is prepended + *
    + * + *

    Values are treated as opaque strings. Any propagation-format-specific validation or parsing is + * the responsibility of the propagator, not this carrier. + * + *

    Size limitations: Environment variable sizes are platform-dependent (e.g., + * Windows limits name=value pairs to 32,767 characters). Callers are responsible for being aware of + * platform-specific limits when injecting context. + * + * @see Environment + * Variable Format Restrictions + */ +public final class EnvironmentSetter implements TextMapSetter> { + + private static final EnvironmentSetter INSTANCE = new EnvironmentSetter(); + + private EnvironmentSetter() {} + + /** Returns the singleton instance of {@link EnvironmentSetter}. */ + public static EnvironmentSetter getInstance() { + return INSTANCE; + } + + @Override + public void set(@Nullable Map carrier, String key, String value) { + if (carrier == null || key == null || value == null) { + return; + } + String normalizedKey = normalizeKey(key); + carrier.put(normalizedKey, value); + } + + /** + * Returns {@code true} if {@code key} is already a normalized environment variable name. + * + *

    A normalized name is non-empty, contains only uppercase ASCII letters, digits, and + * underscores, and does not start with a digit. + */ + static boolean isNormalizedKey(String key) { + if (key.isEmpty()) { + return false; + } + char first = key.charAt(0); + if (first >= '0' && first <= '9') { + return false; + } + for (int i = 0; i < key.length(); i++) { + char ch = key.charAt(i); + if (!((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_')) { + return false; + } + } + return true; + } + + /** + * Normalizes a key as an environment variable name. + * + *

      + *
    • An empty key is replaced with a single underscore ({@code _}) + *
    • ASCII letters are converted to uppercase + *
    • Any character that is not an ASCII letter, digit, or underscore is replaced with an + * underscore (including {@code .}, {@code -}, whitespace, and control characters) + *
    • If the result would start with a digit, an underscore is prepended + *
    + */ + static String normalizeKey(String key) { + if (isNormalizedKey(key)) { + return key; + } + if (key.isEmpty()) { + return "_"; + } + StringBuilder sb = new StringBuilder(key.length() + 1); + for (int i = 0; i < key.length(); i++) { + char ch = key.charAt(i); + if (ch >= 'a' && ch <= 'z') { + sb.append((char) (ch - 32)); + } else if ((ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '_') { + sb.append(ch); + } else { + sb.append('_'); + } + } + if (sb.length() > 0 && sb.charAt(0) >= '0' && sb.charAt(0) <= '9') { + sb.insert(0, '_'); + } + return sb.toString(); + } + + @Override + public String toString() { + return "EnvironmentSetter"; + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagators.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagators.java new file mode 100644 index 00000000000..e9ddb4dcdbb --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagators.java @@ -0,0 +1,81 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapGetter; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * Utility class to simplify context propagation. + * + *

    The README + * explains the use cases in more detail. + */ +public final class ExtendedContextPropagators { + + private ExtendedContextPropagators() {} + + private static final TextMapGetter> TEXT_MAP_GETTER = + new TextMapGetter>() { + @Override + public Set keys(Map carrier) { + return carrier.keySet(); + } + + @Override + @Nullable + public String get(@Nullable Map carrier, String key) { + return carrier == null ? null : carrier.get(key); + } + }; + + /** + * Injects the current context into a string map, which can then be added to HTTP headers or the + * metadata of a message. + * + * @param propagators provide the propagators from {@link OpenTelemetry#getPropagators()} + */ + public static Map getTextMapPropagationContext(ContextPropagators propagators) { + Map carrier = new HashMap<>(); + propagators + .getTextMapPropagator() + .inject( + Context.current(), + carrier, + (map, key, value) -> { + if (map != null) { + map.put(key, value); + } + }); + + return Collections.unmodifiableMap(carrier); + } + + /** + * Extract the context from a string map, which you get from HTTP headers of the metadata of a + * message you're processing. + * + * @param carrier the string map + * @param propagators provide the propagators from {@link OpenTelemetry#getPropagators()} + */ + public static Context extractTextMapPropagationContext( + Map carrier, ContextPropagators propagators) { + Context current = Context.current(); + if (carrier == null) { + return current; + } + CaseInsensitiveMap caseInsensitiveMap = new CaseInsensitiveMap(carrier); + return propagators.getTextMapPropagator().extract(current, caseInsensitiveMap, TEXT_MAP_GETTER); + } +} diff --git a/extensions/incubator/src/main/java/io/opentelemetry/extension/incubator/propagation/PassThroughPropagator.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/PassThroughPropagator.java similarity index 95% rename from extensions/incubator/src/main/java/io/opentelemetry/extension/incubator/propagation/PassThroughPropagator.java rename to api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/PassThroughPropagator.java index 64e6e40b1b5..a5f8507a13f 100644 --- a/extensions/incubator/src/main/java/io/opentelemetry/extension/incubator/propagation/PassThroughPropagator.java +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/propagation/PassThroughPropagator.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.extension.incubator.propagation; +package io.opentelemetry.api.incubator.propagation; import static java.util.Objects.requireNonNull; @@ -99,4 +99,9 @@ public Context extract(Context context, @Nullable C carrier, TextMapGetter carrier) { + setParent(ExtendedContextPropagators.extractTextMapPropagationContext(carrier, propagators)); + return this; + } + + @Override + public NoopSpanBuilder setNoParent() { + spanContext = SpanContext.getInvalid(); + return this; + } + + @Override + public NoopSpanBuilder addLink(SpanContext spanContext) { + return this; + } + + @Override + public NoopSpanBuilder addLink(SpanContext spanContext, Attributes attributes) { + return this; + } + + @Override + public NoopSpanBuilder setAttribute(String key, @Nullable String value) { + return this; + } + + @Override + public NoopSpanBuilder setAttribute(String key, long value) { + return this; + } + + @Override + public NoopSpanBuilder setAttribute(String key, double value) { + return this; + } + + @Override + public NoopSpanBuilder setAttribute(String key, boolean value) { + return this; + } + + @Override + public NoopSpanBuilder setAttribute(AttributeKey key, @Nullable T value) { + return this; + } + + @Override + public NoopSpanBuilder setAllAttributes(Attributes attributes) { + return this; + } + + @Override + public NoopSpanBuilder setSpanKind(SpanKind spanKind) { + return this; + } + + @Override + public NoopSpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit) { + return this; + } + + @Override + public T startAndCall(SpanCallable spanCallable) throws E { + return spanCallable.callInSpan(); + } + + @Override + public T startAndCall( + SpanCallable spanCallable, BiConsumer handleException) throws E { + return spanCallable.callInSpan(); + } + + @Override + public void startAndRun(SpanRunnable runnable) throws E { + runnable.runInSpan(); + } + + @Override + public void startAndRun( + SpanRunnable runnable, BiConsumer handleException) throws E { + runnable.runInSpan(); + } + + private NoopSpanBuilder() {} + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerBuilder.java new file mode 100644 index 00000000000..20469674ae5 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerBuilder.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerBuilder; + +final class ExtendedDefaultTracerBuilder implements TracerBuilder { + private static final ExtendedDefaultTracerBuilder INSTANCE = new ExtendedDefaultTracerBuilder(); + + static TracerBuilder getInstance() { + return INSTANCE; + } + + @Override + public TracerBuilder setSchemaUrl(String schemaUrl) { + return this; + } + + @Override + public TracerBuilder setInstrumentationVersion(String instrumentationScopeVersion) { + return this; + } + + @Override + public Tracer build() { + return ExtendedDefaultTracer.getNoop(); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerProvider.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerProvider.java new file mode 100644 index 00000000000..ce6e897a986 --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerProvider.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerBuilder; +import io.opentelemetry.api.trace.TracerProvider; +import javax.annotation.concurrent.ThreadSafe; + +/** A no-op tracer provider supporting the incubating tracing API. */ +@ThreadSafe +public class ExtendedDefaultTracerProvider implements TracerProvider { + + private static final TracerProvider INSTANCE = new ExtendedDefaultTracerProvider(); + + public static TracerProvider getNoop() { + return INSTANCE; + } + + @Override + public Tracer get(String instrumentationScopeName) { + return ExtendedDefaultTracer.getNoop(); + } + + @Override + public Tracer get(String instrumentationScopeName, String instrumentationScopeVersion) { + return ExtendedDefaultTracer.getNoop(); + } + + @Override + public TracerBuilder tracerBuilder(String instrumentationScopeName) { + return ExtendedDefaultTracerBuilder.getInstance(); + } + + private ExtendedDefaultTracerProvider() {} +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedSpanBuilder.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedSpanBuilder.java new file mode 100644 index 00000000000..419172f10be --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedSpanBuilder.java @@ -0,0 +1,150 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanBuilder; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.propagation.ContextPropagators; +import java.time.Instant; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; + +/** Extended {@link SpanBuilder} with experimental APIs. */ +public interface ExtendedSpanBuilder extends SpanBuilder { + + /** + * Extract a span context from the given carrier and set it as parent of the span for {@link + * #startAndCall(SpanCallable)} and {@link #startAndRun(SpanRunnable)}. + * + *

    The span context will be extracted from the carrier, which you usually get from + * HTTP headers of the metadata of a message you're processing. + * + * @param propagators provide the propagators from {@link OpenTelemetry#getPropagators()} + * @param carrier the string map where to extract the span context from + */ + ExtendedSpanBuilder setParentFrom(ContextPropagators propagators, Map carrier); + + /** + * Runs the given {@link SpanCallable} inside of the span created by the given {@link + * SpanBuilder}. The span will be ended at the end of the {@link SpanCallable}. + * + *

    If an exception is thrown by the {@link SpanCallable}, the span will be marked as error, and + * the exception will be recorded. + * + * @param spanCallable the {@link SpanCallable} to call + * @param the type of the result + * @param the type of the exception + * @return the result of the {@link SpanCallable} + */ + T startAndCall(SpanCallable spanCallable) throws E; + + /** + * Runs the given {@link SpanCallable} inside of the span created by the given {@link + * SpanBuilder}. The span will be ended at the end of the {@link SpanCallable}. + * + *

    If an exception is thrown by the {@link SpanCallable}, the handleException + * consumer will be called, giving you the opportunity to handle the exception and span in a + * custom way, e.g. not marking the span as error. + * + * @param spanCallable the {@link SpanCallable} to call + * @param handleException the consumer to call when an exception is thrown + * @param the type of the result + * @param the type of the exception + * @return the result of the {@link SpanCallable} + */ + T startAndCall( + SpanCallable spanCallable, BiConsumer handleException) throws E; + + /** + * Runs the given {@link SpanRunnable} inside of the span created by the given {@link + * SpanBuilder}. The span will be ended at the end of the {@link SpanRunnable}. + * + *

    If an exception is thrown by the {@link SpanRunnable}, the span will be marked as error, and + * the exception will be recorded. + * + * @param runnable the {@link SpanRunnable} to run + * @param the type of the exception + */ + void startAndRun(SpanRunnable runnable) throws E; + + /** + * Runs the given {@link SpanRunnable} inside of the span created by the given {@link + * SpanBuilder}. The span will be ended at the end of the {@link SpanRunnable}. + * + *

    If an exception is thrown by the {@link SpanRunnable}, the handleException + * consumer will be called, giving you the opportunity to handle the exception and span in a + * custom way, e.g. not marking the span as error. + * + * @param runnable the {@link SpanRunnable} to run + * @param the type of the exception + */ + void startAndRun( + SpanRunnable runnable, BiConsumer handleException) throws E; + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setParent(Context context); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setNoParent(); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder addLink(SpanContext spanContext); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder addLink(SpanContext spanContext, Attributes attributes); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setAttribute(String key, @Nullable String value); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setAttribute(String key, long value); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setAttribute(String key, double value); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setAttribute(String key, boolean value); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setAttribute(AttributeKey key, @Nullable T value); + + /** {@inheritDoc} */ + @Override + default ExtendedSpanBuilder setAllAttributes(Attributes attributes) { + return (ExtendedSpanBuilder) SpanBuilder.super.setAllAttributes(attributes); + } + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setSpanKind(SpanKind spanKind); + + /** {@inheritDoc} */ + @Override + ExtendedSpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit); + + /** {@inheritDoc} */ + @Override + default ExtendedSpanBuilder setStartTimestamp(Instant startTimestamp) { + return (ExtendedSpanBuilder) SpanBuilder.super.setStartTimestamp(startTimestamp); + } +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedTracer.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedTracer.java new file mode 100644 index 00000000000..047f34c0d9f --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/ExtendedTracer.java @@ -0,0 +1,15 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +import io.opentelemetry.api.trace.Tracer; + +/** Extended {@link Tracer} with experimental APIs. */ +public interface ExtendedTracer extends Tracer { + + @Override + ExtendedSpanBuilder spanBuilder(String spanName); +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/SpanCallable.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/SpanCallable.java new file mode 100644 index 00000000000..881e1bd541d --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/SpanCallable.java @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +/** + * An interface for creating a lambda that is wrapped in a span, returns a value, and that may + * throw. + * + * @param Thrown exception type. + */ +@FunctionalInterface +public interface SpanCallable { + T callInSpan() throws E; +} diff --git a/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/SpanRunnable.java b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/SpanRunnable.java new file mode 100644 index 00000000000..9f245f340bf --- /dev/null +++ b/api/incubator/src/main/java/io/opentelemetry/api/incubator/trace/SpanRunnable.java @@ -0,0 +1,16 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +/** + * An interface for creating a lambda that is wrapped in a span and that may throw. + * + * @param Thrown exception type. + */ +@FunctionalInterface +public interface SpanRunnable { + void runInSpan() throws E; +} diff --git a/api/incubator/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/reflect-config.json b/api/incubator/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/reflect-config.json new file mode 100644 index 00000000000..d9abd56c422 --- /dev/null +++ b/api/incubator/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-api/reflect-config.json @@ -0,0 +1,38 @@ +[ + { + "methods": [ + { + "name": "getNoop", + "parameterTypes": [] + } + ], + "name": "io.opentelemetry.api.incubator.logs.ExtendedDefaultLoggerProvider" + }, + { + "methods": [ + { + "name": "getNoop", + "parameterTypes": [] + } + ], + "name": "io.opentelemetry.api.incubator.metrics.ExtendedDefaultMeterProvider" + }, + { + "methods": [ + { + "name": "getNoop", + "parameterTypes": [] + } + ], + "name": "io.opentelemetry.api.incubator.trace.ExtendedDefaultTracerProvider" + }, + { + "methods": [ + { + "name": "getNoop", + "parameterTypes": [] + } + ], + "name": "io.opentelemetry.api.incubator.ExtendedDefaultOpenTelemetry" + } +] diff --git a/api/incubator/src/test/java/io/opentelemetry/api/config/DeclarativeConfigPropertyUtilTest.java b/api/incubator/src/test/java/io/opentelemetry/api/config/DeclarativeConfigPropertyUtilTest.java new file mode 100644 index 00000000000..a4b3e9632cb --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/config/DeclarativeConfigPropertyUtilTest.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableMap; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.YamlDeclarativeConfigProperties; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class DeclarativeConfigPropertyUtilTest { + + @RegisterExtension + LogCapturer logCapturer = + LogCapturer.create().captureForType(YamlDeclarativeConfigProperties.class); + + @Test + void toMap_doesNotLogTypeWarnings() { + Map properties = new HashMap<>(); + properties.put("string_key", "value"); + properties.put("bool_key", true); + properties.put("int_key", 1); + properties.put("double_key", 0.25); + properties.put("map_key", Collections.singletonMap("ratio", 0.25)); + properties.put("string_list_key", Arrays.asList("a", "b")); + properties.put( + "structured_list_key", Collections.singletonList(Collections.singletonMap("k", false))); + DeclarativeConfigProperties config = + YamlDeclarativeConfigProperties.create( + properties, ComponentLoader.forClassLoader(getClass().getClassLoader())); + + Map result = DeclarativeConfigProperties.toMap(config); + + assertThat(result) + .containsExactlyInAnyOrderEntriesOf( + ImmutableMap.builder() + .put("string_key", "value") + .put("bool_key", true) + .put("int_key", 1L) + .put("double_key", 0.25) + .put("map_key", ImmutableMap.of("ratio", 0.25)) + .put("string_list_key", Arrays.asList("a", "b")) + .put("structured_list_key", Collections.singletonList(ImmutableMap.of("k", false))) + .build()); + assertThat(logCapturer.getEvents()).isEmpty(); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/config/InstrumentationConfigUtilTest.java b/api/incubator/src/test/java/io/opentelemetry/api/config/InstrumentationConfigUtilTest.java new file mode 100644 index 00000000000..63fbb8dda80 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/config/InstrumentationConfigUtilTest.java @@ -0,0 +1,160 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.config; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.incubator.config.InstrumentationConfigUtil; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.YamlDeclarativeConfigProperties; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class InstrumentationConfigUtilTest { + + /** + * See kitchen-sink.yaml. + */ + private static final String kitchenSinkInstrumentationConfig = + "instrumentation/development:\n" + + " general:\n" + + " peer:\n" + + " service_mapping:\n" + + " - peer: 1.2.3.4\n" + + " service: FooService\n" + + " - peer: 2.3.4.5\n" + + " service: BarService\n" + + " http:\n" + + " client:\n" + + " request_captured_headers:\n" + + " - client-request-header1\n" + + " - client-request-header2\n" + + " response_captured_headers:\n" + + " - client-response-header1\n" + + " - client-response-header2\n" + + " server:\n" + + " request_captured_headers:\n" + + " - server-request-header1\n" + + " - server-request-header2\n" + + " response_captured_headers:\n" + + " - server-response-header1\n" + + " - server-response-header2\n" + + " java:\n" + + " example:\n" + + " property: \"value\""; + + private static final ConfigProvider kitchenSinkConfigProvider = + toConfigProvider(kitchenSinkInstrumentationConfig); + private static final ConfigProvider emptyInstrumentationConfigProvider = + toConfigProvider("instrumentation/development:\n"); + private static final ConfigProvider emptyGeneralConfigProvider = + toConfigProvider("instrumentation/development:\n general:\n"); + private static final ConfigProvider emptyHttpConfigProvider = + toConfigProvider("instrumentation/development:\n general:\n http:\n"); + + private static ConfigProvider toConfigProvider(String configYaml) { + return SdkConfigProvider.create( + DeclarativeConfiguration.toConfigProperties( + new ByteArrayInputStream(configYaml.getBytes(StandardCharsets.UTF_8)))); + } + + @Test + void httpClientRequestCapturedHeaders() { + assertThat( + InstrumentationConfigUtil.httpClientRequestCapturedHeaders(kitchenSinkConfigProvider)) + .isEqualTo(Arrays.asList("client-request-header1", "client-request-header2")); + assertThat( + InstrumentationConfigUtil.httpClientRequestCapturedHeaders( + emptyInstrumentationConfigProvider)) + .isNull(); + assertThat( + InstrumentationConfigUtil.httpClientRequestCapturedHeaders(emptyGeneralConfigProvider)) + .isNull(); + assertThat(InstrumentationConfigUtil.httpClientRequestCapturedHeaders(emptyHttpConfigProvider)) + .isNull(); + } + + @Test + void httpClientResponseCapturedHeaders() { + assertThat( + InstrumentationConfigUtil.httpClientResponseCapturedHeaders(kitchenSinkConfigProvider)) + .isEqualTo(Arrays.asList("client-response-header1", "client-response-header2")); + assertThat( + InstrumentationConfigUtil.httpClientResponseCapturedHeaders( + emptyInstrumentationConfigProvider)) + .isNull(); + assertThat( + InstrumentationConfigUtil.httpClientResponseCapturedHeaders(emptyGeneralConfigProvider)) + .isNull(); + assertThat(InstrumentationConfigUtil.httpClientResponseCapturedHeaders(emptyHttpConfigProvider)) + .isNull(); + } + + @Test + void httpServerRequestCapturedHeaders() { + assertThat( + InstrumentationConfigUtil.httpServerRequestCapturedHeaders(kitchenSinkConfigProvider)) + .isEqualTo(Arrays.asList("server-request-header1", "server-request-header2")); + assertThat( + InstrumentationConfigUtil.httpServerRequestCapturedHeaders( + emptyInstrumentationConfigProvider)) + .isNull(); + assertThat( + InstrumentationConfigUtil.httpServerRequestCapturedHeaders(emptyGeneralConfigProvider)) + .isNull(); + assertThat(InstrumentationConfigUtil.httpServerRequestCapturedHeaders(emptyHttpConfigProvider)) + .isNull(); + } + + @Test + void httpServerResponseCapturedHeaders() { + assertThat( + InstrumentationConfigUtil.httpServerResponseCapturedHeaders(kitchenSinkConfigProvider)) + .isEqualTo(Arrays.asList("server-response-header1", "server-response-header2")); + assertThat( + InstrumentationConfigUtil.httpServerResponseCapturedHeaders( + emptyInstrumentationConfigProvider)) + .isNull(); + assertThat( + InstrumentationConfigUtil.httpServerResponseCapturedHeaders(emptyGeneralConfigProvider)) + .isNull(); + assertThat(InstrumentationConfigUtil.httpServerResponseCapturedHeaders(emptyHttpConfigProvider)) + .isNull(); + } + + @Test + void javaInstrumentationConfig() { + assertThat( + InstrumentationConfigUtil.javaInstrumentationConfig( + kitchenSinkConfigProvider, "example")) + .isNotNull() + .isInstanceOfSatisfying( + YamlDeclarativeConfigProperties.class, + exampleConfig -> + assertThat(DeclarativeConfigProperties.toMap(exampleConfig)) + .isEqualTo(ImmutableMap.of("property", "value"))); + assertThat( + InstrumentationConfigUtil.javaInstrumentationConfig(kitchenSinkConfigProvider, "foo")) + .isNull(); + assertThat( + InstrumentationConfigUtil.javaInstrumentationConfig( + emptyInstrumentationConfigProvider, "example")) + .isNull(); + assertThat( + InstrumentationConfigUtil.javaInstrumentationConfig( + emptyGeneralConfigProvider, "example")) + .isNull(); + assertThat( + InstrumentationConfigUtil.javaInstrumentationConfig(emptyHttpConfigProvider, "example")) + .isNull(); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/ConfigProviderTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/ConfigProviderTest.java new file mode 100644 index 00000000000..b5fdca1cdf6 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/ConfigProviderTest.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.incubator.config.ConfigProvider; +import org.junit.jupiter.api.Test; + +class ConfigProviderTest { + + @Test + void noopEquality() { + ConfigProvider noop = ConfigProvider.noop(); + assertThat(ConfigProvider.noop()).isSameAs(noop); + } + + @Test + void instrumentationConfigFallback() { + ConfigProvider configProvider = ConfigProvider.noop(); + assertThat(configProvider.getInstrumentationConfig()).isNotNull(); + assertThat(configProvider.getInstrumentationConfig("servlet")).isNotNull(); + assertThat(configProvider.getGeneralInstrumentationConfig()).isNotNull(); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/ExtendedOpenTelemetryTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/ExtendedOpenTelemetryTest.java new file mode 100644 index 00000000000..94bc73dabc1 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/ExtendedOpenTelemetryTest.java @@ -0,0 +1,126 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.incubator.logs.ExtendedDefaultLoggerProvider; +import io.opentelemetry.api.incubator.logs.ExtendedLogger; +import io.opentelemetry.api.incubator.metrics.ExtendedDefaultMeterProvider; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounterBuilder; +import io.opentelemetry.api.incubator.trace.ExtendedDefaultTracerProvider; +import io.opentelemetry.api.incubator.trace.ExtendedTracer; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.testing.internal.AbstractOpenTelemetryTest; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ExtendedOpenTelemetryTest extends AbstractOpenTelemetryTest { + + @Override + protected TracerProvider getTracerProvider() { + return ExtendedDefaultTracerProvider.getNoop(); + } + + @Override + protected MeterProvider getMeterProvider() { + return ExtendedDefaultMeterProvider.getNoop(); + } + + @Override + protected LoggerProvider getLoggerProvider() { + return ExtendedDefaultLoggerProvider.getNoop(); + } + + @BeforeEach + void setUp() { + GlobalOpenTelemetry.resetForTest(); + } + + @Test + void incubatingApiIsLoaded() { + assertIsExtended(OpenTelemetry.noop()); + assertIsExtended(OpenTelemetry.propagating(ContextPropagators.noop())); + } + + @Test + void globalOpenTelemetry() { + GlobalOpenTelemetry.set( + ExtendedOpenTelemetrySdk.create( + OpenTelemetrySdk.builder().build(), + SdkConfigProvider.create(DeclarativeConfigProperties.empty()))); + assertThat(GlobalOpenTelemetry.get()).isInstanceOf(ExtendedOpenTelemetry.class); + } + + private static void assertIsExtended(OpenTelemetry openTelemetry) { + assertThat(openTelemetry.getMeter("test").counterBuilder("test")) + .isInstanceOf(ExtendedLongCounterBuilder.class); + assertThat(openTelemetry.getLogsBridge().get("test")).isInstanceOf(ExtendedLogger.class); + assertThat(openTelemetry.getTracer("test")).isInstanceOf(ExtendedTracer.class); + } + + @Test + void instrumentationConfig() { + String configYaml = + "instrumentation/development:\n" + + " general:\n" + + " http:\n" + + " client:\n" + + " request_captured_headers:\n" + + " - client-request-header1\n" + + " - client-request-header2\n" + + " java:\n" + + " example:\n" + + " property: \"value\""; + + SdkConfigProvider configProvider = + SdkConfigProvider.create( + DeclarativeConfiguration.toConfigProperties( + new ByteArrayInputStream(configYaml.getBytes(StandardCharsets.UTF_8)))); + ExtendedOpenTelemetry openTelemetry = + ExtendedOpenTelemetrySdk.create(OpenTelemetrySdk.builder().build(), configProvider); + + // shortcuts to get specific instrumentation config + assertThat(openTelemetry.getInstrumentationConfig("example").getString("property")) + .isEqualTo("value"); + assertThat( + openTelemetry + .getGeneralInstrumentationConfig() + .get("http") + .get("client") + .getScalarList("request_captured_headers", String.class)) + .isEqualTo(Arrays.asList("client-request-header1", "client-request-header2")); + } + + @Test + void instrumentationConfigFallback() { + ConfigProvider configProvider = ConfigProvider.noop(); + // cannot create ExtendedOpenTelemetry with noop ConfigProvider right now, + // but will be possible once stable API is available + ExtendedOpenTelemetry openTelemetry = spy(ExtendedOpenTelemetry.class); + when(openTelemetry.getConfigProvider()).thenReturn(configProvider); + + assertThat(configProvider.getInstrumentationConfig()).isNotNull(); + assertThat(openTelemetry.getInstrumentationConfig("servlet")).isNotNull(); + assertThat(openTelemetry.getGeneralInstrumentationConfig()).isNotNull(); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesTest.java new file mode 100644 index 00000000000..30ab653dcc3 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesTest.java @@ -0,0 +1,83 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.common; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import org.junit.jupiter.api.Test; + +class ContextAttributesTest { + + @Test + void emptyContext_returnsEmptyAttributes() { + assertThat(ContextAttributes.get(Context.root())).isEqualTo(Attributes.empty()); + assertThat(ContextAttributes.get(null)).isEqualTo(Attributes.empty()); + } + + @Test + void setNullValidation() { + Context root = Context.root(); + Attributes attrs = Attributes.of(stringKey("k"), "v"); + assertThat(ContextAttributes.set(null, attrs)).isEqualTo(Context.root()); + assertThat(ContextAttributes.set(root, null)).isSameAs(root); + } + + @Test + void setReplacesExistingAndClearsWithEmpty() { + Context ctx1 = + ContextAttributes.set( + Context.root(), Attributes.of(stringKey("k1"), "v1", longKey("k2"), 2L)); + assertThat(ContextAttributes.get(ctx1)) + .isEqualTo(Attributes.of(stringKey("k1"), "v1", longKey("k2"), 2L)); + + // set() completely replaces previous attributes + Context ctx2 = ContextAttributes.set(ctx1, Attributes.of(stringKey("k3"), "v3")); + assertThat(ContextAttributes.get(ctx2)).isEqualTo(Attributes.of(stringKey("k3"), "v3")); + + // set() with empty clears attributes + Context ctxCleared = ContextAttributes.set(ctx2, Attributes.empty()); + assertThat(ContextAttributes.get(ctxCleared)).isEqualTo(Attributes.empty()); + + // set() with empty on already empty returns same context + assertThat(ContextAttributes.set(Context.root(), Attributes.empty())).isSameAs(Context.root()); + } + + @Test + void setAndGet_singleLayer() { + Attributes attrs = Attributes.of(stringKey("user.id"), "u123", longKey("retry"), 1L); + Context ctx = ContextAttributes.set(Context.root(), attrs); + + assertThat(ContextAttributes.get(ctx)).isEqualTo(attrs); + assertThat(ContextAttributes.get(Context.root())).isEqualTo(Attributes.empty()); + } + + @Test + void scopeAttachment_restoresOuterContextAttributesOnClose() { + Context outer = ContextAttributes.set(Context.root(), Attributes.of(stringKey("env"), "prod")); + try (Scope ignoredOuter = outer.makeCurrent()) { + assertThat(ContextAttributes.get(Context.current())) + .isEqualTo(Attributes.of(stringKey("env"), "prod")); + + Context inner = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("env"), "staging", stringKey("req"), "r1")); + try (Scope ignoredInner = inner.makeCurrent()) { + assertThat(ContextAttributes.get(Context.current())) + .isEqualTo(Attributes.of(stringKey("env"), "staging", stringKey("req"), "r1")); + } + + assertThat(ContextAttributes.get(Context.current())) + .isEqualTo(Attributes.of(stringKey("env"), "prod")); + } + assertThat(ContextAttributes.get(Context.current())).isEqualTo(Attributes.empty()); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesUsageTest.java new file mode 100644 index 00000000000..33f6840dbcb --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesUsageTest.java @@ -0,0 +1,178 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.common; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Demonstrating usage of {@link ContextAttributes}. */ +class ContextAttributesUsageTest { + + private InMemorySpanExporter spanExporter; + private InMemoryLogRecordExporter logExporter; + private InMemoryMetricReader metricReader; + + private Tracer tracer; + private Logger logger; + private LongCounter counter; + + @BeforeEach + void setUp() { + spanExporter = InMemorySpanExporter.create(); + logExporter = InMemoryLogRecordExporter.create(); + metricReader = InMemoryMetricReader.create(); + + SdkTracerProviderBuilder tracerProviderBuilder = + SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(spanExporter)); + SdkTracerProviderUtil.setContextScopedAttributesFilter( + tracerProviderBuilder, (scope, key) -> true); + + SdkLoggerProviderBuilder loggerProviderBuilder = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(logExporter)); + SdkLoggerProviderUtil.setContextScopedAttributesFilter( + loggerProviderBuilder, (scope, key) -> true); + + SdkMeterProviderBuilder meterProviderBuilder = + SdkMeterProvider.builder().registerMetricReader(metricReader); + SdkMeterProviderUtil.setContextScopedAttributesFilter( + meterProviderBuilder, (scope, key) -> true); + + OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider(tracerProviderBuilder.build()) + .setLoggerProvider(loggerProviderBuilder.build()) + .setMeterProvider(meterProviderBuilder.build()) + .build(); + + tracer = sdk.getTracer("usage-test"); + logger = sdk.getLogsBridge().get("usage-test"); + Meter meter = sdk.getMeter("usage-test"); + counter = meter.counterBuilder("orders_total").build(); + } + + @Test + void multiSignalPropagation() { + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("tenant.id"), "t-123", stringKey("environment"), "production")); + + try (Scope ignored = ctx.makeCurrent()) { + Span span = + tracer + .spanBuilder("process-checkout") + .setAttribute("operation.type", "checkout") + .startSpan(); + span.end(); + + logger.logRecordBuilder().setBody("checkout initiated").emit(); + + counter.add(1, Attributes.of(stringKey("currency"), "USD")); + } + + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactly(span -> + assertThat(span) + .hasName("process-checkout") + .hasAttributes( + attributeEntry("operation.type", "checkout"), + attributeEntry("tenant.id", "t-123"), + attributeEntry("environment", "production"))); + + assertThat(logExporter.getFinishedLogRecordItems()) + .satisfiesExactly(log -> + assertThat(log) + .hasBody("checkout initiated") + .hasAttributes( + attributeEntry("tenant.id", "t-123"), + attributeEntry("environment", "production"))); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("orders_total") + .hasLongSumPointsSatisfying(point -> + point + .hasValue(1) + .hasAttributes( + attributeEntry("currency", "USD"), + attributeEntry("tenant.id", "t-123"), + attributeEntry("environment", "production")))); + } + + @Test + void selectiveFiltering() { + InMemorySpanExporter localSpanExporter = InMemorySpanExporter.create(); + InMemoryMetricReader localMetricReader = InMemoryMetricReader.create(); + + SdkTracerProviderBuilder tracerBuilder = + SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(localSpanExporter)); + SdkTracerProviderUtil.setContextScopedAttributesFilter( + tracerBuilder, (scope, key) -> key.getKey().equals("tenant.id")); + + SdkMeterProviderBuilder meterBuilder = + SdkMeterProvider.builder().registerMetricReader(localMetricReader); + SdkMeterProviderUtil.setContextScopedAttributesFilter( + meterBuilder, (scope, key) -> key.getKey().equals("region")); + + OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider(tracerBuilder.build()) + .setMeterProvider(meterBuilder.build()) + .build(); + + Tracer localTracer = sdk.getTracer("usage-test"); + LongCounter localCounter = sdk.getMeter("usage-test").counterBuilder("requests").build(); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("tenant.id"), "t-999", stringKey("region"), "us-west-2")); + + try (Scope ignored = ctx.makeCurrent()) { + localTracer.spanBuilder("request").startSpan().end(); + localCounter.add(1); + } + + assertThat(localSpanExporter.getFinishedSpanItems()) + .satisfiesExactly( + span -> assertThat(span).hasAttributes(attributeEntry("tenant.id", "t-999"))); + + assertThat(localMetricReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongSumPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("region", "us-west-2")))); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/config/DeclarativeConfigPropertiesTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/config/DeclarativeConfigPropertiesTest.java new file mode 100644 index 00000000000..bb8abef5873 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/config/DeclarativeConfigPropertiesTest.java @@ -0,0 +1,146 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") +class DeclarativeConfigPropertiesTest { + + @Test + void empty() { + DeclarativeConfigProperties empty = DeclarativeConfigProperties.empty(); + assertThat(empty).isNotNull(); + assertThat(empty.getString("str")).isNull(); + assertThat(empty.getBoolean("bool")).isNull(); + assertThat(empty.getInt("int")).isNull(); + assertThat(empty.getLong("long")).isNull(); + assertThat(empty.getDouble("double")).isNull(); + assertThat(empty.getScalarList("list", String.class)).isNull(); + assertThat(empty.getStructured("struct")).isNull(); + assertThat(empty.getStructuredList("structList")).isNull(); + assertThat(empty.getPropertyKeys()).isEmpty(); + assertThat(empty.getComponentLoader()).isNotNull(); + + // Default methods with default values + assertThat(empty.getString("str", "def")).isEqualTo("def"); + assertThat(empty.getBoolean("bool", true)).isTrue(); + assertThat(empty.getInt("int", 42)).isEqualTo(42); + assertThat(empty.getLong("long", 100L)).isEqualTo(100L); + assertThat(empty.getDouble("double", 3.14)).isEqualTo(3.14); + assertThat(empty.getScalarList("list", String.class, Collections.singletonList("d"))) + .containsExactly("d"); + assertThat(empty.getStructured("struct", empty)).isSameAs(empty); + assertThat(empty.get("struct")).isNotNull(); + assertThat(empty.getStructuredList("structList", Collections.singletonList(empty))) + .containsExactly(empty); + + // Default type check methods + assertThat(empty.isString("str")).isFalse(); + assertThat(empty.isBoolean("bool")).isFalse(); + assertThat(empty.isInt("int")).isFalse(); + assertThat(empty.isLong("long")).isFalse(); + assertThat(empty.isDouble("double")).isFalse(); + } + + @Test + void toMap() { + DeclarativeConfigProperties empty = DeclarativeConfigProperties.empty(); + Map map = DeclarativeConfigProperties.toMap(empty); + assertThat(map).isNotNull().isEmpty(); + } + + @Test + void toMapWithValues() { + DeclarativeConfigProperties props = mock(DeclarativeConfigProperties.class); + DeclarativeConfigProperties subProps = mock(DeclarativeConfigProperties.class); + DeclarativeConfigProperties listItemProps = mock(DeclarativeConfigProperties.class); + + when(props.getScalarList(anyString(), any())).thenReturn(null); + when(props.getStructuredList(anyString())).thenReturn(null); + when(props.getStructured(anyString())).thenReturn(null); + + when(props.getPropertyKeys()) + .thenReturn( + new HashSet<>( + Arrays.asList( + "str", + "bool", + "long", + "double", + "strList", + "boolList", + "longList", + "doubleList", + "struct", + "structList", + "unknown"))); + + when(props.isString("str")).thenReturn(true); + when(props.getString("str")).thenReturn("hello"); + + when(props.isBoolean("bool")).thenReturn(true); + when(props.getBoolean("bool")).thenReturn(true); + + when(props.isLong("long")).thenReturn(true); + when(props.getLong("long")).thenReturn(123L); + + when(props.isDouble("double")).thenReturn(true); + when(props.getDouble("double")).thenReturn(45.67); + + when(props.getScalarList("strList", String.class)).thenReturn(Arrays.asList("a", "b")); + when(props.getScalarList("boolList", Boolean.class)).thenReturn(Arrays.asList(true, false)); + when(props.getScalarList("longList", Long.class)).thenReturn(Arrays.asList(1L, 2L)); + when(props.getScalarList("doubleList", Double.class)).thenReturn(Arrays.asList(1.1, 2.2)); + + when(subProps.getPropertyKeys()).thenReturn(Collections.singleton("subKey")); + when(subProps.isString("subKey")).thenReturn(true); + when(subProps.getString("subKey")).thenReturn("subVal"); + when(props.getStructured("struct")).thenReturn(subProps); + + when(listItemProps.getPropertyKeys()).thenReturn(Collections.singleton("itemKey")); + when(listItemProps.isLong("itemKey")).thenReturn(true); + when(listItemProps.getLong("itemKey")).thenReturn(999L); + when(props.getStructuredList("structList")) + .thenReturn(Collections.singletonList(listItemProps)); + + Map map = DeclarativeConfigProperties.toMap(props); + assertThat(map).containsEntry("str", "hello"); + assertThat(map).containsEntry("bool", true); + assertThat(map).containsEntry("long", 123L); + assertThat(map).containsEntry("double", 45.67); + assertThat(map).containsEntry("strList", Arrays.asList("a", "b")); + assertThat(map).containsEntry("boolList", Arrays.asList(true, false)); + assertThat(map).containsEntry("longList", Arrays.asList(1L, 2L)); + assertThat(map).containsEntry("doubleList", Arrays.asList(1.1, 2.2)); + assertThat(map).containsEntry("struct", Collections.singletonMap("subKey", "subVal")); + assertThat(map) + .containsEntry( + "structList", Collections.singletonList(Collections.singletonMap("itemKey", 999L))); + assertThat(map).containsEntry("unknown", null); + } + + @Test + void declarativeConfigException() { + DeclarativeConfigException ex1 = new DeclarativeConfigException("error message"); + assertThat(ex1.getMessage()).isEqualTo("error message"); + + RuntimeException cause = new RuntimeException("cause"); + DeclarativeConfigException ex2 = new DeclarativeConfigException("error with cause", cause); + assertThat(ex2.getMessage()).isEqualTo("error with cause"); + assertThat(ex2.getCause()).isSameAs(cause); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/internal/ObfuscatedExtendedOpenTelemetryTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/internal/ObfuscatedExtendedOpenTelemetryTest.java new file mode 100644 index 00000000000..5752419bb78 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/internal/ObfuscatedExtendedOpenTelemetryTest.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.incubator.ExtendedOpenTelemetry; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerBuilder; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.ContextPropagators; +import org.junit.jupiter.api.Test; + +class ObfuscatedExtendedOpenTelemetryTest { + + @Test + void delegatesAllCallsToDelegate() { + ExtendedOpenTelemetry delegate = mock(ExtendedOpenTelemetry.class); + + TracerProvider tracerProvider = mock(TracerProvider.class); + MeterProvider meterProvider = mock(MeterProvider.class); + LoggerProvider loggerProvider = mock(LoggerProvider.class); + ContextPropagators propagators = mock(ContextPropagators.class); + TracerBuilder tracerBuilder = mock(TracerBuilder.class); + ConfigProvider configProvider = mock(ConfigProvider.class); + + when(delegate.getTracerProvider()).thenReturn(tracerProvider); + when(delegate.getMeterProvider()).thenReturn(meterProvider); + when(delegate.getLogsBridge()).thenReturn(loggerProvider); + when(delegate.getPropagators()).thenReturn(propagators); + when(delegate.tracerBuilder("test-instrumentation")).thenReturn(tracerBuilder); + when(delegate.getConfigProvider()).thenReturn(configProvider); + + ObfuscatedExtendedOpenTelemetry obfuscated = new ObfuscatedExtendedOpenTelemetry(delegate); + + assertThat(obfuscated.getTracerProvider()).isSameAs(tracerProvider); + verify(delegate).getTracerProvider(); + + assertThat(obfuscated.getMeterProvider()).isSameAs(meterProvider); + verify(delegate).getMeterProvider(); + + assertThat(obfuscated.getLogsBridge()).isSameAs(loggerProvider); + verify(delegate).getLogsBridge(); + + assertThat(obfuscated.getPropagators()).isSameAs(propagators); + verify(delegate).getPropagators(); + + assertThat(obfuscated.tracerBuilder("test-instrumentation")).isSameAs(tracerBuilder); + verify(delegate).tracerBuilder("test-instrumentation"); + + assertThat(obfuscated.getConfigProvider()).isSameAs(configProvider); + verify(delegate).getConfigProvider(); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLoggerTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLoggerTest.java new file mode 100644 index 00000000000..4c81a9396cf --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedDefaultLoggerTest.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.testing.internal.AbstractDefaultLoggerTest; +import io.opentelemetry.context.Context; +import org.junit.jupiter.api.Test; + +class ExtendedDefaultLoggerTest extends AbstractDefaultLoggerTest { + + @Override + protected LoggerProvider getLoggerProvider() { + return ExtendedDefaultLoggerProvider.getNoop(); + } + + @Override + protected Logger getLogger() { + return ExtendedDefaultLogger.getNoop(); + } + + @Test + void incubatingApiIsLoaded() { + Logger logger = LoggerProvider.noop().get("test"); + assertThat(logger.isEnabled(Severity.ERROR, Context.current())).isFalse(); + assertThat(logger.isEnabled(Severity.ERROR)).isFalse(); + + assertThat(logger).isInstanceOf(ExtendedLogger.class); + assertThat(logger.isEnabled(Severity.ERROR, Context.current())).isFalse(); + ExtendedLogRecordBuilder builder = (ExtendedLogRecordBuilder) logger.logRecordBuilder(); + assertThat(builder).isInstanceOf(ExtendedLogRecordBuilder.class); + assertThat(builder.setBody(Value.of(0))).isSameAs(builder); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java new file mode 100644 index 00000000000..b8c8f48c6a7 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/logs/ExtendedLogsBridgeApiUsageTest.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.logs; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.logs.internal.LoggerConfig.disabled; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import java.util.Random; +import org.junit.jupiter.api.Test; + +/** Demonstrating usage of extended Logs Bridge API. */ +class ExtendedLogsBridgeApiUsageTest { + + @Test + void loggerEnabled() { + // Setup SdkLoggerProvider + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProviderBuilder loggerProviderBuilder = + SdkLoggerProvider.builder() + // Default resource used for demonstration purposes + .setResource(Resource.getDefault()) + // In-memory exporter used for demonstration purposes + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)); + // Disable loggerB + SdkLoggerProviderUtil.addLoggerConfiguratorCondition( + loggerProviderBuilder, nameEquals("loggerB"), disabled()); + SdkLoggerProvider loggerProvider = loggerProviderBuilder.build(); + + // Create loggerA and loggerB + ExtendedLogger loggerA = (ExtendedLogger) loggerProvider.get("loggerA"); + ExtendedLogger loggerB = (ExtendedLogger) loggerProvider.get("loggerB"); + + // Check if logger is enabled before emitting log and avoid unnecessary computation + if (loggerA.isEnabled(Severity.INFO)) { + loggerA + .logRecordBuilder() + .setSeverity(Severity.INFO) + .setBody("hello world!") + .setAllAttributes(Attributes.builder().put("result", flipCoin()).build()) + .emit(); + } + if (loggerB.isEnabled(Severity.INFO)) { + loggerB + .logRecordBuilder() + .setSeverity(Severity.INFO) + .setBody("hello world!") + .setAllAttributes(Attributes.builder().put("result", flipCoin()).build()) + .emit(); + } + + // loggerA is enabled, loggerB is disabled + assertThat(loggerA.isEnabled(Severity.INFO)).isTrue(); + assertThat(loggerB.isEnabled(Severity.INFO)).isFalse(); + + // Collected data only consists of logs from loggerA. Note, loggerB's logs would be + // omitted from the results even if logs were emitted. The check if enabled simply avoids + // unnecessary computation. + assertThat(exporter.getFinishedLogRecordItems()) + .allSatisfy(logRecordData -> + assertThat(logRecordData.getInstrumentationScopeInfo().getName()).isEqualTo("loggerA")); + } + + private static final Random random = new Random(); + + private static String flipCoin() { + return random.nextBoolean() ? "heads" : "tails"; + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java new file mode 100644 index 00000000000..dfbd103fdf1 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/BoundInstrumentUsageTest.java @@ -0,0 +1,130 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Random; +import org.junit.jupiter.api.Test; + +/** + * Demonstrates usage of bound instruments for a dice-rolling scenario. + * + *

    When the full set of attribute combinations is known ahead of time β€” as it is here, with 6 + * fixed die faces β€” bound instruments eliminate the per-recording overhead of the CHM lookup + * (bucket traversal, {@link Attributes} equality comparison) and attribute processing by resolving + * the underlying timeseries once at bind time. + */ +class BoundInstrumentUsageTest { + + private static final AttributeKey ROLL_VALUE = AttributeKey.longKey("roll.value"); + + // One Attributes object per die face, constructed once and reused across all recordings. + // With unbound instruments each call would look these up on every add(). + private static final Attributes ROLL_1 = Attributes.of(ROLL_VALUE, 1L); + private static final Attributes ROLL_2 = Attributes.of(ROLL_VALUE, 2L); + private static final Attributes ROLL_3 = Attributes.of(ROLL_VALUE, 3L); + private static final Attributes ROLL_4 = Attributes.of(ROLL_VALUE, 4L); + private static final Attributes ROLL_5 = Attributes.of(ROLL_VALUE, 5L); + private static final Attributes ROLL_6 = Attributes.of(ROLL_VALUE, 6L); + + @Test + void rollTheDice() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(reader).build()) { + + Meter meter = meterProvider.get("io.opentelemetry.example.dice"); + + // The bind() API lives on the incubating ExtendedLongCounter, reached by casting the + // instrument returned from the (stable) builder. + ExtendedLongCounter rolls = + (ExtendedLongCounter) + meter + .counterBuilder("dice.rolls") + .setDescription("The number of times each side of the die was rolled") + .setUnit("{roll}") + .build(); + + // Bind one BoundLongCounter per die face. Each bind() call resolves the underlying timeseries + // once, so subsequent add() calls record directly without any attribute lookup. + // + // Equivalent unbound setup (no bind calls needed, but per-recording overhead is higher): + // // no setup β€” just call rolls.add(1, ROLL_N) inline below + BoundLongCounter face1 = rolls.bind(ROLL_1); + BoundLongCounter face2 = rolls.bind(ROLL_2); + BoundLongCounter face3 = rolls.bind(ROLL_3); + BoundLongCounter face4 = rolls.bind(ROLL_4); + BoundLongCounter face5 = rolls.bind(ROLL_5); + BoundLongCounter face6 = rolls.bind(ROLL_6); + + // Simulate 600 rolls with a fixed seed for a reproducible distribution. + Random random = new Random(42); + long[] counts = new long[7]; // indexed 1..6; index 0 unused + + for (int i = 0; i < 600; i++) { + int result = random.nextInt(6) + 1; + counts[result]++; + switch (result) { + case 1: + face1.add(1); + // Equivalent unbound: rolls.add(1, ROLL_1); + break; + case 2: + face2.add(1); + // Equivalent unbound: rolls.add(1, ROLL_2); + break; + case 3: + face3.add(1); + // Equivalent unbound: rolls.add(1, ROLL_3); + break; + case 4: + face4.add(1); + // Equivalent unbound: rolls.add(1, ROLL_4); + break; + case 5: + face5.add(1); + // Equivalent unbound: rolls.add(1, ROLL_5); + break; + case 6: + face6.add(1); + // Equivalent unbound: rolls.add(1, ROLL_6); + break; + default: + break; + } + } + + // A bound counter and the unbound instrument it came from record to the same timeseries; the + // two styles are interchangeable and can be mixed. + LongCounter unbound = rolls; + unbound.add(0, ROLL_1); + + // One cumulative data point per die face, each with the exact roll count recorded above. + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("dice.rolls") + .hasDescription("The number of times each side of the die was rolled") + .hasUnit("{roll}") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying( + point -> point.hasAttributes(ROLL_1).hasValue(counts[1]), + point -> point.hasAttributes(ROLL_2).hasValue(counts[2]), + point -> point.hasAttributes(ROLL_3).hasValue(counts[3]), + point -> point.hasAttributes(ROLL_4).hasValue(counts[4]), + point -> point.hasAttributes(ROLL_5).hasValue(counts[5]), + point -> point.hasAttributes(ROLL_6).hasValue(counts[6])))); + } + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeterTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeterTest.java new file mode 100644 index 00000000000..97204fc93ea --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedDefaultMeterTest.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.testing.internal.AbstractDefaultMeterTest; +import org.junit.jupiter.api.Test; + +class ExtendedDefaultMeterTest extends AbstractDefaultMeterTest { + + @Override + protected Meter getMeter() { + return ExtendedDefaultMeter.getNoop(); + } + + @Override + protected MeterProvider getMeterProvider() { + return ExtendedDefaultMeterProvider.getNoop(); + } + + @Test + void incubatingApiIsLoaded() { + Meter meter = MeterProvider.noop().get("test"); + assertThat(meter).isSameAs(OpenTelemetry.noop().getMeter("test")); + + assertThat(meter.gaugeBuilder("test").ofLongs()).isInstanceOf(ExtendedLongGaugeBuilder.class); + assertThat(meter.gaugeBuilder("test").ofLongs().build().isEnabled()).isFalse(); + assertThat(meter.gaugeBuilder("test").ofLongs().build()).isInstanceOf(ExtendedLongGauge.class); + assertThat(meter.gaugeBuilder("test")).isInstanceOf(ExtendedDoubleGaugeBuilder.class); + assertThat(meter.gaugeBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.gaugeBuilder("test").build()).isInstanceOf(ExtendedDoubleGauge.class); + + assertThat(meter.histogramBuilder("test").ofLongs()) + .isInstanceOf(ExtendedLongHistogramBuilder.class); + assertThat(meter.histogramBuilder("test").ofLongs().build().isEnabled()).isFalse(); + assertThat(meter.histogramBuilder("test").ofLongs().build()) + .isInstanceOf(ExtendedLongHistogram.class); + assertThat(meter.histogramBuilder("test")).isInstanceOf(ExtendedDoubleHistogramBuilder.class); + assertThat(meter.histogramBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.histogramBuilder("test").build()).isInstanceOf(ExtendedDoubleHistogram.class); + + assertThat(meter.counterBuilder("test")).isInstanceOf(ExtendedLongCounterBuilder.class); + assertThat(meter.counterBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.counterBuilder("test").build()).isInstanceOf(ExtendedLongCounter.class); + assertThat(meter.counterBuilder("test").ofDoubles()) + .isInstanceOf(ExtendedDoubleCounterBuilder.class); + assertThat(meter.counterBuilder("test").ofDoubles().build().isEnabled()).isFalse(); + assertThat(meter.counterBuilder("test").ofDoubles().build()) + .isInstanceOf(ExtendedDoubleCounter.class); + + assertThat(meter.upDownCounterBuilder("test")) + .isInstanceOf(ExtendedLongUpDownCounterBuilder.class); + assertThat(meter.upDownCounterBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.upDownCounterBuilder("test").build()) + .isInstanceOf(ExtendedLongUpDownCounter.class); + assertThat(meter.upDownCounterBuilder("test").ofDoubles()) + .isInstanceOf(ExtendedDoubleUpDownCounterBuilder.class); + assertThat(meter.upDownCounterBuilder("test").ofDoubles().build().isEnabled()).isFalse(); + assertThat(meter.upDownCounterBuilder("test").ofDoubles().build()) + .isInstanceOf(ExtendedDoubleUpDownCounter.class); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java new file mode 100644 index 00000000000..e7f679557fe --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/metrics/ExtendedMetricsApiUsageTest.java @@ -0,0 +1,145 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.metrics; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.metrics.internal.MeterConfig.disabled; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableSet; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Random; +import org.junit.jupiter.api.Test; + +/** Demonstrating usage of extended Metrics API. */ +class ExtendedMetricsApiUsageTest { + + @Test + void meterEnabled() { + // Setup SdkMeterProvider + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProviderBuilder meterProviderBuilder = + SdkMeterProvider.builder() + // Default resource used for demonstration purposes + .setResource(Resource.getDefault()) + // In-memory reader used for demonstration purposes + .registerMetricReader(reader); + // Disable meterB + SdkMeterProviderUtil.addMeterConfiguratorCondition( + meterProviderBuilder, nameEquals("meterB"), disabled()); + SdkMeterProvider meterProvider = meterProviderBuilder.build(); + + // Create meterA and meterB, and corresponding instruments + Meter meterA = meterProvider.get("meterA"); + Meter meterB = meterProvider.get("meterB"); + ExtendedDoubleHistogram histogramA = + (ExtendedDoubleHistogram) meterA.histogramBuilder("histogramA").build(); + ExtendedDoubleHistogram histogramB = + (ExtendedDoubleHistogram) meterB.histogramBuilder("histogramB").build(); + + // Check if instrument is enabled before recording measurement and avoid unnecessary computation + if (histogramA.isEnabled()) { + histogramA.record(1.0, Attributes.builder().put("result", flipCoin()).build()); + } + if (histogramB.isEnabled()) { + histogramA.record(1.0, Attributes.builder().put("result", flipCoin()).build()); + } + + // histogramA is enabled since meterA is enabled, histogramB is disabled since meterB is + // disabled + assertThat(histogramA.isEnabled()).isTrue(); + assertThat(histogramB.isEnabled()).isFalse(); + + // Collected data only consists of metrics from meterA. Note, meterB's histogramB would be + // omitted from the results even if values were recorded. The check if enabled simply avoids + // unnecessary computation. + assertThat(reader.collectAllMetrics()) + .allSatisfy(metric -> + assertThat(metric.getInstrumentationScopeInfo().getName()).isEqualTo("meterA")); + } + + private static final Random random = new Random(); + + private static String flipCoin() { + return random.nextBoolean() ? "heads" : "tails"; + } + + @Test + void attributesAdvice() { + // Setup SdkMeterProvider + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + // Default resource used for demonstration purposes + .setResource(Resource.getDefault()) + // In-memory reader used for demonstration purposes + .registerMetricReader(reader) + // Register a view which indicates that for counter1, attributes key1, key2 should be + // retained + .registerView( + InstrumentSelector.builder().setName("counter1").build(), + View.builder().setAttributeFilter(ImmutableSet.of("key1", "key2")).build()) + .build(); + + // Get a Meter for a scope + Meter meter = meterProvider.get("org.foo.my-scope"); + + // To apply attribute advice, cast the instrument builder to appropriate + // Extended{Instrument}Builder, and call setAttributeAdvice + // Here we create counter1 and counter2, both configured to only retain attribute key1. counter1 + // has a view configured which overrides this and retains key1, key2. + LongCounter counter1 = + ((ExtendedLongCounterBuilder) meter.counterBuilder("counter1")) + .setAttributesAdvice(ImmutableList.of(AttributeKey.stringKey("key1"))) + .build(); + LongCounter counter2 = + ((ExtendedLongCounterBuilder) meter.counterBuilder("counter2")) + .setAttributesAdvice(ImmutableList.of(AttributeKey.stringKey("key1"))) + .build(); + + // Record data with attribute key1, key2 + counter1.add(1, Attributes.builder().put("key1", "value1").put("key2", "value2").build()); + counter2.add(1, Attributes.builder().put("key1", "value1").put("key2", "value2").build()); + + // Verify that counter1 has both key1, key2 since view overrides the attribute advice + // Verify that counter2 only has key1, since attribute advice causes key2 to be dropped by + // default + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasName("counter1") + .hasLongSumSatisfying(sumAssert -> + sumAssert.hasPointsSatisfying(point -> + point + .hasValue(1L) + .hasAttributes( + Attributes.builder() + .put("key1", "value1") + .put("key2", "value2") + .build()))), + metricData -> + assertThat(metricData) + .hasName("counter2") + .hasLongSumSatisfying(sumAssert -> + sumAssert.hasPointsSatisfying(point -> + point + .hasValue(1L) + .hasAttributes( + Attributes.builder().put("key1", "value1").build())))); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/CaseInsensitiveMapTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/CaseInsensitiveMapTest.java new file mode 100644 index 00000000000..ac9feee91b4 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/CaseInsensitiveMapTest.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class CaseInsensitiveMapTest { + + @Test + void createByConstructor() { + Map map = new HashMap<>(); + map.put("Key1", "test"); + map.put("Key2", "test2"); + + CaseInsensitiveMap caseInsensitiveMap = new CaseInsensitiveMap(map); + + Map standardMap = new HashMap<>(); + standardMap.put("key1", "test"); + standardMap.put("key2", "test2"); + + assertThat(caseInsensitiveMap).isEqualTo(standardMap); + } + + @Test + void putAll() { + CaseInsensitiveMap caseInsensitiveMap = new CaseInsensitiveMap(); + Map standardMap = new HashMap<>(); + standardMap.put("key1", "test"); + standardMap.put("key2", "test2"); + caseInsensitiveMap.putAll(standardMap); + assertThat(caseInsensitiveMap).isEqualTo(standardMap); + } + + @Test + void putIfAbsent() { + CaseInsensitiveMap caseInsensitiveMap = new CaseInsensitiveMap(); + caseInsensitiveMap.putIfAbsent("key1", "test"); + assertThat(caseInsensitiveMap.get("KEY1")).isEqualTo("test"); + caseInsensitiveMap.putIfAbsent("key1", "nope"); + assertThat(caseInsensitiveMap.get("KEY1")).isEqualTo("test"); + } + + @Test + void createByConstructorWithNullMap() { + CaseInsensitiveMap caseInsensitiveMap = new CaseInsensitiveMap(null); + assertThat(caseInsensitiveMap).isEmpty(); + } + + @Test + void caseInsensitivity() { + CaseInsensitiveMap caseInsensitiveMap = new CaseInsensitiveMap(null); + + assertThat(caseInsensitiveMap).isEmpty(); + + caseInsensitiveMap.put("KEY1", "test1"); + caseInsensitiveMap.put("KEY2", "test2"); + assertThat(caseInsensitiveMap.get("key1")).isEqualTo("test1"); + assertThat(caseInsensitiveMap.get("key2")).isEqualTo("test2"); + assertThat(caseInsensitiveMap.get("kEy2")).isEqualTo("test2"); + assertThat(caseInsensitiveMap.get("KEY2")).isEqualTo("test2"); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/EnvironmentGetterTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/EnvironmentGetterTest.java new file mode 100644 index 00000000000..31670c08aa9 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/EnvironmentGetterTest.java @@ -0,0 +1,111 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class EnvironmentGetterTest { + + @RegisterExtension + LogCapturer logCapturer = LogCapturer.create().captureForType(EnvironmentGetter.class); + + @Test + void get() { + Map carrier = new HashMap<>(); + carrier.put("TRACEPARENT", "val1"); + carrier.put("TRACESTATE", "val2"); + carrier.put("BAGGAGE", "val3"); + carrier.put("OTHER", "val4"); + + assertThat(EnvironmentGetter.getInstance().get(carrier, "traceparent")).isEqualTo("val1"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "TRACESTATE")).isEqualTo("val2"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "Baggage")).isEqualTo("val3"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "other")).isEqualTo("val4"); + } + + @Test + void get_normalization() { + Map carrier = new HashMap<>(); + // Carrier entries are expected to have normalized keys (i.e. set via EnvironmentSetter). + carrier.put("OTEL_TRACE_ID", "val1"); + carrier.put("OTEL_BAGGAGE_KEY", "val2"); + carrier.put("_", "val3"); + // Carrier entry with an unnormalized key is not reachable via get(). + carrier.put("", "val4"); + carrier.put("otel-unreachable-key", "val5"); + + // Lookup keys are normalized before the carrier map is consulted. + assertThat(EnvironmentGetter.getInstance().get(carrier, "otel.trace.id")).isEqualTo("val1"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "otel-baggage-key")).isEqualTo("val2"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "")).isEqualTo("val3"); + // Carrier entries with unnormalized names are not consulted by get(). + assertThat(EnvironmentGetter.getInstance().get(carrier, "otel-unreachable-key")).isNull(); + } + + @Test + void get_null() { + assertThat(EnvironmentGetter.getInstance().get(null, "key")).isNull(); + assertThat(EnvironmentGetter.getInstance().get(Collections.emptyMap(), null)).isNull(); + } + + @Test + @SuppressLogger(EnvironmentGetter.class) + void keys_onlyNormalizedKeysIncluded() { + Map carrier = new HashMap<>(); + carrier.put("", "V0"); + carrier.put("otel.trace.id", "V1"); + carrier.put("otel-baggage-key", "V2"); + carrier.put("OTEL_FOO", "V3"); + carrier.put("_", "V4"); + + // Non-normalized keys are excluded; only already-normalized keys are returned. + assertThat(EnvironmentGetter.getInstance().keys(carrier)) + .containsExactlyInAnyOrder("OTEL_FOO", "_"); + for (String key : EnvironmentGetter.getInstance().keys(carrier)) { + assertThat(EnvironmentGetter.getInstance().get(carrier, key)).isNotNull(); + } + assertThat(EnvironmentGetter.getInstance().keys(null)).isEmpty(); + + assertThat(logCapturer.size()).isEqualTo(1); + logCapturer.assertContains("returns only normalized environment variable names"); + } + + @Test + void get_valuesAreUnmodified() { + Map carrier = new HashMap<>(); + carrier.put("KEY1", "simple-value"); + carrier.put("KEY2", "value with spaces"); + carrier.put("KEY3", "value\twith\ttabs"); + carrier.put("KEY4", "value\u0000with\u0001control"); + carrier.put("KEY5", "value\nwith\nnewlines"); + carrier.put("KEY6", "value\u0080non-ascii"); + carrier.put("KEY7", ""); + + assertThat(EnvironmentGetter.getInstance().get(carrier, "key1")).isEqualTo("simple-value"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "key2")).isEqualTo("value with spaces"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "key3")).isEqualTo("value\twith\ttabs"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "key4")) + .isEqualTo("value\u0000with\u0001control"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "key5")) + .isEqualTo("value\nwith\nnewlines"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "key6")) + .isEqualTo("value\u0080non-ascii"); + assertThat(EnvironmentGetter.getInstance().get(carrier, "key7")).isEmpty(); + } + + @Test + void testToString() { + assertThat(EnvironmentGetter.getInstance().toString()).isEqualTo("EnvironmentGetter"); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/EnvironmentSetterTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/EnvironmentSetterTest.java new file mode 100644 index 00000000000..c280bcf9bbf --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/EnvironmentSetterTest.java @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class EnvironmentSetterTest { + + @Test + void set() { + Map carrier = new HashMap<>(); + EnvironmentSetter.getInstance().set(carrier, "traceparent", "val1"); + EnvironmentSetter.getInstance().set(carrier, "TRACESTATE", "val2"); + EnvironmentSetter.getInstance().set(carrier, "Baggage", "val3"); + + assertThat(carrier).containsEntry("TRACEPARENT", "val1"); + assertThat(carrier).containsEntry("TRACESTATE", "val2"); + assertThat(carrier).containsEntry("BAGGAGE", "val3"); + } + + @Test + void set_normalization() { + Map carrier = new HashMap<>(); + EnvironmentSetter.getInstance().set(carrier, "otel.trace.id", "val1"); + EnvironmentSetter.getInstance().set(carrier, "otel-baggage-key", "val2"); + EnvironmentSetter.getInstance().set(carrier, "", "val3"); + + assertThat(carrier).containsEntry("OTEL_TRACE_ID", "val1"); + assertThat(carrier).containsEntry("OTEL_BAGGAGE_KEY", "val2"); + assertThat(carrier).containsEntry("_", "val3"); + } + + @Test + void set_null() { + Map carrier = new HashMap<>(); + EnvironmentSetter.getInstance().set(null, "key", "val"); + EnvironmentSetter.getInstance().set(carrier, null, "val"); + EnvironmentSetter.getInstance().set(carrier, "key", null); + assertThat(carrier).isEmpty(); + } + + @Test + void set_valuesAreUnmodified() { + Map carrier = new HashMap<>(); + EnvironmentSetter.getInstance().set(carrier, "key1", "simple-value"); + EnvironmentSetter.getInstance().set(carrier, "key2", "value with spaces"); + EnvironmentSetter.getInstance().set(carrier, "key3", "value\twith\ttabs"); + EnvironmentSetter.getInstance().set(carrier, "key4", "value\u0000with\u0001control"); + EnvironmentSetter.getInstance().set(carrier, "key5", "value\nwith\nnewlines"); + EnvironmentSetter.getInstance().set(carrier, "key6", "value\u0080non-ascii"); + EnvironmentSetter.getInstance().set(carrier, "key7", ""); + + assertThat(carrier).containsEntry("KEY1", "simple-value"); + assertThat(carrier).containsEntry("KEY2", "value with spaces"); + assertThat(carrier).containsEntry("KEY3", "value\twith\ttabs"); + assertThat(carrier).containsEntry("KEY4", "value\u0000with\u0001control"); + assertThat(carrier).containsEntry("KEY5", "value\nwith\nnewlines"); + assertThat(carrier).containsEntry("KEY6", "value\u0080non-ascii"); + assertThat(carrier).containsEntry("KEY7", ""); + } + + @ParameterizedTest + @MethodSource("isNormalizedKeyCases") + void isNormalizedKey(String key, boolean expected) { + assertThat(EnvironmentSetter.isNormalizedKey(key)).isEqualTo(expected); + } + + static Stream isNormalizedKeyCases() { + return Stream.of( + Arguments.argumentSet("uppercase letters", "TRACEPARENT", true), + Arguments.argumentSet("uppercase with underscores", "OTEL_TRACE_ID", true), + Arguments.argumentSet("single underscore", "_", true), + Arguments.argumentSet("single letter", "A", true), + Arguments.argumentSet("letter then digit", "A0", true), + Arguments.argumentSet("mixed uppercase digits underscores", "A_B_0", true), + Arguments.argumentSet("empty string", "", false), + Arguments.argumentSet("starts with digit", "0ABC", false), + Arguments.argumentSet("lowercase letters", "traceparent", false), + Arguments.argumentSet("dots", "otel.trace.id", false), + Arguments.argumentSet("hyphens", "otel-baggage-key", false), + Arguments.argumentSet("space", "OTEL TRACE", false)); + } + + @Test + void testToString() { + assertThat(EnvironmentSetter.getInstance().toString()).isEqualTo("EnvironmentSetter"); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagatorsUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagatorsUsageTest.java new file mode 100644 index 00000000000..322ad4c4628 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/ExtendedContextPropagatorsUsageTest.java @@ -0,0 +1,83 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.propagation; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Demonstrating usage of extended ContextPropagators API. */ +class ExtendedContextPropagatorsUsageTest { + + @Test + void getTextMapPropagationContextUsage() { + // Setup Propagators + ContextPropagators propagators = + ContextPropagators.create( + TextMapPropagator.composite(W3CTraceContextPropagator.getInstance())); + + // Setup SdkTracerProvider + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(mock(SpanExporter.class))) + .setSampler(Sampler.alwaysOn()) + .build(); + + // Get a Tracer for a scope + Tracer tracer = tracerProvider.get("org.foo.my-scope"); + + try (Scope scope = tracer.spanBuilder("span name").startSpan().makeCurrent()) { + // Simplify context injection by getting a text map of the key/value pairs to inject + Map textMap = + ExtendedContextPropagators.getTextMapPropagationContext(propagators); + // Assert textmap contains the "traceparent" field as injected by W3CTraceContextPropagator + assertThat(textMap) + .hasEntrySatisfying("traceparent", value -> assertThat(value).isNotEmpty()); + } + } + + @Test + void extractTextMapPropagationContextUsage() { + // Setup Propagators + ContextPropagators propagators = + ContextPropagators.create( + TextMapPropagator.composite(W3CTraceContextPropagator.getInstance())); + + // Setup map with context key/value pairs + Map contextCarrier = + ImmutableMap.of("traceparent", "00-713bde54561be5ded62545d0e7369d4a-3c3a5ddefce9c1e1-01"); + + // Extract context from the carrier map + Context context = + ExtendedContextPropagators.extractTextMapPropagationContext(contextCarrier, propagators); + // Assert SpanContext is properly extracted from the W3cTraceContextPropagator + assertThat(Span.fromContext(context).getSpanContext()) + .isEqualTo( + SpanContext.createFromRemoteParent( + "713bde54561be5ded62545d0e7369d4a", + "3c3a5ddefce9c1e1", + TraceFlags.getSampled(), + TraceState.getDefault())); + } +} diff --git a/extensions/incubator/src/test/java/io/opentelemetry/extension/incubator/propagation/PassThroughPropagatorTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/PassThroughPropagatorTest.java similarity index 93% rename from extensions/incubator/src/test/java/io/opentelemetry/extension/incubator/propagation/PassThroughPropagatorTest.java rename to api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/PassThroughPropagatorTest.java index d23c9a5ca98..008694252b8 100644 --- a/extensions/incubator/src/test/java/io/opentelemetry/extension/incubator/propagation/PassThroughPropagatorTest.java +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/propagation/PassThroughPropagatorTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.extension.incubator.propagation; +package io.opentelemetry.api.incubator.propagation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -87,4 +87,9 @@ void nullFields() { .isInstanceOf(NullPointerException.class) .hasMessageContaining("field"); } + + @Test + void toString_Valid() { + assertThat(propagator.toString()).isEqualTo("PassThroughPropagator{fields=[animal, food]}"); + } } diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerTest.java new file mode 100644 index 00000000000..1ccec2a4ba6 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedDefaultTracerTest.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.verify; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.testing.internal.AbstractDefaultTracerTest; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerProvider; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class ExtendedDefaultTracerTest extends AbstractDefaultTracerTest { + + @Override + public Tracer getTracer() { + return ExtendedDefaultTracer.getNoop(); + } + + @Override + public TracerProvider getTracerProvider() { + return ExtendedDefaultTracerProvider.getNoop(); + } + + @Test + void incubatingApiIsLoaded() { + Tracer tracer = TracerProvider.noop().get("test"); + assertThat(tracer).isSameAs(OpenTelemetry.noop().getTracer("test")); + assertThat(tracer.isEnabled()).isFalse(); + + assertThat(tracer).isInstanceOf(ExtendedTracer.class); + assertThat(tracer.spanBuilder("test")).isInstanceOf(ExtendedSpanBuilder.class); + } + + @SuppressWarnings("unchecked") + @Test + void incubatingApi() { + ExtendedSpanBuilder spanBuilder = + (ExtendedSpanBuilder) ExtendedDefaultTracer.getNoop().spanBuilder("test"); + assertThat(spanBuilder.setParentFrom(null, null)).isSameAs(spanBuilder); + + SpanRunnable spanRunnable = Mockito.mock(SpanRunnable.class); + + spanBuilder.startAndRun(spanRunnable); + verify(spanRunnable).runInSpan(); + reset(spanRunnable); + + spanBuilder.startAndRun(spanRunnable, null); + verify(spanRunnable).runInSpan(); + reset(spanRunnable); + + SpanCallable spanCallable = Mockito.mock(SpanCallable.class); + + spanBuilder.startAndCall(spanCallable); + verify(spanCallable).callInSpan(); + reset(spanCallable); + + spanBuilder.startAndCall(spanCallable, null); + verify(spanCallable).callInSpan(); + reset(spanCallable); + } +} diff --git a/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java b/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java new file mode 100644 index 00000000000..5759b6923b9 --- /dev/null +++ b/api/incubator/src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java @@ -0,0 +1,277 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator.trace; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.trace.internal.TracerConfig.disabled; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.IdGenerator; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.data.StatusData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.function.BiConsumer; +import org.junit.jupiter.api.Test; + +/** Demonstrating usage of extended Trace API. */ +class ExtendedTraceApiUsageTest { + + @Test + void tracerEnabled() { + // Setup SdkTracerProvider + InMemorySpanExporter exporter = InMemorySpanExporter.create(); + SdkTracerProviderBuilder tracerProviderBuilder = + SdkTracerProvider.builder() + // Default resource used for demonstration purposes + .setResource(Resource.getDefault()) + // In-memory exporter used for demonstration purposes + .addSpanProcessor(SimpleSpanProcessor.create(exporter)); + // Disable tracerB + SdkTracerProviderUtil.addTracerConfiguratorCondition( + tracerProviderBuilder, nameEquals("tracerB"), disabled()); + SdkTracerProvider tracerProvider = tracerProviderBuilder.build(); + + // Create tracerA and tracerB + ExtendedTracer tracerA = (ExtendedTracer) tracerProvider.get("tracerA"); + ExtendedTracer tracerB = (ExtendedTracer) tracerProvider.get("tracerB"); + + // Check if tracer is enabled before recording span and avoid unnecessary computation + if (tracerA.isEnabled()) { + tracerA + .spanBuilder("span name") + .startSpan() + .setAllAttributes(Attributes.builder().put("result", flipCoin()).build()) + .end(); + } + if (tracerB.isEnabled()) { + tracerB + .spanBuilder("span name") + .startSpan() + .setAllAttributes(Attributes.builder().put("result", flipCoin()).build()) + .end(); + } + + // tracerA is enabled, tracerB is disabled + assertThat(tracerA.isEnabled()).isTrue(); + assertThat(tracerB.isEnabled()).isFalse(); + + // Collected data only consists of spans from tracerA. Note, tracerB's spans would be + // omitted from the results even if spans were recorded. The check if enabled simply avoids + // unnecessary computation. + assertThat(exporter.getFinishedSpanItems()) + .allSatisfy(spanData -> + assertThat(spanData.getInstrumentationScopeInfo().getName()).isEqualTo("tracerA")); + } + + private static final Random random = new Random(); + + private static String flipCoin() { + return random.nextBoolean() ? "heads" : "tails"; + } + + /** Demonstrates {@link ExtendedSpanBuilder#setParentFrom(ContextPropagators, Map)}. */ + @Test + void setParentFrom() { + // Setup SdkTracerProvider + InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + // Default resource used for demonstration purposes + .setResource(Resource.getDefault()) + // SimpleSpanProcessor with InMemorySpanExporter used for demonstration purposes + .addSpanProcessor(SimpleSpanProcessor.create(spanExporter)) + .build(); + + // Setup ContextPropagators + ContextPropagators contextPropagators = + ContextPropagators.create( + TextMapPropagator.composite(W3CTraceContextPropagator.getInstance())); + + // Get a Tracer for a scope + Tracer tracer = tracerProvider.get("org.foo.my-scope"); + + // Populate a map with W3C trace context + Map contextCarrier = new HashMap<>(); + SpanContext remoteParentContext = + SpanContext.createFromRemoteParent( + IdGenerator.random().generateTraceId(), + IdGenerator.random().generateSpanId(), + TraceFlags.getSampled(), + TraceState.getDefault()); + W3CTraceContextPropagator.getInstance() + .inject( + Context.current().with(Span.wrap(remoteParentContext)), + contextCarrier, + (carrier, key, value) -> { + if (carrier != null) { + carrier.put(key, value); + } + }); + + // Set parent from the Map context carrier + ((ExtendedSpanBuilder) tracer.spanBuilder("local_root")) + .setParentFrom(contextPropagators, contextCarrier) + .startSpan() + .end(); + + // Verify the span has the correct parent context + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactly(span -> + assertThat(span) + .hasName("local_root") + .hasParentSpanId(remoteParentContext.getSpanId()) + .hasTraceId(remoteParentContext.getTraceId())); + } + + /** + * Demonstrates {@link ExtendedSpanBuilder#startAndCall(SpanCallable)}, {@link + * ExtendedSpanBuilder#startAndCall(SpanCallable, BiConsumer)}, {@link + * ExtendedSpanBuilder#startAndRun(SpanRunnable)}, {@link + * ExtendedSpanBuilder#startAndRun(SpanRunnable, BiConsumer)}. + */ + @Test + void startAndCallOrRun() { + // Setup SdkTracerProvider + InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + // Default resource used for demonstration purposes + .setResource(Resource.getDefault()) + // SimpleSpanProcessor with InMemorySpanExporter used for demonstration purposes + .addSpanProcessor(SimpleSpanProcessor.create(spanExporter)) + .build(); + + // Get a Tracer for a scope + Tracer tracer = tracerProvider.get("org.foo.my-scope"); + ExtendedTracer extendedTracer = (ExtendedTracer) tracer; + + // Wrap the resetCheckout method in a span + String cartId = + ((ExtendedSpanBuilder) tracer.spanBuilder("reset_checkout_and_return")) + .setAttribute("key123", "val456") + .startAndCall(() -> resetCheckoutAndReturn("abc123", /* throwException= */ false)); + assertThat(cartId).isEqualTo("abc123"); + // ...or use ExtendedTracer instance + // ...or runnable variation + extendedTracer + .spanBuilder("reset_checkout") + .startAndRun(() -> resetCheckout("abc123", /* throwException= */ false)); + + // Wrap the resetCheckout method in a span; resetCheckout throws an exception + try { + extendedTracer + .spanBuilder("reset_checkout_and_return") + .startAndCall(() -> resetCheckoutAndReturn("def456", /* throwException= */ true)); + } catch (Throwable e) { + // Ignore expected exception + } + // ...or runnable variation + try { + extendedTracer + .spanBuilder("reset_checkout") + .startAndRun(() -> resetCheckout("def456", /* throwException= */ true)); + } catch (Throwable e) { + // Ignore expected exception + } + + // Wrap the resetCheckout method in a span; resetCheckout throws an exception; use custom error + // handler + try { + extendedTracer + .spanBuilder("reset_checkout_and_return") + .startAndCall( + () -> resetCheckoutAndReturn("ghi789", /* throwException= */ true), + (span, throwable) -> span.setAttribute("my-attribute", "error")); + } catch (Throwable e) { + // Ignore expected exception + } + // ...or runnable variation + try { + extendedTracer + .spanBuilder("reset_checkout") + .startAndRun( + () -> resetCheckout("ghi789", /* throwException= */ true), + (span, throwable) -> span.setAttribute("my-attribute", "error")); + } catch (Throwable e) { + // Ignore expected exception + } + + // Verify the spans are as expected + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactly( + span -> + assertThat(span) + .hasName("reset_checkout_and_return") + .hasAttribute(AttributeKey.stringKey("cartId"), "abc123") + .hasStatus(StatusData.unset()) + .hasTotalRecordedEvents(0), + span -> + assertThat(span) + .hasName("reset_checkout") + .hasAttribute(AttributeKey.stringKey("cartId"), "abc123") + .hasStatus(StatusData.unset()) + .hasTotalRecordedEvents(0), + span -> + assertThat(span) + .hasName("reset_checkout_and_return") + .hasAttribute(AttributeKey.stringKey("cartId"), "def456") + .hasStatus(StatusData.error()) + .hasEventsSatisfyingExactly(event -> event.hasName("exception")), + span -> + assertThat(span) + .hasName("reset_checkout") + .hasAttribute(AttributeKey.stringKey("cartId"), "def456") + .hasStatus(StatusData.error()) + .hasEventsSatisfyingExactly(event -> event.hasName("exception")), + span -> + assertThat(span) + .hasName("reset_checkout_and_return") + .hasAttribute(AttributeKey.stringKey("cartId"), "ghi789") + .hasAttribute(AttributeKey.stringKey("my-attribute"), "error") + .hasStatus(StatusData.unset()) + .hasTotalRecordedEvents(0), + span -> + assertThat(span) + .hasName("reset_checkout") + .hasAttribute(AttributeKey.stringKey("cartId"), "ghi789") + .hasAttribute(AttributeKey.stringKey("my-attribute"), "error") + .hasStatus(StatusData.unset()) + .hasTotalRecordedEvents(0)); + } + + private static String resetCheckoutAndReturn(String cartId, boolean throwException) { + Span.current().setAttribute("cartId", cartId); + if (throwException) { + throw new RuntimeException("Error!"); + } + return cartId; + } + + private static void resetCheckout(String cartId, boolean throwException) { + Span.current().setAttribute("cartId", cartId); + if (throwException) { + throw new RuntimeException("Error!"); + } + } +} diff --git a/api/incubator/src/testConvertToModel/java/io/opentelemetry/api/incubator/InstrumentationConfigUtilTest.java b/api/incubator/src/testConvertToModel/java/io/opentelemetry/api/incubator/InstrumentationConfigUtilTest.java new file mode 100644 index 00000000000..67892d0ca58 --- /dev/null +++ b/api/incubator/src/testConvertToModel/java/io/opentelemetry/api/incubator/InstrumentationConfigUtilTest.java @@ -0,0 +1,267 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.incubator; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.incubator.config.InstrumentationConfigUtil; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.YamlDeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalInstrumentationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLanguageSpecificInstrumentationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLanguageSpecificInstrumentationPropertyModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.OpenTelemetryConfigurationModelAccessor; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import org.junit.jupiter.api.Test; + +@SuppressLogger(YamlDeclarativeConfigProperties.class) +class InstrumentationConfigUtilTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + @Test + void toMap_RoundTrip() throws JsonProcessingException { + Map map = new HashMap<>(); + map.put("string", "val"); + map.put("boolean", true); + map.put("long", 1L); + map.put("double", 1.1); + map.put("null", null); + map.put("stringList", Arrays.asList("val1", "val2")); + map.put("boolList", Arrays.asList(true, false)); + map.put("longList", Arrays.asList(1L, 2L)); + map.put("doubleList", Arrays.asList(1.1d, 2.2d)); + map.put( + "structuredList", Collections.singletonList(Collections.singletonMap("childKey", "val"))); + map.put("emptyList", Collections.emptyList()); + map.put("structured", Collections.singletonMap("childKey", "val")); + map.put("emptyStructured", Collections.emptyMap()); + + String mapJson = MAPPER.writeValueAsString(map); + DeclarativeConfigProperties properties = + DeclarativeConfiguration.toConfigProperties( + new ByteArrayInputStream(mapJson.getBytes(StandardCharsets.UTF_8))); + + assertThat(DeclarativeConfigProperties.toMap(properties)).isEqualTo(map); + } + + @Test + void getInstrumentationConfigModel_UnsetConfig() { + ConfigProvider configProvider = DeclarativeConfigProperties::empty; + + assertThat( + InstrumentationConfigUtil.getInstrumentationConfigModel( + configProvider, "my_instrumentation_library", MAPPER, Model.class)) + .isNull(); + } + + @Test + void getInstrumentationConfigModel_EmptyConfig() { + ConfigProvider configProvider = + withInstrumentationConfig( + "my_instrumentation_library", + new ExperimentalLanguageSpecificInstrumentationPropertyModel()); + + assertThat( + InstrumentationConfigUtil.getInstrumentationConfigModel( + configProvider, "my_instrumentation_library", MAPPER, Model.class)) + .isEqualTo(new Model()); + } + + @Test + void getInstrumentationConfigModel_KitchenSink() { + ConfigProvider configProvider = + withInstrumentationConfig( + "my_instrumentation_library", + new ExperimentalLanguageSpecificInstrumentationPropertyModel() + .setAdditionalProperty("string_property", "value") + .setAdditionalProperty("boolean_property", true) + .setAdditionalProperty("long_property", 1L) + .setAdditionalProperty("double_property", 1.1d) + .setAdditionalProperty("string_list_property", Arrays.asList("val1", "val2")) + .setAdditionalProperty("boolean_list_property", Arrays.asList(true, false)) + .setAdditionalProperty("long_list_property", Arrays.asList(1L, 2L)) + .setAdditionalProperty("double_list_property", Arrays.asList(1.1d, 2.2d)) + .setAdditionalProperty("map_property", Collections.singletonMap("childKey", "val")) + .setAdditionalProperty( + "structured_list_property", + Collections.singletonList( + ImmutableMap.of("key", "the_key", "value", "the_value")))); + + Model expected = new Model(); + expected.stringProperty = "value"; + expected.booleanProperty = true; + expected.longProperty = 1L; + expected.doubleProperty = 1.1d; + expected.stringListProperty = Arrays.asList("val1", "val2"); + expected.booleanListProperty = Arrays.asList(true, false); + expected.longListProperty = Arrays.asList(1L, 2L); + expected.doubleListProperty = Arrays.asList(1.1d, 2.2d); + expected.mapProperty = Collections.singletonMap("childKey", "val"); + ListEntryModel listEntryModel = new ListEntryModel(); + listEntryModel.key = "the_key"; + listEntryModel.value = "the_value"; + expected.structuredListProperty = Collections.singletonList(listEntryModel); + + assertThat( + InstrumentationConfigUtil.getInstrumentationConfigModel( + configProvider, "my_instrumentation_library", MAPPER, Model.class)) + .isEqualTo(expected); + } + + private static ConfigProvider withInstrumentationConfig( + String instrumentationName, + ExperimentalLanguageSpecificInstrumentationPropertyModel instrumentationConfig) { + ExperimentalLanguageSpecificInstrumentationModel javaConfig = + new ExperimentalLanguageSpecificInstrumentationModel(); + javaConfig.setAdditionalProperty(instrumentationName, instrumentationConfig); + DeclarativeConfigProperties modelProperties = + DeclarativeConfiguration.toConfigProperties( + OpenTelemetryConfigurationModelAccessor.setInstrumentation( + new OpenTelemetryConfigurationModel(), + new ExperimentalInstrumentationModel().setJava(javaConfig))); + + return SdkConfigProvider.create(modelProperties); + } + + private static class Model { + @JsonProperty("string_property") + private String stringProperty; + + @JsonProperty("boolean_property") + private Boolean booleanProperty; + + @JsonProperty("long_property") + private Long longProperty; + + @JsonProperty("double_property") + private Double doubleProperty; + + @JsonProperty("string_list_property") + private List stringListProperty; + + @JsonProperty("boolean_list_property") + private List booleanListProperty; + + @JsonProperty("long_list_property") + private List longListProperty; + + @JsonProperty("double_list_property") + private List doubleListProperty; + + @JsonProperty("map_property") + private Map mapProperty; + + @JsonProperty("structured_list_property") + private List structuredListProperty; + + @Override + public boolean equals(Object o) { + if (!(o instanceof Model)) { + return false; + } + Model model = (Model) o; + return Objects.equals(stringProperty, model.stringProperty) + && Objects.equals(booleanProperty, model.booleanProperty) + && Objects.equals(longProperty, model.longProperty) + && Objects.equals(doubleProperty, model.doubleProperty) + && Objects.equals(stringListProperty, model.stringListProperty) + && Objects.equals(booleanListProperty, model.booleanListProperty) + && Objects.equals(longListProperty, model.longListProperty) + && Objects.equals(doubleListProperty, model.doubleListProperty) + && Objects.equals(mapProperty, model.mapProperty) + && Objects.equals(structuredListProperty, model.structuredListProperty); + } + + @Override + public int hashCode() { + return Objects.hash( + stringProperty, + booleanProperty, + longProperty, + doubleProperty, + stringListProperty, + booleanListProperty, + longListProperty, + doubleListProperty, + mapProperty, + structuredListProperty); + } + + @Override + public String toString() { + return "Model{" + + "stringProperty='" + + stringProperty + + '\'' + + ", booleanProperty='" + + booleanProperty + + '\'' + + ", longProperty='" + + longProperty + + '\'' + + ", doubleProperty='" + + doubleProperty + + '\'' + + ", stringListProperty=" + + stringListProperty + + ", booleanListProperty=" + + booleanListProperty + + ", longListProperty=" + + longListProperty + + ", doubleListProperty=" + + doubleListProperty + + ", mapProperty=" + + mapProperty + + ", structuredListProperty=" + + structuredListProperty + + '}'; + } + } + + private static final class ListEntryModel { + @JsonProperty("key") + private String key; + + @JsonProperty("value") + private String value; + + @Override + public boolean equals(Object o) { + if (o == null || getClass() != o.getClass()) { + return false; + } + ListEntryModel that = (ListEntryModel) o; + return Objects.equals(key, that.key) && Objects.equals(value, that.value); + } + + @Override + public int hashCode() { + return Objects.hash(key, value); + } + + @Override + public String toString() { + return "ListEntryModel{" + "key='" + key + '\'' + ", value='" + value + '\'' + '}'; + } + } +} diff --git a/api/testing-internal/build.gradle.kts b/api/testing-internal/build.gradle.kts new file mode 100644 index 00000000000..328f54dd801 --- /dev/null +++ b/api/testing-internal/build.gradle.kts @@ -0,0 +1,23 @@ +plugins { + id("otel.java-conventions") +} + +description = "OpenTelemetry API Testing (Internal)" +otelJava.moduleName.set("io.opentelemetry.api.testing.internal") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) + +dependencies { + api(project(":api:all")) + + implementation(project(":testing-internal")) + + implementation("com.linecorp.armeria:armeria-junit5") + implementation("org.assertj:assertj-core") + implementation("org.mockito:mockito-core") +} + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false +} diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java new file mode 100644 index 00000000000..9ea2e794c86 --- /dev/null +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultLoggerTest.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.testing.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.context.Context; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +/** Unit tests for No-op {@link Logger}. */ +public abstract class AbstractDefaultLoggerTest { + + protected abstract LoggerProvider getLoggerProvider(); + + protected abstract Logger getLogger(); + + @Test + void noopLoggerProvider_doesNotThrow() { + LoggerProvider provider = LoggerProvider.noop(); + + assertThat(provider).isSameAs(getLoggerProvider()); + assertThatCode(() -> provider.get("scope-name")).doesNotThrowAnyException(); + assertThatCode(() -> + provider + .loggerBuilder("scope-name") + .setInstrumentationVersion("1.0") + .setSchemaUrl("http://schema.com") + .build()) + .doesNotThrowAnyException(); + + assertThatCode(() -> provider.loggerBuilder("scope-name").build().logRecordBuilder()) + .doesNotThrowAnyException(); + } + + @Test + void defaultIsEnabled() { + assertThat(getLogger().isEnabled(Severity.ERROR, Context.root())).isFalse(); + assertThat(getLogger().isEnabled(Severity.ERROR)).isFalse(); + } + + @Test + void buildAndEmit() { + assertThatCode(() -> + getLogger() + .logRecordBuilder() + .setEventName("event name") + .setTimestamp(100, TimeUnit.SECONDS) + .setTimestamp(Instant.now()) + .setObservedTimestamp(100, TimeUnit.SECONDS) + .setObservedTimestamp(Instant.now()) + .setContext(Context.root()) + .setSeverity(Severity.DEBUG) + .setSeverityText("debug") + .setBody("body") + .setBody(Value.of("body")) + .setAttribute(AttributeKey.stringKey("key1"), "value1") + .setAttribute("stringKey", "value") + .setAttribute("longKey", 100L) + .setAttribute("intKey", 100) + .setAttribute("doubleKey", 1.23) + .setAttribute("boolKey", true) + .setAttribute("valueKey", Value.of("value")) + .setAllAttributes(Attributes.builder().put("key2", "value2").build()) + .setException(new RuntimeException("error")) + .emit()) + .doesNotThrowAnyException(); + } +} diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java new file mode 100644 index 00000000000..282abaeef73 --- /dev/null +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultMeterTest.java @@ -0,0 +1,309 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.testing.internal; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.DoubleGauge; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongGauge; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; +import io.opentelemetry.api.metrics.ObservableLongMeasurement; +import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import org.junit.jupiter.api.Test; + +/** Unit tests for No-op {@link Meter}. */ +@SuppressLogger +public abstract class AbstractDefaultMeterTest { + private final Meter meter = getMeter(); + + protected abstract Meter getMeter(); + + protected abstract MeterProvider getMeterProvider(); + + @Test + void noopMeterProvider_getDoesNotThrow() { + MeterProvider provider = getMeterProvider(); + provider.get("user-instrumentation"); + } + + @Test + void noopMeterProvider_builderDoesNotThrow() { + MeterProvider provider = getMeterProvider(); + provider.meterBuilder("user-instrumentation").build(); + provider.meterBuilder("advanced-instrumentation").setInstrumentationVersion("1.0").build(); + provider.meterBuilder("schema-instrumentation").setSchemaUrl("myschema://url").build(); + provider + .meterBuilder("schema-instrumentation") + .setInstrumentationVersion("1.0") + .setSchemaUrl("myschema://url") + .build(); + } + + @Test + void defaultIsEnabled() { + assertThat(meter.counterBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.counterBuilder("test").ofDoubles().build().isEnabled()).isFalse(); + assertThat(meter.histogramBuilder("test").ofLongs().build().isEnabled()).isFalse(); + assertThat(meter.histogramBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.upDownCounterBuilder("test").build().isEnabled()).isFalse(); + assertThat(meter.upDownCounterBuilder("test").ofDoubles().build().isEnabled()).isFalse(); + assertThat(meter.gaugeBuilder("test").ofLongs().build().isEnabled()).isFalse(); + assertThat(meter.gaugeBuilder("test").build().isEnabled()).isFalse(); + } + + @Test + void noopLongCounter_doesNotThrow() { + LongCounter counter = + meter.counterBuilder("size").setDescription("The size I'm measuring").setUnit("1").build(); + counter.add(1); + counter.add(1, Attributes.of(stringKey("thing"), "car")); + counter.add(1, Attributes.of(stringKey("thing"), "car"), Context.current()); + + ObservableLongMeasurement measurement = + meter + .counterBuilder("size") + .setDescription("The size I'm measuring") + .setUnit("1") + .buildObserver(); + measurement.record(1); + measurement.record(1, Attributes.of(stringKey("thing"), "car")); + } + + @Test + void noopDoubleCounter_doesNotThrow() { + DoubleCounter counter = + meter + .counterBuilder("size") + .ofDoubles() + .setDescription("The size I'm measuring") + .setUnit("1") + .build(); + counter.add(1.2); + counter.add(2.5, Attributes.of(stringKey("thing"), "car")); + counter.add(2.5, Attributes.of(stringKey("thing"), "car"), Context.current()); + + ObservableDoubleMeasurement measurement = + meter + .counterBuilder("size") + .ofDoubles() + .setDescription("The size I'm measuring") + .setUnit("1") + .buildObserver(); + measurement.record(1.2); + measurement.record(2.5, Attributes.of(stringKey("thing"), "car")); + } + + @Test + void noopLongUpDownCounter_doesNotThrow() { + LongUpDownCounter counter = + meter + .upDownCounterBuilder("size") + .setDescription("The size I'm measuring") + .setUnit("1") + .build(); + counter.add(-1); + counter.add(1, Attributes.of(stringKey("thing"), "car")); + counter.add(1, Attributes.of(stringKey("thing"), "car"), Context.current()); + + ObservableLongMeasurement measurement = + meter + .upDownCounterBuilder("size") + .setDescription("The size I'm measuring") + .setUnit("1") + .buildObserver(); + measurement.record(-1); + measurement.record(1, Attributes.of(stringKey("thing"), "car")); + } + + @Test + void noopDoubleUpDownCounter_doesNotThrow() { + DoubleUpDownCounter counter = + meter + .upDownCounterBuilder("size") + .ofDoubles() + .setDescription("The size I'm measuring") + .setUnit("1") + .build(); + counter.add(-2e4); + counter.add(1.0e-1, Attributes.of(stringKey("thing"), "car")); + counter.add(1.0e-1, Attributes.of(stringKey("thing"), "car"), Context.current()); + + ObservableDoubleMeasurement measurement = + meter + .upDownCounterBuilder("size") + .ofDoubles() + .setDescription("The size I'm measuring") + .setUnit("1") + .buildObserver(); + measurement.record(-2e4); + measurement.record(1.0e-1, Attributes.of(stringKey("thing"), "car")); + } + + @Test + void noopLongHistogram_doesNotThrow() { + LongHistogram histogram = + meter + .histogramBuilder("size") + .ofLongs() + .setDescription("The size I'm measuring") + .setUnit("1") + .build(); + histogram.record(-1); + histogram.record(1, Attributes.of(stringKey("thing"), "car")); + histogram.record(1, Attributes.of(stringKey("thing"), "car"), Context.current()); + } + + @Test + void noopDoubleHistogram_doesNotThrow() { + DoubleHistogram histogram = + meter + .histogramBuilder("size") + .setDescription("The size I'm measuring") + .setUnit("1") + .build(); + histogram.record(-2e4); + histogram.record(1.0e-1, Attributes.of(stringKey("thing"), "car")); + histogram.record(1.0e-1, Attributes.of(stringKey("thing"), "car"), Context.current()); + } + + @Test + void noopLongGauge_doesNotThrow() { + LongGauge gauge = + meter + .gaugeBuilder("temperature") + .ofLongs() + .setDescription("The current temperature") + .setUnit("C") + .build(); + gauge.set(1); + gauge.set(2, Attributes.of(stringKey("thing"), "engine")); + gauge.set(2, Attributes.of(stringKey("thing"), "engine"), Context.current()); + + ObservableLongMeasurement measurement = + meter + .gaugeBuilder("temperature") + .ofLongs() + .setDescription("The current temperature") + .setUnit("C") + .buildObserver(); + measurement.record(1); + measurement.record(1, Attributes.of(stringKey("thing"), "engine")); + } + + @Test + void noopObservableLongGauge_doesNotThrow() { + meter + .gaugeBuilder("temperature") + .ofLongs() + .setDescription("The current temperature") + .setUnit("C") + .buildWithCallback(m -> { + m.record(1); + m.record(2, Attributes.of(stringKey("thing"), "engine")); + }); + } + + @Test + void noopDoubleGauge_doesNotThrow() { + DoubleGauge gauge = + meter + .gaugeBuilder("temperature") + .setDescription("The current temperature") + .setUnit("C") + .build(); + gauge.set(1); + gauge.set(2, Attributes.of(stringKey("thing"), "engine")); + gauge.set(2, Attributes.of(stringKey("thing"), "engine"), Context.current()); + + ObservableDoubleMeasurement measurement = + meter + .gaugeBuilder("temperature") + .setDescription("The current temperature") + .setUnit("C") + .buildObserver(); + measurement.record(1.0); + measurement.record(1.0, Attributes.of(stringKey("thing"), "engine")); + } + + @Test + void noopObservableDoubleGauge_doesNotThrow() { + meter + .gaugeBuilder("temperature") + .setDescription("The current temperature") + .setUnit("C") + .buildWithCallback(m -> { + m.record(1.0e1); + m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); + }); + } + + @Test + void noopObservableLongCounter_doesNotThrow() { + meter + .counterBuilder("temperature") + .setDescription("The current temperature") + .setUnit("C") + .buildWithCallback(m -> { + m.record(1); + m.record(2, Attributes.of(stringKey("thing"), "engine")); + }); + } + + @Test + void noopObservableDoubleCounter_doesNotThrow() { + meter + .counterBuilder("temperature") + .ofDoubles() + .setDescription("The current temperature") + .setUnit("C") + .buildWithCallback(m -> { + m.record(1.0e1); + m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); + }); + } + + @Test + void noopObservableLongUpDownCounter_doesNotThrow() { + meter + .upDownCounterBuilder("temperature") + .setDescription("The current temperature") + .setUnit("C") + .buildWithCallback(m -> { + m.record(1); + m.record(2, Attributes.of(stringKey("thing"), "engine")); + }); + } + + @Test + void noopObservableDoubleUpDownCounter_doesNotThrow() { + meter + .upDownCounterBuilder("temperature") + .ofDoubles() + .setDescription("The current temperature") + .setUnit("C") + .buildWithCallback(m -> { + m.record(1.0e1); + m.record(-27.4, Attributes.of(stringKey("thing"), "engine")); + }); + } + + @Test + @SuppressWarnings("NullAway") + void noopBatchCallback_doesNotThrow() { + meter.batchCallback(() -> {}, null); + } +} diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultTracerTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultTracerTest.java new file mode 100644 index 00000000000..41f80623d5e --- /dev/null +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractDefaultTracerTest.java @@ -0,0 +1,171 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.testing.internal; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanBuilder; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +/** Unit tests for No-op {@link Tracer}. */ +// Need to suppress warnings for MustBeClosed because Android 14 does not support +// try-with-resources. +@SuppressWarnings("MustBeClosedChecker") +public abstract class AbstractDefaultTracerTest { + private final Tracer defaultTracer = getTracer(); + private static final String SPAN_NAME = "MySpanName"; + private static final SpanContext spanContext = + SpanContext.create( + "00000000000000000000000000000061", + "0000000000000061", + TraceFlags.getDefault(), + TraceState.getDefault()); + + public abstract Tracer getTracer(); + + public abstract TracerProvider getTracerProvider(); + + @Test + void returnsDefaultTracer() { + TracerProvider tracerProvider = getTracerProvider(); + Class want = defaultTracer.getClass(); + assertThat( + tracerProvider + .tracerBuilder("test") + .setSchemaUrl("schema") + .setInstrumentationVersion("1") + .build()) + .isInstanceOf(want); + assertThat(tracerProvider.get("test")).isInstanceOf(want); + assertThat(tracerProvider.get("test", "1.0")).isInstanceOf(want); + } + + @Test + void defaultSpanBuilderWithName() { + assertThat(defaultTracer.spanBuilder(SPAN_NAME).startSpan().getSpanContext().isValid()) + .isFalse(); + } + + @Test + void defaultIsEnabled() { + assertThat(defaultTracer.isEnabled()).isFalse(); + } + + @Test + @SuppressWarnings("NullAway") + void spanContextPropagationExplicitParent() { + assertThat( + defaultTracer + .spanBuilder(SPAN_NAME) + .setParent(Context.root().with(Span.wrap(spanContext))) + .startSpan() + .getSpanContext()) + .isSameAs(spanContext); + + SpanBuilder builder = defaultTracer.spanBuilder(SPAN_NAME); + assertThat(builder.setParent(null)).isSameAs(builder); + } + + @Test + void spanContextPropagation() { + Span parent = Span.wrap(spanContext); + + Span span = + defaultTracer.spanBuilder(SPAN_NAME).setParent(Context.root().with(parent)).startSpan(); + assertThat(span.getSpanContext()).isSameAs(spanContext); + } + + @Test + void noSpanContextMakesInvalidSpans() { + Span span = defaultTracer.spanBuilder(SPAN_NAME).startSpan(); + assertThat(span.getSpanContext()).isSameAs(SpanContext.getInvalid()); + } + + @Test + void spanContextPropagation_fromContext() { + Context context = Context.current().with(Span.wrap(spanContext)); + + Span span = defaultTracer.spanBuilder(SPAN_NAME).setParent(context).startSpan(); + assertThat(span.getSpanContext()).isSameAs(spanContext); + } + + @Test + void spanContextPropagation_fromContextAfterNoParent() { + Context context = Context.current().with(Span.wrap(spanContext)); + + Span span = defaultTracer.spanBuilder(SPAN_NAME).setNoParent().setParent(context).startSpan(); + assertThat(span.getSpanContext()).isSameAs(spanContext); + } + + @Test + void spanContextPropagation_fromContextThenNoParent() { + Context context = Context.current().with(Span.wrap(spanContext)); + + Span span = defaultTracer.spanBuilder(SPAN_NAME).setParent(context).setNoParent().startSpan(); + assertThat(span.getSpanContext()).isEqualTo(SpanContext.getInvalid()); + } + + @Test + @SuppressWarnings("NullAway") + @SuppressLogger(loggerName = "io.opentelemetry.usage") + void doNotCrash_NoopImplementation() { + assertThatCode( + () -> { + SpanBuilder spanBuilder = defaultTracer.spanBuilder(null); + spanBuilder.setSpanKind(null); + spanBuilder.setParent(null); + spanBuilder.setNoParent(); + spanBuilder.addLink(null); + spanBuilder.addLink(null, Attributes.empty()); + spanBuilder.addLink(SpanContext.getInvalid(), null); + spanBuilder.setAttribute((String) null, "foo"); + spanBuilder.setAttribute("foo", null); + spanBuilder.setAttribute(null, 0L); + spanBuilder.setAttribute(null, 0.0); + spanBuilder.setAttribute(null, false); + spanBuilder.setAttribute((AttributeKey) null, "foo"); + spanBuilder.setAttribute(stringKey(null), "foo"); + spanBuilder.setAttribute(stringKey(""), "foo"); + spanBuilder.setAttribute(stringKey("foo"), null); + spanBuilder.setStartTimestamp(-1, TimeUnit.MILLISECONDS); + spanBuilder.setStartTimestamp(1, null); + spanBuilder.setParent(Context.root().with(Span.wrap(null))); + spanBuilder.setParent(Context.root()); + spanBuilder.setNoParent(); + spanBuilder.addLink(Span.getInvalid().getSpanContext()); + spanBuilder.addLink(Span.getInvalid().getSpanContext(), Attributes.empty()); + spanBuilder.setAttribute("key", "value"); + spanBuilder.setAttribute("key", 12345L); + spanBuilder.setAttribute("key", .12345); + spanBuilder.setAttribute("key", true); + spanBuilder.setAttribute(stringKey("key"), "value"); + spanBuilder.setAllAttributes(Attributes.of(stringKey("key"), "value")); + spanBuilder.setAllAttributes(Attributes.empty()); + spanBuilder.setAllAttributes(null); + spanBuilder.setStartTimestamp(12345L, TimeUnit.NANOSECONDS); + spanBuilder.setStartTimestamp(Instant.EPOCH); + spanBuilder.setStartTimestamp(null); + spanBuilder.setAttribute(longKey("MyLongAttributeKey"), 123); + assertThat(spanBuilder.startSpan().getSpanContext().isValid()).isFalse(); + }) + .doesNotThrowAnyException(); + } +} diff --git a/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java new file mode 100644 index 00000000000..d613a16fd27 --- /dev/null +++ b/api/testing-internal/src/main/java/io/opentelemetry/api/testing/internal/AbstractOpenTelemetryTest.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.api.testing.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.ContextPropagators; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +/** Unit tests for No-op {@link OpenTelemetry}. */ +public abstract class AbstractOpenTelemetryTest { + + @BeforeAll + public static void beforeClass() { + GlobalOpenTelemetry.resetForTest(); + } + + private void setOpenTelemetry() { + GlobalOpenTelemetry.set(getOpenTelemetry()); + } + + @AfterEach + public void after() { + GlobalOpenTelemetry.resetForTest(); + } + + @Test + void testDefault() { + assertThat(getOpenTelemetry().getTracerProvider()).isSameAs(getTracerProvider()); + assertThat(getOpenTelemetry().getPropagators()).isSameAs(ContextPropagators.noop()); + assertThat(getOpenTelemetry().getMeterProvider()).isSameAs(getMeterProvider()); + assertThat(getOpenTelemetry().getLogsBridge()).isSameAs(getLoggerProvider()); + } + + protected abstract TracerProvider getTracerProvider(); + + protected OpenTelemetry getOpenTelemetry() { + return OpenTelemetry.noop(); + } + + protected abstract MeterProvider getMeterProvider(); + + protected abstract LoggerProvider getLoggerProvider(); + + @Test + void propagating() { + ContextPropagators contextPropagators = Mockito.mock(ContextPropagators.class); + OpenTelemetry openTelemetry = OpenTelemetry.propagating(contextPropagators); + + assertThat(openTelemetry.getTracerProvider()).isSameAs(getTracerProvider()); + assertThat(openTelemetry.getMeterProvider()).isSameAs(getMeterProvider()); + assertThat(openTelemetry.getLogsBridge()).isSameAs(getLoggerProvider()); + assertThat(openTelemetry.getPropagators()).isSameAs(contextPropagators); + } + + @Test + void testGlobalBeforeSet() { + assertThat(GlobalOpenTelemetry.getTracerProvider()).isSameAs(getTracerProvider()); + assertThat(GlobalOpenTelemetry.getTracerProvider()) + .isSameAs(GlobalOpenTelemetry.getTracerProvider()); + assertThat(GlobalOpenTelemetry.getPropagators()).isSameAs(GlobalOpenTelemetry.getPropagators()); + } + + @Test + void independentNonGlobalPropagators() { + ContextPropagators propagators1 = Mockito.mock(ContextPropagators.class); + OpenTelemetry otel1 = OpenTelemetry.propagating(propagators1); + ContextPropagators propagators2 = Mockito.mock(ContextPropagators.class); + OpenTelemetry otel2 = OpenTelemetry.propagating(propagators2); + + assertThat(otel1.getPropagators()).isSameAs(propagators1); + assertThat(otel2.getPropagators()).isSameAs(propagators2); + } + + @Test + void setThenSet() { + assertThat(GlobalOpenTelemetry.isSet()).isFalse(); + setOpenTelemetry(); + assertThat(GlobalOpenTelemetry.isSet()).isTrue(); + assertThatThrownBy(() -> GlobalOpenTelemetry.set(getOpenTelemetry())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("GlobalOpenTelemetry.set has already been called") + .hasStackTraceContaining("setOpenTelemetry"); + } + + @Test + void getThenSet() { + assertThat(GlobalOpenTelemetry.isSet()).isFalse(); + assertThat(GlobalOpenTelemetry.getOrNoop()).isSameAs(OpenTelemetry.noop()); + + // Calling GlobalOpenTelemetry.get() has the side effect of setting GlobalOpenTelemetry to an + // (obfuscated) noop. + // Call GlobalOpenTelemetry.get() using a utility method so we can later assert it was + // responsible for setting GlobalOpenTelemetry. + assertThat(getGlobalOpenTelemetry()) + .satisfies(instance -> + assertThat(instance.getClass().getName()) + .isEqualTo("io.opentelemetry.api.GlobalOpenTelemetry$ObfuscatedOpenTelemetry")) + .extracting("delegate") + .isSameAs(OpenTelemetry.noop()); + + assertThat(GlobalOpenTelemetry.isSet()).isTrue(); + assertThat(GlobalOpenTelemetry.getOrNoop()).isNotSameAs(OpenTelemetry.noop()); + + assertThatThrownBy(() -> GlobalOpenTelemetry.set(getOpenTelemetry())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("GlobalOpenTelemetry.set has already been called") + .hasStackTraceContaining("getGlobalOpenTelemetry"); + } + + private static OpenTelemetry getGlobalOpenTelemetry() { + return GlobalOpenTelemetry.get(); + } + + @Test + void getOrNoop() { + // Should be able to call getOrNoop multiple times without side effect and later call set. + assertThat(GlobalOpenTelemetry.getOrNoop()).isSameAs(OpenTelemetry.noop()); + assertThat(GlobalOpenTelemetry.getOrNoop()).isSameAs(OpenTelemetry.noop()); + setOpenTelemetry(); + assertThat(GlobalOpenTelemetry.getOrNoop()).isNotSameAs(OpenTelemetry.noop()); + } + + @Test + void toString_noop_Valid() { + assertThat(getOpenTelemetry().toString()) + .isEqualTo( + "DefaultOpenTelemetry{" + + "propagators=DefaultContextPropagators{textMapPropagator=NoopTextMapPropagator}" + + "}"); + } +} diff --git a/bom-alpha/build.gradle.kts b/bom-alpha/build.gradle.kts index 0ed9fbdeaec..df363b28fd1 100644 --- a/bom-alpha/build.gradle.kts +++ b/bom-alpha/build.gradle.kts @@ -6,4 +6,12 @@ description = "OpenTelemetry Bill of Materials (Alpha)" group = "io.opentelemetry" base.archivesName.set("opentelemetry-bom-alpha") -otelBom.projectFilter.set { it.findProperty("otel.release") == "alpha" } \ No newline at end of file +otelBom.projectFilter.set { it.findProperty("otel.release") == "alpha" } + +// Required to place dependency on opentelemetry-bom +javaPlatform.allowDependencies() + +dependencies { + // Add dependency on opentelemetry-bom to ensure synchronization between alpha and stable artifacts + api(platform(project(":bom"))) +} diff --git a/bom/build.gradle.kts b/bom/build.gradle.kts index 8ef13b38a42..50d8dc950a1 100644 --- a/bom/build.gradle.kts +++ b/bom/build.gradle.kts @@ -6,4 +6,4 @@ description = "OpenTelemetry Bill of Materials" group = "io.opentelemetry" base.archivesName.set("opentelemetry-bom") -otelBom.projectFilter.set { !it.hasProperty("otel.release") } \ No newline at end of file +otelBom.projectFilter.set { !it.hasProperty("otel.release") } diff --git a/build.gradle.kts b/build.gradle.kts index 684f4b2e991..b2953d90939 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -1,28 +1,21 @@ import java.time.Duration plugins { - id("com.github.ben-manes.versions") id("io.github.gradle-nexus.publish-plugin") id("otel.spotless-conventions") } -if (!JavaVersion.current().isJava11Compatible()) { - throw GradleException( - "JDK 11 or higher is required to build. " + - "One option is to download it from https://adoptopenjdk.net/. If you believe you already " + - "have it, please check that the JAVA_HOME environment variable is pointing at the " + - "JDK 11 installation." - ) -} - apply(from = "version.gradle.kts") nexusPublishing { packageGroup.set("io.opentelemetry") repositories { + // see https://central.sonatype.org/publish/publish-portal-ossrh-staging-api/#configuration sonatype { + nexusUrl.set(uri("https://ossrh-staging-api.central.sonatype.com/service/local/")) + snapshotRepositoryUrl.set(uri("https://central.sonatype.com/repository/maven-snapshots/")) username.set(System.getenv("SONATYPE_USER")) password.set(System.getenv("SONATYPE_KEY")) } @@ -52,13 +45,13 @@ subprojects { tasks { register("updateVersionInDocs") { group = "documentation" + val version = findProperty("release.version") + val readme = file("README.md") doLast { - val version = findProperty("release.version") val versionParts = version.toString().split('.') val minorVersionNumber = Integer.parseInt(versionParts[1]) val nextSnapshot = "${versionParts[0]}.${minorVersionNumber + 1}.0-SNAPSHOT" - val readme = file("README.md") if (readme.exists()) { val readmeText = readme.readText() val updatedText = readmeText diff --git a/buildSrc/build.gradle.kts b/buildSrc/build.gradle.kts index a6d0af0000b..0dd5d2a0cb5 100644 --- a/buildSrc/build.gradle.kts +++ b/buildSrc/build.gradle.kts @@ -2,7 +2,28 @@ plugins { `kotlin-dsl` // When updating, update below in dependencies too - id("com.diffplug.spotless") version "6.4.2" + id("com.diffplug.spotless") version "8.11.0" +} + +spotless { + kotlinGradle { + ktlint().editorConfigOverride(mapOf( + "indent_size" to "2", + "continuation_indent_size" to "2", + "max_line_length" to "160", + "insert_final_newline" to "true", + "ktlint_standard_no-wildcard-imports" to "disabled", + // ktlint does not break up long lines, it just fails on them + "ktlint_standard_max-line-length" to "disabled", + // ktlint makes it *very* hard to locate where this actually happened + "ktlint_standard_trailing-comma-on-call-site" to "disabled", + // depends on ktlint_standard_wrapping + "ktlint_standard_trailing-comma-on-declaration-site" to "disabled", + // also very hard to find out where this happens + "ktlint_standard_wrapping" to "disabled" + )) + target("**/*.gradle.kts") + } } repositories { @@ -12,41 +33,23 @@ repositories { } dependencies { + implementation("biz.aQute.bnd:biz.aQute.bnd.gradle:7.4.0") + implementation(enforcedPlatform("com.squareup.wire:wire-bom:7.1.2")) + implementation("com.google.auto.value:auto-value-annotations:1.11.1") // When updating, update above in plugins too - implementation("com.diffplug.spotless:spotless-plugin-gradle:6.4.2") - // Needed for japicmp but not automatically brought in for some reason. - implementation("com.google.guava:guava:31.1-jre") + implementation("com.diffplug.spotless:spotless-plugin-gradle:8.11.0") + implementation("com.gradle.develocity:com.gradle.develocity.gradle.plugin:4.6.1") + implementation("com.fasterxml.jackson.core:jackson-databind:2.23.0") implementation("com.squareup:javapoet:1.13.0") - implementation("com.squareup.wire:wire-compiler:4.3.0") - implementation("com.squareup.wire:wire-gradle-plugin:4.3.0") - implementation("gradle.plugin.com.google.protobuf:protobuf-gradle-plugin:0.8.18") - implementation("gradle.plugin.io.morethan.jmhreport:gradle-jmh-report:0.9.0") - implementation("me.champeau.gradle:japicmp-gradle-plugin:0.4.0") - implementation("me.champeau.jmh:jmh-gradle-plugin:0.6.6") - implementation("net.ltgt.gradle:gradle-errorprone-plugin:2.0.2") - implementation("net.ltgt.gradle:gradle-nullaway-plugin:1.3.0") - implementation("ru.vyarus:gradle-animalsniffer-plugin:1.5.4") -} - -// We can't apply conventions to this build so include important ones such as the Java compilation -// target. -java { - toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) - } -} - -tasks { - withType().configureEach { - with(options) { - release.set(8) - } - } -} - -spotless { - kotlinGradle { - ktlint().userData(mapOf("indent_size" to "2", "continuation_indent_size" to "2", "disabled_rules" to "no-wildcard-imports")) - target("**/*.gradle.kts") - } + implementation("com.squareup.wire:wire-compiler") + implementation("com.squareup.wire:wire-gradle-plugin") + implementation("com.google.protobuf:protobuf-gradle-plugin:0.10.1") + implementation("gradle.plugin.io.morethan.jmhreport:gradle-jmh-report:0.9.6") + implementation("me.champeau.gradle:japicmp-gradle-plugin:0.4.6") + implementation("me.champeau.jmh:jmh-gradle-plugin:0.7.4") + implementation("net.ltgt.gradle:gradle-errorprone-plugin:5.2.0") + implementation("net.ltgt.gradle:gradle-nullaway-plugin:3.3.0") + implementation("org.jetbrains.kotlin:kotlin-gradle-plugin:2.4.21") + implementation("org.sonatype.gradle.plugins:scan-gradle-plugin:4.1.2-01") + implementation("ru.vyarus:gradle-animalsniffer-plugin:2.0.1") } diff --git a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/DeclarativeConfigPojoGenerator.kt b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/DeclarativeConfigPojoGenerator.kt new file mode 100644 index 00000000000..86244fd3047 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/DeclarativeConfigPojoGenerator.kt @@ -0,0 +1,706 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle + +import com.fasterxml.jackson.databind.JsonNode +import com.fasterxml.jackson.databind.ObjectMapper +import java.io.File + +/** + * POJO generator for the declarative-config model package. Reads the opentelemetry-configuration + * JSON Schema and emits Java source files directly. + * + * Design notes: + * - All schema types (object types and enums) get a "Model" suffix. + * - All enums are top-level files β€” not nested inner classes β€” regardless of how many schema types + * reference them. Cross-model references import the enum type and use its simple name. + * - "Experimental*" types go into the model.internal sub-package. + * - Properties with object-typed additionalProperties get a synthetic "*PropertyModel" companion + * class. When additionalProperties is boolean true (root schema) Map is used + * directly. + * - Properties whose JSON key ends with "/development" are experimental. On stable (non- + * Experimental) classes, these properties are not exposed as public getters or builders. + * Instead, their deserialized values are stored in an opaque experimentalProperties map, and + * a generated "*ModelAccessor" class in model.internal provides typed access. + * - All $refs are local (#/$defs/...). + */ +class DeclarativeConfigPojoGenerator( + private val schemaFile: File, + private val outputDir: File, + private val modelPackage: String, +) { + private val internalPackage = "$modelPackage.internal" + private val mapper = ObjectMapper() + private lateinit var defs: Map + private lateinit var enumDefNames: Set + private lateinit var extensibleDefNames: Set + + private data class ResolvedType(val expr: String, val imports: Set = emptySet()) + + private data class FieldInfo( + val jsonKey: String, + val constName: String, // SCREAMING_SNAKE_CASE version of jsonKey, used as a Java string constant + val javaField: String, + val getter: String, + val builder: String, + val typeExpr: String, + val typeImports: Set, + val description: String?, + ) + + fun generate() { + val schema = mapper.readTree(schemaFile) + defs = schema["\$defs"]?.properties()?.associate { it.key to it.value } ?: emptyMap() + + enumDefNames = defs.entries.filter { (_, node) -> node.has("enum") }.map { it.key }.toSet() + extensibleDefNames = defs.entries + .filter { (_, node) -> node["additionalProperties"]?.let { !it.isBoolean && it.isObject } == true } + .map { it.key } + .toSet() + + // The root schema (title: OpenTelemetryConfiguration) generates OpenTelemetryConfigurationModel. + val rootTitle = schema["title"]?.asText() ?: error("Root schema has no title") + generateClassFile(rootTitle, schema) + + for ((defName, defNode) in defs) { + if (defNode.has("enum")) generateEnumFile(defName, defNode) + else generateClassFile(defName, defNode) + } + } + + // ── Naming ────────────────────────────────────────────────────────────────── + + private fun isExperimental(schemaKey: String) = schemaKey.startsWith("Experimental") + + private fun isExperimentalProperty(jsonKey: String) = jsonKey.endsWith("/development") + + private fun packageForKey(schemaKey: String) = + if (isExperimental(schemaKey)) internalPackage else modelPackage + + private fun classNameForKey(key: String) = "${key}Model" + + private fun javaTypeForRef(defKey: String) = classNameForKey(defKey) + + // ── Property name conversion ───────────────────────────────────────────────── + + /** + * Maps a JSON property name (snake_case, may contain "/") to a Java field name. + * "default" β†’ "_default" (reserved keyword); "foo_bar/baz" β†’ "fooBarBaz". + */ + private fun fieldName(jsonKey: String): String { + val raw = jsonKey + .split("_", "/") + .mapIndexed { i, part -> if (i == 0) part else part.replaceFirstChar { it.uppercase() } } + .joinToString("") + return if (raw == "default") "_default" else raw + } + + /** + * The base name used to build getter/builder names. Strips the leading underscore from + * "_default" so the methods are "getDefault"/"setDefault", not "get_default". + */ + private fun baseNameFor(jsonKey: String): String { + val field = fieldName(jsonKey) + return if (field == "_default") "default" else field + } + + private fun getterName(jsonKey: String) = + "get${baseNameFor(jsonKey).replaceFirstChar { it.uppercase() }}" + + private fun builderName(jsonKey: String) = + "set${baseNameFor(jsonKey).replaceFirstChar { it.uppercase() }}" + + // ── Type resolution ────────────────────────────────────────────────────────── + + private fun resolvePropertyType(propNode: JsonNode, fromPackage: String): ResolvedType { + val ref = propNode["\$ref"]?.asText() + if (ref != null) return resolveDefRef(ref.removePrefix("#/\$defs/"), fromPackage) + + if (isArrayType(propNode["type"])) return resolveArrayType(propNode["items"], fromPackage) + + if (propNode.has("oneOf")) return ResolvedType("Object") + + for (kw in listOf("anyOf", "allOf", "if")) { + if (propNode.has(kw)) error( + "Unhandled schema keyword \"$kw\" encountered during generation. " + + "Update the generator to handle this construct. Property node: $propNode" + ) + } + + // Enums are only handled when declared as top-level $defs (see enumDefNames/generateEnumFile); + // a $ref to such a def resolves to its generated *Model enum above. An inline enum here would + // otherwise fall through to resolveScalarType and be silently emitted as its base scalar type + // (e.g. String), losing type safety. + if (propNode.has("enum")) error( + "Inline enum encountered during generation. Promote it to a top-level \$defs entry " + + "so it generates a typed *Model enum, or update the generator to handle inline enums. " + + "Property node: $propNode" + ) + + return resolveScalarType(propNode["type"]) + } + + private fun resolveDefRef(defKey: String, fromPackage: String): ResolvedType { + val defPkg = packageForKey(defKey) + val simple = javaTypeForRef(defKey) + return if (defPkg == fromPackage) ResolvedType(simple) + else ResolvedType(simple, setOf("$defPkg.$simple")) + } + + private fun resolveArrayType(itemsNode: JsonNode?, fromPackage: String): ResolvedType { + if (itemsNode == null) error( + "Array property has no \"items\" schema: cannot determine element type. " + + "Update the generator to handle this construct." + ) + + val ref = itemsNode["\$ref"]?.asText() + if (ref != null) { + val inner = resolveDefRef(ref.removePrefix("#/\$defs/"), fromPackage) + return ResolvedType("List<${inner.expr}>", inner.imports + "java.util.List") + } + + val javaType = when (itemsNode["type"]?.asText()) { + "string" -> "String" + "number" -> "Double" + "integer" -> "Integer" + "boolean" -> "Boolean" + else -> error( + "Unhandled array items type \"${itemsNode["type"]?.asText()}\" encountered during generation. " + + "Update the generator to handle this type. Items node: $itemsNode" + ) + } + return ResolvedType("List<$javaType>", setOf("java.util.List")) + } + + private fun resolveScalarType(typeNode: JsonNode?): ResolvedType { + if (typeNode == null) error( + "Property has no \$ref, type, oneOf, anyOf, allOf, or if: cannot determine Java type. " + + "Update the generator to handle this construct." + ) + val types = if (typeNode.isArray) typeNode.map { it.asText() } else listOf(typeNode.asText()) + return when (types.firstOrNull { it != "null" }) { + "string" -> ResolvedType("String") + "integer" -> ResolvedType("Integer") + "boolean" -> ResolvedType("Boolean") + "number" -> ResolvedType("Double") + else -> error( + "Unhandled scalar type(s) $types encountered during generation. " + + "Update the generator to handle this type." + ) + } + } + + // Handles both "type": "array" and "type": ["array", "null"]. + private fun isArrayType(typeNode: JsonNode?): Boolean { + if (typeNode == null) return false + return typeNode.asText() == "array" || (typeNode.isArray && typeNode.any { it.asText() == "array" }) + } + + // ── File generation ────────────────────────────────────────────────────────── + + private fun generateEnumFile(defKey: String, defNode: JsonNode) { + val className = classNameForKey(defKey) + val pkg = packageForKey(defKey) + val values = defNode["enum"].map { it.asText() } + writeFile(pkg, className, buildEnumSource(pkg, className, values)) + } + + private fun generateClassFile(defKey: String, defNode: JsonNode) { + val className = classNameForKey(defKey) + val pkg = packageForKey(defKey) + val isExtensible = defKey in extensibleDefNames + val hasOpenAdditionalProperties = defNode["additionalProperties"]?.isBoolean == true && + defNode["additionalProperties"].asBoolean() + val isStable = !isExperimental(defKey) + + writeFile(pkg, className, buildClassSource(pkg, className, defKey, defNode, isExtensible, hasOpenAdditionalProperties)) + + if (isExtensible && !isStable) { + val propClassName = "${defKey}PropertyModel" + writeFile(pkg, propClassName, buildPropertyModelSource(pkg, propClassName)) + } + + if (isStable) { + val experimentalPropPairs = defNode["properties"]?.properties() + ?.filter { isExperimentalProperty(it.key) } + ?.toList() ?: emptyList() + if (experimentalPropPairs.isNotEmpty()) { + generateExperimentalAccessorFile(defKey, pkg, experimentalPropPairs) + } + } + } + + private fun generateExperimentalAccessorFile( + defKey: String, + stablePkg: String, + experimentalPropPairs: List>, + ) { + val accessorClassName = "${classNameForKey(defKey)}Accessor" + writeFile(internalPackage, accessorClassName, + buildExperimentalAccessorSource(defKey, stablePkg, experimentalPropPairs)) + } + + private fun writeFile(pkg: String, className: String, content: String) { + val pkgDir = outputDir.resolve(pkg.replace('.', '/')) + pkgDir.mkdirs() + pkgDir.resolve("$className.java").writeText(content) + } + + // ── Source builders ────────────────────────────────────────────────────────── + + private fun buildEnumSource(pkg: String, className: String, values: List) = buildString { + val constants = values.map { it.toScreamingSnakeCase() to it } + + appendLicense() + append("\npackage $pkg;\n\n") + append("import com.fasterxml.jackson.annotation.JsonCreator;\n") + append("import com.fasterxml.jackson.annotation.JsonValue;\n") + append("import java.util.HashMap;\n") + append("import java.util.Map;\n") + append("import javax.annotation.Generated;\n") + append("\n@Generated(\"io.opentelemetry.gradle.DeclarativeConfigPojoGenerator\")\n") + append("public enum $className {\n") + + constants.forEachIndexed { i, (name, value) -> + val terminator = if (i < constants.size - 1) "," else ";" + append(" $name(\"$value\")$terminator\n") + } + + append(" private final String value;\n") + append(" private static final Map CONSTANTS = new HashMap();\n\n") + append(" static {\n for ($className c : values()) {\n CONSTANTS.put(c.value, c);\n }\n }\n\n") + append(" $className(String value) {\n this.value = value;\n }\n\n") + append(" @Override\n public String toString() {\n return this.value;\n }\n\n") + append(" @JsonValue\n public String value() {\n return this.value;\n }\n\n") + append(" @JsonCreator\n public static $className fromValue(String value) {\n") + append(" $className constant = CONSTANTS.get(value);\n") + append(" if (constant == null) {\n throw new IllegalArgumentException(value);\n") + append(" } else {\n return constant;\n }\n }\n}\n") + } + + private fun buildClassSource( + pkg: String, + className: String, + defKey: String, + defNode: JsonNode, + isExtensible: Boolean, + hasOpenAdditionalProperties: Boolean, + ) = buildString { + val allProperties = defNode["properties"]?.properties()?.toList() ?: emptyList() + val isStable = !isExperimental(defKey) + + val stablePropertyPairs = if (isStable) allProperties.filter { !isExperimentalProperty(it.key) } else allProperties + val experimentalPropPairs = if (isStable) allProperties.filter { isExperimentalProperty(it.key) } else emptyList>() + + val fields = stablePropertyPairs.map { (jsonKey, propNode) -> + val resolved = resolvePropertyType(propNode, pkg) + FieldInfo( + jsonKey = jsonKey, + constName = jsonKey.toScreamingSnakeCase(), + javaField = fieldName(jsonKey), + getter = getterName(jsonKey), + builder = builderName(jsonKey), + typeExpr = resolved.expr, + typeImports = resolved.imports, + description = propNode["description"]?.asText(), + ) + } + + // Types from model.internal produce an import; same-package types produce none. + data class ExpPropInfo(val jsonKey: String, val typeExpr: String, val typeImport: String?) + val expProps = if (isStable) experimentalPropPairs.map { (jsonKey, propNode) -> + val resolved = resolvePropertyType(propNode, pkg) + ExpPropInfo(jsonKey, resolved.expr, resolved.imports.firstOrNull()) + } else emptyList() + + // Non-list stable properties are candidates for graduated /development key detection. + val stableObjectProps = if (isStable) fields.filter { !it.typeExpr.startsWith("List<") } else emptyList() + + val companionName = if (isExtensible && !isStable) "${defKey}PropertyModel" else null + val additionalPropsType = when { + isExtensible && !isStable -> "Map" + hasOpenAdditionalProperties && !isStable -> "Map" + else -> null + } + val allowsAdditionalProperties = isStable && (isExtensible || hasOpenAdditionalProperties) + // Only generate extension property infrastructure when it serves a purpose: current + // experimental properties to store, stable non-list properties as graduation candidates, + // or an open schema acting as a ComponentProvider extension point. + val needsExtensionProperties = isStable && + (expProps.isNotEmpty() || stableObjectProps.isNotEmpty() || allowsAdditionalProperties) + + val imports = sortedSetOf( + "com.fasterxml.jackson.annotation.JsonInclude", + "com.fasterxml.jackson.annotation.JsonPropertyOrder", + "javax.annotation.Generated", + "javax.annotation.Nullable", + ) + if (fields.any { it.typeExpr.startsWith("List<") }) imports.add("java.util.List") + if (additionalPropsType != null) { + imports.addAll(listOf( + "java.util.LinkedHashMap", + "java.util.Map", + "com.fasterxml.jackson.annotation.JsonAnyGetter", + "com.fasterxml.jackson.annotation.JsonAnySetter", + )) + } + if (fields.isNotEmpty()) imports.add("com.fasterxml.jackson.annotation.JsonProperty") + for (f in fields) imports.addAll(f.typeImports) + if (isStable) { + for (f in fields) { + imports.add("static $pkg.$className.${f.constName}") + } + } + if (needsExtensionProperties) { + imports.addAll(listOf( + "java.util.HashMap", + "java.util.LinkedHashMap", + "java.util.Map", + "com.fasterxml.jackson.annotation.JsonAnyGetter", + "com.fasterxml.jackson.annotation.JsonAnySetter", + "$internalPackage.ExtensionPropertyUtil", + )) + if (expProps.isNotEmpty()) { + val accessorFqcn = "$internalPackage.${classNameForKey(defKey)}Accessor" + imports.add(accessorFqcn) + imports.add("static $accessorFqcn.EXPERIMENTAL_PROPERTIES") + } + if (expProps.isEmpty() || stableObjectProps.isEmpty()) { + imports.add("java.util.Collections") + } + } + + appendLicense() + append("\npackage $pkg;\n\n") + for (imp in imports) append("import $imp;\n") + append("\n@JsonInclude(JsonInclude.Include.NON_NULL)\n") + + // @JsonPropertyOrder covers stable properties only β€” experimental entries are served via + // @JsonAnyGetter and always append last regardless. Static self-imports make the class's + // own package-private constants visible at the class-level annotation site. + val propKeyRefs = if (isStable) { + stablePropertyPairs.map { (jsonKey, _) -> jsonKey.toScreamingSnakeCase() } + } else { + allProperties.map { "\"${it.key}\"" } + } + if (propKeyRefs.isEmpty()) { + append("@JsonPropertyOrder({})\n") + } else { + append("@JsonPropertyOrder({\n") + propKeyRefs.forEachIndexed { i, k -> + append(" $k${if (i < propKeyRefs.size - 1) "," else ""}\n") + } + append("})\n") + } + + append("@Generated(\"io.opentelemetry.gradle.DeclarativeConfigPojoGenerator\")\n") + append("public class $className {\n\n") + + if (isStable) { + for (f in fields) { + append(" static final String ${f.constName} = \"${f.jsonKey}\";\n") + } + if (fields.isNotEmpty()) append("\n") + } + if (needsExtensionProperties) { + // STABLE_PROPERTIES maps non-list stable property names to their types for graduated + // /development key detection. Omitted when empty. + if (stableObjectProps.isNotEmpty()) { + append(" private static final Map> STABLE_PROPERTIES;\n") + append(" static {\n STABLE_PROPERTIES = new HashMap<>();\n") + for (f in stableObjectProps) { + append(" STABLE_PROPERTIES.put(${f.constName}, ${f.typeExpr}.class);\n") + } + append(" }\n") + } + append(" private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = $allowsAdditionalProperties;\n") + append("\n") + } + for (f in fields) append(" @Nullable private ${f.typeExpr} ${f.javaField};\n") + // Non-stable extensible types keep their own typed additionalProperties map (unchanged). + if (additionalPropsType != null) { + val init = if (companionName != null) "new LinkedHashMap()" + else "new LinkedHashMap()" + append(" private $additionalPropsType additionalProperties = $init;\n") + } + if (needsExtensionProperties) { + append(" private Map extensionProperties = new LinkedHashMap();\n") + } + if (fields.isNotEmpty() || additionalPropsType != null || needsExtensionProperties) append("\n") + + for (f in fields) { + if (f.description != null) { + append(" /**\n") + for (line in formatJavadoc(f.description)) append(" * $line\n") + append(" */\n") + } + val jsonPropRef = if (isStable) f.constName else "\"${f.jsonKey}\"" + append(" @JsonProperty($jsonPropRef)\n") + append(" @Nullable\n") + // Non-list stable getters on classes with extension properties fall back to reading a + // graduated /development value from extensionProperties. The stable field name is passed + // through; ExtensionPropertyUtil.getGraduated internally appends the /development suffix + // to match handleAnySetter's storage key. + if (needsExtensionProperties && !f.typeExpr.startsWith("List<")) { + append(" public ${f.typeExpr} ${f.getter}() {\n") + append(" if (${f.javaField} == null) {\n") + append(" return ExtensionPropertyUtil.getGraduated(${f.constName}, extensionProperties, ${f.typeExpr}.class);\n") + append(" }\n") + append(" return ${f.javaField};\n") + append(" }\n\n") + } else { + append(" public ${f.typeExpr} ${f.getter}() {\n return ${f.javaField};\n }\n\n") + } + append(" @JsonProperty($jsonPropRef)\n") + append(" public $className ${f.builder}(${f.typeExpr} ${f.javaField}) {\n") + append(" this.${f.javaField} = ${f.javaField};\n return this;\n }\n\n") + } + + // Non-stable extensible types: unchanged additionalProperties getter/setter. + if (additionalPropsType != null) { + val apValueType = companionName ?: "Object" + append(" @JsonAnyGetter\n") + append(" public $additionalPropsType getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n") + append(" @JsonAnySetter\n") + append(" public $className setAdditionalProperty(String name, $apValueType value) {\n") + append(" this.additionalProperties.put(name, value);\n return this;\n }\n\n") + } + + if (needsExtensionProperties) { + append(" @JsonAnyGetter\n") + append(" public Map getExtensionProperties() {\n") + if (stableObjectProps.isNotEmpty()) { + append(" return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES);\n") + } else { + append(" return extensionProperties;\n") + } + append(" }\n\n") + append(" @JsonAnySetter\n") + append(" public $className setExtensionProperty(String name, @Nullable Object value) {\n") + append(" ExtensionPropertyUtil.handleAnySetter(\n") + val experimentalPropsArg = if (expProps.isNotEmpty()) "EXPERIMENTAL_PROPERTIES" else "Collections.emptyMap()" + val stablePropsArg = if (stableObjectProps.isNotEmpty()) "STABLE_PROPERTIES" else "Collections.emptyMap()" + append(" name, value, extensionProperties, $experimentalPropsArg, $stablePropsArg,\n") + append(" ALLOWS_ADDITIONAL_PROPERTIES);\n") + append(" return this;\n }\n\n") + } + + val allFields = fields.map { it.javaField } + + (if (additionalPropsType != null) listOf("additionalProperties") else emptyList()) + + (if (needsExtensionProperties) listOf("extensionProperties") else emptyList()) + + // equals/hashCode compare observable state (getter output), not raw storage: a graduated + // property set via the legacy "x/development" key and the same property set directly via its + // stable setter must compare equal, even though one lives in the real field and the other in + // extensionProperties. getGraduated()'s fallback and getExtensionProperties()'s filtering + // already collapse both representations to the same value; toString keeps showing raw storage + // (more useful for debugging which representation is actually in play). + val equalityFields = fields.map { f -> + if (needsExtensionProperties && !f.typeExpr.startsWith("List<")) "${f.getter}()" else f.javaField + } + + (if (additionalPropsType != null) listOf("additionalProperties") else emptyList()) + + (if (needsExtensionProperties) listOf("getExtensionProperties()") else emptyList()) + + appendToString(className, allFields) + append("\n") + appendHashCode(equalityFields) + append("\n") + appendEquals(className, equalityFields) + append("}\n") + } + + private fun buildExperimentalAccessorSource( + defKey: String, + stablePkg: String, + experimentalPropPairs: List>, + ) = buildString { + val stableClassName = classNameForKey(defKey) + val accessorClassName = "${stableClassName}Accessor" + val stableImport = "$stablePkg.$stableClassName" + + data class PropInfo( + val jsonKey: String, + val constName: String, // SCREAMING_SNAKE_CASE key constant, /development suffix stripped + val getter: String, + val builder: String, + val typeExpr: String, + ) + val props = experimentalPropPairs.map { (jsonKey, propNode) -> + val baseKey = jsonKey.removeSuffix("/development") + val typeExpr = resolvePropertyType(propNode, internalPackage).expr + // The accessor emits ${typeExpr}.class in EXPERIMENTAL_PROPERTIES. Parameterized types like + // List would produce non-compiling Java. Fail fast so a schema change adding a + // list-typed /development property is caught at generation time rather than emitting + // broken source. + if (typeExpr.startsWith("List<")) { + error( + "Experimental property '$jsonKey' on '$defKey' has list type '$typeExpr'; the " + + "generator does not support list-typed experimental properties (see " + + "EXPERIMENTAL_PROPERTIES emission in buildExperimentalAccessorSource)." + ) + } + PropInfo( + jsonKey = jsonKey, + constName = baseKey.toScreamingSnakeCase(), + getter = getterName(baseKey), + builder = builderName(baseKey), + typeExpr = typeExpr, + ) + } + + appendLicense() + append("\npackage $internalPackage;\n\n") + append("import $stableImport;\n") + append("import java.util.HashMap;\n") + append("import java.util.Map;\n") + append("import static java.util.Objects.requireNonNull;\n") + append("import javax.annotation.Nullable;\n") + append("\n") + append("/**\n") + append(" * Provides typed access to experimental properties on {@link $stableClassName}.\n") + append(" *\n") + append(" *

    This class is internal and experimental. Its APIs are unstable and can change at any\n") + append(" * time. Its APIs (or a version of them) may be promoted to the public stable API in the\n") + append(" * future, but no guarantees are made.\n") + append(" */\n") + append("public final class $accessorClassName {\n\n") + append(" private $accessorClassName() {}\n\n") + + for (p in props) { + append(" static final String ${p.constName} = \"${p.jsonKey}\";\n") + } + append("\n") + + append(" public static final Map> EXPERIMENTAL_PROPERTIES;\n") + append(" static {\n EXPERIMENTAL_PROPERTIES = new HashMap<>();\n") + for (p in props) { + append(" EXPERIMENTAL_PROPERTIES.put(${p.constName}, ${p.typeExpr}.class);\n") + } + append(" }\n\n") + + for (p in props) { + append(" @Nullable\n") + append(" public static ${p.typeExpr} ${p.getter}($stableClassName model) {\n") + append(" return ExtensionPropertyUtil.get(\n") + append(" ${p.constName}, model.getExtensionProperties(), ${p.typeExpr}.class);\n") + append(" }\n\n") + + append(" public static $stableClassName ${p.builder}(\n") + append(" $stableClassName model, ${p.typeExpr} value) {\n") + append(" requireNonNull(value, \"value\");\n") + append(" model.setExtensionProperty(${p.constName}, value);\n") + append(" return model;\n") + append(" }\n\n") + } + + append("}\n") + } + + private fun buildPropertyModelSource(pkg: String, className: String) = buildString { + appendLicense() + append("\npackage $pkg;\n\n") + append("import com.fasterxml.jackson.annotation.JsonAnyGetter;\n") + append("import com.fasterxml.jackson.annotation.JsonAnySetter;\n") + append("import com.fasterxml.jackson.annotation.JsonInclude;\n") + append("import com.fasterxml.jackson.annotation.JsonPropertyOrder;\n") + append("import java.util.LinkedHashMap;\n") + append("import java.util.Map;\n") + append("import javax.annotation.Generated;\n") + append("import javax.annotation.Nullable;\n") + append("\n@JsonInclude(JsonInclude.Include.NON_NULL)\n") + append("@JsonPropertyOrder({})\n") + append("@Generated(\"io.opentelemetry.gradle.DeclarativeConfigPojoGenerator\")\n") + append("public class $className {\n\n") + append(" private Map additionalProperties = new LinkedHashMap();\n\n") + append(" @JsonAnyGetter\n") + append(" public Map getAdditionalProperties() {\n return this.additionalProperties;\n }\n\n") + append(" @JsonAnySetter\n") + append(" public $className setAdditionalProperty(String name, Object value) {\n") + append(" this.additionalProperties.put(name, value);\n return this;\n }\n\n") + appendToString(className, listOf("additionalProperties")) + append("\n") + appendHashCode(listOf("additionalProperties")) + append("\n") + appendEquals(className, listOf("additionalProperties")) + append("}\n") + } + + // ── Shared method emitters ─────────────────────────────────────────────────── + + private fun StringBuilder.appendToString(className: String, fields: List) { + append(" @Override\n public String toString() {\n") + if (fields.isEmpty()) { + append(" return \"$className{}\";\n") + } else { + val parts = fields.mapIndexed { i, name -> + if (i == 0) "\"$name=\" + $name" else "\", $name=\" + $name" + } + append(" return \"$className{\" + ${parts.joinToString(" + ")} + \"}\";\n") + } + append(" }\n") + } + + private fun StringBuilder.appendHashCode(fields: List) { + append(" @Override\n public int hashCode() {\n int h = 1;\n") + for (name in fields) { + append(" h *= 1000003;\n") + append(" h ^= (this.$name == null) ? 0 : this.$name.hashCode();\n") + } + append(" return h;\n }\n") + } + + private fun StringBuilder.appendEquals(className: String, fields: List) { + append(" @Override\n public boolean equals(@Nullable Object o) {\n") + append(" if (o == this) {\n return true;\n }\n") + append(" if (o instanceof $className) {\n $className that = ($className) o;\n") + if (fields.isEmpty()) { + append(" return true;\n") + } else { + val conditions = fields.map { "(this.$it == null ? that.$it == null : this.$it.equals(that.$it))" } + append(" return ${conditions.joinToString("\n && ")};\n") + } + append(" }\n return false;\n }\n") + } + + // ── Helpers ────────────────────────────────────────────────────────────────── + + /** + * Converts a JSON enum value to a Java SCREAMING_SNAKE_CASE constant name. + * Splits on "_", "/", "-", and letter-digit boundaries. + * e.g. "trace2" β†’ "TRACE_2", "no_utf8_escaping/development" β†’ "NO_UTF_8_ESCAPING_DEVELOPMENT" + */ + private fun String.toScreamingSnakeCase() = this + .replace("/", "_") + .replace("-", "_") + .replace(Regex("([a-zA-Z])(\\d)"), "$1_$2") + .replace(Regex("(\\d)([a-zA-Z])"), "$1_$2") + .split("_") + .joinToString("_") { it.uppercase() } + + /** + * Formats a schema description string into javadoc lines. Each newline in the schema becomes a + * paragraph break so google-java-format doesn't collapse them into one line. Empty lines from + * double-newline paragraph separators in the schema are skipped β€” the following non-empty line + * opens its own paragraph. + */ + private fun formatJavadoc(description: String): List { + val lines = description.trimEnd('\n').split('\n') + if (lines.size == 1) return lines + return buildList { + lines.forEachIndexed { i, line -> + when { + i == 0 -> add(line) + line.isEmpty() -> Unit + else -> { add(""); add("

    $line") } + } + } + } + } + + private fun StringBuilder.appendLicense() { + append("/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n") + } +} diff --git a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelBomExtension.kt b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelBomExtension.kt index 38e5f797ae8..5857b99808b 100644 --- a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelBomExtension.kt +++ b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelBomExtension.kt @@ -11,4 +11,4 @@ import java.util.function.Predicate abstract class OtelBomExtension { abstract val projectFilter: Property> -} \ No newline at end of file +} diff --git a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelJavaExtension.kt b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelJavaExtension.kt index bf584e71100..6ba360f32f1 100644 --- a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelJavaExtension.kt +++ b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelJavaExtension.kt @@ -5,8 +5,54 @@ package io.opentelemetry.gradle +import org.gradle.api.JavaVersion +import org.gradle.api.provider.ListProperty import org.gradle.api.provider.Property abstract class OtelJavaExtension { abstract val moduleName: Property + + // Set to false for modules that are not OSGi bundles (e.g. test helpers, build tooling, + // aggregators). Skips BND bundle metadata generation entirely. + abstract val osgiEnabled: Property + + abstract val osgiOptionalPackages: ListProperty + + // Packages that should be optional imports but are not on the compile classpath (e.g. due to + // circular dependencies), so BND cannot resolve version="${@}" for them. Added to Import-Package + // with resolution:=optional but no version constraint. + abstract val osgiUnversionedOptionalPackages: ListProperty + + // SPI interfaces whose implementations this bundle registers via META-INF/services. + // Generates Provide-Capability: osgi.serviceloader;... and requires the registrar extender. + abstract val osgiServiceLoaderProvides: ListProperty + + // SPI interfaces this bundle discovers at runtime via ServiceLoader. + // Generates Require-Capability: osgi.serviceloader;... (resolution:=optional) to hint the + // BND resolver to include provider bundles. Does NOT add the processor extender requirement β€” + // use osgiServiceLoaderProcessor for that. + abstract val osgiServiceLoaderRequires: ListProperty + + // When true, adds Require-Capability: osgi.extender=osgi.serviceloader.processor so that a + // ServiceLoader mediator (e.g. SPI Fly) weaves this bundle's ServiceLoader.load() calls to + // route through the OSGi service registry. Set this on whichever bundle contains the actual + // ServiceLoader.load() call site; the SPI types being loaded live elsewhere. + abstract val osgiServiceLoaderProcessor: Property + + abstract val minJavaVersionSupported: Property + + // TODO(#7874): Remove this property and enable the check unconditionally once all modules + // migrate. + abstract val requireSuppressWarningsExplanation: Property + + init { + minJavaVersionSupported.convention(JavaVersion.VERSION_1_8) + osgiEnabled.convention(true) + osgiOptionalPackages.convention(emptyList()) + osgiUnversionedOptionalPackages.convention(emptyList()) + osgiServiceLoaderProvides.convention(emptyList()) + osgiServiceLoaderRequires.convention(emptyList()) + osgiServiceLoaderProcessor.convention(false) + requireSuppressWarningsExplanation.convention(true) + } } diff --git a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelVersionClassPlugin.kt b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelVersionClassPlugin.kt new file mode 100644 index 00000000000..fabcd943840 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/OtelVersionClassPlugin.kt @@ -0,0 +1,89 @@ +package io.opentelemetry.gradle + +import org.gradle.api.DefaultTask +import org.gradle.api.Plugin +import org.gradle.api.Project +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.plugins.JavaPlugin +import org.gradle.api.plugins.JavaPluginExtension +import org.gradle.api.provider.Property +import org.gradle.api.tasks.Input +import org.gradle.api.tasks.OutputDirectory +import org.gradle.api.tasks.TaskAction +import org.gradle.kotlin.dsl.the +import java.io.File + +/** + * This gradle plugin will define a new task called generateOtelVersionClass. + * This task generates a Java source file that contains the project version + * as a string constant. The "compileJava" task is updated to depend on + * generateOtelVersionClass, and the project source set is updated to + * include the new file. + */ +class OtelVersionClassPlugin : Plugin { + override fun apply(project: Project) { + project.plugins.apply(JavaPlugin::class.java) + + val outDir = project.layout.buildDirectory.dir("generated/sources/version/java/main") + + project.tasks.register("generateOtelVersionClass", GenerateOtelVersionClassTask::class.java) { + projectGroup.set("${project.group}") + projectName.set(project.name) + projectVersion.set("${project.version}") + outputDirectory.set(outDir) + } + // Add dependency on this task + project.tasks.matching { it.name == "compileJava" || it.name == "sourcesJar" }.configureEach { + dependsOn("generateOtelVersionClass") + } + // Add new source dir to the "main" source set + val java = project.the() + java.sourceSets.getByName("main").java { + srcDir(outDir) + } + } +} + +abstract class GenerateOtelVersionClassTask : DefaultTask() { + @get:Input + abstract val projectGroup: Property + + @get:Input + abstract val projectName: Property + + @get:Input + abstract val projectVersion: Property + + @get:OutputDirectory + abstract val outputDirectory: DirectoryProperty + + @TaskAction + fun generate() { + val group = projectGroup.get().replace('.', '/') + val name = projectName.get().replace('-', '/') + val outDir = outputDirectory.get().asFile + val filename = "$group/$name/internal/OtelVersion.java" + val outFile = File(outDir, filename) + val packageName = "${projectGroup.get()}.${projectName.get().replace('-', '.')}.internal" + val classBody = getClassBody(projectVersion.get(), packageName) + + outFile.parentFile.mkdirs() + outFile.writeText(classBody) + } + + private fun getClassBody(version: String, packageName: String): String { + return """ + package $packageName; + + import javax.annotation.Generated; + + /** Autogenerated class do not edit. */ + @Generated("io.opentelemetry.gradle.OtelVersionClassPlugin") + public final class OtelVersion { + public static final String VERSION = "$version"; + + private OtelVersion() {} + } + """.trimIndent() + } +} diff --git a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandler.kt b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandler.kt index 20dd0c86962..c24e9031bb2 100644 --- a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandler.kt +++ b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandler.kt @@ -7,7 +7,6 @@ import com.squareup.javapoet.TypeName import com.squareup.javapoet.TypeSpec import com.squareup.wire.WireCompiler import com.squareup.wire.WireLogger -import com.squareup.wire.schema.CustomHandlerBeta import com.squareup.wire.schema.EnumType import com.squareup.wire.schema.Extend import com.squareup.wire.schema.Field @@ -16,6 +15,7 @@ import com.squareup.wire.schema.ProfileLoader import com.squareup.wire.schema.ProtoFile import com.squareup.wire.schema.ProtoType import com.squareup.wire.schema.Schema +import com.squareup.wire.schema.SchemaHandler import com.squareup.wire.schema.Service import com.squareup.wire.schema.Target import com.squareup.wire.schema.Type @@ -33,51 +33,57 @@ import javax.lang.model.element.Modifier.STATIC // generated protoc code. // // Inspired by https://github.com/square/wire/blob/5fac94f86879fdd7e412cddbeb51e09a708b2b64/wire-library/wire-compiler/src/main/java/com/squareup/wire/schema/Target.kt#L152 -class ProtoFieldsWireHandler : CustomHandlerBeta { - override fun newHandler( - schema: Schema, - fs: FileSystem, - outDirectory: String, - logger: WireLogger, - profileLoader: ProfileLoader - ): Target.SchemaHandler { - val modulePath = outDirectory.toPath() - fs.createDirectories(modulePath) - val javaGenerator = JavaGenerator.get(schema) - - return object : Target.SchemaHandler { - override fun handle(extend: Extend, field: Field): Path? = null - override fun handle(service: Service): List = emptyList() - override fun handle(type: Type): Path? { - val typeSpec = javaGenerator.generateType(type, false) - val javaTypeName = javaGenerator.generatedTypeName(type) - - if (typeSpec == null) { - return null - } +class ProtoFieldsWireHandler : SchemaHandler() { + + private var schema: Schema?= null + private var javaGenerator: JavaGenerator?= null + + override fun handle(schema: Schema, context: Context) { + if (this.schema != null && this.schema != schema) { + throw IllegalStateException("Cannot use same handler with multiple schemas") + } + if (this.schema == null) { + this.schema = schema + this.javaGenerator = JavaGenerator.get(schema) + } + super.handle(schema, context) + } - val javaFile = JavaFile.builder(javaTypeName.packageName(), typeSpec) - .addFileComment("\$L", WireCompiler.CODE_GENERATED_BY_WIRE) - .addFileComment("\nSource: \$L in \$L", type.type, type.location.withPathOnly()) - .build() - val generatedFilePath = modulePath / javaFile.packageName / "${javaFile.typeSpec.name}.java" + override fun handle(service: Service, context: Context): List = emptyList() - val filePath = modulePath / - javaFile.packageName.replace(".", "/") / - "${javaTypeName.simpleName()}.java" + override fun handle(extend: Extend, field: Field, context: Context): Path? = null - try { - fs.createDirectories(filePath.parent!!) - fs.write(filePath) { - writeUtf8(javaFile.toString()) - } - } catch (e: IOException) { - throw IOException("Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} " + - "to $outDirectory", e) - } - return generatedFilePath + override fun handle(type: Type, context: Context): Path? { + val fs = context.fileSystem + val outDirectory = context.outDirectory + + val typeSpec = javaGenerator!!.generateType(type, false) + val javaTypeName = javaGenerator!!.generatedTypeName(type) + + if (typeSpec == null) { + return null + } + + val javaFile = JavaFile.builder(javaTypeName.packageName(), typeSpec) + .addFileComment("\$L", WireCompiler.CODE_GENERATED_BY_WIRE) + .addFileComment("\nSource: \$L in \$L", type.type, type.location.withPathOnly()) + .build() + val generatedFilePath = outDirectory / javaFile.packageName / "${javaFile.typeSpec.name}.java" + + val filePath = outDirectory / + javaFile.packageName.replace(".", "/") / + "${javaTypeName.simpleName()}.java" + + try { + fs.createDirectories(filePath.parent!!) + fs.write(filePath) { + writeUtf8(javaFile.toString()) } + } catch (e: IOException) { + throw IOException("Error emitting ${javaFile.packageName}.${javaFile.typeSpec.name} " + + "to $outDirectory", e) } + return generatedFilePath } private class JavaGenerator(private val schema: Schema, private val typeToJavaName: Map) { @@ -93,7 +99,10 @@ class ProtoFieldsWireHandler : CustomHandlerBeta { fun get(schema: Schema): JavaGenerator { val nameToJavaName = linkedMapOf() for (protoFile in schema.protoFiles) { - val javaPackage = javaPackage(protoFile) + if (protoFile.location.path == "wire/extensions.proto") { + continue + } + val javaPackage = javaPackage(protoFile) putAll(nameToJavaName, javaPackage, null, protoFile.types) } @@ -149,7 +158,7 @@ class ProtoFieldsWireHandler : CustomHandlerBeta { for (field in type.fieldsAndOneOfFields) { builder.addField( - FieldSpec.builder(PROTO_FIELD_INFO, field.name.toUpperCase(), PUBLIC, STATIC, FINAL) + FieldSpec.builder(PROTO_FIELD_INFO, field.name.uppercase(), PUBLIC, STATIC, FINAL) .initializer("\$T.create(\$L, \$L, \"\$L\")", PROTO_FIELD_INFO, field.tag, diff --git a/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandlerFactory.kt b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandlerFactory.kt new file mode 100644 index 00000000000..cd99a69dc44 --- /dev/null +++ b/buildSrc/src/main/kotlin/io/opentelemetry/gradle/ProtoFieldsWireHandlerFactory.kt @@ -0,0 +1,17 @@ +package io.opentelemetry.gradle + +import com.squareup.wire.schema.SchemaHandler + +class ProtoFieldsWireHandlerFactory : SchemaHandler.Factory{ + + override fun create( + includes: List, + excludes: List, + exclusive: Boolean, + outDirectory: String, + options: Map + ): SchemaHandler { + return ProtoFieldsWireHandler() + } + +} diff --git a/buildSrc/src/main/kotlin/otel.animalsniffer-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.animalsniffer-conventions.gradle.kts index 9680996fcc8..73bbf0dd2d7 100644 --- a/buildSrc/src/main/kotlin/otel.animalsniffer-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.animalsniffer-conventions.gradle.kts @@ -7,7 +7,7 @@ plugins { } dependencies { - add("signature", "com.toasttab.android:gummy-bears-api-21:0.3.0:coreLib@signature") + signature(project(path = ":animal-sniffer-signature", configuration = "generatedSignature")) } animalsniffer { diff --git a/buildSrc/src/main/kotlin/otel.bom-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.bom-conventions.gradle.kts index d68f56cedb3..ebc33cf98e6 100644 --- a/buildSrc/src/main/kotlin/otel.bom-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.bom-conventions.gradle.kts @@ -17,7 +17,7 @@ rootProject.subprojects.forEach { subproject -> } val otelBom = extensions.create("otelBom") -val generateBuildSubstitutions by tasks.registering { +val generateBuildSubstitutions = tasks.register("generateBuildSubstitutions") { group = "publishing" description = "Generate a code snippet that can be copy-pasted for use in composite builds." } @@ -38,13 +38,13 @@ afterEvaluate { .filter(otelBom.projectFilter.get()::test) .filter { it.plugins.hasPlugin("maven-publish") } - generateBuildSubstitutions { - val outputFile = File(buildDir, "substitutions.gradle.kts") + generateBuildSubstitutions.configure { + val outputFile = File(layout.buildDirectory.asFile.get(), "substitutions.gradle.kts") outputs.file(outputFile) val substitutionSnippet = bomProjects.joinToString( separator = "\n", prefix = "dependencySubstitution {\n", - postfix = "\n}\n" + postfix = "\n}\n", ) { project -> val publication = project.publishing.publications.getByName("mavenPublication") as MavenPublication " substitute(module(\"${publication.groupId}:${publication.artifactId}\")).using(project(\"${project.path}\"))" diff --git a/buildSrc/src/main/kotlin/otel.errorprone-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.errorprone-conventions.gradle.kts index 016bb028966..6c7740992de 100644 --- a/buildSrc/src/main/kotlin/otel.errorprone-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.errorprone-conventions.gradle.kts @@ -7,7 +7,13 @@ plugins { id("net.ltgt.nullaway") } -val disableErrorProne = properties["disableErrorProne"]?.toString()?.toBoolean() ?: false +dependencies { + errorprone("com.google.errorprone:error_prone_core") + errorprone("com.uber.nullaway:nullaway") + errorprone(project(":custom-checks")) +} + +val disableErrorProne = findProperty("disableErrorProne")?.toString()?.toBoolean() ?: false tasks { withType().configureEach { @@ -15,13 +21,17 @@ tasks { errorprone { if (disableErrorProne) { logger.warn("Errorprone has been disabled. Build may not result in a valid PR build.") - isEnabled.set(false) + enabled.set(false) } disableWarningsInGeneratedCode.set(true) allDisabledChecksAsWarnings.set(true) + // Ignore warnings for generated and vendored classes + excludedPaths.set(".*/build/generated/.*|.*/internal/shaded/.*") + // Still Java 8 + disable("TraditionalJavadocToMarkdown") disable("Varifier") // Doesn't currently use Var annotations. @@ -36,17 +46,8 @@ tasks { // Suggests using Guava types for fields but we don't use Guava disable("ImmutableMemberCollection") - // Fully qualified names may be necessary when deprecating a class to avoid - // deprecation warning. - disable("UnnecessarilyFullyQualified") - - // Ignore warnings for protobuf and jmh generated files. - excludedPaths.set(".*generated.*|.*internal.shaded.*") - // We use animal sniffer - disable("Java7ApiChecker") disable("Java8ApiChecker") - disable("AndroidJdkLibsChecker") // apparently disabling android doesn't disable this disable("StaticOrDefaultInterfaceMethod") @@ -73,9 +74,26 @@ tasks { // Only used in comments, but couldn't SuppressWarnings for some reason disable("UnicodeEscape") - if (name.contains("Jmh") || name.contains("Test")) { + // We make liberal use of builders returning "this" which can be safely ignored. Annotating + // every one of these methods is too noisy. + disable("CanIgnoreReturnValueSuggester") + + // YodaConditions may improve safety in some cases. The argument of increased + // cognitive load is dubious. + disable("YodaCondition") + + // We annotate packages with @ParametersAreNonnullByDefault from com.google.code.findbugs:jsr305. + // @NullMarked is the equivalent from jspecify. + disable("AddNullMarkedToPackageInfo") + disable("AddNullMarkedToClass") + + if ((name.contains("Jmh") || name.contains("Test") || project.name.contains("testing-internal")) && !project.name.equals("custom-checks")) { // Allow underscore in test-type method names disable("MemberName") + // Internal javadoc not needed for test or jmh classes + disable("OtelInternalJavadoc") + // Javadoc not required for test or jmh classes + disable("MissingJavadoc") } option("NullAway:CustomContractAnnotations", "io.opentelemetry.api.internal.Contract") diff --git a/buildSrc/src/main/kotlin/otel.jacoco-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.jacoco-conventions.gradle.kts index 4aa1476f5f9..f6aa705f3f1 100644 --- a/buildSrc/src/main/kotlin/otel.jacoco-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.jacoco-conventions.gradle.kts @@ -5,7 +5,7 @@ plugins { } jacoco { - toolVersion = "0.8.8" + toolVersion = "0.8.16" } // https://docs.gradle.org/current/samples/sample_jvm_multi_project_with_code_coverage.html @@ -16,10 +16,9 @@ tasks.named("jacocoTestReport") { } configurations { - val implementation by getting + val implementation = getByName("implementation") create("transitiveSourceElements") { - isVisible = false isCanBeResolved = false isCanBeConsumed = true extendsFrom(implementation) @@ -34,7 +33,6 @@ configurations { } create("coverageDataElements") { - isVisible = false isCanBeResolved = false isCanBeConsumed = true extendsFrom(implementation) diff --git a/buildSrc/src/main/kotlin/otel.japicmp-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.japicmp-conventions.gradle.kts index 764273adf64..6370a2b7351 100644 --- a/buildSrc/src/main/kotlin/otel.japicmp-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.japicmp-conventions.gradle.kts @@ -1,13 +1,9 @@ -import japicmp.model.JApiChangeStatus -import japicmp.model.JApiCompatibility -import japicmp.model.JApiCompatibilityChange +import com.google.auto.value.AutoValue +import com.google.common.io.Files +import japicmp.model.* import me.champeau.gradle.japicmp.JapicmpTask -import me.champeau.gradle.japicmp.report.Severity import me.champeau.gradle.japicmp.report.Violation -import me.champeau.gradle.japicmp.report.stdrules.AbstractRecordingSeenMembers -import me.champeau.gradle.japicmp.report.stdrules.RecordSeenMembersSetup -import me.champeau.gradle.japicmp.report.stdrules.SourceCompatibleRule -import me.champeau.gradle.japicmp.report.stdrules.UnchangedMemberRule +import me.champeau.gradle.japicmp.report.stdrules.* plugins { @@ -17,107 +13,159 @@ plugins { } /** - * The latest *released* version of the project. Evaluated lazily so the work is only done if necessary. + * The baseline version japicmp compares against. Pinned in version.gradle.kts and bumped + * atomically with docs/apidiffs/current_vs_latest/ by the post-release PR opened from + * .github/workflows/release.yml. */ -val latestReleasedVersion: String by lazy { - // hack to find the current released version of the project - val temp: Configuration = configurations.create("tempConfig") - // pick the api, since it's always there. - dependencies.add(temp.name, "io.opentelemetry:opentelemetry-api:latest.release") - val moduleVersion = configurations["tempConfig"].resolvedConfiguration.firstLevelModuleDependencies.elementAt(0).moduleVersion - configurations.remove(temp) - logger.debug("Discovered latest release version: " + moduleVersion) - moduleVersion +val apidiffBaselineVersion = rootProject.extra["apidiffBaselineVersion"] as String + +class AllowNewAbstractMethodOnAutovalueClasses : AbstractRecordingSeenMembers() { + override fun maybeAddViolation(member: JApiCompatibility): Violation? { + val allowableAutovalueChanges = setOf( + JApiCompatibilityChangeType.METHOD_ABSTRACT_ADDED_TO_CLASS, + JApiCompatibilityChangeType.METHOD_ADDED_TO_PUBLIC_CLASS, + JApiCompatibilityChangeType.ANNOTATION_ADDED + ) + if (member.compatibilityChanges.filter { !allowableAutovalueChanges.contains(it.type) } + .isEmpty() && + member is JApiMethod && isAutoValueClass(member.getjApiClass()) + ) { + return Violation.accept(member, "Autovalue will automatically add implementation") + } + if (member.compatibilityChanges.isEmpty() && + member is JApiClass && isAutoValueClass(member) + ) { + return Violation.accept(member, "Autovalue class modification is allowed") + } + return null + } + + fun isAutoValueClass(japiClass: JApiClass): Boolean { + return japiClass.newClass.get().getAnnotation(AutoValue::class.java) != null || + japiClass.newClass.get().getAnnotation(AutoValue.Builder::class.java) != null + } } -class AllowDefaultMethodRule : AbstractRecordingSeenMembers() { +class SourceIncompatibleRule : AbstractRecordingSeenMembers() { override fun maybeAddViolation(member: JApiCompatibility): Violation? { - for (change in member.compatibilityChanges) { - if (change == JApiCompatibilityChange.METHOD_NEW_DEFAULT) { - // JApiCmp treats this as incompatible for the situation where an existing subclass may have - // a method with the same name and different signature. We accept this corner case for - // semver. - continue - } - if (!change.isBinaryCompatible) { - return Violation.notBinaryCompatible(member, Severity.error) - } + if (!member.isSourceCompatible()) { + return Violation.error(member, "Not source compatible: $member") } return null } } -/** - * Locate the project's artifact of a particular version. - */ -fun findArtifact(version: String): File { +fun getAllPublishedModules(): List { + return project.rootProject.allprojects.filter { + it.plugins.hasPlugin("otel.publish-conventions") && !it.hasProperty("otel.release") && it.tasks.findByName( + "jar" + ) != null + }.toList() +} + +fun getClasspathForVersion(version: String): List { + // Temporarily change the group name because we want to fetch an artifact with the same + // Maven coordinates as the project, which Gradle would not allow otherwise. val existingGroup = group + group = "virtual_group" try { - // Temporarily change the group name because we want to fetch an artifact with the same - // Maven coordinates as the project, which Gradle would not allow otherwise. - group = "virtual_group" - val depModule = "io.opentelemetry:${base.archivesName.get()}:$version@jar" - val depJar = "${base.archivesName.get()}-$version.jar" - val configuration: Configuration = configurations.detachedConfiguration( - dependencies.create(depModule) - ) - return files(configuration.files).filter { - it.name.equals(depJar) - }.singleFile + return getAllPublishedModules().map { + val depModule = "io.opentelemetry:${it.base.archivesName.get()}:$version@jar" + val depJar = "${it.base.archivesName.get()}-$version.jar" + val configuration: Configuration = configurations.detachedConfiguration( + dependencies.create(depModule), + ) + files(configuration.files).filter { file -> + file.name.equals(depJar) + }.singleFile + }.toList() } finally { group = existingGroup } } +fun getCurrentClassPath(): List { + return getAllPublishedModules().map { + val archiveFile = it.tasks.getByName("jar").archiveFile + archiveFile.get().asFile + }.toList() +} + // generate the api diff report for any module that is stable and publishes a jar. if (!project.hasProperty("otel.release") && !project.name.startsWith("bom")) { afterEvaluate { tasks { - val jApiCmp by registering(JapicmpTask::class) { - dependsOn("jar") + val jApiCmp = register("jApiCmp") { + // Depends on jar task for all published modules. See notes below. + getAllPublishedModules().forEach { + dependsOn(it.tasks.getByName("jar")) + } // the japicmp "new" version is either the user-specified one, or the locally built jar. - val apiNewVersion: String? by project - val newArtifact = apiNewVersion?.let { findArtifact(it) } - ?: file(getByName("jar").archiveFile) - newClasspath.from(files(newArtifact)) + val apiNewVersion = project.findProperty("apiNewVersion") as String? + // the japicmp "old" version is either the user-specified one, or the pinned baseline. + val apiBaseVersion = project.findProperty("apiBaseVersion") as String? + val baselineVersion = apiBaseVersion ?: apidiffBaselineVersion - // only output changes, not everything - onlyModified.set(true) + // Setup new and old classpath, new and old archives. + // New and old classpaths are set to the set of all artifacts published by this project, at + // the appropriate version. Without this, japicmp is unable to resolve inheritance across module + // boundaries (i.e. Span from opentelemetry-api extends ImplicitContextKeyed from opentelemetry-context) + // and generates false positive compatibility errors when methods are lifted into superclasses, + // superinterfaces. + val archiveName = base.archivesName.get() + val newClassPath = apiNewVersion?.let { getClasspathForVersion(it) } ?: getCurrentClassPath() + val oldClassPath = getClasspathForVersion(baselineVersion) + val pattern = (archiveName + "-([0-9\\.]*)(-SNAPSHOT)?.jar").toRegex() + val newArchive = newClassPath.singleOrNull { it.name.matches(pattern) } + val oldArchive = oldClassPath.singleOrNull { it.name.matches(pattern) } + newClasspath.from(newClassPath) + oldClasspath.from(oldClassPath) + newArchives.from(newArchive) + oldArchives.from(oldArchive) - // the japicmp "old" version is either the user-specified one, or the latest release. - val apiBaseVersion: String? by project - val baselineVersion = apiBaseVersion ?: latestReleasedVersion - oldClasspath.from( - try { - files(findArtifact(baselineVersion)) - } catch (e: Exception) { - // if we can't find the baseline artifact, this is probably one that's never been published before, - // so publish the whole API. We do that by flipping this flag, and comparing the current against nothing. - onlyModified.set(false) - files() - } - ) + // Only generate API diff for changes. + onlyModified.set(true) // Reproduce defaults from https://github.com/melix/japicmp-gradle-plugin/blob/09f52739ef1fccda6b4310cf3f4b19dc97377024/src/main/java/me/champeau/gradle/japicmp/report/ViolationsGenerator.java#L130 - // only changing the BinaryIncompatibleRule to our custom one that allows new default methods - // on interfaces. + // with some changes. + val exclusions = mutableListOf() + // Generics are not detected correctly + exclusions.add("CLASS_GENERIC_TEMPLATE_CHANGED") + // Allow new default methods on interfaces + exclusions.add("METHOD_NEW_DEFAULT") + // Allow adding default implementations for default methods + exclusions.add("METHOD_ABSTRACT_NOW_DEFAULT") + // Bug prevents recognizing default methods of superinterface. + // Fixed in https://github.com/siom79/japicmp/pull/343 but not yet available in me.champeau.gradle.japicmp + exclusions.add("METHOD_ABSTRACT_ADDED_IN_IMPLEMENTED_INTERFACE") + compatibilityChangeExcludes.set(exclusions) richReport { addSetupRule(RecordSeenMembersSetup::class.java) addRule(JApiChangeStatus.NEW, SourceCompatibleRule::class.java) addRule(JApiChangeStatus.MODIFIED, SourceCompatibleRule::class.java) addRule(JApiChangeStatus.UNCHANGED, UnchangedMemberRule::class.java) - addRule(AllowDefaultMethodRule::class.java) - addRule(SourceCompatibleRule::class.java) + // Allow new abstract methods on autovalue + addRule(AllowNewAbstractMethodOnAutovalueClasses::class.java) + addRule(BinaryIncompatibleRule::class.java) + // Disallow source incompatible changes, which are allowed by default for some reason + addRule(SourceIncompatibleRule::class.java) } // this is needed so that we only consider the current artifact, and not dependencies ignoreMissingClasses.set(true) - packageExcludes.addAll("*.internal", "*.internal.*", "io.opentelemetry.internal.shaded.jctools.*") + packageExcludes.addAll( + "*.internal", + "*.internal.*", + "io.opentelemetry.sdk.trace.internal.shaded.jctools.*", + // Temporarily suppress warnings from public generated classes from :sdk-extensions:jaeger-remote-sampler + "io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2" + ) + annotationExcludes.add("@kotlin.Metadata") val baseVersionString = if (apiBaseVersion == null) "latest" else baselineVersion txtOutputFile.set( apiNewVersion?.let { file("$rootDir/docs/apidiffs/${apiNewVersion}_vs_$baselineVersion/${base.archivesName.get()}.txt") } - ?: file("$rootDir/docs/apidiffs/current_vs_$baseVersionString/${base.archivesName.get()}.txt") + ?: file("$rootDir/docs/apidiffs/current_vs_$baseVersionString/${base.archivesName.get()}.txt"), ) } // have the check task depend on the api comparison task, to make it more likely it will get used. diff --git a/buildSrc/src/main/kotlin/otel.java-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.java-conventions.gradle.kts index 256ee6133f2..3257807a990 100644 --- a/buildSrc/src/main/kotlin/otel.java-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.java-conventions.gradle.kts @@ -1,4 +1,7 @@ import io.opentelemetry.gradle.OtelJavaExtension +import net.ltgt.gradle.errorprone.CheckSeverity +import net.ltgt.gradle.errorprone.errorprone +import org.gradle.api.JavaVersion import org.gradle.api.tasks.testing.logging.TestExceptionFormat plugins { @@ -8,9 +11,11 @@ plugins { eclipse idea + id("biz.aQute.bnd.builder") id("otel.errorprone-conventions") id("otel.jacoco-conventions") id("otel.spotless-conventions") + id("org.sonatype.gradle.plugins.scan") } val otelJava = extensions.create("otelJava") @@ -23,9 +28,16 @@ base { } } +// normalize timestamps and file ordering in jars, making the outputs reproducible +// see open-telemetry/opentelemetry-java#4488 +tasks.withType().configureEach { + isPreserveFileTimestamps = false + isReproducibleFileOrder = true +} + java { toolchain { - languageVersion.set(JavaLanguageVersion.of(17)) + languageVersion.set(JavaLanguageVersion.of(25)) } withJavadocJar() @@ -34,17 +46,32 @@ java { checkstyle { configDirectory.set(file("$rootDir/buildscripts/")) - toolVersion = "8.12" + toolVersion = "14.4.0" isIgnoreFailures = false configProperties["rootDir"] = rootDir } +ossIndexAudit { + // Guide PAT authentication ignores this, but the scan plugin requires it. + username = "unused" + password = System.getenv("SONATYPE_GUIDE_PAT") ?: "" + outputFormat = org.sonatype.gradle.plugins.scan.ossindex.OutputFormat.JSON_CYCLONE_DX_1_4 + isPrintBanner = false +} + val testJavaVersion = gradle.startParameter.projectProperties.get("testJavaVersion")?.let(JavaVersion::toVersion) tasks { withType().configureEach { with(options) { - release.set(8) + errorprone.check( + "SuppressWarningsWithoutExplanation", + otelJava.requireSuppressWarningsExplanation.map { + if (it) CheckSeverity.ERROR else CheckSeverity.OFF + }, + ) + + release.set(otelJava.minJavaVersionSupported.map { it.majorVersion.toInt() }) if (name != "jmhCompileGeneratedClasses") { compilerArgs.addAll( @@ -58,10 +85,15 @@ tasks { "-Xlint:-processing", // We suppress the "options" warning because it prevents compilation on modern JDKs "-Xlint:-options", - + "-Xlint:-serial", + "-Xlint:-this-escape", + // We suppress the "deprecation" warning because --release 8 causes javac to warn on + // importing deprecated classes (fixed in JDK 9+, see https://bugs.openjdk.org/browse/JDK-8032211). + // We use a custom Error Prone check instead (OtelDeprecatedApiUsage). + "-Xlint:-deprecation", // Fail build on any warning - "-Werror" - ) + "-Werror", + ), ) } @@ -77,12 +109,12 @@ tasks { withType().configureEach { useJUnitPlatform() - if (testJavaVersion != null) { - javaLauncher.set( - javaToolchains.launcherFor { - languageVersion.set(JavaLanguageVersion.of(testJavaVersion.majorVersion)) - } - ) + val defaultMaxRetries = if (System.getenv().containsKey("CI")) 2 else 0 + val maxTestRetries = gradle.startParameter.projectProperties["maxTestRetries"]?.toInt() ?: defaultMaxRetries + + develocity.testRetry { + // You can see tests that were retried by this mechanism in the collected test reports and build scans. + maxRetries.set(maxTestRetries); } testLogging { @@ -94,6 +126,13 @@ tasks { showStandardStreams = true } maxHeapSize = "1500m" + + doFirst { + // Test dependencies (mockito and assertj) still use Unsafe memory-access methods deprecated by JEP 498. + if (javaLauncher.get().metadata.languageVersion.asInt() >= 24) { + jvmArgs("--sun-misc-unsafe-memory-access=allow") + } + } } withType().configureEach { @@ -106,12 +145,73 @@ tasks { breakIterator(true) addBooleanOption("html5", true) - - links("https://docs.oracle.com/javase/8/docs/api/") addBooleanOption("Xdoclint:all,-missing", true) } } + afterEvaluate { + if (otelJava.osgiEnabled.get()) { + named("jar") { + // Configure OSGi metadata + bundle { + // Compute import packages. + // Certain packages like javax.annotation.* are always optional. + // Modules may have additional optional packages, typically corresponding to compileOnly dependencies. + // Append wildcard "*" last to import any other referenced packages. + val optionalPackages = mutableListOf("javax.annotation") + optionalPackages.addAll(otelJava.osgiOptionalPackages.get()) + val importPackages = optionalPackages.joinToString(",") { "$it.*;resolution:=optional;version=\"\${@}\"" } + ",*" + + // Packages not on the compile classpath (e.g. due to circular dependencies) cannot use + // version="${@}" since BND cannot resolve the version. Add them as optional imports without + // a version constraint; they are listed before the wildcard so BND uses our explicit + // instruction rather than auto-detecting them with a version. + val unversionedOptionalPackages = otelJava.osgiUnversionedOptionalPackages.get() + val unversionedImports = unversionedOptionalPackages.joinToString(",") { "$it.*;resolution:=optional" } + val fullImportPackages = if (unversionedImports.isNotEmpty()) "$unversionedImports,$importPackages" else importPackages + + val bndInstructions = mutableMapOf( + "-exportcontents" to "io.opentelemetry.*", + "Import-Package" to fullImportPackages + ) + + // OSGi ServiceLoader Mediator capabilities. + // Providers declare what SPI implementations they register via META-INF/services. + // Consumers declare what SPI interfaces they discover at runtime via ServiceLoader. + // Both require the corresponding extender from a ServiceLoader mediator (e.g. SPI Fly). + val slProvides = otelJava.osgiServiceLoaderProvides.get() + val slRequires = otelJava.osgiServiceLoaderRequires.get() + val requireClauses = mutableListOf() + + if (slProvides.isNotEmpty()) { + bndInstructions["Provide-Capability"] = slProvides.joinToString(",") { + "osgi.serviceloader;osgi.serviceloader=\"$it\"" + } + requireClauses.add("osgi.extender;filter:=\"(osgi.extender=osgi.serviceloader.registrar)\"") + } + if (slRequires.isNotEmpty()) { + slRequires.forEach { + // resolution:=optional: hints the BND resolver to include provider bundles. + // Does not add the processor extender β€” use osgiServiceLoaderProcessor for that. + requireClauses.add("osgi.serviceloader;filter:=\"(osgi.serviceloader=$it)\";cardinality:=multiple;resolution:=optional") + } + } + if (otelJava.osgiServiceLoaderProcessor.get()) { + // Mandatory: actively pulls a ServiceLoader processor (e.g. SPI Fly) into the resolved + // bundle set so that ServiceLoader.load() calls are routed via the OSGi service registry. + // Set on whichever bundle contains the ServiceLoader.load() call site. + requireClauses.add("osgi.extender;filter:=\"(osgi.extender=osgi.serviceloader.processor)\"") + } + if (requireClauses.isNotEmpty()) { + bndInstructions["Require-Capability"] = requireClauses.joinToString(",") + } + + bnd(bndInstructions) + } + } + } + } + withType().configureEach { inputs.property("moduleName", otelJava.moduleName) @@ -121,7 +221,7 @@ tasks { "Built-By" to System.getProperty("user.name"), "Built-JDK" to System.getProperty("java.version"), "Implementation-Title" to project.name, - "Implementation-Version" to project.version + "Implementation-Version" to project.version, ) } } @@ -137,25 +237,39 @@ tasks { } } +afterEvaluate { + tasks.withType().configureEach { + if (testJavaVersion != null) { + javaLauncher.set( + javaToolchains.launcherFor { + languageVersion.set(JavaLanguageVersion.of(testJavaVersion.majorVersion)) + } + ) + isEnabled = isEnabled && testJavaVersion >= otelJava.minJavaVersionSupported.get() + } + } +} + // Add version information to published artifacts. plugins.withId("otel.publish-conventions") { tasks { register("generateVersionResource") { val moduleName = otelJava.moduleName - val propertiesDir = moduleName.map { File(buildDir, "generated/properties/${it.replace('.', '/')}") } + val propertiesDir = moduleName.map { File(layout.buildDirectory.asFile.get(), "generated/properties/${it.replace('.', '/')}") } + val versionProperty = project.version.toString() - inputs.property("project.version", project.version.toString()) + inputs.property("project.version", versionProperty) outputs.dir(propertiesDir) doLast { - File(propertiesDir.get(), "version.properties").writeText("sdk.version=${project.version}") + File(propertiesDir.get(), "version.properties").writeText("sdk.version=${versionProperty}") } } } sourceSets { main { - output.dir("$buildDir/generated/properties", "builtBy" to "generateVersionResource") + output.dir("${layout.buildDirectory.asFile.get()}/generated/properties", "builtBy" to "generateVersionResource") } } } @@ -167,10 +281,13 @@ configurations.configureEach { } } -val dependencyManagement by configurations.creating { +val dependencyManagement = configurations.create("dependencyManagement") { isCanBeConsumed = false isCanBeResolved = false - isVisible = false +} + +val mockitoAgent = configurations.create("mockitoAgent") { + extendsFrom(dependencyManagement) } dependencies { @@ -183,33 +300,30 @@ dependencies { } } + mockitoAgent("org.mockito:mockito-core") + compileOnly("com.google.auto.value:auto-value-annotations") compileOnly("com.google.code.findbugs:jsr305") - errorprone("com.google.errorprone:error_prone_core") - errorprone("com.uber.nullaway:nullaway") - - annotationProcessor("com.google.guava:guava-beta-checker") - // Workaround for @javax.annotation.Generated // see: https://github.com/grpc/grpc-java/issues/3633 compileOnly("javax.annotation:javax.annotation-api") -} -class TestArgumentsProvider( - @InputFile - @PathSensitive(PathSensitivity.RELATIVE) - val loggingProperties: File, -) : CommandLineArgumentProvider { - override fun asArguments() = listOf( - "-Djava.util.logging.config.file=${loggingProperties.absolutePath}", - ) + modules { + // checkstyle uses the very old google-collections which causes Java 9 module conflict with + // guava which is also on the classpath + module("com.google.collections:google-collections") { + replacedBy("com.google.guava:guava", "google-collections is now part of Guava") + } + } } testing { suites.withType(JvmTestSuite::class).configureEach { + useJUnitJupiter() + dependencies { - implementation(project) + implementation(project()) implementation(project(":testing-internal")) @@ -217,8 +331,6 @@ testing { compileOnly("com.google.errorprone:error_prone_annotations") compileOnly("com.google.code.findbugs:jsr305") - implementation("org.junit.jupiter:junit-jupiter-api") - implementation("org.junit.jupiter:junit-jupiter-params") implementation("nl.jqno.equalsverifier:equalsverifier") implementation("org.mockito:mockito-core") implementation("org.mockito:mockito-junit-jupiter") @@ -227,7 +339,6 @@ testing { implementation("org.junit-pioneer:junit-pioneer") implementation("io.github.netmikey.logunit:logunit-jul") - runtimeOnly("org.junit.jupiter:junit-jupiter-engine") runtimeOnly("org.slf4j:slf4j-simple") } @@ -235,6 +346,27 @@ testing { all { testTask.configure { systemProperty("java.util.logging.config.class", "io.opentelemetry.internal.testing.slf4j.JulBridgeInitializer") + systemProperty("org.slf4j.simpleLogger.log.io.micrometer.core.instrument.MeterRegistry", "error") + systemProperty("org.slf4j.simpleLogger.log.tc", "error") + // Silence ApiUsageLogger output in tests. Includes the one-shot WARNING that fires on + // first misuse plus the per-event FINEST logs. Tests that intentionally exercise API + // misuse can re-enable this logger locally with @SuppressLogger or a Handler override. + systemProperty("org.slf4j.simpleLogger.log.io.opentelemetry.usage", "off") + + // Starting in java 21, dynamically attaching agents triggers warnings. Mockito depends on + // agents to redefine classes. Hence, on java 21+ we get warnings of the form: + // WARNING: A Java agent has been loaded dynamically (/Users/jberg/.gradle/caches/modules-2/files-2.1/net.bytebuddy/byte-buddy-agent/1.12.19/450917cf3b358b691a824acf4c67aa89c826f67e/byte-buddy-agent-1.12.19.jar) + // WARNING: If a serviceability tool is in use, please run with -XX:+EnableDynamicAgentLoading to hide this warning + // WARNING: If a serviceability tool is not in use, please run with -Djdk.instrument.traceUsage for more information + // WARNING: Dynamic loading of agents will be disallowed by default in a future release + // To remove these warnings, we attach the byte-buddy-agent used by mockito directly. + val mockitoAgent: FileCollection = mockitoAgent + doFirst { + // -Xshare:off: the agent appends to the bootstrap classpath, which disables CDS and + // causes a warning in every test process without it. + val mockitoAgentJar = mockitoAgent.files.single { it.name.contains("byte-buddy-agent")} + jvmArgs("-Xshare:off", "-javaagent:${mockitoAgentJar}") + } } } } diff --git a/buildSrc/src/main/kotlin/otel.jmh-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.jmh-conventions.gradle.kts index 96823e1c910..95e6f76fa20 100644 --- a/buildSrc/src/main/kotlin/otel.jmh-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.jmh-conventions.gradle.kts @@ -7,6 +7,11 @@ dependencies { jmh(platform(project(":dependencyManagement"))) jmh("org.openjdk.jmh:jmh-core") jmh("org.openjdk.jmh:jmh-generator-bytecode") + + // This enables running JMH benchmark classes within IntelliJ using + // JMH plugins + jmh("org.openjdk.jmh:jmh-generator-annprocess") + jmhAnnotationProcessor("org.openjdk.jmh:jmh-generator-annprocess") } // invoke jmh on a single benchmark class like so: @@ -18,15 +23,67 @@ jmh { // Could not expand ZIP 'byte-buddy-agent-1.9.7.jar'. includeTests.set(false) profilers.add("gc") - val jmhIncludeSingleClass: String? by project + val jmhIncludeSingleClass = project.findProperty("jmhIncludeSingleClass") as String? if (jmhIncludeSingleClass != null) { - includes.add(jmhIncludeSingleClass as String) + includes.add(jmhIncludeSingleClass) + } + + val jmhFork = project.findProperty("jmhFork") as String? + if (jmhFork != null) { + fork.set(jmhFork.toInt()) + } + + val jmhIterations = project.findProperty("jmhIterations") as String? + if (jmhIterations != null) { + iterations.set(jmhIterations.toInt()) + } + + val jmhTime = project.findProperty("jmhTime") as String? + if (jmhTime != null) { + timeOnIteration.set(jmhTime) + } + + val jmhWarmupIterations = project.findProperty("jmhWarmupIterations") as String? + if (jmhWarmupIterations != null) { + warmupIterations.set(jmhWarmupIterations.toInt()) + } + + val jmhWarmup = project.findProperty("jmhWarmup") as String? + if (jmhWarmup != null) { + warmup.set(jmhWarmup) + } + + val testJavaVersion = gradle.startParameter.projectProperties.get("testJavaVersion")?.let(JavaVersion::toVersion) + if (testJavaVersion != null) { + val javaExecutable = javaToolchains.launcherFor { + languageVersion.set(JavaLanguageVersion.of(testJavaVersion.majorVersion)) + }.get().executablePath.asFile.absolutePath + + jvm.set(javaExecutable) + } +} + +val jmhResultsDir = project.findProperty("jmhResultsDir") as String? +if (jmhResultsDir != null) { + val jmhLabel = (project.findProperty("jmhLabel") as String?) + ?: project.path.trimStart(':').replace(':', '-').ifEmpty { project.name } + + val jmhCopyResults = tasks.register("jmhCopyResults") { + description = "Copies JMH JSON results to jmhResultsDir for cross-run comparison." + from(layout.buildDirectory.file("results/jmh/results.json")) + into(rootProject.file(jmhResultsDir)) + rename { "${jmhLabel}.json" } + } + + tasks.named("jmh") { + finalizedBy(jmhCopyResults) } } jmhReport { - jmhResultPath = file("$buildDir/results/jmh/results.json").absolutePath - jmhReportOutput = file("$buildDir/results/jmh").absolutePath + val buildDirectory = layout.buildDirectory.asFile.get() + jmhResultPath = file("$buildDirectory/results/jmh/results.json").absolutePath + jmhReportOutput = file("$buildDirectory/results/jmh").absolutePath } tasks { diff --git a/buildSrc/src/main/kotlin/otel.protobuf-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.protobuf-conventions.gradle.kts index cacaacbada4..de1aabd9622 100644 --- a/buildSrc/src/main/kotlin/otel.protobuf-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.protobuf-conventions.gradle.kts @@ -1,13 +1,13 @@ import com.google.protobuf.gradle.* plugins { - id("com.google.protobuf") - id("otel.java-conventions") + + id("com.google.protobuf") } protobuf { - val versions: Map by project + val versions = project.property("versions") as Map<*, *> protoc { // The artifact spec for the Protobuf Compiler artifact = "com.google.protobuf:protoc:${versions["com.google.protobuf"]}" diff --git a/buildSrc/src/main/kotlin/otel.publish-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.publish-conventions.gradle.kts index cc8cf3a0f5e..0a6a100fe15 100644 --- a/buildSrc/src/main/kotlin/otel.publish-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.publish-conventions.gradle.kts @@ -32,6 +32,17 @@ publishing { name.set("OpenTelemetry Java") url.set("https://github.com/open-telemetry/opentelemetry-java") + withXml { + // Since 5.0 okhttp uses gradle metadata to choose either okhttp-jvm or okhttp-android. + // This does not work for maven builds that don't understand gradle metadata. They end up + // using the okhttp artifact that is an empty jar. Here we replace usages of okhttp with + // okhttp-jvm so that maven could get the actual okhttp dependency instead of the empty jar. + var result = asString() + var modified = result.toString().replace(">okhttp<", ">okhttp-jvm<") + result.clear() + result.append(modified) + } + licenses { license { name.set("The Apache License, Version 2.0") diff --git a/buildSrc/src/main/kotlin/otel.spotless-conventions.gradle.kts b/buildSrc/src/main/kotlin/otel.spotless-conventions.gradle.kts index d2245ee4b72..b1c39dcd0db 100644 --- a/buildSrc/src/main/kotlin/otel.spotless-conventions.gradle.kts +++ b/buildSrc/src/main/kotlin/otel.spotless-conventions.gradle.kts @@ -22,12 +22,40 @@ spotless { } plugins.withId("org.jetbrains.kotlin.jvm") { kotlin { - ktlint().userData(mapOf("indent_size" to "2", "continuation_indent_size" to "2", "disabled_rules" to "no-wildcard-imports")) + ktlint().editorConfigOverride(mapOf( + "indent_size" to "2", + "continuation_indent_size" to "2", + "max_line_length" to "160", + "insert_final_newline" to "true", + "ktlint_standard_no-wildcard-imports" to "disabled", + // ktlint does not break up long lines, it just fails on them + "ktlint_standard_max-line-length" to "disabled", + // ktlint makes it *very* hard to locate where this actually happened + "ktlint_standard_trailing-comma-on-call-site" to "disabled", + // depends on ktlint_standard_wrapping + "ktlint_standard_trailing-comma-on-declaration-site" to "disabled", + // also very hard to find out where this happens + "ktlint_standard_wrapping" to "disabled" + )) licenseHeaderFile(rootProject.file("buildscripts/spotless.license.java"), "(package|import|class|// Includes work from:)") } } kotlinGradle { - ktlint().userData(mapOf("indent_size" to "2", "continuation_indent_size" to "2", "disabled_rules" to "no-wildcard-imports")) + ktlint().editorConfigOverride(mapOf( + "indent_size" to "2", + "continuation_indent_size" to "2", + "max_line_length" to "160", + "insert_final_newline" to "true", + "ktlint_standard_no-wildcard-imports" to "disabled", + // ktlint does not break up long lines, it just fails on them + "ktlint_standard_max-line-length" to "disabled", + // ktlint makes it *very* hard to locate where this actually happened + "ktlint_standard_trailing-comma-on-call-site" to "disabled", + // depends on ktlint_standard_wrapping + "ktlint_standard_trailing-comma-on-declaration-site" to "disabled", + // also very hard to find out where this happens + "ktlint_standard_wrapping" to "disabled" + )) } format("misc") { // not using "**/..." to help keep spotless fast @@ -40,9 +68,9 @@ spotless { "src/**/*.md", "docs/**/*.md", "*.sh", - "src/**/*.properties" + "src/**/*.properties", ) - indentWithSpaces() + leadingTabsToSpaces() trimTrailingWhitespace() endWithNewline() } diff --git a/buildscripts/checkstyle-suppressions.xml b/buildscripts/checkstyle-suppressions.xml index bee50be5ec9..f5501405d3a 100644 --- a/buildscripts/checkstyle-suppressions.xml +++ b/buildscripts/checkstyle-suppressions.xml @@ -6,7 +6,6 @@ - diff --git a/buildscripts/checkstyle.xml b/buildscripts/checkstyle.xml index 1297813fceb..b52c467bd53 100644 --- a/buildscripts/checkstyle.xml +++ b/buildscripts/checkstyle.xml @@ -151,17 +151,14 @@ value="CLASS_DEF, INTERFACE_DEF, ENUM_DEF, METHOD_DEF, CTOR_DEF, VARIABLE_DEF"/> - + - - - diff --git a/buildscripts/semantic-convention/.gitignore b/buildscripts/semantic-convention/.gitignore deleted file mode 100644 index a93b221beb5..00000000000 --- a/buildscripts/semantic-convention/.gitignore +++ /dev/null @@ -1 +0,0 @@ -opentelemetry-specification/ diff --git a/buildscripts/semantic-convention/generate.sh b/buildscripts/semantic-convention/generate.sh deleted file mode 100755 index aeed653fefe..00000000000 --- a/buildscripts/semantic-convention/generate.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash - -SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -ROOT_DIR="${SCRIPT_DIR}/../../" - -# freeze the spec & generator tools versions to make SemanticAttributes generation reproducible -SEMCONV_VERSION=1.9.0 -SPEC_VERSION=v$SEMCONV_VERSION -SCHEMA_URL=https://opentelemetry.io/schemas/$SEMCONV_VERSION -GENERATOR_VERSION=0.7.0 - -cd ${SCRIPT_DIR} - -rm -rf opentelemetry-specification || true -mkdir opentelemetry-specification -cd opentelemetry-specification - -git init -git remote add origin https://github.com/open-telemetry/opentelemetry-specification.git -git fetch origin "$SPEC_VERSION" -git reset --hard FETCH_HEAD -cd ${SCRIPT_DIR} - -docker run --rm \ - -v ${SCRIPT_DIR}/opentelemetry-specification/semantic_conventions/trace:/source \ - -v ${SCRIPT_DIR}/templates:/templates \ - -v ${ROOT_DIR}/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/:/output \ - otel/semconvgen:$GENERATOR_VERSION \ - -f /source code \ - --template /templates/SemanticAttributes.java.j2 \ - --output /output/SemanticAttributes.java \ - -Dclass=SemanticAttributes \ - -DschemaUrl=$SCHEMA_URL \ - -Dpkg=io.opentelemetry.semconv.trace.attributes - -docker run --rm \ - -v ${SCRIPT_DIR}/opentelemetry-specification/semantic_conventions/resource:/source \ - -v ${SCRIPT_DIR}/templates:/templates \ - -v ${ROOT_DIR}/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/:/output \ - otel/semconvgen:$GENERATOR_VERSION \ - -f /source code \ - --template /templates/SemanticAttributes.java.j2 \ - --output /output/ResourceAttributes.java \ - -Dclass=ResourceAttributes \ - -DschemaUrl=$SCHEMA_URL \ - -Dpkg=io.opentelemetry.semconv.resource.attributes - -cd "$ROOT_DIR" -./gradlew spotlessApply diff --git a/buildscripts/semantic-convention/templates/SemanticAttributes.java.j2 b/buildscripts/semantic-convention/templates/SemanticAttributes.java.j2 deleted file mode 100644 index afc53564759..00000000000 --- a/buildscripts/semantic-convention/templates/SemanticAttributes.java.j2 +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - - -{%- macro to_java_return_type(type) -%} - {%- if type == "string" -%} - String - {%- elif type == "string[]" -%} - List - {%- elif type == "boolean" -%} - boolean - {%- elif type == "int" -%} - long - {%- elif type == "double" -%} - double - {%- else -%} - {{type}} - {%- endif -%} -{%- endmacro %} -{%- macro to_java_key_type(type) -%} - {%- if type == "string" -%} - stringKey - {%- elif type == "string[]" -%} - stringArrayKey - {%- elif type == "boolean" -%} - booleanKey - {%- elif type == "int" -%} - longKey - {%- elif type == "double" -%} - doubleKey - {%- else -%} - {{lowerFirst(type)}}Key - {%- endif -%} -{%- endmacro %} -{%- macro print_value(type, value) -%} - {{ "\"" if type == "String"}}{{value}}{{ "\"" if type == "String"}} -{%- endmacro %} -{%- macro upFirst(text) -%} - {{ text[0]|upper}}{{text[1:] }} -{%- endmacro %} -{%- macro lowerFirst(text) -%} - {{ text[0]|lower}}{{text[1:] }} -{%- endmacro %} - -package {{pkg | trim}}; - -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.doubleKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; - -import io.opentelemetry.api.common.AttributeKey; -import java.util.List; - -// DO NOT EDIT, this is an Auto-generated file from buildscripts/semantic-convention{{template}} -public final class {{class}} { - /** - * The URL of the OpenTelemetry schema for these keys and values. - */ - public static final String SCHEMA_URL = "{{schemaUrl}}"; - {%- for attribute in attributes if attribute.is_local and not attribute.ref %} - - /** - * {{attribute.brief | render_markdown(code="{{@code {0}}}", paragraph="{0}")}} - {%- if attribute.note %} - * - *

    Notes: -

      {{attribute.note | render_markdown(code="{{@code {0}}}", paragraph="
    • {0}
    • ", list="{0}")}}
    - {%- endif %} - {%- if attribute.deprecated %} - * - * @deprecated {{attribute.deprecated | to_doc_brief}}. - {%- endif %} - */ - {%- if attribute.deprecated %} - @Deprecated - {%- endif %} - public static final AttributeKey<{{upFirst(to_java_return_type(attribute.attr_type | string))}}> {{attribute.fqn | to_const_name}} = {{to_java_key_type(attribute.attr_type | string)}}("{{attribute.fqn}}"); - {%- endfor %} - - // Enum definitions - {%- for attribute in attributes if attribute.is_local and not attribute.ref %} - {%- if attribute.is_enum %} - {%- set class_name = attribute.fqn | to_camelcase(True) ~ "Values" %} - {%- set type = to_java_return_type(attribute.attr_type.enum_type) %} - public static final class {{class_name}} { - {%- for member in attribute.attr_type.members %} - /** {% filter escape %}{{member.brief | to_doc_brief}}.{% endfilter %} */ - public static final {{ type }} {{ member.member_id | to_const_name }} = {{ print_value(type, member.value) }}; - {%- endfor %} - private {{ class_name }}() {} - } - - {% endif %} - {%- endfor %} - - {%- if class == "SemanticAttributes" %} - // Manually defined and not YET in the YAML - /** - * The name of an event describing an exception. - * - *

    Typically an event with that name should not be manually created. Instead {@link - * io.opentelemetry.api.trace.Span#recordException(Throwable)} should be used. - */ - public static final String EXCEPTION_EVENT_NAME = "exception"; - - /** - * The name of the keyspace being accessed. - * - * @deprecated this item has been removed as of 1.8.0 of the semantic conventions. Please use {@link SemanticAttributes#DB_NAME} instead. - */ - @Deprecated - public static final AttributeKey DB_CASSANDRA_KEYSPACE = - stringKey("db.cassandra.keyspace"); - - /** - * The HBase namespace being accessed. - * - * @deprecated this item has been removed as of 1.8.0 of the semantic conventions. Please use {@link SemanticAttributes#DB_NAME} instead. - */ - @Deprecated - public static final AttributeKey DB_HBASE_NAMESPACE = stringKey("db.hbase.namespace"); - - {% endif %} - - private {{class}}() {} -} diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 00000000000..18081f4761e --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,21 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry API Common" +otelJava.moduleName.set("io.opentelemetry.common") +otelJava.requireSuppressWarningsExplanation.set(false) +// ServiceLoaderComponentLoader (this bundle) is the ServiceLoader.load() call site for all +// ComponentLoader.forClassLoader() usage; requires the processor extender to weave it. +otelJava.osgiServiceLoaderProcessor.set(true) + +dependencies { +} + +tasks.test { + // Configure environment variable for ConfigUtilTest + environment("CONFIG_KEY", "environment") +} diff --git a/common/src/main/java/io/opentelemetry/common/ComponentLoader.java b/common/src/main/java/io/opentelemetry/common/ComponentLoader.java new file mode 100644 index 00000000000..33d835b9906 --- /dev/null +++ b/common/src/main/java/io/opentelemetry/common/ComponentLoader.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.common; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.ServiceLoader; + +/** A loader for components that are discovered via SPI. */ +public interface ComponentLoader { + /** + * Load implementations of an SPI. + * + * @param spiClass the SPI class + * @param the SPI type + * @return iterable of SPI implementations + */ + Iterable load(Class spiClass); + + /** + * Create an instance for the {@code classLoader} using {@link ServiceLoader#load(Class, + * ClassLoader)}. + */ + static ComponentLoader forClassLoader(ClassLoader classLoader) { + return new ServiceLoaderComponentLoader(classLoader); + } + + /** + * Convenience method to load a list of SPI implementations rather than the iterable returned by + * {@link #load(Class)}. + * + * @since 1.61.0 + */ + static List loadList(ComponentLoader componentLoader, Class spiClass) { + List result = new ArrayList<>(); + componentLoader.load(spiClass).forEach(result::add); + return Collections.unmodifiableList(result); + } +} diff --git a/common/src/main/java/io/opentelemetry/common/ServiceLoaderComponentLoader.java b/common/src/main/java/io/opentelemetry/common/ServiceLoaderComponentLoader.java new file mode 100644 index 00000000000..5f2d0c58cd8 --- /dev/null +++ b/common/src/main/java/io/opentelemetry/common/ServiceLoaderComponentLoader.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.common; + +import java.util.ServiceLoader; + +class ServiceLoaderComponentLoader implements ComponentLoader { + + private final ClassLoader classLoader; + + ServiceLoaderComponentLoader(ClassLoader classLoader) { + this.classLoader = classLoader; + } + + @Override + public Iterable load(Class spiClass) { + return ServiceLoader.load(spiClass, classLoader); + } + + @Override + public String toString() { + return "ServiceLoaderComponentLoader{classLoader=" + classLoader + "}"; + } +} diff --git a/common/src/main/java/io/opentelemetry/common/impl/ApiUsageLogger.java b/common/src/main/java/io/opentelemetry/common/impl/ApiUsageLogger.java new file mode 100644 index 00000000000..15180c019f9 --- /dev/null +++ b/common/src/main/java/io/opentelemetry/common/impl/ApiUsageLogger.java @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.common.impl; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * A utility for logging API misuse, allowing operators to diagnose invalid usage with a single + * logging configuration entry. + * + *

    Logs at {@link Level#FINEST} by default, so messages are silent in production unless + * explicitly enabled. Each log record includes a {@link Throwable} to make the offending call site + * visible in the stack trace without requiring the exception to be thrown. + * + *

    The first time any API misuse is detected, a one-time {@link Level#WARNING} is emitted to the + * {@code io.opentelemetry.usage} logger. This warning is visible under default logging + * configuration and signals that API misuse is occurring. To see the full details of every misuse + * event (message and stack trace), configure the {@code io.opentelemetry.usage} logger at {@link + * Level#FINEST}. + * + *

    This class is not intended for use by application developers. Its API is stable and will not + * be changed or removed in a backwards-incompatible manner. + * + * @since 1.62.0 + */ +public final class ApiUsageLogger { + + /** The logger name used for all API-misuse diagnostics. */ + private static final Logger LOGGER = Logger.getLogger("io.opentelemetry.usage"); + + private static final AtomicBoolean WARN_ONCE = new AtomicBoolean(); + + /** + * Log that {@code paramName} was null in {@code apiClass#methodName}. + * + *

    Convenience overload of {@link #logUsageIssue(Class, String, String)} for the common case of + * a null parameter that should not be null. + * + * @param apiClass the public API class where the misuse occurred + * @param methodName the name of the method where the misuse occurred + * @param paramName the name of the parameter that was null + */ + public static void logNullParam(Class apiClass, String methodName, String paramName) { + logUsageIssue(apiClass, methodName, paramName + " is null"); + } + + /** + * Log a misuse of {@code apiClass#methodName} with the given {@code message}. + * + *

    Logs at {@link Level#FINEST} and includes a stack trace. + * + * @param apiClass the public API class where the misuse occurred + * @param methodName the name of the method where the misuse occurred + * @param message a brief description of the problem + */ + public static void logUsageIssue(Class apiClass, String methodName, String message) { + if (WARN_ONCE.compareAndSet(false, true)) { + LOGGER.warning( + "OpenTelemetry API usage issue detected. To see more details, enable FINEST logging for io.opentelemetry.usage. Stacktraces are included to identify the offending call site."); + } + if (LOGGER.isLoggable(Level.FINEST)) { + LOGGER.log( + Level.FINEST, + apiClass.getSimpleName() + "." + methodName + "(): " + message, + new Throwable()); + } + } + + private ApiUsageLogger() {} +} diff --git a/common/src/main/java/io/opentelemetry/common/impl/ConfigUtil.java b/common/src/main/java/io/opentelemetry/common/impl/ConfigUtil.java new file mode 100644 index 00000000000..cd8ee760793 --- /dev/null +++ b/common/src/main/java/io/opentelemetry/common/impl/ConfigUtil.java @@ -0,0 +1,96 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.common.impl; + +import java.util.ConcurrentModificationException; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; + +/** + * Configuration utilities. + * + *

    This class is not intended for use by application developers. Its API is stable and will not + * be changed or removed in a backwards-incompatible manner. + * + * @since 1.67.0 + */ +public final class ConfigUtil { + + private ConfigUtil() {} + + /** + * Returns a copy of system properties which is safe to iterate over. + * + *

    In java 8 and android environments, iterating through system properties may trigger {@link + * ConcurrentModificationException}. This method ensures callers can iterate safely without risk + * of exception. See https://github.com/open-telemetry/opentelemetry-java/issues/6732 for details. + * + * @return a copy of system properties + */ + public static Properties safeSystemProperties() { + return (Properties) System.getProperties().clone(); + } + + /** + * Return the system property or environment variable for the {@code key}. + * + *

    Normalize the {@code key} using {@link #normalizePropertyKey(String)}. Match to system + * property keys also normalized with {@link #normalizePropertyKey(String)}. Further normalize the + * {@code key} using {@link #normalizeEnvironmentVariableKey(String)} and match to environment + * variable keys normalized the same way. System properties take priority over environment + * variables. + * + *

    For example, {@code otel.experimental.sdk.jvm_stacktrace} matches the environment variable + * {@code OTEL_EXPERIMENTAL_SDK_JVM_STACKTRACE}. + * + * @param key the property key + * @param defaultValue the fallback value if neither system property nor environment variable is + * set + * @return the system property if not null, or the environment variable if not null, or {@code + * defaultValue} + */ + public static String getString(String key, String defaultValue) { + String normalizedKey = normalizePropertyKey(key); + + String systemProperty = + safeSystemProperties().entrySet().stream() + .filter(entry -> normalizedKey.equals(normalizePropertyKey(entry.getKey().toString()))) + .map(entry -> entry.getValue().toString()) + .findFirst() + .orElse(null); + if (systemProperty != null) { + return systemProperty; + } + String environmentVariableKey = normalizeEnvironmentVariableKey(normalizedKey); + return System.getenv().entrySet().stream() + .filter( + entry -> environmentVariableKey.equals(normalizeEnvironmentVariableKey(entry.getKey()))) + .map(Map.Entry::getValue) + .findFirst() + .orElse(defaultValue); + } + + /** + * Normalize an environment variable key by converting to lower case and replacing "_" with ".". + * + * @param key the environment variable key + * @return the normalized key + */ + public static String normalizeEnvironmentVariableKey(String key) { + return key.toLowerCase(Locale.ROOT).replace("_", "."); + } + + /** + * Normalize a property key by converting to lower case and replacing "-" with ".". + * + * @param key the property key + * @return the normalized key + */ + public static String normalizePropertyKey(String key) { + return key.toLowerCase(Locale.ROOT).replace("-", "."); + } +} diff --git a/common/src/test/java/io/opentelemetry/common/impl/ApiUsageLoggerTest.java b/common/src/test/java/io/opentelemetry/common/impl/ApiUsageLoggerTest.java new file mode 100644 index 00000000000..932f3ca0b18 --- /dev/null +++ b/common/src/test/java/io/opentelemetry/common/impl/ApiUsageLoggerTest.java @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.common.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.lang.reflect.Field; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.slf4j.event.Level; + +@SuppressLogger(loggerName = "io.opentelemetry.usage") +class ApiUsageLoggerTest { + + @RegisterExtension + LogCapturer apiUsageLogs = + LogCapturer.create().captureForLogger("io.opentelemetry.usage", Level.TRACE); + + @BeforeEach + void resetWarnOnce() throws Exception { + Field warnOnce = ApiUsageLogger.class.getDeclaredField("WARN_ONCE"); + warnOnce.setAccessible(true); + ((AtomicBoolean) warnOnce.get(null)).set(false); + } + + @Test + void log() { + ApiUsageLogger.logUsageIssue(ApiUsageLoggerTest.class, "log", "thing went wrong"); + apiUsageLogs.assertContains("ApiUsageLoggerTest.log(): thing went wrong"); + } + + @Test + void logNullParam() { + ApiUsageLogger.logNullParam(ApiUsageLoggerTest.class, "logNullParam", "myParam"); + apiUsageLogs.assertContains("ApiUsageLoggerTest.logNullParam(): myParam is null"); + } + + @Test + void warnOnce() { + ApiUsageLogger.logUsageIssue(ApiUsageLoggerTest.class, "warnOnce", "first"); + ApiUsageLogger.logUsageIssue(ApiUsageLoggerTest.class, "warnOnce", "second"); + long count = + apiUsageLogs.getEvents().stream() + .filter(e -> e.getMessage().contains("OpenTelemetry API usage issue detected")) + .count(); + assertEquals(1, count); + } +} diff --git a/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java b/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java new file mode 100644 index 00000000000..851465e0009 --- /dev/null +++ b/common/src/test/java/io/opentelemetry/common/impl/ConfigUtilTest.java @@ -0,0 +1,101 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.common.impl; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.SetSystemProperty; + +/** Relies on environment configuration in {@code ./common/build.gradle.kts}. */ +class ConfigUtilTest { + + @Test + @SetSystemProperty(key = "config.key", value = "system") + void getString_SystemPropertyPriority() { + assertThat(ConfigUtil.getString("config.key", "default")).isEqualTo("system"); + assertThat(ConfigUtil.getString("config-key", "default")).isEqualTo("system"); + assertThat(ConfigUtil.getString("other.config.key", "default")).isEqualTo("default"); + } + + @Test + @SetSystemProperty(key = "CONFIG-KEY", value = "system") + void getString_SystemPropertyNormalized() { + assertThat(ConfigUtil.getString("config.key", "default")).isEqualTo("system"); + assertThat(ConfigUtil.getString("config-key", "default")).isEqualTo("system"); + assertThat(ConfigUtil.getString("other.config.key", "default")).isEqualTo("default"); + } + + @Test + void getString_EnvironmentVariable() { + assertThat(ConfigUtil.getString("config.key", "default")).isEqualTo("environment"); + assertThat(ConfigUtil.getString("config_key", "default")).isEqualTo("environment"); + assertThat(ConfigUtil.getString("other.config.key", "default")).isEqualTo("default"); + } + + @Test + void normalizeEnvironmentVariable() { + assertThat(ConfigUtil.normalizeEnvironmentVariableKey("CONFIG_KEY")).isEqualTo("config.key"); + assertThat(ConfigUtil.normalizeEnvironmentVariableKey("config_key")).isEqualTo("config.key"); + assertThat(ConfigUtil.normalizeEnvironmentVariableKey("config-key")).isEqualTo("config-key"); + assertThat(ConfigUtil.normalizeEnvironmentVariableKey("configkey")).isEqualTo("configkey"); + } + + @Test + void normalizePropertyKey() { + assertThat(ConfigUtil.normalizePropertyKey("CONFIG_KEY")).isEqualTo("config_key"); + assertThat(ConfigUtil.normalizePropertyKey("CONFIG.KEY")).isEqualTo("config.key"); + assertThat(ConfigUtil.normalizePropertyKey("config-key")).isEqualTo("config.key"); + assertThat(ConfigUtil.normalizePropertyKey("configkey")).isEqualTo("configkey"); + } + + @Test + @SuppressWarnings("ReturnValueIgnored") + void systemPropertiesConcurrentAccess() throws ExecutionException, InterruptedException { + int threads = 4; + ExecutorService executor = Executors.newFixedThreadPool(threads); + try { + int cycles = 1000; + CountDownLatch latch = new CountDownLatch(1); + List> futures = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + futures.add( + executor.submit(() -> { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + + for (int j = 0; j < cycles; j++) { + String property = "prop " + j; + System.setProperty(property, "a"); + System.getProperties().remove(property); + } + })); + } + + latch.countDown(); + for (int i = 0; i < cycles; i++) { + assertThatCode(() -> ConfigUtil.getString("x", "y")).doesNotThrowAnyException(); + } + + for (Future future : futures) { + future.get(); + } + } finally { + executor.shutdown(); + } + } +} diff --git a/context/README.md b/context/README.md deleted file mode 100644 index f2ad11c09c1..00000000000 --- a/context/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Context - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-context.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-context diff --git a/context/build.gradle.kts b/context/build.gradle.kts index caf9baedd7c..d539820b281 100644 --- a/context/build.gradle.kts +++ b/context/build.gradle.kts @@ -8,8 +8,10 @@ plugins { description = "OpenTelemetry Context (Incubator)" otelJava.moduleName.set("io.opentelemetry.context") +otelJava.requireSuppressWarningsExplanation.set(false) dependencies { + api(project(":common")) // MustBeClosed compileOnly("com.google.errorprone:error_prone_annotations") @@ -18,40 +20,40 @@ dependencies { testing { suites { - val grpcInOtelTest by registering(JvmTestSuite::class) { + register("grpcInOtelTest") { dependencies { - implementation("io.grpc:grpc-context") + implementation("io.grpc:grpc-api") } } - val otelInGrpcTest by registering(JvmTestSuite::class) { + register("otelInGrpcTest") { dependencies { - implementation("io.grpc:grpc-context") + implementation("io.grpc:grpc-api") } } - val braveInOtelTest by registering(JvmTestSuite::class) { + register("braveInOtelTest") { dependencies { implementation("io.zipkin.brave:brave") } } - val otelInBraveTest by registering(JvmTestSuite::class) { + register("otelInBraveTest") { dependencies { implementation("io.zipkin.brave:brave") } } - val otelAsBraveTest by registering(JvmTestSuite::class) { + register("otelAsBraveTest") { dependencies { implementation("io.zipkin.brave:brave") } } - val storageWrappersTest by registering(JvmTestSuite::class) { + register("storageWrappersTest") { } - val strictContextEnabledTest by registering(JvmTestSuite::class) { + register("strictContextEnabledTest") { dependencies { implementation(project(":api:all")) } diff --git a/context/src/braveInOtelTest/java/io/opentelemetry/context/BraveInOtelTest.java b/context/src/braveInOtelTest/java/io/opentelemetry/context/BraveInOtelTest.java index efaf20562d0..13298a341e2 100644 --- a/context/src/braveInOtelTest/java/io/opentelemetry/context/BraveInOtelTest.java +++ b/context/src/braveInOtelTest/java/io/opentelemetry/context/BraveInOtelTest.java @@ -27,6 +27,7 @@ class BraveInOtelTest { private static final TraceContext TRACE_CONTEXT = TraceContext.newBuilder().traceId(1).spanId(1).addExtra("japan").build(); + @SuppressWarnings("NonFinalStaticField") private static ExecutorService otherThread; @BeforeAll diff --git a/context/src/grpcInOtelTest/java/io/grpc/override/ContextStorageOverride.java b/context/src/grpcInOtelTest/java/io/grpc/override/ContextStorageOverride.java index b30df462eb9..c3c83f32f39 100644 --- a/context/src/grpcInOtelTest/java/io/grpc/override/ContextStorageOverride.java +++ b/context/src/grpcInOtelTest/java/io/grpc/override/ContextStorageOverride.java @@ -19,7 +19,7 @@ public class ContextStorageOverride extends Context.Storage { private static final ContextKey GRPC_CONTEXT = ContextKey.named("grpc-context"); private static final Context.Key OTEL_SCOPE = Context.key("otel-scope"); - @SuppressWarnings("MustBeClosedChecker") + @SuppressWarnings({"MustBeClosedChecker", "ReferenceEquality"}) @Override public Context doAttach(Context toAttach) { io.opentelemetry.context.Context otelContext = io.opentelemetry.context.Context.current(); @@ -39,6 +39,7 @@ public Context doAttach(Context toAttach) { } @Override + @SuppressWarnings("ReferenceEquality") public void detach(Context toDetach, Context toRestore) { if (current() != toDetach) { // Log a severe message instead of throwing an exception as the context to attach is assumed diff --git a/context/src/grpcInOtelTest/java/io/opentelemetry/context/GrpcInOtelTest.java b/context/src/grpcInOtelTest/java/io/opentelemetry/context/GrpcInOtelTest.java index 265c623ed4f..4d22ed765ee 100644 --- a/context/src/grpcInOtelTest/java/io/opentelemetry/context/GrpcInOtelTest.java +++ b/context/src/grpcInOtelTest/java/io/opentelemetry/context/GrpcInOtelTest.java @@ -21,6 +21,7 @@ class GrpcInOtelTest { private static final io.grpc.Context.Key FOOD = io.grpc.Context.key("food"); private static final io.grpc.Context.Key COUNTRY = io.grpc.Context.key("country"); + @SuppressWarnings("NonFinalStaticField") private static ExecutorService otherThread; @BeforeAll diff --git a/context/src/main/java/io/opentelemetry/context/ArrayBasedContext.java b/context/src/main/java/io/opentelemetry/context/ArrayBasedContext.java index ba3f22559eb..d4274c60c8d 100644 --- a/context/src/main/java/io/opentelemetry/context/ArrayBasedContext.java +++ b/context/src/main/java/io/opentelemetry/context/ArrayBasedContext.java @@ -22,6 +22,7 @@ package io.opentelemetry.context; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.Arrays; import javax.annotation.Nullable; @@ -53,7 +54,12 @@ private ArrayBasedContext(Object[] entries) { @Override @Nullable + @SuppressWarnings("ReferenceEquality") public V get(ContextKey key) { + if (key == null) { + ApiUsageLogger.logNullParam(Context.class, "get", "key"); + return null; + } for (int i = 0; i < entries.length; i += 2) { if (entries[i] == key) { @SuppressWarnings("unchecked") @@ -65,7 +71,16 @@ public V get(ContextKey key) { } @Override + @SuppressWarnings("ReferenceEquality") public Context with(ContextKey key, V value) { + if (key == null) { + ApiUsageLogger.logNullParam(Context.class, "with", "key"); + return this; + } + if (value == null) { + ApiUsageLogger.logNullParam(Context.class, "with", "value"); + // Continue to preserve the preexisting behavior of storing null values. + } for (int i = 0; i < entries.length; i += 2) { if (entries[i] == key) { if (entries[i + 1] == value) { diff --git a/context/src/main/java/io/opentelemetry/context/Context.java b/context/src/main/java/io/opentelemetry/context/Context.java index d9c9f50c889..8eec2765928 100644 --- a/context/src/main/java/io/opentelemetry/context/Context.java +++ b/context/src/main/java/io/opentelemetry/context/Context.java @@ -23,10 +23,13 @@ package io.opentelemetry.context; import com.google.errorprone.annotations.MustBeClosed; +import io.opentelemetry.common.impl.ApiUsageLogger; +import java.util.Objects; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; @@ -41,7 +44,7 @@ *

    A Context object can be {@linkplain #makeCurrent set} to the {@link ContextStorage}, which * effectively forms a scope for the context. The scope is bound to the current thread. * Within a scope, its Context is accessible even across API boundaries, through {@link #current}. - * The scope is later exited by {@link Scope#close()} closing} the scope. + * The scope is later exited by {@linkplain Scope#close() closing} the scope. * *

    Context objects are immutable and inherit state from their parent. To add or overwrite the * current state a new context object must be created and then attached, replacing the previously @@ -51,7 +54,7 @@ * Context withCredential = Context.current().with(CRED_KEY, cred); * withCredential.wrap(new Runnable() { * public void run() { - * readUserRecords(userId, CRED_KEY.get()); + * readUserRecords(userId, Context.current().get(CRED_KEY)); * } * }).run(); * } @@ -111,12 +114,14 @@ static Context root() { * *

    This is generally used to create an {@link Executor} which will forward the {@link Context} * during an invocation to another thread. For example, you may use something like {@code Executor - * dbExecutor = Context.wrapTasks(threadPool)} to ensure calls like {@code dbExecutor.execute(() - * -> database.query())} have {@link Context} available on the thread executing database queries. + * dbExecutor = Context.taskWrapping(threadPool)} to ensure calls like {@code + * dbExecutor.execute(() -> database.query())} have {@link Context} available on the thread + * executing database queries. * * @since 1.1.0 */ static Executor taskWrapping(Executor executor) { + Objects.requireNonNull(executor, "executor"); return command -> executor.execute(Context.current().wrap(command)); } @@ -128,16 +133,46 @@ static Executor taskWrapping(Executor executor) { * *

    This is generally used to create an {@link ExecutorService} which will forward the {@link * Context} during an invocation to another thread. For example, you may use something like {@code - * ExecutorService dbExecutor = Context.wrapTasks(threadPool)} to ensure calls like {@code + * ExecutorService dbExecutor = Context.taskWrapping(threadPool)} to ensure calls like {@code * dbExecutor.execute(() -> database.query())} have {@link Context} available on the thread * executing database queries. * * @since 1.1.0 */ static ExecutorService taskWrapping(ExecutorService executorService) { + Objects.requireNonNull(executorService, "executorService"); + if (executorService instanceof CurrentContextExecutorService) { + return executorService; + } return new CurrentContextExecutorService(executorService); } + /** + * Returns an {@link ScheduledExecutorService} which delegates to the provided {@code + * executorService}, wrapping all invocations of {@link ExecutorService} methods such as {@link + * ExecutorService#execute(Runnable)} or {@link ExecutorService#submit(Runnable)} with the + * {@linkplain Context#current() current context} at the time of invocation. + * + *

    This is generally used to create an {@link ScheduledExecutorService} which will forward the + * {@link Context} during an invocation to another thread. For example, you may use something like + * {@code ScheduledExecutorService dbExecutor = Context.taskWrapping(threadPool)} to ensure calls + * like {@code dbExecutor.execute(() -> database.query())} have {@link Context} available on the + * thread executing database queries. + * + *

    Note: The context will not be propagated for {@link + * ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} and {@link + * ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)} calls. + * + * @since 1.43.0 + */ + static ScheduledExecutorService taskWrapping(ScheduledExecutorService executorService) { + Objects.requireNonNull(executorService, "executorService"); + if (executorService instanceof CurrentContextScheduledExecutorService) { + return executorService; + } + return new CurrentContextScheduledExecutorService(executorService); + } + /** * Returns the value stored in this {@link Context} for the given {@link ContextKey}, or {@code * null} if there is no value for the key in this context. @@ -152,7 +187,7 @@ static ExecutorService taskWrapping(ExecutorService executorService) { * Context withCredential = Context.current().with(CRED_KEY, cred); * withCredential.wrap(new Runnable() { * public void run() { - * readUserRecords(userId, CRED_KEY.get()); + * readUserRecords(userId, Context.current().get(CRED_KEY)); * } * }).run(); * } @@ -171,6 +206,10 @@ static ExecutorService taskWrapping(ExecutorService executorService) { /** Returns a new {@link Context} with the given {@link ImplicitContextKeyed} set. */ default Context with(ImplicitContextKeyed value) { + if (value == null) { + ApiUsageLogger.logNullParam(Context.class, "with", "value"); + return this; + } return value.storeInContext(this); } @@ -183,7 +222,7 @@ default Context with(ImplicitContextKeyed value) { * Scope#close()} automatically. * *

    The default implementation of this method will store the {@link Context} in a {@link - * ThreadLocal}. Kotlin coroutine users SHOULD NOT use this method as the {@link ThreadLocal} will + * ThreadLocal}. Kotlin coroutine users should not use this method as the {@link ThreadLocal} will * not be properly synced across coroutine suspension and resumption. Instead, use {@code * withContext(context.asContextElement())} provided by the {@code opentelemetry-extension-kotlin} * library. @@ -207,6 +246,7 @@ default Scope makeCurrent() { * and then invokes the input {@link Runnable}. */ default Runnable wrap(Runnable runnable) { + Objects.requireNonNull(runnable, "runnable"); return () -> { try (Scope ignored = makeCurrent()) { runnable.run(); @@ -215,10 +255,11 @@ default Runnable wrap(Runnable runnable) { } /** - * Returns a {@link Runnable} that makes this the {@linkplain Context#current() current context} - * and then invokes the input {@link Runnable}. + * Returns a {@link Callable} that makes this the {@linkplain Context#current() current context} + * and then invokes the input {@link Callable}. */ default Callable wrap(Callable callable) { + Objects.requireNonNull(callable, "callable"); return () -> { try (Scope ignored = makeCurrent()) { return callable.call(); @@ -231,6 +272,7 @@ default Callable wrap(Callable callable) { * this the {@linkplain Context#current() current context} before each execution. */ default Executor wrap(Executor executor) { + Objects.requireNonNull(executor, "executor"); return command -> executor.execute(wrap(command)); } @@ -239,6 +281,10 @@ default Executor wrap(Executor executor) { * making this the {@linkplain Context#current() current context} before each execution. */ default ExecutorService wrap(ExecutorService executor) { + Objects.requireNonNull(executor, "executor"); + if (executor instanceof ContextExecutorService) { + return executor; + } return new ContextExecutorService(this, executor); } @@ -248,6 +294,10 @@ default ExecutorService wrap(ExecutorService executor) { * execution. */ default ScheduledExecutorService wrap(ScheduledExecutorService executor) { + Objects.requireNonNull(executor, "executor"); + if (executor instanceof ContextScheduledExecutorService) { + return executor; + } return new ContextScheduledExecutorService(this, executor); } @@ -256,6 +306,7 @@ default ScheduledExecutorService wrap(ScheduledExecutorService executor) { * and then invokes the input {@link Function}. */ default Function wrapFunction(Function function) { + Objects.requireNonNull(function, "function"); return t -> { try (Scope ignored = makeCurrent()) { return function.apply(t); @@ -268,6 +319,7 @@ default Function wrapFunction(Function function) { * and then invokes the input {@link BiFunction}. */ default BiFunction wrapFunction(BiFunction function) { + Objects.requireNonNull(function, "function"); return (t, u) -> { try (Scope ignored = makeCurrent()) { return function.apply(t, u); @@ -280,6 +332,7 @@ default BiFunction wrapFunction(BiFunction function) * and then invokes the input {@link Consumer}. */ default Consumer wrapConsumer(Consumer consumer) { + Objects.requireNonNull(consumer, "consumer"); return t -> { try (Scope ignored = makeCurrent()) { consumer.accept(t); @@ -292,6 +345,7 @@ default Consumer wrapConsumer(Consumer consumer) { * and then invokes the input {@link BiConsumer}. */ default BiConsumer wrapConsumer(BiConsumer consumer) { + Objects.requireNonNull(consumer, "consumer"); return (t, u) -> { try (Scope ignored = makeCurrent()) { consumer.accept(t, u); @@ -304,6 +358,7 @@ default BiConsumer wrapConsumer(BiConsumer consumer) { * and then invokes the input {@link Supplier}. */ default Supplier wrapSupplier(Supplier supplier) { + Objects.requireNonNull(supplier, "supplier"); return () -> { try (Scope ignored = makeCurrent()) { return supplier.get(); diff --git a/context/src/main/java/io/opentelemetry/context/ContextKey.java b/context/src/main/java/io/opentelemetry/context/ContextKey.java index 0b7aaf462b8..b7fbb179fb8 100644 --- a/context/src/main/java/io/opentelemetry/context/ContextKey.java +++ b/context/src/main/java/io/opentelemetry/context/ContextKey.java @@ -5,8 +5,10 @@ package io.opentelemetry.context; +import io.opentelemetry.common.impl.ApiUsageLogger; + /** - * Key for indexing values of type {@link T} stored in a {@link Context}. {@link ContextKey} are + * Key for indexing values of type {@code T} stored in a {@link Context}. {@link ContextKey} are * compared by reference, so it is expected that only one {@link ContextKey} is created for a * particular type of context value. * @@ -16,7 +18,7 @@ * private static final ContextKey KEY = ContextKey.named("MyState"); * * public Context startWork() { - * return Context.withValues(KEY, new MyState()); + * return Context.current().with(KEY, new MyState()); * } * * public void continueWork(Context context) { @@ -39,6 +41,10 @@ public interface ContextKey { * keys. */ static ContextKey named(String name) { + if (name == null) { + ApiUsageLogger.logNullParam(ContextKey.class, "named", "name"); + return new DefaultContextKey<>(""); + } return new DefaultContextKey<>(name); } } diff --git a/context/src/main/java/io/opentelemetry/context/ContextStorage.java b/context/src/main/java/io/opentelemetry/context/ContextStorage.java index 6a62f4be959..62458015c28 100644 --- a/context/src/main/java/io/opentelemetry/context/ContextStorage.java +++ b/context/src/main/java/io/opentelemetry/context/ContextStorage.java @@ -22,6 +22,7 @@ package io.opentelemetry.context; +import io.opentelemetry.common.impl.ApiUsageLogger; import java.util.function.Function; import javax.annotation.Nullable; @@ -33,31 +34,31 @@ * before {@link Context} is attached: * *

    {@code
    - * > public class MyStorage implements ContextStorageProvider {
    - * >
    - * >   @Override
    - * >   public ContextStorage get() {
    - * >     ContextStorage threadLocalStorage = ContextStorage.defaultStorage();
    - * >     return new RequestContextStorage() {
    - * >       @Override
    - * >       public Scope T attach(Context toAttach) {
    - * >         Context current = current();
    - * >         setMdc(toAttach);
    - * >         Scope scope = threadLocalStorage.attach(toAttach);
    - * >         return () -> {
    - * >           clearMdc();
    - * >           setMdc(current);
    - * >           scope.close();
    - * >         }
    - * >       }
    - * >
    - * >       @Override
    - * >       public Context current() {
    - * >         return threadLocalStorage.current();
    - * >       }
    - * >     }
    - * >   }
    - * > }
    + * public class MyStorage implements ContextStorageProvider {
    + *
    + *   @Override
    + *   public ContextStorage get() {
    + *     ContextStorage threadLocalStorage = ContextStorage.defaultStorage();
    + *     return new ContextStorage() {
    + *       @Override
    + *       public Scope attach(Context toAttach) {
    + *         Context current = current();
    + *         setMdc(toAttach);
    + *         Scope scope = threadLocalStorage.attach(toAttach);
    + *         return () -> {
    + *           clearMdc();
    + *           setMdc(current);
    + *           scope.close();
    + *         };
    + *       }
    + *
    + *       @Override
    + *       public Context current() {
    + *         return threadLocalStorage.current();
    + *       }
    + *     };
    + *   }
    + * }
      * }
    */ public interface ContextStorage { @@ -86,6 +87,10 @@ static ContextStorage defaultStorage() { * main class. */ static void addWrapper(Function wrapper) { + if (wrapper == null) { + ApiUsageLogger.logNullParam(ContextStorage.class, "addWrapper", "wrapper"); + return; + } ContextStorageWrappers.addWrapper(wrapper); } diff --git a/context/src/main/java/io/opentelemetry/context/ContextStorageProvider.java b/context/src/main/java/io/opentelemetry/context/ContextStorageProvider.java index 1c77bae0c50..cd5b7bc4e19 100644 --- a/context/src/main/java/io/opentelemetry/context/ContextStorageProvider.java +++ b/context/src/main/java/io/opentelemetry/context/ContextStorageProvider.java @@ -16,8 +16,8 @@ *

    {@code * com.linecorp.armeria.common.RequestContext}, {@code - * io.grpc.context.Context}, or {@code io.grpc.Context}, + * or {@code * org.eclipse.microprofile.context.ThreadContext} * diff --git a/context/src/main/java/io/opentelemetry/context/ContextStorageWrappers.java b/context/src/main/java/io/opentelemetry/context/ContextStorageWrappers.java index 9f8eb3276a1..faa05a66c0b 100644 --- a/context/src/main/java/io/opentelemetry/context/ContextStorageWrappers.java +++ b/context/src/main/java/io/opentelemetry/context/ContextStorageWrappers.java @@ -19,6 +19,7 @@ final class ContextStorageWrappers { private static final Logger log = Logger.getLogger(ContextStorageWrappers.class.getName()); + @SuppressWarnings("NonFinalStaticField") private static boolean storageInitialized; private static final List> wrappers = diff --git a/context/src/main/java/io/opentelemetry/context/CurrentContextExecutorService.java b/context/src/main/java/io/opentelemetry/context/CurrentContextExecutorService.java index 346b8498781..f3e5f3aa81b 100644 --- a/context/src/main/java/io/opentelemetry/context/CurrentContextExecutorService.java +++ b/context/src/main/java/io/opentelemetry/context/CurrentContextExecutorService.java @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -final class CurrentContextExecutorService extends ForwardingExecutorService { +class CurrentContextExecutorService extends ForwardingExecutorService { CurrentContextExecutorService(ExecutorService delegate) { super(delegate); diff --git a/context/src/main/java/io/opentelemetry/context/CurrentContextScheduledExecutorService.java b/context/src/main/java/io/opentelemetry/context/CurrentContextScheduledExecutorService.java new file mode 100644 index 00000000000..f32b1faf2a8 --- /dev/null +++ b/context/src/main/java/io/opentelemetry/context/CurrentContextScheduledExecutorService.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.context; + +import java.util.concurrent.Callable; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +final class CurrentContextScheduledExecutorService extends CurrentContextExecutorService + implements ScheduledExecutorService { + + private final ScheduledExecutorService delegate; + + CurrentContextScheduledExecutorService(ScheduledExecutorService delegate) { + super(delegate); + this.delegate = delegate; + } + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + return delegate.schedule(Context.current().wrap(command), delay, unit); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + return delegate.schedule(Context.current().wrap(callable), delay, unit); + } + + @Override + public ScheduledFuture scheduleAtFixedRate( + Runnable command, long initialDelay, long period, TimeUnit unit) { + return delegate.scheduleAtFixedRate(command, initialDelay, period, unit); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay( + Runnable command, long initialDelay, long delay, TimeUnit unit) { + return delegate.scheduleWithFixedDelay(command, initialDelay, delay, unit); + } +} diff --git a/context/src/main/java/io/opentelemetry/context/ImplicitContextKeyed.java b/context/src/main/java/io/opentelemetry/context/ImplicitContextKeyed.java index 48eccfd77b1..327f90c8d11 100644 --- a/context/src/main/java/io/opentelemetry/context/ImplicitContextKeyed.java +++ b/context/src/main/java/io/opentelemetry/context/ImplicitContextKeyed.java @@ -23,7 +23,7 @@ public interface ImplicitContextKeyed { *

    This method is equivalent to {@code Context.current().with(value).makeCurrent()}. * *

    The default implementation of this method will store the {@link ImplicitContextKeyed} in a - * {@link ThreadLocal}. Kotlin coroutine users SHOULD NOT use this method as the {@link + * {@link ThreadLocal}. Kotlin coroutine users should not use this method as the {@link * ThreadLocal} will not be properly synced across coroutine suspension and resumption. Instead, * use {@code withContext(value.asContextElement())} provided by the {@code * opentelemetry-extension-kotlin} library. diff --git a/context/src/main/java/io/opentelemetry/context/LazyStorage.java b/context/src/main/java/io/opentelemetry/context/LazyStorage.java index 12ec85043df..428b87dc481 100644 --- a/context/src/main/java/io/opentelemetry/context/LazyStorage.java +++ b/context/src/main/java/io/opentelemetry/context/LazyStorage.java @@ -37,9 +37,9 @@ package io.opentelemetry.context; +import io.opentelemetry.common.ComponentLoader; import java.util.ArrayList; import java.util.List; -import java.util.ServiceLoader; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.logging.Level; @@ -103,8 +103,10 @@ static ContextStorage createStorage(AtomicReference deferredStorageFa return ContextStorage.defaultStorage(); } + ComponentLoader componentLoader = + ComponentLoader.forClassLoader(LazyStorage.class.getClassLoader()); List providers = new ArrayList<>(); - for (ContextStorageProvider provider : ServiceLoader.load(ContextStorageProvider.class)) { + for (ContextStorageProvider provider : componentLoader.load(ContextStorageProvider.class)) { if (provider .getClass() .getName() @@ -127,7 +129,8 @@ static ContextStorage createStorage(AtomicReference deferredStorageFa deferredStorageFailure.set( new IllegalStateException( "Found multiple ContextStorageProvider. Set the " - + "io.opentelemetry.context.ContextStorageProvider property to the fully " + + CONTEXT_STORAGE_PROVIDER_PROPERTY + + " property to the fully " + "qualified class name of the provider to use. Falling back to default " + "ContextStorage. Found providers: " + providers)); @@ -142,7 +145,8 @@ static ContextStorage createStorage(AtomicReference deferredStorageFa deferredStorageFailure.set( new IllegalStateException( - "io.opentelemetry.context.ContextStorageProvider property set but no matching class " + CONTEXT_STORAGE_PROVIDER_PROPERTY + + " property set but no matching class " + "could be found, requested: " + providerClassName + " but found providers: " diff --git a/context/src/main/java/io/opentelemetry/context/StrictContextStorage.java b/context/src/main/java/io/opentelemetry/context/StrictContextStorage.java index b02d33b4aea..1d2d2c46866 100644 --- a/context/src/main/java/io/opentelemetry/context/StrictContextStorage.java +++ b/context/src/main/java/io/opentelemetry/context/StrictContextStorage.java @@ -22,7 +22,9 @@ import static java.lang.Thread.currentThread; +import io.opentelemetry.common.impl.ApiUsageLogger; import io.opentelemetry.context.internal.shaded.WeakConcurrentMap; +import java.lang.ref.Reference; import java.util.Arrays; import java.util.List; import java.util.concurrent.ConcurrentHashMap; @@ -62,6 +64,11 @@ private StrictContextStorage(ContextStorage delegate) { @Override public Scope attach(Context context) { + if (context == null) { + ApiUsageLogger.logNullParam(ContextStorage.class, "attach", "context"); + return Scope.noop(); + } + Scope scope = delegate.attach(context); CallerStackTrace caller = new CallerStackTrace(context); @@ -124,7 +131,7 @@ public Context current() { * *

    Note: It is important to close all resources prior to calling this, so that * in-flight operations are not mistaken as scope leaks. If this raises an error, consider if a - * {@linkplain Context#wrap(Executor)} wrapped executor} is still running. + * {@linkplain Context#wrap(Executor) wrapped executor} is still running. * * @throws AssertionError if any scopes were left unclosed. */ @@ -179,7 +186,8 @@ public void close() { maybeResumeWithFrameIndex = i + 3; } } - if (stackTrace[maybeResumeWithFrameIndex].getMethodName().equals("invokeSuspend")) { + if (maybeResumeWithFrameIndex < stackTrace.length + && stackTrace[maybeResumeWithFrameIndex].getMethodName().equals("invokeSuspend")) { // Skip synthetic invokeSuspend function. // NB: The stacktrace showed in an IntelliJ debug pane does not show this. maybeResumeWithFrameIndex++; @@ -251,6 +259,7 @@ static PendingScopes create() { thread.setName("weak-ref-cleaner-strictcontextstorage"); thread.setPriority(Thread.MIN_PRIORITY); thread.setDaemon(true); + thread.setContextClassLoader(null); thread.start(); } @@ -266,7 +275,9 @@ List drainPendingCallers() { public void run() { try { while (!Thread.interrupted()) { - CallerStackTrace caller = map.remove(remove()); + Reference reference = remove(); + // on openj9 ReferenceQueue.remove can return null + CallerStackTrace caller = reference != null ? map.remove(reference) : null; if (caller != null && !caller.closed) { logger.log( Level.SEVERE, "Scope garbage collected before being closed.", callerError(caller)); diff --git a/context/src/main/java/io/opentelemetry/context/ThreadLocalContextStorage.java b/context/src/main/java/io/opentelemetry/context/ThreadLocalContextStorage.java index 92f24849a29..784f6ba6eaa 100644 --- a/context/src/main/java/io/opentelemetry/context/ThreadLocalContextStorage.java +++ b/context/src/main/java/io/opentelemetry/context/ThreadLocalContextStorage.java @@ -17,6 +17,7 @@ enum ThreadLocalContextStorage implements ContextStorage { private static final ThreadLocal THREAD_LOCAL_STORAGE = new ThreadLocal<>(); @Override + @SuppressWarnings("ReferenceEquality") public Scope attach(Context toAttach) { if (toAttach == null) { // Null context not allowed so ignore it. @@ -30,14 +31,31 @@ public Scope attach(Context toAttach) { THREAD_LOCAL_STORAGE.set(toAttach); - return () -> { - if (current() != toAttach) { + return new ScopeImpl(beforeAttach, toAttach); + } + + private class ScopeImpl implements Scope { + @Nullable private final Context beforeAttach; + private final Context toAttach; + private boolean closed; + + private ScopeImpl(@Nullable Context beforeAttach, Context toAttach) { + this.beforeAttach = beforeAttach; + this.toAttach = toAttach; + } + + @Override + @SuppressWarnings("ReferenceEquality") + public void close() { + if (!closed && current() == toAttach) { + closed = true; + THREAD_LOCAL_STORAGE.set(beforeAttach); + } else { logger.log( Level.FINE, - "Context in storage not the expected context, Scope.close was not called correctly"); + " Trying to close scope which does not represent current context. Ignoring the call."); } - THREAD_LOCAL_STORAGE.set(beforeAttach); - }; + } } @Override diff --git a/context/src/main/java/io/opentelemetry/context/internal/shaded/AbstractWeakConcurrentMap.java b/context/src/main/java/io/opentelemetry/context/internal/shaded/AbstractWeakConcurrentMap.java index 88335d9e0e8..fd6569cf937 100644 --- a/context/src/main/java/io/opentelemetry/context/internal/shaded/AbstractWeakConcurrentMap.java +++ b/context/src/main/java/io/opentelemetry/context/internal/shaded/AbstractWeakConcurrentMap.java @@ -58,7 +58,9 @@ protected AbstractWeakConcurrentMap() { this(new ConcurrentHashMap, V>()); } - /** @param target ConcurrentMap implementation that this class wraps. */ + /** + * @param target ConcurrentMap implementation that this class wraps. + */ protected AbstractWeakConcurrentMap(ConcurrentMap, V> target) { this.target = target; } diff --git a/context/src/main/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMap.java b/context/src/main/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMap.java index de6502d8798..2580e0c8249 100644 --- a/context/src/main/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMap.java +++ b/context/src/main/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMap.java @@ -73,7 +73,9 @@ protected LookupKey initialValue() { private final boolean reuseKeys; - /** @param cleanerThread {@code true} if a thread should be started that removes stale entries. */ + /** + * @param cleanerThread {@code true} if a thread should be started that removes stale entries. + */ public WeakConcurrentMap(boolean cleanerThread) { this(cleanerThread, isPersistentClassLoader(LookupKey.class.getClassLoader())); } @@ -149,7 +151,9 @@ protected void resetLookupKey(LookupKey lookupKey) { lookupKey.reset(); } - /** @return The cleaner thread or {@code null} if no such thread was set. */ + /** + * @return The cleaner thread or {@code null} if no such thread was set. + */ public Thread getCleanerThread() { return thread; } diff --git a/context/src/main/java/io/opentelemetry/context/propagation/ContextPropagators.java b/context/src/main/java/io/opentelemetry/context/propagation/ContextPropagators.java index 7031227bdc6..230327e7f1e 100644 --- a/context/src/main/java/io/opentelemetry/context/propagation/ContextPropagators.java +++ b/context/src/main/java/io/opentelemetry/context/propagation/ContextPropagators.java @@ -30,8 +30,8 @@ * // Inject the span's SpanContext and other available concerns (such as correlations) * // contained in the specified Context. * Map map = new HashMap<>(); - * textMapPropagator.inject(Context.current(), map, new Setter() { - * public void put(Map map, String key, String value) { + * textMapPropagator.inject(Context.current(), map, new TextMapSetter>() { + * public void set(Map map, String key, String value) { * map.put(key, value); * } * }); @@ -50,10 +50,13 @@ * * // Extract and store the propagated span's SpanContext and other available concerns * // in the specified Context. - * Context context = textMapPropagator.extract(Context.current(), request, - * new Getter() { - * public String get(Object request, String key) { - * // Return the value associated to the key, if available. + * Context context = textMapPropagator.extract(Context.current(), headers, + * new TextMapGetter>() { + * public Iterable keys(Map carrier) { + * return carrier.keySet(); + * } + * public String get(Map carrier, String key) { + * return carrier.get(key); * } * } * ); @@ -80,7 +83,7 @@ public interface ContextPropagators { *

    {@code
        * ContextPropagators propagators = ContextPropagators.create(
        *   TextMapPropagator.composite(
    -   *     HttpTraceContext.getInstance(),
    +   *     W3CTraceContextPropagator.getInstance(),
        *     W3CBaggagePropagator.getInstance(),
        *     new MyCustomContextPropagator()));
        * }
    diff --git a/context/src/main/java/io/opentelemetry/context/propagation/DefaultContextPropagators.java b/context/src/main/java/io/opentelemetry/context/propagation/DefaultContextPropagators.java index 28e41ed9893..dd1b8983891 100644 --- a/context/src/main/java/io/opentelemetry/context/propagation/DefaultContextPropagators.java +++ b/context/src/main/java/io/opentelemetry/context/propagation/DefaultContextPropagators.java @@ -33,4 +33,9 @@ public TextMapPropagator getTextMapPropagator() { DefaultContextPropagators(TextMapPropagator textMapPropagator) { this.textMapPropagator = textMapPropagator; } + + @Override + public String toString() { + return "DefaultContextPropagators{textMapPropagator=" + textMapPropagator + "}"; + } } diff --git a/context/src/main/java/io/opentelemetry/context/propagation/MultiTextMapPropagator.java b/context/src/main/java/io/opentelemetry/context/propagation/MultiTextMapPropagator.java index ce2cecb165c..cee960af923 100644 --- a/context/src/main/java/io/opentelemetry/context/propagation/MultiTextMapPropagator.java +++ b/context/src/main/java/io/opentelemetry/context/propagation/MultiTextMapPropagator.java @@ -16,17 +16,17 @@ import javax.annotation.Nullable; final class MultiTextMapPropagator implements TextMapPropagator { - private final TextMapPropagator[] textPropagators; + private final TextMapPropagator[] textMapPropagators; private final Collection allFields; - MultiTextMapPropagator(TextMapPropagator... textPropagators) { - this(Arrays.asList(textPropagators)); + MultiTextMapPropagator(TextMapPropagator... textMapPropagators) { + this(Arrays.asList(textMapPropagators)); } - MultiTextMapPropagator(List textPropagators) { - this.textPropagators = new TextMapPropagator[textPropagators.size()]; - textPropagators.toArray(this.textPropagators); - this.allFields = Collections.unmodifiableList(getAllFields(this.textPropagators)); + MultiTextMapPropagator(List textMapPropagators) { + this.textMapPropagators = new TextMapPropagator[textMapPropagators.size()]; + textMapPropagators.toArray(this.textMapPropagators); + this.allFields = Collections.unmodifiableList(getAllFields(this.textMapPropagators)); } @Override @@ -48,7 +48,7 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se if (context == null || setter == null) { return; } - for (TextMapPropagator textPropagator : textPropagators) { + for (TextMapPropagator textPropagator : textMapPropagators) { textPropagator.inject(context, carrier, setter); } } @@ -61,9 +61,14 @@ public Context extract(Context context, @Nullable C carrier, TextMapGetter carrier of propagation fields, such as an http request. */ +@FunctionalInterface public interface TextMapGetter { /** * Returns all the keys in the given carrier. * + *

    The default implementation returns an empty iterable. + * * @param carrier carrier of propagation fields, such as an http request. + * @deprecated Use {@link #get(Object, String)} or {@link #getAll(Object, String)} to read known + * propagation fields instead. Enumerating all keys is discouraged. * @since 0.10.0 */ - Iterable keys(C carrier); + @Deprecated + default Iterable keys(C carrier) { + return Collections.emptyList(); + } /** * Returns the first value of the given propagation {@code key} or returns {@code null}. @@ -33,4 +43,24 @@ public interface TextMapGetter { */ @Nullable String get(@Nullable C carrier, String key); + + /** + * If implemented, returns all values for a given {@code key} in order, or returns an empty list. + * + *

    The default method returns the first value of the given propagation {@code key} as a + * singleton list, or returns an empty list. + * + * @param carrier carrier of propagation fields, such as an http request. + * @param key the key of the field. + * @return all values for a given {@code key} in order, or returns an empty list. Default method + * wraps {@code get()} as an {@link Iterator}. + * @since 1.50.0 + */ + default Iterator getAll(@Nullable C carrier, String key) { + String first = get(carrier, key); + if (first == null) { + return Collections.emptyIterator(); + } + return Collections.singleton(first).iterator(); + } } diff --git a/context/src/main/java/io/opentelemetry/context/propagation/TextMapPropagator.java b/context/src/main/java/io/opentelemetry/context/propagation/TextMapPropagator.java index 8505d9a49a5..8b3b83c5d75 100644 --- a/context/src/main/java/io/opentelemetry/context/propagation/TextMapPropagator.java +++ b/context/src/main/java/io/opentelemetry/context/propagation/TextMapPropagator.java @@ -24,18 +24,24 @@ * *

    Specific concern values (traces, correlations, etc) will be read from the specified {@code * Context}, and resulting values will be stored in a new {@code Context} upon extraction. It is - * recommended to use a single {@code Context.Key} to store the entire concern data: + * recommended to use a single {@code ContextKey} to store the entire concern data: * *

    {@code
    - * public static final Context.Key CONCERN_KEY = Context.key("my-concern-key");
    - * public MyConcernPropagator implements TextMapPropagator {
    - *   public  void inject(Context context, C carrier, Setter setter) {
    - *     Object concern = CONCERN_KEY.get(context);
    + * public class MyConcernPropagator implements TextMapPropagator {
    + *   private static final ContextKey CONCERN_KEY = ContextKey.named("my-concern-key");
    + *
    + *   public Collection fields() {
    + *     return Collections.singletonList("my-concern-header");
    + *   }
    + *
    + *   public  void inject(Context context, C carrier, TextMapSetter setter) {
    + *     Object concern = context.get(CONCERN_KEY);
      *     // Use concern in the specified context to propagate data.
      *   }
    - *   public  Context extract(Context context, C carrier, Getter getter) {
    - *     // Use getter to get the data from the carrier.
    - *     return context.withValue(CONCERN_KEY, concern);
    + *
    + *   public  Context extract(Context context, C carrier, TextMapGetter getter) {
    + *     Object concern = getter.get(carrier, "my-concern-header");
    + *     return context.with(CONCERN_KEY, concern);
      *   }
      * }
      * }
    @@ -82,7 +88,7 @@ static TextMapPropagator noop() {
     
       /**
        * The propagation fields defined. If your carrier is reused, you should delete the fields here
    -   * before calling {@link #inject(Context, Object, TextMapSetter)} )}.
    +   * before calling {@link #inject(Context, Object, TextMapSetter)}.
        *
        * 

    For example, if the carrier is a single-use or immutable request object, you don't need to * clear fields as they couldn't have been set before. If it is a mutable, retryable object, diff --git a/context/src/main/java/io/opentelemetry/context/propagation/internal/ExtendedTextMapGetter.java b/context/src/main/java/io/opentelemetry/context/propagation/internal/ExtendedTextMapGetter.java new file mode 100644 index 00000000000..22df25b3fa9 --- /dev/null +++ b/context/src/main/java/io/opentelemetry/context/propagation/internal/ExtendedTextMapGetter.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.context.propagation.internal; + +import io.opentelemetry.context.propagation.TextMapGetter; + +/** + * Extended {@link TextMapGetter} with experimental APIs. + * + *

    This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public interface ExtendedTextMapGetter extends TextMapGetter { + + // keep this class even if it is empty, since experimental methods may be added in the future. + +} diff --git a/context/src/otelAsBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java b/context/src/otelAsBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java index 416176aa56d..7bc42667374 100644 --- a/context/src/otelAsBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java +++ b/context/src/otelAsBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java @@ -63,6 +63,7 @@ private static class BraveContextValues { this.values = values; } + @SuppressWarnings("ReferenceEquality") Object getValue(Object key) { for (int i = 0; i < values.length; i += 2) { if (values[i] == key) { @@ -72,6 +73,7 @@ Object getValue(Object key) { return null; } + @SuppressWarnings("ReferenceEquality") BraveContextValues with(Object key, Object value) { Object[] copy; for (int i = 0; i < values.length; i += 2) { diff --git a/context/src/otelAsBraveTest/java/io/opentelemetry/context/OtelAsBraveTest.java b/context/src/otelAsBraveTest/java/io/opentelemetry/context/OtelAsBraveTest.java index 6acad3d0e7b..f3498727995 100644 --- a/context/src/otelAsBraveTest/java/io/opentelemetry/context/OtelAsBraveTest.java +++ b/context/src/otelAsBraveTest/java/io/opentelemetry/context/OtelAsBraveTest.java @@ -27,6 +27,7 @@ class OtelAsBraveTest { private static final TraceContext TRACE_CONTEXT = TraceContext.newBuilder().traceId(1).spanId(1).addExtra("japan").build(); + @SuppressWarnings("NonFinalStaticField") private static ExecutorService otherThread; @BeforeAll diff --git a/context/src/otelInBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java b/context/src/otelInBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java index e138c6a714d..ed1f5a7bf9a 100644 --- a/context/src/otelInBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java +++ b/context/src/otelInBraveTest/java/io/opentelemetry/context/BraveContextStorageProvider.java @@ -74,6 +74,7 @@ static final class BraveContextWrapper implements Context { this.delegate = delegate; } + @SuppressWarnings("ReferenceEquality") TraceContext toBraveContext() { if (fromBraveContext(baseBraveContext) == delegate) { return baseBraveContext; diff --git a/context/src/otelInBraveTest/java/io/opentelemetry/context/OtelInBraveTest.java b/context/src/otelInBraveTest/java/io/opentelemetry/context/OtelInBraveTest.java index 72a8b402acf..232cb0c4755 100644 --- a/context/src/otelInBraveTest/java/io/opentelemetry/context/OtelInBraveTest.java +++ b/context/src/otelInBraveTest/java/io/opentelemetry/context/OtelInBraveTest.java @@ -28,6 +28,7 @@ class OtelInBraveTest { BraveContextStorageProvider.toBraveContext( TraceContext.newBuilder().traceId(1).spanId(1).build(), CONTEXT_WITH_ANIMAL); + @SuppressWarnings("NonFinalStaticField") private static ExecutorService otherThread; @BeforeAll diff --git a/context/src/otelInGrpcTest/java/io/opentelemetry/context/GrpcContextStorageProvider.java b/context/src/otelInGrpcTest/java/io/opentelemetry/context/GrpcContextStorageProvider.java index 828b90fb391..1fbfbb24c6e 100644 --- a/context/src/otelInGrpcTest/java/io/opentelemetry/context/GrpcContextStorageProvider.java +++ b/context/src/otelInGrpcTest/java/io/opentelemetry/context/GrpcContextStorageProvider.java @@ -18,6 +18,7 @@ private enum GrpcContextStorage implements ContextStorage { INSTANCE; @Override + @SuppressWarnings("ReferenceEquality") public Scope attach(Context toAttach) { io.grpc.Context grpcContext = io.grpc.Context.current(); Context current = OTEL_CONTEXT.get(grpcContext); @@ -71,6 +72,7 @@ private static GrpcContextWrapper wrapperFromGrpc(io.grpc.Context grpcContext) { return new GrpcContextWrapper(grpcContext, OTEL_CONTEXT.get(grpcContext)); } + @SuppressWarnings("ReferenceEquality") private io.grpc.Context toGrpcContext() { if (OTEL_CONTEXT.get(baseGrpcContext) == context) { // No changes to the wrapper diff --git a/context/src/otelInGrpcTest/java/io/opentelemetry/context/OtelInGrpcTest.java b/context/src/otelInGrpcTest/java/io/opentelemetry/context/OtelInGrpcTest.java index 6b5cf16dabb..6024100b986 100644 --- a/context/src/otelInGrpcTest/java/io/opentelemetry/context/OtelInGrpcTest.java +++ b/context/src/otelInGrpcTest/java/io/opentelemetry/context/OtelInGrpcTest.java @@ -21,6 +21,7 @@ class OtelInGrpcTest { private static final io.grpc.Context.Key FOOD = io.grpc.Context.key("food"); private static final io.grpc.Context.Key COUNTRY = io.grpc.Context.key("country"); + @SuppressWarnings("NonFinalStaticField") private static ExecutorService otherThread; @BeforeAll diff --git a/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java b/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java index 262edb84150..7d68d975978 100644 --- a/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java +++ b/context/src/strictContextEnabledTest/java/io/opentelemetry/context/StrictContextStorageTest.java @@ -120,14 +120,13 @@ void scope_close_onWrongThread(Supplier method, String methodName) throws AtomicReference errorCatcher = new AtomicReference<>(); Thread t2 = - new Thread( - () -> { - try { - closeable.get().close(); - } catch (Throwable t) { - errorCatcher.set(t); - } - }); + new Thread(() -> { + try { + closeable.get().close(); + } catch (Throwable t) { + errorCatcher.set(t); + } + }); t2.setName("t2"); t2.start(); t2.join(); @@ -135,10 +134,9 @@ void scope_close_onWrongThread(Supplier method, String methodName) throws assertThat(errorCatcher.get()) .isInstanceOf(IllegalStateException.class) .hasMessage("Thread [t1] opened scope, but thread [t2] closed it") - .satisfies( - e -> - assertThat(e.getCause().getMessage()) - .matches("Thread \\[t1\\] opened scope for .* here:")); + .satisfies(e -> + assertThat(e.getCause().getMessage()) + .matches("Thread \\[t1\\] opened scope for .* here:")); } @SuppressWarnings("ReturnValueIgnored") @@ -175,14 +173,12 @@ void garbageCollectedScope() { await() .atMost(Duration.ofSeconds(30)) - .untilAsserted( - () -> { - System.gc(); - LoggingEvent log = - logs.assertContains("Scope garbage collected before being closed."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - assertThat(log.getThrowable().getMessage()) - .matches("Thread \\[Test worker\\] opened a scope of .* here:"); - }); + .untilAsserted(() -> { + System.gc(); + LoggingEvent log = logs.assertContains("Scope garbage collected before being closed."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + assertThat(log.getThrowable().getMessage()) + .matches("Thread \\[Test worker\\] opened a scope of .* here:"); + }); } } diff --git a/context/src/test/java/io/opentelemetry/context/ContextTest.java b/context/src/test/java/io/opentelemetry/context/ContextTest.java index 2ee5e01ab18..0f671dade48 100644 --- a/context/src/test/java/io/opentelemetry/context/ContextTest.java +++ b/context/src/test/java/io/opentelemetry/context/ContextTest.java @@ -7,8 +7,12 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -28,6 +32,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.LongAdder; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; @@ -104,6 +109,12 @@ void attachSameTwice() { assertThat(Context.current().get(ANIMAL)).isNull(); } + @Test + void keyEqualityIsInstanceCheck() { + Context context = Context.current().with(ContextKey.named("animal"), "cat"); + assertNull(context.get(ContextKey.named("animal"))); // yup + } + @Test void newThreadStartsWithRoot() throws Exception { Context context = Context.current().with(ANIMAL, "cat"); @@ -118,7 +129,7 @@ void newThreadStartsWithRoot() throws Exception { } @Test - public void closingScopeWhenNotActiveIsLogged() { + void closingScopeWhenNotActiveIsNoopAndLogged() { Context initial = Context.current(); Context context = initial.with(ANIMAL, "cat"); try (Scope scope = context.makeCurrent()) { @@ -126,13 +137,34 @@ public void closingScopeWhenNotActiveIsLogged() { try (Scope ignored = context2.makeCurrent()) { assertThat(Context.current().get(ANIMAL)).isEqualTo("dog"); scope.close(); + assertThat(Context.current().get(ANIMAL)).isEqualTo("dog"); } } assertThat(Context.current()).isEqualTo(initial); - LoggingEvent log = logs.assertContains("Context in storage not the expected context"); + LoggingEvent log = + logs.assertContains("Trying to close scope which does not represent current context"); assertThat(log.getLevel()).isEqualTo(Level.DEBUG); } + @SuppressWarnings("MustBeClosedChecker") + @Test + void closeScopeIsIdempotent() { + Context initial = Context.current(); + Context context1 = Context.root().with(ANIMAL, "cat"); + Scope scope1 = context1.makeCurrent(); + Context context2 = context1.with(ANIMAL, "dog"); + Scope scope2 = context2.makeCurrent(); + + scope2.close(); + assertThat(Context.current()).isEqualTo(context1); + + scope1.close(); + assertThat(Context.current()).isEqualTo(initial); + + scope2.close(); + assertThat(Context.current()).isEqualTo(initial); + } + @Test void withValues() { Context context1 = Context.current().with(ANIMAL, "cat"); @@ -167,11 +199,10 @@ void withValues() { assertThat(context5).isSameAs(context4); String dog = new String("dog"); - assertThat(dog).isEqualTo("dog"); - assertThat(dog).isNotSameAs("dog"); + assertThat(dog).isEqualTo("dog").isNotSameAs("dog"); Context context6 = context5.with(ANIMAL, dog); assertThat(context6.get(ANIMAL)).isEqualTo("dog"); - // We reuse context object when values match by reference, not value. + // We reuse the context object when values match by reference, not value. assertThat(context6).isNotSameAs(context5); } @@ -213,7 +244,7 @@ void wrapCallable() throws Exception { void wrapFunction() { AtomicReference value = new AtomicReference<>(); Function callback = - (a) -> { + a -> { value.set(Context.current().get(ANIMAL)); return "foo"; }; @@ -252,7 +283,7 @@ void wrapConsumer() { AtomicReference value = new AtomicReference<>(); AtomicBoolean consumed = new AtomicBoolean(); Consumer callback = - (a) -> { + a -> { value.set(Context.current().get(ANIMAL)); consumed.set(true); }; @@ -337,11 +368,29 @@ void wrapExecutor() { } } + @Test + void wrapExecutorService() { + // given + ExecutorService executorService = Executors.newSingleThreadExecutor(); + + // when + ExecutorService firstWrap = CAT.wrap(executorService); + ExecutorService secondWrap = CAT.wrap(firstWrap); + + // then + assertThat(firstWrap).isInstanceOf(ContextExecutorService.class); + assertThat(((ContextExecutorService) firstWrap).context()).isEqualTo(CAT); + assertThat(((ContextExecutorService) firstWrap).delegate()).isEqualTo(executorService); + assertThat(secondWrap).isInstanceOf(ContextExecutorService.class); + assertThat(((ContextExecutorService) secondWrap).context()).isEqualTo(CAT); + assertThat(((ContextExecutorService) secondWrap).delegate()).isEqualTo(executorService); + } + @Nested @TestInstance(Lifecycle.PER_CLASS) class WrapExecutorService { - protected ScheduledExecutorService executor; + protected ExecutorService executor; protected ExecutorService wrapped; protected AtomicReference value; @@ -480,6 +529,221 @@ void invokeAnyTimeout() throws Exception { } } + @Test + void wrapScheduledExecutorService() { + // given + ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); + + // when + ScheduledExecutorService firstWrap = CAT.wrap(executorService); + ScheduledExecutorService secondWrap = CAT.wrap(firstWrap); + + // then + assertThat(firstWrap).isInstanceOf(ContextScheduledExecutorService.class); + assertThat(((ContextScheduledExecutorService) firstWrap).context()).isEqualTo(CAT); + assertThat(((ContextScheduledExecutorService) firstWrap).delegate()).isEqualTo(executorService); + assertThat(secondWrap).isInstanceOf(ContextScheduledExecutorService.class); + assertThat(((ContextScheduledExecutorService) secondWrap).context()).isEqualTo(CAT); + assertThat(((ContextScheduledExecutorService) secondWrap).delegate()) + .isEqualTo(executorService); + } + + @Nested + @TestInstance(Lifecycle.PER_CLASS) + class WrapScheduledExecutorService { + + protected ScheduledExecutorService executor; + protected ScheduledExecutorService wrapped; + protected AtomicReference value; + + protected ScheduledExecutorService wrap(ScheduledExecutorService executorService) { + return CAT.wrap(executorService); + } + + @BeforeAll + void initExecutor() { + executor = Executors.newSingleThreadScheduledExecutor(); + wrapped = wrap(executor); + } + + @AfterAll + void stopExecutor() { + executor.shutdown(); + } + + @BeforeEach + void setUp() { + value = new AtomicReference<>(); + } + + @Test + void execute() { + Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); + wrapped.execute(runnable); + await().untilAsserted(() -> assertThat(value).hasValue("cat")); + } + + @Test + void submitRunnable() { + Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); + Futures.getUnchecked(wrapped.submit(runnable)); + assertThat(value).hasValue("cat"); + } + + @Test + void submitRunnableResult() { + Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); + assertThat(Futures.getUnchecked(wrapped.submit(runnable, "foo"))).isEqualTo("foo"); + assertThat(value).hasValue("cat"); + } + + @Test + void submitCallable() { + Callable callable = + () -> { + value.set(Context.current().get(ANIMAL)); + return "foo"; + }; + assertThat(Futures.getUnchecked(wrapped.submit(callable))).isEqualTo("foo"); + assertThat(value).hasValue("cat"); + } + + @Test + void invokeAll() throws Exception { + AtomicReference value1 = new AtomicReference<>(); + AtomicReference value2 = new AtomicReference<>(); + Callable callable1 = + () -> { + value1.set(Context.current().get(ANIMAL)); + return "foo"; + }; + Callable callable2 = + () -> { + value2.set(Context.current().get(ANIMAL)); + return "bar"; + }; + List> futures = wrapped.invokeAll(Arrays.asList(callable1, callable2)); + assertThat(futures.get(0).get()).isEqualTo("foo"); + assertThat(futures.get(1).get()).isEqualTo("bar"); + assertThat(value1).hasValue("cat"); + assertThat(value2).hasValue("cat"); + } + + @Test + void invokeAllTimeout() throws Exception { + AtomicReference value1 = new AtomicReference<>(); + AtomicReference value2 = new AtomicReference<>(); + Callable callable1 = + () -> { + value1.set(Context.current().get(ANIMAL)); + return "foo"; + }; + Callable callable2 = + () -> { + value2.set(Context.current().get(ANIMAL)); + return "bar"; + }; + List> futures = + wrapped.invokeAll(Arrays.asList(callable1, callable2), 10, TimeUnit.SECONDS); + assertThat(futures.get(0).get()).isEqualTo("foo"); + assertThat(futures.get(1).get()).isEqualTo("bar"); + assertThat(value1).hasValue("cat"); + assertThat(value2).hasValue("cat"); + } + + @Test + void invokeAny() throws Exception { + AtomicReference value1 = new AtomicReference<>(); + AtomicReference value2 = new AtomicReference<>(); + Callable callable1 = + () -> { + value1.set(Context.current().get(ANIMAL)); + throw new IllegalStateException("callable2 wins"); + }; + Callable callable2 = + () -> { + value2.set(Context.current().get(ANIMAL)); + return "bar"; + }; + assertThat(wrapped.invokeAny(Arrays.asList(callable1, callable2))).isEqualTo("bar"); + assertThat(value1).hasValue("cat"); + assertThat(value2).hasValue("cat"); + } + + @Test + void invokeAnyTimeout() throws Exception { + AtomicReference value1 = new AtomicReference<>(); + AtomicReference value2 = new AtomicReference<>(); + Callable callable1 = + () -> { + value1.set(Context.current().get(ANIMAL)); + throw new IllegalStateException("callable2 wins"); + }; + Callable callable2 = + () -> { + value2.set(Context.current().get(ANIMAL)); + return "bar"; + }; + assertThat(wrapped.invokeAny(Arrays.asList(callable1, callable2), 10, TimeUnit.SECONDS)) + .isEqualTo("bar"); + assertThat(value1).hasValue("cat"); + assertThat(value2).hasValue("cat"); + } + + @Test + void scheduleRunnable() { + Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); + assertThat(Futures.getUnchecked(wrapped.schedule(runnable, 1L, TimeUnit.MILLISECONDS))) + .isNull(); + assertThat(value).hasValue("cat"); + } + + @Test + void scheduleCallable() { + Callable callable = + () -> { + value.set(Context.current().get(ANIMAL)); + return "foo"; + }; + assertThat(Futures.getUnchecked(wrapped.schedule(callable, 1L, TimeUnit.MILLISECONDS))) + .isEqualTo("foo"); + assertThat(value).hasValue("cat"); + } + + @Test + void scheduleAtFixedRate() { + LongAdder longAdder = new LongAdder(); + Runnable runnable = longAdder::increment; + Future future = wrapped.scheduleAtFixedRate(runnable, 1L, 2L, TimeUnit.NANOSECONDS); + assertThat(future).isNotNull(); + await() + .await() + .untilAsserted(() -> { + if (!future.isCancelled()) { + future.cancel(true); + } + assertThat(longAdder.intValue()).isGreaterThan(1); + }); + assertThat(longAdder.intValue()).isGreaterThan(1); + } + + @Test + void scheduleWithFixedDelay() { + LongAdder longAdder = new LongAdder(); + Runnable runnable = longAdder::increment; + Future future = wrapped.scheduleWithFixedDelay(runnable, 1L, 2L, TimeUnit.NANOSECONDS); + assertThat(future).isNotNull(); + await() + .await() + .untilAsserted(() -> { + if (!future.isCancelled()) { + future.cancel(true); + } + assertThat(longAdder.intValue()).isGreaterThan(1); + }); + } + } + @Nested @TestInstance(Lifecycle.PER_CLASS) class CurrentContextWrappingExecutorService extends WrapExecutorService { @@ -504,9 +768,34 @@ void close() { } } + @Nested + @TestInstance(Lifecycle.PER_CLASS) + class CurrentContextWrappingScheduledExecutorService extends WrapScheduledExecutorService { + + @Override + protected ScheduledExecutorService wrap(ScheduledExecutorService executorService) { + return Context.taskWrapping(executorService); + } + + private Scope scope; + + @BeforeEach + // Closed in AfterEach + @SuppressWarnings("MustBeClosedChecker") + void makeCurrent() { + scope = CAT.makeCurrent(); + } + + @AfterEach + void close() { + scope.close(); + scope = null; + } + } + @Test void keyToString() { - assertThat(ANIMAL.toString()).isEqualTo("animal"); + assertThat(ANIMAL).hasToString("animal"); } @Test @@ -531,6 +820,7 @@ class DelegatesToExecutorService { @Test void delegatesCleanupMethods() throws Exception { ExecutorService wrapped = CAT.wrap(executor); + doNothing().when(executor).shutdown(); wrapped.shutdown(); verify(executor).shutdown(); verifyNoMoreInteractions(executor); @@ -552,57 +842,74 @@ void delegatesCleanupMethods() throws Exception { } } + // We test real context-related above but should test cleanup gets delegated, which is best with + // a mock. @Nested @TestInstance(Lifecycle.PER_CLASS) - class WrapScheduledExecutorService extends WrapExecutorService { + @SuppressWarnings("MockitoDoSetup") + class DelegatesToScheduledExecutorService { - private ScheduledExecutorService wrapScheduled; - - @BeforeEach - void wrapScheduled() { - wrapScheduled = CAT.wrap(executor); - } + @Mock private ScheduledExecutorService executor; + @Mock private ScheduledFuture scheduledFuture; @Test - void scheduleRunnable() throws Exception { - Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); - wrapScheduled.schedule(runnable, 0, TimeUnit.SECONDS).get(); - assertThat(value).hasValue("cat"); - } + void delegatesCleanupMethods() throws Exception { + ScheduledExecutorService wrapped = CAT.wrap(executor); - @Test - void scheduleCallable() throws Exception { - Callable callable = - () -> { - value.set(Context.current().get(ANIMAL)); - return "foo"; - }; - assertThat(wrapScheduled.schedule(callable, 0, TimeUnit.SECONDS).get()).isEqualTo("foo"); - assertThat(value).hasValue("cat"); - } + wrapped.shutdown(); + verify(executor).shutdown(); + verifyNoMoreInteractions(executor); - @Test - void scheduleAtFixedRate() { - Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); - ScheduledFuture future = - wrapScheduled.scheduleAtFixedRate(runnable, 0, 10, TimeUnit.SECONDS); - await().untilAsserted(() -> assertThat(value).hasValue("cat")); - future.cancel(true); - } + wrapped.shutdownNow(); + verify(executor).shutdownNow(); + verifyNoMoreInteractions(executor); - @Test - void scheduleWithFixedDelay() { - Runnable runnable = () -> value.set(Context.current().get(ANIMAL)); - ScheduledFuture future = - wrapScheduled.scheduleWithFixedDelay(runnable, 0, 10, TimeUnit.SECONDS); - await().untilAsserted(() -> assertThat(value).hasValue("cat")); - future.cancel(true); + when(executor.isShutdown()).thenReturn(true); + assertThat(wrapped.isShutdown()).isTrue(); + verify(executor).isShutdown(); + verifyNoMoreInteractions(executor); + + when(wrapped.isTerminated()).thenReturn(true); + assertThat(wrapped.isTerminated()).isTrue(); + verify(executor).isTerminated(); + verifyNoMoreInteractions(executor); + + when(executor.awaitTermination(anyLong(), any())).thenReturn(true); + assertThat(wrapped.awaitTermination(1L, TimeUnit.SECONDS)).isTrue(); + verify(executor).awaitTermination(1L, TimeUnit.SECONDS); + verifyNoMoreInteractions(executor); + + doReturn(scheduledFuture) + .when(executor) + .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + assertThat((Future) wrapped.schedule(() -> {}, 1L, TimeUnit.SECONDS)) + .isSameAs(scheduledFuture); + verify(executor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + verifyNoMoreInteractions(executor); + + doReturn(scheduledFuture) + .when(executor) + .scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); + assertThat((Future) wrapped.scheduleAtFixedRate(() -> {}, 1L, 1L, TimeUnit.SECONDS)) + .isSameAs(scheduledFuture); + verify(executor) + .scheduleAtFixedRate(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); + verifyNoMoreInteractions(executor); + + doReturn(scheduledFuture) + .when(executor) + .scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); + assertThat((Future) wrapped.scheduleWithFixedDelay(() -> {}, 1L, 1L, TimeUnit.SECONDS)) + .isSameAs(scheduledFuture); + verify(executor) + .scheduleWithFixedDelay(any(Runnable.class), anyLong(), anyLong(), any(TimeUnit.class)); + verifyNoMoreInteractions(executor); } } @Test void emptyContext() { - assertThat(Context.root().get(new HashCollidingKey())).isEqualTo(null); + assertThat(Context.root().get(new HashCollidingKey())).isNull(); } @Test @@ -625,6 +932,20 @@ void hashcodeCollidingKeys() { assertThat(twoKeys.get(cheese)).isEqualTo("whiz"); } + @Test + void doNotWrapExecutorService() { + ExecutorService executor = mock(CurrentContextExecutorService.class); + ExecutorService wrapped = Context.taskWrapping(executor); + assertThat(wrapped).isSameAs(executor); + } + + @Test + void doNotWrapScheduledExecutorService() { + ScheduledExecutorService executor = mock(CurrentContextScheduledExecutorService.class); + ScheduledExecutorService wrapped = Context.taskWrapping(executor); + assertThat(wrapped).isSameAs(executor); + } + @SuppressWarnings("HashCodeToString") private static class HashCollidingKey implements ContextKey { @Override diff --git a/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java b/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java index 3d635be779c..5319e689fe8 100644 --- a/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java +++ b/context/src/test/java/io/opentelemetry/context/internal/shaded/WeakConcurrentMapTest.java @@ -25,6 +25,7 @@ package io.opentelemetry.context.internal.shaded; +import static org.awaitility.Awaitility.await; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.nullValue; @@ -75,8 +76,7 @@ void testInternalThread() throws Exception { assertThat(map.getCleanerThread(), not(nullValue(Thread.class))); new MapTestCase(map).doTest(); map.getCleanerThread().interrupt(); - Thread.sleep(200L); - assertThat(map.getCleanerThread().isAlive(), is(false)); + await().untilAsserted(() -> assertThat(map.getCleanerThread().isAlive(), is(false))); } static class KeyEqualToWeakRefOfItself { @@ -152,8 +152,11 @@ void doTest() throws Exception { assertThat(values.isEmpty(), is(true)); key1 = key2 = null; // Make eligible for GC System.gc(); - Thread.sleep(200L); - triggerClean(); + await() + .untilAsserted(() -> { + triggerClean(); + assertThat(map.approximateSize(), is(2)); + }); assertThat(map.get(key3), is(value3)); assertThat(map.getIfPresent(key3), is(value3)); assertThat(map.get(key4), is(value4)); diff --git a/context/src/test/java/io/opentelemetry/context/propagation/MultiTextMapPropagatorTest.java b/context/src/test/java/io/opentelemetry/context/propagation/MultiTextMapPropagatorTest.java index 66e80bc95c3..6814373a875 100644 --- a/context/src/test/java/io/opentelemetry/context/propagation/MultiTextMapPropagatorTest.java +++ b/context/src/test/java/io/opentelemetry/context/propagation/MultiTextMapPropagatorTest.java @@ -6,7 +6,7 @@ package io.opentelemetry.context.propagation; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -51,9 +51,8 @@ public String get(Map carrier, String key) { @Test void addPropagator_null() { - assertThrows( - NullPointerException.class, - () -> new MultiTextMapPropagator((List) null)); + assertThatThrownBy(() -> new MultiTextMapPropagator((List) null)) + .isInstanceOf(NullPointerException.class); } @Test @@ -82,7 +81,7 @@ void fields_readOnly() { when(propagator2.fields()).thenReturn(Arrays.asList("buggy", "bumpers")); TextMapPropagator prop = new MultiTextMapPropagator(propagator1, propagator2); Collection fields = prop.fields(); - assertThrows(UnsupportedOperationException.class, () -> fields.add("hi")); + assertThatThrownBy(() -> fields.add("hi")).isInstanceOf(UnsupportedOperationException.class); } @Test @@ -168,4 +167,10 @@ void inject_nullSetter() { new MultiTextMapPropagator(propagator1, propagator2).inject(context, carrier, null); assertThat(carrier).isEmpty(); } + + @Test + void toString_Valid() { + assertThat(new MultiTextMapPropagator(propagator1, propagator2).toString()) + .isEqualTo("MultiTextMapPropagator{textMapPropagators=[propagator1, propagator2]}"); + } } diff --git a/context/src/test/java/io/opentelemetry/context/propagation/NoopTextMapPropagatorTest.java b/context/src/test/java/io/opentelemetry/context/propagation/NoopTextMapPropagatorTest.java index 4b5965df14e..261ae1a989a 100644 --- a/context/src/test/java/io/opentelemetry/context/propagation/NoopTextMapPropagatorTest.java +++ b/context/src/test/java/io/opentelemetry/context/propagation/NoopTextMapPropagatorTest.java @@ -63,6 +63,11 @@ void inject_nullSetter() { assertThat(carrier).isEmpty(); } + @Test + void toString_Valid() { + assertThat(TextMapPropagator.noop().toString()).isEqualTo("NoopTextMapPropagator"); + } + enum MapTextMapGetter implements TextMapGetter> { INSTANCE; diff --git a/context/src/test/java/io/opentelemetry/context/propagation/TextMapGetterTest.java b/context/src/test/java/io/opentelemetry/context/propagation/TextMapGetterTest.java new file mode 100644 index 00000000000..609d9937754 --- /dev/null +++ b/context/src/test/java/io/opentelemetry/context/propagation/TextMapGetterTest.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.context.propagation; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableList; +import io.opentelemetry.context.propagation.internal.ExtendedTextMapGetter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") +class TextMapGetterTest { + + final TextMapGetter nullGet = + new ExtendedTextMapGetter() { + @Override + public Iterable keys(Void carrier) { + return ImmutableList.of("key"); + } + + @Nullable + @Override + public String get(@Nullable Void carrier, String key) { + return null; + } + }; + + final TextMapGetter nonNullGet = + new ExtendedTextMapGetter() { + @Override + public Iterable keys(Void carrier) { + return ImmutableList.of("key"); + } + + @Override + public String get(@Nullable Void carrier, String key) { + return "123"; + } + }; + + @Test + void keysDefault_returnsEmpty() { + TextMapGetter getter = (carrier, key) -> "value"; + + assertThat(getter.keys(null)).isEmpty(); + } + + @Test + void keysOverrideIsPreserved() { + assertThat(nullGet.keys(null)).containsExactly("key"); + } + + @Test + void extendedTextMapGetterdefaultMethod_returnsEmpty() { + Iterator result = nullGet.getAll(null, "key"); + assertThat(result).isNotNull(); + List values = iterToList(result); + assertThat(values).isEqualTo(Collections.emptyList()); + } + + @Test + void extendedTextMapGetterdefaultMethod_returnsSingleVal() { + Iterator result = nonNullGet.getAll(null, "key"); + assertThat(result).isNotNull(); + List values = iterToList(result); + assertThat(values).isEqualTo(Collections.singletonList("123")); + } + + private static List iterToList(Iterator iter) { + List list = new ArrayList<>(); + while (iter.hasNext()) { + list.add(iter.next()); + } + return list; + } +} diff --git a/custom-checks/build.gradle.kts b/custom-checks/build.gradle.kts new file mode 100644 index 00000000000..d5a2cfc29f7 --- /dev/null +++ b/custom-checks/build.gradle.kts @@ -0,0 +1,88 @@ +plugins { + id("otel.java-conventions") +} + +dependencies { + compileOnly("com.google.errorprone:error_prone_core") + + testImplementation("com.google.errorprone:error_prone_test_helpers") +} + +otelJava.moduleName.set("io.opentelemetry.gradle.customchecks") +otelJava.requireSuppressWarningsExplanation.set(false) + +// We cannot use "--release" javac option here because that will forbid exporting com.sun.tools package. +// We also can't seem to use the toolchain without the "--release" option. So disable everything. + +java { + sourceCompatibility = JavaVersion.VERSION_21 + targetCompatibility = JavaVersion.VERSION_21 + toolchain { + languageVersion.set(null as JavaLanguageVersion?) + } +} + +tasks { + withType().configureEach { + with(options) { + release.set(null as Int?) + + compilerArgs.addAll( + listOf( + "--add-exports", + "jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED", + "--add-exports", + "jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED", + "--add-exports", + "jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED", + "--add-exports", + "jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED", + "--add-exports", + "jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED", + ), + ) + } + } + + // only test on java 21+ + val testJavaVersion = project.findProperty("testJavaVersion") as String? + if (testJavaVersion != null && Integer.valueOf(testJavaVersion) < 21) { + test { + enabled = false + } + } +} + +tasks.withType().configureEach { + // required when accessing javac internals + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED") + jvmArgs("--add-opens=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED") + jvmArgs("-XX:+IgnoreUnrecognizedVMOptions") +} + +tasks.withType().configureEach { + // using com.sun.tools.javac.api.JavacTrees breaks javadoc generation + enabled = false +} + +// Our conventions apply this project as a dependency in the errorprone configuration, which would cause +// a circular dependency if trying to compile this project with that still there. So we filter this +// project out. +configurations { + named("errorprone") { + dependencies.removeIf { + it is ProjectDependency && it.name == project.name + } + } +} + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false +} diff --git a/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelDeprecatedApiUsage.java b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelDeprecatedApiUsage.java new file mode 100644 index 00000000000..3489fc851de --- /dev/null +++ b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelDeprecatedApiUsage.java @@ -0,0 +1,189 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import static com.google.errorprone.BugPattern.LinkType.NONE; +import static com.google.errorprone.BugPattern.SeverityLevel.ERROR; + +import com.google.errorprone.BugPattern; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker; +import com.google.errorprone.matchers.Description; +import com.google.errorprone.util.ASTHelpers; +import com.sun.source.tree.IdentifierTree; +import com.sun.source.tree.ImportTree; +import com.sun.source.tree.MemberReferenceTree; +import com.sun.source.tree.MemberSelectTree; +import com.sun.source.tree.MethodInvocationTree; +import com.sun.source.tree.NewClassTree; +import com.sun.source.tree.Tree; +import com.sun.tools.javac.code.Symbol; +import javax.annotation.Nullable; + +/** + * Error Prone check that detects usage of deprecated APIs. + * + *

    This is similar to javac's -Xlint:deprecation but properly honors {@code @SuppressWarnings} + * (including on import statements, which javac doesn't support with --release 8 due to JDK-8032211). + * + *

    Can be suppressed with {@code @SuppressWarnings("deprecation")}. + */ +@BugPattern( + summary = "Use of deprecated API", + severity = ERROR, + linkType = NONE, + altNames = "deprecation", // so it can be suppressed with @SuppressWarnings("deprecation") + suppressionAnnotations = SuppressWarnings.class) +public class OtelDeprecatedApiUsage extends BugChecker + implements BugChecker.MethodInvocationTreeMatcher, + BugChecker.NewClassTreeMatcher, + BugChecker.MemberSelectTreeMatcher, + BugChecker.MemberReferenceTreeMatcher, + BugChecker.IdentifierTreeMatcher { + + private static final long serialVersionUID = 1L; + + @Override + public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { + Symbol sym = ASTHelpers.getSymbol(tree); + return checkDeprecated(sym, tree, state); + } + + @Override + public Description matchNewClass(NewClassTree tree, VisitorState state) { + Symbol sym = ASTHelpers.getSymbol(tree); + return checkDeprecated(sym, tree, state); + } + + @Override + public Description matchMemberSelect(MemberSelectTree tree, VisitorState state) { + Symbol sym = ASTHelpers.getSymbol(tree); + return checkDeprecated(sym, tree, state); + } + + @Override + public Description matchMemberReference(MemberReferenceTree tree, VisitorState state) { + Symbol sym = ASTHelpers.getSymbol(tree); + return checkDeprecated(sym, tree, state); + } + + @Override + public Description matchIdentifier(IdentifierTree tree, VisitorState state) { + Symbol sym = ASTHelpers.getSymbol(tree); + return checkDeprecated(sym, tree, state); + } + + private Description checkDeprecated(Symbol sym, Tree tree, VisitorState state) { + if (sym == null) { + return Description.NO_MATCH; + } + + // Don't warn on import statements + if (isInsideImport(state)) { + return Description.NO_MATCH; + } + + // Check if the symbol itself is deprecated + if (!isDeprecated(sym, state)) { + return Description.NO_MATCH; + } + + // Don't warn if we're inside a deprecated context (class, method, etc.) + if (isInsideDeprecatedCode(state)) { + return Description.NO_MATCH; + } + + // Don't warn if the deprecated symbol is in the same top-level class (matches javac behavior) + if (isInSameTopLevelClass(sym, state)) { + return Description.NO_MATCH; + } + + return buildDescription(tree).setMessage("Use of deprecated API: " + sym).build(); + } + + private static boolean isInsideImport(VisitorState state) { + for (Tree tree : state.getPath()) { + if (tree instanceof ImportTree) { + return true; + } + } + return false; + } + + private static boolean isDeprecated(Symbol sym, VisitorState state) { + // First try the symbol's isDeprecated() method + if (sym.isDeprecated()) { + return true; + } + // Also check for @Deprecated annotation (some symbols may not have flag set) + return ASTHelpers.hasAnnotation(sym, "java.lang.Deprecated", state); + } + + private static boolean isInsideDeprecatedCode(VisitorState state) { + // Check enclosing elements (method, class) for @Deprecated + // Skip the first element which is the current node being checked + boolean first = true; + for (Tree tree : state.getPath()) { + if (first) { + first = false; + continue; + } + Symbol sym = ASTHelpers.getSymbol(tree); + if (sym != null && isDeprecated(sym, state)) { + return true; + } + } + return false; + } + + private static boolean isInSameTopLevelClass(Symbol sym, VisitorState state) { + // Get the top-level class containing the deprecated symbol + Symbol.ClassSymbol deprecatedTopLevel = getTopLevelClass(sym); + if (deprecatedTopLevel == null) { + return false; + } + + // Get the top-level class containing the current usage by walking the tree path + // Skip the first element (the node being checked) to find the enclosing class + Symbol.ClassSymbol usageTopLevel = null; + boolean first = true; + for (Tree tree : state.getPath()) { + if (first) { + first = false; + continue; + } + Symbol treeSym = ASTHelpers.getSymbol(tree); + if (treeSym instanceof Symbol.ClassSymbol classSymbol) { + usageTopLevel = getTopLevelClass(classSymbol); + if (usageTopLevel != null) { + break; + } + } + } + if (usageTopLevel == null) { + return false; + } + + return deprecatedTopLevel.equals(usageTopLevel); + } + + @Nullable + private static Symbol.ClassSymbol getTopLevelClass(Symbol sym) { + Symbol current = sym; + while (current != null) { + if (current instanceof Symbol.ClassSymbol classSymbol) { + Symbol owner = classSymbol.owner; + // Top-level class is owned by a package + if (owner instanceof Symbol.PackageSymbol) { + return classSymbol; + } + } + current = current.owner; + } + return null; + } +} diff --git a/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelImplJavadoc.java b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelImplJavadoc.java new file mode 100644 index 00000000000..80044d0b832 --- /dev/null +++ b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelImplJavadoc.java @@ -0,0 +1,76 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import static com.google.errorprone.BugPattern.LinkType.NONE; +import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; + +import com.google.errorprone.BugPattern; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker; +import com.google.errorprone.matchers.Description; +import com.sun.source.doctree.DocCommentTree; +import com.sun.source.tree.ClassTree; +import com.sun.source.tree.PackageTree; +import com.sun.tools.javac.api.JavacTrees; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import javax.lang.model.element.Modifier; + +/** Enforces API stability disclaimers on public types in impl packages. */ +@BugPattern( + summary = + "This public impl class is missing the required javadoc disclaimer: \"" + + OtelImplJavadoc.EXPECTED_IMPL_COMMENT + + "\"", + severity = WARNING, + linkType = NONE) +public class OtelImplJavadoc extends BugChecker implements BugChecker.ClassTreeMatcher { + + private static final long serialVersionUID = 1L; + + private static final Pattern IMPL_PACKAGE_PATTERN = Pattern.compile("\\bimpl\\b"); + + static final String EXPECTED_IMPL_COMMENT = + "This class is not intended for use by application developers." + + " Its API is stable and will not be changed or removed in a backwards-incompatible" + + " manner."; + + @Override + public Description matchClass(ClassTree tree, VisitorState state) { + if (!isPublic(tree) || !isImpl(state) || tree.getSimpleName().toString().endsWith("Test")) { + return Description.NO_MATCH; + } + String javadoc = getJavadoc(state); + if (javadoc != null && javadoc.contains(EXPECTED_IMPL_COMMENT)) { + return Description.NO_MATCH; + } + return describeMatch(tree); + } + + private static boolean isPublic(ClassTree tree) { + return tree.getModifiers().getFlags().contains(Modifier.PUBLIC); + } + + private static boolean isImpl(VisitorState state) { + PackageTree packageTree = state.getPath().getCompilationUnit().getPackage(); + if (packageTree == null) { + return false; + } + String packageName = state.getSourceForNode(packageTree.getPackageName()); + return packageName != null && IMPL_PACKAGE_PATTERN.matcher(packageName).find(); + } + + @Nullable + private static String getJavadoc(VisitorState state) { + DocCommentTree docCommentTree = + JavacTrees.instance(state.context).getDocCommentTree(state.getPath()); + if (docCommentTree == null) { + return null; + } + return docCommentTree.toString().replace("\n", " ").replace(" * ", " ").replaceAll("\\s+", " "); + } +} diff --git a/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelInternalJavadoc.java b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelInternalJavadoc.java new file mode 100644 index 00000000000..2955b47f749 --- /dev/null +++ b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelInternalJavadoc.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import static com.google.errorprone.BugPattern.LinkType.NONE; +import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; + +import com.google.errorprone.BugPattern; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker; +import com.google.errorprone.matchers.Description; +import com.sun.source.doctree.DocCommentTree; +import com.sun.source.tree.ClassTree; +import com.sun.source.tree.PackageTree; +import com.sun.tools.javac.api.JavacTrees; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import javax.lang.model.element.Modifier; + +/** Enforces API stability disclaimers on public types in internal packages. */ +@BugPattern( + summary = + "This public internal class doesn't contain any of the applicable javadoc disclaimers: \"" + + OtelInternalJavadoc.EXPECTED_INTERNAL_COMMENT_V1 + + "\", or \"" + + OtelInternalJavadoc.EXPECTED_INTERNAL_COMMENT_V2 + + "\"", + severity = WARNING, + linkType = NONE) +public class OtelInternalJavadoc extends BugChecker implements BugChecker.ClassTreeMatcher { + + private static final long serialVersionUID = 1L; + + private static final Pattern INTERNAL_PACKAGE_PATTERN = Pattern.compile("\\binternal\\b"); + + static final String EXPECTED_INTERNAL_COMMENT_V1 = + "This class is internal and is hence not for public use." + + " Its APIs are unstable and can change at any time."; + + static final String EXPECTED_INTERNAL_COMMENT_V2 = + "This class is internal and experimental. Its APIs are unstable and can change at any time." + + " Its APIs (or a version of them) may be promoted to the public stable API in the" + + " future, but no guarantees are made."; + + @Override + public Description matchClass(ClassTree tree, VisitorState state) { + if (!isPublic(tree) || !isInternal(state) || tree.getSimpleName().toString().endsWith("Test")) { + return Description.NO_MATCH; + } + String javadoc = getJavadoc(state); + if (javadoc != null + && (javadoc.contains(EXPECTED_INTERNAL_COMMENT_V1) + || javadoc.contains(EXPECTED_INTERNAL_COMMENT_V2))) { + return Description.NO_MATCH; + } + return describeMatch(tree); + } + + private static boolean isPublic(ClassTree tree) { + return tree.getModifiers().getFlags().contains(Modifier.PUBLIC); + } + + private static boolean isInternal(VisitorState state) { + PackageTree packageTree = state.getPath().getCompilationUnit().getPackage(); + if (packageTree == null) { + return false; + } + String packageName = state.getSourceForNode(packageTree.getPackageName()); + return packageName != null && INTERNAL_PACKAGE_PATTERN.matcher(packageName).find(); + } + + @Nullable + private static String getJavadoc(VisitorState state) { + DocCommentTree docCommentTree = + JavacTrees.instance(state.context).getDocCommentTree(state.getPath()); + if (docCommentTree == null) { + return null; + } + return docCommentTree.toString().replace("\n", " ").replace(" * ", " ").replaceAll("\\s+", " "); + } +} diff --git a/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelPrivateConstructorForUtilityClass.java b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelPrivateConstructorForUtilityClass.java new file mode 100644 index 00000000000..fc9a983e34e --- /dev/null +++ b/custom-checks/src/main/java/io/opentelemetry/gradle/customchecks/OtelPrivateConstructorForUtilityClass.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import static com.google.errorprone.BugPattern.LinkType.NONE; +import static com.google.errorprone.BugPattern.SeverityLevel.WARNING; +import static com.google.errorprone.matchers.Description.NO_MATCH; + +import com.google.errorprone.BugPattern; +import com.google.errorprone.VisitorState; +import com.google.errorprone.bugpatterns.BugChecker; +import com.google.errorprone.bugpatterns.PrivateConstructorForUtilityClass; +import com.google.errorprone.matchers.Description; +import com.sun.source.tree.ClassTree; + +/** Enforces private constructors on utility classes, including classes with a main method. */ +@BugPattern( + summary = + "Classes which are not intended to be instantiated should be made non-instantiable with a private constructor. This includes utility classes (classes with only static members), and the main class.", + severity = WARNING, + linkType = NONE) +public class OtelPrivateConstructorForUtilityClass extends BugChecker + implements BugChecker.ClassTreeMatcher { + + private static final long serialVersionUID = 1L; + + private final PrivateConstructorForUtilityClass delegate = + new PrivateConstructorForUtilityClass(); + + @Override + public Description matchClass(ClassTree tree, VisitorState state) { + Description description = delegate.matchClass(tree, state); + if (description.equals(NO_MATCH)) { + return description; + } + return describeMatch(tree); + } +} diff --git a/custom-checks/src/main/resources/META-INF/services/com.google.errorprone.bugpatterns.BugChecker b/custom-checks/src/main/resources/META-INF/services/com.google.errorprone.bugpatterns.BugChecker new file mode 100644 index 00000000000..7bb2c5507d7 --- /dev/null +++ b/custom-checks/src/main/resources/META-INF/services/com.google.errorprone.bugpatterns.BugChecker @@ -0,0 +1,4 @@ +io.opentelemetry.gradle.customchecks.OtelDeprecatedApiUsage +io.opentelemetry.gradle.customchecks.OtelImplJavadoc +io.opentelemetry.gradle.customchecks.OtelInternalJavadoc +io.opentelemetry.gradle.customchecks.OtelPrivateConstructorForUtilityClass diff --git a/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelDeprecatedApiUsageTest.java b/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelDeprecatedApiUsageTest.java new file mode 100644 index 00000000000..b5b9a66f4be --- /dev/null +++ b/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelDeprecatedApiUsageTest.java @@ -0,0 +1,191 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import com.google.errorprone.CompilationTestHelper; +import org.junit.jupiter.api.Test; + +class OtelDeprecatedApiUsageTest { + + @Test + void positiveCases() { + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "DeprecatedClass.java", + "package test;", + "@Deprecated", + "public class DeprecatedClass {", + " @Deprecated", + " public static void deprecatedMethod() {}", + " @Deprecated", + " public static String DEPRECATED_FIELD = \"old\";", + "}") + .addSourceLines( + "PositiveCases.java", + "package test;", + "public class PositiveCases {", + " void method() {", + " // BUG: Diagnostic contains: Use of deprecated API: deprecatedMethod()", + " DeprecatedClass.deprecatedMethod();", + " // BUG: Diagnostic contains: Use of deprecated API: DEPRECATED_FIELD", + " String s = DeprecatedClass.DEPRECATED_FIELD;", + " }", + "}") + .doTest(); + } + + @Test + void positiveCases_classAsFieldType() { + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "DeprecatedClass.java", + "package test;", + "@Deprecated", + "public class DeprecatedClass {}") + .addSourceLines( + "PositiveCases.java", + "package test;", + "public class PositiveCases {", + " // BUG: Diagnostic contains: Use of deprecated API: test.DeprecatedClass", + " DeprecatedClass obj;", + "}") + .doTest(); + } + + @Test + void negativeCases_suppressWarningsDeprecation() { + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "DeprecatedClass.java", + "package test;", + "@Deprecated", + "public class DeprecatedClass {", + " @Deprecated", + " public static void deprecatedMethod() {}", + "}") + .addSourceLines( + "NegativeCases.java", + "package test;", + "@SuppressWarnings(\"deprecation\")", + "public class NegativeCases {", + " DeprecatedClass obj;", + " void method() {", + " DeprecatedClass.deprecatedMethod();", + " }", + "}") + .doTest(); + } + + @Test + void negativeCases_suppressWarningsCheckName() { + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "DeprecatedClass.java", + "package test;", + "@Deprecated", + "public class DeprecatedClass {}") + .addSourceLines( + "NegativeCases.java", + "package test;", + "@SuppressWarnings(\"OtelDeprecatedApiUsage\")", + "public class NegativeCases {", + " DeprecatedClass obj;", + "}") + .doTest(); + } + + @Test + void negativeCases_insideDeprecatedClass() { + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "DeprecatedClass.java", + "package test;", + "@Deprecated", + "public class DeprecatedClass {", + " @Deprecated", + " public static void deprecatedMethod() {}", + "}") + .addSourceLines( + "NegativeCases.java", + "package test;", + "@Deprecated", + "public class NegativeCases {", + " // Inside a deprecated class, using other deprecated APIs is fine", + " DeprecatedClass obj;", + " void method() {", + " DeprecatedClass.deprecatedMethod();", + " }", + "}") + .doTest(); + } + + @Test + void negativeCases_sameClassDeprecation() { + // Matches javac behavior: using deprecated members within the same class doesn't warn + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "SameClass.java", + "package test;", + "public class SameClass {", + " @Deprecated", + " public SameClass() {}", + " public static SameClass create() {", + " // No warning: deprecated constructor is in same class", + " return new SameClass();", + " }", + " @Deprecated", + " public static void deprecatedMethod() {}", + " public void caller() {", + " // No warning: deprecated method is in same class", + " deprecatedMethod();", + " }", + "}") + .doTest(); + } + + @Test + void negativeCases_importDeprecatedClass() { + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "deprecated/DeprecatedClass.java", + "package deprecated;", + "@Deprecated", + "public class DeprecatedClass {}") + .addSourceLines( + "NegativeCases.java", + "package test;", + "import deprecated.DeprecatedClass;", // Should NOT warn on import + "@SuppressWarnings(\"deprecation\")", + "public class NegativeCases {", + " void method(DeprecatedClass obj) {}", + "}") + .doTest(); + } + + @Test + void positiveCases_externalDeprecatedApi() { + // Verify the check detects deprecated APIs from external code (JDK in this case) + CompilationTestHelper.newInstance( + OtelDeprecatedApiUsage.class, OtelDeprecatedApiUsageTest.class) + .addSourceLines( + "ExternalDeprecated.java", + "package test;", + "public class ExternalDeprecated {", + " void method() {", + " // BUG: Diagnostic contains: Use of deprecated API", + " new Boolean(false);", + " }", + "}") + .doTest(); + } +} diff --git a/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelImplJavadocTest.java b/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelImplJavadocTest.java new file mode 100644 index 00000000000..ad294d61b2c --- /dev/null +++ b/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelImplJavadocTest.java @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import com.google.errorprone.CompilationTestHelper; +import org.junit.jupiter.api.Test; + +class OtelImplJavadocTest { + + @Test + void positiveCases() { + CompilationTestHelper.newInstance(OtelImplJavadoc.class, OtelImplJavadocTest.class) + .addSourceLines( + "impl/ImplJavadocPositiveCases.java", + "/*", + " * Copyright The OpenTelemetry Authors", + " * SPDX-License-Identifier: Apache-2.0", + " */", + "package io.opentelemetry.gradle.customchecks.impl;", + "// BUG: Diagnostic contains: missing the required javadoc disclaimer", + "public class ImplJavadocPositiveCases {", + " // BUG: Diagnostic contains: missing the required javadoc disclaimer", + " public static class One {}", + " /** Doesn't have the disclaimer. */", + " // BUG: Diagnostic contains: missing the required javadoc disclaimer", + " public static class Two {}", + "}") + .doTest(); + } + + @Test + void negativeCases() { + CompilationTestHelper.newInstance(OtelImplJavadoc.class, OtelImplJavadocTest.class) + .addSourceLines( + "impl/ImplJavadocNegativeCases.java", + "/*", + " * Copyright The OpenTelemetry Authors", + " * SPDX-License-Identifier: Apache-2.0", + " */", + "package io.opentelemetry.gradle.customchecks.impl;", + "/**", + " * This class is not intended for use by application developers. Its API is stable and", + " * will not be changed or removed in a backwards-incompatible manner.", + " */", + "public class ImplJavadocNegativeCases {", + " /**", + " * This class is not intended for use by application developers. Its API is stable", + " * and will not be changed or removed in a backwards-incompatible manner.", + " */", + " public static class One {}", + " // Non-public class without disclaimer is fine.", + " static class Two {}", + "}") + .doTest(); + } + + @Test + void nonImplPackageIgnored() { + CompilationTestHelper.newInstance(OtelImplJavadoc.class, OtelImplJavadocTest.class) + .addSourceLines( + "other/NonImplPackageCases.java", + "/*", + " * Copyright The OpenTelemetry Authors", + " * SPDX-License-Identifier: Apache-2.0", + " */", + "package io.opentelemetry.gradle.customchecks.other;", + "public class NonImplPackageCases {", + " public static class One {}", + "}") + .doTest(); + } +} diff --git a/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelInternalJavadocTest.java b/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelInternalJavadocTest.java new file mode 100644 index 00000000000..723487996b3 --- /dev/null +++ b/custom-checks/src/test/java/io/opentelemetry/gradle/customchecks/OtelInternalJavadocTest.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.gradle.customchecks; + +import com.google.errorprone.CompilationTestHelper; +import org.junit.jupiter.api.Test; + +class OtelInternalJavadocTest { + + @Test + void positiveCases() { + CompilationTestHelper.newInstance(OtelInternalJavadoc.class, OtelInternalJavadocTest.class) + .addSourceLines( + "internal/InternalJavadocPositiveCases.java", + "/*", + " * Copyright The OpenTelemetry Authors", + " * SPDX-License-Identifier: Apache-2.0", + " */", + "package io.opentelemetry.gradle.customchecks.internal;", + "// BUG: Diagnostic contains: doesn't contain any of the applicable javadoc disclaimers", + "public class InternalJavadocPositiveCases {", + " // BUG: Diagnostic contains: doesn't contain any of the applicable javadoc disclaimers", + " public static class One {}", + " /** Doesn't have the disclaimer. */", + " // BUG: Diagnostic contains: doesn't contain any of the applicable javadoc disclaimers", + " public static class Two {}", + "}") + .doTest(); + } + + @Test + void negativeCases() { + CompilationTestHelper.newInstance(OtelInternalJavadoc.class, OtelInternalJavadocTest.class) + .addSourceLines( + "internal/InternalJavadocNegativeCases.java", + "/*", + " * Copyright The OpenTelemetry Authors", + " * SPDX-License-Identifier: Apache-2.0", + " */", + "package io.opentelemetry.gradle.customchecks.internal;", + "/**", + " * This class is internal and is hence not for public use. Its APIs are unstable and can change at", + " * any time.", + " */", + "public class InternalJavadocNegativeCases {", + " /**", + " * This class is internal and is hence not for public use. Its APIs are unstable and can change at", + " * any time.", + " */", + " public static class One {}", + " static class Two {}", + "}") + .doTest(); + } +} diff --git a/dependencyManagement/build.gradle.kts b/dependencyManagement/build.gradle.kts index 47faffba64e..cf984d7c3a7 100644 --- a/dependencyManagement/build.gradle.kts +++ b/dependencyManagement/build.gradle.kts @@ -1,9 +1,5 @@ -import com.github.benmanes.gradle.versions.updates.DependencyUpdatesTask - plugins { `java-platform` - - id("com.github.ben-manes.versions") } data class DependencySet(val group: String, val version: String, val modules: List) @@ -11,95 +7,101 @@ data class DependencySet(val group: String, val version: String, val modules: Li val dependencyVersions = hashMapOf() rootProject.extra["versions"] = dependencyVersions + +val autoValueVersion = "1.11.1" +val errorProneVersion = "2.52.0" +val jmhVersion = "1.37" +// Mockito 5.x.x requires Java 11 https://github.com/mockito/mockito/releases/tag/v5.0.0 +val mockitoVersion = "4.11.0" +val slf4jVersion = "2.0.20" +val opencensusVersion = "0.31.1" +val prometheusServerVersion = "1.8.0" +val armeriaVersion = "1.43.0" +val junitVersion = "5.14.4" +val junitPlatformVersion = "1.14.4" +val okhttpVersion = "5.5.1" + val DEPENDENCY_BOMS = listOf( - "com.fasterxml.jackson:jackson-bom:2.13.2.20220328", - "com.google.guava:guava-bom:31.1-jre", - "com.google.protobuf:protobuf-bom:3.20.0", - "com.linecorp.armeria:armeria-bom:1.15.0", - "com.squareup.okhttp3:okhttp-bom:4.9.3", - "io.grpc:grpc-bom:1.45.1", - "io.micrometer:micrometer-bom:1.8.4", - "io.zipkin.brave:brave-bom:5.13.8", - "io.zipkin.reporter2:zipkin-reporter-bom:2.16.3", - "org.junit:junit-bom:5.8.2", - "org.testcontainers:testcontainers-bom:1.16.3", - "org.yaml:snakeyaml:1.30" -) + // for some reason boms show up as runtime dependencies in license and vulnerability scans + // even if they are only used by test dependencies, so not using junit bom here + // (which is EPL licensed) or armeria bom (which is Apache licensed but is getting flagged + // by FOSSA for containing EPL-licensed) -val DEPENDENCY_SETS = listOf( - DependencySet( - "com.google.auto.value", - "1.9", - listOf("auto-value", "auto-value-annotations") - ), - DependencySet( - "com.google.errorprone", - "2.12.1", - listOf("error_prone_annotations", "error_prone_core") - ), - DependencySet( - "io.opencensus", - "0.31.0", - listOf( - "opencensus-api", - "opencensus-impl-core", - "opencensus-impl", - "opencensus-exporter-metrics-util", - "opencensus-contrib-exemplar-util" - ) - ), - DependencySet( - "io.prometheus", - "0.15.0", - listOf("simpleclient", "simpleclient_common", "simpleclient_httpserver") - ), - DependencySet( - "javax.annotation", - "1.3.2", - listOf("javax.annotation-api") - ), - DependencySet( - "org.openjdk.jmh", - "1.35", - listOf("jmh-core", "jmh-generator-bytecode") - ), - DependencySet( - "org.mockito", - "4.4.0", - listOf("mockito-core", "mockito-junit-jupiter") - ), - DependencySet( - "org.slf4j", - "1.7.36", - listOf("jul-to-slf4j", "slf4j-simple") - ), + "com.fasterxml.jackson:jackson-bom:2.23.0", + "com.google.guava:guava-bom:33.8.0-jre", + "com.google.protobuf:protobuf-bom:4.36.2", + "com.squareup.okhttp3:okhttp-bom:$okhttpVersion", + "com.squareup.okio:okio-bom:3.18.2", // applies to transitive dependencies of okhttp + "io.grpc:grpc-bom:1.85.1", + "io.netty:netty-bom:4.2.20.Final", + "org.assertj:assertj-bom:3.27.7", + "org.osgi:org.osgi.test.bom:1.3.0", + "org.testcontainers:testcontainers-bom:2.0.5", + "org.snakeyaml:snakeyaml-engine:2.10" ) val DEPENDENCIES = listOf( + "org.junit.jupiter:junit-jupiter:${junitVersion}", + "org.junit.jupiter:junit-jupiter-api:${junitVersion}", + "org.junit.jupiter:junit-jupiter-engine:${junitVersion}", + "org.junit.jupiter:junit-jupiter-params:${junitVersion}", + "org.junit.platform:junit-platform-launcher:${junitPlatformVersion}", + "com.linecorp.armeria:armeria:${armeriaVersion}", + "com.linecorp.armeria:armeria-grpc:${armeriaVersion}", + "com.linecorp.armeria:armeria-grpc-protocol:${armeriaVersion}", + "com.linecorp.armeria:armeria-junit5:${armeriaVersion}", + + "com.google.auto.value:auto-value:${autoValueVersion}", + "com.google.auto.value:auto-value-annotations:${autoValueVersion}", + "com.google.errorprone:error_prone_annotations:${errorProneVersion}", + "com.google.errorprone:error_prone_core:${errorProneVersion}", + "com.google.errorprone:error_prone_test_helpers:${errorProneVersion}", + "io.opencensus:opencensus-api:${opencensusVersion}", + "io.opencensus:opencensus-impl-core:${opencensusVersion}", + "io.opencensus:opencensus-impl:${opencensusVersion}", + "io.opencensus:opencensus-exporter-metrics-util:${opencensusVersion}", + "io.opencensus:opencensus-contrib-exemplar-util:${opencensusVersion}", + "org.openjdk.jmh:jmh-core:${jmhVersion}", + "org.openjdk.jmh:jmh-generator-bytecode:${jmhVersion}", + "org.openjdk.jmh:jmh-generator-annprocess:${jmhVersion}", + "org.mockito:mockito-core:${mockitoVersion}", + "org.mockito:mockito-junit-jupiter:${mockitoVersion}", + "org.slf4j:slf4j-simple:${slf4jVersion}", + "org.slf4j:jul-to-slf4j:${slf4jVersion}", + "io.prometheus:prometheus-metrics-exporter-httpserver:${prometheusServerVersion}", + "io.prometheus:prometheus-metrics-exposition-formats-no-protobuf:${prometheusServerVersion}", + "javax.annotation:javax.annotation-api:1.3.2", "com.github.stefanbirkner:system-rules:1.19.0", - "com.google.api.grpc:proto-google-common-protos:2.8.0", + "com.google.api.grpc:proto-google-common-protos:2.81.0", "com.google.code.findbugs:jsr305:3.0.2", - "com.google.guava:guava-beta-checker:1.0", - "com.lmax:disruptor:3.4.4", "com.sun.net.httpserver:http:20070405", - "com.tngtech.archunit:archunit-junit5:0.23.1", - "com.uber.nullaway:nullaway:0.9.6", - // TODO(anuraaga): Skip 1.8 because of https://github.com/rohanpadhye/JQF/issues/172 - "edu.berkeley.cs.jqf:jqf-fuzz:1.7", - "eu.rekawek.toxiproxy:toxiproxy-java:2.1.5", - "io.github.netmikey.logunit:logunit-jul:1.1.3", - "io.jaegertracing:jaeger-client:1.8.0", - "io.opentelemetry.proto:opentelemetry-proto:0.18.0-alpha", + "com.squareup.okhttp3:okhttp:$okhttpVersion", + "com.tngtech.archunit:archunit-junit5:1.5.1", + "com.uber.nullaway:nullaway:0.14.3", + "edu.berkeley.cs.jqf:jqf-fuzz:1.7", // jqf-fuzz version 1.8+ requires Java 11+ + "eu.rekawek.toxiproxy:toxiproxy-java:2.1.11", + "io.github.crac:org-crac:0.1.3", + "io.github.netmikey.logunit:logunit-jul:2.0.0", + "io.jaegertracing:jaeger-client:1.8.1", + "io.opentelemetry.instrumentation:opentelemetry-resources:2.28.1-alpha", + "io.opentelemetry.contrib:opentelemetry-aws-xray-propagator:1.62.1-alpha", + "io.opentelemetry.semconv:opentelemetry-semconv-incubating:1.45.0-alpha", + "io.opentelemetry.proto:opentelemetry-proto:1.11.1-alpha", "io.opentracing:opentracing-api:0.33.0", + "io.opentracing:opentracing-noop:0.33.0", + "io.zipkin.brave:brave:6.3.1", "junit:junit:4.13.2", - "nl.jqno.equalsverifier:equalsverifier:3.10", - "org.assertj:assertj-core:3.22.0", - "org.awaitility:awaitility:4.2.0", - "org.bouncycastle:bcpkix-jdk15on:1.70", - "org.codehaus.mojo:animal-sniffer-annotations:1.21", - "org.jctools:jctools-core:3.3.0", - "org.junit-pioneer:junit-pioneer:1.6.2", - "org.skyscreamer:jsonassert:1.5.0", + "nl.jqno.equalsverifier:equalsverifier:3.19.4", + "org.apache.aries.spifly:org.apache.aries.spifly.dynamic.bundle:1.3.8", + "org.apache.felix:org.apache.felix.framework:8.0.0", + "org.awaitility:awaitility:4.3.0", + "org.codehaus.mojo:animal-sniffer-annotations:1.29.1", + "org.jctools:jctools-core:4.0.7", + "org.junit-pioneer:junit-pioneer:1.9.1", + "org.mock-server:mockserver-netty:5.15.0:shaded", + "org.osgi:osgi.core:8.0.0", + "org.skyscreamer:jsonassert:1.5.3", + "com.android.tools:desugar_jdk_libs:2.1.5", ) javaPlatform { @@ -113,12 +115,6 @@ dependencies { dependencyVersions[split[0]] = split[2] } constraints { - for (set in DEPENDENCY_SETS) { - for (module in set.modules) { - api("${set.group}:$module:${set.version}") - dependencyVersions[set.group] = set.version - } - } for (dependency in DEPENDENCIES) { api(dependency) val split = dependency.split(':') @@ -126,22 +122,3 @@ dependencies { } } } - -fun isNonStable(version: String): Boolean { - val stableKeyword = listOf("RELEASE", "FINAL", "GA").any { version.toUpperCase().contains(it) } - val regex = "^[0-9,.v-]+(-r)?$".toRegex() - val isGuava = version.endsWith("-jre") - val isStable = stableKeyword || regex.matches(version) || isGuava - return isStable.not() -} - -tasks { - named("dependencyUpdates") { - revision = "release" - checkConstraints = true - - rejectVersionIf { - isNonStable(candidate.version) - } - } -} diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-api.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-api.txt new file mode 100644 index 00000000000..04e1e24528c --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-api.txt @@ -0,0 +1,36 @@ +Comparing source compatibility of against ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.metrics.BatchCallback (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) void close() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleCounterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableDoubleMeasurement buildObserver() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleGaugeBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableDoubleMeasurement buildObserver() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleUpDownCounterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableDoubleMeasurement buildObserver() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongCounterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableLongMeasurement buildObserver() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongGaugeBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableLongMeasurement buildObserver() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongUpDownCounterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableLongMeasurement buildObserver() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.Meter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.BatchCallback batchCallback(java.lang.Runnable, io.opentelemetry.api.metrics.ObservableMeasurement, io.opentelemetry.api.metrics.ObservableMeasurement[]) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.ObservableDoubleMeasurement (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.api.metrics.ObservableMeasurement +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.ObservableLongMeasurement (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.api.metrics.ObservableMeasurement ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.metrics.ObservableMeasurement (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-jaeger-proto.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-context.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-jaeger-proto.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-context.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-jaeger-proto.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-jaeger-thrift.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-jaeger-proto.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-http-metrics.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-jaeger-thrift.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-http-metrics.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-jaeger-thrift.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-jaeger.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-jaeger.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-jaeger.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-http-trace.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-logging-otlp.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-http-trace.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-logging-otlp.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-metrics.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-logging.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-metrics.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-logging.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-trace.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-otlp-common.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-trace.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-otlp-common.txt diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..a376f0e41e4 --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,87 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.data.AggregationTemporality getAggregationTemporality(io.opentelemetry.sdk.metrics.InstrumentType) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter getDefault() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder addHeader(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setAggregationTemporalitySelector(io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setClientTls(byte[], byte[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setCompression(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setEndpoint(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setTrustedCertificates(byte[]) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter getDefault() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder addHeader(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setClientTls(byte[], byte[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setCompression(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setEndpoint(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setMeterProvider(io.opentelemetry.api.metrics.MeterProvider) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setTrustedCertificates(byte[]) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.data.AggregationTemporality getAggregationTemporality(io.opentelemetry.sdk.metrics.InstrumentType) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter getDefault() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder addHeader(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setAggregationTemporalitySelector(io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setChannel(io.grpc.ManagedChannel) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setClientTls(byte[], byte[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setCompression(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setEndpoint(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setTrustedCertificates(byte[]) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter getDefault() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder addHeader(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setChannel(io.grpc.ManagedChannel) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setClientTls(byte[], byte[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setCompression(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setEndpoint(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setMeterProvider(io.opentelemetry.api.metrics.MeterProvider) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setTrustedCertificates(byte[]) diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-zipkin.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-exporter-zipkin.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-exporter-zipkin.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-extension-annotations.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-annotations.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-extension-annotations.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-annotations.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-extension-aws.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-aws.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-extension-aws.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-aws.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-aws.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-kotlin.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-aws.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-kotlin.txt diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-resources.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-trace-propagators.txt similarity index 100% rename from docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-resources.txt rename to docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-extension-trace-propagators.txt diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..1da6fe3008a --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,16 @@ +Comparing source compatibility of against +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) boolean getBoolean(java.lang.String, boolean) + +++! NEW METHOD: PUBLIC(+) double getDouble(java.lang.String, double) + +++! NEW METHOD: PUBLIC(+) java.time.Duration getDuration(java.lang.String, java.time.Duration) + +++! NEW METHOD: PUBLIC(+) int getInt(java.lang.String, int) + +++! NEW METHOD: PUBLIC(+) java.util.List getList(java.lang.String, java.util.List) + +++! NEW METHOD: PUBLIC(+) long getLong(java.lang.String, long) + +++! NEW METHOD: PUBLIC(+) java.util.Map getMap(java.lang.String, java.util.Map) + +++! NEW METHOD: PUBLIC(+) java.lang.String getString(java.lang.String, java.lang.String) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.export.MetricExporter createExporter(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getName() diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-aws.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-resources.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-resources.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-extension-resources.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..3598f6e084d --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,13 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.InstrumentSelector (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.SdkMeterProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.View (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) java.lang.String toString() diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..9e4477426ed --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,12 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.junit4.OpenTelemetryRule (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) void clearMetrics() + +++ NEW METHOD: PUBLIC(+) java.util.List getMetrics() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) void clearMetrics() + +++ NEW METHOD: PUBLIC(+) java.util.List getMetrics() diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk.txt b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.15.0_vs_1.14.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-api.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-context.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger-proto.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger-proto.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger-proto.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..bbc1c8af41d --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,13 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setDefaultAggregationSelector(io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setDefaultAggregationSelector(io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector) diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-annotations.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-annotations.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-annotations.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-aws.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-aws.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-resources.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-resources.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-extension-resources.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..9bf7b967e26 --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,21 @@ +Comparing source compatibility of against ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector getDefault() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector with(io.opentelemetry.sdk.metrics.InstrumentType, io.opentelemetry.sdk.metrics.Aggregation) + +++ NEW ANNOTATION: java.lang.FunctionalInterface +**** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.MetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector + +++* NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) +**** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.MetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector + +++* NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ===* UNCHANGED INTERFACE: io.opentelemetry.sdk.metrics.export.MetricReader + +++ NEW INTERFACE: io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..6be7112f605 --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,11 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.SpanDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.SpanDataAssert hasStatusSatisfying(java.util.function.Consumer) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.StatusDataAssert (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.StatusDataAssert hasCode(io.opentelemetry.api.trace.StatusCode) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.StatusDataAssert hasDescription(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.StatusDataAssert hasDescriptionMatching(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.StatusDataAssert isError() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.StatusDataAssert isOk() diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk.txt b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.16.0_vs_1.15.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-api.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-context.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger-proto.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger-proto.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger-proto.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..580b92e8904 --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setMeterProvider(io.opentelemetry.api.metrics.MeterProvider) diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-annotations.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-annotations.txt new file mode 100644 index 00000000000..b6e56f53151 --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-annotations.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +=== UNCHANGED ANNOTATION: PUBLIC ABSTRACT io.opentelemetry.extension.annotations.SpanAttribute (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED ANNOTATION: PUBLIC ABSTRACT io.opentelemetry.extension.annotations.WithSpan (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-aws.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..5bbb90cb802 --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of against +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++! NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addPropertiesCustomizer(java.util.function.Function) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.sdk.autoconfigure.spi.Ordered ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogExporterProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.export.LogExporter createExporter(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getName() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.spi.Ordered (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) int order() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.sdk.autoconfigure.spi.Ordered diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-aws.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-resources.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-resources.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-extension-resources.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..70a89f7e645 --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.testing.trace.TestSpanData (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.InstrumentationScopeInfo getInstrumentationScopeInfo() diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..59e8eb99545 --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.trace.data.SpanData (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ***! MODIFIED METHOD: PUBLIC NON_ABSTRACT (<- ABSTRACT) io.opentelemetry.sdk.common.InstrumentationScopeInfo getInstrumentationScopeInfo() +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.trace.ReadableSpan (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ***! MODIFIED METHOD: PUBLIC NON_ABSTRACT (<- ABSTRACT) io.opentelemetry.sdk.common.InstrumentationScopeInfo getInstrumentationScopeInfo() diff --git a/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk.txt b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.17.0_vs_1.16.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-api.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-context.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..ef0871634a1 --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setLocalIpAddressSupplier(java.util.function.Supplier) diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-annotations.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-annotations.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-annotations.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-aws.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..d074d37995d --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-common.txt @@ -0,0 +1,14 @@ +Comparing source compatibility of against +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.common.InstrumentationScopeInfo (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.InstrumentationScopeInfoBuilder builder(java.lang.String) + === UNCHANGED METHOD: PUBLIC STATIC io.opentelemetry.sdk.common.InstrumentationScopeInfo create(java.lang.String, java.lang.String, java.lang.String) + +++ NEW ANNOTATION: java.lang.Deprecated + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.Attributes getAttributes() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.common.InstrumentationScopeInfoBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.InstrumentationScopeInfo build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.InstrumentationScopeInfoBuilder setAttributes(io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.InstrumentationScopeInfoBuilder setSchemaUrl(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.InstrumentationScopeInfoBuilder setVersion(java.lang.String) diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-aws.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-resources.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-resources.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-extension-resources.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..8c6945a0500 --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.AttributesAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.AttributesAssert doesNotContainKey(io.opentelemetry.api.common.AttributeKey) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.AttributesAssert doesNotContainKey(java.lang.String) diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk.txt b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.18.0_vs_1.17.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-api.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-context.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..cfe9a9bbcc2 --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,15 @@ +Comparing source compatibility of against +---! REMOVED CLASS: PUBLIC(-) FINAL(-) io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingLogExporter (not serializable) + --- CLASS FILE FORMAT VERSION: n.a. <- 52.0 + ---! REMOVED SUPERCLASS: java.lang.Object + ---! REMOVED METHOD: PUBLIC(-) STATIC(-) io.opentelemetry.sdk.logs.export.LogExporter create() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.common.CompletableResultCode flush() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingLogRecordExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.export.LogRecordExporter create() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..fca6cfdf2cd --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,17 @@ +Comparing source compatibility of against +---! REMOVED CLASS: PUBLIC(-) io.opentelemetry.exporter.logging.SystemOutLogExporter (not serializable) + --- CLASS FILE FORMAT VERSION: n.a. <- 52.0 + ---! REMOVED SUPERCLASS: java.lang.Object + ---! REMOVED CONSTRUCTOR: PUBLIC(-) SystemOutLogExporter() + --- REMOVED ANNOTATION: java.lang.Deprecated + ---! REMOVED METHOD: PUBLIC(-) STATIC(-) io.opentelemetry.exporter.logging.SystemOutLogExporter create() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.common.CompletableResultCode flush() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) io.opentelemetry.exporter.logging.SystemOutLogRecordExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.logging.SystemOutLogRecordExporter create() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-aws.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..5f013e87bab --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,17 @@ +Comparing source compatibility of against +***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLogEmitterProviderCustomizer(java.util.function.BiFunction) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLogExporterCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLoggerProviderCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLogRecordExporterCustomizer(java.util.function.BiFunction) +---! REMOVED INTERFACE: PUBLIC(-) ABSTRACT(-) io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogExporterProvider (not serializable) + --- CLASS FILE FORMAT VERSION: n.a. <- 52.0 + ---! REMOVED SUPERCLASS: java.lang.Object + ---! REMOVED METHOD: PUBLIC(-) ABSTRACT(-) io.opentelemetry.sdk.logs.export.LogExporter createExporter(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + ---! REMOVED METHOD: PUBLIC(-) ABSTRACT(-) java.lang.String getName() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.export.LogRecordExporter createExporter(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getName() diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-aws.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-aws.txt new file mode 100644 index 00000000000..6afe0d0ee07 --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-aws.txt @@ -0,0 +1,31 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.BeanstalkResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.BeanstalkResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.Ec2Resource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.Ec2ResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.EcsResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.EcsResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.EksResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.EksResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.LambdaResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.aws.resource.LambdaResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-resources.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-resources.txt new file mode 100644 index 00000000000..2572189c4cd --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-extension-resources.txt @@ -0,0 +1,31 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.ContainerResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC io.opentelemetry.sdk.extension.resources.ContainerResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.HostResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.HostResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.OsResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.OsResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.ProcessResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.ProcessResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.ProcessRuntimeResource (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.resources.ProcessRuntimeResourceProvider (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk.txt b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..dfdb2bcb9ec --- /dev/null +++ b/docs/apidiffs/1.19.0_vs_1.18.0/opentelemetry-sdk.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of against +***! MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.OpenTelemetrySdk (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.logs.SdkLogEmitterProvider getSdkLogEmitterProvider() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProvider getSdkLoggerProvider() +***! MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.OpenTelemetrySdkBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.OpenTelemetrySdkBuilder setLogEmitterProvider(io.opentelemetry.sdk.logs.SdkLogEmitterProvider) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.OpenTelemetrySdkBuilder setLoggerProvider(io.opentelemetry.sdk.logs.SdkLoggerProvider) diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-api.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-context.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..f2e115c71f2 --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporterBuilder setCompression(java.lang.String) diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..535314c07b1 --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setCompression(java.lang.String) diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-aws.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-aws.txt new file mode 100644 index 00000000000..979e67fbfcf --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-aws.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.aws.AwsConfigurablePropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.aws.AwsXrayPropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk.txt b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.0_vs_1.19.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-api.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-context.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-aws.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-aws.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-aws.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk.txt b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.20.1_vs_1.20.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-api.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-api.txt new file mode 100644 index 00000000000..f29157f7b32 --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-api.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-context.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-common.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..62ccbdb194c --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,10 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.extension.trace.propagation.B3Propagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.extension.trace.propagation.JaegerPropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.extension.trace.propagation.OtTracePropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-common.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..6fa6fca8c60 --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-testing.txt @@ -0,0 +1,23 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.testing.assertj.AbstractPointAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.AbstractPointAssert hasAttributesSatisfyingExactly(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.AbstractPointAssert hasAttributesSatisfyingExactly(java.lang.Iterable) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.DoubleExemplarAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.DoubleExemplarAssert hasFilteredAttributesSatisfyingExactly(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.DoubleExemplarAssert hasFilteredAttributesSatisfyingExactly(java.lang.Iterable) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.EventDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.EventDataAssert hasAttributesSatisfying(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.EventDataAssert hasAttributesSatisfying(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.EventDataAssert hasAttributesSatisfyingExactly(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.EventDataAssert hasAttributesSatisfyingExactly(java.lang.Iterable) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LongExemplarAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LongExemplarAssert hasFilteredAttributesSatisfyingExactly(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LongExemplarAssert hasFilteredAttributesSatisfyingExactly(java.lang.Iterable) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.SpanDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.SpanDataAssert hasAttributesSatisfying(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.SpanDataAssert hasAttributesSatisfying(java.lang.Iterable) diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk.txt b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.21.0_vs_1.20.1/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-api.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-context.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk.txt b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.22.0_vs_1.21.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-api.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-context.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..71a2caf6bfa --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,46 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.Aggregation (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.Aggregation base2ExponentialBucketHistogram() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.Aggregation base2ExponentialBucketHistogram(int, int) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.List getBucketCounts() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getOffset() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getScale() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) long getTotalCount() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.data.ExponentialHistogramData (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: io.opentelemetry.sdk.metrics.data.Data + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.data.AggregationTemporality getAggregationTemporality() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.Collection getPoints() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: io.opentelemetry.sdk.metrics.data.PointData + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) long getCount() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.List getExemplars() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) double getMax() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) double getMin() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets getNegativeBuckets() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets getPositiveBuckets() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getScale() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) double getSum() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) long getZeroCount() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean hasMax() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean hasMin() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.data.MetricData (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.data.ExponentialHistogramData getExponentialHistogramData() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.MetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW METHOD: PUBLIC(+) void close() + +++ NEW EXCEPTION: java.io.IOException +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..bd038863c8e --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,51 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert hasPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert hasPointsSatisfying(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert isCumulative() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert isDelta() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramBucketsAssert (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramBucketsAssert hasCounts(java.util.List) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramBucketsAssert hasOffset(int) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramBucketsAssert hasTotalCount(long) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: io.opentelemetry.sdk.testing.assertj.AbstractPointAssert + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasCount(long) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasExemplars(io.opentelemetry.sdk.metrics.data.DoubleExemplarData[]) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasExemplarsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasExemplarsSatisfying(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasMax(double) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasMin(double) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasNegativeBucketsSatisfying(java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasPositiveBucketsSatisfying(java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasScale(int) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasSum(double) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramPointAssert hasZeroCount(long) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.MetricAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasExponentialHistogramSatisfying(java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasResourceSatisfying(java.util.function.Consumer) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttribute(io.opentelemetry.api.common.AttributeKey, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttribute(io.opentelemetry.sdk.testing.assertj.AttributeAssertion) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributes(io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributes(java.util.Map$Entry[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributesSatisfying(java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributesSatisfying(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributesSatisfying(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributesSatisfyingExactly(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasAttributesSatisfyingExactly(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ResourceAssert hasSchemaUrl(java.lang.String) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.SpanDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.SpanDataAssert hasResourceSatisfying(java.util.function.Consumer) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.TracesAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.assertj.TracesAssert assertThat(java.util.List) diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk.txt b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..9aa3e106809 --- /dev/null +++ b/docs/apidiffs/1.23.0_vs_1.22.0/opentelemetry-sdk.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.OpenTelemetrySdk (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) void close() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-api.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-context.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk.txt b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.23.1_vs_1.23.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-api.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-context.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-common.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-common.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..5d793b8972f --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,70 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + --- REMOVED METHOD: PUBLIC(-) FINAL(-) com.google.protobuf.UnknownFieldSet getUnknownFields() +***! MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder clone() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + --- REMOVED METHOD: PUBLIC(-) FINAL(-) com.google.protobuf.UnknownFieldSet getUnknownFields() +***! MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder clone() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + --- REMOVED METHOD: PUBLIC(-) FINAL(-) com.google.protobuf.UnknownFieldSet getUnknownFields() +***! MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder clone() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + --- REMOVED METHOD: PUBLIC(-) FINAL(-) com.google.protobuf.UnknownFieldSet getUnknownFields() +***! MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder clone() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + --- REMOVED METHOD: PUBLIC(-) FINAL(-) com.google.protobuf.UnknownFieldSet getUnknownFields() +***! MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder clone() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + --- REMOVED METHOD: PUBLIC(-) FINAL(-) com.google.protobuf.UnknownFieldSet getUnknownFields() +***! MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder clone() + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + ---! REMOVED METHOD: PUBLIC(-) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder setClientTls(byte[], byte[]) diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..7997942ae63 --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-metrics.txt @@ -0,0 +1,8 @@ +Comparing source compatibility of against +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.InstrumentSelector (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getInstrumentUnit() + +++ NEW ANNOTATION: javax.annotation.Nullable +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.InstrumentSelectorBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.InstrumentSelectorBuilder setUnit(java.lang.String) diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk.txt b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.24.0_vs_1.23.1/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-api.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-context.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..79c1f8fe85c --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.kotlin.ContextExtensionsKt (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED ANNOTATION: kotlin.Metadata + === UNCHANGED ELEMENT: xi=48 + *** MODIFIED ELEMENT: mv=1,8,0 (<- 1,6,0) + === UNCHANGED ELEMENT: k=2 + === UNCHANGED ELEMENT: d1=οΏ½οΏ½ οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½Β¨οΏ½οΏ½ + === UNCHANGED ELEMENT: d2=asContextElement,Lkotlin/coroutines/CoroutineContext;,Lio/opentelemetry/context/Context;,Lio/opentelemetry/context/ImplicitContextKeyed;,getOpenTelemetryContext,opentelemetry-extension-kotlin diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..8fa41fc79df --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,12 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.SamplingManagerGrpc (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) FINAL(+) io.grpc.ServerServiceDefinition bindService(io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.SamplingManagerGrpc$AsyncService) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) STATIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.SamplingManagerGrpc$AsyncService (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) void getSamplingStrategy(io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters, io.grpc.stub.StreamObserver) +*** MODIFIED CLASS: PUBLIC ABSTRACT STATIC io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.SamplingManagerGrpc$SamplingManagerImplBase (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.SamplingManagerGrpc$AsyncService + --- REMOVED METHOD: PUBLIC(-) void getSamplingStrategy(io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters, io.grpc.stub.StreamObserver) diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk.txt b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.25.0_vs_1.24.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-api.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-context.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..48d81fc8131 --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..6cfcc87ed85 --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,13 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..49d864f550e --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,6 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.opentracingshim.OpenTracingShim (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentracing.Tracer createTracerShim(io.opentelemetry.api.OpenTelemetry) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentracing.Tracer createTracerShim(io.opentelemetry.api.trace.TracerProvider, io.opentelemetry.context.propagation.TextMapPropagator, io.opentelemetry.context.propagation.TextMapPropagator) diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..5d00da675b8 --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..b25be9033f2 --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader create(io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector, io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Aggregation getDefaultAggregation(io.opentelemetry.sdk.metrics.InstrumentType) diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk.txt b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.26.0_vs_1.25.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-api.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-api.txt new file mode 100644 index 00000000000..a6a410d2b61 --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-api.txt @@ -0,0 +1,68 @@ +Comparing source compatibility of against ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.Logger (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder logRecordBuilder() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LoggerBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.Logger build() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LoggerBuilder setInstrumentationVersion(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LoggerBuilder setSchemaUrl(java.lang.String) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LoggerProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.Logger get(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LoggerBuilder loggerBuilder(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.logs.LoggerProvider noop() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void emit() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAllAttributes(io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(io.opentelemetry.api.common.AttributeKey, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setBody(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setContext(io.opentelemetry.context.Context) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setObservedTimestamp(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setObservedTimestamp(java.time.Instant) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setSeverity(io.opentelemetry.api.logs.Severity) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setSeverityText(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setTimestamp(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.LogRecordBuilder setTimestamp(java.time.Instant) ++++ NEW ENUM: PUBLIC(+) FINAL(+) io.opentelemetry.api.logs.Severity (compatible) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.constant.Constable + +++ NEW INTERFACE: java.lang.Comparable + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.Enum + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity WARN2 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity WARN3 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity WARN4 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity INFO + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity TRACE2 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity DEBUG4 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity DEBUG3 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity TRACE4 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity TRACE3 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity ERROR + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity FATAL + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity TRACE + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity FATAL2 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity FATAL3 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity ERROR2 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity ERROR3 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity ERROR4 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity DEBUG2 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity INFO3 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity DEBUG + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity INFO2 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity WARN + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity INFO4 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity UNDEFINED_SEVERITY_NUMBER + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.logs.Severity FATAL4 + +++ NEW METHOD: PUBLIC(+) int getSeverityNumber() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.logs.Severity valueOf(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.logs.Severity[] values() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.OpenTelemetry (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LoggerProvider getLogsBridge() diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-context.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..0a45f10aab2 --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,45 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter getDefault() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder addHeader(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setClientTls(byte[], byte[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setCompression(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setEndpoint(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setMeterProvider(io.opentelemetry.api.metrics.MeterProvider) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setTrustedCertificates(byte[]) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter getDefault() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder addHeader(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setChannel(io.grpc.ManagedChannel) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setClientTls(byte[], byte[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setCompression(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setEndpoint(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setMeterProvider(io.opentelemetry.api.metrics.MeterProvider) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setSslContext(javax.net.ssl.SSLContext, javax.net.ssl.X509TrustManager) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setTrustedCertificates(byte[]) diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..f20edb7e178 --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,49 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder clone() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$OperationSamplingStrategy$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder clone() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$PerOperationSamplingStrategies$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder clone() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$ProbabilisticSamplingStrategy$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder clone() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$RateLimitingSamplingStrategy$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder clone() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyParameters$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) +*** MODIFIED CLASS: PUBLIC STATIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder addRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder clearField(com.google.protobuf.Descriptors$FieldDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder clearOneof(com.google.protobuf.Descriptors$OneofDescriptor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder clone() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder setField(com.google.protobuf.Descriptors$FieldDescriptor, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling$SamplingStrategyResponse$Builder setRepeatedField(com.google.protobuf.Descriptors$FieldDescriptor, int, java.lang.Object) diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..58b71a57cdd --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,124 @@ +Comparing source compatibility of against ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.data.Body (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String asString() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.data.Body empty() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.data.Body$Type getType() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.data.Body string(java.lang.String) ++++ NEW ENUM: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.logs.data.Body$Type (compatible) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.constant.Constable + +++ NEW INTERFACE: java.lang.Comparable + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.Enum + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.logs.data.Body$Type STRING + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.logs.data.Body$Type EMPTY + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.data.Body$Type valueOf(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.data.Body$Type[] values() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.data.LogRecordData (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.Attributes getAttributes() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.data.Body getBody() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.InstrumentationScopeInfo getInstrumentationScopeInfo() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) long getObservedTimestampEpochNanos() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.resources.Resource getResource() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.logs.Severity getSeverity() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getSeverityText() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.trace.SpanContext getSpanContext() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) long getTimestampEpochNanos() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getTotalAttributeCount() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: io.opentelemetry.sdk.logs.LogRecordProcessor + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder builder(io.opentelemetry.sdk.logs.export.LogRecordExporter) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode forceFlush() + +++ NEW METHOD: PUBLIC(+) void onEmit(io.opentelemetry.context.Context, io.opentelemetry.sdk.logs.ReadWriteLogRecord) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setExporterTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setExporterTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setMaxExportBatchSize(int) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setMaxQueueSize(int) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setMeterProvider(io.opentelemetry.api.metrics.MeterProvider) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setScheduleDelay(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setScheduleDelay(java.time.Duration) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.export.LogRecordExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) void close() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.export.LogRecordExporter composite(io.opentelemetry.sdk.logs.export.LogRecordExporter[]) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.export.LogRecordExporter composite(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: io.opentelemetry.sdk.logs.LogRecordProcessor + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.LogRecordProcessor create(io.opentelemetry.sdk.logs.export.LogRecordExporter) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode forceFlush() + +++ NEW METHOD: PUBLIC(+) void onEmit(io.opentelemetry.context.Context, io.opentelemetry.sdk.logs.ReadWriteLogRecord) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.LogLimits (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.LogLimitsBuilder builder() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.LogLimits getDefault() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getMaxAttributeValueLength() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getMaxNumberOfAttributes() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.LogLimitsBuilder toBuilder() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.LogLimitsBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.LogLimits build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.LogLimitsBuilder setMaxAttributeValueLength(int) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.LogLimitsBuilder setMaxNumberOfAttributes(int) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.LogRecordProcessor (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) void close() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.LogRecordProcessor composite(io.opentelemetry.sdk.logs.LogRecordProcessor[]) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.LogRecordProcessor composite(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode forceFlush() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void onEmit(io.opentelemetry.context.Context, io.opentelemetry.sdk.logs.ReadWriteLogRecord) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.ReadWriteLogRecord (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.ReadWriteLogRecord setAttribute(io.opentelemetry.api.common.AttributeKey, java.lang.Object) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.logs.data.LogRecordData toLogRecordData() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.SdkLoggerProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder builder() + +++ NEW METHOD: PUBLIC(+) void close() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode forceFlush() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.Logger get(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LoggerBuilder loggerBuilder(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder addLogRecordProcessor(io.opentelemetry.sdk.logs.LogRecordProcessor) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProvider build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder setClock(io.opentelemetry.sdk.common.Clock) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder setLogLimits(java.util.function.Supplier) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder setResource(io.opentelemetry.sdk.resources.Resource) diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..aa71c04fb1c --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,56 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.HistogramPointAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.HistogramPointAssert hasBucketBoundaries(double[], org.assertj.core.data.Offset) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributes(io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributes(java.util.Map$Entry[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributesSatisfying(java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributesSatisfying(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributesSatisfying(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributesSatisfyingExactly(io.opentelemetry.sdk.testing.assertj.AttributeAssertion[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasAttributesSatisfyingExactly(java.lang.Iterable) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBody(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasInstrumentationScope(io.opentelemetry.sdk.common.InstrumentationScopeInfo) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasObservedTimestamp(long) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasResource(io.opentelemetry.sdk.resources.Resource) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasSeverity(io.opentelemetry.api.logs.Severity) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasSeverityText(java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasSpanContext(io.opentelemetry.api.trace.SpanContext) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasTimestamp(long) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasTotalAttributeCount(int) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert assertThat(io.opentelemetry.sdk.logs.data.LogRecordData) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter create() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode export(java.util.Collection) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode flush() + +++ NEW METHOD: PUBLIC(+) java.util.List getFinishedLogRecordItems() + +++ NEW METHOD: PUBLIC(+) void reset() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder builder() ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) STATIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW CONSTRUCTOR: PUBLIC(+) TestLogRecordData$Builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData build() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setAttributes(io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setBody(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setInstrumentationScopeInfo(io.opentelemetry.sdk.common.InstrumentationScopeInfo) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setObservedTimestamp(java.time.Instant) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setObservedTimestamp(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setResource(io.opentelemetry.sdk.resources.Resource) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setSeverity(io.opentelemetry.api.logs.Severity) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setSeverityText(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setSpanContext(io.opentelemetry.api.trace.SpanContext) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setTimestamp(java.time.Instant) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setTimestamp(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setTotalAttributeCount(int) diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk.txt b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..2a24e0786f8 --- /dev/null +++ b/docs/apidiffs/1.27.0_vs_1.26.0/opentelemetry-sdk.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.OpenTelemetrySdk (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LoggerProvider getLogsBridge() diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-api.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-context.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..d7bd0f79772 --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.exporter.jaeger.thrift.JaegerThriftSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.exporter.jaeger.thrift.JaegerThriftSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..8268b5941c9 --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..d5b027afc0f --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setRetryPolicy(io.opentelemetry.sdk.common.export.RetryPolicy) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setRetryPolicy(io.opentelemetry.sdk.common.export.RetryPolicy) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setRetryPolicy(io.opentelemetry.sdk.common.export.RetryPolicy) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setRetryPolicy(io.opentelemetry.sdk.common.export.RetryPolicy) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setRetryPolicy(io.opentelemetry.sdk.common.export.RetryPolicy) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setRetryPolicy(io.opentelemetry.sdk.common.export.RetryPolicy) diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..1aea53eba09 --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.kotlin.ContextExtensionsKt (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED ANNOTATION: kotlin.Metadata + === UNCHANGED ELEMENT: xi=48 + *** MODIFIED ELEMENT: mv=1,9,0 (<- 1,8,0) + === UNCHANGED ELEMENT: k=2 + === UNCHANGED ELEMENT: d1=οΏ½οΏ½ οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½Β¨οΏ½οΏ½ + === UNCHANGED ELEMENT: d2=asContextElement,Lkotlin/coroutines/CoroutineContext;,Lio/opentelemetry/context/Context;,Lio/opentelemetry/context/ImplicitContextKeyed;,getOpenTelemetryContext,opentelemetry-extension-kotlin diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..69f41370707 --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-common.txt @@ -0,0 +1,18 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder builder() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) double getBackoffMultiplier() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.RetryPolicy getDefault() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.time.Duration getInitialBackoff() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getMaxAttempts() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.time.Duration getMaxBackoff() ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) STATIC(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.RetryPolicy build() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder setBackoffMultiplier(double) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder setInitialBackoff(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder setMaxAttempts(int) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder setMaxBackoff(java.time.Duration) diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..8e54a1a51a4 --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,30 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder builder() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.OpenTelemetrySdk getOpenTelemetrySdk() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk initialize() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addLoggerProviderCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addLogRecordExporterCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addMeterProviderCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addMetricExporterCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addPropagatorCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addPropertiesCustomizer(java.util.function.Function) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addPropertiesSupplier(java.util.function.Supplier) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addResourceCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addSamplerCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addSpanExporterCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addTracerProviderCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder disableShutdownHook() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder setResultAsGlobal() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder setServiceClassLoader(java.lang.ClassLoader) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.autoconfigure.ResourceConfiguration (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.resources.Resource createEnvironmentResource() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.resources.Resource createEnvironmentResource(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..87bf66ea108 --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector lowMemory() diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk.txt b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.28.0_vs_1.27.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-api.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-context.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..67aeae99e2f --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,25 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder toBuilder() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder toBuilder() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder toBuilder() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder toBuilder() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder toBuilder() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder toBuilder() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..8892a49bef6 --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-common.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.common.export.RetryPolicy (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder toBuilder() diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..836280b5bed --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder addResource(io.opentelemetry.sdk.resources.Resource) diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..f504766328b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder addResource(io.opentelemetry.sdk.resources.Resource) diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..28a32e83f11 --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasResourceSatisfying(java.util.function.Consumer) diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..7cc166e26ed --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.SdkTracerProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.SdkTracerProviderBuilder addResource(io.opentelemetry.sdk.resources.Resource) diff --git a/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk.txt b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.29.0_vs_1.28.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-api.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-context.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..ec040faaf8b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,10 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.logging.LoggingMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.logging.LoggingSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC io.opentelemetry.exporter.logging.SystemOutLogRecordExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..772e014e5a0 --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..dff1c969ed8 --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.ViewBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.ViewBuilder setAttributeFilter(java.util.Set) diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk.txt b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.0_vs_1.29.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-api.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-context.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk.txt b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.30.1_vs_1.30.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-api.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-context.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-common.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-common.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..cc95503822e --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-common.txt @@ -0,0 +1,11 @@ +Comparing source compatibility of against ++++ NEW ENUM: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.common.export.MemoryMode (compatible) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.constant.Constable + +++ NEW INTERFACE: java.lang.Comparable + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.Enum + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.MemoryMode REUSABLE_DATA + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.MemoryMode IMMUTABLE_DATA + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.MemoryMode valueOf(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.MemoryMode[] values() diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..11010a0b08b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-logs.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.ReadWriteLogRecord (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.ReadWriteLogRecord setAllAttributes(io.opentelemetry.api.common.Attributes) diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..6cf519e2823 --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-metrics.txt @@ -0,0 +1,21 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.CollectionRegistration (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.util.Collection collectAllMetrics() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.export.CollectionRegistration noop() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.MetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.MemoryMode getMemoryMode() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.export.MetricProducer (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.Collection produce(io.opentelemetry.sdk.resources.Resource) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.MetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.MemoryMode getMemoryMode() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.MemoryMode getMemoryMode() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder registerMetricProducer(io.opentelemetry.sdk.metrics.export.MetricProducer) diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..24ed11618d8 --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-testing.txt @@ -0,0 +1,12 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReaderBuilder builder() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.MemoryMode getMemoryMode() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReaderBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReaderBuilder setAggregationTemporalitySelector(io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReaderBuilder setDefaultAggregationSelector(io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricReaderBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk.txt b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.31.0_vs_1.30.1/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-api.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-api.txt new file mode 100644 index 00000000000..faa8d3cf893 --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-api.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleHistogramBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.DoubleHistogramBuilder setExplicitBucketBoundariesAdvice(java.util.List) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongHistogramBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.LongHistogramBuilder setExplicitBucketBoundariesAdvice(java.util.List) diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-context.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..afee563c67e --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,13 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setMeterProvider(java.util.function.Supplier) diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..e8f3d45d4f7 --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.junit4.OpenTelemetryRule (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) void clearLogRecords() + +++ NEW METHOD: PUBLIC(+) java.util.List getLogRecords() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) void clearLogRecords() + +++ NEW METHOD: PUBLIC(+) java.util.List getLogRecords() diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk.txt b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.32.0_vs_1.31.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-api.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-context.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..7c0ed9b5e5f --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,25 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setConnectTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setConnectTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setHeaders(java.util.function.Supplier>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setConnectTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setConnectTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setHeaders(java.util.function.Supplier>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setConnectTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setConnectTimeout(java.time.Duration) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setHeaders(java.util.function.Supplier>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setHeaders(java.util.function.Supplier>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setHeaders(java.util.function.Supplier>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setHeaders(java.util.function.Supplier>) diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..1945e8c996d --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of against +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.kotlin.ContextExtensionsKt (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED ANNOTATION: kotlin.Metadata + === UNCHANGED ELEMENT: xi=48 + *** MODIFIED ELEMENT: mv=1,6,0 (<- 1,9,0) + === UNCHANGED ELEMENT: k=2 + === UNCHANGED ELEMENT: d1=οΏ½οΏ½ οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½οΏ½ οΏ½οΏ½οΏ½οΏ½0οΏ½*οΏ½0οΏ½Β¨οΏ½οΏ½ + === UNCHANGED ELEMENT: d2=asContextElement,Lkotlin/coroutines/CoroutineContext;,Lio/opentelemetry/context/Context;,Lio/opentelemetry/context/ImplicitContextKeyed;,getOpenTelemetryContext,opentelemetry-extension-kotlin diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..9f4a3fbb37a --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLogRecordProcessorCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addSpanProcessorCustomizer(java.util.function.BiFunction) diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..c4389093f93 --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLogRecordProcessorCustomizer(java.util.function.BiFunction) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addSpanProcessorCustomizer(java.util.function.BiFunction) diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..c1e98158b3d --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.testing.assertj.AbstractPointAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + GENERIC TEMPLATES: === PointAssertT:io.opentelemetry.sdk.testing.assertj.AbstractPointAssert, === PointT:io.opentelemetry.sdk.metrics.data.PointData + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.AbstractPointAssert hasAttributesSatisfying(java.util.function.Consumer) diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk.txt b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.33.0_vs_1.32.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-api.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-context.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..f03b01723c1 --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,12 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder setExportUnsampledSpans(boolean) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.SimpleSpanProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder builder(io.opentelemetry.sdk.trace.export.SpanExporter) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.SimpleSpanProcessor build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder setExportUnsampledSpans(boolean) diff --git a/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk.txt b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.0_vs_1.33.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-api.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-context.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-jaeger-thrift.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-jaeger-thrift.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-jaeger-thrift.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-jaeger.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-jaeger.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-jaeger.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk.txt b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.34.1_vs_1.34.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-api.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-context.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-common.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..479860c48b0 --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + === UNCHANGED METHOD: PUBLIC io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setEncoder(zipkin2.codec.BytesEncoder) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setEncoder(zipkin2.reporter.BytesEncoder) + === UNCHANGED METHOD: PUBLIC io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setSender(zipkin2.reporter.Sender) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setSender(zipkin2.reporter.BytesMessageSender) diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-common.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk.txt b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.35.0_vs_1.34.1/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-api.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-context.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..36d0f38ffc9 --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,22 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setProxyOptions(io.opentelemetry.sdk.common.export.ProxyOptions) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setProxyOptions(io.opentelemetry.sdk.common.export.ProxyOptions) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setProxy(io.opentelemetry.sdk.common.export.ProxyOptions) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setConnectTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setConnectTimeout(java.time.Duration) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setConnectTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setConnectTimeout(java.time.Duration) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setConnectTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setConnectTimeout(java.time.Duration) diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..80cfb0c6678 --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-common.txt @@ -0,0 +1,8 @@ +Comparing source compatibility of against ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.common.export.ProxyOptions (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.ProxyOptions create(java.net.ProxySelector) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.ProxyOptions create(java.net.InetSocketAddress) + +++ NEW METHOD: PUBLIC(+) java.net.ProxySelector getProxySelector() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..c464bbdd2e2 --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addMetricReaderCustomizer(java.util.function.BiFunction) diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..f9bf6463d2c --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +**** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + ===* UNCHANGED METHOD: PUBLIC SYNTHETIC (<- NON_SYNTHETIC) BRIDGE (<- NON_BRIDGE) io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer addLogRecordProcessorCustomizer(java.util.function.BiFunction(<- )) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder addMetricReaderCustomizer(java.util.function.BiFunction) diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk.txt b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.36.0_vs_1.35.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-api.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-api.txt new file mode 100644 index 00000000000..815a9fed06c --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-api.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.trace.Span (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.trace.Span addLink(io.opentelemetry.api.trace.SpanContext) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.trace.Span addLink(io.opentelemetry.api.trace.SpanContext, io.opentelemetry.api.common.Attributes) diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-context.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..d8fcd994b8d --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.MemoryMode getMemoryMode() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.export.MemoryMode getMemoryMode() diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..2039c1c6e68 --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.LogRecordExporter getLogRecordExporter() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.LogRecordExporter getLogRecordExporter() diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..52678bd9ba6 --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.BatchSpanProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.SpanExporter getSpanExporter() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.SimpleSpanProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.SpanExporter getSpanExporter() diff --git a/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk.txt b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.37.0_vs_1.36.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-api.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-api.txt new file mode 100644 index 00000000000..d050fbe201a --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-api.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of against ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.metrics.DoubleGauge (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void set(double) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void set(double, io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void set(double, io.opentelemetry.api.common.Attributes, io.opentelemetry.context.Context) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleGaugeBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.DoubleGauge build() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.metrics.LongGauge (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void set(long) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void set(long, io.opentelemetry.api.common.Attributes) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void set(long, io.opentelemetry.api.common.Attributes, io.opentelemetry.context.Context) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongGaugeBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.LongGauge build() diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-context.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..71f05afd4d1 --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-common.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.common.Clock (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) long now(boolean) diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..ef9c86f56b8 --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,10 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.lang.String asString(io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.lang.String asString(io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector) +*** MODIFIED ENUM: PUBLIC FINAL io.opentelemetry.sdk.metrics.InstrumentType (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.metrics.InstrumentType GAUGE diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..722ee3a950f --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of against +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.trace.ReadableSpan (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.common.Attributes getAttributes() diff --git a/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk.txt b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.38.0_vs_1.37.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-api.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-api.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-context.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-context.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..35bb9f3e97e --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of against +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setMemoryMode(io.opentelemetry.sdk.common.export.MemoryMode) diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk.txt b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..df26146497b --- /dev/null +++ b/docs/apidiffs/1.39.0_vs_1.38.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of against +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-api.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-api.txt new file mode 100644 index 00000000000..ab4fa9fb021 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.40.0.jar against opentelemetry-api-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-context.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-context.txt new file mode 100644 index 00000000000..0e0c373df57 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.40.0.jar against opentelemetry-context-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..8ebecc326a1 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.40.0.jar against opentelemetry-exporter-common-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..a422f20359e --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.40.0.jar against opentelemetry-exporter-logging-otlp-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..5492a866052 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.40.0.jar against opentelemetry-exporter-logging-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..74fcc72b9de --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.40.0.jar against opentelemetry-exporter-otlp-common-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..dc0babb48fd --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.40.0.jar against opentelemetry-exporter-otlp-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..f02a4d71f87 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.40.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..385c556dfb6 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.40.0.jar against opentelemetry-exporter-sender-jdk-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..d325d58ea5d --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.40.0.jar against opentelemetry-exporter-sender-okhttp-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..8ee1e891c91 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.40.0.jar against opentelemetry-exporter-zipkin-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..c038bdf240a --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.40.0.jar against opentelemetry-extension-kotlin-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..45091f1a06c --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.40.0.jar against opentelemetry-extension-trace-propagators-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..06013311639 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.40.0.jar against opentelemetry-opentracing-shim-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..97c399bb7b7 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.40.0.jar against opentelemetry-sdk-common-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..d6707767630 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.40.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..72c89c9f34c --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.40.0.jar against opentelemetry-sdk-extension-autoconfigure-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..edf13347673 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.40.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..04ad97a31ae --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.40.0.jar against opentelemetry-sdk-logs-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..b4b81d47fa6 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.40.0.jar against opentelemetry-sdk-metrics-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..3eba71a9768 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.40.0.jar against opentelemetry-sdk-testing-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..38bc5b93520 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.40.0.jar against opentelemetry-sdk-trace-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk.txt b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..6eb2fc4ff19 --- /dev/null +++ b/docs/apidiffs/1.40.0_vs_1.39.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.40.0.jar against opentelemetry-sdk-1.39.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-api.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-api.txt new file mode 100644 index 00000000000..afe8b67a002 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.41.0.jar against opentelemetry-api-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-context.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-context.txt new file mode 100644 index 00000000000..02ae6fcdd0d --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.41.0.jar against opentelemetry-context-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..d7c1e865d7f --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.41.0.jar against opentelemetry-exporter-common-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..05e56d6ba4e --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.41.0.jar against opentelemetry-exporter-logging-otlp-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..8015b7b7ae0 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.41.0.jar against opentelemetry-exporter-logging-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..3c388babdcc --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.41.0.jar against opentelemetry-exporter-otlp-common-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..6858a24a84d --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.41.0.jar against opentelemetry-exporter-otlp-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..64d2a51493f --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.41.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..e84cf24859a --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.41.0.jar against opentelemetry-exporter-sender-jdk-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..d5e2bdb2a72 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.41.0.jar against opentelemetry-exporter-sender-okhttp-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..a6290a1aa53 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.41.0.jar against opentelemetry-exporter-zipkin-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..8f6c4acd90c --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.41.0.jar against opentelemetry-extension-kotlin-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..0be9d14cee0 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.41.0.jar against opentelemetry-extension-trace-propagators-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..68d4997cb1b --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.41.0.jar against opentelemetry-opentracing-shim-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..cf51f2f56ef --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-common.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.41.0.jar against opentelemetry-sdk-common-1.40.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.common.CompletableResultCode (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode failExceptionally(java.lang.Throwable) + +++ NEW METHOD: PUBLIC(+) java.lang.Throwable getFailureThrowable() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.CompletableResultCode ofExceptionalFailure(java.lang.Throwable) diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..55b6f8964c7 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.41.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..99b5916941d --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.41.0.jar against opentelemetry-sdk-extension-autoconfigure-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..08fc54d6789 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.41.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..d6449ab8f5f --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.41.0.jar against opentelemetry-sdk-logs-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..714c909d030 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.41.0.jar against opentelemetry-sdk-metrics-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..7db61bd614f --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.41.0.jar against opentelemetry-sdk-testing-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..077d6ad7ed2 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.41.0.jar against opentelemetry-sdk-trace-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk.txt b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..b2a1b0452f8 --- /dev/null +++ b/docs/apidiffs/1.41.0_vs_1.40.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.41.0.jar against opentelemetry-sdk-1.40.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-api.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-api.txt new file mode 100644 index 00000000000..3a96056c4f1 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-api.txt @@ -0,0 +1,41 @@ +Comparing source compatibility of opentelemetry-api-1.42.0.jar against opentelemetry-api-1.41.0.jar ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.KeyValue (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getKey() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.Value getValue() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.KeyValue of(java.lang.String, io.opentelemetry.api.common.Value) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.Value (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + GENERIC TEMPLATES: +++ T:java.lang.Object + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String asString() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.ValueType getType() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Object getValue() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value of(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value of(boolean) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value of(long) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value of(double) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value of(byte[]) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value>> of(io.opentelemetry.api.common.Value[]) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value>> of(java.util.List>) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value> of(io.opentelemetry.api.common.KeyValue[]) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value> of(java.util.Map>) ++++ NEW ENUM: PUBLIC(+) FINAL(+) io.opentelemetry.api.common.ValueType (compatible) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.constant.Constable + +++ NEW INTERFACE: java.lang.Comparable + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.Enum + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType BYTES + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType ARRAY + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType KEY_VALUE_LIST + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType STRING + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType DOUBLE + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType BOOLEAN + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType LONG + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.ValueType valueOf(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.ValueType[] values() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.logs.LogRecordBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setBody(io.opentelemetry.api.common.Value) diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-context.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-context.txt new file mode 100644 index 00000000000..4235de83b07 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.42.0.jar against opentelemetry-context-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..b9516eeee56 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.42.0.jar against opentelemetry-exporter-common-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..c20575d8213 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.42.0.jar against opentelemetry-exporter-logging-otlp-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..742accf915d --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.42.0.jar against opentelemetry-exporter-logging-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..65d41b6ec4e --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.42.0.jar against opentelemetry-exporter-otlp-common-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..217a061f337 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.42.0.jar against opentelemetry-exporter-otlp-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..761405711f8 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.42.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..c1b86871894 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.42.0.jar against opentelemetry-exporter-sender-jdk-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..8fee739b86d --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.42.0.jar against opentelemetry-exporter-sender-okhttp-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..29c5e24ef73 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.42.0.jar against opentelemetry-exporter-zipkin-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..74011673f81 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.42.0.jar against opentelemetry-extension-kotlin-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..5a5b46fc554 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.42.0.jar against opentelemetry-extension-trace-propagators-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..459a5cbb037 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.42.0.jar against opentelemetry-opentracing-shim-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..15d384cb970 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.42.0.jar against opentelemetry-sdk-common-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..507709301e4 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.42.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..bc405d103f5 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.42.0.jar against opentelemetry-sdk-extension-autoconfigure-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..debfbaf6acc --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.42.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..44d010071ed --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,15 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.42.0.jar against opentelemetry-sdk-logs-1.41.0.jar +=== UNCHANGED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.data.Body (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + === UNCHANGED METHOD: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.data.Body$Type getType() + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED ENUM: PUBLIC STATIC FINAL io.opentelemetry.sdk.logs.data.Body$Type (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.data.LogRecordData (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + === UNCHANGED METHOD: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.data.Body getBody() + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.common.Value getBodyValue() + +++ NEW ANNOTATION: javax.annotation.Nullable diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..2d8dc8fe717 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.42.0.jar against opentelemetry-sdk-metrics-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..be9647f8b89 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,26 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.42.0.jar against opentelemetry-sdk-testing-1.41.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBody(io.opentelemetry.api.common.Value) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, long) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, double) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, boolean) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, java.lang.String[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, long[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, double[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, boolean[]) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(java.lang.String, io.opentelemetry.api.common.Value) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasBodyField(io.opentelemetry.api.common.AttributeKey, java.lang.Object) + GENERIC TEMPLATES: +++ T:java.lang.Object +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.testing.logs.TestLogRecordData (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.data.Body getBody() + +++ NEW ANNOTATION: java.lang.Deprecated + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.common.Value getBodyValue() + +++ NEW ANNOTATION: javax.annotation.Nullable +**** MODIFIED CLASS: PUBLIC ABSTRACT STATIC io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) NON_ABSTRACT (<- ABSTRACT) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setBody(io.opentelemetry.sdk.logs.data.Body) + +++ NEW ANNOTATION: java.lang.Deprecated + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.testing.logs.TestLogRecordData$Builder setBodyValue(io.opentelemetry.api.common.Value) diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..6812c3e1cd1 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.42.0.jar against opentelemetry-sdk-trace-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk.txt b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..78c1aa54f96 --- /dev/null +++ b/docs/apidiffs/1.42.0_vs_1.41.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.42.0.jar against opentelemetry-sdk-1.41.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-api.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-api.txt new file mode 100644 index 00000000000..b11bbc44363 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-api.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of opentelemetry-api-1.43.0.jar against opentelemetry-api-1.42.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.baggage.Baggage (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.baggage.BaggageEntry getEntry(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-context.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-context.txt new file mode 100644 index 00000000000..f01838a847d --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-context.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-context-1.43.0.jar against opentelemetry-context-1.42.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.context.Context (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.util.concurrent.ScheduledExecutorService taskWrapping(java.util.concurrent.ScheduledExecutorService) diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..4f61afb8eb1 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.43.0.jar against opentelemetry-exporter-common-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..2df260f443c --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.43.0.jar against opentelemetry-exporter-logging-otlp-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..486843d7ca4 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.43.0.jar against opentelemetry-exporter-logging-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..67ed4e71728 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.43.0.jar against opentelemetry-exporter-otlp-common-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..4c3afc0f107 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.43.0.jar against opentelemetry-exporter-otlp-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..f9e1ee6e790 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.43.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..6c717fd3eec --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.43.0.jar against opentelemetry-exporter-sender-jdk-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..3517b983a81 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.43.0.jar against opentelemetry-exporter-sender-okhttp-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..bad70283ecf --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.43.0.jar against opentelemetry-exporter-zipkin-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..a734b74463d --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.43.0.jar against opentelemetry-extension-kotlin-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..66ba7fd51af --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.43.0.jar against opentelemetry-extension-trace-propagators-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..f2bd7607ce4 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.43.0.jar against opentelemetry-opentracing-shim-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..c6c737f6f6f --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.43.0.jar against opentelemetry-sdk-common-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..7e2e0155064 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.43.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..3d38546b923 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.43.0.jar against opentelemetry-sdk-extension-autoconfigure-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..b58ac546dc1 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.43.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..70fcf9a7e92 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.43.0.jar against opentelemetry-sdk-logs-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..a6a67209348 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.43.0.jar against opentelemetry-sdk-metrics-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..1b0720243f5 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.43.0.jar against opentelemetry-sdk-testing-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..dc14e4e2560 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.43.0.jar against opentelemetry-sdk-trace-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk.txt b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..5530c784a30 --- /dev/null +++ b/docs/apidiffs/1.43.0_vs_1.42.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.43.0.jar against opentelemetry-sdk-1.42.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-api.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-api.txt new file mode 100644 index 00000000000..9e70186c29f --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.44.0.jar against opentelemetry-api-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-context.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-context.txt new file mode 100644 index 00000000000..a0b2417ea3d --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.44.0.jar against opentelemetry-context-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..c33ced08682 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.44.0.jar against opentelemetry-exporter-common-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..3384b7a6a8f --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.44.0.jar against opentelemetry-exporter-logging-otlp-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..e0995445a2d --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.44.0.jar against opentelemetry-exporter-logging-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..d5f44a6ee30 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.44.0.jar against opentelemetry-exporter-otlp-common-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..6b9b06b34dc --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.44.0.jar against opentelemetry-exporter-otlp-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..da2b18615cf --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.44.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..fcd6cdf22e2 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.44.0.jar against opentelemetry-exporter-sender-jdk-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..884e240ae22 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.44.0.jar against opentelemetry-exporter-sender-okhttp-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..b2241eeb636 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.44.0.jar against opentelemetry-exporter-zipkin-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..8044b8f8eec --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.44.0.jar against opentelemetry-extension-kotlin-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..da2fff0fb55 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.44.0.jar against opentelemetry-extension-trace-propagators-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..5a3e21de838 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.44.0.jar against opentelemetry-opentracing-shim-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..5ae9baeb962 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.44.0.jar against opentelemetry-sdk-common-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..2a9f6dfbf2b --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.44.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..227dd95136c --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.44.0.jar against opentelemetry-sdk-extension-autoconfigure-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..a35f25ac548 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.44.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..8605a4468ed --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.44.0.jar against opentelemetry-sdk-logs-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..985d2734842 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,16 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.44.0.jar against opentelemetry-sdk-metrics-1.43.0.jar ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector defaultCardinalityLimitSelector() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getCardinalityLimit(io.opentelemetry.sdk.metrics.InstrumentType) + +++ NEW ANNOTATION: java.lang.FunctionalInterface +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder registerMetricReader(io.opentelemetry.sdk.metrics.export.MetricReader, io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector) +*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.View (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) ABSTRACT int getCardinalityLimit() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.ViewBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.sdk.metrics.ViewBuilder setCardinalityLimit(int) diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..8042c5e1b2d --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.44.0.jar against opentelemetry-sdk-testing-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..452716a43f3 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.44.0.jar against opentelemetry-sdk-trace-1.43.0.jar ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.trace.data.ExceptionEventData (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: io.opentelemetry.sdk.trace.data.EventData + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.trace.data.ExceptionEventData create(long, java.lang.Throwable, io.opentelemetry.api.common.Attributes, int) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Throwable getException() diff --git a/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk.txt b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..333f8c4f5b0 --- /dev/null +++ b/docs/apidiffs/1.44.0_vs_1.43.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.44.0.jar against opentelemetry-sdk-1.43.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-api.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-api.txt new file mode 100644 index 00000000000..227cbe9a7d7 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.44.1.jar against opentelemetry-api-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-context.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-context.txt new file mode 100644 index 00000000000..1ba6fac89b4 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.44.1.jar against opentelemetry-context-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..f17cdd1ef90 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.44.1.jar against opentelemetry-exporter-common-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..8b093eaf0aa --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.44.1.jar against opentelemetry-exporter-logging-otlp-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..c60e2be2842 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.44.1.jar against opentelemetry-exporter-logging-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..75bc9a388e8 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.44.1.jar against opentelemetry-exporter-otlp-common-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..c6b8d754b79 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.44.1.jar against opentelemetry-exporter-otlp-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..50b886238aa --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.44.1.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..33c42b914c4 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.44.1.jar against opentelemetry-exporter-sender-jdk-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..9f2ab4ddafb --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.44.1.jar against opentelemetry-exporter-sender-okhttp-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..29340d90453 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.44.1.jar against opentelemetry-exporter-zipkin-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..467a926a409 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.44.1.jar against opentelemetry-extension-kotlin-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..bfcd1605834 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.44.1.jar against opentelemetry-extension-trace-propagators-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..c553192aca9 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.44.1.jar against opentelemetry-opentracing-shim-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..d07f1dadeb8 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.44.1.jar against opentelemetry-sdk-common-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..37aa938da9b --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.44.1.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..750b0e2c27f --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.44.1.jar against opentelemetry-sdk-extension-autoconfigure-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..0643d17dfbb --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.44.1.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..26b4f4b3e5f --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.44.1.jar against opentelemetry-sdk-logs-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..5031b75f9f6 --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.44.1.jar against opentelemetry-sdk-metrics-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..b3c59ff77fd --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.44.1.jar against opentelemetry-sdk-testing-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..2feb43d5d6b --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.44.1.jar against opentelemetry-sdk-trace-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk.txt b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..37868ac312f --- /dev/null +++ b/docs/apidiffs/1.44.1_vs_1.44.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.44.1.jar against opentelemetry-sdk-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-api.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-api.txt new file mode 100644 index 00000000000..bf2bd952ea2 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-api.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-api-1.45.0.jar against opentelemetry-api-1.44.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.trace.SpanBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.trace.SpanBuilder setAttribute(io.opentelemetry.api.common.AttributeKey, int) diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-context.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-context.txt new file mode 100644 index 00000000000..2b2bd88aabf --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.45.0.jar against opentelemetry-context-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..d17a671090b --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.45.0.jar against opentelemetry-exporter-common-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..eacd4d7b06d --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.45.0.jar against opentelemetry-exporter-logging-otlp-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..9a73557f2c7 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.45.0.jar against opentelemetry-exporter-logging-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..26804e02640 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.45.0.jar against opentelemetry-exporter-otlp-common-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..22aba4564a1 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.45.0.jar against opentelemetry-exporter-otlp-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..198cbb3e26a --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.45.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..4dc968493c8 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.45.0.jar against opentelemetry-exporter-sender-jdk-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..6c13a1dedff --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.45.0.jar against opentelemetry-exporter-sender-okhttp-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..fd6e10c1e2c --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.45.0.jar against opentelemetry-exporter-zipkin-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..ab527cf1319 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.45.0.jar against opentelemetry-extension-kotlin-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..03fda39decf --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.45.0.jar against opentelemetry-extension-trace-propagators-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..2b7bfb4bd1c --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.45.0.jar against opentelemetry-opentracing-shim-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..50d8efb7a82 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.45.0.jar against opentelemetry-sdk-common-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..39174b4c385 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.45.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..fe749f6f68c --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.45.0.jar against opentelemetry-sdk-extension-autoconfigure-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..c48ad9ea5c8 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.45.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..b037e09c771 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.45.0.jar against opentelemetry-sdk-logs-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..80ba32106db --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.45.0.jar against opentelemetry-sdk-metrics-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..257565b8a2b --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.45.0.jar against opentelemetry-sdk-testing-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..6f3a3c4eb05 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.45.0.jar against opentelemetry-sdk-trace-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk.txt b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..cb527f8bc36 --- /dev/null +++ b/docs/apidiffs/1.45.0_vs_1.44.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.45.0.jar against opentelemetry-sdk-1.44.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-api.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-api.txt new file mode 100644 index 00000000000..7a52ca19294 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.46.0.jar against opentelemetry-api-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-context.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-context.txt new file mode 100644 index 00000000000..e92b7d7e324 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.46.0.jar against opentelemetry-context-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..81783a03446 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.46.0.jar against opentelemetry-exporter-common-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..df84177a6df --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.46.0.jar against opentelemetry-exporter-logging-otlp-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..58252a79e9f --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.46.0.jar against opentelemetry-exporter-logging-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..42f4bf2f0b7 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.46.0.jar against opentelemetry-exporter-otlp-common-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..91523f25014 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.46.0.jar against opentelemetry-exporter-otlp-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..18e90db15ab --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.46.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..02b60f67e05 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.46.0.jar against opentelemetry-exporter-sender-jdk-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..6b276e92b7a --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.46.0.jar against opentelemetry-exporter-sender-okhttp-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..5ae6fbf884c --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.46.0.jar against opentelemetry-exporter-zipkin-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..b19719fe068 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.46.0.jar against opentelemetry-extension-kotlin-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..45e93a6e2f2 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.46.0.jar against opentelemetry-extension-trace-propagators-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..69f685420e4 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.46.0.jar against opentelemetry-opentracing-shim-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..c9019153006 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.46.0.jar against opentelemetry-sdk-common-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..9afe3d165d4 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.46.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..ba7aa6c29f7 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.46.0.jar against opentelemetry-sdk-extension-autoconfigure-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..ca4395b27eb --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.46.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..20a7acf6688 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,16 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.46.0.jar against opentelemetry-sdk-logs-1.45.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.ReadWriteLogRecord (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.Object getAttribute(io.opentelemetry.api.common.AttributeKey) + +++ NEW ANNOTATION: javax.annotation.Nullable + GENERIC TEMPLATES: +++ T:java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.common.Attributes getAttributes() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.common.Value getBodyValue() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.InstrumentationScopeInfo getInstrumentationScopeInfo() + +++ NEW METHOD: PUBLIC(+) long getObservedTimestampEpochNanos() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.Severity getSeverity() + +++ NEW METHOD: PUBLIC(+) java.lang.String getSeverityText() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.trace.SpanContext getSpanContext() + +++ NEW METHOD: PUBLIC(+) long getTimestampEpochNanos() diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..471c8ad65a8 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.46.0.jar against opentelemetry-sdk-metrics-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..549c10ad82a --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.46.0.jar against opentelemetry-sdk-testing-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..f90c6b4f672 --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.46.0.jar against opentelemetry-sdk-trace-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk.txt b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..e405062aabf --- /dev/null +++ b/docs/apidiffs/1.46.0_vs_1.45.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.46.0.jar against opentelemetry-sdk-1.45.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-api.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-api.txt new file mode 100644 index 00000000000..9b8cec50e3d --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.47.0.jar against opentelemetry-api-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-context.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-context.txt new file mode 100644 index 00000000000..9e926cbce02 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.47.0.jar against opentelemetry-context-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..e9ad6c262dd --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.47.0.jar against opentelemetry-exporter-common-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..19e9e7eee9e --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.47.0.jar against opentelemetry-exporter-logging-otlp-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..f1b1755c49b --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.47.0.jar against opentelemetry-exporter-logging-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..c7ba2d7604b --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.47.0.jar against opentelemetry-exporter-otlp-common-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..c05d0d2101e --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.47.0.jar against opentelemetry-exporter-otlp-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..8df2f05993e --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.47.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..9a32d2426b1 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.47.0.jar against opentelemetry-exporter-sender-jdk-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..c1e4ef30e1e --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.47.0.jar against opentelemetry-exporter-sender-okhttp-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..5728b1c7ebe --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.47.0.jar against opentelemetry-exporter-zipkin-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..d3bb74e7598 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.47.0.jar against opentelemetry-extension-kotlin-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..dd65f61d3ab --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.47.0.jar against opentelemetry-extension-trace-propagators-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..a95c9ed9422 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.47.0.jar against opentelemetry-opentracing-shim-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..490ef238eff --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-common.txt @@ -0,0 +1,8 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.47.0.jar against opentelemetry-sdk-common-1.46.0.jar +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.common.export.RetryPolicy (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.function.Predicate getRetryExceptionPredicate() + +++ NEW ANNOTATION: javax.annotation.Nullable +**** MODIFIED CLASS: PUBLIC ABSTRACT STATIC io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy$RetryPolicyBuilder setRetryExceptionPredicate(java.util.function.Predicate) diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..a6c5cb9acba --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.47.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..e7008c43b4f --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.47.0.jar against opentelemetry-sdk-extension-autoconfigure-1.46.0.jar ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.autoconfigure.EnvironmentResourceProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW CONSTRUCTOR: PUBLIC(+) EnvironmentResourceProvider() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.resources.Resource createResource(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + +++ NEW METHOD: PUBLIC(+) int order() diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..1823240ad66 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.47.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..946e9a23b19 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.47.0.jar against opentelemetry-sdk-logs-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..5a524d47f40 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.47.0.jar against opentelemetry-sdk-metrics-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..37ea274d77d --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.47.0.jar against opentelemetry-sdk-testing-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..5a9f54c51ca --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.47.0.jar against opentelemetry-sdk-trace-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk.txt b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..7e212768780 --- /dev/null +++ b/docs/apidiffs/1.47.0_vs_1.46.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.47.0.jar against opentelemetry-sdk-1.46.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-api.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-api.txt new file mode 100644 index 00000000000..de788f13512 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-api.txt @@ -0,0 +1,8 @@ +Comparing source compatibility of opentelemetry-api-1.48.0.jar against opentelemetry-api-1.47.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.logs.LogRecordBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(java.lang.String, long) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(java.lang.String, double) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(java.lang.String, boolean) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(java.lang.String, int) diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-context.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-context.txt new file mode 100644 index 00000000000..3b24635de3f --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.48.0.jar against opentelemetry-context-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..41b6de6cda4 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.48.0.jar against opentelemetry-exporter-common-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..11d31d04e77 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.48.0.jar against opentelemetry-exporter-logging-otlp-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..a0fdd19735b --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.48.0.jar against opentelemetry-exporter-logging-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..c29eb51623d --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.48.0.jar against opentelemetry-exporter-otlp-common-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..f5dd0481cd3 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.48.0.jar against opentelemetry-exporter-otlp-1.47.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setServiceClassLoader(java.lang.ClassLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setServiceClassLoader(java.lang.ClassLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setServiceClassLoader(java.lang.ClassLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setServiceClassLoader(java.lang.ClassLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setServiceClassLoader(java.lang.ClassLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setServiceClassLoader(java.lang.ClassLoader) diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..e22d383387d --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.48.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..6bdb9162c26 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.48.0.jar against opentelemetry-exporter-sender-jdk-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..7b009644b8e --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.48.0.jar against opentelemetry-exporter-sender-okhttp-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..74111836a9c --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.48.0.jar against opentelemetry-exporter-zipkin-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..ed295a0cfbe --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.48.0.jar against opentelemetry-extension-kotlin-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..adf485b5aea --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.48.0.jar against opentelemetry-extension-trace-propagators-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..ece95e4201f --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.48.0.jar against opentelemetry-opentracing-shim-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..6e9a0615356 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.48.0.jar against opentelemetry-sdk-common-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..bc568f86e98 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.48.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..ed248b7e6a9 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.48.0.jar against opentelemetry-sdk-extension-autoconfigure-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..98b608173eb --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.48.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..db0e655c47c --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.48.0.jar against opentelemetry-sdk-logs-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..83956eff6a5 --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.48.0.jar against opentelemetry-sdk-metrics-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..111061e57cf --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.48.0.jar against opentelemetry-sdk-testing-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..d02ca48d06a --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.48.0.jar against opentelemetry-sdk-trace-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk.txt b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..d5907c73bae --- /dev/null +++ b/docs/apidiffs/1.48.0_vs_1.47.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.48.0.jar against opentelemetry-sdk-1.47.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-api.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-api.txt new file mode 100644 index 00000000000..b2c729b0f7d --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.49.0.jar against opentelemetry-api-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-context.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-context.txt new file mode 100644 index 00000000000..a2d8f2f2c5d --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.49.0.jar against opentelemetry-context-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..2da9ed137ac --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.49.0.jar against opentelemetry-exporter-common-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..ec264c80309 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.49.0.jar against opentelemetry-exporter-logging-otlp-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..79c68b1c3c3 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.49.0.jar against opentelemetry-exporter-logging-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..33945b8d493 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.49.0.jar against opentelemetry-exporter-otlp-common-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..e20c8bb80c1 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.49.0.jar against opentelemetry-exporter-otlp-1.48.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setExecutorService(java.util.concurrent.ExecutorService) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setExecutorService(java.util.concurrent.ExecutorService) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setExecutorService(java.util.concurrent.ExecutorService) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setExecutorService(java.util.concurrent.ExecutorService) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setExecutorService(java.util.concurrent.ExecutorService) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setExecutorService(java.util.concurrent.ExecutorService) diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..150a1efd253 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.49.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..9aafa191f88 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.49.0.jar against opentelemetry-exporter-sender-jdk-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..eb7806a0f6c --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.49.0.jar against opentelemetry-exporter-sender-okhttp-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..70fa0be26b8 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.49.0.jar against opentelemetry-exporter-zipkin-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..fbfd75f18c8 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.49.0.jar against opentelemetry-extension-kotlin-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..4dfcad45757 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.49.0.jar against opentelemetry-extension-trace-propagators-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..ff7bf2a523f --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.49.0.jar against opentelemetry-opentracing-shim-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..67fad35a8da --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.49.0.jar against opentelemetry-sdk-common-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..f2b957076cf --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.49.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..051fd5477d8 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.49.0.jar against opentelemetry-sdk-extension-autoconfigure-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..2db1a2d473b --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.49.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..8014b17b707 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.49.0.jar against opentelemetry-sdk-logs-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..803465ad832 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.49.0.jar against opentelemetry-sdk-metrics-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..95cae875926 --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.49.0.jar against opentelemetry-sdk-testing-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..3222be10e2c --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.49.0.jar against opentelemetry-sdk-trace-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk.txt b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..f73ca46aeef --- /dev/null +++ b/docs/apidiffs/1.49.0_vs_1.48.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.49.0.jar against opentelemetry-sdk-1.48.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-api.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-api.txt new file mode 100644 index 00000000000..61e8fb5e1c0 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.51.0.jar against opentelemetry-api-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-context.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-context.txt new file mode 100644 index 00000000000..a5c30f8a84c --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.51.0.jar against opentelemetry-context-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..fb04506275a --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.51.0.jar against opentelemetry-exporter-common-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..bfd0b27ef09 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.51.0.jar against opentelemetry-exporter-logging-otlp-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..5e54077e527 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.51.0.jar against opentelemetry-exporter-logging-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..653fbfe3412 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.51.0.jar against opentelemetry-exporter-otlp-common-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..555afa389ac --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.51.0.jar against opentelemetry-exporter-otlp-1.50.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..1201a3756a3 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.51.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..3e3e3dd0985 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.51.0.jar against opentelemetry-exporter-sender-jdk-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..eb0b6518e68 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.51.0.jar against opentelemetry-exporter-sender-okhttp-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..f6feb70d2d0 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.51.0.jar against opentelemetry-exporter-zipkin-1.50.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..ae591b19ba8 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.51.0.jar against opentelemetry-extension-kotlin-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..84508810235 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.51.0.jar against opentelemetry-extension-trace-propagators-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..4b19e060157 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.51.0.jar against opentelemetry-opentracing-shim-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..591b97bb37c --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-common.txt @@ -0,0 +1,11 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.51.0.jar against opentelemetry-sdk-common-1.50.0.jar ++++ NEW ENUM: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.common.InternalTelemetryVersion (compatible) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.constant.Constable + +++ NEW INTERFACE: java.lang.Comparable + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.Enum + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.InternalTelemetryVersion LEGACY + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.InternalTelemetryVersion LATEST + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.InternalTelemetryVersion valueOf(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.InternalTelemetryVersion[] values() diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..89f7906d8c5 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.51.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..485f288fd69 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.51.0.jar against opentelemetry-sdk-extension-autoconfigure-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..c6effc36b6d --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.51.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..3609c459646 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.51.0.jar against opentelemetry-sdk-logs-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..ff51495ad1d --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.51.0.jar against opentelemetry-sdk-metrics-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..ce7853cf981 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.51.0.jar against opentelemetry-sdk-testing-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..9fd25fe8edb --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.51.0.jar against opentelemetry-sdk-trace-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk.txt b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..0324c0c4856 --- /dev/null +++ b/docs/apidiffs/1.51.0_vs_1.50.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.51.0.jar against opentelemetry-sdk-1.50.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-api.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-api.txt new file mode 100644 index 00000000000..ed3e1e076ac --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-api.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-api-1.52.0.jar against opentelemetry-api-1.51.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.api.GlobalOpenTelemetry (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) void set(java.util.function.Supplier) diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-common.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-common.txt new file mode 100644 index 00000000000..439922d61d8 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-common.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-common-1.52.0.jar against ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.common.ComponentLoader (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.common.ComponentLoader forClassLoader(java.lang.ClassLoader) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Iterable load(java.lang.Class) + GENERIC TEMPLATES: +++ T:java.lang.Object diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-context.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-context.txt new file mode 100644 index 00000000000..f628e7c6de2 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.52.0.jar against opentelemetry-context-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..7ce59a25907 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.52.0.jar against opentelemetry-exporter-common-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..81183679a77 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.52.0.jar against opentelemetry-exporter-logging-otlp-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..3ce4ed1852e --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.52.0.jar against opentelemetry-exporter-logging-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..12f0ce982e5 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.52.0.jar against opentelemetry-exporter-otlp-common-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..d9395d450cb --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.52.0.jar against opentelemetry-exporter-otlp-1.51.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..a4f7152db37 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.52.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..4f97d2b4cdb --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.52.0.jar against opentelemetry-exporter-sender-jdk-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..ec31b89a9e4 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.52.0.jar against opentelemetry-exporter-sender-okhttp-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..08630dd1b70 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.52.0.jar against opentelemetry-exporter-zipkin-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..c7b73267ea9 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.52.0.jar against opentelemetry-extension-kotlin-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..ae33ad28088 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.52.0.jar against opentelemetry-extension-trace-propagators-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..872c028cb33 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.52.0.jar against opentelemetry-opentracing-shim-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..eb715b8fddd --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.52.0.jar against opentelemetry-sdk-common-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..72353441e67 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.52.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.51.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.common.ComponentLoader getComponentLoader() diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..0b818e8d0f4 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.52.0.jar against opentelemetry-sdk-extension-autoconfigure-1.51.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder setComponentLoader(io.opentelemetry.common.ComponentLoader) diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..97b9523a618 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.52.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..8cd9d9ff50e --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.52.0.jar against opentelemetry-sdk-logs-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..f806e049007 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.52.0.jar against opentelemetry-sdk-metrics-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..bd6d78ab7db --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.52.0.jar against opentelemetry-sdk-testing-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..7aea6b071c1 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.52.0.jar against opentelemetry-sdk-trace-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk.txt b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..31036408d05 --- /dev/null +++ b/docs/apidiffs/1.52.0_vs_1.51.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.52.0.jar against opentelemetry-sdk-1.51.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-api.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-api.txt new file mode 100644 index 00000000000..3bb4cdfc43d --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.53.jar against opentelemetry-api-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-common.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-common.txt new file mode 100644 index 00000000000..1f7dd499d80 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.53.jar against opentelemetry-common-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-context.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-context.txt new file mode 100644 index 00000000000..9cc7a24d37f --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.53.jar against opentelemetry-context-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..895561479b0 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.53.jar against opentelemetry-exporter-common-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..87751352cbd --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.53.jar against opentelemetry-exporter-logging-otlp-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..e4a98a03ede --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.53.jar against opentelemetry-exporter-logging-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..bf6beb5b7b0 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.53.jar against opentelemetry-exporter-otlp-common-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..1a5abfa7db7 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.53.jar against opentelemetry-exporter-otlp-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..ab978a12776 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.53.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..45a6f77044c --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.53.jar against opentelemetry-exporter-sender-jdk-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..7f5e3d048ea --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.53.jar against opentelemetry-exporter-sender-okhttp-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..959a0448716 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.53.jar against opentelemetry-exporter-zipkin-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..f20abb6d6b0 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.53.jar against opentelemetry-extension-kotlin-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..6f81a04231a --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.53.jar against opentelemetry-extension-trace-propagators-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..693446030c7 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.53.jar against opentelemetry-opentracing-shim-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..b0afa5f94cc --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.53.jar against opentelemetry-sdk-common-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..3d3509e2323 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.53.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..409aeb8b48a --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.53.jar against opentelemetry-sdk-extension-autoconfigure-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..3e6742140fa --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.53.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..7bf00a31b00 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.53.jar against opentelemetry-sdk-logs-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..3e03fb66019 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.53.jar against opentelemetry-sdk-metrics-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..9bf3f7548cd --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.53.jar against opentelemetry-sdk-testing-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..c2695432546 --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.53.jar against opentelemetry-sdk-trace-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk.txt b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..89a6eafa75d --- /dev/null +++ b/docs/apidiffs/1.53.0_vs_1.52.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.53.jar against opentelemetry-sdk-1.52.0.jar +No changes. diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-api.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-api.txt new file mode 100644 index 00000000000..fc09f385766 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.54.0.jar against opentelemetry-api-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-common.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-common.txt new file mode 100644 index 00000000000..fc154231caf --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.54.0.jar against opentelemetry-common-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-context.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-context.txt new file mode 100644 index 00000000000..21afd6f8fdc --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.54.0.jar against opentelemetry-context-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..6d27e566214 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.54.0.jar against opentelemetry-exporter-common-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..21dbb026258 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.54.0.jar against opentelemetry-exporter-logging-otlp-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..6055f99143a --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.54.0.jar against opentelemetry-exporter-logging-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..77b226fd7f6 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.54.0.jar against opentelemetry-exporter-otlp-common-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..3738e03549f --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.54.0.jar against opentelemetry-exporter-otlp-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..b354d7b5788 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.54.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..1d7c5b3837a --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.54.0.jar against opentelemetry-exporter-sender-jdk-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..af7f275f117 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.54.0.jar against opentelemetry-exporter-sender-okhttp-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..75f522441b7 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.54.0.jar against opentelemetry-exporter-zipkin-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..4b292ee36e4 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.54.0.jar against opentelemetry-extension-kotlin-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..1cdc943dae9 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.54.0.jar against opentelemetry-extension-trace-propagators-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..6bf1d5be99d --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.54.0.jar against opentelemetry-opentracing-shim-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..2a135ecd53d --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.54.0.jar against opentelemetry-sdk-common-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..322c17c3287 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.54.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..4c68ed5ed1f --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.54.0.jar against opentelemetry-sdk-extension-autoconfigure-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..5023c1daada --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.54.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..e937defff48 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.54.0.jar against opentelemetry-sdk-logs-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..b3a58fd368f --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.54.0.jar against opentelemetry-sdk-metrics-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..28919f73da0 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.54.0.jar against opentelemetry-sdk-testing-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..7350996ed52 --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.54.0.jar against opentelemetry-sdk-trace-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk.txt b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..a2f53a7d77e --- /dev/null +++ b/docs/apidiffs/1.54.0_vs_1.53.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.54.0.jar against opentelemetry-sdk-1.53.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-api.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-api.txt new file mode 100644 index 00000000000..8e83a0c77d4 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.54.1.jar against opentelemetry-api-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-common.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-common.txt new file mode 100644 index 00000000000..baeff2ad240 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.54.1.jar against opentelemetry-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-context.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-context.txt new file mode 100644 index 00000000000..7b55daefabf --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.54.1.jar against opentelemetry-context-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..4be78901ff2 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.54.1.jar against opentelemetry-exporter-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..8b57598fed1 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.54.1.jar against opentelemetry-exporter-logging-otlp-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..da1bf8be15a --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.54.1.jar against opentelemetry-exporter-logging-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..587cf4a3e84 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.54.1.jar against opentelemetry-exporter-otlp-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..e442267f7a0 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.54.1.jar against opentelemetry-exporter-otlp-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..94588f18021 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.54.1.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..89cd26cb6bc --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.54.1.jar against opentelemetry-exporter-sender-jdk-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..b85a563169e --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.54.1.jar against opentelemetry-exporter-sender-okhttp-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..a71dad2b7d4 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.54.1.jar against opentelemetry-exporter-zipkin-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..8071c38deab --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.54.1.jar against opentelemetry-extension-kotlin-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..5aa23517b2f --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.54.1.jar against opentelemetry-extension-trace-propagators-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..3c8dcd2dac0 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.54.1.jar against opentelemetry-opentracing-shim-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..2b3365e8cfe --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.54.1.jar against opentelemetry-sdk-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..2a5d7371c22 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.54.1.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..74b5a64b9b7 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.54.1.jar against opentelemetry-sdk-extension-autoconfigure-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..1a05892ecb6 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.54.1.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..0e5d70de719 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.54.1.jar against opentelemetry-sdk-logs-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..2899522c4c5 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.54.1.jar against opentelemetry-sdk-metrics-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..bf8dd995a25 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.54.1.jar against opentelemetry-sdk-testing-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..7b7d807b4ad --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.54.1.jar against opentelemetry-sdk-trace-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk.txt b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..c18c3eef973 --- /dev/null +++ b/docs/apidiffs/1.54.1_vs_1.54.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.54.1.jar against opentelemetry-sdk-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-api.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-api.txt new file mode 100644 index 00000000000..69ec00ba240 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.55.0.jar against opentelemetry-api-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-common.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-common.txt new file mode 100644 index 00000000000..55bea87c71a --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.55.0.jar against opentelemetry-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-context.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-context.txt new file mode 100644 index 00000000000..a9545d66697 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.55.0.jar against opentelemetry-context-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..04e76a1833d --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.55.0.jar against opentelemetry-exporter-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..7a727777916 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.55.0.jar against opentelemetry-exporter-logging-otlp-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..d406d95d2d0 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.55.0.jar against opentelemetry-exporter-logging-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..ad7ce48b8d4 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.55.0.jar against opentelemetry-exporter-otlp-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..1e23de48f4c --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.55.0.jar against opentelemetry-exporter-otlp-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..c09d0877835 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.55.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..a55e65ebd2a --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.55.0.jar against opentelemetry-exporter-sender-jdk-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..abdda07ed1d --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.55.0.jar against opentelemetry-exporter-sender-okhttp-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..e1b507cd83b --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.55.0.jar against opentelemetry-exporter-zipkin-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..43c1df836b8 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.55.0.jar against opentelemetry-extension-kotlin-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..f66c8803b6c --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.55.0.jar against opentelemetry-extension-trace-propagators-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..1fb724fa0cb --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.55.0.jar against opentelemetry-opentracing-shim-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..77a2ff2d5aa --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.55.0.jar against opentelemetry-sdk-common-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..12514a8d8b9 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.55.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..24f18357cd4 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.55.0.jar against opentelemetry-sdk-extension-autoconfigure-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..70449a99df9 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.55.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..b432d865e8f --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.55.0.jar against opentelemetry-sdk-logs-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..c277f015c6f --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.55.0.jar against opentelemetry-sdk-metrics-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..c8f62b4d944 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.55.0.jar against opentelemetry-sdk-testing-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..81b8522caeb --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.55.0.jar against opentelemetry-sdk-trace-1.54.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk.txt b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..62f61a28379 --- /dev/null +++ b/docs/apidiffs/1.55.0_vs_1.54.0/opentelemetry-sdk.txt @@ -0,0 +1,10 @@ +Comparing source compatibility of opentelemetry-sdk-1.55.0.jar against opentelemetry-sdk-1.54.0.jar +*** MODIFIED CLASS: PUBLIC NON_FINAL (<- FINAL) io.opentelemetry.sdk.OpenTelemetrySdk (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.api.logs.LoggerProvider getLogsBridge() + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.api.metrics.MeterProvider getMeterProvider() + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.context.propagation.ContextPropagators getPropagators() + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.sdk.logs.SdkLoggerProvider getSdkLoggerProvider() + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.sdk.metrics.SdkMeterProvider getSdkMeterProvider() + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.sdk.trace.SdkTracerProvider getSdkTracerProvider() + *** MODIFIED METHOD: PUBLIC FINAL (<- NON_FINAL) io.opentelemetry.api.trace.TracerProvider getTracerProvider() diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-api.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-api.txt new file mode 100644 index 00000000000..bd965016e64 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.56.0.jar against opentelemetry-api-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-common.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-common.txt new file mode 100644 index 00000000000..c23d62ecc91 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.56.0.jar against opentelemetry-common-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-context.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-context.txt new file mode 100644 index 00000000000..3f53fd2394b --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.56.0.jar against opentelemetry-context-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..c753ca85b4c --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.56.0.jar against opentelemetry-exporter-common-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..e6137cc3b0e --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.56.0.jar against opentelemetry-exporter-logging-otlp-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..aea0850d0b2 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.56.0.jar against opentelemetry-exporter-logging-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..2a2352bb35d --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.56.0.jar against opentelemetry-exporter-otlp-common-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..c3b62744268 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.56.0.jar against opentelemetry-exporter-otlp-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..bdb77552b82 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.56.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..f2885ee6c60 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.56.0.jar against opentelemetry-exporter-sender-jdk-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..ff7b5645042 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.56.0.jar against opentelemetry-exporter-sender-okhttp-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..50561d6687a --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.56.0.jar against opentelemetry-exporter-zipkin-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..120ba3e5959 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.56.0.jar against opentelemetry-extension-kotlin-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..b62dbabe541 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.56.0.jar against opentelemetry-extension-trace-propagators-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..dc032eb5e9c --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.56.0.jar against opentelemetry-opentracing-shim-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..19c0835ec38 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.56.0.jar against opentelemetry-sdk-common-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..c32816dfd4a --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.56.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..2bc2dacf809 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.56.0.jar against opentelemetry-sdk-extension-autoconfigure-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..09d0047de92 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.56.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..95942af2391 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.56.0.jar against opentelemetry-sdk-logs-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..b23e211fa07 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,10 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.56.0.jar against opentelemetry-sdk-metrics-1.55.0.jar ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.ExemplarFilter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.ExemplarFilter alwaysOff() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.ExemplarFilter alwaysOn() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.ExemplarFilter traceBased() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder setExemplarFilter(io.opentelemetry.sdk.metrics.ExemplarFilter) diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..66da2fcf665 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.56.0.jar against opentelemetry-sdk-testing-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..153d9741b53 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.56.0.jar against opentelemetry-sdk-trace-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk.txt b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..61077cca860 --- /dev/null +++ b/docs/apidiffs/1.56.0_vs_1.55.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.56.0.jar against opentelemetry-sdk-1.55.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-api.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-api.txt new file mode 100644 index 00000000000..2be01ef1aff --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-api.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of opentelemetry-api-1.57.0.jar against opentelemetry-api-1.56.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.api.GlobalOpenTelemetry (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.OpenTelemetry getOrNoop() + +++ NEW METHOD: PUBLIC(+) STATIC(+) boolean isSet() diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-common.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-common.txt new file mode 100644 index 00000000000..3d6a5111972 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.57.0.jar against opentelemetry-common-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-context.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-context.txt new file mode 100644 index 00000000000..76ab8d03753 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.57.0.jar against opentelemetry-context-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..f1fb18a6c7f --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.57.0.jar against opentelemetry-exporter-common-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..09417122030 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.57.0.jar against opentelemetry-exporter-logging-otlp-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..e059bbc53d6 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.57.0.jar against opentelemetry-exporter-logging-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..41df3078531 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.57.0.jar against opentelemetry-exporter-otlp-common-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..fde798a8644 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.57.0.jar against opentelemetry-exporter-otlp-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..0f5c72c4c24 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.57.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..5bd394fef70 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.57.0.jar against opentelemetry-exporter-sender-jdk-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..4bf0256b978 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.57.0.jar against opentelemetry-exporter-sender-okhttp-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..ccd77122cff --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.57.0.jar against opentelemetry-exporter-zipkin-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..cd9989f7c79 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.57.0.jar against opentelemetry-extension-kotlin-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..bc13bcf212f --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.57.0.jar against opentelemetry-extension-trace-propagators-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..3c312d19285 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.57.0.jar against opentelemetry-opentracing-shim-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..6bdd18ae4c7 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.57.0.jar against opentelemetry-sdk-common-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..d6bc23c1790 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.57.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..64c50a2c97f --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.57.0.jar against opentelemetry-sdk-extension-autoconfigure-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..047d5a97751 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.57.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..c079f4a4a15 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.57.0.jar against opentelemetry-sdk-logs-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..32cfe2afe71 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.57.0.jar against opentelemetry-sdk-metrics-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..0d243242b69 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.57.0.jar against opentelemetry-sdk-testing-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..3a4daaec15f --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.57.0.jar against opentelemetry-sdk-trace-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk.txt b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..20730ebcfb7 --- /dev/null +++ b/docs/apidiffs/1.57.0_vs_1.56.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.57.0.jar against opentelemetry-sdk-1.56.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-api.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-api.txt new file mode 100644 index 00000000000..c899834d648 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.58.0.jar against opentelemetry-api-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-common.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-common.txt new file mode 100644 index 00000000000..4169c3decfc --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.58.0.jar against opentelemetry-common-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-context.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-context.txt new file mode 100644 index 00000000000..21738614f0e --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.58.0.jar against opentelemetry-context-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..2bb5d317c9d --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.58.0.jar against opentelemetry-exporter-common-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..b394d69929c --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.58.0.jar against opentelemetry-exporter-logging-otlp-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..692cc25edb0 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.58.0.jar against opentelemetry-exporter-logging-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..301b74b191b --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.58.0.jar against opentelemetry-exporter-otlp-common-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..518e75a6438 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.58.0.jar against opentelemetry-exporter-otlp-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..3541b52cc88 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.58.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..60d81d8db89 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.58.0.jar against opentelemetry-exporter-sender-jdk-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..5752fc056b4 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.58.0.jar against opentelemetry-exporter-sender-okhttp-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..6a5729f4ea7 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.58.0.jar against opentelemetry-exporter-zipkin-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..b3110459070 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.58.0.jar against opentelemetry-extension-kotlin-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..4ad72504836 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.58.0.jar against opentelemetry-extension-trace-propagators-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..e395e266766 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.58.0.jar against opentelemetry-opentracing-shim-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..748a91ed2de --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.58.0.jar against opentelemetry-sdk-common-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..befaf3dc418 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.58.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..a44ad13b2ad --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.58.0.jar against opentelemetry-sdk-extension-autoconfigure-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..395792d9d86 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.58.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..2dd0ee9df58 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,16 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.58.0.jar against opentelemetry-sdk-logs-1.57.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessorBuilder builder(io.opentelemetry.sdk.logs.export.LogRecordExporter) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessorBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessorBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder setMeterProvider(java.util.function.Supplier) diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..a9824547510 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.58.0.jar against opentelemetry-sdk-metrics-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..f639661d157 --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.58.0.jar against opentelemetry-sdk-testing-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..cbd122511ae --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,11 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.58.0.jar against opentelemetry-sdk-trace-1.57.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder setMeterProvider(java.util.function.Supplier) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.SdkTracerProviderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.trace.SdkTracerProviderBuilder setMeterProvider(java.util.function.Supplier) diff --git a/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk.txt b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..6a4e168036f --- /dev/null +++ b/docs/apidiffs/1.58.0_vs_1.57.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.58.0.jar against opentelemetry-sdk-1.57.0.jar +No changes. diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-api.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-api.txt new file mode 100644 index 00000000000..9e04c7560d2 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-api.txt @@ -0,0 +1,25 @@ +Comparing source compatibility of opentelemetry-api-1.59.0.jar against opentelemetry-api-1.58.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.common.AttributeKey (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + GENERIC TEMPLATES: === T:java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.AttributeKey> valueKey(java.lang.String) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.common.AttributesBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.common.AttributesBuilder put(java.lang.String, io.opentelemetry.api.common.Value) +*** MODIFIED ENUM: PUBLIC FINAL io.opentelemetry.api.common.AttributeType (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.AttributeType VALUE ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.api.common.Empty (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) boolean equals(java.lang.Object) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Empty getInstance() + +++ NEW METHOD: PUBLIC(+) int hashCode() + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.common.Value (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + GENERIC TEMPLATES: === T:java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.common.Value empty() +*** MODIFIED ENUM: PUBLIC FINAL io.opentelemetry.api.common.ValueType (compatible) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.api.common.ValueType EMPTY diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-common.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-common.txt new file mode 100644 index 00000000000..a5cb024628c --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.59.0.jar against opentelemetry-common-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-context.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-context.txt new file mode 100644 index 00000000000..668ca690a5e --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.59.0.jar against opentelemetry-context-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..410f13ecbad --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.59.0.jar against opentelemetry-exporter-common-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..98656eea018 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.59.0.jar against opentelemetry-exporter-logging-otlp-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..9999cbf78b1 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.59.0.jar against opentelemetry-exporter-logging-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..456e7fde26e --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.59.0.jar against opentelemetry-exporter-otlp-common-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..82b52b14189 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.59.0.jar against opentelemetry-exporter-otlp-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..5f6a72baf9f --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.59.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..dca46459eb0 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.59.0.jar against opentelemetry-exporter-sender-jdk-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..90158b74af9 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.59.0.jar against opentelemetry-exporter-sender-okhttp-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..ee34bc6ea20 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.59.0.jar against opentelemetry-exporter-zipkin-1.58.0.jar +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..83795b12215 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.59.0.jar against opentelemetry-extension-kotlin-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..77911ea59ce --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.59.0.jar against opentelemetry-extension-trace-propagators-1.58.0.jar +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.trace.propagation.JaegerPropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.extension.trace.propagation.OtTracePropagator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..313bf5bf138 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.59.0.jar against opentelemetry-opentracing-shim-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..996ff44c73f --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-common.txt @@ -0,0 +1,109 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.59.0.jar against opentelemetry-sdk-common-1.58.0.jar ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.Compressor (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.io.OutputStream compress(java.io.OutputStream) + +++ NEW EXCEPTION: java.io.IOException + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getEncoding() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.GrpcResponse (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) byte[] getResponseMessage() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.GrpcStatusCode getStatusCode() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getStatusDescription() + +++ NEW ANNOTATION: javax.annotation.Nullable ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.GrpcSender (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void send(io.opentelemetry.sdk.common.export.MessageWriter, java.util.function.Consumer, java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.GrpcSenderConfig (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.Compressor getCompressor() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.time.Duration getConnectTimeout() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.net.URI getEndpoint() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.concurrent.ExecutorService getExecutorService() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getFullMethodName() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.function.Supplier>> getHeadersSupplier() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy getRetryPolicy() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) javax.net.ssl.SSLContext getSslContext() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.time.Duration getTimeout() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) javax.net.ssl.X509TrustManager getTrustManager() + +++ NEW ANNOTATION: javax.annotation.Nullable ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.GrpcSenderProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.GrpcSender createSender(io.opentelemetry.sdk.common.export.GrpcSenderConfig) ++++ NEW ENUM: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode (compatible) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.lang.constant.Constable + +++ NEW INTERFACE: java.lang.Comparable + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.Enum + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode RESOURCE_EXHAUSTED + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode ALREADY_EXISTS + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode UNIMPLEMENTED + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode FAILED_PRECONDITION + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode NOT_FOUND + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode DEADLINE_EXCEEDED + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode OUT_OF_RANGE + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode UNAUTHENTICATED + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode CANCELLED + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode DATA_LOSS + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode INTERNAL + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode UNAVAILABLE + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode UNKNOWN + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode ABORTED + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode OK + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode INVALID_ARGUMENT + +++ NEW FIELD: PUBLIC(+) STATIC(+) FINAL(+) io.opentelemetry.sdk.common.export.GrpcStatusCode PERMISSION_DENIED + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.GrpcStatusCode fromValue(int) + +++ NEW METHOD: PUBLIC(+) int getValue() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.GrpcStatusCode valueOf(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.common.export.GrpcStatusCode[] values() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.HttpResponse (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) byte[] getResponseBody() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getStatusCode() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getStatusMessage() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.HttpSender (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void send(io.opentelemetry.sdk.common.export.MessageWriter, java.util.function.Consumer, java.util.function.Consumer) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.HttpSenderConfig (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.Compressor getCompressor() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.time.Duration getConnectTimeout() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getContentType() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.net.URI getEndpoint() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.concurrent.ExecutorService getExecutorService() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.function.Supplier>> getHeadersSupplier() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.ProxyOptions getProxyOptions() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.RetryPolicy getRetryPolicy() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) javax.net.ssl.SSLContext getSslContext() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.time.Duration getTimeout() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) javax.net.ssl.X509TrustManager getTrustManager() + +++ NEW ANNOTATION: javax.annotation.Nullable ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.HttpSenderProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.HttpSender createSender(io.opentelemetry.sdk.common.export.HttpSenderConfig) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.common.export.MessageWriter (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getContentLength() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) void writeMessage(java.io.OutputStream) + +++ NEW EXCEPTION: java.io.IOException diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..8d8f9ba93d0 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.59.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..70a46ffb45f --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.59.0.jar against opentelemetry-sdk-extension-autoconfigure-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..1fcc7ffc94e --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.59.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..7502219f781 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.59.0.jar against opentelemetry-sdk-logs-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..c991d984974 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.59.0.jar against opentelemetry-sdk-metrics-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..077d9c0c80c --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,12 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.59.0.jar against opentelemetry-sdk-testing-1.58.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.AttributesAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.AttributesAssert containsEntry(java.lang.String, io.opentelemetry.api.common.Value) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.util.Map$Entry>,io.opentelemetry.api.common.Value> attributeEntry(java.lang.String, io.opentelemetry.api.common.Value) + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.assertj.AttributeAssertion satisfies(io.opentelemetry.api.common.AttributeKey>, io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions$ValueAssertConsumer) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) STATIC(+) io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions$ValueAssertConsumer (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: java.util.function.Consumer + +++ NEW SUPERCLASS: java.lang.Object diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..d61e69e1864 --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.59.0.jar against opentelemetry-sdk-trace-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk.txt b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..18a051f2e5e --- /dev/null +++ b/docs/apidiffs/1.59.0_vs_1.58.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.59.0.jar against opentelemetry-sdk-1.58.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-api.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-api.txt new file mode 100644 index 00000000000..e2cc248fc7a --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-api.txt @@ -0,0 +1,14 @@ +Comparing source compatibility of opentelemetry-api-1.60.0.jar against opentelemetry-api-1.59.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.logs.LogRecordBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setException(java.lang.Throwable) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.trace.TraceFlags (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.trace.TraceFlagsBuilder builder() + +++ NEW METHOD: PUBLIC(+) boolean isTraceIdRandom() ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.trace.TraceFlagsBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.trace.TraceFlags build() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.trace.TraceFlagsBuilder setRandomTraceId(boolean) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.trace.TraceFlagsBuilder setSampled(boolean) diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-common.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-common.txt new file mode 100644 index 00000000000..44076acea54 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.60.0.jar against opentelemetry-common-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-context.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-context.txt new file mode 100644 index 00000000000..302f5779560 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.60.0.jar against opentelemetry-context-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..2b45b05e5e5 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.60.0.jar against opentelemetry-exporter-common-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..825e3dba628 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.60.0.jar against opentelemetry-exporter-logging-otlp-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..21e66e2aada --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.60.0.jar against opentelemetry-exporter-logging-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..141cf478c6c --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.60.0.jar against opentelemetry-exporter-otlp-common-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..d7534d28cd1 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.60.0.jar against opentelemetry-exporter-otlp-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..8ade7dee9fa --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.60.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..602725c6baf --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.60.0.jar against opentelemetry-exporter-sender-jdk-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..de74c51a87c --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.60.0.jar against opentelemetry-exporter-sender-okhttp-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..78115cdacde --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.60.0.jar against opentelemetry-exporter-zipkin-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..bb1f855d641 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.60.0.jar against opentelemetry-extension-kotlin-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..159b21aef6f --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.60.0.jar against opentelemetry-extension-trace-propagators-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..c9c54620ca8 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.60.0.jar against opentelemetry-opentracing-shim-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..bc6c69ea4bb --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.60.0.jar against opentelemetry-sdk-common-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..def0cc7f5b1 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.60.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..da1e546ecba --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.60.0.jar against opentelemetry-sdk-extension-autoconfigure-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..633d6088475 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.60.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..d84491181bc --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.60.0.jar against opentelemetry-sdk-logs-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..7accbfbef65 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,40 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.60.0.jar against opentelemetry-sdk-metrics-1.59.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.Aggregation (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + === UNCHANGED METHOD: PUBLIC STATIC io.opentelemetry.sdk.metrics.Aggregation base2ExponentialBucketHistogram(int, int) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.Aggregation base2ExponentialBucketHistogram(io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions) + === UNCHANGED METHOD: PUBLIC STATIC io.opentelemetry.sdk.metrics.Aggregation explicitBucketHistogram(java.util.List) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.Aggregation explicitBucketHistogram(io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions) ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions$Builder builder() + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions getDefault() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getMaxBuckets() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) int getMaxScale() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean getRecordMinMax() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions$Builder toBuilder() ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) STATIC(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions$Builder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions build() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions$Builder setMaxBuckets(int) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions$Builder setMaxScale(int) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions$Builder setRecordMinMax(boolean) ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions$Builder builder() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.List getBucketBoundaries() + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions getDefault() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean getRecordMinMax() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions$Builder toBuilder() ++++ NEW CLASS: PUBLIC(+) ABSTRACT(+) STATIC(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions$Builder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions build() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions$Builder setBucketBoundaries(java.util.List) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions$Builder setRecordMinMax(boolean) diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..b0d7fc15540 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.60.0.jar against opentelemetry-sdk-testing-1.59.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LogRecordDataAssert hasException(java.lang.Throwable) diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..873eec0e41a --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.60.0.jar against opentelemetry-sdk-trace-1.59.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.trace.IdGenerator (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean generatesRandomTraceIds() diff --git a/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk.txt b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..e2a16fa3074 --- /dev/null +++ b/docs/apidiffs/1.60.0_vs_1.59.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.60.0.jar against opentelemetry-sdk-1.59.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-api.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-api.txt new file mode 100644 index 00000000000..ac579cf0cc2 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.60.1.jar against opentelemetry-api-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-common.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-common.txt new file mode 100644 index 00000000000..0fd4c4ed016 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.60.1.jar against opentelemetry-common-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-context.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-context.txt new file mode 100644 index 00000000000..1b3148a5e11 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.60.1.jar against opentelemetry-context-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..17efc183cdd --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.60.1.jar against opentelemetry-exporter-common-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..72f85e6d9be --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.60.1.jar against opentelemetry-exporter-logging-otlp-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..e11f84377db --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.60.1.jar against opentelemetry-exporter-logging-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..fe250a8dd63 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.60.1.jar against opentelemetry-exporter-otlp-common-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..e7e68a7fa9b --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.60.1.jar against opentelemetry-exporter-otlp-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..d29f29e5004 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.60.1.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..d6b0abba5e3 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.60.1.jar against opentelemetry-exporter-sender-jdk-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..427a52765a3 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.60.1.jar against opentelemetry-exporter-sender-okhttp-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..2e603e1f7b8 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.60.1.jar against opentelemetry-exporter-zipkin-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..fe2976f89c5 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.60.1.jar against opentelemetry-extension-kotlin-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..ac91ff6c6bc --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.60.1.jar against opentelemetry-extension-trace-propagators-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..6dba4bd840c --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.60.1.jar against opentelemetry-opentracing-shim-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..1cb30c92b28 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.60.1.jar against opentelemetry-sdk-common-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..1417e33b10b --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.60.1.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..765aceffbd5 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.60.1.jar against opentelemetry-sdk-extension-autoconfigure-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..2a716e50a93 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.60.1.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..f5dda43ce7e --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.60.1.jar against opentelemetry-sdk-logs-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..a726f2ebc0c --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.60.1.jar against opentelemetry-sdk-metrics-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..51c616646ae --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.60.1.jar against opentelemetry-sdk-testing-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..312df7e6c08 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.60.1.jar against opentelemetry-sdk-trace-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk.txt b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..36ad2b94d93 --- /dev/null +++ b/docs/apidiffs/1.60.1_vs_1.60.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.60.1.jar against opentelemetry-sdk-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-api.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-api.txt new file mode 100644 index 00000000000..2707a690ca8 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-api.txt @@ -0,0 +1,32 @@ +Comparing source compatibility of opentelemetry-api-1.61.0.jar against opentelemetry-api-1.60.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.logs.Logger (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled(io.opentelemetry.api.logs.Severity, io.opentelemetry.context.Context) + +++ NEW METHOD: PUBLIC(+) boolean isEnabled(io.opentelemetry.api.logs.Severity) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleCounter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleGauge (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleHistogram (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleUpDownCounter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongCounter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongGauge (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongHistogram (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongUpDownCounter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.trace.Tracer (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) boolean isEnabled() diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-common.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-common.txt new file mode 100644 index 00000000000..4fb30c4746c --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-common.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of opentelemetry-common-1.61.0.jar against opentelemetry-common-1.60.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.common.ComponentLoader (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.util.List loadList(io.opentelemetry.common.ComponentLoader, java.lang.Class) + GENERIC TEMPLATES: +++ T:java.lang.Object diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-context.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-context.txt new file mode 100644 index 00000000000..d8affae4a81 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.61.0.jar against opentelemetry-context-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..95b30132311 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.61.0.jar against opentelemetry-exporter-common-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..d334b796077 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.61.0.jar against opentelemetry-exporter-logging-otlp-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..44f33dc1214 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.61.0.jar against opentelemetry-exporter-logging-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..4e5d5f85451 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.61.0.jar against opentelemetry-exporter-otlp-common-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..3a3e3ab7374 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.61.0.jar against opentelemetry-exporter-otlp-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..91bb46fd6e7 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.61.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..18812dfb9b2 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.61.0.jar against opentelemetry-exporter-sender-jdk-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..dfdcdf0873a --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.61.0.jar against opentelemetry-exporter-sender-okhttp-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..6d0a9a939f4 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.61.0.jar against opentelemetry-exporter-zipkin-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..ebe4f733f43 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.61.0.jar against opentelemetry-extension-kotlin-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..0e82d4a1c38 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.61.0.jar against opentelemetry-extension-trace-propagators-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..c4b59de19ed --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.61.0.jar against opentelemetry-opentracing-shim-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..5383c9b2802 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-common.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.61.0.jar against opentelemetry-sdk-common-1.60.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.common.export.GrpcSenderConfig (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) long getMaxResponseBodySize() +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.common.export.HttpSenderConfig (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) long getMaxResponseBodySize() diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..e29206e1f2a --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.61.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.60.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.autoconfigure.spi.Ordered (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.util.List loadOrderedList(io.opentelemetry.common.ComponentLoader, java.lang.Class) + GENERIC TEMPLATES: +++ T:io.opentelemetry.sdk.autoconfigure.spi.Ordered diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..fa29f26f93e --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.61.0.jar against opentelemetry-sdk-extension-autoconfigure-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..459bd833c2b --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.61.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.60.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder setMaxSamplingStrategyResponseBodySize(long) diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..4e696e44ad1 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.61.0.jar against opentelemetry-sdk-logs-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..b25de349a02 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.61.0.jar against opentelemetry-sdk-metrics-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..5e3f0d952b4 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.61.0.jar against opentelemetry-sdk-testing-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..0c820b58c90 --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.61.0.jar against opentelemetry-sdk-trace-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk.txt b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..6b38e0a0fab --- /dev/null +++ b/docs/apidiffs/1.61.0_vs_1.60.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.61.0.jar against opentelemetry-sdk-1.60.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-api.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-api.txt new file mode 100644 index 00000000000..741f6b3749f --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.62.0.jar against opentelemetry-api-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-common.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-common.txt new file mode 100644 index 00000000000..9ac034644b4 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-common.txt @@ -0,0 +1,6 @@ +Comparing source compatibility of opentelemetry-common-1.62.0.jar against opentelemetry-common-1.61.0.jar ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.common.impl.ApiUsageLogger (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) void logNullParam(java.lang.Class, java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) void logUsageIssue(java.lang.Class, java.lang.String, java.lang.String) diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-context.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-context.txt new file mode 100644 index 00000000000..e6de19f0116 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.62.0.jar against opentelemetry-context-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..5bd6ccafd4a --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.62.0.jar against opentelemetry-exporter-common-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..98daf34abae --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.62.0.jar against opentelemetry-exporter-logging-otlp-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..91d028ebcea --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.62.0.jar against opentelemetry-exporter-logging-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..abddebfcd85 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.62.0.jar against opentelemetry-exporter-otlp-common-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..fa70ff06411 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.62.0.jar against opentelemetry-exporter-otlp-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..62bd7bda7eb --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.62.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..b18b15b56f6 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.62.0.jar against opentelemetry-exporter-sender-jdk-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..cf85ef4880a --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.62.0.jar against opentelemetry-exporter-sender-okhttp-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..2d9eea8a54b --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.62.0.jar against opentelemetry-exporter-zipkin-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..4ef8ef1ecdb --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.62.0.jar against opentelemetry-extension-kotlin-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..7efcaae7582 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.62.0.jar against opentelemetry-extension-trace-propagators-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..eedda8574dd --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.62.0.jar against opentelemetry-opentracing-shim-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..dec35521d1f --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.62.0.jar against opentelemetry-sdk-common-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..a9d18f19e25 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.62.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..a69df385003 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.62.0.jar against opentelemetry-sdk-extension-autoconfigure-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..6fb1d77e6b4 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.62.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..bac5ac34497 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.62.0.jar against opentelemetry-sdk-logs-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..926bc0d1ae4 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.62.0.jar against opentelemetry-sdk-metrics-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..4fc8760971a --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,42 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.62.0.jar against opentelemetry-sdk-testing-1.61.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.DoubleGaugeAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.DoubleGaugeAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.DoubleGaugeAssert containsPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.DoublePointAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.DoublePointAssert hasValueSatisfying(java.util.function.Consumer>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.DoubleSumAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.DoubleSumAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.DoubleSumAssert containsPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.ExponentialHistogramAssert containsPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.HistogramAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.HistogramAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.HistogramAssert containsPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LongGaugeAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.LongGaugeAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LongGaugeAssert containsPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LongPointAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LongPointAssert hasValueSatisfying(java.util.function.Consumer>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.LongSumAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.LongSumAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.LongSumAssert containsPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.SummaryAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.SummaryAssert containsPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.SummaryAssert containsPointsSatisfying(java.lang.Iterable>) diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..d6ca11afe31 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.62.0.jar against opentelemetry-sdk-trace-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk.txt b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..f2d024d3575 --- /dev/null +++ b/docs/apidiffs/1.62.0_vs_1.61.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.62.0.jar against opentelemetry-sdk-1.61.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-api.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-api.txt new file mode 100644 index 00000000000..71d66d497c4 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-api.txt @@ -0,0 +1,12 @@ +Comparing source compatibility of opentelemetry-api-1.63.0.jar against opentelemetry-api-1.62.0.jar ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.api.impl.InstrumentationUtil (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) boolean shouldSuppressInstrumentation(io.opentelemetry.context.Context) + +++ NEW METHOD: PUBLIC(+) STATIC(+) void suppressInstrumentation(java.lang.Runnable) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.logs.LogRecordBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.logs.LogRecordBuilder setAttribute(java.lang.String, io.opentelemetry.api.common.Value) +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.trace.Span (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.trace.Span setAttribute(java.lang.String, io.opentelemetry.api.common.Value) diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-common.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-common.txt new file mode 100644 index 00000000000..ca43688c83b --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.63.0.jar against opentelemetry-common-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-context.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-context.txt new file mode 100644 index 00000000000..1a062df61a4 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.63.0.jar against opentelemetry-context-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..60914f7eb9c --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.63.0.jar against opentelemetry-exporter-common-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..a6a4583f8f4 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.63.0.jar against opentelemetry-exporter-logging-otlp-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..8c8c1d31bc8 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.63.0.jar against opentelemetry-exporter-logging-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..fc9392294ff --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.63.0.jar against opentelemetry-exporter-otlp-common-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..eb9546cee89 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.63.0.jar against opentelemetry-exporter-otlp-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..841564a1c64 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.63.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..32817b3fece --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.63.0.jar against opentelemetry-exporter-sender-jdk-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..9167dbdccb1 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.63.0.jar against opentelemetry-exporter-sender-okhttp-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..120876fdbbf --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.63.0.jar against opentelemetry-exporter-zipkin-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..12f930a9347 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.63.0.jar against opentelemetry-extension-kotlin-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..ecf7fd72d7c --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.63.0.jar against opentelemetry-extension-trace-propagators-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..96cbbc2652a --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,8 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.63.0.jar against opentelemetry-opentracing-shim-1.62.0.jar +=== UNCHANGED CLASS: PUBLIC FINAL io.opentelemetry.opentracingshim.OpenTracingShim (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + === UNCHANGED METHOD: PUBLIC STATIC io.opentracing.Tracer createTracerShim(io.opentelemetry.api.OpenTelemetry) + +++ NEW ANNOTATION: java.lang.Deprecated + === UNCHANGED METHOD: PUBLIC STATIC io.opentracing.Tracer createTracerShim(io.opentelemetry.api.trace.TracerProvider, io.opentelemetry.context.propagation.TextMapPropagator, io.opentelemetry.context.propagation.TextMapPropagator) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW ANNOTATION: java.lang.Deprecated diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..1695afe245b --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.63.0.jar against opentelemetry-sdk-common-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..f9c1fa59136 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.63.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..f31ba6d2a04 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.63.0.jar against opentelemetry-sdk-extension-autoconfigure-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..3d706b29e72 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.63.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..7bae03d54d1 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.63.0.jar against opentelemetry-sdk-logs-1.62.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.logs.export.LogRecordExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.logs.export.LogRecordExporter noop() diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..8f1772f5fab --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.63.0.jar against opentelemetry-sdk-metrics-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..fa549a74ddd --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.63.0.jar against opentelemetry-sdk-testing-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..43a82308acc --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.63.0.jar against opentelemetry-sdk-trace-1.62.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.trace.export.SpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.trace.export.SpanExporter noop() diff --git a/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk.txt b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..3ae03a580a8 --- /dev/null +++ b/docs/apidiffs/1.63.0_vs_1.62.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.63.0.jar against opentelemetry-sdk-1.62.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-api.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-api.txt new file mode 100644 index 00000000000..36da7700052 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.64.0.jar against opentelemetry-api-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-common.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-common.txt new file mode 100644 index 00000000000..f682834fd9e --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.64.0.jar against opentelemetry-common-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-context.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-context.txt new file mode 100644 index 00000000000..9c8f5e365d3 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.64.0.jar against opentelemetry-context-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..02f081648a6 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.64.0.jar against opentelemetry-exporter-common-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..bbf48bbae0a --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.64.0.jar against opentelemetry-exporter-logging-otlp-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..e585961dff0 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.64.0.jar against opentelemetry-exporter-logging-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..cce41a1e032 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.64.0.jar against opentelemetry-exporter-otlp-common-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..765f730cf91 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.64.0.jar against opentelemetry-exporter-otlp-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..e6c964f6e6d --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.64.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..18d98be1c09 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.64.0.jar against opentelemetry-exporter-sender-jdk-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..62474337185 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.64.0.jar against opentelemetry-exporter-sender-okhttp-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-zipkin.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-zipkin.txt new file mode 100644 index 00000000000..767ca786978 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-exporter-zipkin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-zipkin-1.64.0.jar against opentelemetry-exporter-zipkin-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..c0f3d27c4ab --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.64.0.jar against opentelemetry-extension-kotlin-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..252d211e435 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.64.0.jar against opentelemetry-extension-trace-propagators-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..f0bdc9af685 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.64.0.jar against opentelemetry-opentracing-shim-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..971ba74d622 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.64.0.jar against opentelemetry-sdk-common-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..03dff621800 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.64.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..e008e06c28c --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.64.0.jar against opentelemetry-sdk-extension-autoconfigure-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..287c5ba457d --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.64.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..41b64e2b593 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.64.0.jar against opentelemetry-sdk-logs-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..0c77a53b3a2 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.64.0.jar against opentelemetry-sdk-metrics-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..fa28722e159 --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.64.0.jar against opentelemetry-sdk-testing-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..4913882063f --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.64.0.jar against opentelemetry-sdk-trace-1.63.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.trace.export.BatchSpanProcessor (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.trace.export.BatchSpanProcessor create(io.opentelemetry.sdk.trace.export.SpanExporter) diff --git a/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk.txt b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..cc73da6d3cf --- /dev/null +++ b/docs/apidiffs/1.64.0_vs_1.63.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.64.0.jar against opentelemetry-sdk-1.63.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-api.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-api.txt new file mode 100644 index 00000000000..3b6e5f18e2b --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.65.0.jar against opentelemetry-api-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-common.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-common.txt new file mode 100644 index 00000000000..cf5be7dcfad --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.65.0.jar against opentelemetry-common-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-context.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-context.txt new file mode 100644 index 00000000000..ec22e42b965 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.65.0.jar against opentelemetry-context-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..17eea60b177 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.65.0.jar against opentelemetry-exporter-common-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..4303af636c0 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.65.0.jar against opentelemetry-exporter-logging-otlp-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..90f7897dd4a --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.65.0.jar against opentelemetry-exporter-logging-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..83547be3629 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.65.0.jar against opentelemetry-exporter-otlp-common-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..4e485c33ec2 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.65.0.jar against opentelemetry-exporter-otlp-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..c13f6c517fc --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.65.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..0ea1494a056 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.65.0.jar against opentelemetry-exporter-sender-jdk-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..e3b002db93f --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.65.0.jar against opentelemetry-exporter-sender-okhttp-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..1d917dadfe1 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.65.0.jar against opentelemetry-extension-kotlin-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..97238a1db0c --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.65.0.jar against opentelemetry-extension-trace-propagators-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..23b31acc50c --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.65.0.jar against opentelemetry-opentracing-shim-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..982d6b35d9d --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.65.0.jar against opentelemetry-sdk-common-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..2f981a9eb26 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.65.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..d800b025e84 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.65.0.jar against opentelemetry-sdk-extension-autoconfigure-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..cb0eab6b66f --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,6 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.65.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.64.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSampler (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + === UNCHANGED METHOD: PUBLIC void close() + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..57a439d7595 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.65.0.jar against opentelemetry-sdk-logs-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..33f5ae9807a --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,4 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.65.0.jar against opentelemetry-sdk-metrics-1.64.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder setInternalTelemetryVersion(io.opentelemetry.sdk.common.InternalTelemetryVersion) diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..0a51175c92c --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.65.0.jar against opentelemetry-sdk-testing-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..86462307ad5 --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.65.0.jar against opentelemetry-sdk-trace-1.64.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.trace.samplers.Sampler (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW INTERFACE: java.io.Closeable + +++ NEW INTERFACE: java.lang.AutoCloseable + +++ NEW METHOD: PUBLIC(+) void close() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.common.CompletableResultCode shutdown() diff --git a/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk.txt b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..1aa65f687ad --- /dev/null +++ b/docs/apidiffs/1.65.0_vs_1.64.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.65.0.jar against opentelemetry-sdk-1.64.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-api.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-api.txt new file mode 100644 index 00000000000..cc34d3dd614 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.66.0.jar against opentelemetry-api-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-common.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-common.txt new file mode 100644 index 00000000000..6bc8a1cf1d8 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.66.0.jar against opentelemetry-common-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-context.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-context.txt new file mode 100644 index 00000000000..56896948dbb --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.66.0.jar against opentelemetry-context-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..2fe461fc1d9 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.66.0.jar against opentelemetry-exporter-common-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..c9455d0e31d --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,10 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.66.0.jar against opentelemetry-exporter-logging-otlp-1.65.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingLogRecordExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingSpanExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.lang.String toString() diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..9df6e561a32 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.66.0.jar against opentelemetry-exporter-logging-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..298c630f487 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.66.0.jar against opentelemetry-exporter-otlp-common-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..22d2754728c --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.66.0.jar against opentelemetry-exporter-otlp-1.65.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setEnabledProtocols(java.util.List) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setEnabledProtocols(java.util.List) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setEnabledProtocols(java.util.List) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setEnabledProtocols(java.util.List) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setEnabledProtocols(java.util.List) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setEnabledProtocols(java.util.List) diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..34699ad03e6 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.66.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..31e282b7fa5 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.66.0.jar against opentelemetry-exporter-sender-jdk-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..7a2b9c697cc --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.66.0.jar against opentelemetry-exporter-sender-okhttp-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..5cd1d810ac4 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.66.0.jar against opentelemetry-extension-kotlin-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..5fbfd3c17b2 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.66.0.jar against opentelemetry-extension-trace-propagators-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..329d8449c37 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.66.0.jar against opentelemetry-opentracing-shim-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..878d6a230d8 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-common.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.66.0.jar against opentelemetry-sdk-common-1.65.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.common.export.GrpcSenderConfig (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.util.List getEnabledProtocols() + +++ NEW ANNOTATION: javax.annotation.Nullable +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.sdk.common.export.HttpSenderConfig (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) java.util.List getEnabledProtocols() + +++ NEW ANNOTATION: javax.annotation.Nullable diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..b6a136717bb --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.66.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..ada36c8f6dc --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.66.0.jar against opentelemetry-sdk-extension-autoconfigure-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..78d99055c5e --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.66.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..e078fcf9c00 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.66.0.jar against opentelemetry-sdk-logs-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..cc8befcde09 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.66.0.jar against opentelemetry-sdk-metrics-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..d4742285b9e --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.66.0.jar against opentelemetry-sdk-testing-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..647205d80ae --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.66.0.jar against opentelemetry-sdk-trace-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk.txt b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..cab5f37a351 --- /dev/null +++ b/docs/apidiffs/1.66.0_vs_1.65.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.66.0.jar against opentelemetry-sdk-1.65.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-api.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-api.txt new file mode 100644 index 00000000000..01d4165f9b5 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-api.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-api-1.67.0.jar against opentelemetry-api-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-common.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-common.txt new file mode 100644 index 00000000000..f4987ba5c13 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-common.txt @@ -0,0 +1,8 @@ +Comparing source compatibility of opentelemetry-common-1.67.0.jar against opentelemetry-common-1.66.0.jar ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.common.impl.ConfigUtil (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.lang.String getString(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.lang.String normalizeEnvironmentVariableKey(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.lang.String normalizePropertyKey(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.util.Properties safeSystemProperties() diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-context.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-context.txt new file mode 100644 index 00000000000..6bafb7ab241 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-context.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-context-1.67.0.jar against opentelemetry-context-1.66.0.jar +*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.context.propagation.TextMapGetter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + GENERIC TEMPLATES: === C:java.lang.Object + *** MODIFIED METHOD: PUBLIC NON_ABSTRACT (<- ABSTRACT) java.lang.Iterable keys(java.lang.Object) + +++ NEW ANNOTATION: java.lang.Deprecated + +++ NEW ANNOTATION: java.lang.FunctionalInterface diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..6b8a31fb8e3 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.67.0.jar against opentelemetry-exporter-common-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..d40e2e45e1e --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.67.0.jar against opentelemetry-exporter-logging-otlp-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..08a4cea2ace --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.67.0.jar against opentelemetry-exporter-logging-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..2f60cab423b --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.67.0.jar against opentelemetry-exporter-otlp-common-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..291881e139c --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,19 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.67.0.jar against opentelemetry-exporter-otlp-1.66.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder setMaxRequestBodySize(long) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder setMaxRequestBodySize(long) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder setMaxRequestBodySize(long) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder setMaxRequestMessageSize(long) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder setMaxRequestMessageSize(long) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder setMaxRequestMessageSize(long) diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..9ed77463685 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.67.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..fb2df21a08c --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.67.0.jar against opentelemetry-exporter-sender-jdk-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..9a7da00ecad --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.67.0.jar against opentelemetry-exporter-sender-okhttp-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..46be9292474 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.67.0.jar against opentelemetry-extension-kotlin-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..e7f0ddc51e9 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.67.0.jar against opentelemetry-extension-trace-propagators-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..f2931a0b845 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.67.0.jar against opentelemetry-opentracing-shim-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..8bbfdfd9f48 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.67.0.jar against opentelemetry-sdk-common-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..7d1e7e397d2 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.67.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..3d81f4ff416 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,9 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.67.0.jar against opentelemetry-sdk-extension-autoconfigure-1.66.0.jar ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.autoconfigure.ServiceInstanceIdResourceProvider (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW INTERFACE: io.opentelemetry.sdk.autoconfigure.spi.Ordered + +++ NEW INTERFACE: io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW CONSTRUCTOR: PUBLIC(+) ServiceInstanceIdResourceProvider() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.resources.Resource createResource(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + +++ NEW METHOD: PUBLIC(+) int order() diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..b553c9526d5 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.67.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..bca444b6abf --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.67.0.jar against opentelemetry-sdk-logs-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..4d59fd33dd7 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,7 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.67.0.jar against opentelemetry-sdk-metrics-1.66.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + *** MODIFIED METHOD: PUBLIC (<- PACKAGE_PROTECTED) io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder setMaxExportBatchSize(int) +**** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.View (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++* NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.function.Predicate getAttributeFilter() diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..b5cacedadd8 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.67.0.jar against opentelemetry-sdk-testing-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..91831055182 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.67.0.jar against opentelemetry-sdk-trace-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk.txt b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..fe8ebe753f2 --- /dev/null +++ b/docs/apidiffs/1.67.0_vs_1.66.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.67.0.jar against opentelemetry-sdk-1.66.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-api.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-api.txt new file mode 100644 index 00000000000..fcbb3e84113 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-api.txt @@ -0,0 +1,13 @@ +Comparing source compatibility of opentelemetry-api-1.68.0.jar against opentelemetry-api-1.67.0.jar ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.api.impl.Base16EncodingUtils (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) byte[] bytesFromBase16(java.lang.CharSequence, int) + +++ NEW METHOD: PUBLIC(+) STATIC(+) void bytesFromBase16(java.lang.CharSequence, int, byte[]) + +++ NEW METHOD: PUBLIC(+) STATIC(+) boolean isValidBase16String(java.lang.CharSequence) + +++ NEW METHOD: PUBLIC(+) STATIC(+) long longFromBase16String(java.lang.CharSequence, int) + +++ NEW METHOD: PUBLIC(+) STATIC(+) void longToBase16String(long, char[], int) ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.api.impl.TemporaryBuffers (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) char[] chars(int) diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-common.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-common.txt new file mode 100644 index 00000000000..595c364558f --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.68.0.jar against opentelemetry-common-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-context.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-context.txt new file mode 100644 index 00000000000..076d9ee6969 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-context.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-context-1.68.0.jar against opentelemetry-context-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-common.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..29fd8bfc2a6 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.68.0.jar against opentelemetry-exporter-common-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-logging-otlp.txt new file mode 100644 index 00000000000..c1e31d0fcad --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-logging-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.68.0.jar against opentelemetry-exporter-logging-otlp-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-logging.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-logging.txt new file mode 100644 index 00000000000..f48e9a39464 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-logging.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-logging-1.68.0.jar against opentelemetry-exporter-logging-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-otlp-common.txt new file mode 100644 index 00000000000..8545c34f81a --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-otlp-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.68.0.jar against opentelemetry-exporter-otlp-common-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-otlp.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-otlp.txt new file mode 100644 index 00000000000..35815c2ca4f --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-otlp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-otlp-1.68.0.jar against opentelemetry-exporter-otlp-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..c35b82c28cf --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.68.0.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..24cba1bb45d --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.68.0.jar against opentelemetry-exporter-sender-jdk-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..ff209a343b5 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.68.0.jar against opentelemetry-exporter-sender-okhttp-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-extension-kotlin.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-extension-kotlin.txt new file mode 100644 index 00000000000..d617211e1dc --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-extension-kotlin.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-kotlin-1.68.0.jar against opentelemetry-extension-kotlin-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-extension-trace-propagators.txt new file mode 100644 index 00000000000..f46eb7c3465 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-extension-trace-propagators.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.68.0.jar against opentelemetry-extension-trace-propagators-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-opentracing-shim.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..4fd8b146451 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.68.0.jar against opentelemetry-opentracing-shim-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-common.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-common.txt new file mode 100644 index 00000000000..b95c6e64d21 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-common-1.68.0.jar against opentelemetry-sdk-common-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-autoconfigure-spi.txt new file mode 100644 index 00000000000..bb7358989a4 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.68.0.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..aeca5e47713 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.68.0.jar against opentelemetry-sdk-extension-autoconfigure-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt new file mode 100644 index 00000000000..0ca43ffe644 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.68.0.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-logs.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..dc68c13fa8b --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.68.0.jar against opentelemetry-sdk-logs-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-metrics.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-metrics.txt new file mode 100644 index 00000000000..6355a154fe4 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-metrics.txt @@ -0,0 +1,5 @@ +Comparing source compatibility of opentelemetry-sdk-metrics-1.68.0.jar against opentelemetry-sdk-metrics-1.67.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder setExporterTimeout(long, java.util.concurrent.TimeUnit) + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder setExporterTimeout(java.time.Duration) diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-testing.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-testing.txt new file mode 100644 index 00000000000..d1aab24c36b --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-testing.txt @@ -0,0 +1,32 @@ +Comparing source compatibility of opentelemetry-sdk-testing-1.68.0.jar against opentelemetry-sdk-testing-1.67.0.jar +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.assertj.MetricAssert (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasDoubleGaugePointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasDoubleGaugePointsSatisfying(java.lang.Iterable>) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasDoubleSumPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasDoubleSumPointsSatisfying(java.lang.Iterable>) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasExponentialHistogramPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasExponentialHistogramPointsSatisfying(java.lang.Iterable>) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasHistogramPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasHistogramPointsSatisfying(java.lang.Iterable>) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasLongGaugePointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasLongGaugePointsSatisfying(java.lang.Iterable>) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasLongSumPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasLongSumPointsSatisfying(java.lang.Iterable>) + +++ NEW METHOD: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasSummaryPointsSatisfying(java.util.function.Consumer[]) + +++ NEW ANNOTATION: java.lang.SafeVarargs + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.assertj.MetricAssert hasSummaryPointsSatisfying(java.lang.Iterable>) +*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporter (not serializable) + === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporterBuilder builder() ++++ NEW CLASS: PUBLIC(+) FINAL(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporterBuilder (not serializable) + +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. + +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporter build() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporterBuilder setAggregationTemporalitySelector(io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector) diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-trace.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-trace.txt new file mode 100644 index 00000000000..f4857e70898 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk-trace.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-trace-1.68.0.jar against opentelemetry-sdk-trace-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk.txt b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk.txt new file mode 100644 index 00000000000..79ee9f1d746 --- /dev/null +++ b/docs/apidiffs/1.68.0_vs_1.67.0/opentelemetry-sdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-1.68.0.jar against opentelemetry-sdk-1.67.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-api.txt b/docs/apidiffs/current_vs_latest/opentelemetry-api.txt index 04e1e24528c..3f5c935f761 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-api.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-api.txt @@ -1,36 +1,46 @@ -Comparing source compatibility of against -+++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.metrics.BatchCallback (not serializable) +Comparing source compatibility of opentelemetry-api-1.69.0-SNAPSHOT.jar against opentelemetry-api-1.68.0.jar ++++ NEW CLASS: PUBLIC(+) io.opentelemetry.api.config.DeclarativeConfigException (compatible) +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. - +++ NEW INTERFACE: java.lang.AutoCloseable - +++ NEW SUPERCLASS: java.lang.Object - +++ NEW METHOD: PUBLIC(+) void close() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleCounterBuilder (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableDoubleMeasurement buildObserver() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleGaugeBuilder (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableDoubleMeasurement buildObserver() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.DoubleUpDownCounterBuilder (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableDoubleMeasurement buildObserver() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongCounterBuilder (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableLongMeasurement buildObserver() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongGaugeBuilder (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableLongMeasurement buildObserver() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.LongUpDownCounterBuilder (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.ObservableLongMeasurement buildObserver() -***! MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.Meter (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++! NEW METHOD: PUBLIC(+) io.opentelemetry.api.metrics.BatchCallback batchCallback(java.lang.Runnable, io.opentelemetry.api.metrics.ObservableMeasurement, io.opentelemetry.api.metrics.ObservableMeasurement[]) -*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.ObservableDoubleMeasurement (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW INTERFACE: io.opentelemetry.api.metrics.ObservableMeasurement -*** MODIFIED INTERFACE: PUBLIC ABSTRACT io.opentelemetry.api.metrics.ObservableLongMeasurement (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW INTERFACE: io.opentelemetry.api.metrics.ObservableMeasurement -+++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.metrics.ObservableMeasurement (not serializable) + +++ NEW INTERFACE: java.io.Serializable + +++ NEW SUPERCLASS: java.lang.RuntimeException + +++ NEW CONSTRUCTOR: PUBLIC(+) DeclarativeConfigException(java.lang.String) + +++ NEW CONSTRUCTOR: PUBLIC(+) DeclarativeConfigException(java.lang.String, java.lang.Throwable) ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.config.DeclarativeConfigProperties (not serializable) +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. +++ NEW SUPERCLASS: java.lang.Object + +++ NEW METHOD: PUBLIC(+) STATIC(+) io.opentelemetry.api.config.DeclarativeConfigProperties empty() + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.config.DeclarativeConfigProperties get(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Boolean getBoolean(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) boolean getBoolean(java.lang.String, boolean) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.common.ComponentLoader getComponentLoader() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Double getDouble(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) double getDouble(java.lang.String, double) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Integer getInt(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) int getInt(java.lang.String, int) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Long getLong(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) long getLong(java.lang.String, long) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.Set getPropertyKeys() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.List getScalarList(java.lang.String, java.lang.Class) + +++ NEW ANNOTATION: javax.annotation.Nullable + GENERIC TEMPLATES: +++ T:java.lang.Object + +++ NEW METHOD: PUBLIC(+) java.util.List getScalarList(java.lang.String, java.lang.Class, java.util.List) + GENERIC TEMPLATES: +++ T:java.lang.Object + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getString(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) java.lang.String getString(java.lang.String, java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.api.config.DeclarativeConfigProperties getStructured(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) io.opentelemetry.api.config.DeclarativeConfigProperties getStructured(java.lang.String, io.opentelemetry.api.config.DeclarativeConfigProperties) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.util.List getStructuredList(java.lang.String) + +++ NEW ANNOTATION: javax.annotation.Nullable + +++ NEW METHOD: PUBLIC(+) java.util.List getStructuredList(java.lang.String, java.util.List) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean isBoolean(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean isDouble(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean isInt(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean isLong(java.lang.String) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) boolean isString(java.lang.String) + +++ NEW METHOD: PUBLIC(+) STATIC(+) java.util.Map toMap(io.opentelemetry.api.config.DeclarativeConfigProperties) diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-common.txt b/docs/apidiffs/current_vs_latest/opentelemetry-common.txt new file mode 100644 index 00000000000..123d439aa90 --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-common-1.69.0-SNAPSHOT.jar against opentelemetry-common-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-context.txt b/docs/apidiffs/current_vs_latest/opentelemetry-context.txt index df26146497b..06bd806a807 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-context.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-context.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-context-1.69.0-SNAPSHOT.jar against opentelemetry-context-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-common.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-common.txt new file mode 100644 index 00000000000..663d788f36f --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-common.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-common-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-common-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging-otlp.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging-otlp.txt index df26146497b..ffc5d6751ff 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging-otlp.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging-otlp.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-exporter-logging-otlp-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-logging-otlp-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging.txt index df26146497b..b51a811c36e 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-logging.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-exporter-logging-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-logging-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-common.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-common.txt index df26146497b..7999376b4f4 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-common.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp-common.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-exporter-otlp-common-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-otlp-common-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp.txt index df26146497b..c0b4195a25f 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-otlp.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-exporter-otlp-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-otlp-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-grpc-managed-channel.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-grpc-managed-channel.txt new file mode 100644 index 00000000000..6a91a158b27 --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-grpc-managed-channel.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-grpc-managed-channel-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-sender-grpc-managed-channel-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-jdk.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-jdk.txt new file mode 100644 index 00000000000..f79f1c2ce3d --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-jdk.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-jdk-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-sender-jdk-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-okhttp.txt b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-okhttp.txt new file mode 100644 index 00000000000..4d7dd2fa17a --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-exporter-sender-okhttp.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-exporter-sender-okhttp-1.69.0-SNAPSHOT.jar against opentelemetry-exporter-sender-okhttp-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-extension-kotlin.txt b/docs/apidiffs/current_vs_latest/opentelemetry-extension-kotlin.txt index df26146497b..665578ee19e 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-extension-kotlin.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-extension-kotlin.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-extension-kotlin-1.69.0-SNAPSHOT.jar against opentelemetry-extension-kotlin-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-extension-trace-propagators.txt b/docs/apidiffs/current_vs_latest/opentelemetry-extension-trace-propagators.txt index df26146497b..1b13ae71301 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-extension-trace-propagators.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-extension-trace-propagators.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-extension-trace-propagators-1.69.0-SNAPSHOT.jar against opentelemetry-extension-trace-propagators-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-opentracing-shim.txt b/docs/apidiffs/current_vs_latest/opentelemetry-opentracing-shim.txt new file mode 100644 index 00000000000..06cc9a344a8 --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-opentracing-shim.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-opentracing-shim-1.69.0-SNAPSHOT.jar against opentelemetry-opentracing-shim-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-common.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-common.txt index df26146497b..11effdbb7b2 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-common.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-common.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-sdk-common-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-common-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure-spi.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure-spi.txt index 15e711a77fb..e9d9c15d5f0 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure-spi.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure-spi.txt @@ -1,6 +1,7 @@ -Comparing source compatibility of against -+++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider (not serializable) +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-spi-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-extension-autoconfigure-spi-1.68.0.jar ++++ NEW INTERFACE: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider (not serializable) +++ CLASS FILE FORMAT VERSION: 52.0 <- n.a. +++ NEW SUPERCLASS: java.lang.Object - +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) io.opentelemetry.sdk.metrics.export.MetricExporter createExporter(io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties) + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Object create(io.opentelemetry.api.config.DeclarativeConfigProperties) +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.String getName() + +++ NEW METHOD: PUBLIC(+) ABSTRACT(+) java.lang.Class getType() diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure.txt new file mode 100644 index 00000000000..63c30542c8b --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-autoconfigure.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-extension-autoconfigure-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-extension-autoconfigure-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-jaeger-remote-sampler.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-jaeger-remote-sampler.txt index df26146497b..9f8eb47a24a 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-jaeger-remote-sampler.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-extension-jaeger-remote-sampler.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-sdk-extension-jaeger-remote-sampler-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-extension-jaeger-remote-sampler-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-logs.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-logs.txt new file mode 100644 index 00000000000..94a4aa9ea1c --- /dev/null +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-logs.txt @@ -0,0 +1,2 @@ +Comparing source compatibility of opentelemetry-sdk-logs-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-logs-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-metrics.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-metrics.txt index 3598f6e084d..f7029245718 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-metrics.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-metrics.txt @@ -1,13 +1,2 @@ -Comparing source compatibility of against -*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.export.PeriodicMetricReader (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) java.lang.String toString() -*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.InstrumentSelector (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) FINAL(+) java.lang.String toString() -*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.metrics.SdkMeterProvider (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) java.lang.String toString() -*** MODIFIED CLASS: PUBLIC ABSTRACT io.opentelemetry.sdk.metrics.View (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) FINAL(+) java.lang.String toString() +Comparing source compatibility of opentelemetry-sdk-metrics-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-metrics-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-testing.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-testing.txt index 9e4477426ed..792bcf705d1 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-testing.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-testing.txt @@ -1,12 +1,2 @@ -Comparing source compatibility of against -*** MODIFIED CLASS: PUBLIC io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) java.lang.String toString() -*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.junit4.OpenTelemetryRule (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) void clearMetrics() - +++ NEW METHOD: PUBLIC(+) java.util.List getMetrics() -*** MODIFIED CLASS: PUBLIC FINAL io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension (not serializable) - === CLASS FILE FORMAT VERSION: 52.0 <- 52.0 - +++ NEW METHOD: PUBLIC(+) void clearMetrics() - +++ NEW METHOD: PUBLIC(+) java.util.List getMetrics() +Comparing source compatibility of opentelemetry-sdk-testing-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-testing-1.68.0.jar +No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-trace.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-trace.txt index df26146497b..d0cedf669c5 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk-trace.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk-trace.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-sdk-trace-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-trace-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/apidiffs/current_vs_latest/opentelemetry-sdk.txt b/docs/apidiffs/current_vs_latest/opentelemetry-sdk.txt index df26146497b..e187a225a87 100644 --- a/docs/apidiffs/current_vs_latest/opentelemetry-sdk.txt +++ b/docs/apidiffs/current_vs_latest/opentelemetry-sdk.txt @@ -1,2 +1,2 @@ -Comparing source compatibility of against +Comparing source compatibility of opentelemetry-sdk-1.69.0-SNAPSHOT.jar against opentelemetry-sdk-1.68.0.jar No changes. \ No newline at end of file diff --git a/docs/jmh.md b/docs/jmh.md deleted file mode 100644 index 698e0174419..00000000000 --- a/docs/jmh.md +++ /dev/null @@ -1,21 +0,0 @@ - -# how to jmh - -[jmh] (Java Benchmark Harness) is a tool for running benchmarks and reporting results. - -opentelemetry-java has a lot of micro benchmarks. They live inside -`jmh` directories in the appropriate module. - -The benchmarks are run with a gradle plugin. - -To run an entire suite for a module, you can run the jmh gradle task. -As an example, here's how you can run the benchmarks for all of -the sdk trace module. - -``` -`./gradlew :sdk:trace:jmh` -``` - -If you just want to run a single benchmark and not the entire suite: - -`./gradlew -PjmhIncludeSingleClass=BatchSpanProcessorBenchmark :sdk:trace:jmh` diff --git a/docs/knowledge/README.md b/docs/knowledge/README.md new file mode 100644 index 00000000000..b05ca895ace --- /dev/null +++ b/docs/knowledge/README.md @@ -0,0 +1,28 @@ +# Knowledge Index + +Repository guidance for coding and review, written to be useful for both humans and machines. + +**For humans**: these documents use plain language and examples rather than rigid rules. Where +something is a strong convention, it's described as such. Where something is a matter of +judgment, it's described that way too. + +**For machines**: load only files relevant to the current scope β€” the "Load when" column below +is the signal. + +## Topics + +| File | Load when | +|------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------| +| [build.md](build.md) | Always β€” build requirements and common tasks | +| [general-patterns.md](general-patterns.md) | Always β€” style, nullability, visibility, AutoValue, locking, logging, internal & impl packages | +| [api-design.md](api-design.md) | Public API additions, removals, renames, or deprecations or implementations; configuration changes; null guards; stable vs alpha compatibility | +| [gradle-conventions.md](gradle-conventions.md) | `build.gradle.kts` or `settings.gradle.kts` changes; new modules | +| [testing-patterns.md](testing-patterns.md) | Test files in scope β€” assertions, test utilities, test suites | +| [other-tasks.md](other-tasks.md) | Dev environment setup, benchmarks, composite builds, native image tests, OTLP protobuf updates | + +## Conventions + +- File names are kebab-cased and topic-oriented. Most follow a `-.md` pattern + (e.g. `api-design.md`, `testing-patterns.md`). +- Sections within each document are ordered alphabetically, with the exception of any + introductory content placed directly under the document title. diff --git a/docs/knowledge/api-design.md b/docs/knowledge/api-design.md new file mode 100644 index 00000000000..fd63bd8ec54 --- /dev/null +++ b/docs/knowledge/api-design.md @@ -0,0 +1,208 @@ +# API Design + +See [VERSIONING.md](../../VERSIONING.md) for the full versioning and compatibility policy. + +## Breaking changes in alpha modules + +Breaking changes are allowed in alpha modules but should still be approached carefully: + +- Prefer going through a deprecation cycle to ease migration, unless the deprecation would be too + cumbersome or the old API is genuinely unusable. +- Bundle breaking changes together where possible to reduce churn for consumers. +- Deprecations in alpha modules are typically introduced and removed within one release cycle + (approximately one month). + +## Breaking changes in stable modules + +Breaking changes are not allowed in stable modules outside of a major version bump. The build +enforces this via japicmp β€” see [japicmp](#japicmp) below. + +## Configuration + +There are [3 configuration interfaces](https://github.com/open-telemetry/opentelemetry-specification/tree/main/specification/configuration#configuration-interfaces): + +- Programmatic configuration: invoke Java APIs to build components. This is the base of all other + configuration interfaces. +- Env var / system property configuration: set flat env vars / system properties, which are + interpreted to equivalent calls to the programmatic configuration interface. +- Declarative configuration: structured, YAML-based configuration, which is interpreted to + equivalent calls to the programmatic configuration interface. + +As a general rule, all configuration interfaces are bound by the spec. However, we make certain +exceptions with Java-specific additions in places where the lack of such features is detrimental to +the OpenTelemetry Java ecosystem. For example: + +- The OTLP exporters have programmatic proxy configuration options. Despite not being part of the + spec, this is a common enough use case that not supporting it would be a glaring oversight. +- Env var / system property configuration has an `otel.java.metrics.cardinality.limit` property for + configuring a global cardinality limit. This is not part of the spec, but it is an important and + common enough use case that we added a Java-specific property for it. + +Configuration options outside the spec are added at maintainers' discretion. If proposing an +option outside the spec, start with programmatic configuration, which we are much more likely to +accept. + +Declarative configuration is stable at the spec level and was designed to solve the expressiveness +shortcomings of env var / system property configuration. It is the priority interface for current +and future configuration enhancements. By default, new non-programmatic configuration options +should target declarative configuration. This means: + +- We are judicious about extending the env var / system property configuration interface with new + options. Additions are at maintainers' discretion. When proposing such an addition, also open a + corresponding issue or discussion post describing the use-case and justification. +- Declarative configuration must be a strict superset of env var / system property configuration. + In the event new env var / system properties are added, there must be equivalent capabilities in + declarative config, with the caveat that naming and structure do not need to be identical. + +Configuration is part of our public API surface area, subject to our +[versioning policy](../../VERSIONING.md) unless explicitly marked unstable (for example, +`*.experimental.*` for env vars / system properties and `*/development` for declarative config). + +### Zero values + +Prefer `0` to mean "no limit" for optional upper bounds, such as export timeouts +and maximum request sizes, when disabling the bound has well-defined semantics +and does not trigger a large up-front memory allocation. + +The litmus test is: "Can we disable this bound coherently without treating +infinity as an allocation size or changing the component's operating model?" + +Require positive values for concrete allocation capacities, such as batch +processor queue and batch sizes, or when unlimited behavior would require a +materially different implementation. Preserve meaningful literal-zero semantics, +such as no delay, rather than interpreting zero intervals as infinity. + +Follow specification-defined semantics. Relaxing an API to accept a previously +rejected `0` is allowed, including in stable modules. Document and test zero +behavior explicitly. + +## Deprecating API + +Applies to both stable and alpha modules. Use plain `@Deprecated` β€” do **not** use +`forRemoval = true` or `since = "..."` (Java 8 compatibility requirement). + +```java +/** + * @deprecated Use {@link #newMethod()} instead. + */ +@Deprecated +public ReturnType oldMethod() { + return newMethod(); // delegate to replacement +} +``` + +Rules: +- Include a `@deprecated` Javadoc tag naming the replacement. +- The deprecated method must delegate to its replacement, not the other way around β€” this ensures + overriders of the old method still get called. +- Deprecated items in stable modules cannot be removed until the next major version. +- Deprecated items in alpha modules should indicate when they will be removed (e.g. + `// to be removed in 1.X.0`). It is also common to log a warning when a deprecated-for-removal + feature is used, to increase visibility for consumers. +- Add the `deprecation` label to the PR. + +## japicmp + +`otel.japicmp-conventions` runs the `jApiCmp` task as part of `check` for every published module. +It compares the locally-built jar against the release pinned by `apidiffBaselineVersion` in +`version.gradle.kts` to detect breaking changes, and writes a human-readable diff to +`docs/apidiffs/current_vs_latest/.txt`. + +- Breaking changes in stable modules fail the build. +- AutoValue classes are exempt from the abstract-method-added check β€” the generated implementation + handles those automatically. +- The diff files are committed to the repo. Include any changes to them in your PR. +- Run `./gradlew jApiCmp` to regenerate diffs after API changes. + +## Null guards + +`@Nullable` annotations (see [general-patterns.md](general-patterns.md)) and +[NullAway](https://github.com/uber/NullAway) enforce null contracts at build time within this +repo. At runtime there is no such guarantee β€” callers in other +codebases can pass `null` regardless of annotations. Add null guards only at **public API entry +points**; once inside the implementation, trust NullAway. + +### Configuration-time boundaries (SDK builders, provider factories) + +Fail fast with `Objects.requireNonNull`: + +```java +public SdkTracerProviderBuilder setResource(Resource resource) { + Objects.requireNonNull(resource, "resource"); + this.resource = resource; + return this; +} +``` + +These APIs are called once during startup, so a hard failure surfaces the bug immediately and +unambiguously. + +### Runtime / instrumentation-time boundaries (Span methods, metric recordings, log builders) + +Do **not** throw. Log the violation via +[`ApiUsageLogger`](../../common/src/main/java/io/opentelemetry/common/impl/ApiUsageLogger.java) β€” +which logs at `FINEST` with a stack trace so the offending call site is visible β€” then degrade +gracefully (return `this`, an empty/noop result, or substitute a safe default such as +`Attributes.empty()` or `Context.current()`): + +```java +@Override +public Span addEvent(String name) { + if (name == null) { + ApiUsageLogger.logNullParam(Span.class, "addEvent", "name"); + return this; + } + // ... normal implementation +} +``` + +Return after logging unless the remaining code is a noop or explicitly handles null (for example, by +substituting a default). Do not continue into a loop or other logic just because it happens to +tolerate null. + +Check non-`@Nullable` reference arguments in declaration order, logging each null once unless an +early return ends the call. + +The class and method arguments identify the problem immediately in the log message without +requiring stack trace analysis. Use `ApiUsageLogger.log(...)` directly when the message is not +simply "X is null" (e.g. `"spanIdBytes is null or too short"`). `FINEST` is silent by default, so there is no production noise. +To investigate misuse, enable the logger named `io.opentelemetry.usage` at `FINEST` in +development, or periodically in staging/production. Check each argument once, at the first +public entry point β€” internal methods called by that entry point do not need to re-validate. + +### SDK extension interfaces and SPIs + +These interfaces are called by the SDK, not directly by application developers. +Examples include `Sampler`, `SpanExporter`, `SpanProcessor`, `LogRecordExporter`, +`MetricExporter`, `MetricReader`, `ComponentProvider`, and SPI interfaces such as those in +`sdk-extensions/autoconfigure-spi` (`ResourceProvider`, `AutoConfigurationCustomizerProvider`, +etc.), `HttpSenderProvider`, and `ContextStorageProvider`. + +Because the SDK is NullAway-verified, a null argument here indicates a bug in the SDK itself, +not misuse by an application developer. Use `Objects.requireNonNull` β€” a hard failure surfaces +the bug immediately and unambiguously, which is preferable to silent degradation that would +mask the underlying SDK defect. + +### Where to implement guards + +Add guards in the concrete implementation class, or in an existing `default` interface method +that would otherwise NPE. Do **not** add new `default` methods to interfaces solely for null +safety β€” that expands the interface surface without a functional benefit. + +## Stable vs alpha modules + +Artifacts without an `-alpha` version suffix are **stable**. Artifacts with `-alpha` have no +compatibility guarantees and may break on every release. The `internal` package is always exempt +from compatibility guarantees regardless of artifact stability. + +To mark a module as alpha, add a `gradle.properties` file at the module root containing: + +```properties +otel.release=alpha +``` + +See [`exporters/prometheus/gradle.properties`](../../exporters/prometheus/gradle.properties) for +an example. + +See [VERSIONING.md](../../VERSIONING.md) for the full compatibility policy, including what +constitutes a source-incompatible vs binary-incompatible change. diff --git a/docs/knowledge/build.md b/docs/knowledge/build.md new file mode 100644 index 00000000000..c309cf2c8bb --- /dev/null +++ b/docs/knowledge/build.md @@ -0,0 +1,36 @@ +# Build + +Java 25 or higher is required to build. The built artifacts target Java 8 or higher. + +## Common tasks + +```bash +# Fix formatting violations +./gradlew spotlessApply + +# Run checks only (tests + static analysis + formatting verification) +./gradlew check + +# Build, run tests, static analysis, and check formatting +./gradlew build +``` + +All tasks can be scoped to a single module by prefixing with the module path: + +```bash +./gradlew :sdk:metrics:spotlessApply +./gradlew :sdk:metrics:check +./gradlew :sdk:metrics:build +``` + +`./gradlew build` and `./gradlew check` both depend on the `jApiCmp` task, which compares the +locally-built jars against the release pinned by `apidiffBaselineVersion` in `version.gradle.kts` +and writes diffs to `docs/apidiffs/current_vs_latest/`. Include any changes to those files in your +PR. See [api-design.md](api-design.md#japicmp) for details. + +If your branch is not up to date with `main`, `jApiCmp` may produce a diff that reflects changes +already merged to `main` rather than your own changes. Rebase or merge `main` before treating +the diff as meaningful. + +For dev environment setup, composite builds, OTLP protobuf updates, and other tasks, see +[other-tasks.md](other-tasks.md). diff --git a/docs/knowledge/general-patterns.md b/docs/knowledge/general-patterns.md new file mode 100644 index 00000000000..7d5860d87a4 --- /dev/null +++ b/docs/knowledge/general-patterns.md @@ -0,0 +1,174 @@ +# General Patterns + +## @Nullable + +All arguments and members are treated as non-null by default. Annotate with `@Nullable` (from +`javax.annotation`) only when `null` is actually possible. + +- **Fields**: annotate only if the field can hold `null` after construction. +- **Parameters**: annotate only if `null` is actually passed by callers. +- **Return types**: annotate only if the method actually returns `null`. A non-null implementation + of a `@Nullable`-declared interface method should omit the annotation β€” it is more precise. + +For null guard behavior at public API boundaries, see [api-design.md](api-design.md). + +## API consistency + +The project aims to provide a consistent experience across all public APIs. When designing new +API, look for prior art in the project before introducing new patterns β€” prefer the style already +established in the same package, then the same module, then the broader project. + +## AutoValue + +Use [AutoValue](https://github.com/google/auto/tree/master/value) for new value classes. + +- Add `annotationProcessor("com.google.auto.value:auto-value")` in `build.gradle.kts`. +- `auto-value-annotations` is already available via `otel.java-conventions`. +- Add a package-private constructor to all AutoValue classes to prevent external extension. +- `japicmp` allows new abstract methods on AutoValue classes β€” the `AllowNewAbstractMethodOnAutovalueClasses` rule handles this. + +## Class member ordering + +In general, order class members as follows: + +1. Static fields (final before non-final) +2. Instance fields (final before non-final) +3. Constructors + - In static utility classes, the private constructor goes after methods, not before. +4. Methods + - If methods call each other, the calling method should appear above the method it calls. +5. Nested classes + +## Dedicated lock objects + +Do not synchronize using a class's intrinsic lock (`synchronized(this)` or `synchronized` method). +Use a dedicated lock object: + +```java +private final Object lock = new Object(); + +public void doSomething() { + synchronized (lock) { ... } +} +``` + +## Formatting + +Formatting is enforced by three tools. Run `./gradlew spotlessApply` before committing β€” it fixes +most violations automatically. + +- **Spotless** β€” formatting rules vary by file type (see `buildSrc/src/main/kotlin/otel.spotless-conventions.gradle.kts`): + Java uses google-java-format; Kotlin uses ktlint. Also enforces the Apache license header + (template in `buildscripts/spotless.license.java`) and misc file hygiene (trailing whitespace, + final newline, etc.). +- **Checkstyle** β€” enforces naming conventions, import ordering, Javadoc structure, and other + rules not covered by formatting alone. Config is in `buildscripts/checkstyle.xml`. +- **EditorConfig** (`.editorconfig`) β€” configures IntelliJ to match project style automatically. + It doesn't cover all rules, so `spotlessApply` is still required. + +## Impl (Implementation) code + +Use `*.impl.*` sub-packages for code that must be `public` to be shared across OpenTelemetry +modules, but is not intended for use by application developers. This is the right choice when +`*.internal.*` is too restrictive β€” for example, a utility used by both the API and SDK modules +that needs a stable contract across module boundaries. + +Unlike `*.internal.*` packages, `*.impl.*` packages carry full backwards-compatibility guarantees +and are included in `japicmp` compatibility checks. + +Public classes in `impl` packages must carry the following disclaimer (enforced by the +`OtelImplJavadoc` Error Prone check in `custom-checks/`): + +```java +/** + * This class is not intended for use by application developers. Its API is stable and will not + * be changed or removed in a backwards-incompatible manner. + */ +``` + +See also [Internal code](#internal-code) for code that is not for application developers and has +no stability guarantees. + +## Internal code + +Prefer package-private over putting code in an `internal` package. Use `internal` only when the +code must be `public` for technical reasons (e.g. accessed across packages within the same module) +but should not be part of the public API. + +Public classes in `internal` packages are excluded from semver guarantees and Javadoc, but they +must carry one of the two standard disclaimers (enforced by the `OtelInternalJavadoc` Error Prone +check in `custom-checks/`): + +```java +// Standard internal disclaimer: +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ + +// For incubating internal code that may be promoted to public API: +/** + * This class is internal and experimental. Its APIs are unstable and can change at any time. + * Its APIs (or a version of them) may be promoted to the public stable API in the future, but + * no guarantees are made. + */ +``` + +Internal code must not be used across module boundaries β€” module `foo` must not call internal +code from module `bar`. Cross-module internal usage is a known issue being tracked and cleaned up +in open-telemetry/opentelemetry-java#6970. + +See also [Impl (Implementation) code](#impl-implementation-code) for cross-module code that is not for application developers but +requires a stable API. + +## Javadoc + +All public classes, and their public and protected methods, must have complete Javadoc including +all parameters β€” this is enforced for public APIs. Package-private and private members may have +Javadoc at the author's discretion. + +- No `@author` tags. +- New public API elements require a `@since` annotation. This is added automatically during the + [release process](../../RELEASING.md) β€” do not include it in your PR. +- See [section 7.3.1](https://google.github.io/styleguide/javaguide.html#s7.3.1-javadoc-exception-self-explanatory) + for self-explanatory exceptions. + +Published Javadoc is available at https://javadoc.io/doc/io.opentelemetry. + +## Language version compatibility + +Production code targets Java 8. Test code also targets Java 8. Do not use Java 9+ APIs unless +the module explicitly sets a higher minimum. See [VERSIONING.md](../../VERSIONING.md) for the full +language version compatibility policy, including Android and Kotlin minimum versions. + +## Logging + +Use `java.util.logging` (JUL) in production source sets. Do not use SLF4J or other logging +frameworks in `src/main/`. Tests bridge JUL to SLF4J via `JulBridgeInitializer` (configured +automatically by `otel.java-conventions`). + +```java +private static final Logger LOGGER = Logger.getLogger(MyClass.class.getName()); +``` + +When logging exceptions, pass the exception as the `Throwable` parameter to the logger rather +than stringifying it via `getMessage()` or concatenation. This ensures logging frameworks can +render the full stack trace. + +```java +// Do: +logger.log(Level.WARNING, "Failed to process request", exception); +// Don't: +logger.warning("Failed to process request: " + exception.getMessage()); +``` + +## toString() + +Adding `toString()` overrides is encouraged for debugging assistance. All `toString()` +implementations should be considered unstable unless explicitly documented otherwise β€” do not +rely on their output programmatically. + +## Visibility + +Use the most restrictive access modifier that still allows the code to function correctly. Use +`final` on classes unless extension is explicitly intended. diff --git a/docs/knowledge/gradle-conventions.md b/docs/knowledge/gradle-conventions.md new file mode 100644 index 00000000000..394eb54b1b7 --- /dev/null +++ b/docs/knowledge/gradle-conventions.md @@ -0,0 +1,78 @@ +# Gradle Conventions + +## AutoValue in build files + +See [general-patterns.md](general-patterns.md#autovalue) for the AutoValue usage pattern. +`auto-value-annotations` is provided globally by `otel.java-conventions`. Only add the +annotation processor if the module uses AutoValue in production code: + +```kotlin +dependencies { + annotationProcessor("com.google.auto.value:auto-value") // production + testAnnotationProcessor("com.google.auto.value:auto-value") // tests only +} +``` + +## Convention plugins + +Every module applies a base set of convention plugins from `buildSrc/src/main/kotlin/`. + +| Plugin | Purpose | Who applies it | +| --- | --- | --- | +| `otel.java-conventions` | Base Java toolchain, Checkstyle, Spotless, Error Prone, test config | All modules | +| `otel.publish-conventions` | Maven publishing, POM generation | Published (non-internal) modules | +| `otel.animalsniffer-conventions` | Android API level compatibility checking | Modules targeting Android | +| `otel.jmh-conventions` | JMH benchmark support | Modules with benchmarks | +| `otel.japicmp-conventions` | API diff generation against the pinned `apidiffBaselineVersion` release | Published modules (applied by `otel.publish-conventions`) | +| `otel.protobuf-conventions` | Protobuf code generation | Protobuf modules only | + +A typical published module: + +```kotlin +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") +} +``` + +A testing-internal module (shared test utilities, not published): + +```kotlin +plugins { + id("otel.java-conventions") + // no otel.publish-conventions +} +``` + +## Dependency resolution + +All external dependency versions are managed by `:dependencyManagement` (a BOM). Do not +specify versions directly in `build.gradle.kts` β€” add new entries to the BOM if a version +needs to be pinned. + +`otel.java-conventions` configures `failOnVersionConflict()` and `preferProjectModules()` +globally. Do not override these without a strong reason. + +## Module naming + +Every module must declare its Java module name: + +```kotlin +otelJava.moduleName.set("io.opentelemetry.sdk.metrics") +``` + +When the archive name cannot be derived correctly from the project name, set it explicitly: + +```kotlin +base.archivesName.set("opentelemetry-api") +``` + +## `settings.gradle.kts` ordering + +New `include(...)` entries must be in **alphabetical order** within their surrounding group. The +file is large β€” find the right lexicographic position before inserting. + +## Shared test utilities and test suites + +See [testing-patterns.md](testing-patterns.md) for shared test utility patterns and test suite +registration. diff --git a/docs/knowledge/other-tasks.md b/docs/knowledge/other-tasks.md new file mode 100644 index 00000000000..8f7c4f8cee9 --- /dev/null +++ b/docs/knowledge/other-tasks.md @@ -0,0 +1,112 @@ +# Other Tasks + +## Benchmarks (JMH) + +Microbenchmarks use [JMH](https://github.com/openjdk/jmh) via the `otel.jmh-conventions` plugin. +Benchmark sources live in `jmh/` directories within their respective modules. + +```bash +# Run all benchmarks for a module +./gradlew :sdk:trace:jmh + +# Run a single benchmark class +./gradlew -PjmhIncludeSingleClass=BatchSpanProcessorBenchmark :sdk:trace:jmh +``` + +The following JMH parameters can be configured via `-P` flags: + +| Flag | JMH setting | Example | +|---|---|---| +| `-PjmhIncludeSingleClass=` | Run only this benchmark class | `-PjmhIncludeSingleClass=BatchSpanProcessorBenchmark` | +| `-PjmhFork=` | Number of forks | `-PjmhFork=1` | +| `-PjmhIterations=` | Measurement iterations | `-PjmhIterations=5` | +| `-PjmhTime=` | Time per measurement iteration | `-PjmhTime=2s` | +| `-PjmhWarmupIterations=` | Warmup iterations | `-PjmhWarmupIterations=3` | +| `-PjmhWarmup=` | Time per warmup iteration | `-PjmhWarmup=1s` | +| `-PjmhResultsDir=` | Copy JSON results to this directory after the run | `-PjmhResultsDir=scratch/benchmarks` | +| `-PjmhLabel=` | Filename stem for the copied JSON; only used when `jmhResultsDir` is set (default: sanitized project path, e.g. `sdk-all`) | `-PjmhLabel=baseline` | + +## Composite builds + +> **No compatibility guarantees**: this process can change at any time. Steps that work for one +> commit may break with the next. + +To test local changes to this repo against another project (e.g. instrumentation or an app), +use Gradle [composite builds](https://docs.gradle.org/current/userguide/composite_builds.html). + +This repo does not work with composite builds out of the box because Gradle cannot automatically +map project names to the customized Maven artifact coordinates (see +[gradle/gradle#18291](https://github.com/gradle/gradle/issues/18291)). A helper task generates +the required substitution mappings. + +1. Run `./gradlew generateBuildSubstitutions` β€” generates `build/substitutions.gradle.kts` in + the `bom/` and `bom-alpha/` directories, containing substitutions for stable and alpha + projects respectively. +2. In the consuming project's `settings.gradle.kts`, add an `includeBuild` block and paste in + the generated `dependencySubstitution` content: + + ```kotlin + includeBuild("PATH/TO/OPENTELEMETRY-JAVA/ROOT/DIRECTORY") { + // paste from generated substitutions.gradle.kts + dependencySubstitution { + substitute(module("io.opentelemetry:opentelemetry-api")).using(project(":api:all")) + substitute(module("io.opentelemetry:opentelemetry-sdk")).using(project(":sdk:all")) + // ... + } + } + ``` + +3. Confirm the local version aligns with the version declared in the consuming project β€” + if they differ, `dependencySubstitution` may not take effect. +4. Use the prefix `:DIRECTORY:` to invoke tasks within the included build, where `DIRECTORY` + is the last path component of the included build's root directory. + +See [discussions/6551](https://github.com/open-telemetry/opentelemetry-java/discussions/6551) for +known issues and solutions. + +## Dev environment setup + +### EditorConfig + +An `.editorconfig` file is provided and automatically applied by IntelliJ to match project style. +It doesn't cover all formatting rules β€” `./gradlew spotlessApply` is still required β€” but it +reduces friction for common cases. + +### Pre-commit hook + +A pre-commit hook that runs `spotlessApply` automatically is provided at `buildscripts/pre-commit`. +Copy or symlink it into `.git/hooks/` to delegate formatting to the machine: + +```bash +cp buildscripts/pre-commit .git/hooks/pre-commit +# or +ln -s ../../buildscripts/pre-commit .git/hooks/pre-commit +``` + +## Native image tests (GraalVM) + +GraalVM native image integration tests live in `integration-tests/graal` and +`integration-tests/graal-incubating`. They are **not** part of the standard `build` task and +require a GraalVM JDK with `native-image` installed. + +```bash +# Both flags required due to https://github.com/graalvm/native-build-tools/issues/477: +# --no-parallel prevents a race where the plugin's shared build service creates project-scoped +# detached configurations that are concurrently accessed during task fingerprinting. +# --no-configuration-cache prevents the cache store phase from adding additional concurrency. +./gradlew nativeTest --no-configuration-cache --no-parallel +``` + +## Updating OTLP protobufs + +OTLP protobuf Java bindings are published via +[opentelemetry-proto-java](https://github.com/open-telemetry/opentelemetry-proto-java). This +project uses the `.proto` files published in that binding jar, not the generated Java bindings +themselves. + +When a new version of the upstream proto definitions is released, the process is: + +1. [Release a new version of the java bindings](https://github.com/open-telemetry/opentelemetry-proto-java/blob/main/RELEASING.md) + in the `opentelemetry-proto-java` repo (which we maintain). +2. Renovate will automatically open a PR to update `io.opentelemetry.proto:opentelemetry-proto` + in this repo once the new version is published. diff --git a/docs/knowledge/testing-patterns.md b/docs/knowledge/testing-patterns.md new file mode 100644 index 00000000000..760af9171d8 --- /dev/null +++ b/docs/knowledge/testing-patterns.md @@ -0,0 +1,156 @@ +# Testing Patterns + +## Assertion library + +Use [AssertJ](https://assertj.github.io/doc/) for all assertions. + +```java +import static org.assertj.core.api.Assertions.assertThat; + +assertThat(result).isEqualTo(expected); +assertThat(list).hasSize(3).contains("foo"); +assertThatThrownBy(() -> doThing()).isInstanceOf(IllegalArgumentException.class); +``` + +For SDK signal data (spans, metrics, logs), use the OTel-specific assertj extensions from +`sdk:testing`: + +```java +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +``` + +These provide fluent assertions on `SpanData`, `MetricData`, `LogRecordData`, etc. + +## Clocks and time + +Avoid `System.currentTimeMillis()` or `Instant.now()` in tests. Use `TestClock` from +`sdk:testing` for deterministic time control: + +```java +TestClock clock = TestClock.create(); +clock.advance(Duration.ofSeconds(1)); +``` + +## Equals and hashCode + +Use [EqualsVerifier](https://jqno.nl/equalsverifier/) to verify `equals`/`hashCode` contracts: + +```java +EqualsVerifier.forClass(MyValueClass.class).verify(); +``` + +Available in all test suites via `otel.java-conventions`. + +## Log capture + +Use [LogUnit](https://github.com/netmikey/logunit) to assert on log output: + +```java +@RegisterExtension +LogCapturer logs = LogCapturer.create().captureForType(MyClass.class); + +@Test +void logsWarning() { + // trigger code under test + logs.assertContains("expected warning text"); +} +``` + +`logunit-jul` is included in all test suites via `otel.java-conventions`. + +## Parameterized tests + +Prefer `@ParameterizedTest` with `@MethodSource` when testing the same logic across multiple +inputs. This keeps assertions in one place and gives each case a distinct name in the test report. + +Use `Arguments.argumentSet(String name, Object... args)` to name each case. This requires no +changes to the test method signature and no `name =` attribute on the annotation: + +```java +@ParameterizedTest +@MethodSource("createTestCases") +void create(MyModel model, MyResult expected) { + assertThat(factory.create(model)).isEqualTo(expected); +} + +static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet("http default", new MyModel().withHttp(...), expectedHttp), + Arguments.argumentSet("grpc default", new MyModel().withGrpc(...), expectedGrpc)); +} +``` + +## Mocking + +Mockito is available in all test suites via `otel.java-conventions`. Use +`@ExtendWith(MockitoExtension.class)` with `@Mock` fields, or `Mockito.mock(...)` inline. + +```java +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MyTest { + @Mock MetricReader reader; +} +``` + +The byte-buddy agent is pre-attached by `otel.java-conventions` to suppress dynamic-agent +warnings on Java 21+. No extra configuration needed. + +## Shared test utilities + +Do **not** use the `java-test-fixtures` plugin. It adds test dependencies to published POMs and +creates a separate `*-test-fixtures.jar` artifact. Shared test utilities belong in a +`*:testing-internal` module. + +The root `:testing-internal` module (`/testing-internal/`) contains utilities available across +all modules. It is included automatically by `otel.java-conventions` as a test dependency. + +For module-group-specific utilities, create a sibling `testing-internal` module: + +``` +sdk/ + metrics/ + src/test/java/... ← module-specific tests + testing/ ← published SDK testing utilities (sdk:testing) + src/main/java/... +``` + +`sdk:testing` is published and intended for use by external consumers testing OTel integrations. +Keep it stable β€” treat it as public API. + +## Test framework + +JUnit 5 (Jupiter). `otel.java-conventions` configures `useJUnitJupiter()` for all test suites. + +- Use `@Test`, `@BeforeEach`, `@AfterEach`, `@ParameterizedTest` from `org.junit.jupiter.api`. +- Use `@RegisterExtension` for JUnit 5 extensions (not `@Rule`). +- `@ExtendWith(MockitoExtension.class)` for Mockito injection. + +## Test suites + +This repo uses Gradle's `JvmTestSuite` API (not manual `Test` task registration). + +```kotlin +testing { + suites { + register("testIncubating") { + dependencies { + implementation(project(":api:incubator")) + } + } + } +} + +tasks { + check { + dependsOn(testing.suites) // wires all suites into check + } +} +``` + +Rules: +- All registered test suites must be wired into `check` β€” omitting this causes them to be + silently skipped in CI. +- Each suite has its own source set under `src//java/`. +- Suite-specific JVM args go in a `targets { all { testTask.configure { ... } } }` block. diff --git a/docs/rationale.md b/docs/rationale.md index 641cf6515c9..0311e7514e0 100644 --- a/docs/rationale.md +++ b/docs/rationale.md @@ -13,7 +13,7 @@ which try-with-resources does not allow. Take this example: ```java Span span = tracer.spanBuilder("someWork").startSpan(); -try (Scope scope = TracingContextUtils.currentContextWith(span)) { +try (Scope scope = span.makeCurrent()) { // Do things. } catch (Exception ex) { span.recordException(ex); diff --git a/docs/sdk-configuration-design.md b/docs/sdk-configuration-design.md new file mode 100644 index 00000000000..e4e401f3882 --- /dev/null +++ b/docs/sdk-configuration-design.md @@ -0,0 +1,660 @@ +# 🚨 Archival Use Only! 🚨 +> This is a historical design document and is not updated with evolving APIs. For up-to-date +> examples of SDK configuration see the +> [manual instrumentation documentation](https://opentelemetry.io/docs/languages/java/instrumentation/) +> and the [SDK configuration documentation](https://opentelemetry.io/docs/languages/java/configuration/). +> This document is maintained here for historical purposes only, and it is intended to +> help future readers to understand the rationale behind certain design decisions. + +# Design for configuring the SDK + +This document outlines some of the goals we have for user configuration of the SDK. It is a +continuation of discussion started with https://github.com/open-telemetry/opentelemetry-java/issues/2022. + +## Target audiences + +There are a few different target audiences that are related to our configuration story. + +- Application developers, aka end-users. Often have no knowledge of tracing but want to add +OpenTelemetry to their app and see traces show up in a console. Application developers will increase +in number forever, while the below are more constant. + +- Dev-ops / framework developers. Write components or frameworks to support providing tracing to +their application developers. May write custom SDK extensions such as exporters, samplers, to fit +with their internal infrastructure and as such have some familiarity with tracing at least as the +SDK presents it. + +- Telemetry extension authors. Write custom SDK extensions, often to support a particular backend. +Very familiar with telemetry. + +- OpenTelemetry maintainers. Write the SDK code. + +When making decisions, especially about complexity, we always prioritize the application developers, +then framework developers, then maintainers. This is because we expect those with less domain +knowledge about tracing to require a simpler experience than those with more. There is also more +bang-for-the-buck by making the end-user experience as streamlined as possible since we expect there +to be much more of them than other audiences. + +## Goals and non-goals + +### Goals + +- Provide a single entrypoint to configuring the SDK. For end-users, less familiar with the SDK, we +want to have everything together to provide discoverability and simpler end-user code. If there are +several, clear use cases which benefit from different entrypoints, we could have multiple +corresponding to each one. + +- Fit well with common Java idioms such as dependency injection, or common frameworks like Spring. + +- Reduce the chance of gotchas or configuration mishaps. + +- Aim for optimal performance of the configured SDK for the most common use case. + +### Non-goals + +- Provide the best possible experience for custom SDKs. Generally the burden of the experience for +custom SDKs can fall on their authors, we optimize for our standard usage, the full SDK. Any +reference to "the SDK" in this document refers to the full SDK with all signals. + +- Make sure everything is auto-configurable. This is out of the scope of the SDK, and instead is +left to auto-configuration layers, which are also described below but not as part of the core SDK. +The SDK provides an autoconfiguration extension as an option which is not internal to the main SDK +components. + +## Configuring an instance of the SDK + +The SDK exposes configuration options for all the signals it supports. Users all have different +requirements for how they use the SDK; for example they may use different exporters depending on +their backend. Because we cannot guess the configuration the user needs, we expect that the SDK must +be configured by the user before it can be used. + +Goals for configuring the SDK are + +- Discoverability of options +- Ease of use by end users, e.g., less complicated code required +- Avoid requiring duplicate configuration, which can lead to errors or confusion +- Provide good defaults where possible + +In Java, the builder pattern is common for configuring instances. Let's look at what that may look +like. The simplest configuration will be when a user wants to get a default experience, exporting +with a specific exporter to an endpoint. + +The SDK builder will simply accept its components as builder parameters. It only allows +setting SDK implementations and is not meant for use with partial SDKs. + +```java +class OpenTelemetrySdkBuilder { + public OpenTelemetrySdkBuilder setTracerProvider(SdkTracerProvider tracerProvider); + public OpenTelemetrySdkBuilder setPropagators(ContextPropagators propagators); + public OpenTelemetrySdk buildAndRegisterGlobal(); + public OpenTelemetrySdk build(); +} +``` + +Metrics are yet GA and must be configured separately. Eventually, metrics configuration will become +part of the `OpenTelemetrySdkBuilder`. + +A very simple configuration may look like this. + +```java +class HelloWorld { + public static void main(String[] args) { + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor( + BatchSpanProcessor.builder( + OtlpGrpcSpanExporter.builder() + .setEndpoint("https://collector-service:4317") + .build()) + .build()) + .build(); + + OpenTelemetrySdk openTelemetry = + OpenTelemetrySdk.builder() + .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) + .setTracerProvider(tracerProvider) + .buildAndRegisterGlobal(); + + PeriodicMetricReaderFactory periodicMetricReaderFactory = + PeriodicMetricReader.create( + OtlpGrpcMetricExporter.builder() + .setEndpoint("https://collector-service:4317") + .build(), + Duration.ofMillis(1000)); + + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .registerMetricReader(periodicMetricReaderFactory) + .buildAndRegisterGlobal(); + } +} +``` + +This + +- Exports spans using OTLP to `collector-service` + - Uses the BatchSpanProcessor. +- Exports metrics using OTLP to `collector-service` + - Uses the PeriodicMetricReader +- Uses ParentBased(AlwaysOn) sampler +- Uses standard random IDs +- Uses a default Resource which simply consists of the SDK (or any other resources we decide to) +include in the core SDK, not extensions +- Uses the default Clock, which uses Java 8 / 9+ optimized APIs for getting time + - The only real reason a user would set this is for unit tests, not for production +- Enforces default numeric limits related to number of attribute, etc +- Enables single w3c propagator + +Because the exporting is often the only aspect an end user needs to configure, this is the simplest +possible API for configuring the SDK. + +Let's look at a more complicated example + +```java +class HelloWorld { + public static void main(String[] args) { + Resource resource = Resource.getDefault().merge(CoolResource.getDefault()); + Clock clock = AtomicClock.create(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .setResource(resource) + .setClock(clock) + .addSpanProcessor(CustomAttributeAddingProcessor.create()) + .addSpanProcessor(CustomEventAddingProcessor.create()) + .addSpanProcessor( + BatchSpanProcessor.builder( + OtlpGrpcSpanExporter.builder() + .setEndpoint("https://collector-service:4317") + .setTimeout(Duration.ofSeconds(10)) + .build()) + .setMaxExportBatchSize(10000) + .build()) + .addSpanProcessor( + SimpleSpanProcessor.create( + ZipkinSpanExporter.builder() + .setEndpoint("https://zipkin-service:9411") + .build())) + .setSampler(Sampler.traceIdRatioBased(0.5)) + .setSpanLimits(SpanLimits.builder().setMaxNumberOfAttributes(10).build()) + .setIdGenerator(TimestampedIdGenerator.create()) + .build(); + + OpenTelemetrySdk openTelemetry = + OpenTelemetrySdk.builder() + .setPropagators( + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + B3Propagator.injectingSingleHeader()))) + .setTracerProvider(tracerProvider) + .buildAndRegisterGlobal(); + + OpenTelemetrySdk openTelemetryForJaegerBackend = + OpenTelemetrySdk.builder() + .setPropagators(ContextPropagators.create(JaegerPropagator.getInstance())) + .setTracerProvider(tracerProvider) + .build(); + + PeriodicMetricReaderFactory periodicMetricReaderFactory = + PeriodicMetricReader.create( + OtlpGrpcMetricExporter.builder() + .setEndpoint("https://collector-service:4317") + .build(), + Duration.ofMillis(1000)); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .setResource(resource) + .setClock(clock) + .registerView( + InstrumentSelector.builder() + .setInstrumentType(InstrumentType.COUNTER) + .build(), + View.builder().build()) + .registerMetricReader(periodicMetricReaderFactory) + .buildAndRegisterGlobal(); + } +} +``` + +This configures resource, clock, exporters, span processors, propagators, sampler, trace limits, and metrics. +It configures two SDKs with different propagators. We unfortunately cannot achieve our goal of only +setting a property once - `Resource` and `Clock` are shared among signals but configured repeatedly. +An alternative is to flatten all settings onto `OpenTelemetrySdkBuilder` - this has a downside that +it makes it very natural to create new tracer / meter providers for each configuration of the SDK, +which could result in a lot of duplication of resources like threads, workers, TCP connections. So +instead, this can make it clearer that those signals themselves are full-featured, and +`OpenTelemetry` is just a bag of signals. + +Keep in mind, reconfiguring `Clock` is expected to be an extremely uncommon operation. + +Another thing to keep in mind is that it will be less common for an application developer to go this far +and we can expect it is actually framework developers that use the full configuration capabilities +of the SDK, likely by tying it to a separate configuration system. + +### Why build instances + +We have found that even at such an early stage of user adoption, users want to build instances of +the SDK. + +- Integrates with dependency injection, e.g., Spring, in a similar way as many other libraries +- Can allow having multiple instances in the same app, in multi-concern single-classloader scenarios +- Allow managing lifecycle of SDK, e.g., shutting down and starting along with the lifecycle of a +serverless runtime + +### Configuring the SDK in a framework + +It is extremely common for Java apps to be written using a dependency injection framework like +Spring, Guice, Dagger, HK, and many more. They will all follow a very similar pattern though. + +```java +@Component +public class OpenTelemetryModule { + @Bean + public Resource resource() { + return Resource.getDefault().merge(CoolResource.getDefault()); + } + + @Bean + public Clock otelClock() { + return AtomicClock.create(); + } + + @Bean + public TracerSdkProvider tracerProvider(Resource resource, Clock clock, MonitoringConfig config) { + return SdkTracerProvider.builder() + .setResource(resource) + .setClock(clock) + .addSpanProcessor(CustomAttributeAddingProcessor.create()) + .addSpanProcessor(CustomEventAddingProcessor.create()) + .addSpanProcessor( + BatchSpanProcessor.builder( + OtlpGrpcSpanExporter.builder() + .setEndpoint(config.getOtlpExporter().getEndpoint()) + .setTimeout(config.getOtlpExporter().getTimeout()) + .build()) + .setBatchQueueSize(config.getOtlpExporter().getQueueSize()) + .setExporterTimeout(config.getOtlpExporter().getTimeout()) + .build()) + .addSpanProcessor( + SimpleSpanProcessor.create( + ZipkinSpanExporter.builder() + .setEndpoint(config.getZipkinExporter().getEndpoint()) + .build())) + .setSampler( + config.getSamplingRatio() != 0 + ? Sampler.traceIdRatioBased(config.getSamplingRatio()) + : Sampler.parentBased(Sampler.alwaysOn())) + .setSpanLimits( + SpanLimits.builder().setMaxNumberOfAttributes(config.getMaxSpanAttributes()).build()) + .setIdGenerator(TimestampedIdGenerator.create()) + .build(); + } + + @Bean + public MeterSdkProvider meterProvider(Resource resource, Clock clock) { + return SdkMeterProvider.builder() + .setResource(resource) + .setClock(clock) + .registerView( + InstrumentSelector.builder() + .setInstrumentType(InstrumentType.COUNTER) + .build(), + View.builder().build()) + .build(); + } + + @Bean + public MeterSdkProvider meterProvider(Resource resource, Clock clock, PeriodicMetricReaderFactory periodicMetricReaderFactory) { + return SdkMeterProvider.builder() + .setResource(resource) + .setClock(clock) + .registerView( + InstrumentSelector.builder() + .setInstrumentType(InstrumentType.COUNTER) + .build(), + View.builder().build()) + .registerMetricReader(periodicMetricReaderFactory) + .build(); + } + + @Bean + public OpenTelemetry openTelemetry(SdkTracerProvider tracerProvider, SdkMeterProvider meterProvider) { + GlobalMeterProvider.set(meterProvider); + return OpenTelemetrySdk.builder() + .setPropagators( + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + B3Propagator.injectingSingleHeader()))) + .setTracerProvider(tracerProvider) + .buildAndRegisterGlobal(); + } + + @Bean + @ForJaeger + public OpenTelemetry openTelemetryJaeger(SdkTracerProvider tracerProvider, SdkMeterProvider meterProvider) { + return OpenTelemetrySdk.builder() + .setPropagators(ContextPropagators.create(JaegerPropagator.getInstance())) + .setTracerProvider(tracerProvider) + .build(); + } + + @Bean + public AuthServiceStub authService(@ForJaeger OpenTelemetry openTelemetry, AuthConfig config) { + return AuthServiceGrpc.newBlockingStub(ManagedChannelBuilder.forEndpoint(config.getEndpoint())) + .withInterceptor(TracingClientInterceptor.create(openTelemetry)); + } + + @Bean + public ServletFilter servletFilter(OpenTelemetry openTelemetry) { + return TracingServletFilter.create(openTelemetry); + } +} + +// Use some instrumented client +@Component +public class MyAuthInterceptor { + + private final AuthServiceStub authService; + + @Inject + public MyAuthInterceptor(AuthServiceStub authService) { + this.authService = authService; + } + + public void doAuth() { + if (!authService.getToken("credential").isAuthenticated()) { + throw new HackerException(); + } + } +} + +// Use tracer directly, not so common +@Component +public class MyService { + + private final Tracer tracer; + private final Meter meter; + + @Inject + public MyService(TracerProvider tracerProvider, MeterProvider meterProvider) { + tracer = tracerProvider.get("my-service"); + meter = meterProvider.get("my-service"); + } + + public void doLogic() { + Span span = tracer.spanBuilder("logic").startSpan(); + try (Scope ignored = span.makeCurrent()) { + Thread.sleep(1000); + } finally { + span.end(); + } + } +} +``` + +## The global instance of the SDK + +A built instance is convenient to use in most Java apps because of dependency injection. Because it +has a easy-to-reason initialization ordering, being tied into the dependency ordering (even if dependency +injection happened to be done manually through constructor invocation), we encourage application +developers to only use it. + +However, there are corner cases where an instance cannot be injected. The famous example is MySQL - +MySQL interceptors are initialized by calling a default constructor, and there is no way to pass a +built instance of a signal provider. For this case, we must store an SDK instance into a global +variable. It is expected that frameworks or end-users will set the SDK as the global to support +instrumentation that requires this. + +Before an SDK has been set, access to the global `OpenTelemetry` will return a no-op +`DefaultOpenTelemetry`. This is because it is possible library instrumentation is using the global, +and it may even use it during the processing of a request (rather than only at initialization time). +For this reason, we cannot throw an exception. Instead, if the SDK is detected on the classpath, we +will log a `SEVERE` warning once-only indicating the API has been accessed before the SDK configured +with directions on how a user could solve the problem. SDKs must be configured early +in an application to ensure it applies to all of the logic in the app, and this will generally be +ensured by the configuration framework such as Spring. For application developers, this restriction +should not have any effect one way or the other in the vast majority of cases. + +MySQL is the only known corner case that requires the global SDK instance. If such a corner case +didn't exist, we may not even support it in the first place. + +See special note about Java Agent below though. + +## Telemetry within SDK components + +SDK components, such as exporters or remote samplers, may want to emit telemetry for their own +processing. However, the SDK components must be initialized before the SDK can be fully built. We do +not support partially built SDK because one cannot reason about the behavior of it. Similarly we +do not support using the global instance of the SDK before it has been built. Therefore, SDK +components that require `OpenTelemetry` must accept it lazily. This is a restriction, but given +such components are rarely developed by application developers, and generally developed by either +framework authors or OpenTelemetry maintainers, this restriction is deemed reasonable. + +If this mechanism was built into the SDK, it may look like + +```java +interface OpenTelemetryComponent { + default void setOpenTelemetry(OpenTelemetry openTelemetry) {} +} +interface SpanExporter extends OpenTelemetryComponent { +} +public class BatchExporter implements SpanExporter { + + private volatile Tracer tracer; + + @Override + public void setOpenTelemetry(OpenTelemetry openTelemetry) { + tracer = openTelemetry.getTracerProvider().get("spanexporter"); + } + + @Override + public void export() { + Tracer tracer = this.tracer; + if (tracer != null) { + tracer.spanBuilder("export").startSpan(); + } + } +} +public class OpenTelemetrySdkBuilder { + public OpenTelemetrySdkBuilder addSpanExporter(SpanExporter exporter) { + tracerProvider.addSpanExporter(exporter); + components.add(exporter); + } + + public OpenTelemetrySdkBuilder setSampler(Sampler sampler) { + tracerProvider.setSampler(sampler); + components.add(sampler); + } + + public OpenTelemetry build() { + OpenTelemetrySdk sdk = new OpenTelemetrySdk(tracerProvider.build(), meterProvider.build()); + for (OpenTelemetryComponent component : components) { + component.setOpenTelemetry(sdk); + } + } +} +``` + +A framework author will have an even easier time since most dependency injection frameworks +natively support lazy injection. + +```java +@Component +public class MonitoringModule { + + @Bean + @ForSpanExporter + public Tracer tracer(TracerProvider tracerProvider) { + return tracerProvider.get("spanexporter"); + } +} + +@Component +public class MyExporter implements SpanExporter { + + private Lazy tracer; + + @Inject + public MyExporter(@ForSpanExporter Lazy tracer) { + this.tracer = tracer; + } + + @Override + public void export() { + tracer.get().spanBuilder("export").startSpan(); + } +} +``` + +## Immutability of OpenTelemetry configuration + +The above attempts to avoid allowing a built SDK to be mutated, e.g., it is shallow immutable. Allowing mutation can make code +harder to reason about (any component, even deep in business logic, could update the SDK without +hindrance), can reduce performance (require volatile read on most operations), and produce thread +safety issues if not well implemented. In particular, compared to the current state as of writing, + +- `TracerSdkManagement.addSpanProcessor` is not needed. We needed a mutable SDK to allow span +processors to use global APIs for telemetry, but because we instead push the complexity of handling +[telemetry within SDK components](#Telemetry within SDK components) to those components, where the +maintainers will have more domain knowledge. It allows this mutator method to be removed from the +end-user API. + +- `TracerSdkManagement.updateTraceConfig` - instead of allowing replacing of the config at the top level, we should consider making +`TraceConfig` an interface, and the SDK default implementation is a simple implementation that always returns +a constant configuration. It allows the above benefits of immutability to be in place for the common case where dynamic updates are not needed. +Where dynamic updates are needed, it can be replaced with a mutable implementation instead of making +the SDK configuration mutable. This keeps update methods out of the end-user APIs and will generally +give framework developers more control by handling dynamicism themselves without the chance of +end-users to affect it negatively. For example, spring-boot may wire trace config updates to +actuator, its admin interface, and does not have to worry about business logic side-stepping this +mechanism by calling `updateTraceConfig`. + +Some highly buggy code that could be enabled by mutability. + +```java +class SleuthUsingService { + + @Inject + private OpenTelemetry openTelemetry; + + public void doLogic() { + // My logic is important, so always sample it! + OpenTelemetrySdk.getTracerManagement().updateTraceConfig(config -> config.setSampler(ALWAYS_ON)); + // This service was able to affect other services, even though Sleuth intends to + // "manage the SDK". Unlike the javaagent, it can't block access to SDK methods we may provide. + doSampledLogicWhileOtherServicesAlsoGetSampled(); + } +} +``` + +## Library instrumentation + +As the configuration of observability is contained on `OpenTelemetry` instances, it is expected that +library instrumentation accept an `OpenTelemetry` instance, often as a builder for their e.g., +tracing interceptor, when configuring observability. + +## Auto-configuration + +The above presents programmatic configuration for the SDK and proposes that the core SDK has no +other mechanism for configuration. There is no SPI nor processing of environment variables or +system properties. There are many mechanisms for configuration, for example Spring Boot. +Integration with these systems becomes easier to reason about if we consider auto-configuration at +a layer above the core SDK. + +### Java Auto-Instrumentation Agent + +Java Auto-Instrumentation Agent is the primary means of automatically configuring the SDK. It +contains system properties, environment variables, and SPIs for allowing a user to have a fully +setup tracing configuration just by applying the agent. In fact, the agent does not even allow a +user to use the SDK directly, actively blocking it. Instead of having a situation where some +configuration is automatic in the core SDK and some in the agent, we can move it all to the agent. +The agent already exposes exporter SPIs - it can also expose SPIs for customization of the SDK +components that are manually configured above. + +- We could consider having a very similar autoconfiguration wrapper artifact as an SDK extension too. +But we would assume the core SDK is always manually configured. + +To allow users of the agent to apply tracing to their own code, the agent should attempt to +instrument dependency injection to provide an instance of `OpenTelemetry` using the agent-configured +SDK, for example it should add it to the Spring `ApplicationContext`. For cases where dependency +injection is not available, though, there is no option but to provide access to the SDK through a +global variable. We can expect such usage to still function correctly even if the agent is removed +and a different configuration mechanism is used, such as manual configuration as above, or Spring +Sleuth. + +### SDK Auto-Configuration Wrapper + +For non-agent users, we can still provide a non-programmatic solution for configuring the SDK - +it can be a different artifact which contains SPIs similar to what we have currently, supports +environment variables and other auto-configuration. A single entrypoint method, `initialize()` could +determine the configuration, initialize `OpenTelemetry`, and set it as the global. As this artifact +is in our control, it would be reasonable for `opentelemetry-api` to check the classpath for the +presence of the wrapper and invoke it automatically. + +### Spring Sleuth + +Spring Sleuth (or any similar observability-aware server framework +or internal frameworks developed by devops teams at companies) is also a mechanism for automatically +configuring the SDK. In general, we would expect Sleuth users to not be using the java agent. + +Examples of how Sleuth could work are presented above in examples using `@Bean`. In particular, we +expect it to have its own set of configuration properties - by making sure we don't implement +configuration properties in the core SDK, only configuration layers like the agent or a possible +configuration wrapper, we avoid the possibility of confusion by having duplicate variables (in +practice, OpenTelemetry naming would likely be ignored and overwritten by Spring naming). + +## Partial SDKs + +We allow implementing particular signals of the OpenTelemetry API without using our SDK. For example, +a MeterProvider may be implemented with micrometer. For this reason, each signal must also present +all of its options in the form of, e.g., `TracerSdkProviderBuilder`. We expect the vast majority of +users to use `OpenTelemetrySdkBuilder` - while there is some duplication with the signal provider +builder, it is work maintainers can do to present the simplest interface for the most common use +case of using the whole SDK. + +Without SPI, the way to initialize a partial SDK would be to use `DefaultOpenTelemetry`. + +```java +@Bean +public OpenTelemetry openTelemetry() { + return DefaultOpenTelemetry.builder() + .setTraceProvider(TracerSdkProvider.builder().build()) + .setMeterProvider(MicrometerProvider.builder().build()) + .build(); +} +``` + +As this should be a fairly minor use case, and commonly handled by framework developers, this seems +reasonable. We can also hope that where it is important, it is the author of partial SDKs that +provide a one-stop-shop entrypoint. + +```java +@Bean +public OpenTelemetry openTelemetry() { + return OpenTelemetrySdkWithMicrometer.builder() + .addSpanExporter() + .setMeterRegistry() + .build(); +} +``` + +## Alternatives considered + +### Always allow using the global OpenTelemetry + +We discuss some [advantages](#Immutability of OpenTelemetry configuration) of `OpenTelemetry` not +being mutable. One of the main side effects of this decision is not allowing the global to be used +before it is configured. An alternative approach may start with a core that is mutated when +configured, and global usage would still be valid even if references are made before configuration. +The lifecycle becomes difficult to reason about i.e., when is `OpenTelemetry` actually ready for use? +Dependency injection makes it explicit, global doesn't. It also seems to have performance +implications for less common end-user use cases (dynamic config) or for reasons that non-end-users +can handle (telemetry within telemetry). + +### SPI loading of OpenTelemetry components + +We could detect OpenTelemetry components using SPI, but we don't expect partial SDKs to be so common. +Instead of an inside-out approach of initializing a partial SDK within our code, we can instead just +encourage an outside-in approach where a partial-SDK-specific wrapper is created. This reduces the +magic in configuring `OpenTelemetry`, it all happens through our single entry-point. diff --git a/docs/sdk-configuration.md b/docs/sdk-configuration.md deleted file mode 100644 index 768e14eb124..00000000000 --- a/docs/sdk-configuration.md +++ /dev/null @@ -1,657 +0,0 @@ -> This is a design document and is not necessarily updated with evolving APIs. For up-to-date -> examples of SDK configuration see the -> [documentation](https://opentelemetry.io/docs/java/manual_instrumentation/). - -# Design for configuring the SDK - -This document outlines some of the goals we have for user configuration of the SDK. It is a -continuation of discussion started with https://github.com/open-telemetry/opentelemetry-java/issues/2022. - -## Target audiences - -There are a few different target audiences that are related to our configuration story. - -- Application developers, aka end-users. Often have no knowledge of tracing but want to add -OpenTelemetry to their app and see traces show up in a console. Application developers will increase -in number forever, while the below are more constant. - -- Dev-ops / framework developers. Write components or frameworks to support providing tracing to -their application developers. May write custom SDK extensions such as exporters, samplers, to fit -with their internal infrastructure and as such have some familiarity with tracing at least as the -SDK presents it. - -- Telemetry extension authors. Write custom SDK extensions, often to support a particular backend. -Very familiar with telemetry. - -- OpenTelemetry maintainers. Write the SDK code. - -When making decisions, especially about complexity, we always prioritize the application developers, -then framework developers, then maintainers. This is because we expect those with less domain -knowledge about tracing to require a simpler experience than those with more. There is also more -bang-for-the-buck by making the end-user experience as streamlined as possible since we expect there -to be much more of them than other audiences. - -## Goals and non-goals - -### Goals - -- Provide a single entrypoint to configuring the SDK. For end-users, less familiar with the SDK, we -want to have everything together to provide discoverability and simpler end-user code. If there are -several, clear use cases which benefit from different entrypoints, we could have multiple -corresponding to each one. - -- Fit well with common Java idioms such as dependency injection, or common frameworks like Spring. - -- Reduce the chance of gotchas or configuration mishaps. - -- Aim for optimal performance of the configured SDK for the most common use case. - -### Non-goals - -- Provide the best possible experience for custom SDKs. Generally the burden of the experience for -custom SDKs can fall on their authors, we optimize for our standard usage, the full SDK. Any -reference to "the SDK" in this document refers to the full SDK with all signals. - -- Make sure everything is auto-configurable. This is out of the scope of the SDK, and instead is -left to auto-configuration layers, which are also described below but not as part of the core SDK. -The SDK provides an autoconfiguration extension as an option which is not internal to the main SDK -components. - -## Configuring an instance of the SDK - -The SDK exposes configuration options for all the signals it supports. Users all have different -requirements for how they use the SDK; for example they may use different exporters depending on -their backend. Because we cannot guess the configuration the user needs, we expect that the SDK must -be configured by the user before it can be used. - -Goals for configuring the SDK are - -- Discoverability of options -- Ease of use by end users, e.g., less complicated code required -- Avoid requiring duplicate configuration, which can lead to errors or confusion -- Provide good defaults where possible - -In Java, the builder pattern is common for configuring instances. Let's look at what that may look -like. The simplest configuration will be when a user wants to get a default experience, exporting -with a specific exporter to an endpoint. - -The SDK builder will simply accept its components as builder parameters. It only allows -setting SDK implementations and is not meant for use with partial SDKs. - -```java -class OpenTelemetrySdkBuilder { - public OpenTelemetrySdkBuilder setTracerProvider(SdkTracerProvider tracerProvider); - public OpenTelemetrySdkBuilder setPropagators(ContextPropagators propagators); - public OpenTelemetrySdk buildAndRegisterGlobal(); - public OpenTelemetrySdk build(); -} -``` - -Metrics are yet GA and must be configured separately. Eventually, metrics configuration will become -part of the `OpenTelemetrySdkBuilder`. - -A very simple configuration may look like this. - -```java -class HelloWorld { - public static void main(String[] args) { - SdkTracerProvider tracerProvider = - SdkTracerProvider.builder() - .addSpanProcessor( - BatchSpanProcessor.builder( - OtlpGrpcSpanExporter.builder() - .setEndpoint("https://collector-service:4317") - .build()) - .build()) - .build(); - - OpenTelemetrySdk openTelemetry = - OpenTelemetrySdk.builder() - .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance())) - .setTracerProvider(tracerProvider) - .buildAndRegisterGlobal(); - - PeriodicMetricReaderFactory periodicMetricReaderFactory = - PeriodicMetricReader.create( - OtlpGrpcMetricExporter.builder() - .setEndpoint("https://collector-service:4317") - .build(), - Duration.ofMillis(1000)); - - SdkMeterProvider sdkMeterProvider = - SdkMeterProvider.builder() - .registerMetricReader(periodicMetricReaderFactory) - .buildAndRegisterGlobal(); - } -} -``` - -This - -- Exports spans using OTLP to `collector-service` - - Uses the BatchSpanProcessor. -- Exports metrics using OTLP to `collector-service` - - Uses the PeriodicMetricReader -- Uses ParentBased(AlwaysOn) sampler -- Uses standard random IDs -- Uses a default Resource which simply consists of the SDK (or any other resources we decide to) -include in the core SDK, not extensions -- Uses the default Clock, which uses Java 8 / 9+ optimized APIs for getting time - - The only real reason a user would set this is for unit tests, not for production -- Enforces default numeric limits related to number of attribute, etc -- Enables single w3c propagator - -Because the exporting is often the only aspect an end user needs to configure, this is the simplest -possible API for configuring the SDK. - -Let's look at a more complicated example - -```java -class HelloWorld { - public static void main(String[] args) { - Resource resource = Resource.getDefault().merge(CoolResource.getDefault()); - Clock clock = AtomicClock.create(); - SdkTracerProvider tracerProvider = - SdkTracerProvider.builder() - .setResource(resource) - .setClock(clock) - .addSpanProcessor(CustomAttributeAddingProcessor.create()) - .addSpanProcessor(CustomEventAddingProcessor.create()) - .addSpanProcessor( - BatchSpanProcessor.builder( - OtlpGrpcSpanExporter.builder() - .setEndpoint("https://collector-service:4317") - .setTimeout(Duration.ofSeconds(10)) - .build()) - .setMaxExportBatchSize(10000) - .build()) - .addSpanProcessor( - SimpleSpanProcessor.create( - ZipkinSpanExporter.builder() - .setEndpoint("https://zipkin-service:9411") - .build())) - .setSampler(Sampler.traceIdRatioBased(0.5)) - .setSpanLimits(SpanLimits.builder().setMaxNumberOfAttributes(10).build()) - .setIdGenerator(TimestampedIdGenerator.create()) - .build(); - - OpenTelemetrySdk openTelemetry = - OpenTelemetrySdk.builder() - .setPropagators( - ContextPropagators.create( - TextMapPropagator.composite( - W3CTraceContextPropagator.getInstance(), - B3Propagator.injectingSingleHeader()))) - .setTracerProvider(tracerProvider) - .buildAndRegisterGlobal(); - - OpenTelemetrySdk openTelemetryForJaegerBackend = - OpenTelemetrySdk.builder() - .setPropagators(ContextPropagators.create(JaegerPropagator.getInstance())) - .setTracerProvider(tracerProvider) - .build(); - - PeriodicMetricReaderFactory periodicMetricReaderFactory = - PeriodicMetricReader.create( - OtlpGrpcMetricExporter.builder() - .setEndpoint("https://collector-service:4317") - .build(), - Duration.ofMillis(1000)); - SdkMeterProvider meterProvider = - SdkMeterProvider.builder() - .setResource(resource) - .setClock(clock) - .registerView( - InstrumentSelector.builder() - .setInstrumentType(InstrumentType.COUNTER) - .build(), - View.builder().build()) - .registerMetricReader(periodicMetricReaderFactory) - .buildAndRegisterGlobal(); - } -} -``` - -This configures resource, clock, exporters, span processors, propagators, sampler, trace limits, and metrics. -It configures two SDKs with different propagators. We unfortunately cannot achieve our goal of only -setting a property once - `Resource` and `Clock` are shared among signals but configured repeatedly. -An alternative is to flatten all settings onto `OpenTelemetrySdkBuilder` - this has a downside that -it makes it very natural to create new tracer / meter providers for each configuration of the SDK, -which could result in a lot of duplication of resources like threads, workers, TCP connections. So -instead, this can make it clearer that those signals themselves are full-featured, and -`OpenTelemetry` is just a bag of signals. - -Keep in mind, reconfiguring `Clock` is expected to be an extremely uncommon operation. - -Another thing to keep in mind is that it will be less common for an application developer to go this far -and we can expect it is actually framework developers that use the full configuration capabilities -of the SDK, likely by tying it to a separate configuration system. - -### Why build instances - -We have found that even at such an early stage of user adoption, users want to build instances of -the SDK. - -- Integrates with dependency injection, e.g., Spring, in a similar way as many other libraries -- Can allow having multiple instances in the same app, in multi-concern single-classloader scenarios -- Allow managing lifecycle of SDK, e.g., shutting down and starting along with the lifecycle of a -serverless runtime - -### Configuring the SDK in a framework - -It is extremely common for Java apps to be written using a dependency injection framework like -Spring, Guice, Dagger, HK, and many more. They will all follow a very similar pattern though. - -```java -@Component -public class OpenTelemetryModule { - @Bean - public Resource resource() { - return Resource.getDefault().merge(CoolResource.getDefault()); - } - - @Bean - public Clock otelClock() { - return AtomicClock.create(); - } - - @Bean - public TracerSdkProvider tracerProvider(Resource resource, Clock clock, MonitoringConfig config) { - return SdkTracerProvider.builder() - .setResource(resource) - .setClock(clock) - .addSpanProcessor(CustomAttributeAddingProcessor.create()) - .addSpanProcessor(CustomEventAddingProcessor.create()) - .addSpanProcessor( - BatchSpanProcessor.builder( - OtlpGrpcSpanExporter.builder() - .setEndpoint(config.getOtlpExporter().getEndpoint()) - .setTimeout(config.getOtlpExporter().getTimeout()) - .build()) - .setBatchQueueSize(config.getOtlpExporter().getQueueSize()) - .setExporterTimeout(config.getOtlpExporter().getTimeout()) - .build()) - .addSpanProcessor( - SimpleSpanProcessor.create( - ZipkinSpanExporter.builder() - .setEndpoint(config.getZipkinExporter().getEndpoint()) - .build())) - .setSampler( - config.getSamplingRatio() != 0 - ? Sampler.traceIdRatioBased(config.getSamplingRatio()) - : Sampler.parentBased(Sampler.alwaysOn())) - .setSpanLimits( - SpanLimits.builder().setMaxNumberOfAttributes(config.getMaxSpanAttributes()).build()) - .setIdGenerator(TimestampedIdGenerator.create()) - .build(); - } - - @Bean - public MeterSdkProvider meterProvider(Resource resource, Clock clock) { - return SdkMeterProvider.builder() - .setResource(resource) - .setClock(clock) - .registerView( - InstrumentSelector.builder() - .setInstrumentType(InstrumentType.COUNTER) - .build(), - View.builder().build()) - .build(); - } - - @Bean - public MeterSdkProvider meterProvider(Resource resource, Clock clock, PeriodicMetricReaderFactory periodicMetricReaderFactory) { - return SdkMeterProvider.builder() - .setResource(resource) - .setClock(clock) - .registerView( - InstrumentSelector.builder() - .setInstrumentType(InstrumentType.COUNTER) - .build(), - View.builder().build()) - .registerMetricReader(periodicMetricReaderFactory) - .build(); - } - - @Bean - public OpenTelemetry openTelemetry(SdkTracerProvider tracerProvider, SdkMeterProvider meterProvider) { - GlobalMeterProvider.set(meterProvider); - return OpenTelemetrySdk.builder() - .setPropagators( - ContextPropagators.create( - TextMapPropagator.composite( - W3CTraceContextPropagator.getInstance(), - B3Propagator.injectingSingleHeader()))) - .setTracerProvider(tracerProvider) - .buildAndRegisterGlobal(); - } - - @Bean - @ForJaeger - public OpenTelemetry openTelemetryJaeger(SdkTracerProvider tracerProvider, SdkMeterProvider meterProvider) { - return OpenTelemetrySdk.builder() - .setPropagators(ContextPropagators.create(JaegerPropagator.getInstance())) - .setTracerProvider(tracerProvider) - .build(); - } - - @Bean - public AuthServiceStub authService(@ForJaeger OpenTelemetry openTelemetry, AuthConfig config) { - return AuthServiceGrpc.newBlockingStub(ManagedChannelBuilder.forEndpoint(config.getEndpoint())) - .withInterceptor(TracingClientInterceptor.create(openTelemetry)); - } - - @Bean - public ServletFilter servletFilter(OpenTelemetry openTelemetry) { - return TracingServletFilter.create(openTelemetry); - } -} - -// Use some instrumented client -@Component -public class MyAuthInterceptor { - - private final AuthServiceStub authService; - - @Inject - public MyAuthInterceptor(AuthServiceStub authService) { - this.authService = authService; - } - - public void doAuth() { - if (!authService.getToken("credential").isAuthenticated()) { - throw new HackerException(); - } - } -} - -// Use tracer directly, not so common -@Component -public class MyService { - - private final Tracer tracer; - private final Meter meter; - - @Inject - public MyService(TracerProvider tracerProvider, MeterProvider meterProvider) { - tracer = tracerProvider.get("my-service"); - meter = meterProvider.get("my-service"); - } - - public void doLogic() { - Span span = tracer.spanBuilder("logic").startSpan(); - try (Scope ignored = span.makeCurrent()) { - Thread.sleep(1000); - } finally { - span.end(); - } - } -} -``` - -## The global instance of the SDK - -A built instance is convenient to use in most Java apps because of dependency injection. Because it -has a easy-to-reason initialization ordering, being tied into the dependency ordering (even if dependency -injection happened to be done manually through constructor invocation), we encourage application -developers to only use it. - -However, there are corner cases where an instance cannot be injected. The famous example is MySQL - -MySQL interceptors are initialized by calling a default constructor, and there is no way to pass a -built instance of a signal provider. For this case, we must store an SDK instance into a global -variable. It is expected that frameworks or end-users will set the SDK as the global to support -instrumentation that requires this. - -Before an SDK has been set, access to the global `OpenTelemetry` will return a no-op -`DefaultOpenTelemetry`. This is because it is possible library instrumentation is using the global, -and it may even use it during the processing of a request (rather than only at initialization time). -For this reason, we cannot throw an exception. Instead, if the SDK is detected on the classpath, we -will log a `SEVERE` warning once-only indicating the API has been accessed before the SDK configured -with directions on how a user could solve the problem. SDKs must be configured early -in an application to ensure it applies to all of the logic in the app, and this will generally be -ensured by the configuration framework such as Spring. For application developers, this restriction -should not have any effect one way or the other in the vast majority of cases. - -MySQL is the only known corner case that requires the global SDK instance. If such a corner case -didn't exist, we may not even support it in the first place. - -See special note about Java Agent below though. - -## Telemetry within SDK components - -SDK components, such as exporters or remote samplers, may want to emit telemetry for their own -processing. However, the SDK components must be initialized before the SDK can be fully built. We do -not support partially built SDK because one cannot reason about the behavior of it. Similarly we -do not support using the global instance of the SDK before it has been built. Therefore, SDK -components that require `OpenTelemetry` must accept it lazily. This is a restriction, but given -such components are rarely developed by application developers, and generally developed by either -framework authors or OpenTelemetry maintainers, this restriction is deemed reasonable. - -If this mechanism was built into the SDK, it may look like - -```java -interface OpenTelemetryComponent { - default void setOpenTelemetry(OpenTelemetry openTelemetry) {} -} -interface SpanExporter extends OpenTelemetryComponent { -} -public class BatchExporter implements SpanExporter { - - private volatile Tracer tracer; - - @Override - public void setOpenTelemetry(OpenTelemetry openTelemetry) { - tracer = openTelemetry.getTracerProvider().get("spanexporter"); - } - - @Override - public void export() { - Tracer tracer = this.tracer; - if (tracer != null) { - tracer.spanBuilder("export").startSpan(); - } - } -} -public class OpenTelemetrySdkBuilder { - public OpenTelemetrySdkBuilder addSpanExporter(SpanExporter exporter) { - tracerProvider.addSpanExporter(exporter); - components.add(exporter); - } - - public OpenTelemetrySdkBuilder setSampler(Sampler sampler) { - tracerProvider.setSampler(sampler); - components.add(sampler); - } - - public OpenTelemetry build() { - OpenTelemetrySdk sdk = new OpenTelemetrySdk(tracerProvider.build(), meterProvider.build()); - for (OpenTelemetryComponent component : components) { - component.setOpenTelemetry(sdk); - } - } -} -``` - -A framework author will have an even easier time since most dependency injection frameworks -natively support lazy injection. - -```java -@Component -public class MonitoringModule { - - @Bean - @ForSpanExporter - public Tracer tracer(TracerProvider tracerProvider) { - return tracerProvider.get("spanexporter"); - } -} - -@Component -public class MyExporter implements SpanExporter { - - private Lazy tracer; - - @Inject - public MyExporter(@ForSpanExporter Lazy tracer) { - this.tracer = tracer; - } - - @Override - public void export() { - tracer.get().spanBuilder("export").startSpan(); - } -} -``` - -## Immutability of OpenTelemetry configuration - -The above attempts to avoid allowing a built SDK to be mutated, e.g., it is shallow immutable. Allowing mutation can make code -harder to reason about (any component, even deep in business logic, could update the SDK without -hindrance), can reduce performance (require volatile read on most operations), and produce thread -safety issues if not well implemented. In particular, compared to the current state as of writing, - -- `TracerSdkManagement.addSpanProcessor` is not needed. We needed a mutable SDK to allow span -processors to use global APIs for telemetry, but because we instead push the complexity of handling -[telemetry within SDK components](#Telemetry within SDK components) to those components, where the -maintainers will have more domain knowledge. It allows this mutator method to be removed from the -end-user API. - -- `TracerSdkManagement.updateTraceConfig` - instead of allowing replacing of the config at the top level, we should consider making -`TraceConfig` an interface, and the SDK default implementation is a simple implementation that always returns -a constant configuration. It allows the above benefits of immutability to be in place for the common case where dynamic updates are not needed. -Where dynamic updates are needed, it can be replaced with a mutable implementation instead of making -the SDK configuration mutable. This keeps update methods out of the end-user APIs and will generally -give framework developers more control by handling dynamicism themselves without the chance of -end-users to affect it negatively. For example, spring-boot may wire trace config updates to -actuator, its admin interface, and does not have to worry about business logic side-stepping this -mechanism by calling `updateTraceConfig`. - -Some highly buggy code that could be enabled by mutability. - -```java -class SleuthUsingService { - - @Inject - private OpenTelemetry openTelemetry; - - public void doLogic() { - // My logic is important, so always sample it! - OpenTelemetrySdk.getTracerManagement().updateTraceConfig(config -> config.setSampler(ALWAYS_ON)); - // This service was able to affect other services, even though Sleuth intends to - // "manage the SDK". Unlike the javaagent, it can't block access to SDK methods we may provide. - doSampledLogicWhileOtherServicesAlsoGetSampled(); - } -} -``` - -## Library instrumentation - -As the configuration of observability is contained on `OpenTelemetry` instances, it is expected that -library instrumentation accept an `OpenTelemetry` instance, often as a builder for their e.g., -tracing interceptor, when configuring observability. - -## Auto-configuration - -The above presents programmatic configuration for the SDK and proposes that the core SDK has no -other mechanism for configuration. There is no SPI nor processing of environment variables or -system properties. There are many mechanisms for configuration, for example Spring Boot. -Integration with these systems becomes easier to reason about if we consider auto-configuration at -a layer above the core SDK. - -### Java Auto-Instrumentation Agent - -Java Auto-Instrumentation Agent is the primary means of automatically configuring the SDK. It -contains system properties, environment variables, and SPIs for allowing a user to have a fully -setup tracing configuration just by applying the agent. In fact, the agent does not even allow a -user to use the SDK directly, actively blocking it. Instead of having a situation where some -configuration is automatic in the core SDK and some in the agent, we can move it all to the agent. -The agent already exposes exporter SPIs - it can also expose SPIs for customization of the SDK -components that are manually configured above. - -- We could consider having a very similar autoconfiguration wrapper artifact as an SDK extension too. -But we would assume the core SDK is always manually configured. - -To allow users of the agent to apply tracing to their own code, the agent should attempt to -instrument dependency injection to provide an instance of `OpenTelemetry` using the agent-configured -SDK, for example it should add it to the Spring `ApplicationContext`. For cases where dependency -injection is not available, though, there is no option but to provide access to the SDK through a -global variable. We can expect such usage to still function correctly even if the agent is removed -and a different configuration mechanism is used, such as manual configuration as above, or Spring -Sleuth. - -### SDK Auto-Configuration Wrapper - -For non-agent users, we can still provide a non-programmatic solution for configuring the SDK - -it can be a different artifact which contains SPIs similar to what we have currently, supports -environment variables and other auto-configuration. A single entrypoint method, `initialize()` could -determine the configuration, initialize `OpenTelemetry`, and set it as the global. As this artifact -is in our control, it would be reasonable for `opentelemetry-api` to check the classpath for the -presence of the wrapper and invoke it automatically. - -### Spring Sleuth - -[Spring Sleuth](https://spring.io/projects/spring-cloud-sleuth) (or any similar observability-aware server framework such as -[curio-server-framework](https://github.com/curioswitch/curiostack/blob/master/common/server/framework/src/main/java/org/curioswitch/common/server/framework/monitoring/MonitoringModule.java) -or internal frameworks developed by devops teams at companies) is also a mechanism for automatically -configuring the SDK. In general, we would expect Sleuth users to not be using the java agent. - -Examples of how Sleuth could work are presented above in examples using `@Bean`. In particular, we -expect it to have its own set of configuration properties - by making sure we don't implement -configuration properties in the core SDK, only configuration layers like the agent or a possible -configuration wrapper, we avoid the possibility of confusion by having duplicate variables (in -practice, OpenTelemetry naming would likely be ignored and overwritten by Spring naming). - -## Partial SDKs - -We allow implementing particular signals of the OpenTelemetry API without using our SDK. For example, -a MeterProvider may be implemented with micrometer. For this reason, each signal must also present -all of its options in the form of, e.g., `TracerSdkProviderBuilder`. We expect the vast majority of -users to use `OpenTelemetrySdkBuilder` - while there is some duplication with the signal provider -builder, it is work maintainers can do to present the simplest interface for the most common use -case of using the whole SDK. - -Without SPI, the way to initialize a partial SDK would be to use `DefaultOpenTelemetry`. - -```java -@Bean -public OpenTelemetry openTelemetry() { - return DefaultOpenTelemetry.builder() - .setTraceProvider(TracerSdkProvider.builder().build()) - .setMeterProvider(MicrometerProvider.builder().build()) - .build(); -} -``` - -As this should be a fairly minor use case, and commonly handled by framework developers, this seems -reasonable. We can also hope that where it is important, it is the author of partial SDKs that -provide a one-stop-shop entrypoint. - -```java -@Bean -public OpenTelemetry openTelemetry() { - return OpenTelemetrySdkWithMicrometer.builder() - .addSpanExporter() - .setMeterRegistry() - .build(); -} -``` - -## Alternatives considered - -### Always allow using the global OpenTelemetry - -We discuss some [advantages](#Immutability of OpenTelemetry configuration) of `OpenTelemetry` not -being mutable. One of the main side effects of this decision is not allowing the global to be used -before it is configured. An alternative approach may start with a core that is mutated when -configured, and global usage would still be valid even if references are made before configuration. -The lifecycle becomes difficult to reason about i.e., when is `OpenTelemetry` actually ready for use? -Dependency injection makes it explicit, global doesn't. It also seems to have performance -implications for less common end-user use cases (dynamic config) or for reasons that non-end-users -can handle (telemetry within telemetry). - -### SPI loading of OpenTelemetry components - -We could detect OpenTelemetry components using SPI, but we don't expect partial SDKs to be so common. -Instead of an inside-out approach of initializing a partial SDK within our code, we can instead just -encourage an outside-in approach where a partial-SDK-specific wrapper is created. This reduces the -magic in configuring `OpenTelemetry`, it all happens through our single entry-point. diff --git a/docs/zpages/TRACEZ_DESIGN.md b/docs/zpages/TRACEZ_DESIGN.md deleted file mode 100644 index 9db9465466e..00000000000 --- a/docs/zpages/TRACEZ_DESIGN.md +++ /dev/null @@ -1,168 +0,0 @@ -# OpenTelemetry SDK Contrib - /tracez and /traceconfigz Design Doc - -This file contains information about the design choices for the OpenTelemetry /tracez and -/traceconfigz zPages. - -## Introduction - -The OpenTelemetry zPages are a set of dynamically generated HTML pages that display trace and -metrics data for a running process: the /tracez zPage displays trace information about running -spans, sample span latencies, and sample error spans, while the /traceconfigz zPage is a web page -that allows the users to change tracing parameters, such as sampling probability and max number of -attributes. - -### /tracez zPage - -The /tracez zPage displays information on running spans, sample span latencies, and sample error -spans. The data is aggregated into a summary-level table: - -![tracez-table](img/tracez-table.png) - -You can click on each of the counts in the table cells to access the corresponding span -details. For example, here are the details of the `ChildSpan` latency sample (row 1, col 4): - -![tracez-details](img/tracez-details.png) - -### /traceconfigz zPage - -The /traceconfigz zPage displays information about the currently active tracing configuration and -provides an interface for users to modify relevant parameters: - -![traceconfigz](img/traceconfigz.png) - -## Motivation - -We are building the Java zPages in order to create a lightweight application performance monitoring -tool that allows users to troubleshoot OpenTelemetry instrumentation. - -## Design - -### Frontend - -#### HttpHandler - -The `HttpHandler` is responsible for rendering corresponding HTML content. An abstract base class, -`ZPageHandler` (OpenCensus implementation), is implemented to standardize handlers for different -zPages. Each page will implement their own `ZPageHandler`, extending the base class, to generate the -corresponding HTML content for that page. - -![httphandler](img/httphandler.png) - -##### TraceZ Handler - -For the `TracezZPageHandler` class, the span data from `TracezDataAggregator` will be passed in when -an instance of the class is created. It will later be used to retrieve span information and display -the data in a table. - -##### TraceConfigZ Handler - -For the `TraceConfigzZPageHandler` class, the `TraceConfig` class will be used to change sampling -rate and tracing parameters. - -#### HttpServer -The `HttpServer` is responsible for listening to incoming requests, obtaining requested data, and -rendering corresponding HTML content. The `HttpServer` class from `com.sun.net` will be used to -handle http requests and responses on different routes (users need to ensure that they are using a -version of JDK that includes the `HttpServer` class; this requirement will be added to the README). -Once a request is received by the `HttpServer`, it will invoke the handle function which in turn -invokes the `emitHtml` function to render the HTML content. - -The `HttpServer` class utilizes `com.sun.net.httpserver` to create servers. Users need to ensure -that they are using a version of JDK that comes with the package. - -##### Handling Requests - -![requests-flowchart](img/requests-flowchart.png) - -### Backend - -#### Overview - -The proposed structure is encompassed by the following diagram: - -![span-lifecycle](img/span-lifecycle.png) - -Spans, which are the units of tracing, are monitored by a `SpanProcessor`. The `SpanProcessor` is -exposed to a `DataAggregator`, which can retrieve information about the spans through API calls. -Lastly, the frontend calls functions in the `DataAggregator` to obtain information needed for the -web page. - -#### SpanProcessor - -A `SpanProcessor` watches the lifecycle of each span, and its functions are called every time a span -starts or ends. For the /tracez zPage, I have implemented a `TracezSpanProcessor`, which will -maintain two data structures: a running span cache and a completed span cache. - -##### Visual Diagram - -Below is a visual diagram of the `TracezSpanProcessor` class: - -![span-processor-flowchart](img/span-processor-flowchart.png) - -When a span starts, it is first added to the `runningSpanCache`. Once that span ends, it is removed -from the `runningSpanCache` and added to the `completedSpanCache` as either a latency sample if -there are no errors or an error sample if there are. - -##### Initial Design - -At first, we planned to have both the running span and completed span caches map span IDs to spans. -The problem with this setup was that the number of completed spans would grow without bound. Note -that the number of running spans is naturally limited by the SDK, so the size of the running span -cache will never grow too large at any given time. However, the same cannot be said of the completed -span cache. In order to limit the number of completed spans, we had to consider an alternative data -structure that could impose the necessary limits. - -##### Proposed Design - -To constrain the number of completed spans, we built a new class called `TracezSpanBuckets` and -reworked the completed span cache to map span names to `TracezSpanBuckets` instances. The -`TracezSpanBuckets` class uses FIFO evicting queues to limit the number of latency samples per -bucket to 16 and the number of error samples per bucket to 8. With a hard limit, this setup ensures -that the completed span cache does not grow too large too quickly. For reference, OpenCensus -restricted the number of latency samples per bucket to 10 and the number of error samples per bucket -to 5. - -#### DataAggregator - -The `DataAggregator` restructures the data from the `SpanProcessor` into an accessible format for -the frontend to display. For this, I have implemented a class called `TracezDataAggregator`. This -class is constructed with a `TracezSpanProcessor` instance, so that the `TracezDataAggregator` class -can access the spans collected by a specific `TracezSpanProcessor`. - -##### Proposed Design - -The `TracezDataAggregator`'s purpose is to simplify the frontend's job of displaying information. -Consequently, the class supports functions for retrieving spans names, span counts, along with the -spans themselves. The frontend can then directly use the data collections that are returned. - -##### Accessing the TracezSpanProcessor - -When a user instruments their code, they first create a `SpanProcessor` and then add that instance -to a `TracerSdkProvider` with `addSpanProcessor`. An example from the official quickstart docs is -shown below: - -![quickstart](img/quickstart.png) - -While implementing the `TracezDataAggregator`, we faced the issue of how the backend was supposed to -access a `TracezSpanProcessor` created by the user. At the moment, there is no way for developers to -access the span processor instances that are added to the `TracerSdkProvider`. Consequently, we -propose that the `HttpServer` class add the `TracezSpanProcessor` itself, rather than requiring the -user to create and add the instance. This can be done by replicating the code in the above example: -use the `getTracerProvider` function in the `OpenTelemetrySdk` class and then call addProcessor with -the returned object. Note that `getTracerProvider` in the `OpenTelemetrySdk` class calls -`getTracerProvider` in the `OpenTelemetry` class, which returns a Singleton instance. This means -that the `OpenTelemetrySdk` class should return a Singleton instance as well, so the backend will -get the same `TracerSdkProvider` that the user uses. - -#### TraceConfigZ - -The final component of this project is the /traceconfigz zPage, which allows the user to update the -config for the /tracez zPage in real-time. In OpenTelemetry, updates are already handled by the -TraceSdkProvider class, so we only needed to wire them up and write the corresponding HTML. Since -most of the infrastructure was already built, there was no real design aspect to this. - -### Sequence Diagram - -Below is a sequence diagram of how the frontend and backend components will communicate: - -![sequence-diagram](img/sequence-diagram.png) diff --git a/docs/zpages/img/httphandler.png b/docs/zpages/img/httphandler.png deleted file mode 100644 index f42a36268c6..00000000000 Binary files a/docs/zpages/img/httphandler.png and /dev/null differ diff --git a/docs/zpages/img/quickstart.png b/docs/zpages/img/quickstart.png deleted file mode 100644 index d4530f1d083..00000000000 Binary files a/docs/zpages/img/quickstart.png and /dev/null differ diff --git a/docs/zpages/img/requests-flowchart.png b/docs/zpages/img/requests-flowchart.png deleted file mode 100644 index 01b57a5f1d3..00000000000 Binary files a/docs/zpages/img/requests-flowchart.png and /dev/null differ diff --git a/docs/zpages/img/sequence-diagram.png b/docs/zpages/img/sequence-diagram.png deleted file mode 100644 index aeb7b0210ce..00000000000 Binary files a/docs/zpages/img/sequence-diagram.png and /dev/null differ diff --git a/docs/zpages/img/span-lifecycle.png b/docs/zpages/img/span-lifecycle.png deleted file mode 100644 index 16827c263d6..00000000000 Binary files a/docs/zpages/img/span-lifecycle.png and /dev/null differ diff --git a/docs/zpages/img/span-processor-flowchart.png b/docs/zpages/img/span-processor-flowchart.png deleted file mode 100644 index eea13c89872..00000000000 Binary files a/docs/zpages/img/span-processor-flowchart.png and /dev/null differ diff --git a/docs/zpages/img/traceconfigz.png b/docs/zpages/img/traceconfigz.png deleted file mode 100644 index 0047e1ab8c1..00000000000 Binary files a/docs/zpages/img/traceconfigz.png and /dev/null differ diff --git a/docs/zpages/img/tracez-details.png b/docs/zpages/img/tracez-details.png deleted file mode 100644 index d45a013911e..00000000000 Binary files a/docs/zpages/img/tracez-details.png and /dev/null differ diff --git a/docs/zpages/img/tracez-table.png b/docs/zpages/img/tracez-table.png deleted file mode 100644 index c9605fe38d2..00000000000 Binary files a/docs/zpages/img/tracez-table.png and /dev/null differ diff --git a/exporters/common/build.gradle.kts b/exporters/common/build.gradle.kts new file mode 100644 index 00000000000..149a5633855 --- /dev/null +++ b/exporters/common/build.gradle.kts @@ -0,0 +1,132 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry Exporter Common" +otelJava.moduleName.set("io.opentelemetry.exporter.internal") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator.config", "io.opentelemetry.sdk.autoconfigure.spi")) +// sun.misc, io.grpc, and org.jspecify are not OSGi bundles and have no package versioning; must use unversioned optional. +otelJava.osgiUnversionedOptionalPackages.set(listOf("sun.misc", "io.grpc", "org.jspecify.annotations")) +// This bundle's exporters load sender implementations via SPI. +otelJava.osgiServiceLoaderRequires.set(listOf( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + "io.opentelemetry.sdk.common.export.HttpSenderProvider" +)) + +java { + sourceSets { + create("java9") { + java { + srcDir("src/main/java9") + } + // Make java9 source set depend on main source set + // since VarHandleStringEncoder implements StringEncoder from the main source set + compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath + } + } +} + +// Configure java9 compilation to see main source classes +sourceSets.named("java9") { + compileClasspath += sourceSets.main.get().output +} + +tasks.named("compileJava9Java") { + options.release.set(9) +} + +tasks.named("jar") { + manifest { + attributes["Multi-Release"] = "true" + } + from(sourceSets.named("java9").get().output) { + into("META-INF/versions/9") + } +} + +// Configure test to include java9 classes when running on Java 9+ +// so that StringEncoderHolder.createUnsafeEncoder() can instantiate the Java 9 version +val javaVersion = JavaVersion.current() +if (javaVersion >= JavaVersion.VERSION_1_9) { + sourceSets.named("test") { + runtimeClasspath += sourceSets.named("java9").get().output + } +} + +val versions = project.property("versions") as Map<*, *> +dependencies { + api(project(":api:all")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + + compileOnly(project(":api:incubator")) + compileOnly(project(":sdk:common")) + compileOnly(project(":exporters:common:compile-stub")) + + compileOnly("org.codehaus.mojo:animal-sniffer-annotations") + + annotationProcessor("com.google.auto.value:auto-value") + + // sun.misc.Unsafe from the JDK isn't found by the compiler, we provide our own trimmed down + // version that we can compile against. + compileOnly("io.grpc:grpc-stub") + + testImplementation(project(":sdk:common")) + testImplementation(project(":sdk:testing")) + + testImplementation("com.google.protobuf:protobuf-java-util") + testImplementation("com.linecorp.armeria:armeria-junit5") + testImplementation("com.google.api.grpc:proto-google-common-protos") + testImplementation("io.grpc:grpc-testing") + testImplementation("edu.berkeley.cs.jqf:jqf-fuzz") + testRuntimeOnly("io.grpc:grpc-netty-shaded") +} + +val testJavaVersion = project.findProperty("testJavaVersion") as String? + +testing { + suites { + register("testSenderProvider") { + dependencies { + implementation(project(":exporters:sender:jdk")) + implementation(project(":exporters:sender:okhttp")) + implementation(project(":exporters:sender:grpc-managed-channel")) + implementation(project(":sdk:common")) + } + targets { + all { + testTask { + enabled = !testJavaVersion.equals("8") + } + } + } + } + } + suites { + register("testWithoutUnsafe") {} + } +} + +tasks { + check { + dependsOn(testing.suites) + } + + withType { + // Allow VarHandle access to String internals + // generally users won't do this and so won't get the VarHandle implementation + // but the Java agent is able to automatically open these modules + // (see ModuleOpener.java in that repository) + jvmArgs("--add-opens=java.base/java.lang=ALL-UNNAMED") + jvmArgs("-XX:+IgnoreUnrecognizedVMOptions") // needed for Java 8 + } +} + +afterEvaluate { + tasks.named("compileTestSenderProviderJava") { + options.release.set(11) + } +} diff --git a/exporters/common/compile-stub/build.gradle.kts b/exporters/common/compile-stub/build.gradle.kts new file mode 100644 index 00000000000..59270eab31b --- /dev/null +++ b/exporters/common/compile-stub/build.gradle.kts @@ -0,0 +1,8 @@ +plugins { + id("otel.java-conventions") +} + +description = "OpenTelemetry Exporter Compile Stub" +otelJava.moduleName.set("io.opentelemetry.exporter.internal.compile-stub") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) diff --git a/exporters/common/compile-stub/src/main/java/sun/misc/Unsafe.java b/exporters/common/compile-stub/src/main/java/sun/misc/Unsafe.java new file mode 100644 index 00000000000..48b37ad371f --- /dev/null +++ b/exporters/common/compile-stub/src/main/java/sun/misc/Unsafe.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package sun.misc; + +import java.lang.reflect.Field; + +/** + * sun.misc.Unsafe from the JDK isn't found by the compiler, we provide our own trimmed down version + * that we can compile against. + */ +public class Unsafe { + + public long objectFieldOffset(Field f) { + return -1; + } + + public Object getObject(Object o, long offset) { + return null; + } + + public byte getByte(Object o, long offset) { + return 0; + } + + public int arrayBaseOffset(Class arrayClass) { + return 0; + } + + public long getLong(Object o, long offset) { + return 0; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/EndpointUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/EndpointUtil.java new file mode 100644 index 00000000000..a9c9ca00a37 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/EndpointUtil.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +/** + * Utilities for validating exporter endpoints. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class EndpointUtil { + + /** Validate an exporter endpoint. */ + public static URI validateEndpoint(String endpoint) { + URI uri; + try { + uri = new URI(endpoint); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid endpoint, must be a URL: " + endpoint, e); + } + + if (uri.getScheme() == null + || (!uri.getScheme().equals("http") && !uri.getScheme().equals("https"))) { + throw new IllegalArgumentException( + "Invalid endpoint, must start with http:// or https://: " + uri); + } + if (!hasHost(uri, endpoint)) { + throw new IllegalArgumentException( + "Invalid endpoint, must start with http:// or https://: " + uri); + } + return uri; + } + + /** + * {@link URI#getHost()} follows RFC 2396 and returns {@code null} for some valid DNS names + * (JDK-8188305), for example a label that starts with a digit. {@link URL#getHost()} accepts + * those names, matching {@code OtlpConfigUtil.validateEndpoint}. + */ + private static boolean hasHost(URI uri, String endpoint) { + if (uri.getHost() != null) { + return true; + } + try { + String host = new URL(endpoint).getHost(); + return host != null && !host.isEmpty(); + } catch (MalformedURLException e) { + return false; + } + } + + private EndpointUtil() {} +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/ExporterBuilderUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/ExporterBuilderUtil.java new file mode 100644 index 00000000000..7a6bcbf0fe9 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/ExporterBuilderUtil.java @@ -0,0 +1,109 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static io.opentelemetry.sdk.metrics.Aggregation.explicitBucketHistogram; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; +import java.util.Locale; +import java.util.function.Consumer; + +/** + * Utilities for exporter builders. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ExporterBuilderUtil { + + /** Invoke the {@code memoryModeConsumer} with the configured {@link MemoryMode}. */ + public static void configureExporterMemoryMode( + ConfigProperties config, Consumer memoryModeConsumer) { + String memoryModeStr = config.getString("otel.java.exporter.memory_mode"); + if (memoryModeStr == null) { + return; + } + MemoryMode memoryMode; + try { + memoryMode = MemoryMode.valueOf(memoryModeStr.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new ConfigurationException("Unrecognized memory mode: " + memoryModeStr, e); + } + memoryModeConsumer.accept(memoryMode); + } + + /** + * Invoke the {@code defaultAggregationSelectorConsumer} with the configured {@link + * DefaultAggregationSelector}. + */ + public static void configureHistogramDefaultAggregation( + String defaultHistogramAggregation, + Consumer defaultAggregationSelectorConsumer) { + if (AggregationUtil.aggregationName(Aggregation.base2ExponentialBucketHistogram()) + .equalsIgnoreCase(defaultHistogramAggregation)) { + defaultAggregationSelectorConsumer.accept( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.base2ExponentialBucketHistogram())); + } else if (!AggregationUtil.aggregationName(explicitBucketHistogram()) + .equalsIgnoreCase(defaultHistogramAggregation)) { + throw new ConfigurationException( + "Unrecognized default histogram aggregation: " + defaultHistogramAggregation); + } + } + + /** + * Invoke the {@code aggregationTemporalitySelectorConsumer} with the configured {@link + * AggregationTemporality}. + */ + public static void configureOtlpAggregationTemporality( + ConfigProperties config, + Consumer aggregationTemporalitySelectorConsumer) { + String temporalityStr = config.getString("otel.exporter.otlp.metrics.temporality.preference"); + if (temporalityStr == null) { + return; + } + AggregationTemporalitySelector temporalitySelector; + switch (temporalityStr.toLowerCase(Locale.ROOT)) { + case "cumulative": + temporalitySelector = AggregationTemporalitySelector.alwaysCumulative(); + break; + case "delta": + temporalitySelector = AggregationTemporalitySelector.deltaPreferred(); + break; + case "lowmemory": + temporalitySelector = AggregationTemporalitySelector.lowMemory(); + break; + default: + throw new ConfigurationException("Unrecognized aggregation temporality: " + temporalityStr); + } + aggregationTemporalitySelectorConsumer.accept(temporalitySelector); + } + + /** + * Invoke the {@code defaultAggregationSelectorConsumer} with the configured {@link + * DefaultAggregationSelector}. + */ + public static void configureOtlpHistogramDefaultAggregation( + ConfigProperties config, + Consumer defaultAggregationSelectorConsumer) { + String defaultHistogramAggregation = + config.getString("otel.exporter.otlp.metrics.default.histogram.aggregation"); + if (defaultHistogramAggregation != null) { + configureHistogramDefaultAggregation( + defaultHistogramAggregation, defaultAggregationSelectorConsumer); + } + } + + private ExporterBuilderUtil() {} +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/FailedExportException.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/FailedExportException.java new file mode 100644 index 00000000000..a6ad9caffd6 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/FailedExportException.java @@ -0,0 +1,136 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.HttpResponse; +import javax.annotation.Nullable; + +/** + * Represents the failure of a gRPC or HTTP exporter. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public abstract class FailedExportException extends Exception { + + private static final long serialVersionUID = 6988924855140178789L; + + private FailedExportException(@Nullable Throwable cause) { + super(cause); + } + + /** Indicates an HTTP export failed after receiving a response from the server. */ + public static HttpExportException httpFailedWithResponse(HttpResponse response) { + return new HttpExportException(response, null); + } + + /** Indicates an HTTP export failed exceptionally without receiving a response from the server. */ + public static HttpExportException httpFailedExceptionally(Throwable cause) { + return new HttpExportException(null, cause); + } + + /** Indicates a gRPC export failed after receiving a response from the server. */ + public static GrpcExportException grpcFailedWithResponse(GrpcResponse response) { + return new GrpcExportException(response, null); + } + + /** Indicates a gRPC export failed exceptionally without receiving a response from the server. */ + public static GrpcExportException grpcFailedExceptionally(Throwable cause) { + return new GrpcExportException(null, cause); + } + + /** Returns true if the export failed with a response from the server. */ + public abstract boolean failedWithResponse(); + + /** + * Represents the failure of an HTTP exporter. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ + public static final class HttpExportException extends FailedExportException { + + private static final long serialVersionUID = -6787390183017184775L; + + @Nullable private final HttpResponse response; + @Nullable private final Throwable cause; + + private HttpExportException(@Nullable HttpResponse response, @Nullable Throwable cause) { + super(cause); + this.response = response; + this.cause = cause; + } + + @Override + public boolean failedWithResponse() { + return response != null; + } + + /** + * Returns the response if the export failed with a response from the server, or null if the + * export failed exceptionally with no response. + */ + @Nullable + public HttpResponse getResponse() { + return response; + } + + /** + * Returns the exceptional cause of failure, or null if the export failed with a response from + * the server. + */ + @Nullable + @Override + public Throwable getCause() { + return cause; + } + } + + /** + * Represents the failure of a gRPC exporter. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ + public static final class GrpcExportException extends FailedExportException { + + private static final long serialVersionUID = -9157548250286695364L; + + @Nullable private final GrpcResponse response; + @Nullable private final Throwable cause; + + private GrpcExportException(@Nullable GrpcResponse response, @Nullable Throwable cause) { + super(cause); + this.response = response; + this.cause = cause; + } + + @Override + public boolean failedWithResponse() { + return response != null; + } + + /** + * Returns the response if the export failed with a response from the server, or null if the + * export failed exceptionally with no response. + */ + @Nullable + public GrpcResponse getResponse() { + return response; + } + + /** + * Returns the exceptional cause of failure, or null if the export failed with a response from + * the server. + */ + @Nullable + @Override + public Throwable getCause() { + return cause; + } + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/IncubatingExporterBuilderUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/IncubatingExporterBuilderUtil.java new file mode 100644 index 00000000000..8d8ec8d83a6 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/IncubatingExporterBuilderUtil.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static io.opentelemetry.sdk.metrics.Aggregation.explicitBucketHistogram; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; +import java.util.Locale; +import java.util.function.Consumer; + +/** + * Utilities for exporter builders. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class IncubatingExporterBuilderUtil { + + /** Invoke the {@code memoryModeConsumer} with the configured {@link MemoryMode}. */ + public static void configureExporterMemoryMode( + DeclarativeConfigProperties config, Consumer memoryModeConsumer) { + String memoryModeStr = config.getString("memory_mode"); + if (memoryModeStr == null) { + return; + } + MemoryMode memoryMode; + try { + memoryMode = MemoryMode.valueOf(memoryModeStr.toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new ConfigurationException("Unrecognized memory_mode: " + memoryModeStr, e); + } + memoryModeConsumer.accept(memoryMode); + } + + public static void configureOtlpAggregationTemporality( + DeclarativeConfigProperties config, + Consumer aggregationTemporalitySelectorConsumer) { + String temporalityStr = config.getString("temporality_preference"); + if (temporalityStr == null) { + return; + } + AggregationTemporalitySelector temporalitySelector; + switch (temporalityStr.toLowerCase(Locale.ROOT)) { + case "cumulative": + temporalitySelector = AggregationTemporalitySelector.alwaysCumulative(); + break; + case "delta": + temporalitySelector = AggregationTemporalitySelector.deltaPreferred(); + break; + case "low_memory": + temporalitySelector = AggregationTemporalitySelector.lowMemory(); + break; + default: + throw new ConfigurationException("Unrecognized temporality_preference: " + temporalityStr); + } + aggregationTemporalitySelectorConsumer.accept(temporalitySelector); + } + + /** + * Invoke the {@code defaultAggregationSelectorConsumer} with the configured {@link + * DefaultAggregationSelector}. + */ + public static void configureOtlpHistogramDefaultAggregation( + DeclarativeConfigProperties config, + Consumer defaultAggregationSelectorConsumer) { + String defaultHistogramAggregation = config.getString("default_histogram_aggregation"); + if (defaultHistogramAggregation == null) { + return; + } + if (AggregationUtil.aggregationName(Aggregation.base2ExponentialBucketHistogram()) + .equalsIgnoreCase(defaultHistogramAggregation)) { + defaultAggregationSelectorConsumer.accept( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.base2ExponentialBucketHistogram())); + } else if (!AggregationUtil.aggregationName(explicitBucketHistogram()) + .equalsIgnoreCase(defaultHistogramAggregation)) { + throw new ConfigurationException( + "Unrecognized default_histogram_aggregation: " + defaultHistogramAggregation); + } + } + + private IncubatingExporterBuilderUtil() {} +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/InstrumentationUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/InstrumentationUtil.java new file mode 100644 index 00000000000..a40ea3a8664 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/InstrumentationUtil.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import io.opentelemetry.context.Context; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + * + * @deprecated use {@link io.opentelemetry.api.impl.InstrumentationUtil} instead. This class should + * be removed once instrumentation does not refer to it anymore. + */ +@Deprecated +public final class InstrumentationUtil { + + private InstrumentationUtil() {} + + /** + * Adds a Context boolean key that will allow to identify HTTP calls coming from OTel exporters. + * The key later be checked by an automatic instrumentation to avoid tracing OTel exporter's + * calls. + */ + public static void suppressInstrumentation(Runnable runnable) { + io.opentelemetry.api.impl.InstrumentationUtil.suppressInstrumentation(runnable); + } + + /** + * Checks if an automatic instrumentation should be suppressed with the provided Context. + * + * @return TRUE to suppress the automatic instrumentation, FALSE to continue with the + * instrumentation. + */ + public static boolean shouldSuppressInstrumentation(Context context) { + return io.opentelemetry.api.impl.InstrumentationUtil.shouldSuppressInstrumentation(context); + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/RetryUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/RetryUtil.java new file mode 100644 index 00000000000..8d6d43ae91c --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/RetryUtil.java @@ -0,0 +1,91 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import java.time.Duration; +import java.time.Instant; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.OptionalLong; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class RetryUtil { + + private static final Set RETRYABLE_GRPC_STATUS_CODES; + private static final Set RETRYABLE_HTTP_STATUS_CODES = + Collections.unmodifiableSet(new HashSet<>(Arrays.asList(429, 502, 503, 504))); + + static { + Set retryableGrpcStatusCodes = new HashSet<>(); + retryableGrpcStatusCodes.add(GrpcStatusCode.CANCELLED.getValue()); + retryableGrpcStatusCodes.add(GrpcStatusCode.DEADLINE_EXCEEDED.getValue()); + retryableGrpcStatusCodes.add(GrpcStatusCode.RESOURCE_EXHAUSTED.getValue()); + retryableGrpcStatusCodes.add(GrpcStatusCode.ABORTED.getValue()); + retryableGrpcStatusCodes.add(GrpcStatusCode.OUT_OF_RANGE.getValue()); + retryableGrpcStatusCodes.add(GrpcStatusCode.UNAVAILABLE.getValue()); + retryableGrpcStatusCodes.add(GrpcStatusCode.DATA_LOSS.getValue()); + RETRYABLE_GRPC_STATUS_CODES = + Collections.unmodifiableSet( + retryableGrpcStatusCodes.stream().map(Object::toString).collect(Collectors.toSet())); + } + + private RetryUtil() {} + + /** Returns the retryable gRPC status codes. */ + public static Set retryableGrpcStatusCodes() { + return RETRYABLE_GRPC_STATUS_CODES; + } + + /** Returns the retryable HTTP status codes. */ + public static Set retryableHttpResponseCodes() { + return RETRYABLE_HTTP_STATUS_CODES; + } + + /** + * Returns the delay specified by a {@code Retry-After} header, or empty if the value is absent or + * malformed. + */ + public static OptionalLong retryAfterNanos(@Nullable String retryAfter) { + return retryAfterNanos(retryAfter, Instant.now()); + } + + static OptionalLong retryAfterNanos(@Nullable String retryAfter, Instant now) { + if (retryAfter == null) { + return OptionalLong.empty(); + } + + try { + long delaySeconds = Long.parseLong(retryAfter); + if (delaySeconds < 0) { + return OptionalLong.empty(); + } + return OptionalLong.of(TimeUnit.SECONDS.toNanos(delaySeconds)); + } catch (NumberFormatException ignored) { + // Fall through and try the HTTP-date form. + } + + try { + Instant retryAfterInstant = + ZonedDateTime.parse(retryAfter, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant(); + long delayNanos = Duration.between(now, retryAfterInstant).toNanos(); + return OptionalLong.of(Math.max(0, delayNanos)); + } catch (DateTimeParseException | ArithmeticException ignored) { + return OptionalLong.empty(); + } + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/SenderUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/SenderUtil.java new file mode 100644 index 00000000000..0ada71e9943 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/SenderUtil.java @@ -0,0 +1,149 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.common.impl.ConfigUtil; +import io.opentelemetry.sdk.common.export.GrpcSenderProvider; +import io.opentelemetry.sdk.common.export.HttpSenderProvider; +import java.util.HashMap; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Utilities for loading senders. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class SenderUtil { + + private static final Logger LOGGER = Logger.getLogger(SenderUtil.class.getName()); + + private static final String GRPC_SPI_PROPERTY = + "io.opentelemetry.sdk.common.export.GrpcSenderProvider"; + private static final String HTTP_SPI_PROPERTY = + "io.opentelemetry.sdk.common.export.HttpSenderProvider"; + + private SenderUtil() {} + + /** + * Resolve the {@link GrpcSenderProvider}. + * + *

    If no {@link GrpcSenderProvider} is available, throw {@link IllegalStateException}. + * + *

    If only one {@link GrpcSenderProvider} is available, use it. + * + *

    If multiple are available and.. + * + *

      + *
    • {@code io.opentelemetry.sdk.common.export.GrpcSenderProvider} is empty, use the first + * found. + *
    • {@code io.opentelemetry.sdk.common.export.GrpcSenderProvider} is set, use the matching + * provider. If none match, throw {@link IllegalStateException}. + *
    + */ + public static GrpcSenderProvider resolveGrpcSenderProvider(ComponentLoader componentLoader) { + Map grpcSenderProviders = new HashMap<>(); + for (GrpcSenderProvider spi : componentLoader.load(GrpcSenderProvider.class)) { + grpcSenderProviders.put(spi.getClass().getName(), spi); + } + + // No provider on classpath, throw + if (grpcSenderProviders.isEmpty()) { + throw new IllegalStateException( + "No GrpcSenderProvider found on classpath. Please add dependency on " + + "opentelemetry-exporter-sender-okhttp or opentelemetry-exporter-sender-grpc-managed-channel"); + } + + // Exactly one provider on classpath, use it + if (grpcSenderProviders.size() == 1) { + return grpcSenderProviders.values().stream().findFirst().get(); + } + + // If we've reached here, there are multiple GrpcSenderProviders + String configuredSender = ConfigUtil.getString(GRPC_SPI_PROPERTY, ""); + + // Multiple providers but none configured, use first we find and log a warning + if (configuredSender.isEmpty()) { + LOGGER.log( + Level.WARNING, + "Multiple GrpcSenderProvider found. Please include only one, " + + "or specify preference setting " + + GRPC_SPI_PROPERTY + + " to the FQCN of the preferred provider."); + return grpcSenderProviders.values().stream().findFirst().get(); + } + + // Multiple providers with configuration match, use configuration match + if (grpcSenderProviders.containsKey(configuredSender)) { + return grpcSenderProviders.get(configuredSender); + } + + // Multiple providers, configured does not match, throw + throw new IllegalStateException( + "No GrpcSenderProvider matched configured " + GRPC_SPI_PROPERTY + ": " + configuredSender); + } + + /** + * Resolve the {@link HttpSenderProvider}. + * + *

    If no {@link HttpSenderProvider} is available, throw {@link IllegalStateException}. + * + *

    If only one {@link HttpSenderProvider} is available, use it. + * + *

    If multiple are available and.. + * + *

      + *
    • {@code io.opentelemetry.sdk.common.export.HttpSenderProvider} is empty, use the first + * found. + *
    • {@code io.opentelemetry.sdk.common.export.HttpSenderProvider} is set, use the matching + * provider. If none match, throw {@link IllegalStateException}. + *
    + */ + public static HttpSenderProvider resolveHttpSenderProvider(ComponentLoader componentLoader) { + Map httpSenderProviders = new HashMap<>(); + for (HttpSenderProvider spi : componentLoader.load(HttpSenderProvider.class)) { + httpSenderProviders.put(spi.getClass().getName(), spi); + } + + // No provider on classpath, throw + if (httpSenderProviders.isEmpty()) { + throw new IllegalStateException( + "No HttpSenderProvider found on classpath. Please add dependency on " + + "opentelemetry-exporter-sender-okhttp or opentelemetry-exporter-sender-jdk"); + } + + // Exactly one provider on classpath, use it + if (httpSenderProviders.size() == 1) { + return httpSenderProviders.values().stream().findFirst().get(); + } + + // If we've reached here, there are multiple HttpSenderProviders + String configuredSender = ConfigUtil.getString(HTTP_SPI_PROPERTY, ""); + + // Multiple providers but none configured, use first we find and log a warning + if (configuredSender.isEmpty()) { + LOGGER.log( + Level.WARNING, + "Multiple HttpSenderProvider found. Please include only one, " + + "or specify preference setting " + + HTTP_SPI_PROPERTY + + " to the FQCN of the preferred provider."); + return httpSenderProviders.values().stream().findFirst().get(); + } + + // Multiple providers with configuration match, use configuration match + if (httpSenderProviders.containsKey(configuredSender)) { + return httpSenderProviders.get(configuredSender); + } + + // Multiple providers, configured does not match, throw + throw new IllegalStateException( + "No HttpSenderProvider matched configured " + HTTP_SPI_PROPERTY + ": " + configuredSender); + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/TlsConfigHelper.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/TlsConfigHelper.java new file mode 100644 index 00000000000..9ded82943fd --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/TlsConfigHelper.java @@ -0,0 +1,150 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import javax.annotation.Nullable; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; + +/** + * Utility class to help with management of TLS related components. TLS config consists {@link + * #keyManager}, {@link #trustManager}, which combine to form {@link #sslContext}. These components + * can be configured via higher level APIs ({@link #setTrustManagerFromCerts(byte[])} and {@link + * #setKeyManagerFromCerts(byte[], byte[])}) which parse keys in PEM format, or the lower level API + * {@link #setSslContext(SSLContext, X509TrustManager)} in which the components are directly set, + * but NOT both. Attempts to reconfigure components which have already been configured throw {@link + * IllegalStateException}. Consumers access components via any combination of {@link + * #getKeyManager()}, {@link #getTrustManager()}, and {@link #getSslContext()}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class TlsConfigHelper { + + @Nullable private X509KeyManager keyManager; + @Nullable private X509TrustManager trustManager; + @Nullable private SSLContext sslContext; + + public TlsConfigHelper() {} + + /** + * Configure the {@link X509TrustManager} from the given cert content. + * + *

    Must not be called multiple times, or if {@link #setSslContext(SSLContext, + * X509TrustManager)} has been previously called. + * + * @param trustedCertsPem Certificate in PEM format. + */ + public void setTrustManagerFromCerts(byte[] trustedCertsPem) { + if (sslContext != null) { + throw new IllegalStateException("sslContext has been previously configured"); + } + if (trustManager != null) { + throw new IllegalStateException("trustManager has been previously configured"); + } + + try { + this.trustManager = TlsUtil.trustManager(trustedCertsPem); + } catch (SSLException e) { + throw new IllegalStateException( + "Error creating X509TrustManager with provided certs. Are they valid X.509 in PEM format?", + e); + } + } + + /** + * Configure the {@link X509KeyManager} from the given private key and certificate, both in PEM + * format. + * + *

    Must not be called multiple times, or if {@link #setSslContext(SSLContext, + * X509TrustManager)} has been previously called. + * + * @param privateKeyPem Private key content in PEM format. + * @param certificatePem Certificate content in PEM format. + */ + public void setKeyManagerFromCerts(byte[] privateKeyPem, byte[] certificatePem) { + if (keyManager != null) { + throw new IllegalStateException("keyManager has been previously configured"); + } + if (sslContext != null) { + throw new IllegalStateException("sslContext has been previously configured"); + } + + try { + keyManager = TlsUtil.keyManager(privateKeyPem, certificatePem); + } catch (SSLException e) { + throw new IllegalStateException( + "Error creating X509KeyManager with provided certs. Are they valid X.509 in PEM format?", + e); + } + } + + /** + * Configure the {@link SSLContext} and {@link X509TrustManager}. + * + *

    Must not be called multiple times, or if {@link #setTrustManagerFromCerts(byte[])} or {@link + * #setKeyManagerFromCerts(byte[], byte[])} has been previously called. + * + * @param sslContext the SSL context. + * @param trustManager the trust manager. + */ + public void setSslContext(SSLContext sslContext, X509TrustManager trustManager) { + if (this.sslContext != null || this.trustManager != null) { + throw new IllegalStateException("sslContext or trustManager has been previously configured"); + } + if (this.keyManager != null) { + throw new IllegalStateException("keyManager has been previously configured"); + } + this.trustManager = trustManager; + this.sslContext = sslContext; + } + + /** Get the {@link X509KeyManager}. */ + @Nullable + public X509KeyManager getKeyManager() { + return keyManager; + } + + /** Get the {@link X509TrustManager}. */ + @Nullable + public X509TrustManager getTrustManager() { + return trustManager; + } + + /** Get the {@link SSLContext}. */ + @Nullable + public SSLContext getSslContext() { + if (sslContext != null) { + return sslContext; + } + + try { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init( + keyManager == null ? null : new KeyManager[] {keyManager}, + trustManager == null ? null : new TrustManager[] {trustManager}, + null); + return sslContext; + } catch (NoSuchAlgorithmException | KeyManagementException e) { + throw new IllegalArgumentException(e); + } + } + + /** Return a shallow copy of this instance. */ + public TlsConfigHelper copy() { + TlsConfigHelper copy = new TlsConfigHelper(); + copy.keyManager = keyManager; + copy.trustManager = trustManager; + copy.sslContext = sslContext; + return copy; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/TlsUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/TlsUtil.java new file mode 100644 index 00000000000..587e7fe9629 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/TlsUtil.java @@ -0,0 +1,184 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.joining; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.UnrecoverableKeyException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLException; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; + +/** + * Utilities for working with TLS. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class TlsUtil { + + private static final String PEM_KEY_HEADER = "-----BEGIN PRIVATE KEY-----"; + private static final String PEM_KEY_FOOTER = "-----END PRIVATE KEY-----"; + private static final List SUPPORTED_KEY_FACTORIES; + + static { + SUPPORTED_KEY_FACTORIES = new ArrayList<>(); + try { + SUPPORTED_KEY_FACTORIES.add(KeyFactory.getInstance("RSA")); + } catch (NoSuchAlgorithmException e) { + // Ignore and continue + } + try { + SUPPORTED_KEY_FACTORIES.add(KeyFactory.getInstance("EC")); + } catch (NoSuchAlgorithmException e) { + // Ignore and continue + } + } + + private TlsUtil() {} + + /** + * Creates {@link KeyManager} initiated by keystore containing single private key with matching + * certificate chain. + */ + public static X509KeyManager keyManager(byte[] privateKeyPem, byte[] certificatePem) + throws SSLException { + requireNonNull(privateKeyPem, "privateKeyPem"); + requireNonNull(certificatePem, "certificatePem"); + try { + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); + ks.load(null); + PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodePem(privateKeyPem)); + PrivateKey key = generatePrivateKey(keySpec, SUPPORTED_KEY_FACTORIES); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + ByteArrayInputStream is = new ByteArrayInputStream(certificatePem); + // pass the input stream to generateCertificates to get a list of certificates + // generateCertificates can handle multiple certificates in a single input stream + // including PEM files with explanatory text + List chain = (List) cf.generateCertificates(is); + ks.setKeyEntry("trusted", key, "".toCharArray(), chain.toArray(new Certificate[] {})); + + KeyManagerFactory kmf = + KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, "".toCharArray()); + return (X509KeyManager) kmf.getKeyManagers()[0]; + } catch (CertificateException + | KeyStoreException + | IOException + | NoSuchAlgorithmException + | UnrecoverableKeyException e) { + throw new SSLException("Could not build KeyManagerFactory from clientKeysPem.", e); + } + } + + /** Returns the platform default {@link X509TrustManager}. */ + public static X509TrustManager defaultTrustManager() throws SSLException { + try { + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + // Initialize with the platform default trust store. + tmf.init((KeyStore) null); + + return defaultTrustManager(tmf); + } catch (KeyStoreException | NoSuchAlgorithmException e) { + throw new SSLException("Could not build default TrustManager.", e); + } + } + + // Visible for testing + static X509TrustManager defaultTrustManager(TrustManagerFactory tmf) throws SSLException { + for (TrustManager trustManager : tmf.getTrustManagers()) { + if (trustManager instanceof X509TrustManager) { + return (X509TrustManager) trustManager; + } + } + + throw new SSLException("No X509TrustManager found"); + } + + // Visible for testing + static PrivateKey generatePrivateKey(PKCS8EncodedKeySpec keySpec, List keyFactories) + throws SSLException { + // Try to generate key using supported key factories + for (KeyFactory factory : keyFactories) { + try { + return factory.generatePrivate(keySpec); + } catch (InvalidKeySpecException e) { + // Ignore + } + } + throw new SSLException( + "Unable to generate key from supported algorithms: " + + keyFactories.stream().map(KeyFactory::getAlgorithm).collect(joining(",", "[", "]"))); + } + + /** Returns a {@link TrustManager} for the given trusted certificates. */ + public static X509TrustManager trustManager(byte[] trustedCertificatesPem) throws SSLException { + requireNonNull(trustedCertificatesPem, "trustedCertificatesPem"); + try { + KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); + ks.load(null); + + ByteArrayInputStream is = new ByteArrayInputStream(trustedCertificatesPem); + CertificateFactory factory = CertificateFactory.getInstance("X.509"); + int i = 0; + // pass the input stream to generateCertificates to get a list of certificates + // generateCertificates can handle multiple certificates in a single input stream + // including PEM files with explanatory text + List certificates = + (List) factory.generateCertificates(is); + for (Certificate certificate : certificates) { + ks.setCertificateEntry("cert_" + i, certificate); + i++; + } + + TrustManagerFactory tmf = + TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + tmf.init(ks); + return (X509TrustManager) tmf.getTrustManagers()[0]; + } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException e) { + throw new SSLException("Could not build TrustManagerFactory from trustedCertificatesPem.", e); + } + } + + // Visible for testing + static byte[] decodePem(byte[] pem) { + String pemStr = new String(pem, StandardCharsets.UTF_8).trim(); + if (!pemStr.startsWith(PEM_KEY_HEADER) || !pemStr.endsWith(PEM_KEY_FOOTER)) { + // pem may already be a decoded binary key, try to use it. + return pem; + } + + String contentWithNewLines = + pemStr.substring(PEM_KEY_HEADER.length(), pemStr.length() - PEM_KEY_FOOTER.length()); + String content = contentWithNewLines.replaceAll("\\s", ""); + + return Base64.getDecoder().decode(content); + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/ExtendedGrpcSenderConfig.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/ExtendedGrpcSenderConfig.java new file mode 100644 index 00000000000..2055ef35f9d --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/ExtendedGrpcSenderConfig.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.grpc; + +import io.opentelemetry.sdk.common.export.GrpcSenderConfig; +import javax.annotation.Nullable; + +/** + * Extended {@link GrpcSenderConfig} with internal / experimental APIs. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ExtendedGrpcSenderConfig extends GrpcSenderConfig { + + @Nullable + Object getManagedChannel(); +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStream.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStream.java similarity index 81% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStream.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStream.java index 39c49c10245..49b3916cc55 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStream.java +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStream.java @@ -22,10 +22,9 @@ package io.opentelemetry.exporter.internal.grpc; -import com.google.common.io.ByteStreams; import io.grpc.Drainable; import io.grpc.KnownLength; -import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.export.MessageWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -34,7 +33,7 @@ import javax.annotation.Nullable; /** - * Adapter from {@link Marshaler} to gRPC types. + * Adapter from {@link MessageWriter} to gRPC types. * *

    This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. @@ -43,11 +42,11 @@ // https://github.com/grpc/grpc-java/blob/2c2ebaebd5a93acec92fbd2708faac582db99371/protobuf-lite/src/main/java/io/grpc/protobuf/lite/ProtoInputStream.java public final class MarshalerInputStream extends InputStream implements Drainable, KnownLength { - @Nullable private Marshaler message; + @Nullable private MessageWriter message; @Nullable private ByteArrayInputStream partial; /** Creates a new {@link MarshalerInputStream}. */ - public MarshalerInputStream(Marshaler message) { + public MarshalerInputStream(MessageWriter message) { this.message = message; } @@ -55,11 +54,17 @@ public MarshalerInputStream(Marshaler message) { public int drainTo(OutputStream target) throws IOException { int written; if (message != null) { - written = message.getBinarySerializedSize(); - message.writeBinaryTo(target); + written = message.getContentLength(); + message.writeMessage(target); message = null; } else if (partial != null) { - written = (int) ByteStreams.copy(partial, target); + byte[] buffer = new byte[8192]; + written = 0; + int read; + while ((read = partial.read(buffer)) != -1) { + target.write(buffer, 0, read); + written += read; + } partial = null; } else { written = 0; @@ -82,7 +87,7 @@ public int read() throws IOException { @Override public int read(byte[] b, int off, int len) throws IOException { if (message != null) { - int size = message.getBinarySerializedSize(); + int size = message.getContentLength(); if (size == 0) { message = null; partial = null; @@ -103,16 +108,16 @@ public int read(byte[] b, int off, int len) throws IOException { return -1; } - private static byte[] toByteArray(Marshaler message) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(message.getBinarySerializedSize()); - message.writeBinaryTo(bos); + private static byte[] toByteArray(MessageWriter message) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(message.getContentLength()); + message.writeMessage(bos); return bos.toByteArray(); } @Override public int available() { if (message != null) { - return message.getBinarySerializedSize(); + return message.getContentLength(); } else if (partial != null) { return partial.available(); } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/package-info.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/package-info.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/package-info.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/grpc/package-info.java diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/AbstractStringEncoder.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/AbstractStringEncoder.java new file mode 100644 index 00000000000..33118d369ac --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/AbstractStringEncoder.java @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; +import javax.annotation.Nullable; + +/** + * This class contains shared logic for UTF-8 encoding operations while allowing subclasses to + * implement different mechanisms for accessing String internal byte arrays (e.g., Unsafe vs + * VarHandle). + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +abstract class AbstractStringEncoder implements StringEncoder { + + private final FallbackStringEncoder fallback = new FallbackStringEncoder(); + + @Override + public final void writeUtf8(CodedOutputStream output, @Nullable String string, int utf8Length) + throws IOException { + if (string == null) { + return; + } + // if the length of the latin1 string and the utf8 output are the same then the string must be + // composed of only 7bit characters and can be directly copied to the output + if (string.length() == utf8Length && isLatin1(string)) { + byte[] bytes = getStringBytes(string); + output.write(bytes, 0, bytes.length); + } else { + fallback.writeUtf8(output, string, utf8Length); + } + } + + @Override + public final int getUtf8Size(@Nullable String string) { + if (string == null) { + return 0; + } else if (isLatin1(string)) { + byte[] bytes = getStringBytes(string); + // latin1 bytes with negative value (most significant bit set) are encoded as 2 bytes in utf8 + return string.length() + countNegative(bytes); + } + + return fallback.getUtf8Size(string); + } + + protected abstract byte[] getStringBytes(String string); + + protected abstract boolean isLatin1(String string); + + protected abstract long getLong(byte[] bytes, int offset); + + // Inner loop can process at most 8 * 255 bytes without overflowing counter. To process more bytes + // inner loop has to be run multiple times. + private static final int MAX_INNER_LOOP_SIZE = 8 * 255; + // mask that selects only the most significant bit in every byte of the long + private static final long MOST_SIGNIFICANT_BIT_MASK = 0x8080808080808080L; + + /** Returns the count of bytes with negative value. */ + private int countNegative(byte[] bytes) { + int count = 0; + int offset = 0; + // We are processing one long (8 bytes) at a time. In the inner loop we are keeping counts in a + // long where each byte in the long is a separate counter. Due to this the inner loop can + // process a maximum of 8*255 bytes at a time without overflow. + for (int i = 1; i <= bytes.length / MAX_INNER_LOOP_SIZE + 1; i++) { + long tmp = 0; // each byte in this long is a separate counter + int limit = Math.min(i * MAX_INNER_LOOP_SIZE, bytes.length & ~7); + for (; offset < limit; offset += 8) { + long value = getLong(bytes, offset); + // Mask the value keeping only the most significant bit in each byte and then shift this bit + // to the position of the least significant bit in each byte. If the input byte was not + // negative then after this transformation it will be zero, if it was negative then it will + // be one. + tmp += (value & MOST_SIGNIFICANT_BIT_MASK) >>> 7; + } + // sum up counts + if (tmp != 0) { + for (int j = 0; j < 8; j++) { + count += (int) (tmp & 0xff); + tmp = tmp >>> 8; + } + } + } + + // Handle remaining bytes. Previous loop processes 8 bytes a time, if the input size is not + // divisible with 8 the remaining bytes are handled here. + for (int i = offset; i < bytes.length; i++) { + // same as if (bytes[i] < 0) count++; + count += bytes[i] >>> 31; + } + return count; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedInputStream.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedInputStream.java similarity index 99% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedInputStream.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedInputStream.java index 4a139b4530e..b6761258700 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedInputStream.java +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedInputStream.java @@ -127,6 +127,7 @@ private boolean isAtEnd() { } /** Read varint32. */ + @SuppressWarnings("LabelledBreakTarget") public int readRawVarint32() throws IOException { // See implementation notes for readRawVarint64 fastpath: diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedOutputStream.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedOutputStream.java similarity index 90% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedOutputStream.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedOutputStream.java index 4280de65c79..6cb0aa4db86 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedOutputStream.java +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/CodedOutputStream.java @@ -41,8 +41,10 @@ import static io.opentelemetry.exporter.internal.marshal.WireFormat.MAX_VARINT32_SIZE; import static io.opentelemetry.exporter.internal.marshal.WireFormat.MAX_VARINT_SIZE; +import io.opentelemetry.common.impl.ConfigUtil; import java.io.IOException; import java.io.OutputStream; +import java.nio.ByteBuffer; /** * Protobuf wire encoder. @@ -55,7 +57,7 @@ // // Differences // - No support for Message/Lite -// - No support for ByteString or ByteBuffer +// - No support for ByteString // - No support for message set extensions // - No support for Unsafe // - No support for Java String, only UTF-8 bytes @@ -71,7 +73,10 @@ public abstract class CodedOutputStream { static { int bufferSize = 50 * 1024; try { - bufferSize = Integer.parseInt(System.getProperty("otel.experimental.otlp.buffer-size")); + String bufferSizeConfig = ConfigUtil.getString("otel.experimental.otlp.buffer-size", ""); + if (!bufferSizeConfig.isEmpty()) { + bufferSize = Integer.parseInt(bufferSizeConfig); + } } catch (Throwable t) { // Ignore. } @@ -209,7 +214,7 @@ static int computeInt32SizeNoTag(final int value) { } /** Compute the number of bytes that would be needed to encode a {@code uint32} field. */ - static int computeUInt32SizeNoTag(final int value) { + public static int computeUInt32SizeNoTag(final int value) { if ((value & (~0 << 7)) == 0) { return 1; } @@ -325,6 +330,11 @@ public static int computeByteArraySizeNoTag(final byte[] value) { return computeLengthDelimitedFieldSize(value.length); } + /** Compute the number of bytes that would be needed to encode a {@code bytes} field. */ + public static int computeByteBufferSizeNoTag(final ByteBuffer value) { + return computeLengthDelimitedFieldSize(value.capacity()); + } + static int computeLengthDelimitedFieldSize(int fieldLength) { return computeUInt32SizeNoTag(fieldLength) + fieldLength; } @@ -371,6 +381,8 @@ static long encodeZigZag64(final long n) { abstract void writeByteArrayNoTag(final byte[] value, final int offset, final int length) throws IOException; + abstract void writeByteBufferNoTag(final ByteBuffer value) throws IOException; + // ================================================================= /** Abstract base class for buffered encoders. */ @@ -483,6 +495,49 @@ void writeByteArrayNoTag(final byte[] value, int offset, int length) throws IOEx write(value, offset, length); } + @Override + void writeByteBufferNoTag(final ByteBuffer value) throws IOException { + writeUInt32NoTag(value.capacity()); + if (value.hasArray()) { + write(value.array(), value.arrayOffset(), value.capacity()); + } else { + write((ByteBuffer) value.duplicate().clear()); + } + } + + void write(ByteBuffer value) throws IOException { + int length = value.remaining(); + if (limit - position >= length) { + // We have room in the current buffer. + value.get(buffer, position, length); + position += length; + totalBytesWritten += length; + } else { + // Write extends past current buffer. Fill the rest of this buffer and + // flush. + final int bytesWritten = limit - position; + value.get(buffer, position, bytesWritten); + length -= bytesWritten; + position = limit; + totalBytesWritten += bytesWritten; + doFlush(); + + // Now deal with the rest. + // Since we have an output stream, this is our buffer + // and buffer offset == 0 + while (length > limit) { + // Copy data into the buffer before writing it to OutputStream. + value.get(buffer, 0, limit); + out.write(buffer, 0, limit); + length -= limit; + totalBytesWritten += limit; + } + value.get(buffer, 0, length); + position = length; + totalBytesWritten += length; + } + } + @Override void write(byte value) throws IOException { if (position == limit) { diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/FallbackStringEncoder.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/FallbackStringEncoder.java new file mode 100644 index 00000000000..090a852d12f --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/FallbackStringEncoder.java @@ -0,0 +1,143 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; +import javax.annotation.Nullable; + +/** + * Fallback StringEncoder implementation using standard Java string operations. + * + *

    This implementation works on all Java versions and provides correct UTF-8 handling. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class FallbackStringEncoder implements StringEncoder { + + FallbackStringEncoder() {} + + @Override + public int getUtf8Size(@Nullable String string) { + return string != null ? encodedUtf8Length(string) : 0; + } + + @Override + public void writeUtf8(CodedOutputStream output, @Nullable String string, int utf8Length) + throws IOException { + if (string != null) { + encodeUtf8(output, string); + } + } + + // adapted from + // https://github.com/protocolbuffers/protobuf/blob/b618f6750aed641a23d5f26fbbaf654668846d24/java/core/src/main/java/com/google/protobuf/Utf8.java#L217 + private static int encodedUtf8Length(String string) { + // Warning to maintainers: this implementation is highly optimized. + int utf16Length = string.length(); + int utf8Length = utf16Length; + int i = 0; + + // This loop optimizes for pure ASCII. + while (i < utf16Length && string.charAt(i) < 0x80) { + i++; + } + + // This loop optimizes for chars less than 0x800. + for (; i < utf16Length; i++) { + char c = string.charAt(i); + if (c < 0x800) { + utf8Length += ((0x7f - c) >>> 31); // branch free! + } else { + utf8Length += encodedUtf8LengthGeneral(string, i); + break; + } + } + + if (utf8Length < utf16Length) { + // Necessary and sufficient condition for overflow because of maximum 3x expansion + throw new IllegalArgumentException( + "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); + } + + return utf8Length; + } + + // adapted from + // https://github.com/protocolbuffers/protobuf/blob/b618f6750aed641a23d5f26fbbaf654668846d24/java/core/src/main/java/com/google/protobuf/Utf8.java#L247 + private static int encodedUtf8LengthGeneral(String string, int start) { + int utf16Length = string.length(); + int utf8Length = 0; + for (int i = start; i < utf16Length; i++) { + char c = string.charAt(i); + if (c < 0x800) { + utf8Length += (0x7f - c) >>> 31; // branch free! + } else { + utf8Length += 2; + if (Character.isSurrogate(c)) { + // Check that we have a well-formed surrogate pair. + if (Character.codePointAt(string, i) != c) { + i++; + } else { + // invalid sequence + // At this point we have accumulated 3 byes of length (2 in this method and 1 in caller) + // for current character, reduce the length to 1 bytes as we are going to encode the + // invalid character as ? + utf8Length -= 2; + } + } + } + } + + return utf8Length; + } + + // encode utf8 the same way as length is computed in encodedUtf8Length + // adapted from + // https://github.com/protocolbuffers/protobuf/blob/b618f6750aed641a23d5f26fbbaf654668846d24/java/core/src/main/java/com/google/protobuf/Utf8.java#L1016 + private static void encodeUtf8(CodedOutputStream output, String in) throws IOException { + int utf16Length = in.length(); + int i = 0; + // Designed to take advantage of + // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination + for (char c; i < utf16Length && (c = in.charAt(i)) < 0x80; i++) { + output.write((byte) c); + } + if (i == utf16Length) { + return; + } + + for (char c; i < utf16Length; i++) { + c = in.charAt(i); + if (c < 0x80) { + // 1 byte, 7 bits + output.write((byte) c); + } else if (c < 0x800) { // 11 bits, two UTF-8 bytes + output.write((byte) ((0xF << 6) | (c >>> 6))); + output.write((byte) (0x80 | (0x3F & c))); + } else if (!Character.isSurrogate(c)) { + // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes + output.write((byte) ((0xF << 5) | (c >>> 12))); + output.write((byte) (0x80 | (0x3F & (c >>> 6)))); + output.write((byte) (0x80 | (0x3F & c))); + } else { + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, + // four UTF-8 bytes + int codePoint = Character.codePointAt(in, i); + if (codePoint != c) { + output.write((byte) ((0xF << 4) | (codePoint >>> 18))); + output.write((byte) (0x80 | (0x3F & (codePoint >>> 12)))); + output.write((byte) (0x80 | (0x3F & (codePoint >>> 6)))); + output.write((byte) (0x80 | (0x3F & codePoint))); + i++; + } else { + // invalid sequence + output.write((byte) '?'); + } + } + } + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonBufferedEncoder.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonBufferedEncoder.java new file mode 100644 index 00000000000..b679893ed17 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonBufferedEncoder.java @@ -0,0 +1,321 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; + +/** + * A minimal JSON encoder that serializes directly to an {@link OutputStream} as UTF-8, buffering + * writes and implementing only the subset of JSON generation {@link JsonSerializer} needs so OTLP + * JSON serialization has no third party dependency. Method names mirror the Jackson {@code + * JsonGenerator} that previously backed {@link JsonSerializer}. + * + *

    The caller is responsible for structural validity (matching braces); this class only inserts + * separators between members. {@link #writeRaw(String)} writes verbatim without touching separator + * state, which {@link MarshalerUtil#preserializeJsonFields(Marshaler)} relies on. + * + *

    Nesting depth is capped at {@value #MAX_NESTING_DEPTH}. Attempting to nest deeper throws + * {@link IOException} rather than {@link StackOverflowError}, which matters for recursive OTLP + * structures such as cyclic {@code Value} bodies that could otherwise DoS an exporter. The cap is + * intentionally conservative (Jackson 3's default is 500). Real OTLP payloads nest only a handful + * of levels, and it is easier to relax the cap later than to tighten it. + */ +final class JsonBufferedEncoder { + + static final int MAX_NESTING_DEPTH = 100; + + private static final byte[] TRUE = {'t', 'r', 'u', 'e'}; + private static final byte[] FALSE = {'f', 'a', 'l', 's', 'e'}; + private static final byte[] HEX = { + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + private final OutputStream out; + private final byte[] buffer = new byte[4096]; + private int pos; + + // Whether any member has been written at each nesting depth; depth 0 is the implicit root. The + // array grows on demand in push(), so it does not cap nesting depth. + private boolean[] hasMembers = new boolean[16]; + private int depth; + // True immediately after a field name has been written, meaning the next value is that field's + // value and must not be preceded by a comma. + private boolean afterKey; + + JsonBufferedEncoder(OutputStream out) { + this.out = out; + } + + void writeStartObject() throws IOException { + beforeValue(); + writeByte((byte) '{'); + push(); + } + + void writeEndObject() throws IOException { + pop(); + writeByte((byte) '}'); + } + + void writeObjectFieldStart(String name) throws IOException { + writeFieldName(name); + writeStartObject(); + } + + void writeArrayFieldStart(String name) throws IOException { + writeFieldName(name); + beforeValue(); + writeByte((byte) '['); + push(); + } + + void writeEndArray() throws IOException { + pop(); + writeByte((byte) ']'); + } + + void writeFieldName(String name) throws IOException { + if (hasMembers[depth]) { + writeByte((byte) ','); + } + hasMembers[depth] = true; + writeQuoted(name); + writeByte((byte) ':'); + afterKey = true; + } + + void writeStringField(String name, String value) throws IOException { + writeFieldName(name); + writeString(value); + } + + void writeBooleanField(String name, boolean value) throws IOException { + writeFieldName(name); + beforeValue(); + writeRawBytes(value ? TRUE : FALSE); + } + + void writeNumberField(String name, int value) throws IOException { + writeFieldName(name); + beforeValue(); + writeAscii(Integer.toString(value)); + } + + void writeNumberField(String name, double value) throws IOException { + writeFieldName(name); + writeNumber(value); + } + + void writeBinaryField(String name, byte[] value) throws IOException { + writeFieldName(name); + beforeValue(); + writeByte((byte) '"'); + writeRawBytes(Base64.getEncoder().encode(value)); + writeByte((byte) '"'); + } + + void writeString(String value) throws IOException { + beforeValue(); + writeQuoted(value); + } + + /** + * Writes a JSON string value from already UTF-8 encoded bytes, avoiding a decode-then-re-encode + * round trip. ASCII bytes are escaped as needed; multi-byte UTF-8 sequences pass through + * verbatim. + */ + void writeUtf8String(byte[] utf8Bytes) throws IOException { + beforeValue(); + writeByte((byte) '"'); + for (byte b : utf8Bytes) { + if (b >= 0) { + writeEscapedAscii(b); // ASCII, may need escaping + } else { + writeByte(b); // multi-byte UTF-8, never escapable + } + } + writeByte((byte) '"'); + } + + void writeNumber(double value) throws IOException { + beforeValue(); + // proto3 JSON encodes the non-finite values as quoted strings; a bare NaN/Infinity is not valid + // JSON. This matches io.opentelemetry.api.common.JsonEncoding. + if (Double.isNaN(value)) { + writeAscii("\"NaN\""); + } else if (Double.isInfinite(value)) { + writeAscii(value > 0 ? "\"Infinity\"" : "\"-Infinity\""); + } else { + writeAscii(Double.toString(value)); + } + } + + /** Writes pre-serialized JSON verbatim, without updating separator state. */ + void writeRaw(String raw) throws IOException { + writeRawBytes(raw.getBytes(StandardCharsets.UTF_8)); + } + + /** + * Drains buffered bytes to the underlying stream. Like {@code ProtoSerializer}, it neither + * flushes nor closes the underlying stream; the caller owns its lifecycle. + */ + void close() throws IOException { + try { + if (pos > 0) { + out.write(buffer, 0, pos); + pos = 0; + } + } catch (IOException e) { + // In try-with-resources, draining may rethrow the same exception that failed the body; wrap + // it so re-throwing doesn't trigger an IllegalArgumentException from illegal + // self-suppression. + throw new IOException(e); + } + } + + private void beforeValue() throws IOException { + if (afterKey) { + afterKey = false; + return; + } + if (hasMembers[depth]) { + writeByte((byte) ','); + } + hasMembers[depth] = true; + } + + private void push() throws IOException { + if (depth == MAX_NESTING_DEPTH) { + throw new IOException( + "JSON nesting depth exceeds maximum allowed (" + MAX_NESTING_DEPTH + ")"); + } + depth++; + if (depth == hasMembers.length) { + hasMembers = Arrays.copyOf(hasMembers, hasMembers.length * 2); + } + hasMembers[depth] = false; + } + + private void pop() { + depth--; + } + + /** Writes a quoted, escaped JSON string, encoding {@code value} as UTF-8. */ + private void writeQuoted(String value) throws IOException { + writeByte((byte) '"'); + int length = value.length(); + for (int i = 0; i < length; i++) { + char c = value.charAt(i); + if (c < 0x80) { + writeEscapedAscii((byte) c); + } else if (c < 0x800) { + writeByte((byte) (0xC0 | (c >> 6))); + writeByte((byte) (0x80 | (c & 0x3F))); + } else if (Character.isHighSurrogate(c) && i + 1 < length) { + char low = value.charAt(i + 1); + if (Character.isLowSurrogate(low)) { + int codePoint = Character.toCodePoint(c, low); + writeByte((byte) (0xF0 | (codePoint >> 18))); + writeByte((byte) (0x80 | ((codePoint >> 12) & 0x3F))); + writeByte((byte) (0x80 | ((codePoint >> 6) & 0x3F))); + writeByte((byte) (0x80 | (codePoint & 0x3F))); + i++; + } else { + writeByte((byte) '?'); + } + } else if (Character.isSurrogate(c)) { + // Unpaired surrogate; emit a replacement to keep the output valid UTF-8. + writeByte((byte) '?'); + } else { + writeByte((byte) (0xE0 | (c >> 12))); + writeByte((byte) (0x80 | ((c >> 6) & 0x3F))); + writeByte((byte) (0x80 | (c & 0x3F))); + } + } + writeByte((byte) '"'); + } + + /** Writes a single ASCII byte (0x00-0x7F), escaping it if required by JSON. */ + private void writeEscapedAscii(byte b) throws IOException { + switch (b) { + case '"': + writeByte((byte) '\\'); + writeByte((byte) '"'); + return; + case '\\': + writeByte((byte) '\\'); + writeByte((byte) '\\'); + return; + case '\b': + writeByte((byte) '\\'); + writeByte((byte) 'b'); + return; + case '\f': + writeByte((byte) '\\'); + writeByte((byte) 'f'); + return; + case '\n': + writeByte((byte) '\\'); + writeByte((byte) 'n'); + return; + case '\r': + writeByte((byte) '\\'); + writeByte((byte) 'r'); + return; + case '\t': + writeByte((byte) '\\'); + writeByte((byte) 't'); + return; + default: + if (b < 0x20) { + writeByte((byte) '\\'); + writeByte((byte) 'u'); + writeByte((byte) '0'); + writeByte((byte) '0'); + writeByte(HEX[(b >> 4) & 0xF]); + writeByte(HEX[b & 0xF]); + } else { + writeByte(b); + } + } + } + + /** Writes the bytes of an ASCII-only string such as a formatted number. */ + private void writeAscii(String value) throws IOException { + int length = value.length(); + for (int i = 0; i < length; i++) { + writeByte((byte) value.charAt(i)); + } + } + + private void writeRawBytes(byte[] bytes) throws IOException { + int offset = 0; + int remaining = bytes.length; + while (remaining > 0) { + if (pos == buffer.length) { + out.write(buffer, 0, pos); + pos = 0; + } + int chunk = Math.min(remaining, buffer.length - pos); + System.arraycopy(bytes, offset, buffer, pos, chunk); + pos += chunk; + offset += chunk; + remaining -= chunk; + } + } + + private void writeByte(byte b) throws IOException { + if (pos == buffer.length) { + out.write(buffer, 0, pos); + pos = 0; + } + buffer[pos++] = b; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonSerializer.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonSerializer.java new file mode 100644 index 00000000000..1d89aeba02f --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonSerializer.java @@ -0,0 +1,242 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.List; + +final class JsonSerializer extends Serializer { + + private final JsonBufferedEncoder encoder; + + JsonSerializer(OutputStream output) { + this.encoder = new JsonBufferedEncoder(output); + } + + @Override + protected void writeTraceId(ProtoFieldInfo field, String traceId) throws IOException { + encoder.writeStringField(field.getJsonName(), traceId); + } + + @Override + protected void writeSpanId(ProtoFieldInfo field, String spanId) throws IOException { + encoder.writeStringField(field.getJsonName(), spanId); + } + + @Override + public void writeBool(ProtoFieldInfo field, boolean value) throws IOException { + encoder.writeBooleanField(field.getJsonName(), value); + } + + @Override + protected void writeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) throws IOException { + encoder.writeNumberField(field.getJsonName(), enumValue.getEnumNumber()); + } + + @Override + protected void writeUint32(ProtoFieldInfo field, int value) throws IOException { + encoder.writeNumberField(field.getJsonName(), value); + } + + @Override + protected void writeSInt32(ProtoFieldInfo field, int value) throws IOException { + encoder.writeNumberField(field.getJsonName(), value); + } + + @Override + protected void writeint32(ProtoFieldInfo field, int value) throws IOException { + encoder.writeNumberField(field.getJsonName(), value); + } + + @Override + public void writeInt64(ProtoFieldInfo field, long value) throws IOException { + encoder.writeStringField(field.getJsonName(), Long.toString(value)); + } + + @Override + protected void writeFixed64(ProtoFieldInfo field, long value) throws IOException { + encoder.writeStringField(field.getJsonName(), Long.toString(value)); + } + + @Override + protected void writeFixed64Value(long value) throws IOException { + encoder.writeString(Long.toString(value)); + } + + @Override + protected void writeUInt64Value(long value) throws IOException { + encoder.writeString(Long.toString(value)); + } + + @Override + public void writeUInt64(ProtoFieldInfo field, long value) throws IOException { + encoder.writeStringField(field.getJsonName(), Long.toString(value)); + } + + @Override + protected void writeFixed32(ProtoFieldInfo field, int value) throws IOException { + encoder.writeNumberField(field.getJsonName(), value); + } + + @Override + public void writeDouble(ProtoFieldInfo field, double value) throws IOException { + encoder.writeNumberField(field.getJsonName(), value); + } + + @Override + protected void writeDoubleValue(double value) throws IOException { + encoder.writeNumber(value); + } + + @Override + public void writeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException { + encoder.writeFieldName(field.getJsonName()); + // Marshalers already encoded the String to UTF-8 bytes (binary serialization needs them for + // both size computation and writing), so write them directly rather than decoding and + // re-encoding. + encoder.writeUtf8String(utf8Bytes); + } + + @Override + public void writeString( + ProtoFieldInfo field, String string, int utf8Length, MarshalerContext context) + throws IOException { + encoder.writeFieldName(field.getJsonName()); + encoder.writeString(string); + } + + @Override + public void writeRepeatedString(ProtoFieldInfo field, byte[][] utf8Bytes) throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + for (byte[] value : utf8Bytes) { + // See writeString(ProtoFieldInfo, byte[]): the bytes are already UTF-8, so write directly. + encoder.writeUtf8String(value); + } + encoder.writeEndArray(); + } + + @Override + public void writeBytes(ProtoFieldInfo field, byte[] value) throws IOException { + encoder.writeBinaryField(field.getJsonName(), value); + } + + @Override + public void writeByteBuffer(ProtoFieldInfo field, ByteBuffer value) throws IOException { + byte[] data = new byte[value.capacity()]; + ((ByteBuffer) value.duplicate().clear()).get(data); + encoder.writeBinaryField(field.getJsonName(), data); + } + + @Override + protected void writeStartMessage(ProtoFieldInfo field, int protoMessageSize) throws IOException { + encoder.writeObjectFieldStart(field.getJsonName()); + } + + @Override + protected void writeEndMessage() throws IOException { + encoder.writeEndObject(); + } + + @Override + protected void writeStartRepeatedPrimitive( + ProtoFieldInfo field, int protoSizePerElement, int numElements) throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + } + + @Override + protected void writeEndRepeatedPrimitive() throws IOException { + encoder.writeEndArray(); + } + + @Override + protected void writeStartRepeatedVarint(ProtoFieldInfo field, int payloadSize) + throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + } + + @Override + protected void writeEndRepeatedVarint() throws IOException { + encoder.writeEndArray(); + } + + @Override + public void serializeRepeatedMessage(ProtoFieldInfo field, Marshaler[] repeatedMessage) + throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + for (Marshaler marshaler : repeatedMessage) { + writeMessageValue(marshaler); + } + encoder.writeEndArray(); + } + + @Override + public void serializeRepeatedMessage( + ProtoFieldInfo field, List repeatedMessage) throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + for (Marshaler marshaler : repeatedMessage) { + writeMessageValue(marshaler); + } + encoder.writeEndArray(); + } + + @Override + public void serializeRepeatedMessageWithContext( + ProtoFieldInfo field, + List messages, + StatelessMarshaler marshaler, + MarshalerContext context) + throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + for (int i = 0; i < messages.size(); i++) { + T message = messages.get(i); + encoder.writeStartObject(); + marshaler.writeTo(this, message, context); + encoder.writeEndObject(); + } + encoder.writeEndArray(); + } + + @Override + public void writeStartRepeated(ProtoFieldInfo field) throws IOException { + encoder.writeArrayFieldStart(field.getJsonName()); + } + + @Override + public void writeEndRepeated() throws IOException { + encoder.writeEndArray(); + } + + @Override + public void writeStartRepeatedElement(ProtoFieldInfo field, int protoMessageSize) + throws IOException { + encoder.writeStartObject(); + } + + @Override + public void writeEndRepeatedElement() throws IOException { + encoder.writeEndObject(); + } + + // Not a field. + void writeMessageValue(Marshaler message) throws IOException { + encoder.writeStartObject(); + message.writeTo(this); + encoder.writeEndObject(); + } + + @Override + public void writeSerializedMessage(byte[] protoSerialized, String jsonSerialized) + throws IOException { + encoder.writeRaw(jsonSerialized); + } + + @Override + public void close() throws IOException { + encoder.close(); + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Marshaler.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Marshaler.java new file mode 100644 index 00000000000..1c65e3303ce --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Marshaler.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.IOException; +import java.io.OutputStream; + +/** + * Marshaler from an SDK structure to protobuf wire format. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public abstract class Marshaler { + + /** Marshals into the {@link OutputStream} in proto binary format. */ + public final void writeBinaryTo(OutputStream output) throws IOException { + try (Serializer serializer = new ProtoSerializer(output)) { + writeTo(serializer); + } + } + + /** Marshals into the {@link OutputStream} in proto JSON format. */ + public final void writeJsonTo(OutputStream output) throws IOException { + try (JsonSerializer serializer = new JsonSerializer(output)) { + serializer.writeMessageValue(this); + } + } + + /** Returns the number of bytes this Marshaler will write in proto binary format. */ + public abstract int getBinarySerializedSize(); + + protected abstract void writeTo(Serializer output) throws IOException; + + public MessageWriter toJsonMessageWriter() { + return new MessageWriter() { + @Override + public void writeMessage(OutputStream output) throws IOException { + writeJsonTo(output); + } + + @Override + public int getContentLength() { + return -1; + } + }; + } + + public MessageWriter toBinaryMessageWriter() { + return new MessageWriter() { + @Override + public void writeMessage(OutputStream output) throws IOException { + writeBinaryTo(output); + } + + @Override + public int getContentLength() { + return getBinarySerializedSize(); + } + }; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerContext.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerContext.java new file mode 100644 index 00000000000..62177877ccc --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerContext.java @@ -0,0 +1,243 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceId; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * Class for keeping marshaling state. The state consists of integers, that we call sizes, and + * objects, that we call data. Both integers and objects can be read from the state in the order + * they were added (first in, first out). Additionally, this class provides various pools and caches + * for objects that can be reused between marshalling attempts. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class MarshalerContext { + private final boolean marshalStringNoAllocation; + private final StringEncoder stringEncoder; + + private int[] sizes = new int[16]; + private int sizeReadIndex; + private int sizeWriteIndex; + private Object[] data = new Object[16]; + private int dataReadIndex; + private int dataWriteIndex; + + public MarshalerContext() { + this(/* marshalStringNoAllocation= */ true); + } + + public MarshalerContext(boolean marshalStringNoAllocation) { + this.marshalStringNoAllocation = marshalStringNoAllocation; + this.stringEncoder = StringEncoder.getInstance(); + } + + public MarshalerContext(boolean marshalStringNoAllocation, StringEncoder stringEncoder) { + this.marshalStringNoAllocation = marshalStringNoAllocation; + this.stringEncoder = stringEncoder; + } + + public boolean marshalStringNoAllocation() { + return marshalStringNoAllocation; + } + + public StringEncoder getStringEncoder() { + return stringEncoder; + } + + public void addSize(int size) { + growSizeIfNeeded(); + sizes[sizeWriteIndex++] = size; + } + + public int addSize() { + growSizeIfNeeded(); + return sizeWriteIndex++; + } + + private void growSizeIfNeeded() { + if (sizeWriteIndex == sizes.length) { + int[] newSizes = new int[sizes.length * 2]; + System.arraycopy(sizes, 0, newSizes, 0, sizes.length); + sizes = newSizes; + } + } + + public void setSize(int index, int size) { + sizes[index] = size; + } + + public int getSize() { + return sizes[sizeReadIndex++]; + } + + public void addData(@Nullable Object o) { + growDataIfNeeded(); + data[dataWriteIndex++] = o; + } + + private void growDataIfNeeded() { + if (dataWriteIndex == data.length) { + Object[] newData = new Object[data.length * 2]; + System.arraycopy(data, 0, newData, 0, data.length); + data = newData; + } + } + + public T getData(Class type) { + return type.cast(data[dataReadIndex++]); + } + + private final IdPool traceIdPool = new IdPool(TraceId.getLength() / 2); + + /** Returns a buffer that can be used to hold a trace id. */ + public byte[] getTraceIdBuffer() { + return traceIdPool.get(); + } + + private final IdPool spanIdPool = new IdPool(SpanId.getLength() / 2); + + /** Returns a buffer that can be used to hold a span id. */ + public byte[] getSpanIdBuffer() { + return spanIdPool.get(); + } + + private static class IdPool { + private final List pool = new ArrayList<>(); + int index; + final int idSize; + + IdPool(int idSize) { + this.idSize = idSize; + } + + byte[] get() { + if (index < pool.size()) { + return pool.get(index++); + } + byte[] result = new byte[idSize]; + pool.add(result); + index++; + + return result; + } + + void reset() { + index = 0; + } + } + + private final Pool> mapPool = new Pool<>(IdentityHashMap::new, Map::clear); + + /** Returns a pooled identity map. */ + @SuppressWarnings("unchecked") + public Map getIdentityMap() { + return (Map) mapPool.get(); + } + + private final Pool> listPool = new Pool<>(ArrayList::new, List::clear); + + /** Returns a pooled list. */ + @SuppressWarnings("unchecked") + public List getList() { + return (List) listPool.get(); + } + + private static class Pool { + private final List pool = new ArrayList<>(); + private int index; + private final Supplier factory; + private final Consumer clean; + + Pool(Supplier factory, Consumer clean) { + this.factory = factory; + this.clean = clean; + } + + T get() { + if (index < pool.size()) { + return pool.get(index++); + } + T result = factory.get(); + pool.add(result); + index++; + + return result; + } + + void reset() { + for (int i = 0; i < index; i++) { + clean.accept(pool.get(i)); + } + index = 0; + } + } + + /** Reset context so that serialization could be re-run. */ + public void resetReadIndex() { + sizeReadIndex = 0; + dataReadIndex = 0; + } + + /** Reset context so that it could be reused. */ + public void reset() { + sizeReadIndex = 0; + sizeWriteIndex = 0; + for (int i = 0; i < dataWriteIndex; i++) { + data[i] = null; + } + dataReadIndex = 0; + dataWriteIndex = 0; + + traceIdPool.reset(); + spanIdPool.reset(); + + mapPool.reset(); + listPool.reset(); + } + + private static final AtomicInteger KEY_INDEX = new AtomicInteger(); + + /** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ + public static class Key { + final int index = KEY_INDEX.getAndIncrement(); + } + + public static Key key() { + return new Key(); + } + + private Object[] instances = new Object[16]; + + @SuppressWarnings("unchecked") + public T getInstance(Key key, Supplier supplier) { + if (key.index >= instances.length) { + Object[] newData = new Object[instances.length * 2]; + System.arraycopy(instances, 0, newData, 0, instances.length); + instances = newData; + } + + T result = (T) instances[key.index]; + if (result == null) { + result = supplier.get(); + instances[key.index] = result; + } + return result; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerUtil.java new file mode 100644 index 00000000000..9d7a10471f6 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerUtil.java @@ -0,0 +1,421 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.resources.Resource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import javax.annotation.Nullable; + +/** + * Marshaler utilities. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class MarshalerUtil { + private static final int TRACE_ID_VALUE_SIZE = + CodedOutputStream.computeLengthDelimitedFieldSize(TraceId.getLength() / 2); + private static final int SPAN_ID_VALUE_SIZE = + CodedOutputStream.computeLengthDelimitedFieldSize(SpanId.getLength() / 2); + + private static final byte[] EMPTY_BYTES = new byte[0]; + + /** Groups SDK items by resource and instrumentation scope. */ + public static + Map>> groupByResourceAndScope( + Collection dataList, + Function getResource, + Function getInstrumentationScope, + Function createMarshaler) { + // expectedMaxSize of 8 means initial map capacity of 16 to match HashMap + IdentityHashMap>> result = + new IdentityHashMap<>(8); + for (T data : dataList) { + Map> scopeInfoListMap = + result.computeIfAbsent(getResource.apply(data), unused -> new IdentityHashMap<>(8)); + List marshalerList = + scopeInfoListMap.computeIfAbsent( + getInstrumentationScope.apply(data), unused -> new ArrayList<>()); + marshalerList.add(createMarshaler.apply(data)); + } + return result; + } + + /** Preserialize into JSON format. */ + public static String preserializeJsonFields(Marshaler marshaler) { + ByteArrayOutputStream jsonBos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(jsonBos); + } catch (IOException e) { + throw new UncheckedIOException( + "Serialization error, this is likely a bug in OpenTelemetry.", e); + } + + // Strip the surrounding { } so the cached value can be embedded as the fields of an enclosing + // object. + byte[] jsonBytes = jsonBos.toByteArray(); + return new String(jsonBytes, 1, jsonBytes.length - 2, StandardCharsets.UTF_8); + } + + /** Returns the size of a repeated fixed64 field. */ + public static int sizeRepeatedFixed64(ProtoFieldInfo field, List values) { + return sizeRepeatedFixed64(field, values.size()); + } + + private static int sizeRepeatedFixed64(ProtoFieldInfo field, int numValues) { + if (numValues == 0) { + return 0; + } + int dataSize = WireFormat.FIXED64_SIZE * numValues; + int size = 0; + size += field.getTagSize(); + size += CodedOutputStream.computeLengthDelimitedFieldSize(dataSize); + return size; + } + + /** Returns the size of a repeated string field. */ + @SuppressWarnings("AvoidObjectArrays") + public static int sizeRepeatedString(ProtoFieldInfo field, byte[][] utf8Bytes) { + int size = 0; + for (byte[] i : utf8Bytes) { + size += sizeBytes(field, i, /* skipEmpty= */ false); + } + return size; + } + + /** + * Returns the size of a repeated uint64 field. + * + *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, + * and an actual payload of repeated varints. + */ + public static int sizeRepeatedUInt64(ProtoFieldInfo field, long[] values) { + if (values.length == 0) { + return 0; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); + } + + // tag size + payload indicator size + actual payload size + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; + } + + /** + * Returns the size of a repeated uint64 field. + * + *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, + * and an actual payload of repeated varints. + */ + public static int sizeRepeatedUInt64(ProtoFieldInfo field, List values) { + if (values.isEmpty()) { + return 0; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); + } + + // tag size + payload indicator size + actual payload size + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; + } + + /** + * Returns the size of a repeated uint64 field. + * + *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, + * and an actual payload of repeated varints. + * + *

    NOTE: This method has the same logic as {@link #sizeRepeatedUInt64(ProtoFieldInfo, long[])} + * )} but instead of using a primitive array it uses {@link DynamicPrimitiveLongList} to avoid + * boxing/unboxing + */ + public static int sizeRepeatedUInt64(ProtoFieldInfo field, DynamicPrimitiveLongList values) { + if (values.isEmpty()) { + return 0; + } + + int payloadSize = 0; + for (int i = 0; i < values.size(); i++) { + long v = values.getLong(i); + payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); + } + + // tag size + payload indicator size + actual payload size + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; + } + + /** + * Returns the size of a repeated int64 field. + * + *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, + * and an actual payload of repeated varints. + */ + public static int sizeRepeatedInt64(ProtoFieldInfo field, long[] values) { + if (values.length == 0) { + return 0; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeInt64SizeNoTag(v); + } + + // tag size + payload indicator size + actual payload size + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; + } + + /** + * Returns the size of a repeated int64 field. + * + *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, + * and an actual payload of repeated varints. + */ + public static int sizeRepeatedInt64(ProtoFieldInfo field, List values) { + if (values.isEmpty()) { + return 0; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeInt64SizeNoTag(v); + } + + // tag size + payload indicator size + actual payload size + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; + } + + /** + * Returns the size of a repeated int32 field. + * + *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, + * and an actual payload of repeated varints. + */ + public static int sizeRepeatedInt32(ProtoFieldInfo field, List values) { + if (values.isEmpty()) { + return 0; + } + + int payloadSize = 0; + for (int v : values) { + payloadSize += CodedOutputStream.computeInt32SizeNoTag(v); + } + + // tag size + payload indicator size + actual payload size + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; + } + + /** Returns the size of a repeated double field. */ + public static int sizeRepeatedDouble(ProtoFieldInfo field, List values) { + // Same as fixed64. + return sizeRepeatedFixed64(field, values.size()); + } + + /** Returns the size of a repeated message field. */ + @SuppressWarnings("AvoidObjectArrays") + public static int sizeRepeatedMessage( + ProtoFieldInfo field, T[] repeatedMessage) { + int size = 0; + int fieldTagSize = field.getTagSize(); + for (Marshaler message : repeatedMessage) { + int fieldSize = message.getBinarySerializedSize(); + size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + } + return size; + } + + /** Returns the size of a repeated message field. */ + public static int sizeRepeatedMessage( + ProtoFieldInfo field, List repeatedMessage) { + int size = 0; + int fieldTagSize = field.getTagSize(); + for (Marshaler message : repeatedMessage) { + int fieldSize = message.getBinarySerializedSize(); + size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + } + return size; + } + + /** Returns the size of a message field. */ + public static int sizeMessage(ProtoFieldInfo field, Marshaler message) { + int fieldSize = message.getBinarySerializedSize(); + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + } + + /** Returns the size of a bool field. */ + public static int sizeBool(ProtoFieldInfo field, boolean value) { + if (!value) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeBoolSizeNoTag(value); + } + + /** Returns the size of a int64 field. */ + public static int sizeInt64(ProtoFieldInfo field, long message) { + if (message == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeInt64SizeNoTag(message); + } + + /** Returns the size of a uint64 field. */ + public static int sizeUInt64(ProtoFieldInfo field, long message) { + if (message == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeUInt64SizeNoTag(message); + } + + /** Returns the size of a uint32 field. */ + public static int sizeUInt32(ProtoFieldInfo field, int message) { + if (message == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(message); + } + + /** Returns the size of a sint32 field. */ + public static int sizeSInt32(ProtoFieldInfo field, int message) { + if (message == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeSInt32SizeNoTag(message); + } + + /** Returns the size of a int32 field. */ + public static int sizeInt32(ProtoFieldInfo field, int message) { + if (message == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeInt32SizeNoTag(message); + } + + /** Returns the size of an optional int32 field. */ + public static int sizeInt32Optional(ProtoFieldInfo field, int message) { + return field.getTagSize() + CodedOutputStream.computeInt32SizeNoTag(message); + } + + /** Returns the size of an optional int32 field. */ + public static int sizeInt32Optional(ProtoFieldInfo field, @Nullable Integer message) { + if (message == null) { + return 0; + } + return sizeInt32Optional(field, (int) message); + } + + /** Returns the size of a double field. */ + public static int sizeDouble(ProtoFieldInfo field, double value) { + if (value == 0D) { + return 0; + } + return sizeDoubleOptional(field, value); + } + + /** Returns the size of a double field. */ + public static int sizeDoubleOptional(ProtoFieldInfo field, double value) { + return field.getTagSize() + CodedOutputStream.computeDoubleSizeNoTag(value); + } + + /** Returns the size of a fixed64 field. */ + public static int sizeFixed64(ProtoFieldInfo field, long value) { + if (value == 0L) { + return 0; + } + return sizeFixed64Optional(field, value); + } + + /** Returns the size of a fixed64 field. */ + public static int sizeFixed64Optional(ProtoFieldInfo field, long value) { + return field.getTagSize() + CodedOutputStream.computeFixed64SizeNoTag(value); + } + + /** Returns the size of a byte field when propagated to a fixed32. */ + public static int sizeByteAsFixed32(ProtoFieldInfo field, byte message) { + return sizeFixed32(field, ((int) message) & 0xff); + } + + /** Returns the size of a fixed32 field. */ + public static int sizeFixed32(ProtoFieldInfo field, int message) { + if (message == 0L) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeFixed32SizeNoTag(message); + } + + /** Returns the size of a bytes field. */ + public static int sizeBytes(ProtoFieldInfo field, byte[] message) { + return sizeBytes(field, message, /* skipEmpty= */ true); + } + + /** Returns the size of a bytes field. */ + public static int sizeBytes(ProtoFieldInfo field, byte[] message, boolean skipEmpty) { + if (message.length == 0 && skipEmpty) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeByteArraySizeNoTag(message); + } + + /** Returns the size of a bytes field based on the buffer's capacity. */ + public static int sizeByteBuffer(ProtoFieldInfo field, ByteBuffer message) { + if (message.capacity() == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeByteBufferSizeNoTag(message); + } + + /** Returns the size of a enum field. */ + // Assumes OTLP always defines the first item in an enum with number 0, which it does and will. + public static int sizeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) { + int number = enumValue.getEnumNumber(); + if (number == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeEnumSizeNoTag(number); + } + + /** Returns the size of a trace_id field. */ + public static int sizeTraceId(ProtoFieldInfo field, @Nullable String traceId) { + if (traceId == null) { + return 0; + } + return field.getTagSize() + TRACE_ID_VALUE_SIZE; + } + + /** Returns the size of a span_id field. */ + public static int sizeSpanId(ProtoFieldInfo field, @Nullable String spanId) { + if (spanId == null) { + return 0; + } + return field.getTagSize() + SPAN_ID_VALUE_SIZE; + } + + /** Converts the string to utf8 bytes for encoding. */ + public static byte[] toBytes(@Nullable String value) { + if (value == null || value.isEmpty()) { + return EMPTY_BYTES; + } + return value.getBytes(StandardCharsets.UTF_8); + } + + private MarshalerUtil() {} +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerWithSize.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerWithSize.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerWithSize.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerWithSize.java diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoEnumInfo.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoEnumInfo.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoEnumInfo.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoEnumInfo.java diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoFieldInfo.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoFieldInfo.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoFieldInfo.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoFieldInfo.java diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoSerializer.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoSerializer.java new file mode 100644 index 00000000000..a7b2b0a4491 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoSerializer.java @@ -0,0 +1,300 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import io.opentelemetry.api.impl.Base16EncodingUtils; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceId; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Serializer for the protobuf binary wire format. */ +final class ProtoSerializer extends Serializer implements AutoCloseable { + + // Cache ID conversion to bytes since we know it's common to use the same ID multiple times within + // a single export (trace ID and parent span ID). + // In practice, there is often only one thread that calls this code in the BatchSpanProcessor so + // reusing buffers for the thread is almost free. Even with multiple threads, it should still be + // worth it and is common practice in serialization libraries such as Jackson. + private static final ThreadLocal> THREAD_LOCAL_ID_CACHE = new ThreadLocal<>(); + + private final CodedOutputStream output; + private final Map idCache; + + ProtoSerializer(OutputStream output) { + this.output = CodedOutputStream.newInstance(output); + idCache = getIdCache(); + } + + @Override + protected void writeTraceId(ProtoFieldInfo field, String traceId) throws IOException { + byte[] traceIdBytes = + idCache.computeIfAbsent( + traceId, id -> Base16EncodingUtils.bytesFromBase16(id, TraceId.getLength())); + writeBytes(field, traceIdBytes); + } + + @Override + protected void writeTraceId(ProtoFieldInfo field, String traceId, MarshalerContext context) + throws IOException { + byte[] traceIdBytes = idCache.get(traceId); + if (traceIdBytes == null) { + traceIdBytes = context.getTraceIdBuffer(); + Base16EncodingUtils.bytesFromBase16(traceId, TraceId.getLength(), traceIdBytes); + idCache.put(traceId, traceIdBytes); + } + writeBytes(field, traceIdBytes); + } + + @Override + protected void writeSpanId(ProtoFieldInfo field, String spanId) throws IOException { + byte[] spanIdBytes = + idCache.computeIfAbsent( + spanId, id -> Base16EncodingUtils.bytesFromBase16(id, SpanId.getLength())); + writeBytes(field, spanIdBytes); + } + + @Override + protected void writeSpanId(ProtoFieldInfo field, String spanId, MarshalerContext context) + throws IOException { + byte[] spanIdBytes = idCache.get(spanId); + if (spanIdBytes == null) { + spanIdBytes = context.getSpanIdBuffer(); + Base16EncodingUtils.bytesFromBase16(spanId, SpanId.getLength(), spanIdBytes); + idCache.put(spanId, spanIdBytes); + } + writeBytes(field, spanIdBytes); + } + + @Override + public void writeBool(ProtoFieldInfo field, boolean value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeBoolNoTag(value); + } + + @Override + protected void writeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeEnumNoTag(enumValue.getEnumNumber()); + } + + @Override + protected void writeUint32(ProtoFieldInfo field, int value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeUInt32NoTag(value); + } + + @Override + protected void writeSInt32(ProtoFieldInfo field, int value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeSInt32NoTag(value); + } + + @Override + protected void writeint32(ProtoFieldInfo field, int value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeInt32NoTag(value); + } + + @Override + public void writeInt64(ProtoFieldInfo field, long value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeInt64NoTag(value); + } + + @Override + public void writeUInt64(ProtoFieldInfo field, long value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeUInt64NoTag(value); + } + + @Override + protected void writeFixed64(ProtoFieldInfo field, long value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeFixed64NoTag(value); + } + + @Override + protected void writeFixed64Value(long value) throws IOException { + output.writeFixed64NoTag(value); + } + + @Override + protected void writeUInt64Value(long value) throws IOException { + output.writeUInt64NoTag(value); + } + + @Override + protected void writeFixed32(ProtoFieldInfo field, int value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeFixed32NoTag(value); + } + + @Override + public void writeDouble(ProtoFieldInfo field, double value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeDoubleNoTag(value); + } + + @Override + protected void writeDoubleValue(double value) throws IOException { + output.writeDoubleNoTag(value); + } + + @Override + public void writeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException { + writeBytes(field, utf8Bytes); + } + + @Override + public void writeString( + ProtoFieldInfo field, String string, int utf8Length, MarshalerContext context) + throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeUInt32NoTag(utf8Length); + + context.getStringEncoder().writeUtf8(output, string, utf8Length); + } + + @Override + public void writeRepeatedString(ProtoFieldInfo field, byte[][] utf8Bytes) throws IOException { + for (byte[] value : utf8Bytes) { + writeString(field, value); + } + } + + @Override + public void writeBytes(ProtoFieldInfo field, byte[] value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeByteArrayNoTag(value); + } + + @Override + public void writeByteBuffer(ProtoFieldInfo field, ByteBuffer value) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeByteBufferNoTag(value); + } + + @Override + protected void writeStartMessage(ProtoFieldInfo field, int protoMessageSize) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeUInt32NoTag(protoMessageSize); + } + + @Override + protected void writeEndMessage() { + // Do nothing + } + + @Override + protected void writeStartRepeatedPrimitive( + ProtoFieldInfo field, int protoSizePerElement, int numElements) throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeUInt32NoTag(protoSizePerElement * numElements); + } + + @Override + protected void writeEndRepeatedPrimitive() { + // Do nothing + } + + @Override + protected void writeStartRepeatedVarint(ProtoFieldInfo field, int payloadSize) + throws IOException { + output.writeUInt32NoTag(field.getTag()); + output.writeUInt32NoTag(payloadSize); + } + + @Override + protected void writeEndRepeatedVarint() { + // Do nothing + } + + @Override + public void serializeRepeatedMessage(ProtoFieldInfo field, Marshaler[] repeatedMessage) + throws IOException { + for (Marshaler message : repeatedMessage) { + serializeMessage(field, message); + } + } + + @Override + public void serializeRepeatedMessage( + ProtoFieldInfo field, List repeatedMessage) throws IOException { + for (Marshaler message : repeatedMessage) { + serializeMessage(field, message); + } + } + + @Override + public void serializeRepeatedMessageWithContext( + ProtoFieldInfo field, + List messages, + StatelessMarshaler marshaler, + MarshalerContext context) + throws IOException { + for (int i = 0; i < messages.size(); i++) { + T message = messages.get(i); + writeStartMessage(field, context.getSize()); + marshaler.writeTo(this, message, context); + writeEndMessage(); + } + } + + @Override + public void writeStartRepeated(ProtoFieldInfo field) { + // Do nothing + } + + @Override + public void writeEndRepeated() { + // Do nothing + } + + @Override + public void writeStartRepeatedElement(ProtoFieldInfo field, int protoMessageSize) + throws IOException { + writeStartMessage(field, protoMessageSize); + } + + @Override + public void writeEndRepeatedElement() { + writeEndMessage(); + } + + @Override + public void writeSerializedMessage(byte[] protoSerialized, String jsonSerialized) + throws IOException { + output.writeRawBytes(protoSerialized); + } + + @Override + public void close() throws IOException { + idCache.clear(); + try { + output.flush(); + } catch (IOException e) { + // If close is called automatically as part of try-with-resources, it's possible that + // output.flush() will throw the same exception. Re-throwing the same exception in a finally + // block triggers an IllegalArgumentException indicating illegal self suppression. To avoid + // this, we wrap the exception so a different instance is thrown. + throw new IOException(e); + } + } + + private static Map getIdCache() { + Map result = THREAD_LOCAL_ID_CACHE.get(); + if (result == null) { + result = new HashMap<>(); + THREAD_LOCAL_ID_CACHE.set(result); + } + return result; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java new file mode 100644 index 00000000000..d93a8f10fdf --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java @@ -0,0 +1,705 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import javax.annotation.Nullable; + +/** + * Serializer to use when converting from an SDK data object into a protobuf output format. Unlike + * {@link CodedOutputStream}, which strictly encodes data into the protobuf binary format, this + * + *

      + *
    • Handles proto3 semantics of not outputting the value when it matches the default of a field + *
    • Can be implemented to serialize into protobuf JSON format (not binary) + *
    + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public abstract class Serializer implements AutoCloseable { + private static final MarshalerContext.Key ATTRIBUTES_WRITER_KEY = MarshalerContext.key(); + + Serializer() {} + + /** Serializes a trace ID field. */ + public void serializeTraceId(ProtoFieldInfo field, @Nullable String traceId) throws IOException { + if (traceId == null) { + return; + } + writeTraceId(field, traceId); + } + + public void serializeTraceId( + ProtoFieldInfo field, @Nullable String traceId, MarshalerContext context) throws IOException { + if (traceId == null) { + return; + } + writeTraceId(field, traceId, context); + } + + protected abstract void writeTraceId(ProtoFieldInfo field, String traceId) throws IOException; + + protected void writeTraceId(ProtoFieldInfo field, String traceId, MarshalerContext context) + throws IOException { + writeTraceId(field, traceId); + } + + /** Serializes a span ID field. */ + public void serializeSpanId(ProtoFieldInfo field, @Nullable String spanId) throws IOException { + if (spanId == null) { + return; + } + writeSpanId(field, spanId); + } + + public void serializeSpanId( + ProtoFieldInfo field, @Nullable String spanId, MarshalerContext context) throws IOException { + if (spanId == null) { + return; + } + writeSpanId(field, spanId, context); + } + + protected abstract void writeSpanId(ProtoFieldInfo field, String spanId) throws IOException; + + protected void writeSpanId(ProtoFieldInfo field, String spanId, MarshalerContext context) + throws IOException { + writeSpanId(field, spanId); + } + + /** Serializes a protobuf {@code bool} field. */ + public void serializeBool(ProtoFieldInfo field, boolean value) throws IOException { + if (!value) { + return; + } + writeBool(field, value); + } + + /** Writes a protobuf {@code bool} field, even if it matches the default value. */ + public abstract void writeBool(ProtoFieldInfo field, boolean value) throws IOException; + + /** Serializes a protobuf {@code enum} field. */ + public void serializeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) throws IOException { + if (enumValue.getEnumNumber() == 0) { + return; + } + writeEnum(field, enumValue); + } + + protected abstract void writeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) + throws IOException; + + /** Serializes a protobuf {@code uint32} field. */ + public void serializeUInt32(ProtoFieldInfo field, int value) throws IOException { + if (value == 0) { + return; + } + writeUint32(field, value); + } + + protected abstract void writeUint32(ProtoFieldInfo field, int value) throws IOException; + + /** Serializes a protobuf {@code sint32} field. */ + public void serializeSInt32(ProtoFieldInfo field, int value) throws IOException { + if (value == 0) { + return; + } + writeSInt32(field, value); + } + + protected abstract void writeSInt32(ProtoFieldInfo info, int value) throws IOException; + + /** Serializes a protobuf {@code int32} field. */ + public void serializeInt32(ProtoFieldInfo field, int value) throws IOException { + if (value == 0) { + return; + } + writeint32(field, value); + } + + /** Serializes a protobuf {@code int32} field. */ + public void serializeInt32Optional(ProtoFieldInfo field, int value) throws IOException { + writeint32(field, value); + } + + /** Serializes a protobuf {@code int32} field. */ + public void serializeInt32Optional(ProtoFieldInfo field, @Nullable Integer value) + throws IOException { + if (value != null) { + serializeInt32Optional(field, (int) value); + } + } + + protected abstract void writeint32(ProtoFieldInfo field, int value) throws IOException; + + /** Serializes a protobuf {@code int64} field. */ + public void serializeInt64(ProtoFieldInfo field, long value) throws IOException { + if (value == 0) { + return; + } + writeInt64(field, value); + } + + /** Serializes a protobuf {@code uint64} field. */ + public void serializeUInt64(ProtoFieldInfo field, long value) throws IOException { + if (value == 0) { + return; + } + writeUInt64(field, value); + } + + /** Writes a protobuf {@code int64} field, even if it matches the default value. */ + public abstract void writeInt64(ProtoFieldInfo field, long value) throws IOException; + + /** Writes a protobuf {@code uint64} field, even if it matches the default value. */ + public abstract void writeUInt64(ProtoFieldInfo field, long value) throws IOException; + + /** Serializes a protobuf {@code fixed64} field. */ + public void serializeFixed64(ProtoFieldInfo field, long value) throws IOException { + if (value == 0) { + return; + } + writeFixed64(field, value); + } + + /** Serializes a protobuf {@code fixed64} field. */ + public void serializeFixed64Optional(ProtoFieldInfo field, long value) throws IOException { + writeFixed64(field, value); + } + + protected abstract void writeFixed64(ProtoFieldInfo field, long value) throws IOException; + + protected abstract void writeFixed64Value(long value) throws IOException; + + protected abstract void writeUInt64Value(long value) throws IOException; + + /** + * Serializes a byte as a protobuf {@code fixed32} field. Ensures that there is no sign + * propagation if the high bit in the byte is set. + */ + public void serializeByteAsFixed32(ProtoFieldInfo field, byte value) throws IOException { + serializeFixed32(field, ((int) value) & 0xff); + } + + /** Serializes a protobuf {@code fixed32} field. */ + public void serializeFixed32(ProtoFieldInfo field, int value) throws IOException { + if (value == 0) { + return; + } + writeFixed32(field, value); + } + + protected abstract void writeFixed32(ProtoFieldInfo field, int value) throws IOException; + + /** Serializes a proto buf {@code double} field. */ + public void serializeDouble(ProtoFieldInfo field, double value) throws IOException { + if (value == 0D) { + return; + } + writeDouble(field, value); + } + + /** Serializes a proto buf {@code double} field. */ + public void serializeDoubleOptional(ProtoFieldInfo field, double value) throws IOException { + writeDouble(field, value); + } + + /** Writes a protobuf {@code double} field, even if it matches the default value. */ + public abstract void writeDouble(ProtoFieldInfo field, double value) throws IOException; + + protected abstract void writeDoubleValue(double value) throws IOException; + + /** + * Serializes a protobuf {@code string} field. {@code utf8Bytes} is the UTF8 encoded bytes of the + * string to serialize. + */ + public void serializeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException { + if (utf8Bytes.length == 0) { + return; + } + writeString(field, utf8Bytes); + } + + /** + * Serializes a protobuf {@code repeated string} field. {@code utf8Bytes} is the UTF8 encoded + * bytes of the strings to serialize. + */ + @SuppressWarnings("AvoidObjectArrays") + public void serializeRepeatedString(ProtoFieldInfo field, byte[][] utf8Bytes) throws IOException { + if (utf8Bytes.length == 0) { + return; + } + writeRepeatedString(field, utf8Bytes); + } + + /** + * Serializes a protobuf {@code string} field. {@code string} is the value to be serialized and + * {@code utf8Length} is the length of the string after it is encoded in UTF8. This method reads + * elements from context, use together with {@link + * StatelessMarshalerUtil#sizeStringWithContext(ProtoFieldInfo, String, MarshalerContext)}. + */ + public void serializeStringWithContext( + ProtoFieldInfo field, @Nullable String string, MarshalerContext context) throws IOException { + if (string == null || string.isEmpty()) { + return; + } + writeStringWithContext(field, string, context); + } + + /** + * Writes a protobuf {@code string} field, even if it matches the default value. This method reads + * elements from context, use together with {@link StatelessMarshalerUtil#getUtf8Size(String, + * MarshalerContext)}. + */ + public void writeStringWithContext(ProtoFieldInfo field, String string, MarshalerContext context) + throws IOException { + if (context.marshalStringNoAllocation()) { + writeString(field, string, context.getSize(), context); + } else { + byte[] valueUtf8 = context.getData(byte[].class); + writeString(field, valueUtf8); + } + } + + /** Writes a protobuf {@code string} field, even if it matches the default value. */ + public abstract void writeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException; + + public abstract void writeString( + ProtoFieldInfo field, String string, int utf8Length, MarshalerContext context) + throws IOException; + + /** Writes a protobuf {@code repeated string} field, even if it matches the default value. */ + @SuppressWarnings("AvoidObjectArrays") + public abstract void writeRepeatedString(ProtoFieldInfo field, byte[][] utf8Bytes) + throws IOException; + + /** Serializes a protobuf {@code bytes} field. */ + public void serializeBytes(ProtoFieldInfo field, byte[] value) throws IOException { + if (value.length == 0) { + return; + } + writeBytes(field, value); + } + + /** + * Serializes a protobuf {@code bytes} field. Writes all content of the ByteBuffer regardless of + * the current position and limit. Does not alter the position or limit of the provided + * ByteBuffer. + */ + public void serializeByteBuffer(ProtoFieldInfo field, ByteBuffer value) throws IOException { + if (value.capacity() == 0) { + return; + } + writeByteBuffer(field, value); + } + + public abstract void writeBytes(ProtoFieldInfo field, byte[] value) throws IOException; + + public abstract void writeByteBuffer(ProtoFieldInfo field, ByteBuffer value) throws IOException; + + protected abstract void writeStartMessage(ProtoFieldInfo field, int protoMessageSize) + throws IOException; + + protected abstract void writeEndMessage() throws IOException; + + /** Serializes a protobuf embedded {@code message}. */ + public void serializeMessage(ProtoFieldInfo field, Marshaler message) throws IOException { + writeStartMessage(field, message.getBinarySerializedSize()); + message.writeTo(this); + writeEndMessage(); + } + + /** + * Serializes a protobuf embedded {@code message}. This method adds elements to context, use + * together with {@link StatelessMarshalerUtil#sizeMessageWithContext(ProtoFieldInfo, Object, + * StatelessMarshaler, MarshalerContext)}. + */ + public void serializeMessageWithContext( + ProtoFieldInfo field, T message, StatelessMarshaler marshaler, MarshalerContext context) + throws IOException { + writeStartMessage(field, context.getSize()); + marshaler.writeTo(this, message, context); + writeEndMessage(); + } + + /** + * Serializes a protobuf embedded {@code message}. This method adds elements to context, use + * together with {@link StatelessMarshalerUtil#sizeMessageWithContext(ProtoFieldInfo, Object, + * Object, StatelessMarshaler2, MarshalerContext)}. + */ + public void serializeMessageWithContext( + ProtoFieldInfo field, + K key, + V value, + StatelessMarshaler2 marshaler, + MarshalerContext context) + throws IOException { + writeStartMessage(field, context.getSize()); + marshaler.writeTo(this, key, value, context); + writeEndMessage(); + } + + @SuppressWarnings("SameParameterValue") + protected abstract void writeStartRepeatedPrimitive( + ProtoFieldInfo field, int protoSizePerElement, int numElements) throws IOException; + + protected abstract void writeEndRepeatedPrimitive() throws IOException; + + protected abstract void writeStartRepeatedVarint(ProtoFieldInfo field, int payloadSize) + throws IOException; + + protected abstract void writeEndRepeatedVarint() throws IOException; + + /** Serializes a {@code repeated int32} field. */ + public void serializeRepeatedInt32(ProtoFieldInfo field, List values) + throws IOException { + if (values.isEmpty()) { + return; + } + + int payloadSize = 0; + for (int v : values) { + payloadSize += CodedOutputStream.computeInt32SizeNoTag(v); + } + + writeStartRepeatedVarint(field, payloadSize); + for (int value : values) { + writeUInt64Value(value); + } + writeEndRepeatedVarint(); + } + + /** Serializes a {@code repeated fixed64} field. */ + public void serializeRepeatedFixed64(ProtoFieldInfo field, List values) throws IOException { + if (values.isEmpty()) { + return; + } + writeStartRepeatedPrimitive(field, WireFormat.FIXED64_SIZE, values.size()); + for (int i = 0; i < values.size(); i++) { + Long value = values.get(i); + writeFixed64Value(value); + } + writeEndRepeatedPrimitive(); + } + + /** Serializes a {@code repeated fixed64} field. */ + public void serializeRepeatedFixed64(ProtoFieldInfo field, long[] values) throws IOException { + if (values.length == 0) { + return; + } + writeStartRepeatedPrimitive(field, WireFormat.FIXED64_SIZE, values.length); + for (long value : values) { + writeFixed64Value(value); + } + writeEndRepeatedPrimitive(); + } + + /** Serializes a {@code repeated uint64} field. */ + public void serializeRepeatedUInt64(ProtoFieldInfo field, long[] values) throws IOException { + if (values.length == 0) { + return; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); + } + + writeStartRepeatedVarint(field, payloadSize); + for (long value : values) { + writeUInt64Value(value); + } + writeEndRepeatedVarint(); + } + + /** Serializes a {@code repeated uint64} field. */ + public void serializeRepeatedUInt64(ProtoFieldInfo field, List values) throws IOException { + if (values.isEmpty()) { + return; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); + } + + writeStartRepeatedVarint(field, payloadSize); + for (long value : values) { + writeUInt64Value(value); + } + writeEndRepeatedVarint(); + } + + /** + * Serializes a {@code repeated uint64} field. + * + *

    NOTE: This is the same as {@link #serializeRepeatedUInt64(ProtoFieldInfo, long[])} but + * instead of taking a primitive array it takes a {@link DynamicPrimitiveLongList} as input. + */ + public void serializeRepeatedUInt64(ProtoFieldInfo field, DynamicPrimitiveLongList values) + throws IOException { + if (values.isEmpty()) { + return; + } + + int payloadSize = 0; + for (int i = 0; i < values.size(); i++) { + long v = values.getLong(i); + payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); + } + + writeStartRepeatedVarint(field, payloadSize); + for (int i = 0; i < values.size(); i++) { + long value = values.getLong(i); + writeUInt64Value(value); + } + writeEndRepeatedVarint(); + } + + /** Serializes a {@code repeated int64} field. */ + public void serializeRepeatedInt64(ProtoFieldInfo field, List values) throws IOException { + if (values.isEmpty()) { + return; + } + + int payloadSize = 0; + for (long v : values) { + payloadSize += CodedOutputStream.computeInt64SizeNoTag(v); + } + + writeStartRepeatedVarint(field, payloadSize); + for (long value : values) { + writeUInt64Value(value); + } + writeEndRepeatedVarint(); + } + + /** Serializes a {@code repeated double} field. */ + public void serializeRepeatedDouble(ProtoFieldInfo field, List values) + throws IOException { + if (values.isEmpty()) { + return; + } + writeStartRepeatedPrimitive(field, WireFormat.FIXED64_SIZE, values.size()); + for (int i = 0; i < values.size(); i++) { + Double value = values.get(i); + writeDoubleValue(value); + } + writeEndRepeatedPrimitive(); + } + + /** Serializes {@code repeated message} field. */ + @SuppressWarnings("AvoidObjectArrays") + public abstract void serializeRepeatedMessage(ProtoFieldInfo field, Marshaler[] repeatedMessage) + throws IOException; + + /** Serializes {@code repeated message} field. */ + public abstract void serializeRepeatedMessage( + ProtoFieldInfo field, List repeatedMessage) throws IOException; + + /** + * Serializes {@code repeated message} field. This method reads elements from context, use + * together with {@link StatelessMarshalerUtil#sizeRepeatedMessageWithContext(ProtoFieldInfo, + * List, StatelessMarshaler, MarshalerContext)}. + */ + public abstract void serializeRepeatedMessageWithContext( + ProtoFieldInfo field, + List messages, + StatelessMarshaler marshaler, + MarshalerContext context) + throws IOException; + + /** + * Serializes {@code repeated message} field. This method reads elements from context, use + * together with {@link StatelessMarshalerUtil#sizeRepeatedMessageWithContext(ProtoFieldInfo, + * Collection, StatelessMarshaler, MarshalerContext, MarshalerContext.Key)}. + */ + @SuppressWarnings("unchecked") + public void serializeRepeatedMessageWithContext( + ProtoFieldInfo field, + Collection messages, + StatelessMarshaler marshaler, + MarshalerContext context, + MarshalerContext.Key key) + throws IOException { + if (messages instanceof List) { + serializeRepeatedMessageWithContext(field, (List) messages, marshaler, context); + return; + } + + writeStartRepeated(field); + + if (!messages.isEmpty()) { + RepeatedElementWriter writer = context.getInstance(key, RepeatedElementWriter::new); + writer.initialize(field, this, marshaler, context); + try { + messages.forEach(writer); + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + + writeEndRepeated(); + } + + /** + * Serializes {@code repeated message} field. This method reads elements from context, use + * together with {@link StatelessMarshalerUtil#sizeRepeatedMessageWithContext(ProtoFieldInfo, Map, + * StatelessMarshaler2, MarshalerContext, MarshalerContext.Key)}. + */ + public void serializeRepeatedMessageWithContext( + ProtoFieldInfo field, + Map messages, + StatelessMarshaler2 marshaler, + MarshalerContext context, + MarshalerContext.Key key) + throws IOException { + writeStartRepeated(field); + + if (!messages.isEmpty()) { + RepeatedElementPairWriter writer = + context.getInstance(key, RepeatedElementPairWriter::new); + writer.initialize(field, this, marshaler, context); + try { + messages.forEach(writer); + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + + writeEndRepeated(); + } + + /** + * Serializes {@code repeated message} field. This method reads elements from context, use + * together with {@link StatelessMarshalerUtil#sizeRepeatedMessageWithContext(ProtoFieldInfo, + * Attributes, StatelessMarshaler2, MarshalerContext)}. + */ + public void serializeRepeatedMessageWithContext( + ProtoFieldInfo field, + Attributes attributes, + StatelessMarshaler2, Object> marshaler, + MarshalerContext context) + throws IOException { + writeStartRepeated(field); + + if (!attributes.isEmpty()) { + RepeatedElementPairWriter, Object> writer = + context.getInstance(ATTRIBUTES_WRITER_KEY, RepeatedElementPairWriter::new); + writer.initialize(field, this, marshaler, context); + try { + attributes.forEach(writer); + } catch (UncheckedIOException e) { + throw e.getCause(); + } + } + + writeEndRepeated(); + } + + private static class RepeatedElementWriter implements Consumer { + @SuppressWarnings("NullAway") + private ProtoFieldInfo field; + + @SuppressWarnings("NullAway") + private Serializer output; + + @SuppressWarnings("NullAway") + private StatelessMarshaler marshaler; + + @SuppressWarnings("NullAway") + private MarshalerContext context; + + void initialize( + ProtoFieldInfo field, + Serializer output, + StatelessMarshaler marshaler, + MarshalerContext context) { + this.field = field; + this.output = output; + this.marshaler = marshaler; + this.context = context; + } + + @Override + public void accept(T element) { + try { + output.writeStartRepeatedElement(field, context.getSize()); + marshaler.writeTo(output, element, context); + output.writeEndRepeatedElement(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } + + private static class RepeatedElementPairWriter implements BiConsumer { + @SuppressWarnings("NullAway") + private ProtoFieldInfo field; + + @SuppressWarnings("NullAway") + private Serializer output; + + @SuppressWarnings("NullAway") + private StatelessMarshaler2 marshaler; + + @SuppressWarnings("NullAway") + private MarshalerContext context; + + void initialize( + ProtoFieldInfo field, + Serializer output, + StatelessMarshaler2 marshaler, + MarshalerContext context) { + this.field = field; + this.output = output; + this.marshaler = marshaler; + this.context = context; + } + + @Override + public void accept(K key, V value) { + try { + output.writeStartRepeatedElement(field, context.getSize()); + marshaler.writeTo(output, key, value, context); + output.writeEndRepeatedElement(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + } + } + + /** Writes start of repeated messages. */ + public abstract void writeStartRepeated(ProtoFieldInfo field) throws IOException; + + /** Writes end of repeated messages. */ + public abstract void writeEndRepeated() throws IOException; + + /** Writes start of a repeated message element. */ + public abstract void writeStartRepeatedElement(ProtoFieldInfo field, int protoMessageSize) + throws IOException; + + /** Writes end of a repeated message element. */ + public abstract void writeEndRepeatedElement() throws IOException; + + /** Writes the value for a message field that has been pre-serialized. */ + public abstract void writeSerializedMessage(byte[] protoSerialized, String jsonSerialized) + throws IOException; + + @Override + public abstract void close() throws IOException; +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshaler.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshaler.java new file mode 100644 index 00000000000..dac3b7bbb94 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshaler.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; + +/** + * Marshaler from an SDK structure to protobuf wire format. It is intended that the instances of + * this interface don't keep marshaling state and can be singletons. Any state needed for marshaling + * should be stored in {@link MarshalerContext}. Marshaler should be used so that first {@link + * #getBinarySerializedSize} is called and after that {@link #writeTo} is called. Calling {@link + * #getBinarySerializedSize} may add values to {@link MarshalerContext} that are later used in + * {@link #writeTo}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface StatelessMarshaler { + + /** Returns the number of bytes marshaling given value will write in proto binary format. */ + int getBinarySerializedSize(T value, MarshalerContext context); + + /** Marshal given value using the provided {@link Serializer}. */ + void writeTo(Serializer output, T value, MarshalerContext context) throws IOException; +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshaler2.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshaler2.java new file mode 100644 index 00000000000..c2fc8769046 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshaler2.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; + +/** + * Marshaler from an SDK structure to protobuf wire format. It is intended that the instances of + * this interface don't keep marshaling state and can be singletons. Any state needed for marshaling + * should be stored in {@link MarshalerContext}. Marshaler should be used so that first {@link + * #getBinarySerializedSize} is called and after that {@link #writeTo} is called. Calling {@link + * #getBinarySerializedSize} may add values to {@link MarshalerContext} that are later used in + * {@link #writeTo}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface StatelessMarshaler2 { + + /** Returns the number of bytes this Marshaler will write. */ + int getBinarySerializedSize(K key, V value, MarshalerContext context); + + /** Marshal given key and value using the provided {@link Serializer}. */ + void writeTo(Serializer output, K key, V value, MarshalerContext context) throws IOException; +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshalerUtil.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshalerUtil.java new file mode 100644 index 00000000000..55e234b2b4a --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StatelessMarshalerUtil.java @@ -0,0 +1,309 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Function; +import javax.annotation.Nullable; + +/** + * Marshaler utilities. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class StatelessMarshalerUtil { + private static final MarshalerContext.Key GROUPER_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key ATTRIBUTES_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + + /** Groups SDK items by resource and instrumentation scope. */ + public static Map>> groupByResourceAndScope( + Collection dataList, + Function getResource, + Function getInstrumentationScope, + MarshalerContext context) { + Map>> result = context.getIdentityMap(); + + Grouper grouper = context.getInstance(GROUPER_KEY, Grouper::new); + grouper.initialize(result, getResource, getInstrumentationScope, context); + dataList.forEach(grouper); + + return result; + } + + private static class Grouper implements Consumer { + @SuppressWarnings("NullAway") + private Map>> result; + + @SuppressWarnings("NullAway") + private Function getResource; + + @SuppressWarnings("NullAway") + private Function getInstrumentationScope; + + @SuppressWarnings("NullAway") + private MarshalerContext context; + + void initialize( + Map>> result, + Function getResource, + Function getInstrumentationScope, + MarshalerContext context) { + this.result = result; + this.getResource = getResource; + this.getInstrumentationScope = getInstrumentationScope; + this.context = context; + } + + @Override + public void accept(T data) { + Resource resource = getResource.apply(data); + Map> scopeInfoListMap = result.get(resource); + if (scopeInfoListMap == null) { + scopeInfoListMap = context.getIdentityMap(); + result.put(resource, scopeInfoListMap); + } + InstrumentationScopeInfo instrumentationScopeInfo = getInstrumentationScope.apply(data); + List elementList = scopeInfoListMap.get(instrumentationScopeInfo); + if (elementList == null) { + elementList = context.getList(); + scopeInfoListMap.put(instrumentationScopeInfo, elementList); + } + elementList.add(data); + } + } + + /** + * Returns the size of a string field. This method adds elements to context, use together with + * {@link Serializer#serializeStringWithContext(ProtoFieldInfo, String, MarshalerContext)}. + */ + public static int sizeStringWithContext( + ProtoFieldInfo field, @Nullable String value, MarshalerContext context) { + if (value == null || value.isEmpty()) { + return sizeBytes(field, 0); + } + return sizeBytes(field, getUtf8Size(value, context)); + } + + /** + * Returns the UTF-8 size of a string, adding data to the context for later serialization. Use + * together with {@link Serializer#writeString(ProtoFieldInfo, String, int, MarshalerContext)}. + */ + public static int getUtf8Size(String value, MarshalerContext context) { + if (context.marshalStringNoAllocation()) { + int utf8Size = context.getStringEncoder().getUtf8Size(value); + context.addSize(utf8Size); + return utf8Size; + } else { + byte[] valueUtf8 = MarshalerUtil.toBytes(value); + context.addData(valueUtf8); + return valueUtf8.length; + } + } + + /** Returns the size of a bytes field. */ + private static int sizeBytes(ProtoFieldInfo field, int length) { + if (length == 0) { + return 0; + } + return field.getTagSize() + CodedOutputStream.computeLengthDelimitedFieldSize(length); + } + + /** + * Returns the size of a repeated message field. This method adds elements to context, use + * together with {@link Serializer#serializeRepeatedMessageWithContext(ProtoFieldInfo, List, + * StatelessMarshaler, MarshalerContext)}. + */ + public static int sizeRepeatedMessageWithContext( + ProtoFieldInfo field, + List messages, + StatelessMarshaler marshaler, + MarshalerContext context) { + if (messages.isEmpty()) { + return 0; + } + + int size = 0; + int fieldTagSize = field.getTagSize(); + for (int i = 0; i < messages.size(); i++) { + T message = messages.get(i); + int sizeIndex = context.addSize(); + int fieldSize = marshaler.getBinarySerializedSize(message, context); + context.setSize(sizeIndex, fieldSize); + size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + } + return size; + } + + /** + * Returns the size of a repeated message field. This method adds elements to context, use + * together with {@link Serializer#serializeRepeatedMessageWithContext(ProtoFieldInfo, Collection, + * StatelessMarshaler, MarshalerContext, MarshalerContext.Key)}. + */ + @SuppressWarnings("unchecked") + public static int sizeRepeatedMessageWithContext( + ProtoFieldInfo field, + Collection messages, + StatelessMarshaler marshaler, + MarshalerContext context, + MarshalerContext.Key key) { + if (messages instanceof List) { + return sizeRepeatedMessageWithContext(field, (List) messages, marshaler, context); + } + + if (messages.isEmpty()) { + return 0; + } + + RepeatedElementSizeCalculator sizeCalculator = + context.getInstance(key, RepeatedElementSizeCalculator::new); + sizeCalculator.initialize(field, marshaler, context); + messages.forEach(sizeCalculator); + + return sizeCalculator.size; + } + + /** + * Returns the size of a repeated message field. This method adds elements to context, use + * together with {@link Serializer#serializeRepeatedMessageWithContext(ProtoFieldInfo, Map, + * StatelessMarshaler2, MarshalerContext, MarshalerContext.Key)}. + */ + public static int sizeRepeatedMessageWithContext( + ProtoFieldInfo field, + Map messages, + StatelessMarshaler2 marshaler, + MarshalerContext context, + MarshalerContext.Key key) { + if (messages.isEmpty()) { + return 0; + } + + RepeatedElementPairSizeCalculator sizeCalculator = + context.getInstance(key, RepeatedElementPairSizeCalculator::new); + sizeCalculator.initialize(field, marshaler, context); + messages.forEach(sizeCalculator); + + return sizeCalculator.size; + } + + /** + * Returns the size of a repeated message field. This method adds elements to context, use + * together with {@link Serializer#serializeRepeatedMessageWithContext(ProtoFieldInfo, Attributes, + * StatelessMarshaler2, MarshalerContext)}. + */ + public static int sizeRepeatedMessageWithContext( + ProtoFieldInfo field, + Attributes attributes, + StatelessMarshaler2, Object> marshaler, + MarshalerContext context) { + if (attributes.isEmpty()) { + return 0; + } + + RepeatedElementPairSizeCalculator, Object> sizeCalculator = + context.getInstance(ATTRIBUTES_SIZE_CALCULATOR_KEY, RepeatedElementPairSizeCalculator::new); + sizeCalculator.initialize(field, marshaler, context); + attributes.forEach(sizeCalculator); + + return sizeCalculator.size; + } + + private static class RepeatedElementSizeCalculator implements Consumer { + private int size; + private int fieldTagSize; + + @SuppressWarnings("NullAway") + private StatelessMarshaler marshaler; + + @SuppressWarnings("NullAway") + private MarshalerContext context; + + void initialize( + ProtoFieldInfo field, StatelessMarshaler marshaler, MarshalerContext context) { + this.size = 0; + this.fieldTagSize = field.getTagSize(); + this.marshaler = marshaler; + this.context = context; + } + + @Override + public void accept(T element) { + int sizeIndex = context.addSize(); + int fieldSize = marshaler.getBinarySerializedSize(element, context); + context.setSize(sizeIndex, fieldSize); + size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + } + } + + private static class RepeatedElementPairSizeCalculator implements BiConsumer { + private int size; + private int fieldTagSize; + + @SuppressWarnings("NullAway") + private StatelessMarshaler2 marshaler; + + @SuppressWarnings("NullAway") + private MarshalerContext context; + + void initialize( + ProtoFieldInfo field, StatelessMarshaler2 marshaler, MarshalerContext context) { + this.size = 0; + this.fieldTagSize = field.getTagSize(); + this.marshaler = marshaler; + this.context = context; + } + + @Override + public void accept(K key, V value) { + int sizeIndex = context.addSize(); + int fieldSize = marshaler.getBinarySerializedSize(key, value, context); + context.setSize(sizeIndex, fieldSize); + size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + } + } + + /** + * Returns the size of a message field. This method adds elements to context, use together with + * {@link Serializer#serializeMessageWithContext(ProtoFieldInfo, Object, StatelessMarshaler, + * MarshalerContext)}. + */ + public static int sizeMessageWithContext( + ProtoFieldInfo field, T element, StatelessMarshaler marshaler, MarshalerContext context) { + int sizeIndex = context.addSize(); + int fieldSize = marshaler.getBinarySerializedSize(element, context); + int size = field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + context.setSize(sizeIndex, fieldSize); + return size; + } + + /** + * Returns the size of a message field. This method adds elements to context, use together with + * {@link Serializer#serializeMessageWithContext(ProtoFieldInfo, Object, Object, + * StatelessMarshaler2, MarshalerContext)}. + */ + public static int sizeMessageWithContext( + ProtoFieldInfo field, + K key, + V value, + StatelessMarshaler2 marshaler, + MarshalerContext context) { + int sizeIndex = context.addSize(); + int fieldSize = marshaler.getBinarySerializedSize(key, value, context); + int size = field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; + context.setSize(sizeIndex, fieldSize); + return size; + } + + private StatelessMarshalerUtil() {} +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StringEncoder.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StringEncoder.java new file mode 100644 index 00000000000..94344b70e4e --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StringEncoder.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.io.IOException; +import javax.annotation.Nullable; + +/** + * Interface for efficient UTF-8 string encoding operations. + * + *

    This interface provides optimized string-to-UTF-8 conversion with multiple implementations + * based on available platform capabilities. + * + *

    The optimal implementation is automatically selected at runtime via {@link #getInstance()}, in + * this priority order: + * + *

      + *
    • {@code UnsafeStringEncoder} - High-performance Java 9+ implementation using sun.misc.Unsafe + * to read the compact string fields of {@code String}. Only attempted when the Java version + * is detected to be below 23, to avoid the JEP 498 deprecation warning, and not on Android, + * where {@code String} does not have those fields. + *
    • {@code VarHandleStringEncoder} - High-performance Java 9+ implementation using VarHandle. + * Requires {@code --add-opens=java.base/java.lang=ALL-UNNAMED}. + *
    • {@code FallbackStringEncoder} - Implementation using standard Java operations + *
    + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +// public visibility only needed for benchmarking purposes +public interface StringEncoder { + + /** Returns the number of bytes required to encode the string as UTF-8. */ + int getUtf8Size(@Nullable String string); + + /** + * Write a string as UTF-8 bytes to the output stream using the pre-calculated UTF-8 length from + * {@link #getUtf8Size(String)}. + */ + void writeUtf8(CodedOutputStream output, @Nullable String string, int utf8Length) + throws IOException; + + /** Returns the best available StringEncoder implementation. */ + static StringEncoder getInstance() { + return StringEncoderHolder.INSTANCE; + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StringEncoderHolder.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StringEncoderHolder.java new file mode 100644 index 00000000000..ee52f1fa716 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/StringEncoderHolder.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.lang.reflect.Method; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * Factory and holder class for StringEncoder implementations. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +// public visibility only needed for benchmarking purposes +public final class StringEncoderHolder { + private static final Logger logger = Logger.getLogger(StringEncoderHolder.class.getName()); + + static final StringEncoder INSTANCE = createInstance(); + + /** + * Creates a FallbackStringEncoder instance. + * + * @return a new FallbackStringEncoder instance + */ + public static StringEncoder createFallbackEncoder() { + return new FallbackStringEncoder(); + } + + /** + * Creates an UnsafeStringEncoder instance if available. + * + * @return an UnsafeStringEncoder instance if available, or null if not available + */ + @Nullable + public static StringEncoder createUnsafeEncoder() { + // Android exposes sun.misc.Unsafe, but String does not have the OpenJDK internal fields used by + // UnsafeStringEncoder. ART logs an error when these missing fields are queried, even though the + // exception is caught. + if ("Dalvik".equals(System.getProperty("java.vm.name"))) { + return null; + } + return UnsafeStringEncoder.createIfAvailable(); + } + + /** + * Creates a VarHandleStringEncoder instance if available. + * + * @return a VarHandleStringEncoder instance if available, or null if not available + */ + @Nullable + public static StringEncoder createVarHandleEncoder() { + try { + Class varHandleClass = + Class.forName("io.opentelemetry.exporter.internal.marshal.VarHandleStringEncoder"); + Method createMethod = varHandleClass.getMethod("createIfAvailable"); + return (StringEncoder) createMethod.invoke(null); + } catch (Throwable t) { + return null; + } + } + + private static StringEncoder createInstance() { + // UnsafeStringEncoder has slightly better performance than VarHandleStringEncoder + // so try it first + if (!proactivelyAvoidUnsafe()) { + StringEncoder unsafeImpl = createUnsafeEncoder(); + if (unsafeImpl != null) { + logger.log(Level.FINE, "Using UnsafeStringEncoder for optimized Java 9+ performance"); + return unsafeImpl; + } + } + + // the VarHandle implementation requires --add-opens=java.base/java.lang=ALL-UNNAMED + // for VarHandles to access String internals + // + // generally users won't do this and so won't get the VarHandle implementation + // but the Java agent is able to automatically open these modules + // (see ModuleOpener.java in that repository) + StringEncoder varHandleImpl = createVarHandleEncoder(); + if (varHandleImpl != null) { + logger.log(Level.FINE, "Using VarHandleStringEncoder for optimal Java 9+ performance"); + return varHandleImpl; + } + + // Use fallback implementation + logger.log(Level.FINE, "Using FallbackStringEncoder"); + return createFallbackEncoder(); + } + + private static boolean proactivelyAvoidUnsafe() { + Optional javaVersion = getJavaVersion(); + // Avoid Unsafe on Java 23+ due to JEP-498 deprecation warnings: + // "WARNING: A terminally deprecated method in sun.misc.Unsafe has been called" + return javaVersion.map(version -> version >= 23).orElse(true); + } + + private static Optional getJavaVersion() { + String specVersion = System.getProperty("java.specification.version"); + if (specVersion != null) { + try { + return Optional.of(Double.parseDouble(specVersion)); + } catch (NumberFormatException exception) { + // ignore + } + } + return Optional.empty(); + } + + private StringEncoderHolder() {} +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/UnsafeStringEncoder.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/UnsafeStringEncoder.java new file mode 100644 index 00000000000..3abb014b9b7 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/UnsafeStringEncoder.java @@ -0,0 +1,105 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.lang.reflect.Field; +import javax.annotation.Nullable; +import sun.misc.Unsafe; + +/** + * StringEncoder implementation using sun.misc.Unsafe for high performance on Java 9+. + * + *

    This implementation provides optimized string operations by directly accessing String internal + * fields using Unsafe operations. It's only created if Unsafe is available and all required field + * offsets can be resolved. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class UnsafeStringEncoder extends AbstractStringEncoder { + + // Field offsets for direct memory access + private final long valueOffset; + private final long coderOffset; + private final long byteArrayBaseOffset; + + private UnsafeStringEncoder(long valueOffset, long coderOffset, long byteArrayBaseOffset) { + this.valueOffset = valueOffset; + this.coderOffset = coderOffset; + this.byteArrayBaseOffset = byteArrayBaseOffset; + } + + @Nullable + public static UnsafeStringEncoder createIfAvailable() { + if (UnsafeHolder.UNSAFE == null) { + return null; + } + + long valueOffset = getStringFieldOffset("value", byte[].class); + long coderOffset = getStringFieldOffset("coder", byte.class); // this only exists in Java 9+ + + if (valueOffset == -1 || coderOffset == -1) { + return null; + } + + long byteArrayBaseOffset = UnsafeHolder.UNSAFE.arrayBaseOffset(byte[].class); + + return new UnsafeStringEncoder(valueOffset, coderOffset, byteArrayBaseOffset); + } + + @Override + protected byte[] getStringBytes(String string) { + return (byte[]) UnsafeHolder.UNSAFE.getObject(string, valueOffset); + } + + @Override + protected boolean isLatin1(String string) { + return UnsafeHolder.UNSAFE.getByte(string, coderOffset) == 0; + } + + @Override + protected long getLong(byte[] bytes, int offset) { + return UnsafeHolder.UNSAFE.getLong(bytes, byteArrayBaseOffset + offset); + } + + private static long getStringFieldOffset(String fieldName, Class expectedType) { + try { + if (UnsafeHolder.UNSAFE == null) { + return -1; + } + + Field field = String.class.getDeclaredField(fieldName); + if (!expectedType.isAssignableFrom(field.getType())) { + return -1; + } + return UnsafeHolder.UNSAFE.objectFieldOffset(field); + } catch (Exception exception) { + return -1; + } + } + + /** Holder class for lazy initialization of Unsafe. */ + private static final class UnsafeHolder { + private static final Unsafe UNSAFE; + + static { + UNSAFE = getUnsafe(); + } + + private UnsafeHolder() {} + + @SuppressWarnings("NullAway") + private static Unsafe getUnsafe() { + try { + Field field = Unsafe.class.getDeclaredField("theUnsafe"); + field.setAccessible(true); + return (Unsafe) field.get(null); + } catch (Throwable t) { + return null; + } + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/WireFormat.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/WireFormat.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/WireFormat.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/WireFormat.java diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/package-info.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/package-info.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/package-info.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/marshal/package-info.java diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/ExporterInstrumentation.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/ExporterInstrumentation.java new file mode 100644 index 00000000000..5a2c37334a5 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/ExporterInstrumentation.java @@ -0,0 +1,158 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.common.internal.Signal; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URL; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class ExporterInstrumentation { + + private final ExporterMetrics implementation; + + public ExporterInstrumentation( + InternalTelemetryVersion schema, + Supplier meterProviderSupplier, + StandardComponentId componentId, + URI endpoint) { + + Signal signal = componentId.getStandardType().signal(); + switch (schema) { + case LEGACY: + implementation = + LegacyExporterMetrics.isSupportedType(componentId.getStandardType()) + ? new LegacyExporterMetrics(meterProviderSupplier, componentId.getStandardType()) + : NoopExporterMetrics.INSTANCE; + break; + case LATEST: + implementation = + signal == Signal.PROFILE + ? NoopExporterMetrics.INSTANCE + : new SemConvExporterMetrics( + meterProviderSupplier, signal, componentId, extractServerAttributes(endpoint)); + break; + default: + throw new IllegalStateException("Unhandled case: " + schema); + } + } + + // visible for testing + static Attributes extractServerAttributes(URI httpEndpoint) { + AttributesBuilder builder = Attributes.builder(); + String host = httpEndpoint.getHost(); + int port = httpEndpoint.getPort(); + if (host == null) { + // URI.getHost() returns null for some valid DNS names (JDK-8188305); URL accepts them. + try { + URL url = httpEndpoint.toURL(); + if (!url.getHost().isEmpty()) { + host = url.getHost(); + } + port = url.getPort(); + } catch (MalformedURLException e) { + // Not a URL either, leave host unset. + } + } + if (host != null) { + builder.put(SemConvConstants.SERVER_ADDRESS, host); + } + if (port == -1) { + String scheme = httpEndpoint.getScheme(); + if ("https".equals(scheme)) { + port = 443; + } else if ("http".equals(scheme)) { + port = 80; + } + } + if (port != -1) { + builder.put(SemConvConstants.SERVER_PORT, port); + } + return builder.build(); + } + + public Recording startRecordingExport(int itemCount) { + return new Recording(implementation.startRecordingExport(itemCount)); + } + + /** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ + public static class Recording { + + private final ExporterMetrics.Recording delegate; + @Nullable private Long httpStatusCode; + @Nullable private GrpcStatusCode grpcStatusCode; + + private Recording(ExporterMetrics.Recording delegate) { + this.delegate = delegate; + } + + public void setHttpStatusCode(long httpStatusCode) { + if (grpcStatusCode != null) { + throw new IllegalStateException( + "gRPC status code already set, can only set either gRPC or HTTP"); + } + this.httpStatusCode = httpStatusCode; + } + + public void setGrpcStatusCode(GrpcStatusCode grpcStatusCode) { + if (httpStatusCode != null) { + throw new IllegalStateException( + "HTTP status code already set, can only set either gRPC or HTTP"); + } + this.grpcStatusCode = grpcStatusCode; + } + + /** Callback to notify that the export was successful. */ + public void finishSuccessful() { + delegate.finishSuccessful(buildRequestAttributes()); + } + + /** + * Callback to notify that the export has failed with the given {@link Throwable} as failure + * cause. + * + * @param failureCause the cause of the failure + */ + public void finishFailed(Throwable failureCause) { + finishFailed(failureCause.getClass().getName()); + } + + /** + * Callback to notify that the export has failed. + * + * @param errorType a failure reason suitable for the error.type attribute + */ + public void finishFailed(String errorType) { + delegate.finishFailed(errorType, buildRequestAttributes()); + } + + private Attributes buildRequestAttributes() { + if (httpStatusCode != null) { + return Attributes.of(SemConvConstants.HTTP_RESPONSE_STATUS_CODE, httpStatusCode); + } + if (grpcStatusCode != null) { + return Attributes.of(SemConvConstants.RPC_STATUS_CODE, grpcStatusCode.name()); + } + return Attributes.empty(); + } + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/ExporterMetrics.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/ExporterMetrics.java new file mode 100644 index 00000000000..ca7d29187df --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/ExporterMetrics.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.metrics; + +import io.opentelemetry.api.common.Attributes; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public interface ExporterMetrics { + + Recording startRecordingExport(int itemCount); + + /** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ + abstract class Recording { + + private boolean alreadyEnded = false; + + protected Recording() {} + + public final void finishSuccessful(Attributes requestAttributes) { + ensureEndedOnce(); + doFinish(null, requestAttributes); + } + + public final void finishFailed(String errorType, Attributes requestAttributes) { + ensureEndedOnce(); + if (errorType == null || errorType.isEmpty()) { + throw new IllegalArgumentException("The export failed but no failure reason was provided"); + } + doFinish(errorType, requestAttributes); + } + + private void ensureEndedOnce() { + if (alreadyEnded) { + throw new IllegalStateException("Recording already ended"); + } + alreadyEnded = true; + } + + /** + * Invoked when the export has finished, either successfully or failed. + * + * @param errorType null if the export was successful, otherwise a failure reason suitable for + * the error.type attribute + * @param requestAttributes additional attributes to add to request metrics + */ + protected abstract void doFinish(@Nullable String errorType, Attributes requestAttributes); + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/LegacyExporterMetrics.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/LegacyExporterMetrics.java new file mode 100644 index 00000000000..235ab16fdaa --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/LegacyExporterMetrics.java @@ -0,0 +1,191 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.metrics; + +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.internal.Signal; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * Implements health metrics for exporters which were defined prior to the standardization in + * semantic conventions. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class LegacyExporterMetrics implements ExporterMetrics { + + private static final AttributeKey ATTRIBUTE_KEY_TYPE = stringKey("type"); + private static final AttributeKey ATTRIBUTE_KEY_SUCCESS = booleanKey("success"); + + private final Supplier meterProviderSupplier; + private final String exporterName; + private final String transportName; + private final Attributes seenAttrs; + private final Attributes successAttrs; + private final Attributes failedAttrs; + + /** Access via {@link #seen()}. */ + @Nullable private volatile LongCounter seen; + + /** Access via {@link #exported()} . */ + @Nullable private volatile LongCounter exported; + + LegacyExporterMetrics( + Supplier meterProviderSupplier, + StandardComponentId.ExporterType exporterType) { + this.meterProviderSupplier = meterProviderSupplier; + this.exporterName = getExporterName(exporterType); + this.transportName = getTransportName(exporterType); + this.seenAttrs = + Attributes.builder().put(ATTRIBUTE_KEY_TYPE, getTypeString(exporterType.signal())).build(); + this.successAttrs = this.seenAttrs.toBuilder().put(ATTRIBUTE_KEY_SUCCESS, true).build(); + this.failedAttrs = this.seenAttrs.toBuilder().put(ATTRIBUTE_KEY_SUCCESS, false).build(); + } + + public static boolean isSupportedType(StandardComponentId.ExporterType exporterType) { + switch (exporterType) { + case OTLP_GRPC_SPAN_EXPORTER: + case OTLP_HTTP_SPAN_EXPORTER: + case OTLP_HTTP_JSON_SPAN_EXPORTER: + case OTLP_GRPC_LOG_EXPORTER: + case OTLP_HTTP_LOG_EXPORTER: + case OTLP_HTTP_JSON_LOG_EXPORTER: + case OTLP_GRPC_METRIC_EXPORTER: + case OTLP_HTTP_METRIC_EXPORTER: + case OTLP_HTTP_JSON_METRIC_EXPORTER: + return true; + default: + return false; + } + } + + private static String getTypeString(Signal signal) { + switch (signal) { + case SPAN: + return "span"; + case LOG: + return "log"; + case METRIC: + return "metric"; + case PROFILE: + throw new IllegalArgumentException("Profiles are not supported"); + } + throw new IllegalArgumentException("Unhandled signal type: " + signal); + } + + private static String getExporterName(StandardComponentId.ExporterType exporterType) { + switch (exporterType) { + case OTLP_GRPC_SPAN_EXPORTER: + case OTLP_HTTP_SPAN_EXPORTER: + case OTLP_HTTP_JSON_SPAN_EXPORTER: + case OTLP_GRPC_LOG_EXPORTER: + case OTLP_HTTP_LOG_EXPORTER: + case OTLP_HTTP_JSON_LOG_EXPORTER: + case OTLP_GRPC_METRIC_EXPORTER: + case OTLP_HTTP_METRIC_EXPORTER: + case OTLP_HTTP_JSON_METRIC_EXPORTER: + return "otlp"; + case OTLP_GRPC_PROFILES_EXPORTER: + throw new IllegalArgumentException("Profiles are not supported"); + } + throw new IllegalArgumentException("Not a supported exporter type: " + exporterType); + } + + private static String getTransportName(StandardComponentId.ExporterType exporterType) { + switch (exporterType) { + case OTLP_GRPC_SPAN_EXPORTER: + case OTLP_GRPC_LOG_EXPORTER: + case OTLP_GRPC_METRIC_EXPORTER: + return "grpc"; + case OTLP_HTTP_SPAN_EXPORTER: + case OTLP_HTTP_LOG_EXPORTER: + case OTLP_HTTP_METRIC_EXPORTER: + return "http"; + case OTLP_HTTP_JSON_SPAN_EXPORTER: + case OTLP_HTTP_JSON_LOG_EXPORTER: + case OTLP_HTTP_JSON_METRIC_EXPORTER: + return "http-json"; + case OTLP_GRPC_PROFILES_EXPORTER: + throw new IllegalArgumentException("Profiles are not supported"); + } + throw new IllegalArgumentException("Not a supported exporter type: " + exporterType); + } + + /** Record number of records seen. */ + private void addSeen(long value) { + seen().add(value, seenAttrs); + } + + /** Record number of records which successfully exported. */ + private void addSuccess(long value) { + exported().add(value, successAttrs); + } + + /** Record number of records which failed to export. */ + private void addFailed(long value) { + exported().add(value, failedAttrs); + } + + private LongCounter seen() { + LongCounter seen = this.seen; + if (seen == null || SemConvExporterMetrics.isNoop(seen)) { + seen = meter().counterBuilder(exporterName + ".exporter.seen").build(); + this.seen = seen; + } + return seen; + } + + private LongCounter exported() { + LongCounter exported = this.exported; + if (exported == null || SemConvExporterMetrics.isNoop(exported)) { + exported = meter().counterBuilder(exporterName + ".exporter.exported").build(); + this.exported = exported; + } + return exported; + } + + private Meter meter() { + MeterProvider meterProvider = meterProviderSupplier.get(); + if (meterProvider == null) { + meterProvider = MeterProvider.noop(); + } + return meterProvider.get("io.opentelemetry.exporters." + exporterName + "-" + transportName); + } + + @Override + public ExporterMetrics.Recording startRecordingExport(int itemCount) { + return new Recording(itemCount); + } + + private class Recording extends ExporterMetrics.Recording { + + private final int itemCount; + + private Recording(int itemCount) { + this.itemCount = itemCount; + addSeen(itemCount); + } + + @Override + protected void doFinish(@Nullable String errorType, Attributes requestAttributes) { + if (errorType != null) { + addFailed(itemCount); + } else { + addSuccess(itemCount); + } + } + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/NoopExporterMetrics.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/NoopExporterMetrics.java new file mode 100644 index 00000000000..9190dddb20e --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/NoopExporterMetrics.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.metrics; + +import io.opentelemetry.api.common.Attributes; +import javax.annotation.Nullable; + +class NoopExporterMetrics implements ExporterMetrics { + + static final NoopExporterMetrics INSTANCE = new NoopExporterMetrics(); + + @Override + public Recording startRecordingExport(int itemCount) { + return new NoopRecording(); + } + + private static class NoopRecording extends Recording { + + @Override + protected void doFinish(@Nullable String errorType, Attributes requestAttributes) {} + } +} diff --git a/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/SemConvExporterMetrics.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/SemConvExporterMetrics.java new file mode 100644 index 00000000000..a8da86e5fd7 --- /dev/null +++ b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/metrics/SemConvExporterMetrics.java @@ -0,0 +1,179 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.common.internal.Signal; +import java.util.Collections; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class SemConvExporterMetrics implements ExporterMetrics { + + private static final Clock CLOCK = Clock.getDefault(); + + private final Supplier meterProviderSupplier; + private final Signal signal; + private final ComponentId componentId; + private final Attributes additionalAttributes; + + @Nullable private volatile LongUpDownCounter inflight = null; + @Nullable private volatile LongCounter exported = null; + @Nullable private volatile DoubleHistogram duration = null; + @Nullable private volatile Attributes allAttributes = null; + + public SemConvExporterMetrics( + Supplier meterProviderSupplier, + Signal signal, + ComponentId componentId, + Attributes additionalAttributes) { + this.meterProviderSupplier = meterProviderSupplier; + this.componentId = componentId; + this.signal = signal; + this.additionalAttributes = additionalAttributes; + } + + @Override + public ExporterMetrics.Recording startRecordingExport(int itemCount) { + return new Recording(itemCount); + } + + private Meter meter() { + MeterProvider meterProvider = meterProviderSupplier.get(); + if (meterProvider == null) { + meterProvider = MeterProvider.noop(); + } + return meterProvider.get("io.opentelemetry.exporters." + componentId.getTypeName()); + } + + private Attributes allAttributes() { + // attributes are initialized lazily to trigger lazy initialization of the componentId + Attributes allAttributes = this.allAttributes; + if (allAttributes == null) { + AttributesBuilder builder = Attributes.builder(); + builder.put(SemConvConstants.OTEL_COMPONENT_TYPE, componentId.getTypeName()); + builder.put(SemConvConstants.OTEL_COMPONENT_NAME, componentId.getComponentName()); + builder.putAll(additionalAttributes); + allAttributes = builder.build(); + this.allAttributes = allAttributes; + } + return allAttributes; + } + + private LongUpDownCounter inflight() { + LongUpDownCounter inflight = this.inflight; + if (inflight == null || isNoop(inflight)) { + inflight = + meter() + .upDownCounterBuilder(signal.getExporterInflightMetricName()) + .setUnit(signal.getExporterInflightMetricUnit()) + .setDescription(signal.getExporterInflightMetricDescription()) + .build(); + this.inflight = inflight; + } + return inflight; + } + + private LongCounter exported() { + LongCounter exported = this.exported; + if (exported == null || isNoop(exported)) { + exported = + meter() + .counterBuilder(signal.getExporterExportedMetricName()) + .setUnit(signal.getExporterExportedMetricUnit()) + .setDescription(signal.getExporterExportedMetricDescription()) + .build(); + this.exported = exported; + } + return exported; + } + + private DoubleHistogram duration() { + DoubleHistogram duration = this.duration; + if (duration == null || isNoop(duration)) { + duration = + meter() + .histogramBuilder(SemConvConstants.OTEL_SDK_EXPORTER_OPERATION_DURATION_NAME) + .setUnit(SemConvConstants.OTEL_SDK_EXPORTER_OPERATION_DURATION_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_EXPORTER_OPERATION_DURATION_DESCRIPTION) + .setExplicitBucketBoundariesAdvice(Collections.emptyList()) + .build(); + this.duration = duration; + } + return duration; + } + + private void incrementInflight(long count) { + inflight().add(count, allAttributes()); + } + + private void decrementInflight(long count) { + inflight().add(-count, allAttributes()); + } + + private void incrementExported(long count, @Nullable String errorType) { + exported().add(count, getAttributesWithPotentialError(errorType, Attributes.empty())); + } + + static boolean isNoop(Object instrument) { + // This is a poor way to identify a Noop implementation, but the API doesn't provide a better + // way. Perhaps we could add a common "Noop" interface to allow for an instanceof check? + return instrument.getClass().getSimpleName().startsWith("Noop"); + } + + private Attributes getAttributesWithPotentialError( + @Nullable String errorType, Attributes additionalAttributes) { + Attributes attributes = allAttributes(); + boolean errorPresent = errorType != null && !errorType.isEmpty(); + if (errorPresent || !additionalAttributes.isEmpty()) { + AttributesBuilder builder = attributes.toBuilder(); + if (errorPresent) { + builder.put(SemConvConstants.ERROR_TYPE, errorType); + } + attributes = builder.putAll(additionalAttributes).build(); + } + return attributes; + } + + private void recordDuration( + double seconds, @Nullable String errorType, Attributes requestAttributes) { + duration().record(seconds, getAttributesWithPotentialError(errorType, requestAttributes)); + } + + private class Recording extends ExporterMetrics.Recording { + + private final int itemCount; + + private final long startNanoTime; + + private Recording(int itemCount) { + this.itemCount = itemCount; + startNanoTime = CLOCK.nanoTime(); + incrementInflight(itemCount); + } + + @Override + protected void doFinish(@Nullable String errorType, Attributes requestAttributes) { + decrementInflight(itemCount); + incrementExported(itemCount, errorType); + long durationNanos = CLOCK.nanoTime() - startNanoTime; + recordDuration(durationNanos / 1_000_000_000.0, errorType, requestAttributes); + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/package-info.java b/exporters/common/src/main/java/io/opentelemetry/exporter/internal/package-info.java similarity index 100% rename from exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/package-info.java rename to exporters/common/src/main/java/io/opentelemetry/exporter/internal/package-info.java diff --git a/exporters/common/src/main/java9/io/opentelemetry/exporter/internal/marshal/VarHandleStringEncoder.java b/exporters/common/src/main/java9/io/opentelemetry/exporter/internal/marshal/VarHandleStringEncoder.java new file mode 100644 index 00000000000..c2f27aa3628 --- /dev/null +++ b/exporters/common/src/main/java9/io/opentelemetry/exporter/internal/marshal/VarHandleStringEncoder.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.lang.reflect.Field; +import java.nio.ByteOrder; +import javax.annotation.Nullable; + +/** + * StringEncoder implementation using VarHandle for high performance on Java 9+. + * + *

    This implementation provides optimized string operations by directly accessing String internal + * fields using VarHandle operations. It's only created if VarHandle is available and all required + * handles can be resolved. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class VarHandleStringEncoder extends AbstractStringEncoder { + + private final VarHandle valueHandle; + private final VarHandle coderHandle; + private static final VarHandle LONG_ARRAY_HANDLE = + MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN); + + private VarHandleStringEncoder(VarHandle valueHandle, VarHandle coderHandle) { + this.valueHandle = valueHandle; + this.coderHandle = coderHandle; + } + + @Nullable + public static VarHandleStringEncoder createIfAvailable() { + VarHandle valueHandle1 = getStringFieldHandle("value", byte[].class); + VarHandle coderHandle1 = getStringFieldHandle("coder", byte.class); + + if (valueHandle1 == null || coderHandle1 == null) { + return null; + } + + return new VarHandleStringEncoder(valueHandle1, coderHandle1); + } + + @Override + protected byte[] getStringBytes(String string) { + return (byte[]) valueHandle.get(string); + } + + @Override + protected boolean isLatin1(String string) { + return ((byte) coderHandle.get(string)) == 0; + } + + @Override + protected long getLong(byte[] bytes, int offset) { + return (long) LONG_ARRAY_HANDLE.get(bytes, offset); + } + + @Nullable + private static VarHandle getStringFieldHandle(String fieldName, Class expectedType) { + try { + Field field = String.class.getDeclaredField(fieldName); + if (!expectedType.isAssignableFrom(field.getType())) { + return null; + } + + MethodHandles.Lookup lookup = + MethodHandles.privateLookupIn(String.class, MethodHandles.lookup()); + return lookup.findVarHandle(String.class, fieldName, expectedType); + } catch (Exception exception) { + return null; + } + } +} diff --git a/exporters/common/src/main/resources/META-INF/native-image/io.opentelemetry.opentelemetry-exporter-common/reflect-config.json b/exporters/common/src/main/resources/META-INF/native-image/io.opentelemetry.opentelemetry-exporter-common/reflect-config.json new file mode 100644 index 00000000000..1d93899460b --- /dev/null +++ b/exporters/common/src/main/resources/META-INF/native-image/io.opentelemetry.opentelemetry-exporter-common/reflect-config.json @@ -0,0 +1,14 @@ +[ + { + "name":"io.opentelemetry.sdk.common.export.AutoValue_RetryPolicy", + "queryAllDeclaredMethods":true + }, + { + "name":"io.opentelemetry.sdk.common.export.RetryPolicy", + "queryAllDeclaredMethods":true + }, + { + "name":"io.opentelemetry.exporter.internal.compression.Compressor", + "queryAllDeclaredMethods":true + } +] diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/EndpointUtilTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/EndpointUtilTest.java new file mode 100644 index 00000000000..8a28ff244d5 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/EndpointUtilTest.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.net.URI; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class EndpointUtilTest { + + @ParameterizedTest + @MethodSource("validEndpoints") + void validateEndpoint_valid(String endpoint) { + assertThat(EndpointUtil.validateEndpoint(endpoint)).isEqualTo(URI.create(endpoint)); + } + + private static Stream validEndpoints() { + return Stream.of( + Arguments.argumentSet("http", "http://localhost:4318"), + Arguments.argumentSet("https", "https://localhost:4317"), + Arguments.argumentSet("path", "http://localhost:4318/v1/traces"), + Arguments.argumentSet("userinfo", "http://foo:bar@localhost:4317/path"), + // URI.getHost() is null for these (JDK-8188305); they are valid DNS names. + Arguments.argumentSet( + "dns label starting with digit", "http://otlp.1234-k8s-namespace:4318"), + Arguments.argumentSet( + "dns label starting with digit, path", + "http://otlp-collector.14014-mosaik:4318/v1/metrics"), + Arguments.argumentSet( + "dns label starting with digit, userinfo", "http://foo:bar@otlp.1234-ns:4317/path")); + } + + @ParameterizedTest + @MethodSource("invalidEndpoints") + void validateEndpoint_invalid(String endpoint) { + assertThatThrownBy(() -> EndpointUtil.validateEndpoint(endpoint)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("must start with http:// or https://"); + } + + private static Stream invalidEndpoints() { + return Stream.of( + Arguments.argumentSet("opaque, no host", "http:localhost:4317"), + Arguments.argumentSet("single slash, no host", "https:/foo"), + Arguments.argumentSet("empty host with port", "http://:4318"), + Arguments.argumentSet("no scheme", "localhost"), + Arguments.argumentSet("wrong scheme", "gopher://localhost")); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/InstrumentationUtilTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/InstrumentationUtilTest.java new file mode 100644 index 00000000000..5a6a2cfd5a2 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/InstrumentationUtilTest.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.opentelemetry.context.Context; +import org.junit.jupiter.api.Test; + +class InstrumentationUtilTest { + + // testing deprecated implementation until it's removed + @Test + @SuppressWarnings("deprecation") + void verifySuppressInstrumentation() { + // Should be false by default. + assertFalse(InstrumentationUtil.shouldSuppressInstrumentation(Context.current())); + + // Should be true inside the Runnable passed to InstrumentationUtil.suppressInstrumentation. + InstrumentationUtil.suppressInstrumentation( + () -> assertTrue(InstrumentationUtil.shouldSuppressInstrumentation(Context.current()))); + + // Should be false after the runnable finishes. + assertFalse(InstrumentationUtil.shouldSuppressInstrumentation(Context.current())); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/RetryUtilTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/RetryUtilTest.java new file mode 100644 index 00000000000..1a2311d51c2 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/RetryUtilTest.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.argumentSet; + +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import java.util.OptionalLong; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class RetryUtilTest { + + private static final Instant NOW = Instant.parse("2026-07-17T00:00:00Z"); + + @ParameterizedTest + @MethodSource("retryAfterArgs") + void retryAfterNanos(String retryAfter, Instant now, Long expectedNanos) { + OptionalLong delayNanos = RetryUtil.retryAfterNanos(retryAfter, now); + + if (expectedNanos == null) { + assertThat(delayNanos).isEmpty(); + } else { + assertThat(delayNanos).hasValue(expectedNanos); + } + } + + private static Stream retryAfterArgs() { + return Stream.of( + argumentSet("null", null, Instant.EPOCH, null), + argumentSet("seconds", "30", Instant.EPOCH, TimeUnit.SECONDS.toNanos(30)), + argumentSet("negative seconds", "-1", Instant.EPOCH, null), + argumentSet("malformed", "bad-value", Instant.EPOCH, null), + argumentSet( + "future date", + ZonedDateTime.ofInstant(NOW.plusSeconds(45), ZoneOffset.UTC) + .format(DateTimeFormatter.RFC_1123_DATE_TIME), + NOW, + TimeUnit.SECONDS.toNanos(45)), + argumentSet( + "past date clamps to zero", + ZonedDateTime.ofInstant(NOW.minusSeconds(1), ZoneOffset.UTC) + .format(DateTimeFormatter.RFC_1123_DATE_TIME), + NOW, + 0L)); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java new file mode 100644 index 00000000000..1ac3a304b36 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsConfigHelperTest.java @@ -0,0 +1,112 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.security.cert.CertificateEncodingException; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +@SuppressLogger(TlsConfigHelper.class) +class TlsConfigHelperTest { + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + private TlsConfigHelper helper = new TlsConfigHelper(); + + @Test + void createTrustManager() throws CertificateEncodingException { + helper.setTrustManagerFromCerts(serverTls.certificate().getEncoded()); + + assertThat(helper.getTrustManager()).isNotNull(); + } + + @Test + void createTrustManager_AlreadyExists_Throws() throws Exception { + helper.setTrustManagerFromCerts(serverTls.certificate().getEncoded()); + assertThatThrownBy(() -> helper.setTrustManagerFromCerts(serverTls.certificate().getEncoded())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("trustManager has been previously configured"); + + helper = new TlsConfigHelper(); + helper.setSslContext( + SSLContext.getInstance("TLS"), TlsUtil.trustManager(serverTls.certificate().getEncoded())); + assertThatThrownBy(() -> helper.setTrustManagerFromCerts(serverTls.certificate().getEncoded())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sslContext has been previously configured"); + } + + @Test + void createKeyManager() throws CertificateEncodingException { + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded()); + + assertThat(helper.getKeyManager()).isNotNull(); + } + + @Test + void createKeyManager_AlreadyExists_Throws() throws Exception { + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded()); + assertThatThrownBy(() -> + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("keyManager has been previously configured"); + + helper = new TlsConfigHelper(); + helper.setSslContext( + SSLContext.getInstance("TLS"), TlsUtil.trustManager(serverTls.certificate().getEncoded())); + assertThatThrownBy(() -> + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sslContext has been previously configured"); + } + + @Test + void setSslContext() throws Exception { + SSLContext sslContext = SSLContext.getInstance("TLS"); + X509TrustManager trustManager = TlsUtil.trustManager(serverTls.certificate().getEncoded()); + helper.setSslContext(sslContext, trustManager); + + assertThat(helper.getSslContext()).isEqualTo(sslContext); + assertThat(helper.getTrustManager()).isEqualTo(trustManager); + } + + @Test + void setSslContext_AlreadyExists_Throws() throws Exception { + SSLContext sslContext = SSLContext.getInstance("TLS"); + X509TrustManager trustManager = TlsUtil.trustManager(serverTls.certificate().getEncoded()); + + helper.setSslContext(sslContext, trustManager); + assertThatThrownBy(() -> helper.setSslContext(sslContext, trustManager)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sslContext or trustManager has been previously configured"); + + helper = new TlsConfigHelper(); + helper.setTrustManagerFromCerts(serverTls.certificate().getEncoded()); + assertThatThrownBy(() -> helper.setSslContext(sslContext, trustManager)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("sslContext or trustManager has been previously configured"); + + helper = new TlsConfigHelper(); + helper.setKeyManagerFromCerts( + serverTls.privateKey().getEncoded(), serverTls.certificate().getEncoded()); + assertThatThrownBy(() -> helper.setSslContext(sslContext, trustManager)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("keyManager has been previously configured"); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java new file mode 100644 index 00000000000..7733c6ba8f5 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/TlsUtilTest.java @@ -0,0 +1,153 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.linecorp.armeria.internal.common.util.SelfSignedCertificate; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.security.KeyFactory; +import java.security.KeyStore; +import java.security.cert.CertificateException; +import java.security.spec.PKCS8EncodedKeySpec; +import java.time.Instant; +import java.util.Collections; +import java.util.Date; +import java.util.stream.Stream; +import javax.net.ssl.ManagerFactoryParameters; +import javax.net.ssl.SSLException; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.TrustManagerFactorySpi; +import javax.net.ssl.X509TrustManager; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class TlsUtilTest { + + @TempDir private Path tempDir; + + private static final String EXPLANATORY_TEXT = + "Subject: CN=Foo\n" + + "Issuer: CN=Foo\n" + + "Validity: from 7/9/2012 3:10:38 AM UTC to 7/9/2013 3:10:37 AM UTC\n"; + + private SelfSignedCertificate rsaCertificate; + private SelfSignedCertificate ecCertificate; + + @BeforeEach + void setup() throws CertificateException { + rsaCertificate = + new SelfSignedCertificate(Date.from(Instant.now()), Date.from(Instant.now()), "RSA", 2048); + ecCertificate = + new SelfSignedCertificate(Date.from(Instant.now()), Date.from(Instant.now()), "EC", 256); + } + + @Test + void keyManager_Rsa() { + assertThatCode(() -> + TlsUtil.keyManager( + rsaCertificate.key().getEncoded(), rsaCertificate.cert().getEncoded())) + .doesNotThrowAnyException(); + } + + @Test + void keyManager_Ec() { + assertThatCode(() -> + TlsUtil.keyManager(ecCertificate.key().getEncoded(), ecCertificate.cert().getEncoded())) + .doesNotThrowAnyException(); + } + + @Test + void generatePrivateKey_Invalid() { + PKCS8EncodedKeySpec keySpec = + new PKCS8EncodedKeySpec(TlsUtil.decodePem(rsaCertificate.key().getEncoded())); + assertThatCode(() -> + TlsUtil.generatePrivateKey( + keySpec, Collections.singletonList(KeyFactory.getInstance("EC")))) + .isInstanceOf(SSLException.class) + .hasMessage("Unable to generate key from supported algorithms: [EC]"); + } + + @Test + void defaultTrustManager() { + assertThatCode(TlsUtil::defaultTrustManager).doesNotThrowAnyException(); + } + + @Test + void defaultTrustManager_returnsX509TrustManager() throws Exception { + assertThat(TlsUtil.defaultTrustManager()).isInstanceOf(X509TrustManager.class); + } + + private static TrustManagerFactory trustManagerFactory(TrustManager[] trustManagers) { + return new TrustManagerFactory( + new TrustManagerFactorySpi() { + @Override + protected void engineInit(KeyStore keyStore) {} + + @Override + protected void engineInit(ManagerFactoryParameters spec) {} + + @Override + protected TrustManager[] engineGetTrustManagers() { + return trustManagers; + } + }, + null, + "test") {}; + } + + @Test + void defaultTrustManager_NoX509TrustManagerFound() { + assertThatCode(() -> TlsUtil.defaultTrustManager(trustManagerFactory(new TrustManager[0]))) + .isInstanceOf(SSLException.class) + .hasMessage("No X509TrustManager found"); + } + + /** + * Append explanatory text + * prefix and verify {@link TlsUtil#keyManager(byte[], byte[])} succeeds. + */ + @ParameterizedTest + @MethodSource("keyManagerArgs") + void keyManager_CertWithExplanatoryText(SelfSignedCertificate selfSignedCertificate) + throws IOException { + Path certificate = tempDir.resolve("certificate"); + Files.write(certificate, EXPLANATORY_TEXT.getBytes(StandardCharsets.UTF_8)); + Files.write( + certificate, + com.google.common.io.Files.toByteArray(selfSignedCertificate.certificate()), + StandardOpenOption.APPEND); + Files.write(certificate, "\n".getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); + + assertThatCode(() -> + TlsUtil.keyManager( + com.google.common.io.Files.toByteArray(selfSignedCertificate.privateKey()), + com.google.common.io.Files.toByteArray(new File(certificate.toString())))) + .doesNotThrowAnyException(); + } + + private static Stream keyManagerArgs() throws CertificateException { + Instant now = Instant.now(); + return Stream.of( + Arguments.argumentSet( + "RSA certificate", + new SelfSignedCertificate(Date.from(now), Date.from(now), "RSA", 2048)), + Arguments.argumentSet( + "EC certificate", + new SelfSignedCertificate(Date.from(now), Date.from(now), "EC", 256))); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStreamTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStreamTest.java new file mode 100644 index 00000000000..f70277b783d --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/grpc/MarshalerInputStreamTest.java @@ -0,0 +1,210 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.grpc; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Random; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class MarshalerInputStreamTest { + + private static final byte[] CONTENT = "grpc-test".getBytes(StandardCharsets.UTF_8); + + @Test + void available_withMessage() { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + assertThat(stream.available()).isEqualTo(CONTENT.length); + } + + @Test + void available_withPartial() { + MarshalerInputStream stream = streamWithPartial(CONTENT); + assertThat(stream.available()).isEqualTo(CONTENT.length); + } + + @Test + void available_afterFullyDrained() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + stream.drainTo(new ByteArrayOutputStream()); + assertThat(stream.available()).isEqualTo(0); + } + + @Test + void drainTo_fromMessage() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + int written = stream.drainTo(baos); + + assertThat(written).isEqualTo(CONTENT.length); + assertThat(baos.toByteArray()).isEqualTo(CONTENT); + } + + @ParameterizedTest + @ValueSource(ints = {0, 1, 8192, 8193, 20000}) + void drainTo_fromPartial(int size) throws IOException { + byte[] content = new byte[size]; + new Random(0).nextBytes(content); + MarshalerInputStream stream = streamWithPartial(content); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int written = stream.drainTo(baos); + + assertThat(written).isEqualTo(content.length); + assertThat(baos.toByteArray()).isEqualTo(content); + assertThat(stream.available()).isZero(); + assertThat(stream.read()).isEqualTo(-1); + } + + @Test + void drainTo_afterPartialRead() throws IOException { + MarshalerInputStream stream = streamWithPartial(CONTENT); + assertThat(stream.read()).isEqualTo(CONTENT[0] & 0xFF); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int written = stream.drainTo(baos); + + assertThat(written).isEqualTo(CONTENT.length - 1); + assertThat(baos.toByteArray()).isEqualTo(Arrays.copyOfRange(CONTENT, 1, CONTENT.length)); + } + + @Test + void drainTo_afterAlreadyDrained() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + stream.drainTo(new ByteArrayOutputStream()); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + int written = stream.drainTo(baos); + + assertThat(written).isEqualTo(0); + assertThat(baos.size()).isEqualTo(0); + } + + @Test + void readSingleByte_fromMessage() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + + int firstByte = stream.read(); + assertThat(firstByte).isEqualTo(CONTENT[0] & 0xFF); + + // Read remaining bytes + for (int i = 1; i < CONTENT.length; i++) { + assertThat(stream.read()).isEqualTo(CONTENT[i] & 0xFF); + } + assertThat(stream.read()).isEqualTo(-1); + } + + @Test + void readSingleByte_fromPartial() throws IOException { + MarshalerInputStream stream = streamWithPartial(CONTENT); + + int firstByte = stream.read(); + assertThat(firstByte).isEqualTo(CONTENT[0] & 0xFF); + } + + @Test + void readSingleByte_afterFullyDrained() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + stream.drainTo(new ByteArrayOutputStream()); + + assertThat(stream.read()).isEqualTo(-1); + } + + @Test + void readBulk_fromMessage() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + + byte[] buf = new byte[CONTENT.length]; + int bytesRead = stream.read(buf, 0, buf.length); + + assertThat(bytesRead).isEqualTo(CONTENT.length); + assertThat(buf).isEqualTo(CONTENT); + + // Subsequent read must return -1 + assertThat(stream.read(buf, 0, buf.length)).isEqualTo(-1); + } + + @Test + void readBulk_zeroLengthMessage() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(new byte[0])); + + byte[] buf = new byte[10]; + int bytesRead = stream.read(buf, 0, buf.length); + + assertThat(bytesRead).isEqualTo(-1); + } + + @Test + void readBulk_fromPartial() throws IOException { + MarshalerInputStream stream = streamWithPartial(CONTENT); + + byte[] buf = new byte[CONTENT.length]; + int bytesRead = stream.read(buf, 0, buf.length); + + assertThat(bytesRead).isEqualTo(CONTENT.length); + assertThat(buf).isEqualTo(CONTENT); + } + + @Test + void readBulk_afterFullyDrained() throws IOException { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(CONTENT)); + stream.drainTo(new ByteArrayOutputStream()); + + byte[] buf = new byte[CONTENT.length]; + int bytesRead = stream.read(buf, 0, buf.length); + + assertThat(bytesRead).isEqualTo(-1); + } + + private static MessageWriter messageWriter(byte[] bytes) { + return new TestMessageWriter(bytes); + } + + private static MarshalerInputStream streamWithPartial(byte[] partialBytes) { + try { + MarshalerInputStream stream = new MarshalerInputStream(messageWriter(new byte[0])); + Field messageField = MarshalerInputStream.class.getDeclaredField("message"); + messageField.setAccessible(true); + messageField.set(stream, null); + + Field partialField = MarshalerInputStream.class.getDeclaredField("partial"); + partialField.setAccessible(true); + partialField.set(stream, new ByteArrayInputStream(partialBytes)); + return stream; + } catch (ReflectiveOperationException e) { + throw new LinkageError("Failed to set partial field via reflection", e); + } + } + + private static final class TestMessageWriter implements MessageWriter { + private final byte[] data; + + TestMessageWriter(byte[] data) { + this.data = data; + } + + @Override + public int getContentLength() { + return data.length; + } + + @Override + public void writeMessage(OutputStream out) throws IOException { + out.write(data); + } + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/JsonBufferedEncoderTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/JsonBufferedEncoderTest.java new file mode 100644 index 00000000000..b4f9df3f16e --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/JsonBufferedEncoderTest.java @@ -0,0 +1,304 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class JsonBufferedEncoderTest { + + @FunctionalInterface + private interface Body { + void accept(JsonBufferedEncoder encoder) throws IOException; + } + + @ParameterizedTest + @MethodSource("cases") + void writesExpectedJson(Body body, String expected) throws Exception { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JsonBufferedEncoder encoder = new JsonBufferedEncoder(bos); + body.accept(encoder); + encoder.close(); + assertThat(new String(bos.toByteArray(), StandardCharsets.UTF_8)).isEqualTo(expected); + } + + // Writes a string whose UTF-8 encoding exceeds the encoder's 4096-byte internal buffer, forcing + // at least one intermediate flush to the underlying stream before close(). + @Test + void flushesWhenBufferFills() throws Exception { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < 5000; i++) { + sb.append('a'); + } + String longValue = sb.toString(); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JsonBufferedEncoder encoder = new JsonBufferedEncoder(bos); + encoder.writeString(longValue); + // Before close, the underlying stream must have received bytes from at least one mid-write + // flush; otherwise everything would still be sitting in the 4096-byte buffer. + assertThat(bos.size()).isGreaterThan(0); + encoder.close(); + assertThat(new String(bos.toByteArray(), StandardCharsets.UTF_8)) + .isEqualTo("\"" + longValue + "\""); + } + + // Nests more objects than the initial hasMembers array capacity (16), forcing the array to grow. + @Test + void growsWhenNestingExceedsInitialCapacity() throws Exception { + int depth = 20; + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JsonBufferedEncoder encoder = new JsonBufferedEncoder(bos); + for (int i = 0; i < depth; i++) { + encoder.writeStartObject(); + encoder.writeFieldName("k" + i); + } + encoder.writeString("v"); + for (int i = 0; i < depth; i++) { + encoder.writeEndObject(); + } + encoder.close(); + + StringBuilder expected = new StringBuilder(); + for (int i = 0; i < depth; i++) { + expected.append("{\"k").append(i).append("\":"); + } + expected.append("\"v\""); + for (int i = 0; i < depth; i++) { + expected.append('}'); + } + assertThat(new String(bos.toByteArray(), StandardCharsets.UTF_8)) + .isEqualTo(expected.toString()); + } + + // Unpaired surrogates cannot be encoded as UTF-8; the encoder emits '?' in their place so the + // output remains valid UTF-8. + @Test + void invalidSurrogatesEmitReplacement() throws Exception { + // Lone low surrogate (never preceded by a high surrogate). + assertString(String.valueOf((char) 0xDC00), "\"?\""); + // High surrogate at end of string (no following char). + assertString(String.valueOf((char) 0xD800), "\"?\""); + // High surrogate followed by a non-low-surrogate BMP character (U+00E9 e-acute); the high + // surrogate is replaced and the following char is emitted normally. + assertString("" + (char) 0xD800 + (char) 0x00E9, "\"?" + (char) 0xE9 + "\""); + } + + @Test + void nestingBeyondMaxDepthThrows() throws Exception { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JsonBufferedEncoder encoder = new JsonBufferedEncoder(bos); + // MAX_NESTING_DEPTH successive writeStartObject calls are allowed; the next one must throw. + for (int i = 0; i < JsonBufferedEncoder.MAX_NESTING_DEPTH; i++) { + encoder.writeStartObject(); + encoder.writeFieldName("k"); + } + assertThatThrownBy(encoder::writeStartObject) + .isInstanceOf(IOException.class) + .hasMessageContaining("nesting depth"); + } + + // close() drains the buffer to the underlying stream; if that write throws, the exception is + // wrapped so it can propagate out of a try-with-resources without self-suppression issues. + @Test + void closeWrapsIoException() throws Exception { + IOException boom = new IOException("boom"); + OutputStream failing = + new OutputStream() { + @Override + public void write(int b) throws IOException { + throw boom; + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + throw boom; + } + }; + JsonBufferedEncoder encoder = new JsonBufferedEncoder(failing); + // Write a single byte so there is buffered output for close() to attempt to flush. + encoder.writeString("x"); + assertThatThrownBy(encoder::close).isInstanceOf(IOException.class).hasCause(boom); + } + + private static void assertString(String input, String expected) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + JsonBufferedEncoder encoder = new JsonBufferedEncoder(bos); + encoder.writeString(input); + encoder.close(); + assertThat(new String(bos.toByteArray(), StandardCharsets.UTF_8)).isEqualTo(expected); + } + + static Stream cases() { + // Built with concatenation to keep the source ASCII: quote, backslash, slash, control-char + // shortcuts, NUL, U+001F, 'a', and the 2-/3-/4-byte UTF-8 chars U+00E9 (e-acute), U+4E16 (CJK), + // and U+1F600 (grinning face). Forward slash is not escaped, control characters use lowercase + // \\u00xx, and multi-byte UTF-8 passes through verbatim. + String escapeInput = + "\"" + + '\\' + + '/' + + '\b' + + '\f' + + '\n' + + '\r' + + '\t' + + (char) 0x00 + + (char) 0x1f + + 'a' + + (char) 0xe9 + + (char) 0x4e16 + + new String(Character.toChars(0x1f600)); + String escapeExpected = + "\"\\\"\\\\/\\b\\f\\n\\r\\t\\u0000\\u001fa" + + (char) 0xe9 + + (char) 0x4e16 + + new String(Character.toChars(0x1f600)) + + "\""; + + // 'a', TAB, then U+00E9 (e-acute) as its two UTF-8 bytes 0xC3 0xA9. + byte[] utf8 = {'a', '\t', (byte) 0xc3, (byte) 0xa9}; + String utf8Expected = "\"a\\t" + (char) 0xe9 + "\""; + + return Stream.of( + Arguments.argumentSet( + "empty object", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeEndObject(); + }, + "{}"), + Arguments.argumentSet( + "object inserts separators between fields", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeStringField("a", "b"); + encoder.writeNumberField("n", 1); + encoder.writeBooleanField("t", true); + encoder.writeBooleanField("f", false); + encoder.writeEndObject(); + }, + "{\"a\":\"b\",\"n\":1,\"t\":true,\"f\":false}"), + Arguments.argumentSet( + "nested objects and arrays", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeObjectFieldStart("o"); + encoder.writeStringField("k", "v"); + encoder.writeEndObject(); + encoder.writeArrayFieldStart("arr"); + encoder.writeString("x"); + encoder.writeNumber(2.5); + encoder.writeEndArray(); + encoder.writeEndObject(); + }, + "{\"o\":{\"k\":\"v\"},\"arr\":[\"x\",2.5]}"), + Arguments.argumentSet( + "string escaping", (Body) encoder -> encoder.writeString(escapeInput), escapeExpected), + Arguments.argumentSet( + "writeUtf8String escapes ascii and passes multi-byte through", + (Body) encoder -> encoder.writeUtf8String(utf8), + utf8Expected), + Arguments.argumentSet( + "integer boundaries", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeNumberField("min", Integer.MIN_VALUE); + encoder.writeNumberField("max", Integer.MAX_VALUE); + encoder.writeEndObject(); + }, + "{\"min\":-2147483648,\"max\":2147483647}"), + Arguments.argumentSet( + "exponent and signed-zero doubles", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeArrayFieldStart("d"); + encoder.writeNumber(1.0e7); + encoder.writeNumber(1.0e-4); + encoder.writeNumber(-0.0); + encoder.writeNumber(0.0); + encoder.writeEndArray(); + encoder.writeEndObject(); + }, + "{\"d\":[1.0E7,1.0E-4,-0.0,0.0]}"), + Arguments.argumentSet( + "empty base64", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeBinaryField("b", new byte[0]); + encoder.writeEndObject(); + }, + "{\"b\":\"\"}"), + Arguments.argumentSet( + "objects in array", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeArrayFieldStart("a"); + encoder.writeStartObject(); + encoder.writeNumberField("x", 1); + encoder.writeEndObject(); + encoder.writeStartObject(); + encoder.writeNumberField("y", 2); + encoder.writeEndObject(); + encoder.writeEndArray(); + encoder.writeEndObject(); + }, + "{\"a\":[{\"x\":1},{\"y\":2}]}"), + Arguments.argumentSet( + "non-finite doubles are quoted", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeArrayFieldStart("d"); + encoder.writeNumber(Double.NaN); + encoder.writeNumber(Double.POSITIVE_INFINITY); + encoder.writeNumber(Double.NEGATIVE_INFINITY); + encoder.writeNumber(1.5); + encoder.writeEndArray(); + encoder.writeEndObject(); + }, + "{\"d\":[\"NaN\",\"Infinity\",\"-Infinity\",1.5]}"), + Arguments.argumentSet( + "binary field is base64", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeBinaryField("b", new byte[] {1, 2, 3}); + encoder.writeEndObject(); + }, + "{\"b\":\"AQID\"}"), + // Mirrors MarshalerUtil#preserializeJsonFields: pre-serialized fields written raw into an + // otherwise empty object, without disturbing separator state. + Arguments.argumentSet( + "writeRaw embeds verbatim", + (Body) + encoder -> { + encoder.writeStartObject(); + encoder.writeObjectFieldStart("resource"); + encoder.writeRaw("\"key\":\"val\""); + encoder.writeEndObject(); + encoder.writeEndObject(); + }, + "{\"resource\":{\"key\":\"val\"}}")); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java new file mode 100644 index 00000000000..d635fe7da8a --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/MarshalerTest.java @@ -0,0 +1,177 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class MarshalerTest { + + @Test + void writeTo_NoSelfSuppressionError() throws IOException { + Marshaler marshaler = + new Marshaler() { + @Override + public int getBinarySerializedSize() { + return 0; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + for (int i = 0; i < (50 * 1024 + 100) / 8; i++) { + output.writeFixed64Value(i); + } + } + }; + OutputStream os = mock(OutputStream.class); + + IOException error = new IOException("error!"); + doThrow(error).when(os).write(any(), anyInt(), anyInt()); + doThrow(error).when(os).write(any()); + doThrow(error).when(os).write(anyInt()); + doThrow(error).when(os).flush(); + + // If an exception is thrown writing bytes, and that same exception is thrown in the #close + // method cleaning up the AutoCloseable resource, an IllegalArgumentException will be thrown + // indicating illegal self suppression. Ensure an IOException is thrown instead. + assertThatThrownBy(() -> marshaler.writeBinaryTo(os)).isInstanceOf(IOException.class); + assertThatThrownBy(() -> marshaler.writeJsonTo(os)).isInstanceOf(IOException.class); + } + + /** + * This test ensures that instances where serializer produces runtime exceptions are properly + * converted back to checked {@link IOException}. + * + *

    At various points in {@link Serializer}, we use {@code .forEach}-style methods which accept + * {@link java.util.function.Consumer} and {@link java.util.function.BiConsumer}. These consumers + * that any checked exceptions are caught and rethrown as runtime exceptions. Its essential that + * these runtime exceptions are re-converted back to checked {@link IOException} because calling + * code's error handling is built on top of {@link IOException}. Failure to convert to {@link + * IOException} leads to issues like this: #6946. + */ + @ParameterizedTest + @MethodSource("writeToArgs") + void writeTo_NoRuntimeExceptions(Writer writer) throws IOException { + Marshaler marshaler = + new Marshaler() { + @Override + public int getBinarySerializedSize() { + return 0; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + writer.writeTo(output); + } + }; + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + assertThatThrownBy(() -> marshaler.writeBinaryTo(baos)).isInstanceOf(IOException.class); + } + } + + private static Stream writeToArgs() { + ProtoFieldInfo fieldInfo = ProtoFieldInfo.create(0, 0, "name"); + MarshalerContext context = new MarshalerContext(); + ThrowingMarshaler throwingMarshaler = new ThrowingMarshaler<>(new IOException("error")); + ThrowingMarshaler2 throwingMarshaler2 = + new ThrowingMarshaler2<>(new IOException("error")); + ThrowingMarshaler2, Object> throwingMarshaler2Attributes = + new ThrowingMarshaler2<>(new IOException("error")); + + return Stream.of( + Arguments.argumentSet( + "repeated message collection", + asWriter(output -> + output.serializeRepeatedMessageWithContext( + fieldInfo, + Collections.singleton("value"), + throwingMarshaler, + context, + MarshalerContext.key()))), + Arguments.argumentSet( + "repeated message map", + asWriter(output -> + output.serializeRepeatedMessageWithContext( + fieldInfo, + Collections.singletonMap("key", "value"), + throwingMarshaler2, + context, + MarshalerContext.key()))), + Arguments.argumentSet( + "repeated message attributes", + asWriter(output -> + output.serializeRepeatedMessageWithContext( + fieldInfo, + Attributes.builder().put("key", "value").build(), + throwingMarshaler2Attributes, + context)))); + } + + private static Writer asWriter(Writer writer) { + return writer; + } + + @FunctionalInterface + private interface Writer { + void writeTo(Serializer output) throws IOException; + } + + private static class ThrowingMarshaler implements StatelessMarshaler { + + private final IOException exception; + + private ThrowingMarshaler(IOException exception) { + this.exception = exception; + } + + @Override + public int getBinarySerializedSize(T value, MarshalerContext context) { + return 0; + } + + @Override + public void writeTo(Serializer output, T value, MarshalerContext context) throws IOException { + throw exception; + } + } + + private static class ThrowingMarshaler2 implements StatelessMarshaler2 { + + private final IOException exception; + + private ThrowingMarshaler2(IOException exception) { + this.exception = exception; + } + + @Override + public int getBinarySerializedSize(K key, V value, MarshalerContext context) { + return 0; + } + + @Override + public void writeTo(Serializer output, K key, V value, MarshalerContext context) + throws IOException { + throw exception; + } + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/StringEncoderFuzzTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/StringEncoderFuzzTest.java new file mode 100644 index 00000000000..3da35b6b3b8 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/StringEncoderFuzzTest.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import static io.opentelemetry.exporter.internal.marshal.StringEncoderTest.testUtf8; +import static org.assertj.core.api.Assertions.assertThat; + +import edu.berkeley.cs.jqf.fuzz.Fuzz; +import edu.berkeley.cs.jqf.fuzz.JQF; +import edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing; +import edu.berkeley.cs.jqf.fuzz.random.NoGuidance; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnJre; +import org.junit.jupiter.api.condition.JRE; +import org.junit.runner.Result; +import org.junit.runner.RunWith; + +@SuppressWarnings("SystemOut") +class StringEncoderFuzzTest { + + private static final StringEncoder fallbackStringEncoder = + StringEncoderHolder.createFallbackEncoder(); + private static final StringEncoder unsafeStringEncoder = + StringEncoderHolder.createUnsafeEncoder(); + private static final StringEncoder varHandleStringEncoder = + StringEncoderHolder.createVarHandleEncoder(); + + @RunWith(JQF.class) + public static class EncodeUf8 { + + @Fuzz + public void encodeRandomString_Fallback(String value) { + assertThat(fallbackStringEncoder).isNotNull(); + int utf8Size = value.getBytes(StandardCharsets.UTF_8).length; + assertThat(fallbackStringEncoder.getUtf8Size(value)).isEqualTo(utf8Size); + assertThat(testUtf8(value, utf8Size, fallbackStringEncoder)).isEqualTo(value); + } + + @Fuzz + public void encodeRandomString_Unsafe(String value) { + assertThat(unsafeStringEncoder).isNotNull(); + int utf8Size = value.getBytes(StandardCharsets.UTF_8).length; + assertThat(unsafeStringEncoder.getUtf8Size(value)).isEqualTo(utf8Size); + assertThat(testUtf8(value, utf8Size, unsafeStringEncoder)).isEqualTo(value); + } + + @Fuzz + public void encodeRandomString_VarHandle(String value) { + assertThat(varHandleStringEncoder).isNotNull(); + int utf8Size = value.getBytes(StandardCharsets.UTF_8).length; + assertThat(varHandleStringEncoder.getUtf8Size(value)).isEqualTo(utf8Size); + assertThat(testUtf8(value, utf8Size, varHandleStringEncoder)).isEqualTo(value); + } + } + + @Test + void encodeUf8WithFuzzing_Fallback() { + Result result = + GuidedFuzzing.run( + EncodeUf8.class, + "encodeRandomString_Fallback", + new NoGuidance(10000, System.out), + System.out); + assertThat(result.wasSuccessful()).isTrue(); + } + + @Test + @DisabledOnJre(JRE.JAVA_8) + void encodeUf8WithFuzzing_Unsafe() { + Result result = + GuidedFuzzing.run( + EncodeUf8.class, + "encodeRandomString_Unsafe", + new NoGuidance(10000, System.out), + System.out); + assertThat(result.wasSuccessful()).isTrue(); + } + + @Test + @DisabledOnJre(JRE.JAVA_8) + void encodeUf8WithFuzzing_VarHandle() { + Result result = + GuidedFuzzing.run( + EncodeUf8.class, + "encodeRandomString_VarHandle", + new NoGuidance(10000, System.out), + System.out); + assertThat(result.wasSuccessful()).isTrue(); + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/StringEncoderTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/StringEncoderTest.java new file mode 100644 index 00000000000..a0b117292cf --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/marshal/StringEncoderTest.java @@ -0,0 +1,127 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.Random; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnJre; +import org.junit.jupiter.api.condition.JRE; +import org.junitpioneer.jupiter.SetSystemProperty; + +class StringEncoderTest { + + private static final StringEncoder fallbackStringEncoder = + StringEncoderHolder.createFallbackEncoder(); + private static final StringEncoder unsafeStringEncoder = + StringEncoderHolder.createUnsafeEncoder(); + private static final StringEncoder varHandleStringEncoder = + StringEncoderHolder.createVarHandleEncoder(); + + @Test + void testUtf8Encoding_Fallback() { + testUtf8Encoding(fallbackStringEncoder); + } + + @Test + void testUtf8SizeLatin1_Fallback() { + testUtf8SizeLatin1(fallbackStringEncoder); + } + + @Test + @DisabledOnJre(JRE.JAVA_8) + void testUtf8Encoding_Unsafe() { + testUtf8Encoding(unsafeStringEncoder); + } + + @Test + @DisabledOnJre(JRE.JAVA_8) + void testUtf8SizeLatin1_Unsafe() { + testUtf8SizeLatin1(unsafeStringEncoder); + } + + @Test + @DisabledOnJre(JRE.JAVA_8) + void testUtf8Encoding_VarHandle() { + testUtf8Encoding(varHandleStringEncoder); + } + + @Test + @DisabledOnJre(JRE.JAVA_8) + void testUtf8SizeLatin1_VarHandle() { + testUtf8SizeLatin1(varHandleStringEncoder); + } + + @Test + @SetSystemProperty(key = "java.vm.name", value = "Dalvik") + void unsafeStringEncoderNotAvailableOnAndroid() { + assertThat(StringEncoderHolder.createUnsafeEncoder()).isNull(); + } + + @SuppressWarnings("AvoidEscapedUnicodeCharacters") + private static void testUtf8Encoding(StringEncoder stringEncoder) { + assertThat(stringEncoder).isNotNull(); + + assertThat(stringEncoder.getUtf8Size(null)).isEqualTo(0); + assertThat(testUtf8(null, 0, stringEncoder)).isEqualTo(""); + + assertThat(stringEncoder.getUtf8Size("")).isEqualTo(0); + assertThat(testUtf8("", 0, stringEncoder)).isEqualTo(""); + + assertThat(stringEncoder.getUtf8Size("a")).isEqualTo(1); + assertThat(testUtf8("a", 1, stringEncoder)).isEqualTo("a"); + + assertThat(stringEncoder.getUtf8Size("Β©")).isEqualTo(2); + assertThat(testUtf8("Β©", 2, stringEncoder)).isEqualTo("Β©"); + + assertThat(stringEncoder.getUtf8Size("βˆ†")).isEqualTo(3); + assertThat(testUtf8("βˆ†", 3, stringEncoder)).isEqualTo("βˆ†"); + + assertThat(stringEncoder.getUtf8Size("πŸ˜€")).isEqualTo(4); + assertThat(testUtf8("πŸ˜€", 4, stringEncoder)).isEqualTo("πŸ˜€"); + + // test that invalid characters are replaced with ? + assertThat(stringEncoder.getUtf8Size("\uD83DπŸ˜€\uDE00")).isEqualTo(6); + assertThat(testUtf8("\uD83DπŸ˜€\uDE00", 6, stringEncoder)).isEqualTo("?πŸ˜€?"); + + // the same invalid sequence as encoded by the jdk + byte[] bytes = "\uD83DπŸ˜€\uDE00".getBytes(StandardCharsets.UTF_8); + assertThat(bytes.length).isEqualTo(6); + assertThat(new String(bytes, StandardCharsets.UTF_8)).isEqualTo("?πŸ˜€?"); + } + + private static void testUtf8SizeLatin1(StringEncoder stringEncoder) { + assertThat(stringEncoder.getUtf8Size(null)).isEqualTo(0); + + // Run repeated test logic for each encoder + Random random = new Random(); + for (int i = 0; i < 1000; i++) { + byte[] bytes = new byte[15001]; + random.nextBytes(bytes); + String string = new String(bytes, StandardCharsets.ISO_8859_1); + int utf8Size = string.getBytes(StandardCharsets.UTF_8).length; + assertThat(stringEncoder.getUtf8Size(string)).isEqualTo(utf8Size); + } + } + + static String testUtf8(String string, int utf8Length) { + return testUtf8(string, utf8Length, StringEncoder.getInstance()); + } + + static String testUtf8(String string, int utf8Length, StringEncoder stringEncoder) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); + stringEncoder.writeUtf8(codedOutputStream, string, utf8Length); + codedOutputStream.flush(); + return new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + } catch (Exception exception) { + throw new IllegalArgumentException(exception); + } + } +} diff --git a/exporters/common/src/test/java/io/opentelemetry/exporter/internal/metrics/ExporterInstrumentationTest.java b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/metrics/ExporterInstrumentationTest.java new file mode 100644 index 00000000000..c9d0a8024e7 --- /dev/null +++ b/exporters/common/src/test/java/io/opentelemetry/exporter/internal/metrics/ExporterInstrumentationTest.java @@ -0,0 +1,176 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.metrics; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import java.net.URI; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.Mockito; + +class ExporterInstrumentationTest { + + @SuppressWarnings("unchecked") + Supplier meterProviderSupplier = mock(Supplier.class); + + @ParameterizedTest + @EnumSource + void validMeterProvider(InternalTelemetryVersion schemaVersion) { + when(meterProviderSupplier.get()) + .thenReturn( + SdkMeterProvider.builder() + // Have to provide a valid reader. + .registerMetricReader( + new MetricReader() { + @Override + public void register(CollectionRegistration registration) {} + + @Override + public CompletableResultCode forceFlush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public AggregationTemporality getAggregationTemporality( + InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + }) + .build()); + ExporterInstrumentation instrumentation = + new ExporterInstrumentation( + schemaVersion, + meterProviderSupplier, + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER), + URI.create("http://testing:1234")); + verifyNoInteractions(meterProviderSupplier); // Ensure lazy + + // Verify the supplier is only called once per underlying meter. + + instrumentation.startRecordingExport(42).finishFailed("foo"); + instrumentation.startRecordingExport(42).finishSuccessful(); + verify(meterProviderSupplier, atLeastOnce()).get(); + + instrumentation.startRecordingExport(42).finishFailed("foo"); + instrumentation.startRecordingExport(42).finishSuccessful(); + verifyNoMoreInteractions(meterProviderSupplier); + } + + @ParameterizedTest + @EnumSource + void noopMeterProvider(InternalTelemetryVersion schemaVersion) { + + when(meterProviderSupplier.get()).thenReturn(MeterProvider.noop()); + ExporterInstrumentation instrumentation = + new ExporterInstrumentation( + schemaVersion, + meterProviderSupplier, + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER), + URI.create("http://testing:1234")); + verifyNoInteractions(meterProviderSupplier); // Ensure lazy + + // Verify the supplier is invoked multiple times since it returns a noop meter. + instrumentation.startRecordingExport(42).finishFailed("foo"); + instrumentation.startRecordingExport(42).finishSuccessful(); + verify(meterProviderSupplier, atLeastOnce()).get(); + + Mockito.clearInvocations((Object) meterProviderSupplier); + instrumentation.startRecordingExport(42).finishFailed("foo"); + instrumentation.startRecordingExport(42).finishSuccessful(); + verify(meterProviderSupplier, atLeastOnce()).get(); + } + + @Test + void serverAttributesHttps() { + assertThat( + ExporterInstrumentation.extractServerAttributes( + URI.create("https://example.com/foo/bar?a=b"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "example.com") + .containsEntry(SemConvConstants.SERVER_PORT, 443); + + assertThat( + ExporterInstrumentation.extractServerAttributes( + URI.create("https://example.com:1234/foo/bar?a=b"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "example.com") + .containsEntry(SemConvConstants.SERVER_PORT, 1234); + } + + @Test + void serverAttributesHttp() { + assertThat( + ExporterInstrumentation.extractServerAttributes( + URI.create("http://example.com/foo/bar?a=b"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "example.com") + .containsEntry(SemConvConstants.SERVER_PORT, 80); + + assertThat( + ExporterInstrumentation.extractServerAttributes( + URI.create("http://example.com:1234/foo/bar?a=b"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "example.com") + .containsEntry(SemConvConstants.SERVER_PORT, 1234); + } + + @Test + void serverAttributesUnknownScheme() { + assertThat(ExporterInstrumentation.extractServerAttributes(URI.create("custom://foo"))) + .hasSize(1) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "foo"); + + assertThat(ExporterInstrumentation.extractServerAttributes(URI.create("custom://foo:1234"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "foo") + .containsEntry(SemConvConstants.SERVER_PORT, 1234); + } + + @Test + void serverAttributesHostNotParsedByUri() { + // A label starting with a digit is a valid DNS name, but URI.getHost() returns null for it. + assertThat(URI.create("http://otlp.1234-ns:4318/v1/traces").getHost()).isNull(); + + assertThat( + ExporterInstrumentation.extractServerAttributes( + URI.create("http://otlp.1234-ns:4318/v1/traces"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "otlp.1234-ns") + .containsEntry(SemConvConstants.SERVER_PORT, 4318); + + assertThat( + ExporterInstrumentation.extractServerAttributes( + URI.create("https://otlp.1234-ns/v1/traces"))) + .hasSize(2) + .containsEntry(SemConvConstants.SERVER_ADDRESS, "otlp.1234-ns") + .containsEntry(SemConvConstants.SERVER_PORT, 443); + } +} diff --git a/exporters/common/src/testSenderProvider/java/io/opentelemetry/exporter/internal/grpc/SenderUtilTest.java b/exporters/common/src/testSenderProvider/java/io/opentelemetry/exporter/internal/grpc/SenderUtilTest.java new file mode 100644 index 00000000000..79ab11faef4 --- /dev/null +++ b/exporters/common/src/testSenderProvider/java/io/opentelemetry/exporter/internal/grpc/SenderUtilTest.java @@ -0,0 +1,123 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.grpc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.SenderUtil; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider; +import io.opentelemetry.exporter.sender.jdk.internal.JdkHttpSenderProvider; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSenderProvider; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpHttpSenderProvider; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junitpioneer.jupiter.SetSystemProperty; + +class SenderUtilTest { + + @RegisterExtension + LogCapturer logCapturer = LogCapturer.create().captureForLogger(SenderUtil.class.getName()); + + private final ComponentLoader componentLoader = + ComponentLoader.forClassLoader(SenderUtilTest.class.getClassLoader()); + + @Test + @SuppressLogger(SenderUtil.class) + void resolveGrpcSenderProvider_multipleSendersNoConfiguration() { + assertThatCode(() -> SenderUtil.resolveGrpcSenderProvider(componentLoader)) + .doesNotThrowAnyException(); + + logCapturer.assertContains( + "Multiple GrpcSenderProvider found. Please include only one, " + + "or specify preference setting io.opentelemetry.sdk.common.export.GrpcSenderProvider " + + "to the FQCN of the preferred provider."); + } + + @Test + @SetSystemProperty( + key = "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + value = + "io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider") + void resolveGrpcSenderProvider_multipleSendersWithUpstream() { + assertThat(SenderUtil.resolveGrpcSenderProvider(componentLoader)) + .isInstanceOf(UpstreamGrpcSenderProvider.class); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @Test + @SetSystemProperty( + key = "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + value = "io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSenderProvider") + void resolveGrpcSenderProvider_multipleSendersWithOkHttp() { + assertThat(SenderUtil.resolveGrpcSenderProvider(componentLoader)) + .isInstanceOf(OkHttpGrpcSenderProvider.class); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @Test + @SetSystemProperty(key = "io.opentelemetry.sdk.common.export.GrpcSenderProvider", value = "foo") + void resolveGrpcSenderProvider_multipleSendersNoMatch() { + assertThatThrownBy(() -> SenderUtil.resolveGrpcSenderProvider(componentLoader)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "No GrpcSenderProvider matched configured io.opentelemetry.sdk.common.export.GrpcSenderProvider: foo"); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @Test + @SuppressLogger(SenderUtil.class) + void build_multipleSendersNoConfiguration() { + Assertions.assertThatCode(() -> SenderUtil.resolveHttpSenderProvider(componentLoader)) + .doesNotThrowAnyException(); + + logCapturer.assertContains( + "Multiple HttpSenderProvider found. Please include only one, " + + "or specify preference setting io.opentelemetry.sdk.common.export.HttpSenderProvider " + + "to the FQCN of the preferred provider."); + } + + @Test + @SetSystemProperty( + key = "io.opentelemetry.sdk.common.export.HttpSenderProvider", + value = "io.opentelemetry.exporter.sender.jdk.internal.JdkHttpSenderProvider") + void build_multipleSendersWithJdk() { + assertThat(SenderUtil.resolveHttpSenderProvider(componentLoader)) + .isInstanceOf(JdkHttpSenderProvider.class); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @Test + @SetSystemProperty( + key = "io.opentelemetry.sdk.common.export.HttpSenderProvider", + value = "io.opentelemetry.exporter.sender.okhttp.internal.OkHttpHttpSenderProvider") + void build_multipleSendersWithOkHttp() { + assertThat(SenderUtil.resolveHttpSenderProvider(componentLoader)) + .isInstanceOf(OkHttpHttpSenderProvider.class); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @Test + @SetSystemProperty(key = "io.opentelemetry.sdk.common.export.HttpSenderProvider", value = "foo") + void build_multipleSendersNoMatch() { + assertThatThrownBy(() -> SenderUtil.resolveHttpSenderProvider(componentLoader)) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "No HttpSenderProvider matched configured io.opentelemetry.sdk.common.export.HttpSenderProvider: foo"); + + assertThat(logCapturer.getEvents()).isEmpty(); + } +} diff --git a/exporters/common/src/testWithoutUnsafe/java/io/opentelemetry/exporter/internal/marshal/StringEncoderWithoutUnsafeTest.java b/exporters/common/src/testWithoutUnsafe/java/io/opentelemetry/exporter/internal/marshal/StringEncoderWithoutUnsafeTest.java new file mode 100644 index 00000000000..f93cad83cb9 --- /dev/null +++ b/exporters/common/src/testWithoutUnsafe/java/io/opentelemetry/exporter/internal/marshal/StringEncoderWithoutUnsafeTest.java @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.marshal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class StringEncoderWithoutUnsafeTest { + + // Simulate running in an environment without sun.misc.Unsafe e.g. when running a modular + // application. To use sun.misc.Unsafe in modular application user would need to add dependency to + // jdk.unsupported module or use --add-modules jdk.unsupported. Here we use a custom child first + // class loader that does not delegate loading sun.misc classes to make sun.misc.Unsafe + // unavailable. + @Test + void utf8EncodingWithoutUnsafe() throws Exception { + ClassLoader testClassLoader = + new ClassLoader(this.getClass().getClassLoader()) { + @Override + protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { + // don't allow loading sun.misc classes + if (name.startsWith("sun.misc")) { + throw new ClassNotFoundException(name); + } + // load io.opentelemetry in the custom loader + if (name.startsWith("io.opentelemetry")) { + synchronized (this) { + Class clazz = findLoadedClass(name); + if (clazz != null) { + return clazz; + } + try (InputStream inputStream = + getParent().getResourceAsStream(name.replace(".", "/") + ".class")) { + if (inputStream != null) { + byte[] bytes = readBytes(inputStream); + // we don't bother to define packages or provide protection domain + return defineClass(name, bytes, 0, bytes.length); + } + } catch (IOException exception) { + throw new ClassNotFoundException(name, exception); + } + } + } + return super.loadClass(name, resolve); + } + }; + + // load test class in the custom loader and run the test + Class testClass = testClassLoader.loadClass(this.getClass().getName() + "$TestClass"); + assertThat(testClass.getClassLoader()).isEqualTo(testClassLoader); + Runnable test = (Runnable) testClass.getConstructor().newInstance(); + test.run(); + } + + private static byte[] readBytes(InputStream inputStream) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + + int readCount; + while ((readCount = inputStream.read(buffer, 0, buffer.length)) != -1) { + out.write(buffer, 0, readCount); + } + return out.toByteArray(); + } + + @SuppressWarnings("unused") + public static class TestClass implements Runnable { + + @Override + public void run() { + // verify that unsafe can't be found + assertThatThrownBy(() -> Class.forName("sun.misc.Unsafe")) + .isInstanceOf(ClassNotFoundException.class); + // test the methods that use unsafe + assertThat(StringEncoder.getInstance().getUtf8Size("a")).isEqualTo(1); + assertThat(testUtf8("a", 0)).isEqualTo("a"); + } + + static String testUtf8(String string, int utf8Length) { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + CodedOutputStream codedOutputStream = CodedOutputStream.newInstance(outputStream); + StringEncoder.getInstance().writeUtf8(codedOutputStream, string, utf8Length); + codedOutputStream.flush(); + return new String(outputStream.toByteArray(), StandardCharsets.UTF_8); + } catch (Exception exception) { + throw new IllegalArgumentException(exception); + } + } + } +} diff --git a/exporters/jaeger-proto/build.gradle.kts b/exporters/jaeger-proto/build.gradle.kts deleted file mode 100644 index ab9825af1a9..00000000000 --- a/exporters/jaeger-proto/build.gradle.kts +++ /dev/null @@ -1,26 +0,0 @@ -plugins { - id("otel.protobuf-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry - Jaeger Exporter Proto (Internal Use Only)" -otelJava.moduleName.set("io.opentelemetry.exporter.jaeger.proto") - -dependencies { - api("com.google.protobuf:protobuf-java") - - compileOnly("io.grpc:grpc-api") - compileOnly("io.grpc:grpc-protobuf") - compileOnly("io.grpc:grpc-stub") -} - -tasks { - compileJava { - with(options) { - // Generated code so can't control serialization. - compilerArgs.add("-Xlint:-serial") - } - } -} diff --git a/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/collector.proto b/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/collector.proto deleted file mode 100644 index 03d6b6be8ca..00000000000 --- a/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/collector.proto +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -syntax="proto3"; - -package jaeger.api_v2; - -import "jaeger/api_v2/model.proto"; - -option java_package = "io.opentelemetry.exporter.jaeger.proto.api_v2"; - -message PostSpansRequest { - Batch batch = 1; -} - -message PostSpansResponse { -} - -service CollectorService { - rpc PostSpans(PostSpansRequest) returns (PostSpansResponse) {} -} diff --git a/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/model.proto b/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/model.proto deleted file mode 100644 index 0d2bd212787..00000000000 --- a/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/model.proto +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -syntax="proto3"; - -package jaeger.api_v2; - -import "google/protobuf/timestamp.proto"; -import "google/protobuf/duration.proto"; - -option java_package = "io.opentelemetry.exporter.jaeger.proto.api_v2"; - -enum ValueType { - STRING = 0; - BOOL = 1; - INT64 = 2; - FLOAT64 = 3; - BINARY = 4; -}; - -message Log { - google.protobuf.Timestamp timestamp = 1; - repeated KeyValue fields = 2; -} - -message KeyValue { - string key = 1; - ValueType v_type = 2; - string v_str = 3; - bool v_bool = 4; - int64 v_int64 = 5; - double v_float64 = 6; - bytes v_binary = 7; -} - -enum SpanRefType { - CHILD_OF = 0; - FOLLOWS_FROM = 1; -}; - -message SpanRef { - bytes trace_id = 1; - bytes span_id = 2; - SpanRefType ref_type = 3; -} - -message Process { - string service_name = 1; - repeated KeyValue tags = 2; -} - -message Span { - bytes trace_id = 1; - bytes span_id = 2; - string operation_name = 3; - repeated SpanRef references = 4; - uint32 flags = 5; - google.protobuf.Timestamp start_time = 6; - google.protobuf.Duration duration = 7; - repeated KeyValue tags = 8; - repeated Log logs = 9; - Process process = 10; - string process_id = 11; - repeated string warnings = 12; -} - -message Trace { - message ProcessMapping { - string process_id = 1; - Process process = 2; - } - repeated Span spans = 1; - repeated ProcessMapping process_map = 2; - repeated string warnings = 3; -} - -message Batch { - repeated Span spans = 1; - Process process = 2; -} - -message DependencyLink { - string parent = 1; - string child = 2; - uint64 call_count = 3; - string source = 4; -} diff --git a/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/time.proto b/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/time.proto deleted file mode 100644 index b92529d7a56..00000000000 --- a/exporters/jaeger-proto/src/main/proto/jaeger/api_v2/time.proto +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: - -// Protocol Buffers - Google's data interchange format -// Copyright 2008 Google Inc. All rights reserved. -// https://developers.google.com/protocol-buffers/ -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above -// copyright notice, this list of conditions and the following disclaimer -// in the documentation and/or other materials provided with the -// distribution. -// * Neither the name of Google Inc. nor the names of its -// contributors may be used to endorse or promote products derived from -// this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -syntax = "proto3"; - -package io.opentelemetry.internal; - -option java_package = "io.opentelemetry.exporter.jaeger.internal.protobuf"; -option java_outer_classname = "TimeProto"; -option java_multiple_files = true; - -// Copied from google.protobuf.Timestamp to provide access to the wire format. -message Time { - // Represents seconds of UTC time since Unix epoch - // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to - // 9999-12-31T23:59:59Z inclusive. - int64 seconds = 1; - - // Non-negative fractions of a second at nanosecond resolution. Negative - // second values with fractions must still have non-negative nanos values - // that count forward in time. Must be from 0 to 999,999,999 - // inclusive. - int32 nanos = 2; -} diff --git a/exporters/jaeger-thrift/README.md b/exporters/jaeger-thrift/README.md deleted file mode 100644 index cb770718b61..00000000000 --- a/exporters/jaeger-thrift/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# OpenTelemetry - Jaeger Exporter - Thrift - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry exporter, sending span data to Jaeger via Thrift over HTTP. - -## Configuration - -The Jaeger Thrift span exporter can be configured programmatically. - -An example of simple Jaeger Thrift exporter initialization. In this case -spans will be sent to a Jaeger Thrift endpoint running on `localhost`: - -```java -JaegerThriftSpanExporter exporter = - JaegerThriftSpanExporter.builder() - .setEndpoint("http://localhost:14268/api/traces") - .build(); -``` - -If you need configuration via environment variables and/or system properties, you will want to use -the [autoconfigure](../../sdk-extensions/autoconfigure) module. - -## Compatibility - -As with the OpenTelemetry SDK itself, this exporter is compatible with Java 8+ and Android API level 24+. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-jaeger-thrift.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-jaeger-thrift diff --git a/exporters/jaeger-thrift/build.gradle.kts b/exporters/jaeger-thrift/build.gradle.kts deleted file mode 100644 index 36160dc8697..00000000000 --- a/exporters/jaeger-thrift/build.gradle.kts +++ /dev/null @@ -1,28 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry - Jaeger Thrift Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.jaeger.thrift") - -dependencies { - api(project(":sdk:all")) - - implementation(project(":sdk:all")) - implementation(project(":semconv")) - - implementation("com.fasterxml.jackson.jr:jackson-jr-objects") - implementation("io.jaegertracing:jaeger-client") { - exclude("com.google.code.gson", "gson") - } - - testImplementation("com.fasterxml.jackson.jr:jackson-jr-stree") - testImplementation("org.testcontainers:junit-jupiter") - testImplementation("com.squareup.okhttp3:okhttp") - testImplementation("com.google.guava:guava-testlib") - - testImplementation(project(":sdk:testing")) -} diff --git a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/Adapter.java b/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/Adapter.java deleted file mode 100644 index cd3bf4ec26f..00000000000 --- a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/Adapter.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger.thrift; - -import static io.opentelemetry.api.common.AttributeKey.booleanKey; - -import com.fasterxml.jackson.jr.ob.JSON; -import io.jaegertracing.thriftjava.Log; -import io.jaegertracing.thriftjava.Span; -import io.jaegertracing.thriftjava.SpanRef; -import io.jaegertracing.thriftjava.SpanRefType; -import io.jaegertracing.thriftjava.Tag; -import io.jaegertracing.thriftjava.TagType; -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.LinkData; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Locale; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import javax.annotation.concurrent.ThreadSafe; - -/** Adapts OpenTelemetry objects to Jaeger objects. */ -@ThreadSafe -final class Adapter { - - static final AttributeKey KEY_ERROR = booleanKey("error"); - static final String KEY_LOG_EVENT = "event"; - static final String KEY_EVENT_DROPPED_ATTRIBUTES_COUNT = "otel.event.dropped_attributes_count"; - static final String KEY_DROPPED_ATTRIBUTES_COUNT = "otel.dropped_attributes_count"; - static final String KEY_DROPPED_EVENTS_COUNT = "otel.dropped_events_count"; - static final String KEY_SPAN_KIND = "span.kind"; - static final String KEY_SPAN_STATUS_MESSAGE = "otel.status_message"; - static final String KEY_SPAN_STATUS_CODE = "otel.status_code"; - static final String KEY_INSTRUMENTATION_SCOPE_NAME = "otel.scope.name"; - static final String KEY_INSTRUMENTATION_SCOPE_VERSION = "otel.scope.version"; - static final String KEY_INSTRUMENTATION_LIBRARY_NAME = "otel.library.name"; - static final String KEY_INSTRUMENTATION_LIBRARY_VERSION = "otel.library.version"; - - private Adapter() {} - - /** - * Converts a list of {@link SpanData} into a collection of Jaeger's {@link Span}. - * - * @param spans the list of spans to be converted - * @return the collection of Jaeger spans - * @see #toJaeger(SpanData) - */ - static List toJaeger(Collection spans) { - return spans.stream().map(Adapter::toJaeger).collect(Collectors.toList()); - } - - /** - * Converts a single {@link SpanData} into a Jaeger's {@link Span}. - * - * @param span the span to be converted - * @return the Jaeger span - */ - static Span toJaeger(SpanData span) { - Span target = new Span(); - - long traceIdHigh = traceIdAsLongHigh(span.getTraceId()); - long traceIdLow = traceIdAsLongLow(span.getTraceId()); - - target.setTraceIdHigh(traceIdHigh); - target.setTraceIdLow(traceIdLow); - target.setSpanId(spanIdAsLong(span.getSpanId())); - target.setOperationName(span.getName()); - target.setStartTime(TimeUnit.NANOSECONDS.toMicros(span.getStartEpochNanos())); - target.setDuration( - TimeUnit.NANOSECONDS.toMicros(span.getEndEpochNanos() - span.getStartEpochNanos())); - - List tags = toTags(span.getAttributes()); - int droppedAttributes = span.getTotalAttributeCount() - span.getAttributes().size(); - if (droppedAttributes > 0) { - tags.add(new Tag(KEY_DROPPED_ATTRIBUTES_COUNT, TagType.LONG).setVLong(droppedAttributes)); - } - - target.setLogs(toJaegerLogs(span.getEvents())); - int droppedEvents = span.getTotalRecordedEvents() - span.getEvents().size(); - if (droppedEvents > 0) { - tags.add(new Tag(KEY_DROPPED_EVENTS_COUNT, TagType.LONG).setVLong(droppedEvents)); - } - - List references = toSpanRefs(span.getLinks()); - - // add the parent span - if (span.getParentSpanContext().isValid()) { - long parentSpanId = spanIdAsLong(span.getParentSpanId()); - references.add(new SpanRef(SpanRefType.CHILD_OF, traceIdLow, traceIdHigh, parentSpanId)); - target.setParentSpanId(parentSpanId); - } - target.setReferences(references); - - if (span.getKind() != SpanKind.INTERNAL) { - tags.add( - new Tag(KEY_SPAN_KIND, TagType.STRING) - .setVStr(span.getKind().name().toLowerCase(Locale.ROOT))); - } - - if (!span.getStatus().getDescription().isEmpty()) { - tags.add( - new Tag(KEY_SPAN_STATUS_MESSAGE, TagType.STRING) - .setVStr(span.getStatus().getDescription())); - } - - if (span.getStatus().getStatusCode() != StatusCode.UNSET) { - tags.add( - new Tag(KEY_SPAN_STATUS_CODE, TagType.STRING) - .setVStr(span.getStatus().getStatusCode().name())); - } - - tags.add( - new Tag(KEY_INSTRUMENTATION_SCOPE_NAME, TagType.STRING) - .setVStr(span.getInstrumentationScopeInfo().getName())); - // Include instrumentation library name for backwards compatibility - tags.add( - new Tag(KEY_INSTRUMENTATION_LIBRARY_NAME, TagType.STRING) - .setVStr(span.getInstrumentationScopeInfo().getName())); - - if (span.getInstrumentationScopeInfo().getVersion() != null) { - tags.add( - new Tag(KEY_INSTRUMENTATION_SCOPE_VERSION, TagType.STRING) - .setVStr(span.getInstrumentationScopeInfo().getVersion())); - // Include instrumentation library name for backwards compatibility - tags.add( - new Tag(KEY_INSTRUMENTATION_LIBRARY_VERSION, TagType.STRING) - .setVStr(span.getInstrumentationScopeInfo().getVersion())); - } - - if (span.getStatus().getStatusCode() == StatusCode.ERROR) { - tags.add(toTag(KEY_ERROR, true)); - } - target.setTags(tags); - - return target; - } - - /** - * Converts {@link EventData}s into a collection of Jaeger's {@link Log}. - * - * @param timedEvents the timed events to be converted - * @return a collection of Jaeger logs - * @see #toJaegerLog(EventData) - */ - // VisibleForTesting - static List toJaegerLogs(List timedEvents) { - return timedEvents.stream().map(Adapter::toJaegerLog).collect(Collectors.toList()); - } - - /** - * Converts a {@link EventData} into Jaeger's {@link Log}. - * - * @param event the timed event to be converted - * @return a Jaeger log - */ - // VisibleForTesting - static Log toJaegerLog(EventData event) { - Log result = new Log(); - result.setTimestamp(TimeUnit.NANOSECONDS.toMicros(event.getEpochNanos())); - result.addToFields(new Tag(KEY_LOG_EVENT, TagType.STRING).setVStr(event.getName())); - - int droppedAttributesCount = event.getDroppedAttributesCount(); - if (droppedAttributesCount > 0) { - result.addToFields( - new Tag(KEY_EVENT_DROPPED_ATTRIBUTES_COUNT, TagType.LONG) - .setVLong(droppedAttributesCount)); - } - List attributeTags = toTags(event.getAttributes()); - for (Tag attributeTag : attributeTags) { - result.addToFields(attributeTag); - } - return result; - } - - /** - * Converts a map of attributes into a collection of Jaeger's {@link Tag}. - * - * @param attributes the span attributes - * @return a collection of Jaeger key values - * @see #toTag - */ - static List toTags(Attributes attributes) { - List results = new ArrayList<>(); - attributes.forEach((key, value) -> results.add(toTag(key, value))); - return results; - } - - /** - * Converts the given {@link AttributeKey} and value into Jaeger's {@link Tag}. - * - * @param key the entry key as string - * @param value the entry value - * @return a Jaeger key value - */ - // VisibleForTesting - static Tag toTag(AttributeKey key, Object value) { - switch (key.getType()) { - case STRING: - return new Tag(key.getKey(), TagType.STRING).setVStr((String) value); - case LONG: - return new Tag(key.getKey(), TagType.LONG).setVLong((long) value); - case BOOLEAN: - return new Tag(key.getKey(), TagType.BOOL).setVBool((boolean) value); - case DOUBLE: - return new Tag(key.getKey(), TagType.DOUBLE).setVDouble((double) value); - default: - try { - return new Tag(key.getKey(), TagType.STRING).setVStr(JSON.std.asString(value)); - } catch (IOException e) { - // Can't have an exception serializing a plain Java object to a String. Add an exception - // mostly to satisfy the compiler. - throw new UncheckedIOException( - "Error serializing a plain Java object to String. " - + "This is a bug in the OpenTelemetry library.", - e); - } - } - } - - /** - * Converts {@link LinkData}s into a collection of Jaeger's {@link SpanRef}. - * - * @param links the span's links property to be converted - * @return a collection of Jaeger span references - */ - // VisibleForTesting - static List toSpanRefs(List links) { - List spanRefs = new ArrayList<>(links.size()); - for (LinkData link : links) { - spanRefs.add(toSpanRef(link)); - } - return spanRefs; - } - - /** - * Converts a single {@link LinkData} into a Jaeger's {@link SpanRef}. - * - * @param link the OpenTelemetry link to be converted - * @return the Jaeger span reference - */ - // VisibleForTesting - static SpanRef toSpanRef(LinkData link) { - // we can assume that all links are *follows from* - // https://github.com/open-telemetry/opentelemetry-java/issues/475 - // https://github.com/open-telemetry/opentelemetry-java/pull/481/files#r312577862 - return new SpanRef( - SpanRefType.FOLLOWS_FROM, - traceIdAsLongLow(link.getSpanContext().getTraceId()), - traceIdAsLongHigh(link.getSpanContext().getTraceId()), - spanIdAsLong(link.getSpanContext().getSpanId())); - } - - private static long traceIdAsLongHigh(String traceId) { - return new BigInteger(traceId.substring(0, 16), 16).longValue(); - } - - private static long traceIdAsLongLow(String traceId) { - return new BigInteger(traceId.substring(16, 32), 16).longValue(); - } - - private static long spanIdAsLong(String spanId) { - return new BigInteger(spanId, 16).longValue(); - } -} diff --git a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporter.java b/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporter.java deleted file mode 100644 index c3ea38f11cc..00000000000 --- a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporter.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger.thrift; - -import io.jaegertracing.internal.exceptions.SenderException; -import io.jaegertracing.thrift.internal.senders.ThriftSender; -import io.jaegertracing.thriftjava.Process; -import io.jaegertracing.thriftjava.Span; -import io.jaegertracing.thriftjava.Tag; -import io.jaegertracing.thriftjava.TagType; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ThrottlingLogger; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports spans to Jaeger via Thrift, using Jaeger's thrift model. */ -@ThreadSafe -public final class JaegerThriftSpanExporter implements SpanExporter { - - static final String DEFAULT_ENDPOINT = "http://localhost:14268/api/traces"; - - private static final String DEFAULT_HOST_NAME = "unknown"; - private static final String CLIENT_VERSION_KEY = "jaeger.version"; - private static final String CLIENT_VERSION_VALUE = "opentelemetry-java"; - private static final String HOSTNAME_KEY = "hostname"; - private static final String IP_KEY = "ip"; - private static final String IP_DEFAULT = "0.0.0.0"; - - private final ThrottlingLogger logger = - new ThrottlingLogger(Logger.getLogger(JaegerThriftSpanExporter.class.getName())); - private final ThriftSender thriftSender; - private final Process process; - - /** - * Creates a new Jaeger gRPC Span Reporter with the given name, using the given channel. - * - * @param thriftSender The sender used for sending the data. - */ - JaegerThriftSpanExporter(ThriftSender thriftSender) { - this.thriftSender = thriftSender; - String hostname; - String ipv4; - - try { - hostname = InetAddress.getLocalHost().getHostName(); - ipv4 = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - hostname = DEFAULT_HOST_NAME; - ipv4 = IP_DEFAULT; - } - - Tag clientTag = new Tag(CLIENT_VERSION_KEY, TagType.STRING).setVStr(CLIENT_VERSION_VALUE); - Tag ipv4Tag = new Tag(IP_KEY, TagType.STRING).setVStr(ipv4); - Tag hostnameTag = new Tag(HOSTNAME_KEY, TagType.STRING).setVStr(hostname); - - this.process = new Process(); - this.process.addToTags(clientTag); - this.process.addToTags(ipv4Tag); - this.process.addToTags(hostnameTag); - } - - /** - * Submits all the given spans in a single batch to the Jaeger collector. - * - * @param spans the list of sampled Spans to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection spans) { - Map> batches = - spans.stream().collect(Collectors.groupingBy(SpanData::getResource)).entrySet().stream() - .collect( - Collectors.toMap( - entry -> createProcess(entry.getKey()), - entry -> Adapter.toJaeger(entry.getValue()))); - - List batchResults = new ArrayList<>(batches.size()); - batches.forEach( - (process, jaegerSpans) -> { - CompletableResultCode batchResult = new CompletableResultCode(); - batchResults.add(batchResult); - try { - // todo: consider making truly async - thriftSender.send(process, jaegerSpans); - batchResult.succeed(); - } catch (SenderException e) { - logger.log(Level.WARNING, "Failed to export spans", e); - batchResult.fail(); - } - }); - return CompletableResultCode.ofAll(batchResults); - } - - private Process createProcess(Resource resource) { - Process result = new Process(this.process); - - String serviceName = resource.getAttribute(ResourceAttributes.SERVICE_NAME); - if (serviceName == null || serviceName.isEmpty()) { - serviceName = Resource.getDefault().getAttribute(ResourceAttributes.SERVICE_NAME); - } - // In practice should never be null unless the default Resource spec is changed. - if (serviceName != null) { - result.setServiceName(serviceName); - } - - List tags = Adapter.toTags(resource.getAttributes()); - tags.forEach(result::addToTags); - return result; - } - - /** - * The Jaeger exporter does not batch spans, so this method will immediately return with success. - * - * @return always Success - */ - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static JaegerThriftSpanExporterBuilder builder() { - return new JaegerThriftSpanExporterBuilder(); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately - * cancelled. - */ - @Override - public CompletableResultCode shutdown() { - CompletableResultCode result = new CompletableResultCode(); - // todo - return result.succeed(); - } - - // Visible for testing - Process getProcess() { - return process; - } -} diff --git a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporterBuilder.java b/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporterBuilder.java deleted file mode 100644 index eb7963a6dcd..00000000000 --- a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporterBuilder.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger.thrift; - -import io.jaegertracing.thrift.internal.senders.HttpSender; -import io.jaegertracing.thrift.internal.senders.ThriftSender; -import javax.annotation.Nullable; -import org.apache.thrift.transport.TTransportException; - -/** Builder utility for this exporter. */ -public final class JaegerThriftSpanExporterBuilder { - - private String endpoint = JaegerThriftSpanExporter.DEFAULT_ENDPOINT; - @Nullable private ThriftSender thriftSender; - - /** - * Explicitly set the {@link ThriftSender} instance to use for this Exporter. Will override any - * endpoint that has been set. - * - * @param thriftSender The ThriftSender to use. - * @return this. - */ - public JaegerThriftSpanExporterBuilder setThriftSender(ThriftSender thriftSender) { - this.thriftSender = thriftSender; - return this; - } - - /** - * Sets the Jaeger endpoint to connect to. Needs to include the full API path for trace ingest. - * - *

    Optional, defaults to "http://localhost:14268/api/traces". - * - * @param endpoint The Jaeger endpoint URL, ex. "https://jaegerhost:14268/api/traces". - * @return this. - */ - public JaegerThriftSpanExporterBuilder setEndpoint(String endpoint) { - this.endpoint = endpoint; - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance. - */ - public JaegerThriftSpanExporter build() { - ThriftSender thriftSender = this.thriftSender; - if (thriftSender == null) { - try { - thriftSender = new HttpSender.Builder(endpoint).build(); - } catch (TTransportException e) { - throw new IllegalStateException("Failed to construct a thrift HttpSender.", e); - } - } - return new JaegerThriftSpanExporter(thriftSender); - } - - JaegerThriftSpanExporterBuilder() {} -} diff --git a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/package-info.java b/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/package-info.java deleted file mode 100644 index 1173e8d8452..00000000000 --- a/exporters/jaeger-thrift/src/main/java/io/opentelemetry/exporter/jaeger/thrift/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -@ParametersAreNonnullByDefault -package io.opentelemetry.exporter.jaeger.thrift; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/AdapterTest.java b/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/AdapterTest.java deleted file mode 100644 index a084b671a36..00000000000 --- a/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/AdapterTest.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger.thrift; - -import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; -import static io.opentelemetry.api.common.AttributeKey.doubleKey; -import static io.opentelemetry.api.common.AttributeKey.longArrayKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.io.BaseEncoding; -import io.jaegertracing.thriftjava.Log; -import io.jaegertracing.thriftjava.SpanRef; -import io.jaegertracing.thriftjava.SpanRefType; -import io.jaegertracing.thriftjava.Tag; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.LinkData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import javax.annotation.Nullable; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link Adapter}. */ -class AdapterTest { - private static final BaseEncoding hex = BaseEncoding.base16().lowerCase(); - private static final String LINK_TRACE_ID = "ff000000000000000000000000cba123"; - private static final String LINK_SPAN_ID = "0000000000fed456"; - private static final String TRACE_ID = "0000000000000000ff00000000abc123"; - private static final String SPAN_ID = "ff00000000def456"; - private static final String PARENT_SPAN_ID = "0000000000aef789"; - - @Test - void testThriftSpans() { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - - SpanData span = getSpanData(startMs, endMs, SpanKind.SERVER); - List spans = Collections.singletonList(span); - - List jaegerSpans = Adapter.toJaeger(spans); - - // the span contents are checked somewhere else - assertThat(jaegerSpans).hasSize(1); - } - - @Test - void testThriftSpan() { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - - SpanData span = getSpanData(startMs, endMs, SpanKind.SERVER, 2, 4); - - // test - io.jaegertracing.thriftjava.Span jaegerSpan = Adapter.toJaeger(span); - - String rebuildTraceId = - traceIdFromLongs(jaegerSpan.getTraceIdHigh(), jaegerSpan.getTraceIdLow()); - assertThat(rebuildTraceId).isEqualTo(span.getTraceId()); - assertThat(spanIdFromLong(jaegerSpan.getSpanId())).isEqualTo(span.getSpanId()); - assertThat(jaegerSpan.getOperationName()).isEqualTo("GET /api/endpoint"); - assertThat(jaegerSpan.getStartTime()).isEqualTo(MILLISECONDS.toMicros(startMs)); - assertThat(jaegerSpan.getDuration()).isEqualTo(MILLISECONDS.toMicros(duration)); - - assertThat(jaegerSpan.getTagsSize()).isEqualTo(8); - assertThat(getValue(jaegerSpan.getTags(), Adapter.KEY_SPAN_KIND).getVStr()).isEqualTo("server"); - assertThat(getValue(jaegerSpan.getTags(), Adapter.KEY_SPAN_STATUS_CODE).getVLong()) - .isEqualTo(0); - assertThat(getValue(jaegerSpan.getTags(), Adapter.KEY_SPAN_STATUS_MESSAGE).getVStr()) - .isEqualTo("ok!"); - assertThat(getValue(jaegerSpan.getTags(), Adapter.KEY_DROPPED_EVENTS_COUNT).getVLong()) - .isEqualTo(1); - assertThat(getValue(jaegerSpan.getTags(), Adapter.KEY_DROPPED_ATTRIBUTES_COUNT).getVLong()) - .isEqualTo(3); - - assertThat(jaegerSpan.getLogsSize()).isEqualTo(1); - Log log = jaegerSpan.getLogs().get(0); - assertThat(getValue(log.getFields(), Adapter.KEY_LOG_EVENT).getVStr()) - .isEqualTo("the log message"); - assertThat(getValue(log.getFields(), "foo").getVStr()).isEqualTo("bar"); - - assertThat(jaegerSpan.getReferencesSize()).isEqualTo(2); - - assertHasFollowsFrom(jaegerSpan); - assertHasParent(jaegerSpan); - } - - @Test - void testThriftSpan_internal() { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - - SpanData span = getSpanData(startMs, endMs, SpanKind.INTERNAL); - - // test - io.jaegertracing.thriftjava.Span jaegerSpan = Adapter.toJaeger(span); - - assertThat(jaegerSpan.getTagsSize()).isEqualTo(5); - assertThat(getValue(jaegerSpan.getTags(), Adapter.KEY_SPAN_KIND)).isNull(); - } - - @Test - void testJaegerLogs() { - // prepare - EventData eventsData = getTimedEvent(); - - // test - Collection logs = Adapter.toJaegerLogs(Collections.singletonList(eventsData)); - - // verify - assertThat(logs).hasSize(1); - } - - @Test - void testJaegerLog() { - // prepare - EventData event = getTimedEvent(); - - // test - Log log = Adapter.toJaegerLog(event); - - // verify - assertThat(log.getFieldsSize()).isEqualTo(2); - - assertThat(getValue(log.getFields(), Adapter.KEY_LOG_EVENT).getVStr()) - .isEqualTo("the log message"); - assertThat(getValue(log.getFields(), "foo").getVStr()).isEqualTo("bar"); - assertThat(getValue(log.getFields(), Adapter.KEY_EVENT_DROPPED_ATTRIBUTES_COUNT)).isNull(); - } - - @Test - void jaegerLog_droppedAttributes() { - EventData event = getTimedEvent(3); - - // test - Log log = Adapter.toJaegerLog(event); - - // verify - assertThat(getValue(log.getFields(), Adapter.KEY_EVENT_DROPPED_ATTRIBUTES_COUNT).getVLong()) - .isEqualTo(2); - } - - @Test - void testKeyValue() { - // test - Tag kvB = Adapter.toTag(booleanKey("valueB"), true); - Tag kvD = Adapter.toTag(doubleKey("valueD"), 1.); - Tag kvI = Adapter.toTag(longKey("valueI"), 2L); - Tag kvS = Adapter.toTag(stringKey("valueS"), "foobar"); - Tag kvArrayB = Adapter.toTag(booleanArrayKey("valueArrayB"), Arrays.asList(true, false)); - Tag kvArrayD = Adapter.toTag(doubleArrayKey("valueArrayD"), Arrays.asList(1.2345, 6.789)); - Tag kvArrayI = Adapter.toTag(longArrayKey("valueArrayI"), Arrays.asList(12345L, 67890L)); - Tag kvArrayS = Adapter.toTag(stringArrayKey("valueArrayS"), Arrays.asList("foobar", "barfoo")); - - // verify - assertThat(kvB.isVBool()).isTrue(); - - assertThat(kvD.getVDouble()).isEqualTo(1); - assertThat(kvI.getVLong()).isEqualTo(2); - assertThat(kvS.getVStr()).isEqualTo("foobar"); - assertThat(kvArrayB.getVStr()).isEqualTo("[true,false]"); - assertThat(kvArrayD.getVStr()).isEqualTo("[1.2345,6.789]"); - assertThat(kvArrayI.getVStr()).isEqualTo("[12345,67890]"); - assertThat(kvArrayS.getVStr()).isEqualTo("[\"foobar\",\"barfoo\"]"); - } - - @Test - void testSpanRefs() { - // prepare - LinkData link = - LinkData.create(createSpanContext("00000000000000000000000000cba123", "0000000000fed456")); - - // test - Collection spanRefs = Adapter.toSpanRefs(Collections.singletonList(link)); - - // verify - assertThat(spanRefs).hasSize(1); // the actual span ref is tested in another test - } - - @Test - void testSpanRef() { - // prepare - LinkData link = LinkData.create(createSpanContext(TRACE_ID, SPAN_ID)); - - // test - SpanRef spanRef = Adapter.toSpanRef(link); - - // verify - assertThat(spanIdFromLong(spanRef.getSpanId())).isEqualTo(SPAN_ID); - assertThat(traceIdFromLongs(spanRef.getTraceIdHigh(), spanRef.getTraceIdLow())) - .isEqualTo(TRACE_ID); - assertThat(spanRef.getRefType()).isEqualTo(SpanRefType.FOLLOWS_FROM); - } - - @Test - void testStatusNotUnset() { - long startMs = System.currentTimeMillis(); - long endMs = startMs + 900; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(createSpanContext(TRACE_ID, SPAN_ID)) - .setName("GET /api/endpoint") - .setStartEpochNanos(MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(MILLISECONDS.toNanos(endMs)) - .setKind(SpanKind.SERVER) - .setStatus(StatusData.error()) - .setTotalRecordedEvents(0) - .setTotalRecordedLinks(0) - .build(); - - assertThat(Adapter.toJaeger(span)).isNotNull(); - } - - @Test - void testSpanError() { - Attributes attributes = - Attributes.of( - stringKey("error.type"), - this.getClass().getName(), - stringKey("error.message"), - "server error"); - long startMs = System.currentTimeMillis(); - long endMs = startMs + 900; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(createSpanContext(TRACE_ID, SPAN_ID)) - .setName("GET /api/endpoint") - .setStartEpochNanos(MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(MILLISECONDS.toNanos(endMs)) - .setKind(SpanKind.SERVER) - .setStatus(StatusData.error()) - .setAttributes(attributes) - .setTotalRecordedEvents(0) - .setTotalRecordedLinks(0) - .build(); - - io.jaegertracing.thriftjava.Span jaegerSpan = Adapter.toJaeger(span); - assertThat(getValue(jaegerSpan.getTags(), "error.type").getVStr()) - .isEqualTo(this.getClass().getName()); - assertThat(getValue(jaegerSpan.getTags(), "error").isVBool()).isTrue(); - } - - private static EventData getTimedEvent() { - return getTimedEvent(-1); - } - - private static EventData getTimedEvent(int totalAttributeCount) { - long epochNanos = MILLISECONDS.toNanos(System.currentTimeMillis()); - Attributes attributes = Attributes.of(stringKey("foo"), "bar"); - if (totalAttributeCount <= 0) { - totalAttributeCount = attributes.size(); - } - return EventData.create(epochNanos, "the log message", attributes, totalAttributeCount); - } - - private static SpanData getSpanData(long startMs, long endMs, SpanKind kind) { - return getSpanData(startMs, endMs, kind, 1, 1); - } - - private static SpanData getSpanData( - long startMs, long endMs, SpanKind kind, int totalRecordedEvents, int totalAttributeCount) { - Attributes attributes = Attributes.of(booleanKey("valueB"), true); - - LinkData link = LinkData.create(createSpanContext(LINK_TRACE_ID, LINK_SPAN_ID), attributes); - - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(createSpanContext(TRACE_ID, SPAN_ID)) - .setParentSpanContext( - SpanContext.create( - TRACE_ID, PARENT_SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(MILLISECONDS.toNanos(endMs)) - .setAttributes(Attributes.of(booleanKey("valueB"), true)) - .setTotalAttributeCount(totalAttributeCount) - .setEvents(Collections.singletonList(getTimedEvent())) - .setTotalRecordedEvents(totalRecordedEvents) - .setLinks(Collections.singletonList(link)) - .setTotalRecordedLinks(1) - .setKind(kind) - .setResource(Resource.create(Attributes.empty())) - .setStatus(StatusData.create(StatusCode.OK, "ok!")) - .build(); - } - - private static SpanContext createSpanContext(String traceId, String spanId) { - return SpanContext.create(traceId, spanId, TraceFlags.getDefault(), TraceState.getDefault()); - } - - @Nullable - private static Tag getValue(List tagsList, String s) { - for (Tag kv : tagsList) { - if (kv.getKey().equals(s)) { - return kv; - } - } - return null; - } - - private static void assertHasFollowsFrom(io.jaegertracing.thriftjava.Span jaegerSpan) { - boolean found = false; - for (SpanRef spanRef : jaegerSpan.getReferences()) { - - if (SpanRefType.FOLLOWS_FROM.equals(spanRef.getRefType())) { - assertThat(traceIdFromLongs(spanRef.getTraceIdHigh(), spanRef.getTraceIdLow())) - .isEqualTo(LINK_TRACE_ID); - assertThat(spanIdFromLong(spanRef.getSpanId())).isEqualTo(LINK_SPAN_ID); - found = true; - } - } - assertThat(found).isTrue(); - } - - private static void assertHasParent(io.jaegertracing.thriftjava.Span jaegerSpan) { - boolean found = false; - for (SpanRef spanRef : jaegerSpan.getReferences()) { - if (SpanRefType.CHILD_OF.equals(spanRef.getRefType())) { - assertThat(traceIdFromLongs(spanRef.getTraceIdHigh(), spanRef.getTraceIdLow())) - .isEqualTo(TRACE_ID); - assertThat(spanIdFromLong(spanRef.getSpanId())).isEqualTo(PARENT_SPAN_ID); - found = true; - } - } - assertThat(found).isTrue(); - assertThat(spanIdFromLong(jaegerSpan.getParentSpanId())).isEqualTo(PARENT_SPAN_ID); - } - - private static String traceIdFromLongs(long high, long low) { - return hex.encode( - ByteBuffer.allocate(16).order(ByteOrder.BIG_ENDIAN).putLong(high).putLong(low).array()); - } - - private static String spanIdFromLong(long id) { - return hex.encode(ByteBuffer.allocate(8).order(ByteOrder.BIG_ENDIAN).putLong(id).array()); - } -} diff --git a/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftIntegrationTest.java b/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftIntegrationTest.java deleted file mode 100644 index e0257222ba1..00000000000 --- a/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftIntegrationTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger.thrift; - -import com.fasterxml.jackson.core.TreeNode; -import com.fasterxml.jackson.jr.ob.JSON; -import com.fasterxml.jackson.jr.stree.JacksonJrsTreeCodec; -import io.opentelemetry.api.OpenTelemetry; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.sdk.OpenTelemetrySdk; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.time.Duration; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; -import org.slf4j.LoggerFactory; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.output.Slf4jLogConsumer; -import org.testcontainers.containers.wait.strategy.Wait; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -@Testcontainers(disabledWithoutDocker = true) -class JaegerThriftIntegrationTest { - private static final OkHttpClient client = new OkHttpClient(); - - private static final int QUERY_PORT = 16686; - private static final int THRIFT_HTTP_PORT = 14268; - private static final int HEALTH_PORT = 14269; - private static final String SERVICE_NAME = "E2E-test"; - private static final String JAEGER_URL = "http://localhost"; - - @Container - public static GenericContainer jaegerContainer = - new GenericContainer<>("ghcr.io/open-telemetry/opentelemetry-java/jaeger:1.32") - .withExposedPorts(THRIFT_HTTP_PORT, QUERY_PORT, HEALTH_PORT) - .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("jaeger"))) - .waitingFor(Wait.forHttp("/").forPort(HEALTH_PORT)); - - @Test - void testJaegerIntegration() { - OpenTelemetry openTelemetry = initOpenTelemetry(); - imitateWork(openTelemetry); - Awaitility.await() - .atMost(Duration.ofSeconds(30)) - .until(JaegerThriftIntegrationTest::assertJaegerHasATrace); - } - - private static OpenTelemetry initOpenTelemetry() { - Integer mappedPort = jaegerContainer.getMappedPort(THRIFT_HTTP_PORT); - - SpanExporter jaegerExporter = - JaegerThriftSpanExporter.builder() - .setEndpoint(JAEGER_URL + ":" + mappedPort + "/api/traces") - .build(); - return OpenTelemetrySdk.builder() - .setTracerProvider( - SdkTracerProvider.builder() - .addSpanProcessor(SimpleSpanProcessor.create(jaegerExporter)) - .setResource( - Resource.getDefault().toBuilder() - .put(ResourceAttributes.SERVICE_NAME, SERVICE_NAME) - .build()) - .build()) - .build(); - } - - private void imitateWork(OpenTelemetry openTelemetry) { - Span span = - openTelemetry.getTracer(getClass().getCanonicalName()).spanBuilder("Test span").startSpan(); - span.addEvent("some event"); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - span.end(); - } - - private static boolean assertJaegerHasATrace() { - try { - Integer mappedPort = jaegerContainer.getMappedPort(QUERY_PORT); - String url = - String.format( - "%s/api/traces?service=%s", - String.format(JAEGER_URL + ":%d", mappedPort), SERVICE_NAME); - - Request request = - new Request.Builder() - .url(url) - .header("Content-Type", "application/json") - .header("Accept", "application/json") - .build(); - - TreeNode json; - try (Response response = client.newCall(request).execute()) { - json = - JSON.builder() - .treeCodec(new JacksonJrsTreeCodec()) - .build() - .treeFrom(response.body().byteStream()); - } - - return json.get("data").get(0).get("traceID") != null; - } catch (Exception e) { - return false; - } - } -} diff --git a/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporterTest.java b/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporterTest.java deleted file mode 100644 index c4f77f539b9..00000000000 --- a/exporters/jaeger-thrift/src/test/java/io/opentelemetry/exporter/jaeger/thrift/JaegerThriftSpanExporterTest.java +++ /dev/null @@ -1,263 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger.thrift; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.verify; - -import io.jaegertracing.internal.exceptions.SenderException; -import io.jaegertracing.thrift.internal.senders.ThriftSender; -import io.jaegertracing.thriftjava.Process; -import io.jaegertracing.thriftjava.Span; -import io.jaegertracing.thriftjava.SpanRef; -import io.jaegertracing.thriftjava.SpanRefType; -import io.jaegertracing.thriftjava.Tag; -import io.jaegertracing.thriftjava.TagType; -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class JaegerThriftSpanExporterTest { - - private static final String TRACE_ID = "a0000000000000000000000000abc123"; - private static final long TRACE_ID_HIGH = 0xa000000000000000L; - private static final long TRACE_ID_LOW = 0x0000000000abc123L; - private static final String SPAN_ID = "00000f0000def456"; - private static final long SPAN_ID_LONG = 0x00000f0000def456L; - private static final String SPAN_ID_2 = "00a0000000aef789"; - private static final long SPAN_ID_2_LONG = 0x00a0000000aef789L; - private static final SpanContext SPAN_CONTEXT = - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()); - private static final SpanContext SPAN_CONTEXT_2 = - SpanContext.create(TRACE_ID, SPAN_ID_2, TraceFlags.getDefault(), TraceState.getDefault()); - - private JaegerThriftSpanExporter exporter; - @Mock private ThriftSender thriftSender; - - @BeforeEach - void beforeEach() { - exporter = JaegerThriftSpanExporter.builder().setThriftSender(thriftSender).build(); - } - - @Test - void testExport() throws SenderException, UnknownHostException { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(SPAN_CONTEXT) - .setParentSpanContext(SPAN_CONTEXT_2) - .setName("GET /api/endpoint") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setStatus(StatusData.ok()) - .setKind(SpanKind.CONSUMER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setResource( - Resource.create( - Attributes.of( - ResourceAttributes.SERVICE_NAME, - "myServiceName", - AttributeKey.stringKey("resource-attr-key"), - "resource-attr-value"))) - .build(); - - // test - CompletableResultCode result = exporter.export(Collections.singletonList(span)); - result.join(1, TimeUnit.SECONDS); - assertThat(result.isSuccess()).isEqualTo(true); - - // verify - Process expectedProcess = new Process("myServiceName"); - expectedProcess.addToTags( - new Tag("jaeger.version", TagType.STRING).setVStr("opentelemetry-java")); - expectedProcess.addToTags( - new Tag("ip", TagType.STRING).setVStr(InetAddress.getLocalHost().getHostAddress())); - expectedProcess.addToTags( - new Tag("hostname", TagType.STRING).setVStr(InetAddress.getLocalHost().getHostName())); - expectedProcess.addToTags( - new Tag("resource-attr-key", TagType.STRING).setVStr("resource-attr-value")); - expectedProcess.addToTags(new Tag("service.name", TagType.STRING).setVStr("myServiceName")); - - Span expectedSpan = - new Span() - .setTraceIdHigh(TRACE_ID_HIGH) - .setTraceIdLow(TRACE_ID_LOW) - .setSpanId(SPAN_ID_LONG) - .setOperationName("GET /api/endpoint") - .setReferences( - Collections.singletonList( - new SpanRef() - .setSpanId(SPAN_ID_2_LONG) - .setTraceIdHigh(TRACE_ID_HIGH) - .setTraceIdLow(TRACE_ID_LOW) - .setRefType(SpanRefType.CHILD_OF))) - .setParentSpanId(SPAN_ID_2_LONG) - .setStartTime(TimeUnit.MILLISECONDS.toMicros(startMs)) - .setDuration(TimeUnit.MILLISECONDS.toMicros(duration)) - .setLogs(Collections.emptyList()); - expectedSpan.addToTags(new Tag("span.kind", TagType.STRING).setVStr("consumer")); - expectedSpan.addToTags(new Tag("otel.status_code", TagType.STRING).setVStr("OK")); - expectedSpan.addToTags( - new Tag("otel.scope.name", TagType.STRING).setVStr("io.opentelemetry.auto")); - expectedSpan.addToTags( - new Tag("otel.library.name", TagType.STRING).setVStr("io.opentelemetry.auto")); - expectedSpan.addToTags(new Tag("otel.scope.version", TagType.STRING).setVStr("1.0.0")); - expectedSpan.addToTags(new Tag("otel.library.version", TagType.STRING).setVStr("1.0.0")); - - List expectedSpans = Collections.singletonList(expectedSpan); - verify(thriftSender).send(expectedProcess, expectedSpans); - } - - @Test - void testExportMultipleResources() throws SenderException, UnknownHostException { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(SPAN_CONTEXT) - .setName("GET /api/endpoint/1") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setStatus(StatusData.ok()) - .setKind(SpanKind.CONSUMER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setResource( - Resource.create( - Attributes.of( - ResourceAttributes.SERVICE_NAME, - "myServiceName1", - AttributeKey.stringKey("resource-attr-key-1"), - "resource-attr-value-1"))) - .build(); - - SpanData span2 = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(SPAN_CONTEXT_2) - .setName("GET /api/endpoint/2") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setStatus(StatusData.ok()) - .setKind(SpanKind.CONSUMER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setResource( - Resource.create( - Attributes.of( - ResourceAttributes.SERVICE_NAME, - "myServiceName2", - AttributeKey.stringKey("resource-attr-key-2"), - "resource-attr-value-2"))) - .build(); - - // test - CompletableResultCode result = exporter.export(Arrays.asList(span, span2)); - result.join(1, TimeUnit.SECONDS); - assertThat(result.isSuccess()).isEqualTo(true); - - // verify - Process expectedProcess1 = new Process("myServiceName1"); - expectedProcess1.addToTags( - new Tag("jaeger.version", TagType.STRING).setVStr("opentelemetry-java")); - expectedProcess1.addToTags( - new Tag("ip", TagType.STRING).setVStr(InetAddress.getLocalHost().getHostAddress())); - expectedProcess1.addToTags( - new Tag("hostname", TagType.STRING).setVStr(InetAddress.getLocalHost().getHostName())); - expectedProcess1.addToTags( - new Tag("resource-attr-key-1", TagType.STRING).setVStr("resource-attr-value-1")); - expectedProcess1.addToTags(new Tag("service.name", TagType.STRING).setVStr("myServiceName1")); - - Process expectedProcess2 = new Process("myServiceName2"); - expectedProcess2.addToTags( - new Tag("jaeger.version", TagType.STRING).setVStr("opentelemetry-java")); - expectedProcess2.addToTags( - new Tag("ip", TagType.STRING).setVStr(InetAddress.getLocalHost().getHostAddress())); - expectedProcess2.addToTags( - new Tag("hostname", TagType.STRING).setVStr(InetAddress.getLocalHost().getHostName())); - expectedProcess2.addToTags( - new Tag("resource-attr-key-2", TagType.STRING).setVStr("resource-attr-value-2")); - expectedProcess2.addToTags(new Tag("service.name", TagType.STRING).setVStr("myServiceName2")); - - Span expectedSpan1 = - new Span() - .setTraceIdHigh(TRACE_ID_HIGH) - .setTraceIdLow(TRACE_ID_LOW) - .setSpanId(SPAN_ID_LONG) - .setOperationName("GET /api/endpoint/1") - .setReferences(Collections.emptyList()) - .setStartTime(TimeUnit.MILLISECONDS.toMicros(startMs)) - .setDuration(TimeUnit.MILLISECONDS.toMicros(duration)) - .setLogs(Collections.emptyList()); - expectedSpan1.addToTags(new Tag("span.kind", TagType.STRING).setVStr("consumer")); - expectedSpan1.addToTags(new Tag("otel.status_code", TagType.STRING).setVStr("OK")); - expectedSpan1.addToTags( - new Tag("otel.scope.name", TagType.STRING).setVStr("io.opentelemetry.auto")); - expectedSpan1.addToTags( - new Tag("otel.library.name", TagType.STRING).setVStr("io.opentelemetry.auto")); - expectedSpan1.addToTags(new Tag("otel.scope.version", TagType.STRING).setVStr("1.0.0")); - expectedSpan1.addToTags(new Tag("otel.library.version", TagType.STRING).setVStr("1.0.0")); - - Span expectedSpan2 = - new Span() - .setTraceIdHigh(TRACE_ID_HIGH) - .setTraceIdLow(TRACE_ID_LOW) - .setSpanId(SPAN_ID_2_LONG) - .setOperationName("GET /api/endpoint/2") - .setReferences(Collections.emptyList()) - .setStartTime(TimeUnit.MILLISECONDS.toMicros(startMs)) - .setDuration(TimeUnit.MILLISECONDS.toMicros(duration)) - .setLogs(Collections.emptyList()); - expectedSpan2.addToTags(new Tag("span.kind", TagType.STRING).setVStr("consumer")); - expectedSpan2.addToTags(new Tag("otel.status_code", TagType.STRING).setVStr("OK")); - expectedSpan2.addToTags( - new Tag("otel.scope.name", TagType.STRING).setVStr("io.opentelemetry.auto")); - expectedSpan2.addToTags( - new Tag("otel.library.name", TagType.STRING).setVStr("io.opentelemetry.auto")); - expectedSpan2.addToTags(new Tag("otel.scope.version", TagType.STRING).setVStr("1.0.0")); - expectedSpan2.addToTags(new Tag("otel.library.version", TagType.STRING).setVStr("1.0.0")); - - verify(thriftSender).send(expectedProcess2, Collections.singletonList(expectedSpan2)); - verify(thriftSender).send(expectedProcess1, Collections.singletonList(expectedSpan1)); - } -} diff --git a/exporters/jaeger/README.md b/exporters/jaeger/README.md deleted file mode 100644 index 7c4df73ef9b..00000000000 --- a/exporters/jaeger/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# OpenTelemetry - Jaeger Exporter - gRPC - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry exporter, sending span data to Jaeger via gRPC. - -## Configuration - -The Jaeger gRPC span exporter can be configured programmatically. - -An example of simple Jaeger gRPC exporter initialization. In this case -spans will be sent to a Jaeger gRPC endpoint running on `localhost`: - -```java -JaegerGrpcSpanExporter exporter = - JaegerGrpcSpanExporter.builder() - .setEndpoint("http://localhost:14250") - .build(); -``` - -If you need configuration via environment variables and/or system properties, you will want to use -the [autoconfigure](../../sdk-extensions/autoconfigure) module. - -## Compatibility - -As with the OpenTelemetry SDK itself, this exporter is compatible with Java 8+ and Android API level 24+. - -## Proto files - -The proto files in this repository were copied over from the [Jaeger main repository][proto-origin]. -At this moment, they have to be manually synchronized, but a [discussion exists][proto-discussion] on how to properly consume them in a more appropriate manner. - -[proto-origin]: https://github.com/jaegertracing/jaeger/tree/5b8c1f40f932897b9322bf3f110d830536ae4c71/model/proto -[proto-discussion]: https://github.com/open-telemetry/opentelemetry-java/issues/235 -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-jaeger.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-jaeger diff --git a/exporters/jaeger/build.gradle.kts b/exporters/jaeger/build.gradle.kts deleted file mode 100644 index da02611162b..00000000000 --- a/exporters/jaeger/build.gradle.kts +++ /dev/null @@ -1,49 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") - - id("com.squareup.wire") -} - -description = "OpenTelemetry - Jaeger Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.jaeger") - -dependencies { - api(project(":sdk:all")) - - protoSource(project(":exporters:jaeger-proto")) - - // TODO(anuraaga): otlp-common has a lot of code not specific to OTLP now. As it's just internal - // code, this mysterious dependency is possibly still OK but we may need a rename or splitting. - implementation(project(":exporters:otlp:common")) - implementation(project(":semconv")) - - compileOnly("io.grpc:grpc-stub") - - implementation("com.fasterxml.jackson.jr:jackson-jr-objects") - - testImplementation(project(":exporters:jaeger-proto")) - - testImplementation("com.fasterxml.jackson.jr:jackson-jr-stree") - testImplementation("com.google.protobuf:protobuf-java-util") - testImplementation("com.linecorp.armeria:armeria-junit5") - testImplementation("com.linecorp.armeria:armeria-grpc-protocol") - testImplementation("com.squareup.okhttp3:okhttp") - testImplementation("org.testcontainers:junit-jupiter") - - testImplementation(project(":sdk:testing")) -} - -wire { - custom { - customHandlerClass = "io.opentelemetry.gradle.ProtoFieldsWireHandler" - } -} - -sourceSets { - main { - java.srcDir("$buildDir/generated/source/wire") - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/BatchMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/BatchMarshaler.java deleted file mode 100644 index 4900b7a47d9..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/BatchMarshaler.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.Batch; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.io.IOException; -import java.util.List; - -final class BatchMarshaler extends MarshalerWithSize { - - private final SpanMarshaler[] spans; - private final ProcessMarshaler process; - - static BatchMarshaler create(List spans, Resource resource) { - SpanMarshaler[] spanMarshalers = SpanMarshaler.createRepeated(spans); - ProcessMarshaler processMarshaler = ProcessMarshaler.create(resource); - return new BatchMarshaler(spanMarshalers, processMarshaler); - } - - BatchMarshaler(SpanMarshaler[] spans, ProcessMarshaler process) { - super(calculateSize(spans, process)); - this.spans = spans; - this.process = process; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeRepeatedMessage(Batch.SPANS, spans); - output.serializeMessage(Batch.PROCESS, process); - } - - private static int calculateSize(SpanMarshaler[] spans, ProcessMarshaler process) { - int size = 0; - size += MarshalerUtil.sizeRepeatedMessage(Batch.SPANS, spans); - size += MarshalerUtil.sizeMessage(Batch.PROCESS, process); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporter.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporter.java deleted file mode 100644 index 9829968a3e8..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporter.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports spans to Jaeger via gRPC, using Jaeger's protobuf model. */ -@ThreadSafe -public final class JaegerGrpcSpanExporter implements SpanExporter { - - private static final String DEFAULT_HOST_NAME = "unknown"; - private static final AttributeKey CLIENT_VERSION_KEY = - AttributeKey.stringKey("jaeger.version"); - private static final String CLIENT_VERSION_VALUE = "opentelemetry-java"; - private static final AttributeKey HOSTNAME_KEY = AttributeKey.stringKey("hostname"); - private static final String IP_DEFAULT = "0.0.0.0"; - // Visible for testing - static final AttributeKey IP_KEY = AttributeKey.stringKey("ip"); - - private final GrpcExporter delegate; - - // Jaeger-specific resource information - private final Resource jaegerResource; - - JaegerGrpcSpanExporter(GrpcExporter delegate) { - this.delegate = delegate; - - String hostname; - String ipv4; - - try { - hostname = InetAddress.getLocalHost().getHostName(); - ipv4 = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException e) { - hostname = DEFAULT_HOST_NAME; - ipv4 = IP_DEFAULT; - } - - jaegerResource = - Resource.builder() - .put(CLIENT_VERSION_KEY, CLIENT_VERSION_VALUE) - .put(IP_KEY, ipv4) - .put(HOSTNAME_KEY, hostname) - .build(); - } - - /** - * Submits all the given spans in a single batch to the Jaeger collector. - * - * @param spans the list of sampled Spans to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection spans) { - List results = new ArrayList<>(); - spans.stream() - .collect(Collectors.groupingBy(SpanData::getResource)) - .forEach( - (resource, spanData) -> - results.add(delegate.export(buildRequest(resource, spanData), spanData.size()))); - - return CompletableResultCode.ofAll(results); - } - - private PostSpansRequestMarshaler buildRequest(Resource resource, List spans) { - Resource mergedResource = jaegerResource.merge(resource); - return PostSpansRequestMarshaler.create(spans, mergedResource); - } - - /** - * The Jaeger exporter does not batch spans, so this method will immediately return with success. - * - * @return always Success - */ - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static JaegerGrpcSpanExporterBuilder builder() { - return new JaegerGrpcSpanExporterBuilder(); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately - * cancelled. - */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } - - // Visible for testing - Resource getJaegerResource() { - return jaegerResource; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporterBuilder.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporterBuilder.java deleted file mode 100644 index 20bfda5cb1a..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporterBuilder.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.grpc.ManagedChannel; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.grpc.GrpcExporterBuilder; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder utility for this exporter. */ -public final class JaegerGrpcSpanExporterBuilder { - - private static final String GRPC_SERVICE_NAME = "jaeger.api_v2.CollectorService"; - - // Visible for testing - static final String GRPC_ENDPOINT_PATH = "/" + GRPC_SERVICE_NAME + "/PostSpans"; - - private static final String DEFAULT_ENDPOINT_URL = "http://localhost:14250"; - private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); - private static final long DEFAULT_TIMEOUT_SECS = 10; - - private final GrpcExporterBuilder delegate; - - JaegerGrpcSpanExporterBuilder() { - delegate = - GrpcExporter.builder( - "jaeger", - "span", - DEFAULT_TIMEOUT_SECS, - DEFAULT_ENDPOINT, - () -> MarshalerCollectorServiceGrpc::newFutureStub, - GRPC_SERVICE_NAME, - GRPC_ENDPOINT_PATH); - } - - /** - * Sets the managed channel to use when communicating with the backend. Takes precedence over - * {@link #setEndpoint(String)} if both are called. - * - * @param channel the channel to use. - * @return this. - * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the - * methods on this builder, please file an issue to let us know what it is. - */ - @Deprecated - public JaegerGrpcSpanExporterBuilder setChannel(ManagedChannel channel) { - delegate.setChannel(channel); - return this; - } - - /** - * Sets the Jaeger endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. - * The endpoint must start with either http:// or https://. - */ - public JaegerGrpcSpanExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of spans. If - * unset, defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public JaegerGrpcSpanExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of spans. If - * unset, defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public JaegerGrpcSpanExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - delegate.setTimeout(timeout); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public JaegerGrpcSpanExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** Sets the client key and chain to use for verifying servers when mTLS is enabled. */ - public JaegerGrpcSpanExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, metrics - * will not be collected. - */ - public JaegerGrpcSpanExporterBuilder setMeterProvider(MeterProvider meterProvider) { - requireNonNull(meterProvider, "meterProvider"); - delegate.setMeterProvider(meterProvider); - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance. - */ - public JaegerGrpcSpanExporter build() { - return new JaegerGrpcSpanExporter(delegate.build()); - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/KeyValueMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/KeyValueMarshaler.java deleted file mode 100644 index 09f8b2f5734..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/KeyValueMarshaler.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import com.fasterxml.jackson.jr.ob.JSON; -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.ProtoEnumInfo; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.KeyValue; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.ValueType; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -@SuppressWarnings({ - "checkstyle:LocalVariableName", - "checkstyle:MemberName", - "checkstyle:ParameterName", -}) -final class KeyValueMarshaler extends MarshalerWithSize { - - private static final byte[] EMPTY_BYTES = new byte[0]; - - private final byte[] keyUtf8; - private final ProtoEnumInfo valueType; - private final byte[] vStrUtf8; - private final boolean vBool; - private final long vInt64; - private final double vFloat64; - - static List createRepeated(Attributes attributes) { - if (attributes.isEmpty()) { - return new ArrayList<>(); - } - - List marshalers = new ArrayList<>(attributes.size()); - attributes.forEach((attributeKey, o) -> marshalers.add(create(attributeKey, o))); - return marshalers; - } - - static KeyValueMarshaler create(AttributeKey key, Object value) { - byte[] keyUtf8 = MarshalerUtil.toBytes(key.getKey()); - - // Default is the 0 value, string in this case - ProtoEnumInfo valueType = ValueType.STRING; - byte[] vStrUtf8 = EMPTY_BYTES; - boolean vBool = false; - long vInt64 = 0; - double vFloat64 = 0; - - switch (key.getType()) { - case STRING: - valueType = ValueType.STRING; - vStrUtf8 = MarshalerUtil.toBytes(((String) value)); - break; - case BOOLEAN: - valueType = ValueType.BOOL; - vBool = (boolean) value; - break; - case LONG: - valueType = ValueType.INT64; - vInt64 = (long) value; - break; - case DOUBLE: - valueType = ValueType.FLOAT64; - vFloat64 = (double) value; - break; - case STRING_ARRAY: - case BOOLEAN_ARRAY: - case LONG_ARRAY: - case DOUBLE_ARRAY: - valueType = ValueType.STRING; - try { - vStrUtf8 = JSON.std.asBytes(value); - } catch (IOException e) { - // Can't happen, just ignore it. - } - break; - } - - return new KeyValueMarshaler(keyUtf8, valueType, vStrUtf8, vBool, vInt64, vFloat64); - } - - KeyValueMarshaler( - byte[] keyUtf8, - ProtoEnumInfo valueType, - byte[] vStrUtf8, - boolean vBool, - long vInt64, - double vFloat64) { - super(calculateSize(keyUtf8, valueType, vStrUtf8, vBool, vInt64, vFloat64)); - this.keyUtf8 = keyUtf8; - this.valueType = valueType; - this.vStrUtf8 = vStrUtf8; - this.vBool = vBool; - this.vInt64 = vInt64; - this.vFloat64 = vFloat64; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeString(KeyValue.KEY, keyUtf8); - output.serializeEnum(KeyValue.V_TYPE, valueType); - output.serializeString(KeyValue.V_STR, vStrUtf8); - output.serializeBool(KeyValue.V_BOOL, vBool); - output.serializeInt64(KeyValue.V_INT64, vInt64); - output.serializeDouble(KeyValue.V_FLOAT64, vFloat64); - } - - private static int calculateSize( - byte[] keyUtf8, - ProtoEnumInfo valueType, - byte[] vStrUtf8, - boolean vBool, - long vInt64, - double vFloat64) { - int size = 0; - size += MarshalerUtil.sizeBytes(KeyValue.KEY, keyUtf8); - size += MarshalerUtil.sizeEnum(KeyValue.V_TYPE, valueType); - size += MarshalerUtil.sizeBytes(KeyValue.V_STR, vStrUtf8); - size += MarshalerUtil.sizeBool(KeyValue.V_BOOL, vBool); - size += MarshalerUtil.sizeInt64(KeyValue.V_INT64, vInt64); - size += MarshalerUtil.sizeDouble(KeyValue.V_FLOAT64, vFloat64); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/LogMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/LogMarshaler.java deleted file mode 100644 index be871489f0b..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/LogMarshaler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.Log; -import io.opentelemetry.sdk.trace.data.EventData; -import java.io.IOException; -import java.util.List; - -final class LogMarshaler extends MarshalerWithSize { - - private static final AttributeKey KEY_LOG_EVENT = AttributeKey.stringKey("event"); - private static final AttributeKey KEY_EVENT_DROPPED_ATTRIBUTES_COUNT = - AttributeKey.longKey("otel.event.dropped_attributes_count"); - - private final TimeMarshaler timestamp; - private final List fields; - - static LogMarshaler[] createRepeated(List events) { - int len = events.size(); - LogMarshaler[] marshalers = new LogMarshaler[len]; - for (int i = 0; i < len; i++) { - marshalers[i] = create(events.get(i)); - } - return marshalers; - } - - static LogMarshaler create(EventData event) { - TimeMarshaler timestamp = TimeMarshaler.create(event.getEpochNanos()); - - List fields = KeyValueMarshaler.createRepeated(event.getAttributes()); - - // name is a top-level property in OpenTelemetry - fields.add(KeyValueMarshaler.create(KEY_LOG_EVENT, event.getName())); - - int droppedAttributesCount = event.getDroppedAttributesCount(); - if (droppedAttributesCount > 0) { - fields.add( - KeyValueMarshaler.create( - KEY_EVENT_DROPPED_ATTRIBUTES_COUNT, (long) droppedAttributesCount)); - } - - return new LogMarshaler(timestamp, fields); - } - - LogMarshaler(TimeMarshaler timestamp, List fields) { - super(calculateSize(timestamp, fields)); - this.timestamp = timestamp; - this.fields = fields; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeMessage(Log.TIMESTAMP, timestamp); - output.serializeRepeatedMessage(Log.FIELDS, fields); - } - - private static int calculateSize(TimeMarshaler timestamp, List fields) { - int size = 0; - size += MarshalerUtil.sizeMessage(Log.TIMESTAMP, timestamp); - size += MarshalerUtil.sizeRepeatedMessage(Log.FIELDS, fields); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/MarshalerCollectorServiceGrpc.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/MarshalerCollectorServiceGrpc.java deleted file mode 100644 index 1f9be7be71b..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/MarshalerCollectorServiceGrpc.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import static io.grpc.MethodDescriptor.generateFullMethodName; - -import com.google.common.util.concurrent.ListenableFuture; -import io.grpc.CallOptions; -import io.grpc.Channel; -import io.grpc.MethodDescriptor; -import io.grpc.stub.ClientCalls; -import io.opentelemetry.exporter.internal.grpc.MarshalerInputStream; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import java.io.InputStream; - -// Adapted from the protoc generated code for CollectorServiceGrpc. -final class MarshalerCollectorServiceGrpc { - - private static final String SERVICE_NAME = "jaeger.api_v2.CollectorService"; - - private static final MethodDescriptor.Marshaller REQUEST_MARSHALLER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(PostSpansRequestMarshaler value) { - return new MarshalerInputStream(value); - } - - @Override - public PostSpansRequestMarshaler parse(InputStream stream) { - throw new UnsupportedOperationException("Only for serializing"); - } - }; - - private static final MethodDescriptor.Marshaller RESPONSE_MARSHALER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(PostSpansResponse value) { - throw new UnsupportedOperationException("Only for parsing"); - } - - @Override - public PostSpansResponse parse(InputStream stream) { - return PostSpansResponse.INSTANCE; - } - }; - - private static final MethodDescriptor - getPostSpansMethod = - MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.UNARY) - .setFullMethodName(generateFullMethodName(SERVICE_NAME, "PostSpans")) - .setRequestMarshaller(REQUEST_MARSHALLER) - .setResponseMarshaller(RESPONSE_MARSHALER) - .build(); - - static CollectorServiceFutureStub newFutureStub(Channel channel) { - return CollectorServiceFutureStub.newStub(CollectorServiceFutureStub::new, channel); - } - - static final class CollectorServiceFutureStub - extends MarshalerServiceStub< - PostSpansRequestMarshaler, PostSpansResponse, CollectorServiceFutureStub> { - private CollectorServiceFutureStub(Channel channel, CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected MarshalerCollectorServiceGrpc.CollectorServiceFutureStub build( - Channel channel, CallOptions callOptions) { - return new MarshalerCollectorServiceGrpc.CollectorServiceFutureStub(channel, callOptions); - } - - @Override - public ListenableFuture export(PostSpansRequestMarshaler request) { - return ClientCalls.futureUnaryCall( - getChannel().newCall(getPostSpansMethod, getCallOptions()), request); - } - } - - private MarshalerCollectorServiceGrpc() {} -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/PostSpansRequestMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/PostSpansRequestMarshaler.java deleted file mode 100644 index 69347f82c80..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/PostSpansRequestMarshaler.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.PostSpansRequest; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.io.IOException; -import java.util.List; - -final class PostSpansRequestMarshaler extends MarshalerWithSize { - - private final BatchMarshaler batch; - - static PostSpansRequestMarshaler create(List spans, Resource resource) { - return new PostSpansRequestMarshaler(BatchMarshaler.create(spans, resource)); - } - - PostSpansRequestMarshaler(BatchMarshaler batch) { - super(calculateSize(batch)); - this.batch = batch; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeMessage(PostSpansRequest.BATCH, batch); - } - - private static int calculateSize(BatchMarshaler batch) { - int size = 0; - size += MarshalerUtil.sizeMessage(PostSpansRequest.BATCH, batch); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/PostSpansResponse.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/PostSpansResponse.java deleted file mode 100644 index 3daa41ce560..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/PostSpansResponse.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -// A Java object to correspond to the gRPC response for the Collector.PostSpans method. If fields -// are added to the type in the future, this can be converted to an actual class. -// -// It may seem like Void could be used instead but gRPC does not allow response values to be -// null. -enum PostSpansResponse { - INSTANCE; -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/ProcessMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/ProcessMarshaler.java deleted file mode 100644 index a0634add365..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/ProcessMarshaler.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.Process; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.IOException; -import java.util.List; - -final class ProcessMarshaler extends MarshalerWithSize { - - private final byte[] serviceNameUtf8; - private final List tags; - - static ProcessMarshaler create(Resource resource) { - String serviceName = resource.getAttribute(ResourceAttributes.SERVICE_NAME); - if (serviceName == null || serviceName.isEmpty()) { - serviceName = Resource.getDefault().getAttribute(ResourceAttributes.SERVICE_NAME); - } - - return new ProcessMarshaler( - MarshalerUtil.toBytes(serviceName), - KeyValueMarshaler.createRepeated(resource.getAttributes())); - } - - ProcessMarshaler(byte[] serviceNameUtf8, List tags) { - super(calculateSize(serviceNameUtf8, tags)); - this.serviceNameUtf8 = serviceNameUtf8; - this.tags = tags; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeString(Process.SERVICE_NAME, serviceNameUtf8); - output.serializeRepeatedMessage(Process.TAGS, tags); - } - - private static int calculateSize(byte[] serviceNameUtf8, List tags) { - int size = 0; - size += MarshalerUtil.sizeBytes(Process.SERVICE_NAME, serviceNameUtf8); - size += MarshalerUtil.sizeRepeatedMessage(Process.TAGS, tags); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/SpanMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/SpanMarshaler.java deleted file mode 100644 index 40f2457eecf..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/SpanMarshaler.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import static io.opentelemetry.api.common.AttributeKey.booleanKey; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.Span; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.io.IOException; -import java.util.List; -import java.util.Locale; - -final class SpanMarshaler extends MarshalerWithSize { - - private static final AttributeKey KEY_ERROR = booleanKey("error"); - private static final AttributeKey KEY_DROPPED_ATTRIBUTES_COUNT = - AttributeKey.longKey("otel.dropped_attributes_count"); - private static final AttributeKey KEY_DROPPED_EVENTS_COUNT = - AttributeKey.longKey("otel.dropped_events_count"); - private static final AttributeKey KEY_SPAN_KIND = AttributeKey.stringKey("span.kind"); - private static final AttributeKey KEY_SPAN_STATUS_MESSAGE = - AttributeKey.stringKey("otel.status_description"); - private static final AttributeKey KEY_SPAN_STATUS_CODE = - AttributeKey.stringKey("otel.status_code"); - private static final AttributeKey KEY_INSTRUMENTATION_SCOPE_NAME = - AttributeKey.stringKey("otel.scope.name"); - private static final AttributeKey KEY_INSTRUMENTATION_SCOPE_VERSION = - AttributeKey.stringKey("otel.scope.version"); - private static final AttributeKey KEY_INSTRUMENTATION_LIBRARY_NAME = - AttributeKey.stringKey("otel.library.name"); - private static final AttributeKey KEY_INSTRUMENTATION_LIBRARY_VERSION = - AttributeKey.stringKey("otel.library.version"); - - private final String traceId; - private final String spanId; - private final byte[] operationNameUtf8; - private final TimeMarshaler startTime; - private final TimeMarshaler duration; - private final List tags; - private final LogMarshaler[] logs; - private final List references; - - static SpanMarshaler[] createRepeated(List spans) { - int len = spans.size(); - SpanMarshaler[] marshalers = new SpanMarshaler[len]; - for (int i = 0; i < len; i++) { - marshalers[i] = SpanMarshaler.create(spans.get(i)); - } - return marshalers; - } - - static SpanMarshaler create(SpanData span) { - String traceId = span.getSpanContext().getTraceId(); - String spanId = span.getSpanContext().getSpanId(); - byte[] operationNameUtf8 = MarshalerUtil.toBytes(span.getName()); - TimeMarshaler startTime = TimeMarshaler.create(span.getStartEpochNanos()); - TimeMarshaler duration = - TimeMarshaler.create(span.getEndEpochNanos() - span.getStartEpochNanos()); - - List tags = KeyValueMarshaler.createRepeated(span.getAttributes()); - int droppedAttributes = span.getTotalAttributeCount() - span.getAttributes().size(); - if (droppedAttributes > 0) { - tags.add(KeyValueMarshaler.create(KEY_DROPPED_ATTRIBUTES_COUNT, (long) droppedAttributes)); - } - - LogMarshaler[] logs = LogMarshaler.createRepeated(span.getEvents()); - int droppedEvents = span.getTotalRecordedEvents() - span.getEvents().size(); - if (droppedEvents > 0) { - tags.add(KeyValueMarshaler.create(KEY_DROPPED_EVENTS_COUNT, (long) droppedEvents)); - } - - List references = SpanRefMarshaler.createRepeated(span.getLinks()); - - // add the parent span - SpanContext parentSpanContext = span.getParentSpanContext(); - if (parentSpanContext.isValid()) { - references.add(SpanRefMarshaler.create(parentSpanContext)); - } - - if (span.getKind() != SpanKind.INTERNAL) { - tags.add( - KeyValueMarshaler.create(KEY_SPAN_KIND, span.getKind().name().toLowerCase(Locale.ROOT))); - } - - if (!span.getStatus().getDescription().isEmpty()) { - tags.add( - KeyValueMarshaler.create(KEY_SPAN_STATUS_MESSAGE, span.getStatus().getDescription())); - } - - if (span.getStatus().getStatusCode() != StatusCode.UNSET) { - tags.add( - KeyValueMarshaler.create(KEY_SPAN_STATUS_CODE, span.getStatus().getStatusCode().name())); - } - - tags.add( - KeyValueMarshaler.create( - KEY_INSTRUMENTATION_SCOPE_NAME, span.getInstrumentationScopeInfo().getName())); - // Include instrumentation library name for backwards compatibility - tags.add( - KeyValueMarshaler.create( - KEY_INSTRUMENTATION_LIBRARY_NAME, span.getInstrumentationScopeInfo().getName())); - - if (span.getInstrumentationScopeInfo().getVersion() != null) { - tags.add( - KeyValueMarshaler.create( - KEY_INSTRUMENTATION_SCOPE_VERSION, span.getInstrumentationScopeInfo().getVersion())); - // Include instrumentation library name for backwards compatibility - tags.add( - KeyValueMarshaler.create( - KEY_INSTRUMENTATION_LIBRARY_VERSION, - span.getInstrumentationScopeInfo().getVersion())); - } - - if (span.getStatus().getStatusCode() == StatusCode.ERROR) { - tags.add(KeyValueMarshaler.create(KEY_ERROR, true)); - } - - return new SpanMarshaler( - traceId, spanId, operationNameUtf8, startTime, duration, tags, logs, references); - } - - SpanMarshaler( - String traceId, - String spanId, - byte[] operationNameUtf8, - TimeMarshaler startTime, - TimeMarshaler duration, - List tags, - LogMarshaler[] logs, - List references) { - super( - calculateSize( - traceId, spanId, operationNameUtf8, startTime, duration, tags, logs, references)); - this.traceId = traceId; - this.spanId = spanId; - this.operationNameUtf8 = operationNameUtf8; - this.startTime = startTime; - this.duration = duration; - this.tags = tags; - this.logs = logs; - this.references = references; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeTraceId(Span.TRACE_ID, traceId); - output.serializeSpanId(Span.SPAN_ID, spanId); - output.serializeString(Span.OPERATION_NAME, operationNameUtf8); - output.serializeMessage(Span.START_TIME, startTime); - output.serializeMessage(Span.DURATION, duration); - output.serializeRepeatedMessage(Span.TAGS, tags); - output.serializeRepeatedMessage(Span.LOGS, logs); - output.serializeRepeatedMessage(Span.REFERENCES, references); - } - - private static int calculateSize( - String traceId, - String spanId, - byte[] operationNameUtf8, - TimeMarshaler startTime, - TimeMarshaler duration, - List tags, - LogMarshaler[] logs, - List references) { - int size = 0; - size += MarshalerUtil.sizeTraceId(Span.TRACE_ID, traceId); - size += MarshalerUtil.sizeSpanId(Span.SPAN_ID, spanId); - size += MarshalerUtil.sizeBytes(Span.OPERATION_NAME, operationNameUtf8); - size += MarshalerUtil.sizeMessage(Span.START_TIME, startTime); - size += MarshalerUtil.sizeMessage(Span.DURATION, duration); - size += MarshalerUtil.sizeRepeatedMessage(Span.TAGS, tags); - size += MarshalerUtil.sizeRepeatedMessage(Span.LOGS, logs); - size += MarshalerUtil.sizeRepeatedMessage(Span.REFERENCES, references); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/SpanRefMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/SpanRefMarshaler.java deleted file mode 100644 index a6dd61a418a..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/SpanRefMarshaler.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.ProtoEnumInfo; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.SpanRef; -import io.opentelemetry.exporter.jaeger.proto.api_v2.internal.SpanRefType; -import io.opentelemetry.sdk.trace.data.LinkData; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -final class SpanRefMarshaler extends MarshalerWithSize { - - private final String traceId; - private final String spanId; - private final ProtoEnumInfo refType; - - static List createRepeated(List links) { - List marshalers = new ArrayList<>(links.size()); - for (LinkData link : links) { - // we can assume that all links are *follows from* - // https://github.com/open-telemetry/opentelemetry-java/issues/475 - // https://github.com/open-telemetry/opentelemetry-java/pull/481/files#r312577862 - marshalers.add(create(link)); - ; - } - return marshalers; - } - - static SpanRefMarshaler create(SpanContext spanContext) { - return new SpanRefMarshaler( - spanContext.getTraceId(), spanContext.getSpanId(), SpanRefType.CHILD_OF); - } - - static SpanRefMarshaler create(LinkData link) { - return new SpanRefMarshaler( - link.getSpanContext().getTraceId(), - link.getSpanContext().getSpanId(), - SpanRefType.FOLLOWS_FROM); - } - - SpanRefMarshaler(String traceId, String spanId, ProtoEnumInfo refType) { - super(calculateSize(traceId, spanId, refType)); - this.traceId = traceId; - this.spanId = spanId; - this.refType = refType; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeTraceId(SpanRef.TRACE_ID, traceId); - output.serializeSpanId(SpanRef.SPAN_ID, spanId); - output.serializeEnum(SpanRef.REF_TYPE, refType); - } - - private static int calculateSize(String traceId, String spanId, ProtoEnumInfo refType) { - int size = 0; - size += MarshalerUtil.sizeTraceId(SpanRef.TRACE_ID, traceId); - size += MarshalerUtil.sizeSpanId(SpanRef.SPAN_ID, spanId); - size += MarshalerUtil.sizeEnum(SpanRef.REF_TYPE, refType); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/TimeMarshaler.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/TimeMarshaler.java deleted file mode 100644 index 961e5461133..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/TimeMarshaler.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.jaeger.internal.protobuf.internal.Time; -import java.io.IOException; -import java.util.concurrent.TimeUnit; - -// The wire format for Timestamp and Duration are exactly the same. Just implement one Marshaler -// for them. -final class TimeMarshaler extends MarshalerWithSize { - private static final long NANOS_PER_SECOND = TimeUnit.SECONDS.toNanos(1); - - private final long seconds; - private final int nanos; - - static TimeMarshaler create(long timeNanos) { - long seconds = timeNanos / NANOS_PER_SECOND; - int nanos = (int) (timeNanos % NANOS_PER_SECOND); - return new TimeMarshaler(seconds, nanos); - } - - TimeMarshaler(long seconds, int nanos) { - super(calculateSize(seconds, nanos)); - this.seconds = seconds; - this.nanos = nanos; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeInt64(Time.SECONDS, seconds); - output.serializeInt32(Time.NANOS, nanos); - } - - private static int calculateSize(long seconds, int nanos) { - int size = 0; - size += MarshalerUtil.sizeInt64(Time.SECONDS, seconds); - size += MarshalerUtil.sizeInt32(Time.NANOS, nanos); - return size; - } -} diff --git a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/package-info.java b/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/package-info.java deleted file mode 100644 index 23e486e2fd8..00000000000 --- a/exporters/jaeger/src/main/java/io/opentelemetry/exporter/jaeger/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -@ParametersAreNonnullByDefault -package io.opentelemetry.exporter.jaeger; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/jaeger/src/main/proto/README.md b/exporters/jaeger/src/main/proto/README.md deleted file mode 100644 index f36259bdd21..00000000000 --- a/exporters/jaeger/src/main/proto/README.md +++ /dev/null @@ -1 +0,0 @@ -Non-empty folder required for wire proto compiler. diff --git a/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporterTest.java b/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporterTest.java deleted file mode 100644 index b6a232a5d06..00000000000 --- a/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/JaegerGrpcSpanExporterTest.java +++ /dev/null @@ -1,363 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.fail; - -import com.google.protobuf.InvalidProtocolBufferException; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.server.ServiceRequestContext; -import com.linecorp.armeria.server.grpc.protocol.AbstractUnaryGrpcService; -import com.linecorp.armeria.testing.junit5.server.ServerExtension; -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.jaeger.proto.api_v2.Collector; -import io.opentelemetry.exporter.jaeger.proto.api_v2.Model; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; -import java.util.concurrent.LinkedBlockingDeque; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class JaegerGrpcSpanExporterTest { - private static final String TRACE_ID = "00000000000000000000000000abc123"; - private static final String SPAN_ID = "0000000000def456"; - private static final String SPAN_ID_2 = "0000000000aef789"; - - private static final BlockingQueue postedRequests = - new LinkedBlockingDeque<>(); - - @RegisterExtension - static final ServerExtension server = - new ServerExtension() { - @Override - protected void configure(ServerBuilder sb) { - sb.service( - JaegerGrpcSpanExporterBuilder.GRPC_ENDPOINT_PATH, - new AbstractUnaryGrpcService() { - @Override - protected CompletionStage handleMessage( - ServiceRequestContext ctx, byte[] message) { - try { - postedRequests.add(Collector.PostSpansRequest.parseFrom(message)); - } catch (InvalidProtocolBufferException e) { - CompletableFuture future = new CompletableFuture<>(); - future.completeExceptionally(e); - return future; - } - return CompletableFuture.completedFuture( - Collector.PostSpansResponse.getDefaultInstance().toByteArray()); - } - }); - } - }; - - private static JaegerGrpcSpanExporter exporter; - - @BeforeAll - static void setUp() { - exporter = - JaegerGrpcSpanExporter.builder() - .setEndpoint(server.httpUri().toString()) - .setMeterProvider(MeterProvider.noop()) - .build(); - } - - @AfterAll - static void tearDown() { - exporter.shutdown(); - } - - @AfterEach - void reset() { - postedRequests.clear(); - } - - @Test - void testExport() throws Exception { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setStatus(StatusData.ok()) - .setKind(SpanKind.CONSUMER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setResource( - Resource.create( - Attributes.of( - ResourceAttributes.SERVICE_NAME, - "myServiceName", - AttributeKey.stringKey("resource-attr-key"), - "resource-attr-value"))) - .build(); - - // test - CompletableResultCode result = exporter.export(Collections.singletonList(span)); - result.join(10, TimeUnit.SECONDS); - assertThat(result.isSuccess()).isEqualTo(true); - - // verify - assertThat(postedRequests).hasSize(1); - Model.Batch batch = postedRequests.poll().getBatch(); - assertThat(batch.getSpans(0).getOperationName()).isEqualTo("GET /api/endpoint"); - assertThat(SpanId.fromBytes(batch.getSpans(0).getSpanId().toByteArray())).isEqualTo(SPAN_ID); - - assertThat( - getTagValue(batch.getProcess().getTagsList(), "resource-attr-key") - .orElseThrow(() -> new AssertionError("resource-attr-key not found")) - .getVStr()) - .isEqualTo("resource-attr-value"); - - verifyBatch(batch); - assertThat(batch.getProcess().getServiceName()).isEqualTo("myServiceName"); - } - - @Test - void testExportMultipleResources() throws Exception { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())) - .setName("GET /api/endpoint/1") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setStatus(StatusData.ok()) - .setKind(SpanKind.CONSUMER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setResource( - Resource.create( - Attributes.of( - ResourceAttributes.SERVICE_NAME, - "myServiceName1", - AttributeKey.stringKey("resource-attr-key-1"), - "resource-attr-value-1"))) - .build(); - - SpanData span2 = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create( - TRACE_ID, SPAN_ID_2, TraceFlags.getSampled(), TraceState.getDefault())) - .setName("GET /api/endpoint/2") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setStatus(StatusData.ok()) - .setKind(SpanKind.CONSUMER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setResource( - Resource.create( - Attributes.of( - ResourceAttributes.SERVICE_NAME, - "myServiceName2", - AttributeKey.stringKey("resource-attr-key-2"), - "resource-attr-value-2"))) - .build(); - - // test - CompletableResultCode result = exporter.export(Arrays.asList(span, span2)); - result.join(10, TimeUnit.SECONDS); - assertThat(result.isSuccess()).isEqualTo(true); - - // verify - assertThat(postedRequests).hasSize(2); - List requests = new ArrayList<>(postedRequests); - assertThat(requests).hasSize(2); - for (Collector.PostSpansRequest request : requests) { - Model.Batch batch = request.getBatch(); - - verifyBatch(batch); - - Optional processTag = - getTagValue(batch.getProcess().getTagsList(), "resource-attr-key-1"); - Optional processTag2 = - getTagValue(batch.getProcess().getTagsList(), "resource-attr-key-2"); - if (processTag.isPresent()) { - assertThat(processTag2.isPresent()).isFalse(); - assertThat(batch.getSpans(0).getOperationName()).isEqualTo("GET /api/endpoint/1"); - assertThat(SpanId.fromBytes(batch.getSpans(0).getSpanId().toByteArray())) - .isEqualTo(SPAN_ID); - assertThat(processTag.get().getVStr()).isEqualTo("resource-attr-value-1"); - assertThat(batch.getProcess().getServiceName()).isEqualTo("myServiceName1"); - } else if (processTag2.isPresent()) { - assertThat(batch.getSpans(0).getOperationName()).isEqualTo("GET /api/endpoint/2"); - assertThat(SpanId.fromBytes(batch.getSpans(0).getSpanId().toByteArray())) - .isEqualTo(SPAN_ID_2); - assertThat(processTag2.get().getVStr()).isEqualTo("resource-attr-value-2"); - assertThat(batch.getProcess().getServiceName()).isEqualTo("myServiceName2"); - } else { - fail("No process tag resource-attr-key-1 or resource-attr-key-2"); - } - } - } - - private static void verifyBatch(Model.Batch batch) throws Exception { - assertThat(batch.getSpansCount()).isEqualTo(1); - assertThat(TraceId.fromBytes(batch.getSpans(0).getTraceId().toByteArray())).isEqualTo(TRACE_ID); - assertThat(batch.getProcess().getTagsCount()).isEqualTo(5); - - assertThat( - getSpanTagValue(batch.getSpans(0), "otel.scope.name") - .orElseThrow(() -> new AssertionError("otel.scope.name not found")) - .getVStr()) - .isEqualTo("io.opentelemetry.auto"); - - assertThat( - getSpanTagValue(batch.getSpans(0), "otel.library.name") - .orElseThrow(() -> new AssertionError("otel.library.name not found")) - .getVStr()) - .isEqualTo("io.opentelemetry.auto"); - - assertThat( - getSpanTagValue(batch.getSpans(0), "otel.library.version") - .orElseThrow(() -> new AssertionError("otel.library.version not found")) - .getVStr()) - .isEqualTo("1.0.0"); - - assertThat( - getSpanTagValue(batch.getSpans(0), "otel.scope.version") - .orElseThrow(() -> new AssertionError("otel.scope.version not found")) - .getVStr()) - .isEqualTo("1.0.0"); - - assertThat( - getTagValue(batch.getProcess().getTagsList(), "ip") - .orElseThrow(() -> new AssertionError("ip not found")) - .getVStr()) - .isEqualTo(exporter.getJaegerResource().getAttribute(JaegerGrpcSpanExporter.IP_KEY)); - - assertThat( - getTagValue(batch.getProcess().getTagsList(), "hostname") - .orElseThrow(() -> new AssertionError("hostname not found")) - .getVStr()) - .isEqualTo(InetAddress.getLocalHost().getHostName()); - - assertThat( - getTagValue(batch.getProcess().getTagsList(), "jaeger.version") - .orElseThrow(() -> new AssertionError("jaeger.version not found")) - .getVStr()) - .isEqualTo("opentelemetry-java"); - } - - private static Optional getSpanTagValue(Model.Span span, String tagKey) { - return getTagValue(span.getTagsList(), tagKey); - } - - private static Optional getTagValue(List tags, String tagKey) { - return tags.stream().filter(kv -> kv.getKey().equals(tagKey)).findFirst(); - } - - @Test - void validTrustedConfig() { - assertThatCode( - () -> - JaegerGrpcSpanExporter.builder() - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - } - - @Test - void validClientKeyConfig() { - assertThatCode( - () -> - JaegerGrpcSpanExporter.builder() - .setClientTls( - "foobar".getBytes(StandardCharsets.UTF_8), - "foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void invalidConfig() { - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setEndpoint("😺://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must be a URL: 😺://localhost") - .hasCauseInstanceOf(URISyntaxException.class); - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setEndpoint("localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); - assertThatThrownBy(() -> JaegerGrpcSpanExporter.builder().setEndpoint("gopher://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); - } - - @Test - void doubleShutdown() { - JaegerGrpcSpanExporter exporter = - JaegerGrpcSpanExporter.builder().setEndpoint(server.httpUri().toString()).build(); - assertThat(exporter.shutdown().join(1, TimeUnit.SECONDS).isSuccess()).isTrue(); - assertThat(exporter.shutdown().join(1, TimeUnit.SECONDS).isSuccess()).isTrue(); - } -} diff --git a/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/JaegerIntegrationTest.java b/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/JaegerIntegrationTest.java deleted file mode 100644 index b55986fafe4..00000000000 --- a/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/JaegerIntegrationTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import com.fasterxml.jackson.core.TreeNode; -import com.fasterxml.jackson.jr.ob.JSON; -import com.fasterxml.jackson.jr.stree.JacksonJrsTreeCodec; -import io.opentelemetry.api.OpenTelemetry; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.sdk.OpenTelemetrySdk; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.time.Duration; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.wait.strategy.Wait; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - -@Testcontainers(disabledWithoutDocker = true) -class JaegerIntegrationTest { - private static final OkHttpClient client = new OkHttpClient(); - - private static final int QUERY_PORT = 16686; - private static final int COLLECTOR_PORT = 14250; - private static final int HEALTH_PORT = 14269; - private static final String SERVICE_NAME = "E2E-test"; - private static final String JAEGER_URL = "http://localhost"; - - @Container - public static GenericContainer jaegerContainer = - new GenericContainer<>("ghcr.io/open-telemetry/opentelemetry-java/jaeger:1.32") - .withExposedPorts(COLLECTOR_PORT, QUERY_PORT, HEALTH_PORT) - .waitingFor(Wait.forHttp("/").forPort(HEALTH_PORT)); - - @Test - void testJaegerIntegration() { - OpenTelemetry openTelemetry = initOpenTelemetry(); - imitateWork(openTelemetry); - Awaitility.await() - .atMost(Duration.ofSeconds(30)) - .until(JaegerIntegrationTest::assertJaegerHaveTrace); - } - - private static OpenTelemetry initOpenTelemetry() { - SpanExporter jaegerExporter = - JaegerGrpcSpanExporter.builder() - .setEndpoint("http://localhost:" + jaegerContainer.getMappedPort(COLLECTOR_PORT)) - .setTimeout(Duration.ofSeconds(30)) - .build(); - return OpenTelemetrySdk.builder() - .setTracerProvider( - SdkTracerProvider.builder() - .addSpanProcessor(SimpleSpanProcessor.create(jaegerExporter)) - .setResource( - Resource.getDefault().toBuilder() - .put(ResourceAttributes.SERVICE_NAME, SERVICE_NAME) - .build()) - .build()) - .build(); - } - - private void imitateWork(OpenTelemetry openTelemetry) { - Span span = - openTelemetry.getTracer(getClass().getCanonicalName()).spanBuilder("Test span").startSpan(); - span.addEvent("some event"); - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - span.end(); - } - - private static boolean assertJaegerHaveTrace() { - try { - String url = - String.format( - "%s/api/traces?service=%s", - String.format(JAEGER_URL + ":%d", jaegerContainer.getMappedPort(QUERY_PORT)), - SERVICE_NAME); - - Request request = - new Request.Builder() - .url(url) - .header("Content-Type", "application/json") - .header("Accept", "application/json") - .build(); - - TreeNode json; - try (Response response = client.newCall(request).execute()) { - json = - JSON.builder() - .treeCodec(new JacksonJrsTreeCodec()) - .build() - .treeFrom(response.body().byteStream()); - } - - return json.get("data").get(0).get("traceID") != null; - } catch (Exception e) { - return false; - } - } -} diff --git a/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/PostSpansRequestMarshalerTest.java b/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/PostSpansRequestMarshalerTest.java deleted file mode 100644 index 00e10c2124e..00000000000 --- a/exporters/jaeger/src/test/java/io/opentelemetry/exporter/jaeger/PostSpansRequestMarshalerTest.java +++ /dev/null @@ -1,437 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.jaeger; - -import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; -import static io.opentelemetry.api.common.AttributeKey.doubleKey; -import static io.opentelemetry.api.common.AttributeKey.longArrayKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Message; -import com.google.protobuf.util.Durations; -import com.google.protobuf.util.Timestamps; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.jaeger.proto.api_v2.Model; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.LinkData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; -import org.junit.jupiter.api.Test; - -class PostSpansRequestMarshalerTest { - - private static final String KEY_LOG_EVENT = "event"; - private static final String KEY_EVENT_DROPPED_ATTRIBUTES_COUNT = - "otel.event.dropped_attributes_count"; - private static final String KEY_DROPPED_ATTRIBUTES_COUNT = "otel.dropped_attributes_count"; - private static final String KEY_DROPPED_EVENTS_COUNT = "otel.dropped_events_count"; - private static final String KEY_SPAN_KIND = "span.kind"; - - private static final String LINK_TRACE_ID = "00000000000000000000000000cba123"; - private static final String LINK_SPAN_ID = "0000000000fed456"; - private static final String TRACE_ID = "00000000000000000000000000abc123"; - private static final String SPAN_ID = "0000000000def456"; - private static final String PARENT_SPAN_ID = "0000000000aef789"; - - @Test - void testProtoSpans() { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - - SpanData span = getSpanData(startMs, endMs, SpanKind.SERVER); - List spans = Collections.singletonList(span); - - SpanMarshaler[] jaegerSpans = SpanMarshaler.createRepeated(spans); - - // the span contents are checked somewhere else - assertThat(jaegerSpans).hasSize(1); - } - - @Test - @SuppressWarnings({"ProtoTimestampGetSecondsGetNano", "ProtoDurationGetSecondsGetNano"}) - void testProtoSpan() { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - - SpanData span = getSpanData(startMs, endMs, SpanKind.SERVER, 2); - - // test - Model.Span jaegerSpan = parse(Model.Span.getDefaultInstance(), SpanMarshaler.create(span)); - assertThat(TraceId.fromBytes(jaegerSpan.getTraceId().toByteArray())) - .isEqualTo(span.getTraceId()); - assertThat(SpanId.fromBytes(jaegerSpan.getSpanId().toByteArray())).isEqualTo(span.getSpanId()); - assertThat(jaegerSpan.getOperationName()).isEqualTo("GET /api/endpoint"); - assertThat(jaegerSpan.getStartTime()).isEqualTo(Timestamps.fromMillis(startMs)); - assertThat(jaegerSpan.getDuration()).isEqualTo(Durations.fromMillis(duration)); - - assertThat(jaegerSpan.getTagsCount()).isEqualTo(7); - Model.KeyValue keyValue = getValue(jaegerSpan.getTagsList(), KEY_SPAN_KIND); - assertThat(keyValue).isNotNull(); - assertThat(keyValue.getVStr()).isEqualTo("server"); - - Model.KeyValue droppedAttributes = - getValue(jaegerSpan.getTagsList(), KEY_DROPPED_ATTRIBUTES_COUNT); - assertThat(droppedAttributes) - .isEqualTo( - Model.KeyValue.newBuilder() - .setKey(KEY_DROPPED_ATTRIBUTES_COUNT) - .setVType(Model.ValueType.INT64) - .setVInt64(2) - .build()); - - assertThat(jaegerSpan.getLogsCount()).isEqualTo(1); - Model.KeyValue droppedEvents = getValue(jaegerSpan.getTagsList(), KEY_DROPPED_EVENTS_COUNT); - assertThat(droppedEvents) - .isEqualTo( - Model.KeyValue.newBuilder() - .setKey(KEY_DROPPED_EVENTS_COUNT) - .setVType(Model.ValueType.INT64) - .setVInt64(1) - .build()); - - Model.Log log = jaegerSpan.getLogs(0); - keyValue = getValue(log.getFieldsList(), KEY_LOG_EVENT); - assertThat(keyValue).isNotNull(); - assertThat(keyValue.getVStr()).isEqualTo("the log message"); - keyValue = getValue(log.getFieldsList(), "foo"); - assertThat(keyValue).isNotNull(); - assertThat(keyValue.getVStr()).isEqualTo("bar"); - - assertThat(jaegerSpan.getReferencesCount()).isEqualTo(2); - - assertHasFollowsFrom(jaegerSpan); - assertHasParent(jaegerSpan); - } - - @Test - void testProtoSpan_internal() { - long duration = 900; // ms - long startMs = System.currentTimeMillis(); - long endMs = startMs + duration; - - SpanData span = getSpanData(startMs, endMs, SpanKind.INTERNAL); - - // test - Model.Span jaegerSpan = parse(Model.Span.getDefaultInstance(), SpanMarshaler.create(span)); - Model.KeyValue keyValue = getValue(jaegerSpan.getTagsList(), KEY_SPAN_KIND); - assertThat(keyValue).isNull(); - } - - @Test - void testJaegerLogs() { - // prepare - EventData eventsData = getTimedEvent(); - - // test - LogMarshaler[] logs = LogMarshaler.createRepeated(Collections.singletonList(eventsData)); - - // verify - assertThat(logs).hasSize(1); - } - - @Test - void testJaegerLog() { - // prepare - EventData event = getTimedEvent(); - - // test - Model.Log log = parse(Model.Log.getDefaultInstance(), LogMarshaler.create(event)); - - // verify - assertThat(log.getFieldsCount()).isEqualTo(2); - - Model.KeyValue keyValue = getValue(log.getFieldsList(), KEY_LOG_EVENT); - assertThat(keyValue).isNotNull(); - assertThat(keyValue.getVStr()).isEqualTo("the log message"); - keyValue = getValue(log.getFieldsList(), "foo"); - assertThat(keyValue).isNotNull(); - assertThat(keyValue.getVStr()).isEqualTo("bar"); - keyValue = getValue(log.getFieldsList(), KEY_EVENT_DROPPED_ATTRIBUTES_COUNT); - assertThat(keyValue).isNull(); - - // verify dropped_attributes_count - event = getTimedEvent(3); - log = parse(Model.Log.getDefaultInstance(), LogMarshaler.create(event)); - keyValue = getValue(log.getFieldsList(), KEY_EVENT_DROPPED_ATTRIBUTES_COUNT); - assertThat(keyValue).isNotNull(); - assertThat(keyValue.getVInt64()).isEqualTo(2); - } - - @Test - void testKeyValue() { - // test - Model.KeyValue kvB = - parse( - Model.KeyValue.getDefaultInstance(), - KeyValueMarshaler.create(booleanKey("valueB"), true)); - Model.KeyValue kvD = - parse( - Model.KeyValue.getDefaultInstance(), KeyValueMarshaler.create(doubleKey("valueD"), 1.)); - Model.KeyValue kvI = - parse(Model.KeyValue.getDefaultInstance(), KeyValueMarshaler.create(longKey("valueI"), 2L)); - Model.KeyValue kvS = - parse( - Model.KeyValue.getDefaultInstance(), - KeyValueMarshaler.create(stringKey("valueS"), "foobar")); - Model.KeyValue kvArrayB = - parse( - Model.KeyValue.getDefaultInstance(), - KeyValueMarshaler.create(booleanArrayKey("valueArrayB"), Arrays.asList(true, false))); - Model.KeyValue kvArrayD = - parse( - Model.KeyValue.getDefaultInstance(), - KeyValueMarshaler.create(doubleArrayKey("valueArrayD"), Arrays.asList(1.2345, 6.789))); - Model.KeyValue kvArrayI = - parse( - Model.KeyValue.getDefaultInstance(), - KeyValueMarshaler.create(longArrayKey("valueArrayI"), Arrays.asList(12345L, 67890L))); - Model.KeyValue kvArrayS = - parse( - Model.KeyValue.getDefaultInstance(), - KeyValueMarshaler.create( - stringArrayKey("valueArrayS"), Arrays.asList("foobar", "barfoo"))); - - // verify - assertThat(kvB.getVBool()).isTrue(); - assertThat(kvB.getVType()).isEqualTo(Model.ValueType.BOOL); - assertThat(kvD.getVFloat64()).isEqualTo(1.); - assertThat(kvD.getVType()).isEqualTo(Model.ValueType.FLOAT64); - assertThat(kvI.getVInt64()).isEqualTo(2); - assertThat(kvI.getVType()).isEqualTo(Model.ValueType.INT64); - assertThat(kvS.getVStr()).isEqualTo("foobar"); - assertThat(kvS.getVStrBytes().toStringUtf8()).isEqualTo("foobar"); - assertThat(kvS.getVType()).isEqualTo(Model.ValueType.STRING); - assertThat(kvArrayB.getVStr()).isEqualTo("[true,false]"); - assertThat(kvArrayB.getVStrBytes().toStringUtf8()).isEqualTo("[true,false]"); - assertThat(kvArrayB.getVType()).isEqualTo(Model.ValueType.STRING); - assertThat(kvArrayD.getVStr()).isEqualTo("[1.2345,6.789]"); - assertThat(kvArrayD.getVStrBytes().toStringUtf8()).isEqualTo("[1.2345,6.789]"); - assertThat(kvArrayD.getVType()).isEqualTo(Model.ValueType.STRING); - assertThat(kvArrayI.getVStr()).isEqualTo("[12345,67890]"); - assertThat(kvArrayI.getVStrBytes().toStringUtf8()).isEqualTo("[12345,67890]"); - assertThat(kvArrayI.getVType()).isEqualTo(Model.ValueType.STRING); - assertThat(kvArrayS.getVStr()).isEqualTo("[\"foobar\",\"barfoo\"]"); - assertThat(kvArrayS.getVStrBytes().toStringUtf8()).isEqualTo("[\"foobar\",\"barfoo\"]"); - assertThat(kvArrayS.getVType()).isEqualTo(Model.ValueType.STRING); - } - - @Test - void testSpanRefs() { - // prepare - LinkData link = - LinkData.create(createSpanContext("00000000000000000000000000cba123", "0000000000fed456")); - - // test - List spanRefs = - SpanRefMarshaler.createRepeated(Collections.singletonList(link)); - - // verify - assertThat(spanRefs).hasSize(1); // the actual span ref is tested in another test - } - - @Test - void testSpanRef() { - // prepare - LinkData link = LinkData.create(createSpanContext(TRACE_ID, SPAN_ID)); - - // test - Model.SpanRef spanRef = - parse(Model.SpanRef.getDefaultInstance(), SpanRefMarshaler.create(link)); - - // verify - assertThat(SpanId.fromBytes(spanRef.getSpanId().toByteArray())).isEqualTo(SPAN_ID); - assertThat(TraceId.fromBytes(spanRef.getTraceId().toByteArray())).isEqualTo(TRACE_ID); - assertThat(spanRef.getRefType()).isEqualTo(Model.SpanRefType.FOLLOWS_FROM); - } - - @Test - void testStatusNotUnset() { - long startMs = System.currentTimeMillis(); - long endMs = startMs + 900; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(createSpanContext(TRACE_ID, SPAN_ID)) - .setName("GET /api/endpoint") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setKind(SpanKind.SERVER) - .setStatus(StatusData.error()) - .setTotalRecordedEvents(0) - .setTotalRecordedLinks(0) - .build(); - - assertThat(SpanMarshaler.create(span)).isNotNull(); - } - - @Test - void testSpanError() { - Attributes attributes = - Attributes.of( - stringKey("error.type"), - this.getClass().getName(), - stringKey("error.message"), - "server error"); - long startMs = System.currentTimeMillis(); - long endMs = startMs + 900; - SpanData span = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(createSpanContext(TRACE_ID, SPAN_ID)) - .setName("GET /api/endpoint") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setKind(SpanKind.SERVER) - .setStatus(StatusData.error()) - .setAttributes(attributes) - .setTotalRecordedEvents(0) - .setTotalRecordedLinks(0) - .build(); - - Model.Span jaegerSpan = parse(Model.Span.getDefaultInstance(), SpanMarshaler.create(span)); - Model.KeyValue errorType = getValue(jaegerSpan.getTagsList(), "error.type"); - assertThat(errorType).isNotNull(); - assertThat(errorType.getVStr()).isEqualTo(this.getClass().getName()); - Model.KeyValue error = getValue(jaegerSpan.getTagsList(), "error"); - assertThat(error).isNotNull(); - assertThat(error.getVBool()).isTrue(); - } - - private static EventData getTimedEvent() { - return getTimedEvent(-1); - } - - private static EventData getTimedEvent(int totalAttributeCount) { - long epochNanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - Attributes attributes = Attributes.of(stringKey("foo"), "bar"); - if (totalAttributeCount <= 0) { - totalAttributeCount = attributes.size(); - } - return EventData.create(epochNanos, "the log message", attributes, totalAttributeCount); - } - - private static SpanData getSpanData(long startMs, long endMs, SpanKind kind) { - return getSpanData(startMs, endMs, kind, 1); - } - - private static SpanData getSpanData( - long startMs, long endMs, SpanKind kind, int totalRecordedEvents) { - Attributes attributes = Attributes.of(booleanKey("valueB"), true); - - LinkData link = LinkData.create(createSpanContext(LINK_TRACE_ID, LINK_SPAN_ID), attributes); - - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext(createSpanContext(TRACE_ID, SPAN_ID)) - .setParentSpanContext( - SpanContext.create( - TRACE_ID, PARENT_SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(TimeUnit.MILLISECONDS.toNanos(startMs)) - .setEndEpochNanos(TimeUnit.MILLISECONDS.toNanos(endMs)) - .setAttributes(Attributes.of(booleanKey("valueB"), true)) - .setTotalAttributeCount(3) - .setEvents(Collections.singletonList(getTimedEvent())) - .setTotalRecordedEvents(totalRecordedEvents) - .setLinks(Collections.singletonList(link)) - .setTotalRecordedLinks(1) - .setKind(kind) - .setResource(Resource.create(Attributes.empty())) - .setStatus(StatusData.ok()) - .build(); - } - - private static SpanContext createSpanContext(String traceId, String spanId) { - return SpanContext.create(traceId, spanId, TraceFlags.getSampled(), TraceState.getDefault()); - } - - @Nullable - private static Model.KeyValue getValue(List tagsList, String s) { - for (Model.KeyValue kv : tagsList) { - if (kv.getKey().equals(s)) { - return kv; - } - } - return null; - } - - private static void assertHasFollowsFrom(Model.Span jaegerSpan) { - boolean found = false; - for (Model.SpanRef spanRef : jaegerSpan.getReferencesList()) { - if (Model.SpanRefType.FOLLOWS_FROM.equals(spanRef.getRefType())) { - assertThat(TraceId.fromBytes(spanRef.getTraceId().toByteArray())).isEqualTo(LINK_TRACE_ID); - assertThat(SpanId.fromBytes(spanRef.getSpanId().toByteArray())).isEqualTo(LINK_SPAN_ID); - found = true; - } - } - assertThat(found).withFailMessage("Should have found the follows-from reference").isTrue(); - } - - private static void assertHasParent(Model.Span jaegerSpan) { - boolean found = false; - for (Model.SpanRef spanRef : jaegerSpan.getReferencesList()) { - if (Model.SpanRefType.CHILD_OF.equals(spanRef.getRefType())) { - assertThat(TraceId.fromBytes(spanRef.getTraceId().toByteArray())).isEqualTo(TRACE_ID); - assertThat(SpanId.fromBytes(spanRef.getSpanId().toByteArray())).isEqualTo(PARENT_SPAN_ID); - found = true; - } - } - assertThat(found).withFailMessage("Should have found the parent reference").isTrue(); - } - - @SuppressWarnings("unchecked") - private static T parse(T prototype, Marshaler marshaler) { - byte[] serialized = toByteArray(marshaler); - T result; - try { - result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); - } catch (InvalidProtocolBufferException e) { - throw new UncheckedIOException(e); - } - // Our marshaler should produce the exact same length of serialized output (for example, field - // default values are not outputted), so we check that here. The output itself may have slightly - // different ordering, mostly due to the way we don't output oneof values in field order all the - // tieme. If the lengths are equal and the resulting protos are equal, the marshaling is - // guaranteed to be valid. - assertThat(result.getSerializedSize()).isEqualTo(serialized.length); - return result; - } - - private static byte[] toByteArray(Marshaler marshaler) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - return bos.toByteArray(); - } -} diff --git a/exporters/jaeger/src/test/resources/logback-test.xml b/exporters/jaeger/src/test/resources/logback-test.xml deleted file mode 100644 index 0f157506f5e..00000000000 --- a/exporters/jaeger/src/test/resources/logback-test.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - %d{HH:mm:ss.SSS} %-5level %logger - %msg%n - - - - - - - \ No newline at end of file diff --git a/exporters/logging-otlp/README.md b/exporters/logging-otlp/README.md deleted file mode 100644 index 82018d4cdd1..00000000000 --- a/exporters/logging-otlp/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenTelemetry - OTLP JSON Logging Exporter - -[![Javadocs][javadoc-image]][javadoc-url] - -Exporters for writing data to logs using OTLP JSON format. They are appropriate for writing spans or -metrics to logs in a way that is both human-readable and structured for machine parsing. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-logging-otlp.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-logging-otlp diff --git a/exporters/logging-otlp/build.gradle.kts b/exporters/logging-otlp/build.gradle.kts index bcc0176d0d6..185268ea71c 100644 --- a/exporters/logging-otlp/build.gradle.kts +++ b/exporters/logging-otlp/build.gradle.kts @@ -7,20 +7,27 @@ plugins { description = "OpenTelemetry Protocol JSON Logging Exporters" otelJava.moduleName.set("io.opentelemetry.exporter.logging.otlp") +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator", "io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) dependencies { - compileOnly(project(":sdk:trace")) - compileOnly(project(":sdk:metrics")) - compileOnly(project(":sdk:logs")) + implementation(project(":sdk:trace")) + implementation(project(":sdk:metrics")) + implementation(project(":sdk:logs")) implementation(project(":exporters:otlp:common")) + compileOnly(project(":api:incubator")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) - implementation("com.fasterxml.jackson.core:jackson-core") - + testImplementation(project(":api:incubator")) testImplementation(project(":sdk:testing")) - testImplementation(project(":sdk:logs")) - testImplementation(project(":sdk:metrics")) - testImplementation(project(":sdk:trace")) + testImplementation(project(":sdk-extensions:autoconfigure-spi")) + testImplementation("com.google.guava:guava") testImplementation("org.skyscreamer:jsonassert") } diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/JsonUtil.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/JsonUtil.java deleted file mode 100644 index b4b8cbc577c..00000000000 --- a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/JsonUtil.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.logging.otlp; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.io.SegmentedStringWriter; -import java.io.IOException; - -final class JsonUtil { - - static final JsonFactory JSON_FACTORY = new JsonFactory(); - - static JsonGenerator create(SegmentedStringWriter stringWriter) { - try { - return JSON_FACTORY.createGenerator(stringWriter); - } catch (IOException e) { - throw new IllegalStateException("Unable to create in-memory JsonGenerator, can't happen.", e); - } - } - - private JsonUtil() {} -} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogExporter.java deleted file mode 100644 index 2f13c1a5078..00000000000 --- a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogExporter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.logging.otlp; - -import static io.opentelemetry.exporter.logging.otlp.JsonUtil.JSON_FACTORY; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.io.SegmentedStringWriter; -import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import java.io.IOException; -import java.util.Collection; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A {@link LogExporter} which writes {@linkplain LogData logs} to a {@link Logger} in OTLP JSON - * format. Each log line will include a single {@code ResourceLogs}. - */ -public final class OtlpJsonLoggingLogExporter implements LogExporter { - - private static final Logger logger = Logger.getLogger(OtlpJsonLoggingLogExporter.class.getName()); - - /** Returns a new {@link OtlpJsonLoggingLogExporter}. */ - public static LogExporter create() { - return new OtlpJsonLoggingLogExporter(); - } - - private OtlpJsonLoggingLogExporter() {} - - @Override - public CompletableResultCode export(Collection logs) { - ResourceLogsMarshaler[] allResourceLogs = ResourceLogsMarshaler.create(logs); - for (ResourceLogsMarshaler resourceLogs : allResourceLogs) { - SegmentedStringWriter sw = new SegmentedStringWriter(JSON_FACTORY._getBufferRecycler()); - try (JsonGenerator gen = JsonUtil.create(sw)) { - resourceLogs.writeJsonTo(gen); - } catch (IOException e) { - // Shouldn't happen in practice, just skip it. - continue; - } - logger.log(Level.INFO, sw.getAndClear()); - } - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - return CompletableResultCode.ofSuccess(); - } -} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogRecordExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogRecordExporter.java new file mode 100644 index 00000000000..b10eb751c51 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogRecordExporter.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporter; +import io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; +import java.util.logging.Logger; + +/** + * A {@link LogRecordExporter} which writes {@linkplain LogRecordData logs} to a {@link Logger} in + * OTLP JSON format. Each log line will include a single {@code ResourceLogs}. + * + *

    Note: This class is superseded by {@link OtlpStdoutLogRecordExporter}, which allows + * configuring a custom logger or output stream. + * + * @since 1.19.0 + */ +public final class OtlpJsonLoggingLogRecordExporter implements LogRecordExporter { + + private static final Logger logger = + Logger.getLogger(OtlpJsonLoggingLogRecordExporter.class.getName()); + + private final OtlpStdoutLogRecordExporter delegate; + + /** Returns a new {@link OtlpJsonLoggingLogRecordExporter}. */ + public static LogRecordExporter create() { + OtlpStdoutLogRecordExporter delegate = + new OtlpStdoutLogRecordExporterBuilder(logger).setWrapperJsonObject(false).build(); + return new OtlpJsonLoggingLogRecordExporter(delegate); + } + + OtlpJsonLoggingLogRecordExporter(OtlpStdoutLogRecordExporter delegate) { + this.delegate = delegate; + } + + @Override + public CompletableResultCode export(Collection logs) { + return delegate.export(logs); + } + + @Override + public CompletableResultCode flush() { + return delegate.flush(); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + return "OtlpJsonLoggingLogRecordExporter{}"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporter.java index 2380a246277..43ba54f3c17 100644 --- a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporter.java +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporter.java @@ -5,24 +5,22 @@ package io.opentelemetry.exporter.logging.otlp; -import static io.opentelemetry.exporter.logging.otlp.JsonUtil.JSON_FACTORY; - -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.io.SegmentedStringWriter; -import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporter; +import io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporterBuilder; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.MetricExporter; -import java.io.IOException; import java.util.Collection; -import java.util.logging.Level; import java.util.logging.Logger; /** - * A {@link MetricExporter} which writes {@linkplain MetricData spans} to a {@link Logger} in OTLP + * A {@link MetricExporter} which writes {@linkplain MetricData metrics} to a {@link Logger} in OTLP * JSON format. Each log line will include a single {@code ResourceMetrics}. + * + *

    Note: This class is superseded by {@link OtlpStdoutMetricExporter}, which allows configuring a + * custom logger or output stream. */ public final class OtlpJsonLoggingMetricExporter implements MetricExporter { @@ -31,12 +29,14 @@ public final class OtlpJsonLoggingMetricExporter implements MetricExporter { private final AggregationTemporality aggregationTemporality; + private final OtlpStdoutMetricExporter delegate; + /** - * Returns a new {@link OtlpJsonLoggingMetricExporter} with a aggregation temporality of {@link + * Returns a new {@link OtlpJsonLoggingMetricExporter} with an aggregation temporality of {@link * AggregationTemporality#CUMULATIVE}. */ public static MetricExporter create() { - return new OtlpJsonLoggingMetricExporter(AggregationTemporality.CUMULATIVE); + return create(AggregationTemporality.CUMULATIVE); } /** @@ -44,13 +44,32 @@ public static MetricExporter create() { * aggregationTemporality}. */ public static MetricExporter create(AggregationTemporality aggregationTemporality) { - return new OtlpJsonLoggingMetricExporter(aggregationTemporality); + OtlpStdoutMetricExporter delegate = + new OtlpStdoutMetricExporterBuilder(logger).setWrapperJsonObject(false).build(); + return new OtlpJsonLoggingMetricExporter(delegate, aggregationTemporality); } - private OtlpJsonLoggingMetricExporter(AggregationTemporality aggregationTemporality) { + OtlpJsonLoggingMetricExporter( + OtlpStdoutMetricExporter delegate, AggregationTemporality aggregationTemporality) { + this.delegate = delegate; this.aggregationTemporality = aggregationTemporality; } + @Override + public CompletableResultCode export(Collection logs) { + return delegate.export(logs); + } + + @Override + public CompletableResultCode flush() { + return delegate.flush(); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + /** * Return the aggregation temporality. * @@ -67,28 +86,7 @@ public AggregationTemporality getAggregationTemporality(InstrumentType instrumen } @Override - public CompletableResultCode export(Collection metrics) { - ResourceMetricsMarshaler[] allResourceMetrics = ResourceMetricsMarshaler.create(metrics); - for (ResourceMetricsMarshaler resourceMetrics : allResourceMetrics) { - SegmentedStringWriter sw = new SegmentedStringWriter(JSON_FACTORY._getBufferRecycler()); - try (JsonGenerator gen = JsonUtil.create(sw)) { - resourceMetrics.writeJsonTo(gen); - } catch (IOException e) { - // Shouldn't happen in practice, just skip it. - continue; - } - logger.log(Level.INFO, sw.getAndClear()); - } - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - return CompletableResultCode.ofSuccess(); + public String toString() { + return "OtlpJsonLoggingMetricExporter{aggregationTemporality=" + aggregationTemporality + "}"; } } diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporter.java index fad7367ec35..220d4d5d954 100644 --- a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporter.java +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporter.java @@ -5,57 +5,56 @@ package io.opentelemetry.exporter.logging.otlp; -import com.fasterxml.jackson.core.JsonGenerator; -import com.fasterxml.jackson.core.io.SegmentedStringWriter; -import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporter; +import io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporterBuilder; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.io.IOException; import java.util.Collection; -import java.util.logging.Level; import java.util.logging.Logger; /** * A {@link SpanExporter} which writes {@linkplain SpanData spans} to a {@link Logger} in OTLP JSON * format. Each log line will include a single {@code ResourceSpans}. + * + *

    Note: This class is superseded by {@link OtlpStdoutSpanExporter}, which allows configuring a + * custom logger or output stream. */ public final class OtlpJsonLoggingSpanExporter implements SpanExporter { private static final Logger logger = Logger.getLogger(OtlpJsonLoggingSpanExporter.class.getName()); + private final OtlpStdoutSpanExporter delegate; + /** Returns a new {@link OtlpJsonLoggingSpanExporter}. */ public static SpanExporter create() { - return new OtlpJsonLoggingSpanExporter(); + OtlpStdoutSpanExporter delegate = + new OtlpStdoutSpanExporterBuilder(logger).setWrapperJsonObject(false).build(); + return new OtlpJsonLoggingSpanExporter(delegate); } - private OtlpJsonLoggingSpanExporter() {} + OtlpJsonLoggingSpanExporter(OtlpStdoutSpanExporter delegate) { + this.delegate = delegate; + } @Override - public CompletableResultCode export(Collection spans) { - ResourceSpansMarshaler[] allResourceSpans = ResourceSpansMarshaler.create(spans); - for (ResourceSpansMarshaler resourceSpans : allResourceSpans) { - SegmentedStringWriter sw = - new SegmentedStringWriter(JsonUtil.JSON_FACTORY._getBufferRecycler()); - try (JsonGenerator gen = JsonUtil.create(sw)) { - resourceSpans.writeJsonTo(gen); - } catch (IOException e) { - // Shouldn't happen in practice, just skip it. - continue; - } - logger.log(Level.INFO, sw.getAndClear()); - } - return CompletableResultCode.ofSuccess(); + public CompletableResultCode export(Collection logs) { + return delegate.export(logs); } @Override public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); + return delegate.flush(); } @Override public CompletableResultCode shutdown() { - return CompletableResultCode.ofSuccess(); + return delegate.shutdown(); + } + + @Override + public String toString() { + return "OtlpJsonLoggingSpanExporter{}"; } } diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/OutputStreamConfigUtil.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/OutputStreamConfigUtil.java new file mode 100644 index 00000000000..327d79ec7a8 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/OutputStreamConfigUtil.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import java.io.BufferedOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.FileSystemNotFoundException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardOpenOption; +import java.util.function.Consumer; + +/** + * Utilities for configuring the output stream of the OTLP file exporters. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OutputStreamConfigUtil { + + private static final String STDOUT = "stdout"; + private static final String FILE_SCHEME = "file"; + + /** + * Invoke the {@code outputStreamConsumer} with the configured output stream. + * + *

    Recognized values are {@code stdout} and a file URI such as {@code + * file:///path/to/file.jsonl}. Missing parent directories of the file are created, and the file + * is appended to if it already exists. + */ + @SuppressWarnings("SystemOut") + public static void configureOutputStream( + DeclarativeConfigProperties config, Consumer outputStreamConsumer) { + String outputStream = config.getString("output_stream"); + if (outputStream == null) { + return; + } + if (STDOUT.equals(outputStream)) { + outputStreamConsumer.accept(System.out); + return; + } + Path path = filePath(outputStream); + try { + Path parent = path.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + outputStreamConsumer.accept( + new BufferedOutputStream( + Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND))); + } catch (IOException e) { + throw new ConfigurationException("Unable to open output_stream: " + outputStream, e); + } + } + + private static Path filePath(String outputStream) { + URI uri; + try { + uri = new URI(outputStream); + } catch (URISyntaxException e) { + throw new ConfigurationException(unrecognized(outputStream), e); + } + if (!FILE_SCHEME.equals(uri.getScheme())) { + throw new ConfigurationException(unrecognized(outputStream)); + } + try { + return Paths.get(uri); + } catch (IllegalArgumentException | FileSystemNotFoundException e) { + throw new ConfigurationException(unrecognized(outputStream), e); + } + } + + private static String unrecognized(String outputStream) { + return "Unrecognized output_stream: " + + outputStream + + ". Expected \"stdout\" or a file:// URI."; + } + + private OutputStreamConfigUtil() {} +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/LoggingLogRecordExporterProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/LoggingLogRecordExporterProvider.java new file mode 100644 index 00000000000..5e038f3c892 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/LoggingLogRecordExporterProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.logs; + +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingLogRecordExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * {@link LogRecordExporter} SPI implementation for {@link OtlpJsonLoggingLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class LoggingLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider { + + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + return OtlpJsonLoggingLogRecordExporter.create(); + } + + @Override + public String getName() { + return "logging-otlp"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporter.java new file mode 100644 index 00000000000..11798e938f0 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporter.java @@ -0,0 +1,110 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.logs; + +import io.opentelemetry.exporter.internal.otlp.logs.LogReusableDataMarshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.logging.otlp.internal.writer.JsonWriter; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; +import java.util.StringJoiner; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Exporter for sending OTLP log records to stdout. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutLogRecordExporter implements LogRecordExporter { + + private static final Logger LOGGER = + Logger.getLogger(OtlpStdoutLogRecordExporter.class.getName()); + + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + private final Logger logger; + private final JsonWriter jsonWriter; + private final boolean wrapperJsonObject; + private final MemoryMode memoryMode; + private final Function, CompletableResultCode> marshaler; + + OtlpStdoutLogRecordExporter( + Logger logger, JsonWriter jsonWriter, boolean wrapperJsonObject, MemoryMode memoryMode) { + this.logger = logger; + this.jsonWriter = jsonWriter; + this.wrapperJsonObject = wrapperJsonObject; + this.memoryMode = memoryMode; + marshaler = createMarshaler(jsonWriter, memoryMode, wrapperJsonObject); + } + + /** Returns a new {@link OtlpStdoutLogRecordExporterBuilder}. */ + @SuppressWarnings("SystemOut") + public static OtlpStdoutLogRecordExporterBuilder builder() { + return new OtlpStdoutLogRecordExporterBuilder(LOGGER).setOutput(System.out); + } + + private static Function, CompletableResultCode> createMarshaler( + JsonWriter jsonWriter, MemoryMode memoryMode, boolean wrapperJsonObject) { + if (wrapperJsonObject) { + LogReusableDataMarshaler reusableDataMarshaler = + new LogReusableDataMarshaler( + memoryMode, (marshaler, numItems) -> jsonWriter.write(marshaler)); + return reusableDataMarshaler::export; + } else { + return logs -> { + // no support for low allocation marshaler + for (ResourceLogsMarshaler marshaler : ResourceLogsMarshaler.create(logs)) { + CompletableResultCode resultCode = jsonWriter.write(marshaler); + if (!resultCode.isSuccess()) { + // already logged + return resultCode; + } + } + return CompletableResultCode.ofSuccess(); + }; + } + } + + @Override + public CompletableResultCode export(Collection logs) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + + return marshaler.apply(logs); + } + + @Override + public CompletableResultCode flush() { + return jsonWriter.flush(); + } + + @Override + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + } else { + jsonWriter.close(); + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpStdoutLogRecordExporter{", "}"); + joiner.add("jsonWriter=" + jsonWriter); + joiner.add("wrapperJsonObject=" + wrapperJsonObject); + joiner.add("memoryMode=" + memoryMode); + return joiner.toString(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterBuilder.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterBuilder.java new file mode 100644 index 00000000000..76e6adb20ad --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterBuilder.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.logs; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingLogRecordExporter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.JsonWriter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.LoggerJsonWriter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.StreamJsonWriter; +import io.opentelemetry.sdk.common.export.MemoryMode; +import java.io.OutputStream; +import java.util.logging.Logger; + +/** + * Builder for {@link OtlpJsonLoggingLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutLogRecordExporterBuilder { + + private static final String TYPE = "log records"; + + private final Logger logger; + private JsonWriter jsonWriter; + private boolean wrapperJsonObject = true; + private MemoryMode memoryMode = MemoryMode.IMMUTABLE_DATA; + + public OtlpStdoutLogRecordExporterBuilder(Logger logger) { + this.logger = logger; + this.jsonWriter = new LoggerJsonWriter(logger, TYPE); + } + + /** + * Sets the exporter to use the specified JSON object wrapper. + * + * @param wrapperJsonObject whether to wrap the JSON object in an outer JSON "resourceLogs" + * object. + */ + public OtlpStdoutLogRecordExporterBuilder setWrapperJsonObject(boolean wrapperJsonObject) { + this.wrapperJsonObject = wrapperJsonObject; + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link MemoryMode#IMMUTABLE_DATA}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + */ + public OtlpStdoutLogRecordExporterBuilder setMemoryMode(MemoryMode memoryMode) { + this.memoryMode = memoryMode; + return this; + } + + /** + * Sets the exporter to use the specified output stream. + * + *

    The output stream will be closed when {@link OtlpStdoutLogRecordExporter#shutdown()} is + * called unless it's {@link System#out} or {@link System#err}. + * + * @param outputStream the output stream to use. + */ + public OtlpStdoutLogRecordExporterBuilder setOutput(OutputStream outputStream) { + requireNonNull(outputStream, "outputStream"); + this.jsonWriter = new StreamJsonWriter(outputStream, TYPE); + return this; + } + + /** Sets the exporter to use the specified logger. */ + public OtlpStdoutLogRecordExporterBuilder setOutput(Logger logger) { + requireNonNull(logger, "logger"); + this.jsonWriter = new LoggerJsonWriter(logger, TYPE); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpStdoutLogRecordExporter build() { + if (memoryMode == MemoryMode.REUSABLE_DATA && !wrapperJsonObject) { + throw new IllegalArgumentException( + "Reusable data mode is not supported without wrapperJsonObject"); + } + return new OtlpStdoutLogRecordExporter(logger, jsonWriter, wrapperJsonObject, memoryMode); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterComponentProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterComponentProvider.java new file mode 100644 index 00000000000..6786db9cef7 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterComponentProvider.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.logs; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.internal.IncubatingExporterBuilderUtil; +import io.opentelemetry.exporter.logging.otlp.internal.OutputStreamConfigUtil; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpStdoutLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutLogRecordExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return LogRecordExporter.class; + } + + @Override + public String getName() { + return "otlp_file/development"; + } + + @Override + public LogRecordExporter create(DeclarativeConfigProperties config) { + OtlpStdoutLogRecordExporterBuilder builder = OtlpStdoutLogRecordExporter.builder(); + IncubatingExporterBuilderUtil.configureExporterMemoryMode(config, builder::setMemoryMode); + OutputStreamConfigUtil.configureOutputStream(config, builder::setOutput); + return builder.build(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterProvider.java new file mode 100644 index 00000000000..08b8021590d --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/logs/OtlpStdoutLogRecordExporterProvider.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.logs; + +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * {@link LogRecordExporter} SPI implementation for {@link OtlpStdoutLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider { + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + OtlpStdoutLogRecordExporterBuilder builder = OtlpStdoutLogRecordExporter.builder(); + ExporterBuilderUtil.configureExporterMemoryMode(config, builder::setMemoryMode); + return builder.build(); + } + + @Override + public String getName() { + return "experimental-otlp/stdout"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/LoggingMetricExporterProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/LoggingMetricExporterProvider.java new file mode 100644 index 00000000000..6748bbd99d1 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/LoggingMetricExporterProvider.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.metrics; + +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingMetricExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * {@link MetricExporter} SPI implementation for {@link OtlpJsonLoggingMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class LoggingMetricExporterProvider implements ConfigurableMetricExporterProvider { + + @Override + public MetricExporter createExporter(ConfigProperties config) { + return OtlpJsonLoggingMetricExporter.create(); + } + + @Override + public String getName() { + return "logging-otlp"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporter.java new file mode 100644 index 00000000000..4294c1d2571 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporter.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.metrics; + +import io.opentelemetry.exporter.internal.otlp.metrics.MetricReusableDataMarshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.logging.otlp.internal.writer.JsonWriter; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.Collection; +import java.util.StringJoiner; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Exporter for sending OTLP metrics to stdout. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutMetricExporter implements MetricExporter { + + private static final Logger LOGGER = Logger.getLogger(OtlpStdoutMetricExporter.class.getName()); + + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + private final Logger logger; + private final JsonWriter jsonWriter; + private final boolean wrapperJsonObject; + private final MemoryMode memoryMode; + private final Function, CompletableResultCode> marshaler; + private final AggregationTemporalitySelector aggregationTemporalitySelector; + private final DefaultAggregationSelector defaultAggregationSelector; + + OtlpStdoutMetricExporter( + Logger logger, + JsonWriter jsonWriter, + boolean wrapperJsonObject, + MemoryMode memoryMode, + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector) { + this.logger = logger; + this.jsonWriter = jsonWriter; + this.wrapperJsonObject = wrapperJsonObject; + this.memoryMode = memoryMode; + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + this.defaultAggregationSelector = defaultAggregationSelector; + marshaler = createMarshaler(jsonWriter, memoryMode, wrapperJsonObject); + } + + /** Returns a new {@link OtlpStdoutMetricExporterBuilder}. */ + @SuppressWarnings("SystemOut") + public static OtlpStdoutMetricExporterBuilder builder() { + return new OtlpStdoutMetricExporterBuilder(LOGGER).setOutput(System.out); + } + + private static Function, CompletableResultCode> createMarshaler( + JsonWriter jsonWriter, MemoryMode memoryMode, boolean wrapperJsonObject) { + if (wrapperJsonObject) { + MetricReusableDataMarshaler reusableDataMarshaler = + new MetricReusableDataMarshaler( + memoryMode, (marshaler, numItems) -> jsonWriter.write(marshaler)); + return reusableDataMarshaler::export; + } else { + return metrics -> { + // no support for low allocation marshaler + for (ResourceMetricsMarshaler marshaler : ResourceMetricsMarshaler.create(metrics)) { + CompletableResultCode resultCode = jsonWriter.write(marshaler); + if (!resultCode.isSuccess()) { + // already logged + return resultCode; + } + } + return CompletableResultCode.ofSuccess(); + }; + } + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); + } + + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return defaultAggregationSelector.getDefaultAggregation(instrumentType); + } + + @Override + public MemoryMode getMemoryMode() { + return memoryMode; + } + + @Override + public CompletableResultCode export(Collection metrics) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + + return marshaler.apply(metrics); + } + + @Override + public CompletableResultCode flush() { + return jsonWriter.flush(); + } + + @Override + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + } else { + jsonWriter.close(); + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpStdoutMetricExporter{", "}"); + joiner.add("jsonWriter=" + jsonWriter); + joiner.add("wrapperJsonObject=" + wrapperJsonObject); + joiner.add("memoryMode=" + memoryMode); + joiner.add( + "aggregationTemporalitySelector=" + + AggregationTemporalitySelector.asString(aggregationTemporalitySelector)); + joiner.add( + "defaultAggregationSelector=" + + DefaultAggregationSelector.asString(defaultAggregationSelector)); + return joiner.toString(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterBuilder.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterBuilder.java new file mode 100644 index 00000000000..945ffd778bd --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterBuilder.java @@ -0,0 +1,142 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.metrics; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingMetricExporter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.JsonWriter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.LoggerJsonWriter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.StreamJsonWriter; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.io.OutputStream; +import java.util.logging.Logger; + +/** + * Builder for {@link OtlpJsonLoggingMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutMetricExporterBuilder { + + private static final String TYPE = "metrics"; + + private static final AggregationTemporalitySelector DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = + AggregationTemporalitySelector.alwaysCumulative(); + + private AggregationTemporalitySelector aggregationTemporalitySelector = + DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; + + private DefaultAggregationSelector defaultAggregationSelector = + DefaultAggregationSelector.getDefault(); + + private final Logger logger; + private JsonWriter jsonWriter; + private boolean wrapperJsonObject = true; + private MemoryMode memoryMode = MemoryMode.IMMUTABLE_DATA; + + public OtlpStdoutMetricExporterBuilder(Logger logger) { + this.logger = logger; + this.jsonWriter = new LoggerJsonWriter(logger, TYPE); + } + + /** + * Sets the exporter to use the specified JSON object wrapper. + * + * @param wrapperJsonObject whether to wrap the JSON object in an outer JSON "resourceMetrics" + * object. + */ + public OtlpStdoutMetricExporterBuilder setWrapperJsonObject(boolean wrapperJsonObject) { + this.wrapperJsonObject = wrapperJsonObject; + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link MemoryMode#IMMUTABLE_DATA}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + */ + public OtlpStdoutMetricExporterBuilder setMemoryMode(MemoryMode memoryMode) { + this.memoryMode = memoryMode; + return this; + } + + /** + * Sets the exporter to use the specified output stream. + * + *

    The output stream will be closed when {@link OtlpStdoutMetricExporter#shutdown()} is called + * unless it's {@link System#out} or {@link System#err}. + * + * @param outputStream the output stream to use. + */ + public OtlpStdoutMetricExporterBuilder setOutput(OutputStream outputStream) { + requireNonNull(outputStream, "outputStream"); + this.jsonWriter = new StreamJsonWriter(outputStream, TYPE); + return this; + } + + /** Sets the exporter to use the specified logger. */ + public OtlpStdoutMetricExporterBuilder setOutput(Logger logger) { + requireNonNull(logger, "logger"); + this.jsonWriter = new LoggerJsonWriter(logger, TYPE); + return this; + } + + /** + * Set the {@link AggregationTemporalitySelector} used for {@link + * MetricExporter#getAggregationTemporality(InstrumentType)}. + * + *

    If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}. + * + *

    {@link AggregationTemporalitySelector#deltaPreferred()} is a common configuration for delta + * backends. + */ + public OtlpStdoutMetricExporterBuilder setAggregationTemporalitySelector( + AggregationTemporalitySelector aggregationTemporalitySelector) { + requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector"); + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + return this; + } + + /** + * Set the {@link DefaultAggregationSelector} used for {@link + * MetricExporter#getDefaultAggregation(InstrumentType)}. + * + *

    If unset, defaults to {@link DefaultAggregationSelector#getDefault()}. + */ + public OtlpStdoutMetricExporterBuilder setDefaultAggregationSelector( + DefaultAggregationSelector defaultAggregationSelector) { + requireNonNull(defaultAggregationSelector, "defaultAggregationSelector"); + this.defaultAggregationSelector = defaultAggregationSelector; + + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpStdoutMetricExporter build() { + if (memoryMode == MemoryMode.REUSABLE_DATA && !wrapperJsonObject) { + throw new IllegalArgumentException( + "Reusable data mode is not supported without wrapperJsonObject"); + } + return new OtlpStdoutMetricExporter( + logger, + jsonWriter, + wrapperJsonObject, + memoryMode, + aggregationTemporalitySelector, + defaultAggregationSelector); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterComponentProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterComponentProvider.java new file mode 100644 index 00000000000..2f2fea5c431 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterComponentProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.metrics; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.internal.IncubatingExporterBuilderUtil; +import io.opentelemetry.exporter.logging.otlp.internal.OutputStreamConfigUtil; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpStdoutMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutMetricExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return MetricExporter.class; + } + + @Override + public String getName() { + return "otlp_file/development"; + } + + @Override + public MetricExporter create(DeclarativeConfigProperties config) { + OtlpStdoutMetricExporterBuilder builder = OtlpStdoutMetricExporter.builder(); + IncubatingExporterBuilderUtil.configureExporterMemoryMode(config, builder::setMemoryMode); + IncubatingExporterBuilderUtil.configureOtlpAggregationTemporality( + config, builder::setAggregationTemporalitySelector); + IncubatingExporterBuilderUtil.configureOtlpHistogramDefaultAggregation( + config, builder::setDefaultAggregationSelector); + OutputStreamConfigUtil.configureOutputStream(config, builder::setOutput); + return builder.build(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterProvider.java new file mode 100644 index 00000000000..84f32f56c7b --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/metrics/OtlpStdoutMetricExporterProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.metrics; + +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * {@link MetricExporter} SPI implementation for {@link OtlpStdoutMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutMetricExporterProvider implements ConfigurableMetricExporterProvider { + @Override + public MetricExporter createExporter(ConfigProperties config) { + OtlpStdoutMetricExporterBuilder builder = OtlpStdoutMetricExporter.builder(); + ExporterBuilderUtil.configureExporterMemoryMode(config, builder::setMemoryMode); + ExporterBuilderUtil.configureOtlpAggregationTemporality( + config, builder::setAggregationTemporalitySelector); + ExporterBuilderUtil.configureOtlpHistogramDefaultAggregation( + config, builder::setDefaultAggregationSelector); + return builder.build(); + } + + @Override + public String getName() { + return "experimental-otlp/stdout"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/LoggingSpanExporterProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/LoggingSpanExporterProvider.java new file mode 100644 index 00000000000..6394acf78aa --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/LoggingSpanExporterProvider.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.traces; + +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingSpanExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * {@link SpanExporter} SPI implementation for {@link OtlpJsonLoggingSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class LoggingSpanExporterProvider implements ConfigurableSpanExporterProvider { + + @Override + public SpanExporter createExporter(ConfigProperties config) { + return OtlpJsonLoggingSpanExporter.create(); + } + + @Override + public String getName() { + return "logging-otlp"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporter.java new file mode 100644 index 00000000000..187cdacc245 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporter.java @@ -0,0 +1,109 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.traces; + +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.internal.otlp.traces.SpanReusableDataMarshaler; +import io.opentelemetry.exporter.logging.otlp.internal.writer.JsonWriter; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; +import java.util.StringJoiner; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Exporter for sending OTLP spans to stdout. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutSpanExporter implements SpanExporter { + + private static final Logger LOGGER = Logger.getLogger(OtlpStdoutSpanExporter.class.getName()); + + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + private final Logger logger; + private final JsonWriter jsonWriter; + private final boolean wrapperJsonObject; + private final MemoryMode memoryMode; + private final Function, CompletableResultCode> marshaler; + + OtlpStdoutSpanExporter( + Logger logger, JsonWriter jsonWriter, boolean wrapperJsonObject, MemoryMode memoryMode) { + this.logger = logger; + this.jsonWriter = jsonWriter; + this.wrapperJsonObject = wrapperJsonObject; + this.memoryMode = memoryMode; + marshaler = createMarshaler(jsonWriter, memoryMode, wrapperJsonObject); + } + + /** Returns a new {@link OtlpStdoutSpanExporterBuilder}. */ + @SuppressWarnings("SystemOut") + public static OtlpStdoutSpanExporterBuilder builder() { + return new OtlpStdoutSpanExporterBuilder(LOGGER).setOutput(System.out); + } + + private static Function, CompletableResultCode> createMarshaler( + JsonWriter jsonWriter, MemoryMode memoryMode, boolean wrapperJsonObject) { + if (wrapperJsonObject) { + SpanReusableDataMarshaler reusableDataMarshaler = + new SpanReusableDataMarshaler( + memoryMode, (marshaler, numItems) -> jsonWriter.write(marshaler)); + return reusableDataMarshaler::export; + } else { + return spans -> { + // no support for low allocation marshaler + for (ResourceSpansMarshaler marshaler : ResourceSpansMarshaler.create(spans)) { + CompletableResultCode resultCode = jsonWriter.write(marshaler); + if (!resultCode.isSuccess()) { + // already logged + return resultCode; + } + } + return CompletableResultCode.ofSuccess(); + }; + } + } + + @Override + public CompletableResultCode export(Collection spans) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + + return marshaler.apply(spans); + } + + @Override + public CompletableResultCode flush() { + return jsonWriter.flush(); + } + + @Override + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + } else { + jsonWriter.close(); + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpStdoutSpanExporter{", "}"); + joiner.add("jsonWriter=" + jsonWriter); + joiner.add("wrapperJsonObject=" + wrapperJsonObject); + joiner.add("memoryMode=" + memoryMode); + return joiner.toString(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterBuilder.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterBuilder.java new file mode 100644 index 00000000000..341f63c6e49 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterBuilder.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.traces; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingSpanExporter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.JsonWriter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.LoggerJsonWriter; +import io.opentelemetry.exporter.logging.otlp.internal.writer.StreamJsonWriter; +import io.opentelemetry.sdk.common.export.MemoryMode; +import java.io.OutputStream; +import java.util.logging.Logger; + +/** + * Builder for {@link OtlpJsonLoggingSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutSpanExporterBuilder { + + private static final String TYPE = "spans"; + + private final Logger logger; + private JsonWriter jsonWriter; + private boolean wrapperJsonObject = true; + private MemoryMode memoryMode = MemoryMode.IMMUTABLE_DATA; + + public OtlpStdoutSpanExporterBuilder(Logger logger) { + this.logger = logger; + this.jsonWriter = new LoggerJsonWriter(logger, TYPE); + } + + /** + * Sets the exporter to use the specified JSON object wrapper. + * + * @param wrapperJsonObject whether to wrap the JSON object in an outer JSON "resourceSpans" + * object. + */ + public OtlpStdoutSpanExporterBuilder setWrapperJsonObject(boolean wrapperJsonObject) { + this.wrapperJsonObject = wrapperJsonObject; + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link MemoryMode#IMMUTABLE_DATA}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + */ + public OtlpStdoutSpanExporterBuilder setMemoryMode(MemoryMode memoryMode) { + this.memoryMode = memoryMode; + return this; + } + + /** + * Sets the exporter to use the specified output stream. + * + *

    The output stream will be closed when {@link OtlpStdoutSpanExporter#shutdown()} is called + * unless it's {@link System#out} or {@link System#err}. + * + * @param outputStream the output stream to use. + */ + public OtlpStdoutSpanExporterBuilder setOutput(OutputStream outputStream) { + requireNonNull(outputStream, "outputStream"); + this.jsonWriter = new StreamJsonWriter(outputStream, TYPE); + return this; + } + + /** Sets the exporter to use the specified logger. */ + public OtlpStdoutSpanExporterBuilder setOutput(Logger logger) { + requireNonNull(logger, "logger"); + this.jsonWriter = new LoggerJsonWriter(logger, TYPE); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpStdoutSpanExporter build() { + if (memoryMode == MemoryMode.REUSABLE_DATA && !wrapperJsonObject) { + throw new IllegalArgumentException( + "Reusable data mode is not supported without wrapperJsonObject"); + } + return new OtlpStdoutSpanExporter(logger, jsonWriter, wrapperJsonObject, memoryMode); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterComponentProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterComponentProvider.java new file mode 100644 index 00000000000..aab536cd67a --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterComponentProvider.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.traces; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.internal.IncubatingExporterBuilderUtil; +import io.opentelemetry.exporter.logging.otlp.internal.OutputStreamConfigUtil; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpStdoutSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutSpanExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return SpanExporter.class; + } + + @Override + public String getName() { + return "otlp_file/development"; + } + + @Override + public SpanExporter create(DeclarativeConfigProperties config) { + OtlpStdoutSpanExporterBuilder builder = OtlpStdoutSpanExporter.builder(); + IncubatingExporterBuilderUtil.configureExporterMemoryMode(config, builder::setMemoryMode); + OutputStreamConfigUtil.configureOutputStream(config, builder::setOutput); + return builder.build(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterProvider.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterProvider.java new file mode 100644 index 00000000000..84514492f24 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/traces/OtlpStdoutSpanExporterProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.traces; + +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * {@link SpanExporter} SPI implementation for {@link OtlpStdoutSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OtlpStdoutSpanExporterProvider implements ConfigurableSpanExporterProvider { + @Override + public SpanExporter createExporter(ConfigProperties config) { + OtlpStdoutSpanExporterBuilder builder = OtlpStdoutSpanExporter.builder(); + ExporterBuilderUtil.configureExporterMemoryMode(config, builder::setMemoryMode); + return builder.build(); + } + + @Override + public String getName() { + return "experimental-otlp/stdout"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/JsonWriter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/JsonWriter.java new file mode 100644 index 00000000000..bfee16cba65 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/JsonWriter.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.writer; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.CompletableResultCode; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public interface JsonWriter { + CompletableResultCode write(Marshaler exportRequest); + + CompletableResultCode flush(); + + CompletableResultCode close(); +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/LoggerJsonWriter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/LoggerJsonWriter.java new file mode 100644 index 00000000000..a071dec98e3 --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/LoggerJsonWriter.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.writer; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.CompletableResultCode; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class LoggerJsonWriter implements JsonWriter { + + private final Logger logger; + private final String type; + + public LoggerJsonWriter(Logger logger, String type) { + this.logger = logger; + this.type = type; + } + + // toString(String) decodes straight from the internal buffer, avoiding the array copy that + // new String(bos.toByteArray(), UTF_8) makes. The toString(Charset) overload errorprone wants is + // Java 10+, but this module targets Java 8. + @SuppressWarnings("JdkObsolete") + @Override + public CompletableResultCode write(Marshaler exportRequest) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + String json; + try { + exportRequest.writeJsonTo(bos); + // UTF-8 is always available; the declared UnsupportedEncodingException cannot occur. + json = bos.toString(StandardCharsets.UTF_8.name()); + } catch (IOException e) { + logger.log(Level.WARNING, "Unable to write OTLP JSON " + type, e); + return CompletableResultCode.ofFailure(); + } + + logger.log(Level.INFO, json); + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode close() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + return "LoggerJsonWriter"; + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/StreamJsonWriter.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/StreamJsonWriter.java new file mode 100644 index 00000000000..7e17363b58a --- /dev/null +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/internal/writer/StreamJsonWriter.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.writer; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import java.io.IOException; +import java.io.OutputStream; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class StreamJsonWriter implements JsonWriter { + + private static final Logger internalLogger = Logger.getLogger(StreamJsonWriter.class.getName()); + + private final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); + + private final String type; + private final OutputStream outputStream; + + public StreamJsonWriter(OutputStream originalStream, String type) { + this.outputStream = originalStream; + this.type = type; + } + + @Override + public CompletableResultCode write(Marshaler exportRequest) { + try { + exportRequest.writeJsonTo(outputStream); + outputStream.write('\n'); + outputStream.flush(); + return CompletableResultCode.ofSuccess(); + } catch (IOException e) { + logger.log(Level.WARNING, "Unable to write OTLP JSON " + type, e); + return CompletableResultCode.ofFailure(); + } + } + + @Override + public CompletableResultCode flush() { + try { + outputStream.flush(); + return CompletableResultCode.ofSuccess(); + } catch (IOException e) { + logger.log(Level.WARNING, "Failed to flush items", e); + return CompletableResultCode.ofFailure(); + } + } + + @SuppressWarnings({"SystemOut", "ReferenceEquality"}) + @Override + public CompletableResultCode close() { + if (outputStream == System.out || outputStream == System.err) { + // closing System.out or System.err is not allowed - it breaks the output stream + return CompletableResultCode.ofSuccess(); + } + try { + outputStream.close(); + return CompletableResultCode.ofSuccess(); + } catch (IOException e) { + logger.log(Level.WARNING, "Failed to close stream", e); + return CompletableResultCode.ofFailure(); + } + } + + @Override + public String toString() { + return "StreamJsonWriter{" + "outputStream=" + getName(outputStream) + '}'; + } + + @SuppressWarnings({"SystemOut", "ReferenceEquality"}) + private static String getName(OutputStream outputStream) { + if (outputStream == System.out) { + return "stdout"; + } + if (outputStream == System.err) { + return "stderr"; + } + return outputStream.toString(); + } +} diff --git a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/package-info.java b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/package-info.java index f6c93513bba..b933fa00aef 100644 --- a/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/package-info.java +++ b/exporters/logging-otlp/src/main/java/io/opentelemetry/exporter/logging/otlp/package-info.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** OpenTelemetry exporters which writes spans or metrics to log using OTLP JSON format. */ +/** OpenTelemetry exporters which write spans, metrics, or logs to a logger in OTLP JSON format. */ @ParametersAreNonnullByDefault package io.opentelemetry.exporter.logging.otlp; diff --git a/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..6fe011882dd --- /dev/null +++ b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,4 @@ +io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporterComponentProvider +io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporterComponentProvider +io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporterComponentProvider + diff --git a/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider new file mode 100644 index 00000000000..20763b2e4e5 --- /dev/null +++ b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider @@ -0,0 +1,2 @@ +io.opentelemetry.exporter.logging.otlp.internal.logs.LoggingLogRecordExporterProvider +io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporterProvider diff --git a/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider new file mode 100644 index 00000000000..b1641bbe303 --- /dev/null +++ b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider @@ -0,0 +1,3 @@ +io.opentelemetry.exporter.logging.otlp.internal.metrics.LoggingMetricExporterProvider +io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporterProvider + diff --git a/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider new file mode 100644 index 00000000000..d1a8bfa347a --- /dev/null +++ b/exporters/logging-otlp/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider @@ -0,0 +1,2 @@ +io.opentelemetry.exporter.logging.otlp.internal.traces.LoggingSpanExporterProvider +io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporterProvider diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java new file mode 100644 index 00000000000..eec8b78a803 --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/AbstractOtlpStdoutExporterTest.java @@ -0,0 +1,426 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableList; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.export.MemoryMode; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; +import javax.annotation.Nullable; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.skyscreamer.jsonassert.JSONAssert; +import org.slf4j.event.LoggingEvent; + +abstract class AbstractOtlpStdoutExporterTest { + + private static PrintStream systemOut; + + private static final String TYPE = "experimental-otlp/stdout"; + + private static final ByteArrayOutputStream SYSTEM_OUT_STREAM = new ByteArrayOutputStream(); + private static final PrintStream SYSTEM_OUT_PRINT_STREAM = new PrintStream(SYSTEM_OUT_STREAM); + + @RegisterExtension LogCapturer logs; + private int skipLogs; + private final String defaultConfigString; + private final TestDataExporter testDataExporter; + protected final Class exporterClass; + private final Class providerClass; + private final Class componentProviderType; + + @TempDir Path tempDir; + + public AbstractOtlpStdoutExporterTest( + TestDataExporter testDataExporter, + Class exporterClass, + Class providerClass, + Class componentProviderType, + String defaultConfigString) { + this.testDataExporter = testDataExporter; + this.exporterClass = exporterClass; + this.providerClass = providerClass; + logs = LogCapturer.create().captureForType(exporterClass); + this.defaultConfigString = defaultConfigString; + this.componentProviderType = componentProviderType; + } + + protected abstract T createExporter( + @Nullable OutputStream outputStream, MemoryMode memoryMode, boolean wrapperJsonObject); + + protected abstract T createDefaultExporter(); + + @SuppressWarnings("JdkObsolete") // Recommended alternative was introduced in java 10 + private String output(@Nullable OutputStream outputStream, @Nullable Path file) { + if (outputStream == null) { + return logs.getEvents().stream() + .skip(skipLogs) + .map(LoggingEvent::getMessage) + .reduce("", (a, b) -> a + b + "\n") + .trim(); + } + + if (file != null) { + try { + return new String(Files.readAllBytes(file), StandardCharsets.UTF_8).trim(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + try { + return SYSTEM_OUT_STREAM.toString(StandardCharsets.UTF_8.name()).trim(); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + @BeforeAll + @SuppressWarnings("SystemOut") + static void setUpStatic() { + systemOut = System.out; + System.setOut(SYSTEM_OUT_PRINT_STREAM); + } + + @AfterAll + @SuppressWarnings("SystemOut") + static void tearDownStatic() { + System.setOut(systemOut); + } + + @BeforeEach + void setUp() { + SYSTEM_OUT_STREAM.reset(); + } + + enum OutputType { + LOGGER, + SYSTEM_OUT, + FILE, + FILE_AND_BUFFERED_WRITER + } + + static Stream exportTestCases() { + return ImmutableList.of( + testCase(OutputType.SYSTEM_OUT, MemoryMode.IMMUTABLE_DATA, /* wrapperJsonObject= */ true), + testCase(OutputType.SYSTEM_OUT, MemoryMode.IMMUTABLE_DATA, /* wrapperJsonObject= */ false), + testCase(OutputType.FILE, MemoryMode.IMMUTABLE_DATA, /* wrapperJsonObject= */ true), + testCase(OutputType.FILE, MemoryMode.IMMUTABLE_DATA, /* wrapperJsonObject= */ false), + testCase( + OutputType.FILE_AND_BUFFERED_WRITER, + MemoryMode.IMMUTABLE_DATA, + /* wrapperJsonObject= */ true), + testCase( + OutputType.FILE_AND_BUFFERED_WRITER, + MemoryMode.IMMUTABLE_DATA, + /* wrapperJsonObject= */ false), + testCase(OutputType.LOGGER, MemoryMode.IMMUTABLE_DATA, /* wrapperJsonObject= */ true), + testCase(OutputType.LOGGER, MemoryMode.IMMUTABLE_DATA, /* wrapperJsonObject= */ false), + testCase(OutputType.SYSTEM_OUT, MemoryMode.REUSABLE_DATA, /* wrapperJsonObject= */ true), + testCase(OutputType.SYSTEM_OUT, MemoryMode.REUSABLE_DATA, /* wrapperJsonObject= */ false), + testCase(OutputType.FILE, MemoryMode.REUSABLE_DATA, /* wrapperJsonObject= */ true), + testCase(OutputType.FILE, MemoryMode.REUSABLE_DATA, /* wrapperJsonObject= */ false), + testCase( + OutputType.FILE_AND_BUFFERED_WRITER, + MemoryMode.REUSABLE_DATA, + /* wrapperJsonObject= */ true), + testCase( + OutputType.FILE_AND_BUFFERED_WRITER, + MemoryMode.REUSABLE_DATA, + /* wrapperJsonObject= */ false), + testCase(OutputType.LOGGER, MemoryMode.REUSABLE_DATA, /* wrapperJsonObject= */ true), + testCase(OutputType.LOGGER, MemoryMode.REUSABLE_DATA, /* wrapperJsonObject= */ false)) + .stream(); + } + + private static Arguments testCase( + OutputType type, MemoryMode memoryMode, boolean wrapperJsonObject) { + String name = + "output=" + + type + + ", wrapperJsonObject=" + + wrapperJsonObject + + ", memoryMode=" + + memoryMode; + return Arguments.argumentSet(name, type, memoryMode, wrapperJsonObject); + } + + @SuppressWarnings("SystemOut") + @ParameterizedTest + @MethodSource("exportTestCases") + void exportWithProgrammaticConfig( + OutputType outputType, MemoryMode memoryMode, boolean wrapperJsonObject) throws Exception { + OutputStream outputStream; + Path file = null; + switch (outputType) { + case LOGGER: + outputStream = null; + break; + case SYSTEM_OUT: + outputStream = System.out; + break; + case FILE: + file = tempDir.resolve("test.log"); + outputStream = Files.newOutputStream(file); + break; + case FILE_AND_BUFFERED_WRITER: + file = tempDir.resolve("test.log"); + outputStream = new BufferedOutputStream(Files.newOutputStream(file)); + break; + default: + throw new IllegalStateException("Unexpected value: " + outputType); + } + + Supplier exporter = () -> createExporter(outputStream, memoryMode, wrapperJsonObject); + + if (memoryMode == MemoryMode.REUSABLE_DATA && !wrapperJsonObject) { + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(exporter::get) + .withMessage("Reusable data mode is not supported without wrapperJsonObject"); + return; + } + + testDataExporter.export(exporter.get()); + + String output = output(outputStream, file); + String expectedJson = testDataExporter.getExpectedJson(wrapperJsonObject); + JSONAssert.assertEquals("Got \n" + output, expectedJson, output, false); + + if (wrapperJsonObject) { + assertThat(output).doesNotContain("\n"); + } + + if (file == null) { + // no need to test again for file - and it's not working with files + assertDoubleOutput(exporter, expectedJson, outputStream); + } + } + + private void assertDoubleOutput( + Supplier exporter, String expectedJson, @Nullable OutputStream outputStream) + throws Exception { + SYSTEM_OUT_STREAM.reset(); + skipLogs = logs.getEvents().size(); + testDataExporter.export(exporter.get()); + testDataExporter.export(exporter.get()); + + String[] lines = output(outputStream, null).split("\n"); + assertThat(lines).hasSize(2); + for (String line : lines) { + JSONAssert.assertEquals("Got \n" + line, expectedJson, line, false); + } + } + + @Test + void testShutdown() { + T exporter = createDefaultExporter(); + assertThat(testDataExporter.shutdown(exporter).isSuccess()).isTrue(); + assertThat(testDataExporter.export(exporter).join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + assertThat(testDataExporter.flush(exporter).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(output(null, null)).isEmpty(); + assertThat(testDataExporter.shutdown(exporter).isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + void defaultToString() { + assertThat(createDefaultExporter()).hasToString(defaultConfigString); + + assertThat(exporterFromProvider(DefaultConfigProperties.createFromMap(emptyMap()))) + .hasToString(defaultConfigString); + } + + @Test + void providerConfig() { + assertThat( + exporterFromProvider( + DefaultConfigProperties.createFromMap( + singletonMap("otel.java.exporter.memory_mode", "immutable_data")))) + .extracting("memoryMode") + .isEqualTo(MemoryMode.IMMUTABLE_DATA); + assertThat( + exporterFromProvider( + DefaultConfigProperties.createFromMap( + singletonMap("otel.java.exporter.memory_mode", "reusable_data")))) + .extracting("memoryMode") + .isEqualTo(MemoryMode.REUSABLE_DATA); + } + + @Test + void componentProviderConfig() { + DeclarativeConfigProperties properties = spy(DeclarativeConfigProperties.empty()); + T exporter = exporterFromComponentProvider(properties); + + assertThat(exporter).extracting("wrapperJsonObject").isEqualTo(true); + assertThat(exporter).extracting("memoryMode").isEqualTo(MemoryMode.IMMUTABLE_DATA); + assertThat(exporter) + .extracting("jsonWriter") + .extracting(Object::toString) + .isEqualTo("StreamJsonWriter{outputStream=stdout}"); + + when(properties.getString("memory_mode")).thenReturn("IMMUTABLE_DATA"); + assertThat(exporterFromComponentProvider(properties)) + .extracting("memoryMode") + .isEqualTo(MemoryMode.IMMUTABLE_DATA); + + when(properties.getString("memory_mode")).thenReturn("REUSABLE_DATA"); + assertThat(exporterFromComponentProvider(properties)) + .extracting("memoryMode") + .isEqualTo(MemoryMode.REUSABLE_DATA); + } + + @Test + void componentProviderConfigOutputStreamStdout() { + DeclarativeConfigProperties properties = spy(DeclarativeConfigProperties.empty()); + when(properties.getString("output_stream")).thenReturn("stdout"); + + assertThat(exporterFromComponentProvider(properties)) + .extracting("jsonWriter") + .extracting(Object::toString) + .isEqualTo("StreamJsonWriter{outputStream=stdout}"); + } + + static Stream outputStreamFileTestCases() { + return Stream.of( + Arguments.argumentSet("file uri", "test.jsonl"), + Arguments.argumentSet("missing parent directory", "missing/test.jsonl")); + } + + @ParameterizedTest + @MethodSource("outputStreamFileTestCases") + void componentProviderConfigOutputStreamFile(String relativePath) throws Exception { + Path file = tempDir.resolve(relativePath); + DeclarativeConfigProperties properties = spy(DeclarativeConfigProperties.empty()); + when(properties.getString("output_stream")).thenReturn(file.toUri().toString()); + + T exporter = exporterFromComponentProvider(properties); + testDataExporter.export(exporter); + + String output = new String(Files.readAllBytes(file), StandardCharsets.UTF_8).trim(); + JSONAssert.assertEquals( + "Got \n" + output, + testDataExporter.getExpectedJson(/* withWrapper= */ true), + output, + false); + + // an exporter created later for the same path appends instead of truncating + testDataExporter.shutdown(exporter); + T secondExporter = exporterFromComponentProvider(properties); + testDataExporter.export(secondExporter); + testDataExporter.shutdown(secondExporter); + assertThat(new String(Files.readAllBytes(file), StandardCharsets.UTF_8).trim().split("\n")) + .hasSize(2); + } + + static Stream outputStreamUnrecognizedTestCases() { + return Stream.of( + Arguments.argumentSet("no scheme", "not-a-stream"), + Arguments.argumentSet("upper case stdout", "STDOUT"), + Arguments.argumentSet("upper case file scheme", "FILE:///test.jsonl"), + Arguments.argumentSet("unsupported scheme", "http://example.com/traces.jsonl"), + Arguments.argumentSet("relative file uri", "file://traces.jsonl"), + Arguments.argumentSet("malformed file uri", "file:///with space.jsonl")); + } + + @ParameterizedTest + @MethodSource("outputStreamUnrecognizedTestCases") + void componentProviderConfigOutputStreamUnrecognized(String value) { + DeclarativeConfigProperties properties = spy(DeclarativeConfigProperties.empty()); + when(properties.getString("output_stream")).thenReturn(value); + + assertThatExceptionOfType(ConfigurationException.class) + .isThrownBy(() -> exporterFromComponentProvider(properties)) + .withMessage( + "Unrecognized output_stream: " + value + ". Expected \"stdout\" or a file:// URI."); + } + + @Test + void componentProviderConfigOutputStreamNotOpenable() { + DeclarativeConfigProperties properties = spy(DeclarativeConfigProperties.empty()); + // the path exists but is a directory, so it cannot be opened for writing + when(properties.getString("output_stream")).thenReturn(tempDir.toUri().toString()); + + assertThatExceptionOfType(ConfigurationException.class) + .isThrownBy(() -> exporterFromComponentProvider(properties)) + .withMessageStartingWith("Unable to open output_stream: ") + .withCauseInstanceOf(IOException.class); + } + + @SuppressWarnings("unchecked") // Each test subclass selects a provider that creates T. + protected T exporterFromComponentProvider(DeclarativeConfigProperties properties) { + return (T) + StreamSupport.stream( + properties.getComponentLoader().load(ComponentProvider.class).spliterator(), false) + .filter(p -> { + return "otlp_file/development".equals(p.getName()) + && p.getType().equals(componentProviderType); + }) + .findFirst() + .orElseThrow(() -> new IllegalStateException("No provider found")) + .create(properties); + } + + @SuppressWarnings("unchecked") // Each test subclass selects a provider that creates T. + protected T exporterFromProvider(ConfigProperties config) { + Object provider = loadProvider(config); + + try { + return (T) + provider + .getClass() + .getDeclaredMethod("createExporter", ConfigProperties.class) + .invoke(provider, config); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private Object loadProvider(ConfigProperties config) { + return StreamSupport.stream( + config.getComponentLoader().load(providerClass).spliterator(), false) + .filter(p -> { + try { + return AbstractOtlpStdoutExporterTest.TYPE.equals( + p.getClass().getDeclaredMethod("getName").invoke(p)); + } catch (Exception e) { + throw new RuntimeException(e); + } + }) + .findFirst() + .orElseThrow(() -> new IllegalStateException("No provider found")); + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogExporterTest.java deleted file mode 100644 index 3458b2a0e6e..00000000000 --- a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogExporterTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.logging.otlp; - -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; - -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.skyscreamer.jsonassert.JSONAssert; -import org.slf4j.event.Level; - -@SuppressLogger(OtlpJsonLoggingLogExporter.class) -class OtlpJsonLoggingLogExporterTest { - - private static final Resource RESOURCE = - Resource.create(Attributes.builder().put("key", "value").build()); - - private static final LogData LOG1 = - LogDataBuilder.create(RESOURCE, InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setBody("body1") - .setSeverity(Severity.INFO) - .setSeverityText("INFO") - .setEpoch(1631533710L, TimeUnit.MILLISECONDS) - .setAttributes(Attributes.of(stringKey("animal"), "cat", longKey("lives"), 9L)) - .setSpanContext( - SpanContext.create( - "12345678876543211234567887654322", - "8765432112345876", - TraceFlags.getDefault(), - TraceState.getDefault())) - .build(); - - private static final LogData LOG2 = - LogDataBuilder.create( - RESOURCE, InstrumentationScopeInfo.create("instrumentation2", "2", null)) - .setBody("body2") - .setSeverity(Severity.INFO) - .setSeverityText("INFO") - .setEpoch(1631533710L, TimeUnit.MILLISECONDS) - .setAttributes(Attributes.of(booleanKey("important"), true)) - .setSpanContext( - SpanContext.create( - "12345678876543211234567887654322", - "8765432112345875", - TraceFlags.getDefault(), - TraceState.getDefault())) - .build(); - - @RegisterExtension - LogCapturer logs = LogCapturer.create().captureForType(OtlpJsonLoggingLogExporter.class); - - LogExporter exporter; - - @BeforeEach - void setUp() { - exporter = OtlpJsonLoggingLogExporter.create(); - } - - @Test - void log() throws Exception { - exporter.export(Arrays.asList(LOG1, LOG2)); - - assertThat(logs.getEvents()) - .hasSize(1) - .allSatisfy(log -> assertThat(log.getLevel()).isEqualTo(Level.INFO)); - String message = logs.getEvents().get(0).getMessage(); - JSONAssert.assertEquals( - "{\n" - + " \"resource\":{\n" - + " \"attributes\":[\n" - + " {\n" - + " \"key\":\"key\",\n" - + " \"value\":{\n" - + " \"stringValue\":\"value\"\n" - + " }\n" - + " }\n" - + " ]\n" - + " },\n" - + " \"scopeLogs\":[\n" - + " {\n" - + " \"scope\":{\n" - + " \"name\":\"instrumentation2\",\n" - + " \"version\":\"2\"\n" - + " },\n" - + " \"logRecords\":[\n" - + " {\n" - + " \"timeUnixNano\":\"1631533710000000\",\n" - + " \"severityNumber\":\"SEVERITY_NUMBER_INFO\",\n" - + " \"severityText\":\"INFO\",\n" - + " \"body\":{\n" - + " \"stringValue\":\"body2\"\n" - + " },\n" - + " \"attributes\":[\n" - + " {\n" - + " \"key\":\"important\",\n" - + " \"value\":{\n" - + " \"boolValue\":true\n" - + " }\n" - + " }\n" - + " ],\n" - + " \"traceId\":\"12345678876543211234567887654322\",\n" - + " \"spanId\":\"8765432112345875\"\n" - + " }\n" - + " ]\n" - + " },\n" - + " {\n" - + " \"scope\":{\n" - + " \"name\":\"instrumentation\",\n" - + " \"version\":\"1\"\n" - + " },\n" - + " \"logRecords\":[\n" - + " {\n" - + " \"timeUnixNano\":\"1631533710000000\",\n" - + " \"severityNumber\":\"SEVERITY_NUMBER_INFO\",\n" - + " \"severityText\":\"INFO\",\n" - + " \"body\":{\n" - + " \"stringValue\":\"body1\"\n" - + " },\n" - + " \"attributes\":[\n" - + " {\n" - + " \"key\":\"animal\",\n" - + " \"value\":{\n" - + " \"stringValue\":\"cat\"\n" - + " }\n" - + " },\n" - + " {\n" - + " \"key\":\"lives\",\n" - + " \"value\":{\n" - + " \"intValue\":\"9\"\n" - + " }\n" - + " }\n" - + " ],\n" - + " \"traceId\":\"12345678876543211234567887654322\",\n" - + " \"spanId\":\"8765432112345876\"\n" - + " }\n" - + " ]\n" - + " }\n" - + " ]\n" - + "}", - message, - /* strict= */ false); - assertThat(message).doesNotContain("\n"); - } - - @Test - void shutdown() { - assertThat(exporter.shutdown().isSuccess()).isTrue(); - } -} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogRecordExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogRecordExporterTest.java new file mode 100644 index 00000000000..aff209bcd2c --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingLogRecordExporterTest.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.skyscreamer.jsonassert.JSONAssert; +import org.slf4j.event.Level; + +@SuppressLogger(OtlpJsonLoggingLogRecordExporter.class) +class OtlpJsonLoggingLogRecordExporterTest { + + private final TestDataExporter testDataExporter = TestDataExporter.forLogs(); + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(OtlpJsonLoggingLogRecordExporter.class); + + LogRecordExporter exporter; + + @BeforeEach + void setUp() { + exporter = OtlpJsonLoggingLogRecordExporter.create(); + } + + @Test + void log() throws Exception { + testDataExporter.export(exporter); + + assertThat(logs.getEvents()) + .hasSize(1) + .allSatisfy(log -> assertThat(log.getLevel()).isEqualTo(Level.INFO)); + String message = logs.getEvents().get(0).getMessage(); + String expectedJson = testDataExporter.getExpectedJson(false); + JSONAssert.assertEquals("Got \n" + message, expectedJson, message, /* strict= */ false); + assertThat(message).doesNotContain("\n"); + } + + @Test + void shutdown() { + assertThat(exporter.shutdown().isSuccess()).isTrue(); + assertThat(testDataExporter.export(exporter).join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + assertThat(logs.getEvents()).isEmpty(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + void stringRepresentation() { + assertThat(OtlpJsonLoggingLogRecordExporter.create().toString()) + .isEqualTo("OtlpJsonLoggingLogRecordExporter{}"); + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporterTest.java index 6b6cb1f0cc2..127565bce81 100644 --- a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporterTest.java +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingMetricExporterTest.java @@ -5,22 +5,15 @@ package io.opentelemetry.exporter.logging.otlp; -import static io.opentelemetry.api.common.AttributeKey.stringKey; import static org.assertj.core.api.Assertions.assertThat; import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.common.Attributes; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.MetricExporter; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -30,36 +23,7 @@ @SuppressLogger(OtlpJsonLoggingMetricExporter.class) class OtlpJsonLoggingMetricExporterTest { - private static final Resource RESOURCE = - Resource.create(Attributes.builder().put("key", "value").build()); - - private static final MetricData METRIC1 = - ImmutableMetricData.createDoubleSum( - RESOURCE, - InstrumentationScopeInfo.create("instrumentation", "1", null), - "metric1", - "metric1 description", - "m", - ImmutableSumData.create( - true, - AggregationTemporality.CUMULATIVE, - Arrays.asList( - ImmutableDoublePointData.create( - 1, 2, Attributes.of(stringKey("cat"), "meow"), 4)))); - - private static final MetricData METRIC2 = - ImmutableMetricData.createDoubleSum( - RESOURCE, - InstrumentationScopeInfo.create("instrumentation2", "2", null), - "metric2", - "metric2 description", - "s", - ImmutableSumData.create( - true, - AggregationTemporality.CUMULATIVE, - Arrays.asList( - ImmutableDoublePointData.create( - 1, 2, Attributes.of(stringKey("cat"), "meow"), 4)))); + private final TestDataExporter testDataExporter = TestDataExporter.forMetrics(); @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(OtlpJsonLoggingMetricExporter.class); @@ -85,72 +49,15 @@ void getAggregationTemporality() { @Test void log() throws Exception { - exporter.export(Arrays.asList(METRIC1, METRIC2)); + testDataExporter.export(exporter); assertThat(logs.getEvents()) .hasSize(1) .allSatisfy(log -> assertThat(log.getLevel()).isEqualTo(Level.INFO)); - JSONAssert.assertEquals( - "{" - + " \"resource\": {" - + " \"attributes\": [{" - + " \"key\": \"key\"," - + " \"value\": {" - + " \"stringValue\": \"value\"" - + " }" - + " }]" - + " }," - + " \"scopeMetrics\": [{" - + " \"scope\": {" - + " \"name\": \"instrumentation2\"," - + " \"version\": \"2\"" - + " }," - + " \"metrics\": [{" - + " \"name\": \"metric2\"," - + " \"description\": \"metric2 description\"," - + " \"unit\": \"s\"," - + " \"sum\": {" - + " \"dataPoints\": [{" - + " \"attributes\": [{" - + " \"key\": \"cat\"," - + " \"value\": {\"stringValue\": \"meow\"}" - + " }]," - + " \"startTimeUnixNano\": \"1\"," - + " \"timeUnixNano\": \"2\"," - + " \"asDouble\": 4.0" - + " }]," - + " \"aggregationTemporality\": \"AGGREGATION_TEMPORALITY_CUMULATIVE\"," - + " \"isMonotonic\": true" - + " }" - + " }]" - + " }, {" - + " \"scope\": {" - + " \"name\": \"instrumentation\"," - + " \"version\": \"1\"" - + " }," - + " \"metrics\": [{" - + " \"name\": \"metric1\"," - + " \"description\": \"metric1 description\"," - + " \"unit\": \"m\"," - + " \"sum\": {" - + " \"dataPoints\": [{" - + " \"attributes\": [{" - + " \"key\": \"cat\"," - + " \"value\": {\"stringValue\": \"meow\"}" - + " }]," - + " \"startTimeUnixNano\": \"1\"," - + " \"timeUnixNano\": \"2\"," - + " \"asDouble\": 4.0" - + " }]," - + " \"aggregationTemporality\": \"AGGREGATION_TEMPORALITY_CUMULATIVE\"," - + " \"isMonotonic\": true" - + " }" - + " }]" - + " }]" - + "}", - logs.getEvents().get(0).getMessage(), - /* strict= */ false); - assertThat(logs.getEvents().get(0).getMessage()).doesNotContain("\n"); + String message = logs.getEvents().get(0).getMessage(); + String expectedJson = testDataExporter.getExpectedJson(false); + JSONAssert.assertEquals("Got \n" + message, expectedJson, message, /* strict= */ false); + assertThat(message).doesNotContain("\n"); } @Test @@ -161,5 +68,22 @@ void flush() { @Test void shutdown() { assertThat(exporter.shutdown().isSuccess()).isTrue(); + assertThat( + exporter + .export(Collections.singletonList(TestDataExporter.METRIC1)) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + assertThat(logs.getEvents()).isEmpty(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + void stringRepresentation() { + assertThat(OtlpJsonLoggingMetricExporter.create().toString()) + .isEqualTo("OtlpJsonLoggingMetricExporter{aggregationTemporality=CUMULATIVE}"); + assertThat(OtlpJsonLoggingMetricExporter.create(AggregationTemporality.DELTA).toString()) + .isEqualTo("OtlpJsonLoggingMetricExporter{aggregationTemporality=DELTA}"); } } diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporterTest.java index 8838ff3bceb..1707244da9e 100644 --- a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporterTest.java +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpJsonLoggingSpanExporterTest.java @@ -5,27 +5,13 @@ package io.opentelemetry.exporter.logging.otlp; -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; import static org.assertj.core.api.Assertions.assertThat; import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Arrays; import java.util.Collections; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -35,56 +21,7 @@ @SuppressLogger(OtlpJsonLoggingSpanExporter.class) class OtlpJsonLoggingSpanExporterTest { - private static final Resource RESOURCE = - Resource.create(Attributes.builder().put("key", "value").build()); - - private static final SpanData SPAN1 = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create( - "12345678876543211234567887654321", - "8765432112345678", - TraceFlags.getSampled(), - TraceState.getDefault())) - .setStartEpochNanos(100) - .setEndEpochNanos(100 + 1000) - .setStatus(StatusData.ok()) - .setName("testSpan1") - .setKind(SpanKind.INTERNAL) - .setAttributes(Attributes.of(stringKey("animal"), "cat", longKey("lives"), 9L)) - .setEvents( - Collections.singletonList( - EventData.create( - 100 + 500, - "somethingHappenedHere", - Attributes.of(booleanKey("important"), true)))) - .setTotalAttributeCount(2) - .setTotalRecordedEvents(1) - .setTotalRecordedLinks(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setResource(RESOURCE) - .build(); - - private static final SpanData SPAN2 = - TestSpanData.builder() - .setHasEnded(false) - .setSpanContext( - SpanContext.create( - "12340000000043211234000000004321", - "8765000000005678", - TraceFlags.getSampled(), - TraceState.getDefault())) - .setStartEpochNanos(500) - .setEndEpochNanos(500 + 1001) - .setStatus(StatusData.error()) - .setName("testSpan2") - .setKind(SpanKind.CLIENT) - .setResource(RESOURCE) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("instrumentation2", "2", null)) - .build(); + private final TestDataExporter testDataExporter = TestDataExporter.forSpans(); @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(OtlpJsonLoggingSpanExporter.class); @@ -98,79 +35,14 @@ void setUp() { @Test void log() throws Exception { - exporter.export(Arrays.asList(SPAN1, SPAN2)); + testDataExporter.export(exporter); assertThat(logs.getEvents()) .hasSize(1) .allSatisfy(log -> assertThat(log.getLevel()).isEqualTo(Level.INFO)); String message = logs.getEvents().get(0).getMessage(); - JSONAssert.assertEquals( - "{" - + " \"resource\": {" - + " \"attributes\": [{" - + " \"key\": \"key\"," - + " \"value\": {" - + " \"stringValue\": \"value\"" - + " }" - + " }]" - + " }," - + " \"scopeSpans\": [{" - + " \"scope\": {" - + " \"name\": \"instrumentation2\"," - + " \"version\": \"2\"" - + " }," - + " \"spans\": [{" - + " \"traceId\": \"12340000000043211234000000004321\"," - + " \"spanId\": \"8765000000005678\"," - + " \"name\": \"testSpan2\"," - + " \"kind\": \"SPAN_KIND_CLIENT\"," - + " \"startTimeUnixNano\": \"500\"," - + " \"endTimeUnixNano\": \"1501\"," - + " \"status\": {" - + " \"code\": \"STATUS_CODE_ERROR\"" - + " }" - + " }]" - + " }, {" - + " \"scope\": {" - + " \"name\": \"instrumentation\"," - + " \"version\": \"1\"" - + " }," - + " \"spans\": [{" - + " \"traceId\": \"12345678876543211234567887654321\"," - + " \"spanId\": \"8765432112345678\"," - + " \"name\": \"testSpan1\"," - + " \"kind\": \"SPAN_KIND_INTERNAL\"," - + " \"startTimeUnixNano\": \"100\"," - + " \"endTimeUnixNano\": \"1100\"," - + " \"attributes\": [{" - + " \"key\": \"animal\"," - + " \"value\": {" - + " \"stringValue\": \"cat\"" - + " }" - + " }, {" - + " \"key\": \"lives\"," - + " \"value\": {" - + " \"intValue\": \"9\"" - + " }" - + " }]," - + " \"events\": [{" - + " \"timeUnixNano\": \"600\"," - + " \"name\": \"somethingHappenedHere\"," - + " \"attributes\": [{" - + " \"key\": \"important\"," - + " \"value\": {" - + " \"boolValue\": true" - + " }" - + " }]" - + " }]," - + " \"status\": {" - + " \"code\": \"STATUS_CODE_OK\"" - + " }" - + " }]" - + " }]" - + "}", - message, - /* strict= */ false); + String expectedJson = testDataExporter.getExpectedJson(false); + JSONAssert.assertEquals("Got \n" + message, expectedJson, message, /* strict= */ false); assertThat(message).doesNotContain("\n"); } @@ -182,5 +54,20 @@ void flush() { @Test void shutdown() { assertThat(exporter.shutdown().isSuccess()).isTrue(); + assertThat( + exporter + .export(Collections.singletonList(TestDataExporter.SPAN1)) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + assertThat(logs.getEvents()).isEmpty(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + void stringRepresentation() { + assertThat(OtlpJsonLoggingSpanExporter.create().toString()) + .isEqualTo("OtlpJsonLoggingSpanExporter{}"); } } diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutLogRecordExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutLogRecordExporterTest.java new file mode 100644 index 00000000000..c19fba0fe3e --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutLogRecordExporterTest.java @@ -0,0 +1,48 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporter; +import io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.io.OutputStream; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +class OtlpStdoutLogRecordExporterTest + extends AbstractOtlpStdoutExporterTest { + + public OtlpStdoutLogRecordExporterTest() { + super( + TestDataExporter.forLogs(), + OtlpStdoutLogRecordExporter.class, + ConfigurableLogRecordExporterProvider.class, + LogRecordExporter.class, + "OtlpStdoutLogRecordExporter{jsonWriter=StreamJsonWriter{outputStream=stdout}, wrapperJsonObject=true, memoryMode=IMMUTABLE_DATA}"); + } + + @Override + protected OtlpStdoutLogRecordExporter createDefaultExporter() { + return OtlpStdoutLogRecordExporter.builder().build(); + } + + @Override + protected OtlpStdoutLogRecordExporter createExporter( + @Nullable OutputStream outputStream, MemoryMode memoryMode, boolean wrapperJsonObject) { + OtlpStdoutLogRecordExporterBuilder builder = + OtlpStdoutLogRecordExporter.builder() + .setMemoryMode(memoryMode) + .setWrapperJsonObject(wrapperJsonObject); + if (outputStream != null) { + builder.setOutput(outputStream); + } else { + builder.setOutput(Logger.getLogger(exporterClass.getName())); + } + return builder.build(); + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java new file mode 100644 index 00000000000..becc0cb4fce --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutMetricExporterTest.java @@ -0,0 +1,124 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporter; +import io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.io.OutputStream; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; + +class OtlpStdoutMetricExporterTest + extends AbstractOtlpStdoutExporterTest { + + public OtlpStdoutMetricExporterTest() { + super( + TestDataExporter.forMetrics(), + OtlpStdoutMetricExporter.class, + ConfigurableMetricExporterProvider.class, + MetricExporter.class, + "OtlpStdoutMetricExporter{jsonWriter=StreamJsonWriter{outputStream=stdout}, wrapperJsonObject=true, memoryMode=IMMUTABLE_DATA, aggregationTemporalitySelector=AggregationTemporalitySelector{COUNTER=CUMULATIVE, UP_DOWN_COUNTER=CUMULATIVE, HISTOGRAM=CUMULATIVE, OBSERVABLE_COUNTER=CUMULATIVE, OBSERVABLE_UP_DOWN_COUNTER=CUMULATIVE, OBSERVABLE_GAUGE=CUMULATIVE, GAUGE=CUMULATIVE}, defaultAggregationSelector=DefaultAggregationSelector{COUNTER=default, UP_DOWN_COUNTER=default, HISTOGRAM=default, OBSERVABLE_COUNTER=default, OBSERVABLE_UP_DOWN_COUNTER=default, OBSERVABLE_GAUGE=default, GAUGE=default}}"); + } + + @Override + protected OtlpStdoutMetricExporter createDefaultExporter() { + return OtlpStdoutMetricExporter.builder().build(); + } + + @Override + protected OtlpStdoutMetricExporter createExporter( + @Nullable OutputStream outputStream, MemoryMode memoryMode, boolean wrapperJsonObject) { + OtlpStdoutMetricExporterBuilder builder = + OtlpStdoutMetricExporter.builder() + .setMemoryMode(memoryMode) + .setWrapperJsonObject(wrapperJsonObject); + if (outputStream != null) { + builder.setOutput(outputStream); + } else { + builder.setOutput(Logger.getLogger(exporterClass.getName())); + } + return builder.build(); + } + + /** Test configuration specific to metric exporter. */ + @Test + void providerMetricConfig() { + OtlpStdoutMetricExporter exporter = + exporterFromProvider( + DefaultConfigProperties.createFromMap( + ImmutableMap.of( + "otel.exporter.otlp.metrics.temporality.preference", + "DELTA", + "otel.exporter.otlp.metrics.default.histogram.aggregation", + "BASE2_EXPONENTIAL_BUCKET_HISTOGRAM"))); + + assertThat(exporter.getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + + assertThat(exporter.getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); + } + + @Test + void componentProviderMetricConfig() { + DeclarativeConfigProperties properties = spy(DeclarativeConfigProperties.empty()); + when(properties.getString("temporality_preference")).thenReturn("DELTA"); + when(properties.getString("default_histogram_aggregation")) + .thenReturn("BASE2_EXPONENTIAL_BUCKET_HISTOGRAM"); + + OtlpStdoutMetricExporter exporter = exporterFromComponentProvider(properties); + assertThat(exporter.getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + + assertThat(exporter.getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); + } + + @Test + void validMetricConfig() { + assertThatCode(() -> + OtlpStdoutMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) + .doesNotThrowAnyException(); + assertThat( + OtlpStdoutMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat( + OtlpStdoutMetricExporter.builder() + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + assertThat( + OtlpStdoutMetricExporter.builder() + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.drop())) + .build() + .getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.drop()); + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutSpanExporterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutSpanExporterTest.java new file mode 100644 index 00000000000..01d3a96ccd2 --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/OtlpStdoutSpanExporterTest.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporter; +import io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.OutputStream; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +class OtlpStdoutSpanExporterTest extends AbstractOtlpStdoutExporterTest { + + public OtlpStdoutSpanExporterTest() { + super( + TestDataExporter.forSpans(), + OtlpStdoutSpanExporter.class, + ConfigurableSpanExporterProvider.class, + SpanExporter.class, + "OtlpStdoutSpanExporter{jsonWriter=StreamJsonWriter{outputStream=stdout}, wrapperJsonObject=true, memoryMode=IMMUTABLE_DATA}"); + } + + @Override + protected OtlpStdoutSpanExporter createDefaultExporter() { + return OtlpStdoutSpanExporter.builder().build(); + } + + @Override + protected OtlpStdoutSpanExporter createExporter( + @Nullable OutputStream outputStream, MemoryMode memoryMode, boolean wrapperJsonObject) { + OtlpStdoutSpanExporterBuilder builder = + OtlpStdoutSpanExporter.builder() + .setMemoryMode(memoryMode) + .setWrapperJsonObject(wrapperJsonObject); + if (outputStream != null) { + builder.setOutput(outputStream); + } else { + builder.setOutput(Logger.getLogger(exporterClass.getName())); + } + return builder.build(); + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/TestDataExporter.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/TestDataExporter.java new file mode 100644 index 00000000000..cbaf58ae2b4 --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/TestDataExporter.java @@ -0,0 +1,279 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp; + +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; + +import com.google.common.io.Resources; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import io.opentelemetry.sdk.testing.trace.TestSpanData; +import io.opentelemetry.sdk.trace.data.EventData; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.data.StatusData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +abstract class TestDataExporter { + + private final String expectedFileNoWrapper; + private final String expectedFileWrapper; + private static final Resource RESOURCE = + Resource.create(Attributes.builder().put("key", "value").build()); + + private static final LogRecordData LOG1 = + TestLogRecordData.builder() + .setResource(RESOURCE) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation") + .setVersion("1") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build()) + .setBody("body1") + .setSeverity(Severity.INFO) + .setSeverityText("INFO") + .setTimestamp(100L, TimeUnit.NANOSECONDS) + .setObservedTimestamp(200L, TimeUnit.NANOSECONDS) + .setAttributes( + Attributes.builder() + .put(stringKey("animal"), "cat") + .put(longKey("lives"), 9L) + .put(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .put(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .put(valueKey("heterogeneousArray"), Value.of(Value.of("string"), Value.of(123L))) + .put(valueKey("empty"), Value.empty()) + .build()) + .setTotalAttributeCount(6) + .setSpanContext( + SpanContext.create( + "12345678876543211234567887654322", + "8765432112345876", + TraceFlags.getDefault(), + TraceState.getDefault())) + .build(); + + private static final LogRecordData LOG2 = + TestLogRecordData.builder() + .setResource(RESOURCE) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation2").setVersion("2").build()) + .setBody("body2") + .setSeverity(Severity.INFO) + .setSeverityText("INFO") + .setTimestamp(100L, TimeUnit.NANOSECONDS) + .setObservedTimestamp(200L, TimeUnit.NANOSECONDS) + .setAttributes(Attributes.of(booleanKey("important"), true)) + .setTotalAttributeCount(1) + .setSpanContext( + SpanContext.create( + "12345678876543211234567887654322", + "8765432112345875", + TraceFlags.getDefault(), + TraceState.getDefault())) + .build(); + + static final SpanData SPAN1 = + TestSpanData.builder() + .setHasEnded(true) + .setSpanContext( + SpanContext.create( + "12345678876543211234567887654321", + "8765432112345678", + TraceFlags.getSampled(), + TraceState.getDefault())) + .setStartEpochNanos(100) + .setEndEpochNanos(100 + 1000) + .setStatus(StatusData.ok()) + .setName("testSpan1") + .setKind(SpanKind.INTERNAL) + .setAttributes( + Attributes.builder() + .put(stringKey("animal"), "cat") + .put(longKey("lives"), 9L) + .put(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .put(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .put(valueKey("heterogeneousArray"), Value.of(Value.of("string"), Value.of(123L))) + .put(valueKey("empty"), Value.empty()) + .build()) + .setEvents( + Collections.singletonList( + EventData.create( + 100 + 500, + "somethingHappenedHere", + Attributes.of(booleanKey("important"), true)))) + .setTotalAttributeCount(2) + .setTotalRecordedEvents(1) + .setTotalRecordedLinks(0) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation") + .setVersion("1") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build()) + .setResource(RESOURCE) + .build(); + + private static final SpanData SPAN2 = + TestSpanData.builder() + .setHasEnded(false) + .setSpanContext( + SpanContext.create( + "12340000000043211234000000004321", + "8765000000005678", + TraceFlags.getSampled(), + TraceState.getDefault())) + .setStartEpochNanos(500) + .setEndEpochNanos(500 + 1001) + .setStatus(StatusData.error()) + .setName("testSpan2") + .setKind(SpanKind.CLIENT) + .setResource(RESOURCE) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation2").setVersion("2").build()) + .build(); + + static final MetricData METRIC1 = + ImmutableMetricData.createDoubleSum( + RESOURCE, + InstrumentationScopeInfo.builder("instrumentation") + .setVersion("1") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build(), + "metric1", + "metric1 description", + "m", + ImmutableSumData.create( + true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableDoublePointData.create( + 1, + 2, + Attributes.builder() + .put(stringKey("cat"), "meow") + .put(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .put(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .put( + valueKey("heterogeneousArray"), + Value.of(Value.of("string"), Value.of(123L))) + .put(valueKey("empty"), Value.empty()) + .build(), + 4)))); + + private static final MetricData METRIC2 = + ImmutableMetricData.createDoubleSum( + RESOURCE, + InstrumentationScopeInfo.builder("instrumentation2").setVersion("2").build(), + "metric2", + "metric2 description", + "s", + ImmutableSumData.create( + true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableDoublePointData.create( + 1, 2, Attributes.of(stringKey("cat"), "meow"), 4)))); + + public TestDataExporter(String expectedFileNoWrapper, String expectedFileWrapper) { + this.expectedFileNoWrapper = expectedFileNoWrapper; + this.expectedFileWrapper = expectedFileWrapper; + } + + public String getExpectedJson(boolean withWrapper) throws IOException { + String file = withWrapper ? expectedFileWrapper : expectedFileNoWrapper; + return Resources.toString(Resources.getResource(file), StandardCharsets.UTF_8); + } + + abstract CompletableResultCode export(T exporter); + + abstract CompletableResultCode flush(T exporter); + + abstract CompletableResultCode shutdown(T exporter); + + static TestDataExporter forLogs() { + return new TestDataExporter( + "expected-logs.json", "expected-logs-wrapper.json") { + @Override + public CompletableResultCode export(LogRecordExporter exporter) { + return exporter.export(Arrays.asList(LOG1, LOG2)); + } + + @Override + public CompletableResultCode flush(LogRecordExporter exporter) { + return exporter.flush(); + } + + @Override + public CompletableResultCode shutdown(LogRecordExporter exporter) { + return exporter.shutdown(); + } + }; + } + + static TestDataExporter forSpans() { + return new TestDataExporter( + "expected-spans.json", "expected-spans-wrapper.json") { + @Override + public CompletableResultCode export(SpanExporter exporter) { + return exporter.export(Arrays.asList(SPAN1, SPAN2)); + } + + @Override + public CompletableResultCode flush(SpanExporter exporter) { + return exporter.flush(); + } + + @Override + public CompletableResultCode shutdown(SpanExporter exporter) { + return exporter.shutdown(); + } + }; + } + + static TestDataExporter forMetrics() { + return new TestDataExporter( + "expected-metrics.json", "expected-metrics-wrapper.json") { + @Override + public CompletableResultCode export(MetricExporter exporter) { + return exporter.export(Arrays.asList(METRIC1, METRIC2)); + } + + @Override + public CompletableResultCode flush(MetricExporter exporter) { + return exporter.flush(); + } + + @Override + public CompletableResultCode shutdown(MetricExporter exporter) { + return exporter.shutdown(); + } + }; + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/internal/writer/LoggerJsonWriterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/internal/writer/LoggerJsonWriterTest.java new file mode 100644 index 00000000000..566000443af --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/internal/writer/LoggerJsonWriterTest.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.writer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.io.IOException; +import java.io.OutputStream; +import java.util.logging.Logger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.Mockito; + +@SuppressLogger(LoggerJsonWriter.class) +class LoggerJsonWriterTest { + + @RegisterExtension + static final LogCapturer logs = LogCapturer.create().captureForType(LoggerJsonWriter.class); + + @Test + void testToString() { + LoggerJsonWriter writer = new LoggerJsonWriter(null, "type"); + assertThat(writer.toString()).isEqualTo("LoggerJsonWriter"); + } + + @Test + void error() throws IOException { + Marshaler marshaler = mock(Marshaler.class); + Mockito.doThrow(new IOException("test")).when(marshaler).writeJsonTo(any(OutputStream.class)); + + Logger logger = Logger.getLogger(LoggerJsonWriter.class.getName()); + + LoggerJsonWriter writer = new LoggerJsonWriter(logger, "type"); + writer.write(marshaler); + + logs.assertContains("Unable to write OTLP JSON type"); + } +} diff --git a/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/internal/writer/StreamJsonWriterTest.java b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/internal/writer/StreamJsonWriterTest.java new file mode 100644 index 00000000000..de88db42dec --- /dev/null +++ b/exporters/logging-otlp/src/test/java/io/opentelemetry/exporter/logging/otlp/internal/writer/StreamJsonWriterTest.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.otlp.internal.writer; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.io.FilterOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; + +@SuppressWarnings("SystemOut") +@SuppressLogger(StreamJsonWriter.class) +class StreamJsonWriterTest { + + @RegisterExtension + static final LogCapturer logs = LogCapturer.create().captureForType(StreamJsonWriter.class); + + @TempDir Path tempDir; + + @Test + @SuppressWarnings("SystemOut") + void testToString() throws IOException { + assertThat( + new StreamJsonWriter(Files.newOutputStream(tempDir.resolve("foo")), "type").toString()) + .startsWith("StreamJsonWriter{outputStream=") + .contains("Channel"); + assertThat(new StreamJsonWriter(System.out, "type").toString()) + .isEqualTo("StreamJsonWriter{outputStream=stdout}"); + assertThat(new StreamJsonWriter(System.err, "type").toString()) + .isEqualTo("StreamJsonWriter{outputStream=stderr}"); + } + + @Test + void errorWriting() throws IOException { + Marshaler marshaler = mock(Marshaler.class); + Mockito.doThrow(new IOException("test")).when(marshaler).writeJsonTo(any(OutputStream.class)); + + StreamJsonWriter writer = new StreamJsonWriter(System.out, "type"); + writer.write(marshaler); + + logs.assertContains("Unable to write OTLP JSON type"); + } + + @Test + void errorFlushing() { + OutputStream outputStream = + new FilterOutputStream(System.out) { + @Override + public void flush() throws IOException { + throw new IOException("No flush"); + } + }; + + StreamJsonWriter writer = new StreamJsonWriter(outputStream, "type"); + writer.flush(); + + logs.assertContains("Failed to flush items"); + } +} diff --git a/exporters/logging-otlp/src/test/resources/expected-logs-wrapper.json b/exporters/logging-otlp/src/test/resources/expected-logs-wrapper.json new file mode 100644 index 00000000000..59a198ba9be --- /dev/null +++ b/exporters/logging-otlp/src/test/resources/expected-logs-wrapper.json @@ -0,0 +1,128 @@ +{ + "resourceLogs": [ + { + "resource": { + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "scopeLogs": [ + { + "scope": { + "name": "instrumentation", + "version": "1", + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "logRecords": [ + { + "timeUnixNano": "100", + "observedTimeUnixNano": "200", + "severityNumber": 9, + "severityText": "INFO", + "body": { + "stringValue": "body1" + }, + "attributes": [ + { + "key": "animal", + "value": { + "stringValue": "cat" + } + }, + { + "key": "bytes", + "value": { + "bytesValue": "AQID" + } + }, + { + "key": "empty", + "value": { + } + }, + { + "key": "heterogeneousArray", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "string" + }, + { + "intValue": "123" + } + ] + } + } + }, + { + "key": "lives", + "value": { + "intValue": "9" + } + }, + { + "key": "map", + "value": { + "kvlistValue": { + "values": [ + { + "key": "nested", + "value": { + "stringValue": "value" + } + } + ] + } + } + } + ], + "traceId": "12345678876543211234567887654322", + "spanId": "8765432112345876" + } + ] + }, + { + "scope": { + "name": "instrumentation2", + "version": "2", + "attributes": [] + }, + "logRecords": [ + { + "timeUnixNano": "100", + "observedTimeUnixNano": "200", + "severityNumber": 9, + "severityText": "INFO", + "body": { + "stringValue": "body2" + }, + "attributes": [ + { + "key": "important", + "value": { + "boolValue": true + } + } + ], + "traceId": "12345678876543211234567887654322", + "spanId": "8765432112345875" + } + ] + } + ] + } + ] +} diff --git a/exporters/logging-otlp/src/test/resources/expected-logs.json b/exporters/logging-otlp/src/test/resources/expected-logs.json new file mode 100644 index 00000000000..b781ab1c89b --- /dev/null +++ b/exporters/logging-otlp/src/test/resources/expected-logs.json @@ -0,0 +1,125 @@ +{ + "resource": { + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "scopeLogs": [ + { + "scope": { + "name": "instrumentation", + "version": "1", + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "logRecords": [ + { + "timeUnixNano": "100", + "observedTimeUnixNano": "200", + "severityNumber": 9, + "severityText": "INFO", + "body": { + "stringValue": "body1" + }, + "attributes": [ + { + "key": "animal", + "value": { + "stringValue": "cat" + } + }, + { + "key": "bytes", + "value": { + "bytesValue": "AQID" + } + }, + { + "key": "empty", + "value": { + } + }, + { + "key": "heterogeneousArray", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "string" + }, + { + "intValue": "123" + } + ] + } + } + }, + { + "key": "lives", + "value": { + "intValue": "9" + } + }, + { + "key": "map", + "value": { + "kvlistValue": { + "values": [ + { + "key": "nested", + "value": { + "stringValue": "value" + } + } + ] + } + } + } + ], + "traceId": "12345678876543211234567887654322", + "spanId": "8765432112345876" + } + ] + }, + { + "scope": { + "name": "instrumentation2", + "version": "2", + "attributes": [] + }, + "logRecords": [ + { + "timeUnixNano": "100", + "observedTimeUnixNano": "200", + "severityNumber": 9, + "severityText": "INFO", + "body": { + "stringValue": "body2" + }, + "attributes": [ + { + "key": "important", + "value": { + "boolValue": true + } + } + ], + "traceId": "12345678876543211234567887654322", + "spanId": "8765432112345875" + } + ] + } + ] +} + diff --git a/exporters/logging-otlp/src/test/resources/expected-metrics-wrapper.json b/exporters/logging-otlp/src/test/resources/expected-metrics-wrapper.json new file mode 100644 index 00000000000..34f3c856e5f --- /dev/null +++ b/exporters/logging-otlp/src/test/resources/expected-metrics-wrapper.json @@ -0,0 +1,133 @@ +{ + "resourceMetrics": [ + { + "resource": { + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "scopeMetrics": [ + { + "scope": { + "name": "instrumentation", + "version": "1", + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "metrics": [ + { + "name": "metric1", + "description": "metric1 description", + "unit": "m", + "sum": { + "dataPoints": [ + { + "startTimeUnixNano": "1", + "timeUnixNano": "2", + "asDouble": 4.0, + "exemplars": [], + "attributes": [ + { + "key": "bytes", + "value": { + "bytesValue": "AQID" + } + }, + { + "key": "cat", + "value": { + "stringValue": "meow" + } + }, + { + "key": "empty", + "value": {} + }, + { + "key": "heterogeneousArray", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "string" + }, + { + "intValue": "123" + } + ] + } + } + }, + { + "key": "map", + "value": { + "kvlistValue": { + "values": [ + { + "key": "nested", + "value": { + "stringValue": "value" + } + } + ] + } + } + } + ] + } + ], + "aggregationTemporality": 2, + "isMonotonic": true + } + } + ] + }, + { + "scope": { + "name": "instrumentation2", + "version": "2", + "attributes": [] + }, + "metrics": [ + { + "name": "metric2", + "description": "metric2 description", + "unit": "s", + "sum": { + "dataPoints": [ + { + "startTimeUnixNano": "1", + "timeUnixNano": "2", + "asDouble": 4.0, + "exemplars": [], + "attributes": [ + { + "key": "cat", + "value": { + "stringValue": "meow" + } + } + ] + } + ], + "aggregationTemporality": 2, + "isMonotonic": true + } + } + ] + } + ] + } + ] +} diff --git a/exporters/logging-otlp/src/test/resources/expected-metrics.json b/exporters/logging-otlp/src/test/resources/expected-metrics.json new file mode 100644 index 00000000000..6946dd2a11f --- /dev/null +++ b/exporters/logging-otlp/src/test/resources/expected-metrics.json @@ -0,0 +1,129 @@ +{ + "resource": { + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "scopeMetrics": [ + { + "scope": { + "name": "instrumentation", + "version": "1", + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "metrics": [ + { + "name": "metric1", + "description": "metric1 description", + "unit": "m", + "sum": { + "dataPoints": [ + { + "startTimeUnixNano": "1", + "timeUnixNano": "2", + "asDouble": 4.0, + "exemplars": [], + "attributes": [ + { + "key": "bytes", + "value": { + "bytesValue": "AQID" + } + }, + { + "key": "cat", + "value": { + "stringValue": "meow" + } + }, + { + "key": "empty", + "value": {} + }, + { + "key": "heterogeneousArray", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "string" + }, + { + "intValue": "123" + } + ] + } + } + }, + { + "key": "map", + "value": { + "kvlistValue": { + "values": [ + { + "key": "nested", + "value": { + "stringValue": "value" + } + } + ] + } + } + } + ] + } + ], + "aggregationTemporality": 2, + "isMonotonic": true + } + } + ] + }, + { + "scope": { + "name": "instrumentation2", + "version": "2", + "attributes": [] + }, + "metrics": [ + { + "name": "metric2", + "description": "metric2 description", + "unit": "s", + "sum": { + "dataPoints": [ + { + "startTimeUnixNano": "1", + "timeUnixNano": "2", + "asDouble": 4.0, + "exemplars": [], + "attributes": [ + { + "key": "cat", + "value": { + "stringValue": "meow" + } + } + ] + } + ], + "aggregationTemporality": 2, + "isMonotonic": true + } + } + ] + } + ] +} diff --git a/exporters/logging-otlp/src/test/resources/expected-spans-wrapper.json b/exporters/logging-otlp/src/test/resources/expected-spans-wrapper.json new file mode 100644 index 00000000000..aa5856bd3f8 --- /dev/null +++ b/exporters/logging-otlp/src/test/resources/expected-spans-wrapper.json @@ -0,0 +1,140 @@ +{ + "resourceSpans": [ + { + "resource": { + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "instrumentation", + "version": "1", + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "spans": [ + { + "traceId": "12345678876543211234567887654321", + "spanId": "8765432112345678", + "name": "testSpan1", + "kind": 1, + "startTimeUnixNano": "100", + "endTimeUnixNano": "1100", + "attributes": [ + { + "key": "animal", + "value": { + "stringValue": "cat" + } + }, + { + "key": "bytes", + "value": { + "bytesValue": "AQID" + } + }, + { + "key": "empty", + "value": { + } + }, + { + "key": "heterogeneousArray", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "string" + }, + { + "intValue": "123" + } + ] + } + } + }, + { + "key": "lives", + "value": { + "intValue": "9" + } + }, + { + "key": "map", + "value": { + "kvlistValue": { + "values": [ + { + "key": "nested", + "value": { + "stringValue": "value" + } + } + ] + } + } + } + ], + "events": [ + { + "timeUnixNano": "600", + "name": "somethingHappenedHere", + "attributes": [ + { + "key": "important", + "value": { + "boolValue": true + } + } + ] + } + ], + "links": [], + "status": { + "code": 1 + }, + "flags": 257 + } + ] + }, + { + "scope": { + "name": "instrumentation2", + "version": "2", + "attributes": [] + }, + "spans": [ + { + "traceId": "12340000000043211234000000004321", + "spanId": "8765000000005678", + "name": "testSpan2", + "kind": 3, + "startTimeUnixNano": "500", + "endTimeUnixNano": "1501", + "attributes": [], + "events": [], + "links": [], + "status": { + "code": 2 + }, + "flags": 257 + } + ] + } + ] + } + ] +} diff --git a/exporters/logging-otlp/src/test/resources/expected-spans.json b/exporters/logging-otlp/src/test/resources/expected-spans.json new file mode 100644 index 00000000000..dc33d9f75d8 --- /dev/null +++ b/exporters/logging-otlp/src/test/resources/expected-spans.json @@ -0,0 +1,136 @@ +{ + "resource": { + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "scopeSpans": [ + { + "scope": { + "name": "instrumentation", + "version": "1", + "attributes": [ + { + "key": "key", + "value": { + "stringValue": "value" + } + } + ] + }, + "spans": [ + { + "traceId": "12345678876543211234567887654321", + "spanId": "8765432112345678", + "name": "testSpan1", + "kind": 1, + "startTimeUnixNano": "100", + "endTimeUnixNano": "1100", + "attributes": [ + { + "key": "animal", + "value": { + "stringValue": "cat" + } + }, + { + "key": "bytes", + "value": { + "bytesValue": "AQID" + } + }, + { + "key": "empty", + "value": { + } + }, + { + "key": "heterogeneousArray", + "value": { + "arrayValue": { + "values": [ + { + "stringValue": "string" + }, + { + "intValue": "123" + } + ] + } + } + }, + { + "key": "lives", + "value": { + "intValue": "9" + } + }, + { + "key": "map", + "value": { + "kvlistValue": { + "values": [ + { + "key": "nested", + "value": { + "stringValue": "value" + } + } + ] + } + } + } + ], + "events": [ + { + "timeUnixNano": "600", + "name": "somethingHappenedHere", + "attributes": [ + { + "key": "important", + "value": { + "boolValue": true + } + } + ] + } + ], + "links": [], + "status": { + "code": 1 + }, + "flags": 257 + } + ] + }, + { + "scope": { + "name": "instrumentation2", + "version": "2", + "attributes": [] + }, + "spans": [ + { + "traceId": "12340000000043211234000000004321", + "spanId": "8765000000005678", + "name": "testSpan2", + "kind": 3, + "startTimeUnixNano": "500", + "endTimeUnixNano": "1501", + "attributes": [], + "events": [], + "links": [], + "status": { + "code": 2 + }, + "flags": 257 + } + ] + } + ] +} diff --git a/exporters/logging/README.md b/exporters/logging/README.md deleted file mode 100644 index 1609476a396..00000000000 --- a/exporters/logging/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry - Logging Exporter - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-logging.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-logging diff --git a/exporters/logging/build.gradle.kts b/exporters/logging/build.gradle.kts index 60cb832c131..3fb14ff8182 100644 --- a/exporters/logging/build.gradle.kts +++ b/exporters/logging/build.gradle.kts @@ -7,11 +7,20 @@ plugins { description = "OpenTelemetry - Logging Exporter" otelJava.moduleName.set("io.opentelemetry.exporter.logging") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator", "io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) dependencies { api(project(":sdk:all")) - api(project(":sdk:metrics")) - api(project(":sdk:logs")) + + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + compileOnly(project(":api:incubator")) testImplementation(project(":sdk:testing")) } diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingMetricExporter.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingMetricExporter.java index 3c30470f253..7c5ee632ea3 100644 --- a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingMetricExporter.java +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingMetricExporter.java @@ -11,13 +11,16 @@ import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.MetricExporter; import java.util.Collection; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; +/** A Metric Exporter that logs every metric at INFO level using java.util.logging. */ public final class LoggingMetricExporter implements MetricExporter { private static final Logger logger = Logger.getLogger(LoggingMetricExporter.class.getName()); + private final AtomicBoolean isShutdown = new AtomicBoolean(); private final AggregationTemporality aggregationTemporality; /** @@ -64,6 +67,10 @@ public AggregationTemporality getAggregationTemporality(InstrumentType instrumen @Override public CompletableResultCode export(Collection metrics) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + logger.info("Received a collection of " + metrics.size() + " metrics for export."); for (MetricData metricData : metrics) { logger.log(Level.INFO, "metric: {0}", metricData); @@ -91,8 +98,15 @@ public CompletableResultCode flush() { @Override public CompletableResultCode shutdown() { - // no-op - this.flush(); - return CompletableResultCode.ofSuccess(); + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + return CompletableResultCode.ofSuccess(); + } + return flush(); + } + + @Override + public String toString() { + return "LoggingMetricExporter{aggregationTemporality=" + aggregationTemporality + "}"; } } diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingSpanExporter.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingSpanExporter.java index e34974a8b36..7ee2adda978 100644 --- a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingSpanExporter.java +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/LoggingSpanExporter.java @@ -10,6 +10,7 @@ import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SpanExporter; import java.util.Collection; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; @@ -18,6 +19,8 @@ public final class LoggingSpanExporter implements SpanExporter { private static final Logger logger = Logger.getLogger(LoggingSpanExporter.class.getName()); + private final AtomicBoolean isShutdown = new AtomicBoolean(); + /** Returns a new {@link LoggingSpanExporter}. */ public static LoggingSpanExporter create() { return new LoggingSpanExporter(); @@ -33,6 +36,10 @@ public LoggingSpanExporter() {} @Override public CompletableResultCode export(Collection spans) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + // We always have 32 + 16 + name + several whitespace, 60 seems like an OK initial guess. StringBuilder sb = new StringBuilder(60); for (SpanData span : spans) { @@ -72,7 +79,7 @@ public CompletableResultCode flush() { try { handler.flush(); } catch (Throwable t) { - resultCode.fail(); + return resultCode.fail(); } } return resultCode.succeed(); @@ -80,6 +87,15 @@ public CompletableResultCode flush() { @Override public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + return CompletableResultCode.ofSuccess(); + } return flush(); } + + @Override + public String toString() { + return "LoggingSpanExporter{}"; + } } diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/SystemOutLogExporter.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/SystemOutLogExporter.java deleted file mode 100644 index 597cf97bd21..00000000000 --- a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/SystemOutLogExporter.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.logging; - -import static java.util.concurrent.TimeUnit.NANOSECONDS; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import java.time.Instant; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.Collection; - -/** - * A {@link LogExporter} implementation that outputs log records to standard out. The output is not - * intended to be comprehensive, but just usable for debugging. - * - *

    Note: this doesn't use a {@code java.util.logging Logger}, as that could result in - * logging-loops if an OTel appender is configured for {@code java.util.logging}. - */ -@SuppressWarnings("SystemOut") -public class SystemOutLogExporter implements LogExporter { - private static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter.ISO_DATE_TIME; - - /** Returns a new {@link SystemOutLogExporter}. */ - public static SystemOutLogExporter create() { - return new SystemOutLogExporter(); - } - - /** - * Class constructor. - * - * @deprecated Use {@link #create()}. - */ - @Deprecated - public SystemOutLogExporter() {} - - @Override - public CompletableResultCode export(Collection logs) { - StringBuilder stringBuilder = new StringBuilder(60); - - for (LogData log : logs) { - stringBuilder.setLength(0); - formatLog(stringBuilder, log); - System.out.println(stringBuilder); - } - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - // VisibleForTesting - static void formatLog(StringBuilder stringBuilder, LogData log) { - InstrumentationScopeInfo instrumentationScopeInfo = log.getInstrumentationScopeInfo(); - stringBuilder - .append( - ISO_FORMAT.format( - Instant.ofEpochMilli(NANOSECONDS.toMillis(log.getEpochNanos())) - .atZone(ZoneOffset.UTC))) - .append(" ") - .append(log.getSeverity()) - .append(" '") - .append(log.getBody().asString()) - .append("' : ") - .append(log.getSpanContext().getTraceId()) - .append(" ") - .append(log.getSpanContext().getSpanId()) - .append(" [scopeInfo: ") - .append(instrumentationScopeInfo.getName()) - .append(":") - .append( - instrumentationScopeInfo.getVersion() == null - ? "" - : instrumentationScopeInfo.getVersion()) - .append("] ") - .append(log.getAttributes()); - } - - @Override - public CompletableResultCode shutdown() { - return CompletableResultCode.ofSuccess(); - } -} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/SystemOutLogRecordExporter.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/SystemOutLogRecordExporter.java new file mode 100644 index 00000000000..5effcb65e2b --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/SystemOutLogRecordExporter.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.time.Instant; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.Collection; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * A {@link LogRecordExporter} implementation that outputs log records to standard out. The output + * is not intended to be comprehensive, but just usable for debugging. + * + *

    Note: this doesn't use a {@code java.util.logging Logger}, as that could result in + * logging-loops if an OTel appender is configured for {@code java.util.logging}. + * + * @since 1.19.0 + */ +@SuppressWarnings("SystemOut") +public class SystemOutLogRecordExporter implements LogRecordExporter { + private static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter.ISO_DATE_TIME; + + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + /** Returns a new {@link SystemOutLogRecordExporter}. */ + public static SystemOutLogRecordExporter create() { + return new SystemOutLogRecordExporter(); + } + + private SystemOutLogRecordExporter() {} + + @Override + public CompletableResultCode export(Collection logs) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + + StringBuilder stringBuilder = new StringBuilder(60); + + for (LogRecordData log : logs) { + stringBuilder.setLength(0); + formatLog(stringBuilder, log); + System.out.println(stringBuilder); + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + // VisibleForTesting + static void formatLog(StringBuilder stringBuilder, LogRecordData log) { + InstrumentationScopeInfo instrumentationScopeInfo = log.getInstrumentationScopeInfo(); + Value body = log.getBodyValue(); + String eventName = log.getEventName(); + long timestampEpochNanos = log.getTimestampEpochNanos(); + if (timestampEpochNanos == 0) { + timestampEpochNanos = log.getObservedTimestampEpochNanos(); + } + stringBuilder + .append( + ISO_FORMAT.format( + Instant.ofEpochMilli(NANOSECONDS.toMillis(timestampEpochNanos)) + .atZone(ZoneOffset.UTC))) + .append(" ") + .append(log.getSeverity()); + if (eventName != null && !eventName.isEmpty()) { + stringBuilder.append(" [eventName: ").append(eventName).append("]"); + } + stringBuilder + .append(" '") + .append(body == null ? "" : body.asString()) + .append("' : ") + .append(log.getSpanContext().getTraceId()) + .append(" ") + .append(log.getSpanContext().getSpanId()) + .append(" [scopeInfo: ") + .append(instrumentationScopeInfo.getName()) + .append(":") + .append( + instrumentationScopeInfo.getVersion() == null + ? "" + : instrumentationScopeInfo.getVersion()) + .append("] ") + .append(log.getAttributes()); + } + + @Override + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + System.out.println("Calling shutdown() multiple times."); + return CompletableResultCode.ofSuccess(); + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + return "SystemOutLogRecordExporter{}"; + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleLogRecordExporterComponentProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleLogRecordExporterComponentProvider.java new file mode 100644 index 00000000000..c8acb72be6c --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleLogRecordExporterComponentProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.logging.SystemOutLogRecordExporter; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * Declarative configuration SPI implementation for {@link SystemOutLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ConsoleLogRecordExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return LogRecordExporter.class; + } + + @Override + public String getName() { + return "console"; + } + + @Override + public LogRecordExporter create(DeclarativeConfigProperties config) { + return SystemOutLogRecordExporter.create(); + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleLogRecordExporterProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleLogRecordExporterProvider.java new file mode 100644 index 00000000000..e9911c8fd86 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleLogRecordExporterProvider.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.exporter.logging.SystemOutLogRecordExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * {@link LogRecordExporter} SPI implementation for {@link SystemOutLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ConsoleLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider { + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + return SystemOutLogRecordExporter.create(); + } + + @Override + public String getName() { + return "console"; + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleMetricExporterComponentProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleMetricExporterComponentProvider.java new file mode 100644 index 00000000000..d38eeb731d7 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleMetricExporterComponentProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.logging.LoggingMetricExporter; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * Declarative configuration SPI implementation for {@link LoggingMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ConsoleMetricExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return MetricExporter.class; + } + + @Override + public String getName() { + return "console"; + } + + @Override + public MetricExporter create(DeclarativeConfigProperties config) { + return LoggingMetricExporter.create(); + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleMetricExporterProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleMetricExporterProvider.java new file mode 100644 index 00000000000..66983914a56 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleMetricExporterProvider.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.exporter.logging.LoggingMetricExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * {@link MetricExporter} SPI implementation for {@link LoggingMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ConsoleMetricExporterProvider implements ConfigurableMetricExporterProvider { + @Override + public MetricExporter createExporter(ConfigProperties config) { + return LoggingMetricExporter.create(); + } + + @Override + public String getName() { + return "console"; + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleSpanExporterComponentProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleSpanExporterComponentProvider.java new file mode 100644 index 00000000000..e259c53730f --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleSpanExporterComponentProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * Declarative configuration SPI implementation for {@link LoggingSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ConsoleSpanExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return SpanExporter.class; + } + + @Override + public String getName() { + return "console"; + } + + @Override + public SpanExporter create(DeclarativeConfigProperties config) { + return LoggingSpanExporter.create(); + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleSpanExporterProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleSpanExporterProvider.java new file mode 100644 index 00000000000..220bd2d6ef0 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/ConsoleSpanExporterProvider.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * {@link SpanExporter} SPI implementation for {@link LoggingSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ConsoleSpanExporterProvider implements ConfigurableSpanExporterProvider { + @Override + public SpanExporter createExporter(ConfigProperties config) { + return LoggingSpanExporter.create(); + } + + @Override + public String getName() { + return "console"; + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingLogRecordExporterProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingLogRecordExporterProvider.java new file mode 100644 index 00000000000..d84c4a9c0e8 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingLogRecordExporterProvider.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.exporter.logging.SystemOutLogRecordExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * {@link LogRecordExporter} SPI implementation for {@link SystemOutLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @deprecated The name {@code logging} is a deprecated alias for {@code console}, which is provided + * via {@link ConsoleLogRecordExporterProvider}. + */ +@Deprecated +public final class LoggingLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider { + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + return SystemOutLogRecordExporter.create(); + } + + @Override + public String getName() { + return "logging"; + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingMetricExporterProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingMetricExporterProvider.java new file mode 100644 index 00000000000..479e7625202 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingMetricExporterProvider.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.exporter.logging.LoggingMetricExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * {@link MetricExporter} SPI implementation for {@link LoggingMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @deprecated The name {@code logging} is a deprecated alias for {@code console}, which is provided + * via {@link ConsoleMetricExporterProvider}. + */ +@Deprecated +public final class LoggingMetricExporterProvider implements ConfigurableMetricExporterProvider { + @Override + public MetricExporter createExporter(ConfigProperties config) { + return LoggingMetricExporter.create(); + } + + @Override + public String getName() { + return "logging"; + } +} diff --git a/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingSpanExporterProvider.java b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingSpanExporterProvider.java new file mode 100644 index 00000000000..24f40ce1867 --- /dev/null +++ b/exporters/logging/src/main/java/io/opentelemetry/exporter/logging/internal/LoggingSpanExporterProvider.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging.internal; + +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * {@link SpanExporter} SPI implementation for {@link LoggingSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @deprecated The name {@code logging} is a deprecated alias for {@code console}, which is provided + * via {@link ConsoleSpanExporterProvider}. + */ +@Deprecated +public final class LoggingSpanExporterProvider implements ConfigurableSpanExporterProvider { + @Override + public SpanExporter createExporter(ConfigProperties config) { + return LoggingSpanExporter.create(); + } + + @Override + public String getName() { + return "logging"; + } +} diff --git a/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..a8c21edc040 --- /dev/null +++ b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,4 @@ +io.opentelemetry.exporter.logging.internal.ConsoleMetricExporterComponentProvider +io.opentelemetry.exporter.logging.internal.ConsoleSpanExporterComponentProvider +io.opentelemetry.exporter.logging.internal.ConsoleLogRecordExporterComponentProvider + diff --git a/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider new file mode 100644 index 00000000000..29f8e2db2da --- /dev/null +++ b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider @@ -0,0 +1,2 @@ +io.opentelemetry.exporter.logging.internal.LoggingLogRecordExporterProvider +io.opentelemetry.exporter.logging.internal.ConsoleLogRecordExporterProvider diff --git a/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider new file mode 100644 index 00000000000..3bdcd20b33f --- /dev/null +++ b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider @@ -0,0 +1,2 @@ +io.opentelemetry.exporter.logging.internal.LoggingMetricExporterProvider +io.opentelemetry.exporter.logging.internal.ConsoleMetricExporterProvider diff --git a/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider new file mode 100644 index 00000000000..682519c7938 --- /dev/null +++ b/exporters/logging/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider @@ -0,0 +1,2 @@ +io.opentelemetry.exporter.logging.internal.LoggingSpanExporterProvider +io.opentelemetry.exporter.logging.internal.ConsoleSpanExporterProvider diff --git a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingMetricExporterTest.java b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingMetricExporterTest.java index 267904ef92d..d03dd4fb992 100644 --- a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingMetricExporterTest.java +++ b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingMetricExporterTest.java @@ -8,46 +8,60 @@ import static io.opentelemetry.api.common.AttributeKey.stringKey; import static org.assertj.core.api.Assertions.assertThat; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; import io.opentelemetry.sdk.resources.Resource; import java.io.ByteArrayOutputStream; import java.io.PrintStream; -import java.util.Arrays; +import java.time.Instant; import java.util.Collections; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.logging.StreamHandler; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; @SuppressLogger(LoggingMetricExporter.class) class LoggingMetricExporterTest { - LoggingMetricExporter exporter; + private static final MetricData METRIC_DATA = + ImmutableMetricData.createLongSum( + Resource.create(Attributes.of(stringKey("host"), "localhost")), + InstrumentationScopeInfo.builder("manualInstrumentation").setVersion("1.0").build(), + "counterOne", + "A simple counter", + "one", + ImmutableSumData.create( + true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create( + TimeUnit.MILLISECONDS.toNanos(Instant.now().toEpochMilli()), + TimeUnit.MILLISECONDS.toNanos(Instant.now().plusMillis(245).toEpochMilli()), + Attributes.of(stringKey("z"), "y", stringKey("x"), "w"), + 1010)))); + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(LoggingMetricExporter.class); + + private LoggingMetricExporter exporter; @BeforeEach void setUp() { exporter = LoggingMetricExporter.create(); } - @AfterEach - void tearDown() { - exporter.shutdown(); - } - @Test void preferredTemporality() { assertThat(LoggingMetricExporter.create().getAggregationTemporality(InstrumentType.COUNTER)) @@ -59,74 +73,76 @@ void preferredTemporality() { } @Test - void testExport() { - long nowEpochNanos = System.currentTimeMillis() * 1000 * 1000; - Resource resource = Resource.create(Attributes.of(stringKey("host"), "localhost")); - InstrumentationScopeInfo instrumentationScopeInfo = - InstrumentationScopeInfo.create("manualInstrumentation", "1.0", null); - exporter.export( - Arrays.asList( - ImmutableMetricData.createDoubleSummary( - resource, - instrumentationScopeInfo, - "measureOne", - "A summarized test measure", - "ms", - ImmutableSummaryData.create( - Collections.singletonList( - ImmutableSummaryPointData.create( - nowEpochNanos, - nowEpochNanos + 245, - Attributes.of(stringKey("a"), "b", stringKey("c"), "d"), - 1010, - 50000, - Arrays.asList( - ImmutableValueAtQuantile.create(0.0, 25), - ImmutableValueAtQuantile.create(1.0, 433)))))), - ImmutableMetricData.createLongSum( - resource, - instrumentationScopeInfo, - "counterOne", - "A simple counter", - "one", - ImmutableSumData.create( - true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - nowEpochNanos, - nowEpochNanos + 245, - Attributes.of(stringKey("z"), "y", stringKey("x"), "w"), - 1010)))), - ImmutableMetricData.createDoubleSum( - resource, - instrumentationScopeInfo, - "observedValue", - "an observer gauge", - "kb", - ImmutableSumData.create( - true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableDoublePointData.create( - nowEpochNanos, - nowEpochNanos + 245, - Attributes.of(stringKey("1"), "2", stringKey("3"), "4"), - 33.7767)))))); + void export() { + assertThat(exporter.export(Collections.singletonList(METRIC_DATA)).isSuccess()).isTrue(); + assertThat(logs.getEvents()) + .satisfiesExactly( + loggingEvent -> + assertThat(loggingEvent.getMessage()) + .isEqualTo("Received a collection of 1 metrics for export."), + loggingEvent -> { + assertThat(loggingEvent.getMessage()).isEqualTo("metric: {0}"); + assertThat(loggingEvent.getArgumentArray()).isEqualTo(new MetricData[] {METRIC_DATA}); + }); } @Test - void testFlush() { + void flush() { AtomicBoolean flushed = new AtomicBoolean(false); - Logger.getLogger(LoggingMetricExporter.class.getName()) - .addHandler( - new StreamHandler(new PrintStream(new ByteArrayOutputStream()), new SimpleFormatter()) { - @Override - public synchronized void flush() { - flushed.set(true); - } - }); - exporter.flush(); - assertThat(flushed.get()).isTrue(); + Logger logger = Logger.getLogger(LoggingMetricExporter.class.getName()); + StreamHandler handler = + new StreamHandler(new PrintStream(new ByteArrayOutputStream()), new SimpleFormatter()) { + @Override + public synchronized void flush() { + flushed.set(true); + } + }; + logger.addHandler(handler); + try { + exporter.flush(); + assertThat(flushed.get()).isTrue(); + } finally { + logger.removeHandler(handler); + } + } + + @Test + void flushFailure() { + Logger logger = Logger.getLogger(LoggingMetricExporter.class.getName()); + StreamHandler failingHandler = + new StreamHandler(new PrintStream(new ByteArrayOutputStream()), new SimpleFormatter()) { + @Override + public synchronized void flush() { + throw new RuntimeException("Flush failed"); + } + }; + logger.addHandler(failingHandler); + try { + assertThat(exporter.flush().isSuccess()).isFalse(); + } finally { + logger.removeHandler(failingHandler); + } + } + + @Test + void shutdown() { + assertThat(exporter.shutdown().isSuccess()).isTrue(); + assertThat( + exporter + .export(Collections.singletonList(METRIC_DATA)) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + assertThat(logs.getEvents()).isEmpty(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + void stringRepresentation() { + assertThat(LoggingMetricExporter.create().toString()) + .isEqualTo("LoggingMetricExporter{aggregationTemporality=CUMULATIVE}"); + assertThat(LoggingMetricExporter.create(AggregationTemporality.DELTA).toString()) + .isEqualTo("LoggingMetricExporter{aggregationTemporality=DELTA}"); } } diff --git a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingSpanExporterTest.java b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingSpanExporterTest.java index b1fa6330cd5..25e28b41632 100644 --- a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingSpanExporterTest.java +++ b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/LoggingSpanExporterTest.java @@ -8,17 +8,18 @@ import static io.opentelemetry.api.common.AttributeKey.booleanKey; import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static java.util.Collections.singletonList; +import static io.opentelemetry.api.common.AttributeKey.valueKey; import static org.assertj.core.api.Assertions.assertThat; import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.testing.trace.TestSpanData; import io.opentelemetry.sdk.trace.data.EventData; @@ -33,7 +34,6 @@ import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import java.util.logging.StreamHandler; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -56,7 +56,15 @@ class LoggingSpanExporterTest { .setStatus(StatusData.ok()) .setName("testSpan1") .setKind(SpanKind.INTERNAL) - .setAttributes(Attributes.of(stringKey("animal"), "cat", longKey("lives"), 9L)) + .setAttributes( + Attributes.builder() + .put(stringKey("animal"), "cat") + .put(longKey("lives"), 9L) + .put(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .put(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .put(valueKey("heterogeneousArray"), Value.of(Value.of("string"), Value.of(123L))) + .put(valueKey("empty"), Value.empty()) + .build()) .setEvents( Collections.singletonList( EventData.create( @@ -82,7 +90,8 @@ class LoggingSpanExporterTest { .setStatus(StatusData.error()) .setName("testSpan2") .setKind(SpanKind.CLIENT) - .setInstrumentationScopeInfo(InstrumentationScopeInfo.create("tracer2", "1.0", null)) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("tracer2").setVersion("1.0").build()) .build(); @RegisterExtension @@ -95,14 +104,9 @@ void setUp() { exporter = LoggingSpanExporter.create(); } - @AfterEach - void tearDown() { - exporter.close(); - } - @Test - void log() { - exporter.export(Arrays.asList(SPAN1, SPAN2)); + void export() { + assertThat(exporter.export(Arrays.asList(SPAN1, SPAN2)).isSuccess()).isTrue(); assertThat(logs.getEvents()) .hasSize(2) @@ -111,7 +115,9 @@ void log() { .isEqualTo( "'testSpan1' : 12345678876543211234567887654321 8765432112345678 " + "INTERNAL [tracer: tracer1:] " - + "{animal=\"cat\", lives=9}"); + + "{animal=\"cat\", bytes=ValueBytes{AQID}, empty=ValueEmpty{}, " + + "heterogeneousArray=ValueArray{[\"string\",123]}, lives=9, " + + "map=KeyValueList{{\"nested\":\"value\"}}}"); assertThat(logs.getEvents().get(1).getMessage()) .isEqualTo( "'testSpan2' : 12340000000043211234000000004321 8765000000005678 " @@ -119,47 +125,59 @@ void log() { } @Test - void returnCode() { - long epochNanos = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - SpanData spanData = - TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create( - "12345678876543211234567887654321", - "8765432112345678", - TraceFlags.getSampled(), - TraceState.getDefault())) - .setStartEpochNanos(epochNanos) - .setEndEpochNanos(epochNanos + 1000) - .setStatus(StatusData.ok()) - .setName("testSpan") - .setKind(SpanKind.INTERNAL) - .setEvents( - Collections.singletonList( - EventData.create( - epochNanos + 500, - "somethingHappenedHere", - Attributes.of(booleanKey("important"), true)))) - .setTotalRecordedEvents(1) - .setTotalRecordedLinks(0) - .build(); - CompletableResultCode resultCode = exporter.export(singletonList(spanData)); - assertThat(resultCode.isSuccess()).isTrue(); + void flush() { + AtomicBoolean flushed = new AtomicBoolean(false); + Logger logger = Logger.getLogger(LoggingSpanExporter.class.getName()); + StreamHandler handler = + new StreamHandler(new PrintStream(new ByteArrayOutputStream()), new SimpleFormatter()) { + @Override + public synchronized void flush() { + flushed.set(true); + } + }; + logger.addHandler(handler); + try { + exporter.flush(); + assertThat(flushed.get()).isTrue(); + } finally { + logger.removeHandler(handler); + } } @Test - void testFlush() { - AtomicBoolean flushed = new AtomicBoolean(false); - Logger.getLogger(LoggingSpanExporter.class.getName()) - .addHandler( - new StreamHandler(new PrintStream(new ByteArrayOutputStream()), new SimpleFormatter()) { - @Override - public synchronized void flush() { - flushed.set(true); - } - }); - exporter.flush(); - assertThat(flushed.get()).isTrue(); + void flushFailure() { + Logger logger = Logger.getLogger(LoggingSpanExporter.class.getName()); + StreamHandler failingHandler = + new StreamHandler(new PrintStream(new ByteArrayOutputStream()), new SimpleFormatter()) { + @Override + public synchronized void flush() { + throw new RuntimeException("Flush failed"); + } + }; + logger.addHandler(failingHandler); + try { + assertThat(exporter.flush().isSuccess()).isFalse(); + } finally { + logger.removeHandler(failingHandler); + } + } + + @Test + void shutdown() { + assertThat(exporter.shutdown().isSuccess()).isTrue(); + assertThat( + exporter + .export(Collections.singletonList(SPAN1)) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + assertThat(logs.getEvents()).isEmpty(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + void stringRepresentation() { + assertThat(LoggingSpanExporter.create().toString()).isEqualTo("LoggingSpanExporter{}"); } } diff --git a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/SystemOutLogExporterTest.java b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/SystemOutLogExporterTest.java deleted file mode 100644 index 694e0b9e1b4..00000000000 --- a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/SystemOutLogExporterTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.logging; - -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.time.LocalDateTime; -import java.time.Month; -import java.time.ZoneOffset; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class SystemOutLogExporterTest { - - @Test - void returnCodes() { - SystemOutLogExporter exporter = SystemOutLogExporter.create(); - CompletableResultCode resultCode = - exporter.export(singletonList(sampleLog(System.currentTimeMillis()))); - assertThat(resultCode).isSameAs(CompletableResultCode.ofSuccess()); - assertThat(exporter.shutdown()).isSameAs(CompletableResultCode.ofSuccess()); - } - - @Test - void format() { - long timestamp = - LocalDateTime.of(1970, Month.AUGUST, 7, 10, 0).toInstant(ZoneOffset.UTC).toEpochMilli(); - LogData log = sampleLog(timestamp); - StringBuilder output = new StringBuilder(); - SystemOutLogExporter.formatLog(output, log); - assertThat(output.toString()) - .isEqualTo( - "1970-08-07T10:00:00Z ERROR3 'message' : 00000000000000010000000000000002 0000000000000003 " - + "[scopeInfo: logTest:1.0] {amount=1, cheese=\"cheddar\"}"); - } - - private static LogData sampleLog(long timestamp) { - return LogDataBuilder.create( - Resource.empty(), InstrumentationScopeInfo.create("logTest", "1.0", null)) - .setAttributes(Attributes.of(stringKey("cheese"), "cheddar", longKey("amount"), 1L)) - .setBody("message") - .setSeverity(Severity.ERROR3) - .setEpoch(timestamp, TimeUnit.MILLISECONDS) - .setSpanContext( - SpanContext.create( - "00000000000000010000000000000002", - "0000000000000003", - TraceFlags.getDefault(), - TraceState.getDefault())) - .build(); - } -} diff --git a/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/SystemOutLogRecordExporterTest.java b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/SystemOutLogRecordExporterTest.java new file mode 100644 index 00000000000..0a6ffe9b080 --- /dev/null +++ b/exporters/logging/src/test/java/io/opentelemetry/exporter/logging/SystemOutLogRecordExporterTest.java @@ -0,0 +1,155 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.logging; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.time.LocalDateTime; +import java.time.Month; +import java.time.ZoneOffset; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class SystemOutLogRecordExporterTest { + + @Test + void export() { + SystemOutLogRecordExporter exporter = SystemOutLogRecordExporter.create(); + assertThat(exporter.export(singletonList(sampleLog(System.currentTimeMillis()))).isSuccess()) + .isTrue(); + } + + @Test + void format() { + long timestamp = + LocalDateTime.of(1970, Month.AUGUST, 7, 10, 0).toInstant(ZoneOffset.UTC).toEpochMilli(); + LogRecordData log = sampleLog(timestamp); + StringBuilder output = new StringBuilder(); + SystemOutLogRecordExporter.formatLog(output, log); + assertThat(output.toString()) + .isEqualTo( + "1970-08-07T10:00:00Z ERROR3 'message' : 00000000000000010000000000000002 0000000000000003 " + + "[scopeInfo: logTest:1.0] {amount=1, bytes=ValueBytes{AQID}, cheese=\"cheddar\", " + + "empty=ValueEmpty{}, heterogeneousArray=ValueArray{[\"string\",123]}, " + + "map=KeyValueList{{\"nested\":\"value\"}}}"); + } + + @Test + void formatWithEventName() { + long timestamp = + LocalDateTime.of(1970, Month.AUGUST, 7, 10, 0).toInstant(ZoneOffset.UTC).toEpochMilli(); + LogRecordData log = + TestLogRecordData.builder() + .setResource(Resource.empty()) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("logTest").setVersion("1.0").build()) + .setBody("message") + .setSeverity(Severity.ERROR3) + .setEventName("my.event") + .setTimestamp(timestamp, TimeUnit.MILLISECONDS) + .setSpanContext( + SpanContext.create( + "00000000000000010000000000000002", + "0000000000000003", + TraceFlags.getDefault(), + TraceState.getDefault())) + .build(); + StringBuilder output = new StringBuilder(); + SystemOutLogRecordExporter.formatLog(output, log); + assertThat(output.toString()) + .isEqualTo( + "1970-08-07T10:00:00Z ERROR3 [eventName: my.event] 'message' : " + + "00000000000000010000000000000002 0000000000000003 [scopeInfo: logTest:1.0] {}"); + } + + @Test + void formatWithoutTimestampUsesObservedTimestamp() { + long observedTimestamp = + LocalDateTime.of(1970, Month.AUGUST, 7, 10, 0).toInstant(ZoneOffset.UTC).toEpochMilli(); + LogRecordData log = + TestLogRecordData.builder() + .setResource(Resource.empty()) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("logTest").setVersion("1.0").build()) + .setBody("message") + .setSeverity(Severity.ERROR3) + .setObservedTimestamp(observedTimestamp, TimeUnit.MILLISECONDS) + .setSpanContext( + SpanContext.create( + "00000000000000010000000000000002", + "0000000000000003", + TraceFlags.getDefault(), + TraceState.getDefault())) + .build(); + StringBuilder output = new StringBuilder(); + SystemOutLogRecordExporter.formatLog(output, log); + assertThat(output.toString()) + .isEqualTo( + "1970-08-07T10:00:00Z ERROR3 'message' : 00000000000000010000000000000002 " + + "0000000000000003 [scopeInfo: logTest:1.0] {}"); + } + + @Test + void shutdown() { + SystemOutLogRecordExporter exporter = SystemOutLogRecordExporter.create(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + assertThat( + exporter + .export(Collections.singletonList(sampleLog(System.currentTimeMillis()))) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + assertThat(exporter.shutdown().isSuccess()).isTrue(); + } + + @Test + void stringRepresentation() { + assertThat(SystemOutLogRecordExporter.create().toString()) + .isEqualTo("SystemOutLogRecordExporter{}"); + } + + private static LogRecordData sampleLog(long timestamp) { + return TestLogRecordData.builder() + .setResource(Resource.empty()) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("logTest").setVersion("1.0").build()) + .setAttributes( + Attributes.builder() + .put(stringKey("cheese"), "cheddar") + .put(longKey("amount"), 1L) + .put(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .put(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .put(valueKey("heterogeneousArray"), Value.of(Value.of("string"), Value.of(123L))) + .put(valueKey("empty"), Value.empty()) + .build()) + .setBody("message") + .setSeverity(Severity.ERROR3) + .setTimestamp(timestamp, TimeUnit.MILLISECONDS) + .setSpanContext( + SpanContext.create( + "00000000000000010000000000000002", + "0000000000000003", + TraceFlags.getDefault(), + TraceState.getDefault())) + .build(); + } +} diff --git a/exporters/otlp-http/build.gradle.kts b/exporters/otlp-http/build.gradle.kts deleted file mode 100644 index a75b7e9c182..00000000000 --- a/exporters/otlp-http/build.gradle.kts +++ /dev/null @@ -1,10 +0,0 @@ -subprojects { - // Workaround https://github.com/gradle/gradle/issues/847 - group = "io.opentelemetry.exporter.otlp.http" - val proj = this - plugins.withId("java") { - configure { - archivesName.set("opentelemetry-exporter-otlp-http-${proj.name}") - } - } -} diff --git a/exporters/otlp-http/logs/build.gradle.kts b/exporters/otlp-http/logs/build.gradle.kts deleted file mode 100644 index 7be794f7773..00000000000 --- a/exporters/otlp-http/logs/build.gradle.kts +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Protocol HTTP Logs Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.http.logs") - -dependencies { - api(project(":sdk:logs")) - - implementation(project(":exporters:otlp:common")) - - implementation("com.squareup.okhttp3:okhttp") - - testImplementation(project(":sdk:testing")) - - testImplementation("com.google.api.grpc:proto-google-common-protos") - testImplementation("com.linecorp.armeria:armeria-junit5") - testImplementation("com.squareup.okhttp3:okhttp-tls") - testImplementation("io.opentelemetry.proto:opentelemetry-proto") -} diff --git a/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporter.java b/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporter.java deleted file mode 100644 index dd05f5789ab..00000000000 --- a/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporter.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.logs; - -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.otlp.logs.LogsRequestMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import java.util.Collection; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports logs using OTLP via HTTP, using OpenTelemetry's protobuf model. */ -@ThreadSafe -public final class OtlpHttpLogExporter implements LogExporter { - - private final OkHttpExporter delegate; - - OtlpHttpLogExporter(OkHttpExporter delegate) { - this.delegate = delegate; - } - - /** - * Returns a new {@link OtlpHttpLogExporter} using the default values. - * - * @return a new {@link OtlpHttpLogExporter} instance. - */ - public static OtlpHttpLogExporter getDefault() { - return builder().build(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static OtlpHttpLogExporterBuilder builder() { - return new OtlpHttpLogExporterBuilder(); - } - - /** - * Submits all the given logs in a single batch to the OpenTelemetry collector. - * - * @param logs the list of sampled Logs to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection logs) { - LogsRequestMarshaler exportRequest = LogsRequestMarshaler.create(logs); - return delegate.export(exportRequest, logs.size()); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** Shutdown the exporter. */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } -} diff --git a/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporterBuilder.java b/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporterBuilder.java deleted file mode 100644 index 9ff5b53e215..00000000000 --- a/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporterBuilder.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.logs; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.logs.LogsRequestMarshaler; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder utility for {@link OtlpHttpLogExporter}. */ -public final class OtlpHttpLogExporterBuilder { - - private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/logs"; - - private final OkHttpExporterBuilder delegate; - - OtlpHttpLogExporterBuilder() { - delegate = new OkHttpExporterBuilder<>("otlp", "log", DEFAULT_ENDPOINT); - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, - * defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpHttpLogExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, - * defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpHttpLogExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - /** - * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The - * endpoint must start with either http:// or https://, and include the full HTTP path. - */ - public OtlpHttpLogExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the method used to compress payloads. If unset, compression is disabled. Currently - * supported compression methods include "gzip" and "none". - */ - public OtlpHttpLogExporterBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - delegate.setCompression(compressionMethod); - return this; - } - - /** Add header to requests. */ - public OtlpHttpLogExporterBuilder addHeader(String key, String value) { - delegate.addHeader(key, value); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public OtlpHttpLogExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** - * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled. - */ - public OtlpHttpLogExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, metrics - * will not be collected. - */ - public OtlpHttpLogExporterBuilder setMeterProvider(MeterProvider meterProvider) { - requireNonNull(meterProvider, "meterProvider"); - delegate.setMeterProvider(meterProvider); - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance - */ - public OtlpHttpLogExporter build() { - return new OtlpHttpLogExporter(delegate.build()); - } -} diff --git a/exporters/otlp-http/logs/src/test/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporterTest.java b/exporters/otlp-http/logs/src/test/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporterTest.java deleted file mode 100644 index e92e25acae7..00000000000 --- a/exporters/otlp-http/logs/src/test/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogExporterTest.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.logs; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Message; -import com.google.rpc.Status; -import com.linecorp.armeria.common.AggregatedHttpRequest; -import com.linecorp.armeria.common.HttpMethod; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.common.MediaType; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; -import com.linecorp.armeria.testing.junit5.server.mock.RecordedRequest; -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; -import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse; -import io.opentelemetry.proto.logs.v1.ResourceLogs; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.time.Instant; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import okhttp3.tls.HeldCertificate; -import okio.Buffer; -import okio.GzipSource; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.slf4j.event.Level; -import org.slf4j.event.LoggingEvent; - -class OtlpHttpLogExporterTest { - - private static final MediaType APPLICATION_PROTOBUF = - MediaType.create("application", "x-protobuf"); - private static final HeldCertificate HELD_CERTIFICATE; - private static final String canonicalHostName; - - static { - try { - canonicalHostName = InetAddress.getByName("localhost").getCanonicalHostName(); - HELD_CERTIFICATE = - new HeldCertificate.Builder() - .commonName("localhost") - .addSubjectAlternativeName(canonicalHostName) - .build(); - } catch (UnknownHostException e) { - throw new IllegalStateException("Error building certificate.", e); - } - } - - @RegisterExtension - static MockWebServerExtension server = - new MockWebServerExtension() { - @Override - protected void configureServer(ServerBuilder sb) { - sb.http(0); - sb.https(0); - sb.tls(HELD_CERTIFICATE.keyPair().getPrivate(), HELD_CERTIFICATE.certificate()); - } - }; - - @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(OkHttpExporter.class); - - private OtlpHttpLogExporterBuilder builder; - - @BeforeEach - void setup() { - builder = - OtlpHttpLogExporter.builder() - .setEndpoint("http://" + canonicalHostName + ":" + server.httpPort() + "/v1/logs") - .addHeader("foo", "bar"); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void validConfig() { - assertThatCode(() -> OtlpHttpLogExporter.builder().setTimeout(0, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpLogExporter.builder().setTimeout(Duration.ofMillis(0))) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpLogExporter.builder().setTimeout(10, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpLogExporter.builder().setTimeout(Duration.ofMillis(10))) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpLogExporter.builder().setEndpoint("http://" + canonicalHostName + ":4317")) - .doesNotThrowAnyException(); - assertThatCode( - () -> OtlpHttpLogExporter.builder().setEndpoint("http://" + canonicalHostName + "")) - .doesNotThrowAnyException(); - assertThatCode( - () -> OtlpHttpLogExporter.builder().setEndpoint("https://" + canonicalHostName + "")) - .doesNotThrowAnyException(); - assertThatCode( - () -> - OtlpHttpLogExporter.builder() - .setEndpoint("http://foo:bar@" + canonicalHostName + "")) - .doesNotThrowAnyException(); - - assertThatCode(() -> OtlpHttpLogExporter.builder().setCompression("gzip")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpLogExporter.builder().setCompression("none")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> OtlpHttpLogExporter.builder().addHeader("foo", "bar").addHeader("baz", "qux")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpLogExporter.builder() - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpLogExporter.builder() - .setClientTls( - "foobar".getBytes(StandardCharsets.UTF_8), - "foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void invalidConfig() { - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy( - () -> OtlpHttpLogExporter.builder().setEndpoint("😺://" + canonicalHostName + "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must be a URL: 😺://" + canonicalHostName + ""); - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setEndpoint("" + canonicalHostName + "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Invalid endpoint, must start with http:// or https://: " + canonicalHostName + ""); - assertThatThrownBy( - () -> OtlpHttpLogExporter.builder().setEndpoint("gopher://" + canonicalHostName + "")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Invalid endpoint, must start with http:// or https://: gopher://" - + canonicalHostName - + ""); - - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setCompression(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("compressionMethod"); - assertThatThrownBy(() -> OtlpHttpLogExporter.builder().setCompression("foo")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Unsupported compression method. Supported compression methods include: gzip, none."); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpHttpLogExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void testExportUncompressed() { - server.enqueue(successResponse()); - OtlpHttpLogExporter exporter = builder.build(); - - ExportLogsServiceRequest payload = exportAndAssertResult(exporter, /* expectedResult= */ true); - RecordedRequest recorded = server.takeRequest(); - AggregatedHttpRequest request = recorded.request(); - assertRequestCommon(request); - assertThat(parseRequestBody(request.content().array())).isEqualTo(payload); - - // OkHttp does not support HTTP/2 upgrade on plaintext. - assertThat(recorded.context().sessionProtocol().isMultiplex()).isFalse(); - } - - @Test - void testExportTls() { - server.enqueue(successResponse()); - OtlpHttpLogExporter exporter = - builder - .setEndpoint("https://" + canonicalHostName + ":" + server.httpsPort() + "/v1/logs") - .setTrustedCertificates( - HELD_CERTIFICATE.certificatePem().getBytes(StandardCharsets.UTF_8)) - .build(); - - ExportLogsServiceRequest payload = exportAndAssertResult(exporter, /* expectedResult= */ true); - RecordedRequest recorded = server.takeRequest(); - AggregatedHttpRequest request = recorded.request(); - assertRequestCommon(request); - assertThat(parseRequestBody(request.content().array())).isEqualTo(payload); - - // OkHttp does support HTTP/2 upgrade on TLS. - assertThat(recorded.context().sessionProtocol().isMultiplex()).isTrue(); - } - - @Test - void testExportGzipCompressed() { - server.enqueue(successResponse()); - OtlpHttpLogExporter exporter = builder.setCompression("gzip").build(); - - ExportLogsServiceRequest payload = exportAndAssertResult(exporter, /* expectedResult= */ true); - AggregatedHttpRequest request = server.takeRequest().request(); - assertRequestCommon(request); - assertThat(request.headers().get("Content-Encoding")).isEqualTo("gzip"); - assertThat(parseRequestBody(gzipDecompress(request.content().array()))).isEqualTo(payload); - } - - private static void assertRequestCommon(AggregatedHttpRequest request) { - assertThat(request.method()).isEqualTo(HttpMethod.POST); - assertThat(request.path()).isEqualTo("/v1/logs"); - assertThat(request.headers().get("foo")).isEqualTo("bar"); - assertThat(request.headers().get("Content-Type")).isEqualTo(APPLICATION_PROTOBUF.toString()); - } - - private static ExportLogsServiceRequest parseRequestBody(byte[] bytes) { - try { - return ExportLogsServiceRequest.parseFrom(bytes); - } catch (InvalidProtocolBufferException e) { - throw new IllegalStateException("Unable to parse Protobuf request body.", e); - } - } - - private static byte[] gzipDecompress(byte[] bytes) { - try { - Buffer result = new Buffer(); - GzipSource source = new GzipSource(new Buffer().write(bytes)); - while (source.read(result, Integer.MAX_VALUE) != -1) {} - return result.readByteArray(); - } catch (IOException e) { - throw new IllegalStateException("Unable to decompress payload.", e); - } - } - - @Test - @SuppressLogger(OkHttpExporter.class) - void testServerError() { - server.enqueue( - buildResponse( - HttpStatus.INTERNAL_SERVER_ERROR, - Status.newBuilder().setMessage("Server error!").build())); - OtlpHttpLogExporter exporter = builder.build(); - - exportAndAssertResult(exporter, /* expectedResult= */ false); - LoggingEvent log = - logs.assertContains( - "Failed to export logs. Server responded with HTTP status code 500. Error message: Server error!"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - } - - @Test - @SuppressLogger(OkHttpExporter.class) - void testServerErrorParseError() { - server.enqueue( - HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, APPLICATION_PROTOBUF, "Server error!")); - OtlpHttpLogExporter exporter = builder.build(); - - exportAndAssertResult(exporter, /* expectedResult= */ false); - LoggingEvent log = - logs.assertContains( - "Failed to export logs. Server responded with HTTP status code 500. Error message: Unable to parse response body, HTTP status message:"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - } - - private static ExportLogsServiceRequest exportAndAssertResult( - OtlpHttpLogExporter otlpHttpLogExporter, boolean expectedResult) { - List logs = Collections.singletonList(generateFakeLog()); - CompletableResultCode resultCode = otlpHttpLogExporter.export(logs); - resultCode.join(10, TimeUnit.SECONDS); - assertThat(resultCode.isSuccess()).isEqualTo(expectedResult); - List resourceLogs = - Arrays.stream(ResourceLogsMarshaler.create(logs)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - return ResourceLogs.parseFrom(bos.toByteArray()); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) - .collect(Collectors.toList()); - return ExportLogsServiceRequest.newBuilder().addAllResourceLogs(resourceLogs).build(); - } - - private static HttpResponse successResponse() { - ExportLogsServiceResponse exportLogsServiceResponse = - ExportLogsServiceResponse.newBuilder().build(); - return buildResponse(HttpStatus.OK, exportLogsServiceResponse); - } - - private static HttpResponse buildResponse(HttpStatus httpStatus, T message) { - return HttpResponse.of(httpStatus, APPLICATION_PROTOBUF, message.toByteArray()); - } - - private static LogData generateFakeLog() { - return LogDataBuilder.create( - Resource.getDefault(), InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) - .setBody("log body") - .setAttributes(Attributes.builder().put("key", "value").build()) - .setSeverity(Severity.INFO) - .setSeverityText(Severity.INFO.name()) - .setEpoch(Instant.now()) - .build(); - } -} diff --git a/exporters/otlp-http/metrics/README.md b/exporters/otlp-http/metrics/README.md deleted file mode 100644 index b15e95db526..00000000000 --- a/exporters/otlp-http/metrics/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenTelemetry - OTLP Metrics Exporter - HTTP - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry exporter, sending metric data to OpenTelemetry collector via HTTP without gRPC. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-http-metrics.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-http-metrics diff --git a/exporters/otlp-http/metrics/build.gradle.kts b/exporters/otlp-http/metrics/build.gradle.kts deleted file mode 100644 index 200f15578b0..00000000000 --- a/exporters/otlp-http/metrics/build.gradle.kts +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Protocol HTTP Metrics Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.http.metrics") - -dependencies { - api(project(":sdk:metrics")) - - implementation(project(":exporters:otlp:common")) - - implementation("com.squareup.okhttp3:okhttp") - - testImplementation(project(":sdk:testing")) - - testImplementation("com.google.api.grpc:proto-google-common-protos") - testImplementation("com.linecorp.armeria:armeria-junit5") - testImplementation("com.squareup.okhttp3:okhttp-tls") - testImplementation("io.opentelemetry.proto:opentelemetry-proto") -} diff --git a/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporter.java b/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporter.java deleted file mode 100644 index 1015832a142..00000000000 --- a/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.metrics; - -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import java.util.Collection; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports metrics using OTLP via HTTP, using OpenTelemetry's protobuf model. */ -@ThreadSafe -public final class OtlpHttpMetricExporter implements MetricExporter { - - private final OkHttpExporter delegate; - private final AggregationTemporalitySelector aggregationTemporalitySelector; - - OtlpHttpMetricExporter( - OkHttpExporter delegate, - AggregationTemporalitySelector aggregationTemporalitySelector) { - this.delegate = delegate; - this.aggregationTemporalitySelector = aggregationTemporalitySelector; - } - - /** - * Returns a new {@link OtlpHttpMetricExporter} using the default values. - * - * @return a new {@link OtlpHttpMetricExporter} instance. - */ - public static OtlpHttpMetricExporter getDefault() { - return builder().build(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static OtlpHttpMetricExporterBuilder builder() { - return new OtlpHttpMetricExporterBuilder(); - } - - @Override - public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); - } - - /** - * Submits all the given metrics in a single batch to the OpenTelemetry collector. - * - * @param metrics the list of sampled Metrics to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection metrics) { - MetricsRequestMarshaler exportRequest = MetricsRequestMarshaler.create(metrics); - return delegate.export(exportRequest, metrics.size()); - } - - /** - * The OTLP exporter does not batch metrics, so this method will immediately return with success. - * - * @return always Success - */ - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** Shutdown the exporter. */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } -} diff --git a/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java b/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java deleted file mode 100644 index eaf69eaf6a8..00000000000 --- a/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.metrics; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder utility for {@link OtlpHttpMetricExporter}. */ -public final class OtlpHttpMetricExporterBuilder { - - private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/metrics"; - - private static final AggregationTemporalitySelector DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = - AggregationTemporalitySelector.alwaysCumulative(); - - private final OkHttpExporterBuilder delegate; - private AggregationTemporalitySelector aggregationTemporalitySelector = - DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; - - OtlpHttpMetricExporterBuilder() { - delegate = new OkHttpExporterBuilder<>("otlp", "metric", DEFAULT_ENDPOINT); - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of metrics. If - * unset, defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpHttpMetricExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of metrics. If - * unset, defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpHttpMetricExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - /** - * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The - * endpoint must start with either http:// or https://, and include the full HTTP path. - */ - public OtlpHttpMetricExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the method used to compress payloads. If unset, compression is disabled. Currently - * supported compression methods include "gzip" and "none". - */ - public OtlpHttpMetricExporterBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - delegate.setCompression(compressionMethod); - return this; - } - - /** Add header to requests. */ - public OtlpHttpMetricExporterBuilder addHeader(String key, String value) { - delegate.addHeader(key, value); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public OtlpHttpMetricExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** - * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled. - */ - public OtlpHttpMetricExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Set the {@link AggregationTemporalitySelector} used for {@link - * MetricExporter#getAggregationTemporality(InstrumentType)}. - * - *

    If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}. - * - *

    {@link AggregationTemporalitySelector#deltaPreferred()} is a common configuration for delta - * backends. - */ - public OtlpHttpMetricExporterBuilder setAggregationTemporalitySelector( - AggregationTemporalitySelector aggregationTemporalitySelector) { - requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector"); - this.aggregationTemporalitySelector = aggregationTemporalitySelector; - return this; - } - - OtlpHttpMetricExporterBuilder exportAsJson() { - delegate.exportAsJson(); - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance - */ - public OtlpHttpMetricExporter build() { - return new OtlpHttpMetricExporter(delegate.build(), aggregationTemporalitySelector); - } -} diff --git a/exporters/otlp-http/metrics/src/test/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterTest.java b/exporters/otlp-http/metrics/src/test/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterTest.java deleted file mode 100644 index d4a7d69ca1e..00000000000 --- a/exporters/otlp-http/metrics/src/test/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterTest.java +++ /dev/null @@ -1,394 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Message; -import com.google.rpc.Status; -import com.linecorp.armeria.common.AggregatedHttpRequest; -import com.linecorp.armeria.common.HttpMethod; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.common.MediaType; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; -import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; -import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; -import io.opentelemetry.proto.metrics.v1.ResourceMetrics; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import okhttp3.tls.HeldCertificate; -import okio.Buffer; -import okio.GzipSource; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.slf4j.event.Level; -import org.slf4j.event.LoggingEvent; - -class OtlpHttpMetricExporterTest { - - private static final MediaType APPLICATION_PROTOBUF = - MediaType.create("application", "x-protobuf"); - private static final MediaType APPLICATION_JSON = MediaType.create("application", "json"); - private static final HeldCertificate HELD_CERTIFICATE; - private static final String canonicalHostName; - - static { - try { - canonicalHostName = InetAddress.getByName("localhost").getCanonicalHostName(); - HELD_CERTIFICATE = - new HeldCertificate.Builder() - .commonName("localhost") - .addSubjectAlternativeName(canonicalHostName) - .build(); - } catch (UnknownHostException e) { - throw new IllegalStateException("Error building certificate.", e); - } - } - - @RegisterExtension - static MockWebServerExtension server = - new MockWebServerExtension() { - @Override - protected void configureServer(ServerBuilder sb) { - sb.tls(HELD_CERTIFICATE.keyPair().getPrivate(), HELD_CERTIFICATE.certificate()); - } - }; - - @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(OkHttpExporter.class); - - private OtlpHttpMetricExporterBuilder builder; - - @BeforeEach - void setup() { - builder = - OtlpHttpMetricExporter.builder() - .setEndpoint("https://" + canonicalHostName + ":" + server.httpsPort() + "/v1/metrics") - .addHeader("foo", "bar") - .setTrustedCertificates( - HELD_CERTIFICATE.certificatePem().getBytes(StandardCharsets.UTF_8)); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void validConfig() { - assertThatCode(() -> OtlpHttpMetricExporter.builder().setTimeout(0, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setTimeout(Duration.ofMillis(0))) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setTimeout(10, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setTimeout(Duration.ofMillis(10))) - .doesNotThrowAnyException(); - - assertThatCode(() -> OtlpHttpMetricExporter.builder().setEndpoint("http://localhost:4318")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setEndpoint("http://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setEndpoint("https://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setEndpoint("http://foo:bar@localhost")) - .doesNotThrowAnyException(); - - assertThatCode(() -> OtlpHttpMetricExporter.builder().setCompression("gzip")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpMetricExporter.builder().setCompression("none")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> OtlpHttpMetricExporter.builder().addHeader("foo", "bar").addHeader("baz", "qux")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpMetricExporter.builder() - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpMetricExporter.builder() - .setClientTls( - "foobar".getBytes(StandardCharsets.UTF_8), - "foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpMetricExporter.builder() - .setAggregationTemporalitySelector( - AggregationTemporalitySelector.deltaPreferred())) - .doesNotThrowAnyException(); - assertThat( - OtlpHttpMetricExporter.builder() - .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) - .build() - .getAggregationTemporality(InstrumentType.COUNTER)) - .isEqualTo(AggregationTemporality.DELTA); - assertThat( - OtlpHttpMetricExporter.builder() - .build() - .getAggregationTemporality(InstrumentType.COUNTER)) - .isEqualTo(AggregationTemporality.CUMULATIVE); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void invalidConfig() { - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setEndpoint("😺://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must be a URL: 😺://localhost"); - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setEndpoint("localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setEndpoint("gopher://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); - - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setCompression(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("compressionMethod"); - assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setCompression("foo")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Unsupported compression method. Supported compression methods include: gzip, none."); - - assertThatThrownBy( - () -> OtlpHttpMetricExporter.builder().setAggregationTemporalitySelector(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("aggregationTemporalitySelector"); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpHttpMetricExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void testExportUncompressed() { - server.enqueue(successResponse()); - OtlpHttpMetricExporter exporter = builder.build(); - - ExportMetricsServiceRequest payload = - exportAndAssertResult(exporter, /* expectedResult= */ true); - AggregatedHttpRequest request = server.takeRequest().request(); - assertRequestCommon(request); - assertThat(parseRequestBody(request.content().array())).isEqualTo(payload); - } - - @Test - void testExportGzipCompressed() { - server.enqueue(successResponse()); - OtlpHttpMetricExporter exporter = builder.setCompression("gzip").build(); - - ExportMetricsServiceRequest payload = - exportAndAssertResult(exporter, /* expectedResult= */ true); - AggregatedHttpRequest request = server.takeRequest().request(); - assertRequestCommon(request); - assertThat(request.headers().get("Content-Encoding")).isEqualTo("gzip"); - assertThat(parseRequestBody(gzipDecompress(request.content().array()))).isEqualTo(payload); - } - - @Test - void testExportAsJson() { - server.enqueue(successResponse()); - OtlpHttpMetricExporter exporter = builder.exportAsJson().build(); - - String payload = exportJsonAndAssertResult(exporter, /* expectedResult= */ true); - AggregatedHttpRequest request = server.takeRequest().request(); - assertRequestCommon(request, /* isJson= */ true); - assertThat(parseJsonRequestBody(request.content().array())).isEqualTo(payload); - } - - @Test - void testExport_flush() { - OtlpHttpMetricExporter exporter = OtlpHttpMetricExporter.builder().build(); - try { - assertThat(exporter.flush().isSuccess()).isTrue(); - } finally { - exporter.shutdown(); - } - } - - private static void assertRequestCommon(AggregatedHttpRequest request) { - assertRequestCommon(request, /* isJson= */ false); - } - - private static void assertRequestCommon(AggregatedHttpRequest request, boolean isJson) { - assertThat(request.method()).isEqualTo(HttpMethod.POST); - assertThat(request.path()).isEqualTo("/v1/metrics"); - assertThat(request.headers().get("foo")).isEqualTo("bar"); - MediaType mediaType = isJson ? APPLICATION_JSON : APPLICATION_PROTOBUF; - assertThat(request.headers().get("Content-Type")).isEqualTo(mediaType.toString()); - } - - private static ExportMetricsServiceRequest parseRequestBody(byte[] bytes) { - try { - return ExportMetricsServiceRequest.parseFrom(bytes); - } catch (InvalidProtocolBufferException e) { - throw new IllegalStateException("Unable to parse Protobuf request body.", e); - } - } - - private static String parseJsonRequestBody(byte[] bytes) { - return new String(bytes, StandardCharsets.UTF_8); - } - - private static byte[] gzipDecompress(byte[] bytes) { - try { - Buffer result = new Buffer(); - GzipSource source = new GzipSource(new Buffer().write(bytes)); - while (source.read(result, Integer.MAX_VALUE) != -1) {} - return result.readByteArray(); - } catch (IOException e) { - throw new IllegalStateException("Unable to decompress payload.", e); - } - } - - @Test - @SuppressLogger(OkHttpExporter.class) - void testServerError() { - server.enqueue( - buildResponse( - HttpStatus.INTERNAL_SERVER_ERROR, - Status.newBuilder().setMessage("Server error!").build())); - OtlpHttpMetricExporter exporter = builder.build(); - - exportAndAssertResult(exporter, /* expectedResult= */ false); - LoggingEvent log = - logs.assertContains( - "Failed to export metrics. Server responded with HTTP status code 500. Error message: Server error!"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - } - - @Test - @SuppressLogger(OkHttpExporter.class) - void testServerErrorParseError() { - server.enqueue( - HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, APPLICATION_PROTOBUF, "Server error!")); - OtlpHttpMetricExporter exporter = builder.build(); - - exportAndAssertResult(exporter, /* expectedResult= */ false); - LoggingEvent log = - logs.assertContains( - "Failed to export metrics. Server responded with HTTP status code 500. Error message: Unable to parse response body, HTTP status message:"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - } - - private static ExportMetricsServiceRequest exportAndAssertResult( - OtlpHttpMetricExporter otlpHttpMetricExporter, boolean expectedResult) { - List metrics = Collections.singletonList(generateFakeMetric()); - CompletableResultCode resultCode = otlpHttpMetricExporter.export(metrics); - resultCode.join(10, TimeUnit.SECONDS); - assertThat(resultCode.isSuccess()).isEqualTo(expectedResult); - List resourceMetrics = - Arrays.stream(ResourceMetricsMarshaler.create(metrics)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - return ResourceMetrics.parseFrom(bos.toByteArray()); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) - .collect(Collectors.toList()); - return ExportMetricsServiceRequest.newBuilder().addAllResourceMetrics(resourceMetrics).build(); - } - - private static String exportJsonAndAssertResult( - OtlpHttpMetricExporter otlpHttpMetricExporter, boolean expectedResult) { - List metrics = Collections.singletonList(generateFakeMetric()); - CompletableResultCode resultCode = otlpHttpMetricExporter.export(metrics); - resultCode.join(10, TimeUnit.SECONDS); - assertThat(resultCode.isSuccess()).isEqualTo(expectedResult); - try (ByteArrayOutputStream jsonBos = new ByteArrayOutputStream()) { - MetricsRequestMarshaler.create(metrics).writeJsonTo(jsonBos); - return new String(jsonBos.toByteArray(), StandardCharsets.UTF_8); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - private static HttpResponse successResponse() { - ExportMetricsServiceResponse exportMetricsServiceResponse = - ExportMetricsServiceResponse.newBuilder().build(); - return buildResponse(HttpStatus.OK, exportMetricsServiceResponse); - } - - private static HttpResponse buildResponse(HttpStatus httpStatus, T message) { - return HttpResponse.of(httpStatus, APPLICATION_PROTOBUF, message.toByteArray()); - } - - private static MetricData generateFakeMetric() { - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + TimeUnit.MILLISECONDS.toNanos(900); - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - startNs, endNs, Attributes.of(stringKey("k"), "v"), 5)))); - } -} diff --git a/exporters/otlp-http/trace/README.md b/exporters/otlp-http/trace/README.md deleted file mode 100644 index c7f09e2e5ed..00000000000 --- a/exporters/otlp-http/trace/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenTelemetry - OTLP Trace Exporter - HTTP - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry exporter, sending span data to OpenTelemetry collector via HTTP without gRPC. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-http-trace.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-http-trace diff --git a/exporters/otlp-http/trace/build.gradle.kts b/exporters/otlp-http/trace/build.gradle.kts deleted file mode 100644 index d8938593dee..00000000000 --- a/exporters/otlp-http/trace/build.gradle.kts +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Protocol HTTP Trace Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.http.trace") - -dependencies { - api(project(":sdk:trace")) - - implementation(project(":exporters:otlp:common")) - - implementation("com.squareup.okhttp3:okhttp") - - testImplementation(project(":sdk:testing")) - - testImplementation("com.google.api.grpc:proto-google-common-protos") - testImplementation("com.linecorp.armeria:armeria-junit5") - testImplementation("com.squareup.okhttp3:okhttp-tls") - testImplementation("io.opentelemetry.proto:opentelemetry-proto") -} diff --git a/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporter.java b/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporter.java deleted file mode 100644 index 6eada480db7..00000000000 --- a/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.trace; - -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Collection; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports spans using OTLP via HTTP, using OpenTelemetry's protobuf model. */ -@ThreadSafe -public final class OtlpHttpSpanExporter implements SpanExporter { - - private final OkHttpExporter delegate; - - OtlpHttpSpanExporter(OkHttpExporter delegate) { - this.delegate = delegate; - } - - /** - * Returns a new {@link OtlpHttpSpanExporter} using the default values. - * - * @return a new {@link OtlpHttpSpanExporter} instance. - */ - public static OtlpHttpSpanExporter getDefault() { - return builder().build(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static OtlpHttpSpanExporterBuilder builder() { - return new OtlpHttpSpanExporterBuilder(); - } - - /** - * Submits all the given spans in a single batch to the OpenTelemetry collector. - * - * @param spans the list of sampled Spans to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection spans) { - TraceRequestMarshaler exportRequest = TraceRequestMarshaler.create(spans); - return delegate.export(exportRequest, spans.size()); - } - - /** - * The OTLP exporter does not batch spans, so this method will immediately return with success. - * - * @return always Success - */ - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** Shutdown the exporter. */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } -} diff --git a/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterBuilder.java b/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterBuilder.java deleted file mode 100644 index 97571a52f52..00000000000 --- a/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterBuilder.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.trace; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder utility for {@link OtlpHttpSpanExporter}. */ -public final class OtlpHttpSpanExporterBuilder { - - private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/traces"; - - private final OkHttpExporterBuilder delegate; - - OtlpHttpSpanExporterBuilder() { - delegate = new OkHttpExporterBuilder<>("otlp", "span", DEFAULT_ENDPOINT); - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of spans. If - * unset, defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpHttpSpanExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of spans. If - * unset, defaults to {@value OkHttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpHttpSpanExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - /** - * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The - * endpoint must start with either http:// or https://, and include the full HTTP path. - */ - public OtlpHttpSpanExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the method used to compress payloads. If unset, compression is disabled. Currently - * supported compression methods include "gzip" and "none". - */ - public OtlpHttpSpanExporterBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - delegate.setCompression(compressionMethod); - return this; - } - - /** Add header to requests. */ - public OtlpHttpSpanExporterBuilder addHeader(String key, String value) { - delegate.addHeader(key, value); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public OtlpHttpSpanExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** - * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled. - */ - public OtlpHttpSpanExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, metrics - * will not be collected. - */ - public OtlpHttpSpanExporterBuilder setMeterProvider(MeterProvider meterProvider) { - requireNonNull(meterProvider, "meterProvider"); - delegate.setMeterProvider(meterProvider); - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance - */ - public OtlpHttpSpanExporter build() { - return new OtlpHttpSpanExporter(delegate.build()); - } -} diff --git a/exporters/otlp-http/trace/src/test/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterTest.java b/exporters/otlp-http/trace/src/test/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterTest.java deleted file mode 100644 index 0389f3cbebc..00000000000 --- a/exporters/otlp-http/trace/src/test/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterTest.java +++ /dev/null @@ -1,353 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.http.trace; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.protobuf.InvalidProtocolBufferException; -import com.google.protobuf.Message; -import com.google.rpc.Status; -import com.linecorp.armeria.common.AggregatedHttpRequest; -import com.linecorp.armeria.common.HttpMethod; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.common.MediaType; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; -import com.linecorp.armeria.testing.junit5.server.mock.RecordedRequest; -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; -import io.opentelemetry.proto.trace.v1.ResourceSpans; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import okhttp3.tls.HeldCertificate; -import okio.Buffer; -import okio.GzipSource; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.slf4j.event.Level; -import org.slf4j.event.LoggingEvent; - -class OtlpHttpSpanExporterTest { - - private static final MediaType APPLICATION_PROTOBUF = - MediaType.create("application", "x-protobuf"); - private static final HeldCertificate HELD_CERTIFICATE; - private static final String canonicalHostName; - - static { - try { - canonicalHostName = InetAddress.getByName("localhost").getCanonicalHostName(); - HELD_CERTIFICATE = - new HeldCertificate.Builder() - .commonName("localhost") - .addSubjectAlternativeName(canonicalHostName) - .build(); - } catch (UnknownHostException e) { - throw new IllegalStateException("Error building certificate.", e); - } - } - - @RegisterExtension - static MockWebServerExtension server = - new MockWebServerExtension() { - @Override - protected void configureServer(ServerBuilder sb) { - sb.http(0); - sb.https(0); - sb.tls(HELD_CERTIFICATE.keyPair().getPrivate(), HELD_CERTIFICATE.certificate()); - } - }; - - @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(OkHttpExporter.class); - - private OtlpHttpSpanExporterBuilder builder; - - @BeforeEach - void setup() { - builder = - OtlpHttpSpanExporter.builder() - .setEndpoint("http://" + canonicalHostName + ":" + server.httpPort() + "/v1/traces") - .addHeader("foo", "bar"); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void validConfig() { - assertThatCode(() -> OtlpHttpSpanExporter.builder().setTimeout(0, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setTimeout(Duration.ofMillis(0))) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setTimeout(10, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setTimeout(Duration.ofMillis(10))) - .doesNotThrowAnyException(); - - assertThatCode(() -> OtlpHttpSpanExporter.builder().setEndpoint("http://localhost:4318")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setEndpoint("http://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setEndpoint("https://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setEndpoint("http://foo:bar@localhost")) - .doesNotThrowAnyException(); - - assertThatCode(() -> OtlpHttpSpanExporter.builder().setCompression("gzip")) - .doesNotThrowAnyException(); - assertThatCode(() -> OtlpHttpSpanExporter.builder().setCompression("none")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> OtlpHttpSpanExporter.builder().addHeader("foo", "bar").addHeader("baz", "qux")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpSpanExporter.builder() - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - OtlpHttpSpanExporter.builder() - .setClientTls( - "foobar".getBytes(StandardCharsets.UTF_8), - "foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void invalidConfig() { - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setEndpoint("😺://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must be a URL: 😺://localhost"); - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setEndpoint("localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setEndpoint("gopher://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); - - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setCompression(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("compressionMethod"); - assertThatThrownBy(() -> OtlpHttpSpanExporter.builder().setCompression("foo")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Unsupported compression method. Supported compression methods include: gzip, none."); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpHttpSpanExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void testExportUncompressed() { - server.enqueue(successResponse()); - OtlpHttpSpanExporter exporter = builder.build(); - - ExportTraceServiceRequest payload = exportAndAssertResult(exporter, /* expectedResult= */ true); - RecordedRequest recorded = server.takeRequest(); - AggregatedHttpRequest request = recorded.request(); - assertRequestCommon(request); - assertThat(parseRequestBody(request.content().array())).isEqualTo(payload); - - // OkHttp does not support HTTP/2 upgrade on plaintext. - assertThat(recorded.context().sessionProtocol().isMultiplex()).isFalse(); - } - - @Test - void testExportTls() { - server.enqueue(successResponse()); - OtlpHttpSpanExporter exporter = - builder - .setEndpoint("https://" + canonicalHostName + ":" + server.httpsPort() + "/v1/traces") - .setTrustedCertificates( - HELD_CERTIFICATE.certificatePem().getBytes(StandardCharsets.UTF_8)) - .build(); - - ExportTraceServiceRequest payload = exportAndAssertResult(exporter, /* expectedResult= */ true); - RecordedRequest recorded = server.takeRequest(); - AggregatedHttpRequest request = recorded.request(); - assertRequestCommon(request); - assertThat(parseRequestBody(request.content().array())).isEqualTo(payload); - - // OkHttp does support HTTP/2 upgrade on TLS. - assertThat(recorded.context().sessionProtocol().isMultiplex()).isTrue(); - } - - @Test - void testExportGzipCompressed() { - server.enqueue(successResponse()); - OtlpHttpSpanExporter exporter = builder.setCompression("gzip").build(); - - ExportTraceServiceRequest payload = exportAndAssertResult(exporter, /* expectedResult= */ true); - AggregatedHttpRequest request = server.takeRequest().request(); - assertRequestCommon(request); - assertThat(request.headers().get("Content-Encoding")).isEqualTo("gzip"); - assertThat(parseRequestBody(gzipDecompress(request.content().array()))).isEqualTo(payload); - } - - private static void assertRequestCommon(AggregatedHttpRequest request) { - assertThat(request.method()).isEqualTo(HttpMethod.POST); - assertThat(request.path()).isEqualTo("/v1/traces"); - assertThat(request.headers().get("foo")).isEqualTo("bar"); - assertThat(request.headers().get("Content-Type")).isEqualTo(APPLICATION_PROTOBUF.toString()); - } - - private static ExportTraceServiceRequest parseRequestBody(byte[] bytes) { - try { - return ExportTraceServiceRequest.parseFrom(bytes); - } catch (InvalidProtocolBufferException e) { - throw new IllegalStateException("Unable to parse Protobuf request body.", e); - } - } - - private static byte[] gzipDecompress(byte[] bytes) { - try { - Buffer result = new Buffer(); - GzipSource source = new GzipSource(new Buffer().write(bytes)); - while (source.read(result, Integer.MAX_VALUE) != -1) {} - return result.readByteArray(); - } catch (IOException e) { - throw new IllegalStateException("Unable to decompress payload.", e); - } - } - - @Test - @SuppressLogger(OkHttpExporter.class) - void testServerError() { - server.enqueue( - buildResponse( - HttpStatus.INTERNAL_SERVER_ERROR, - Status.newBuilder().setMessage("Server error!").build())); - OtlpHttpSpanExporter exporter = builder.build(); - - exportAndAssertResult(exporter, /* expectedResult= */ false); - LoggingEvent log = - logs.assertContains( - "Failed to export spans. Server responded with HTTP status code 500. Error message: Server error!"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - } - - @Test - @SuppressLogger(OkHttpExporter.class) - void testServerErrorParseError() { - server.enqueue( - HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR, APPLICATION_PROTOBUF, "Server error!")); - OtlpHttpSpanExporter exporter = builder.build(); - - exportAndAssertResult(exporter, /* expectedResult= */ false); - LoggingEvent log = - logs.assertContains( - "Failed to export spans. Server responded with HTTP status code 500. Error message: Unable to parse response body, HTTP status message:"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - } - - private static ExportTraceServiceRequest exportAndAssertResult( - OtlpHttpSpanExporter otlpHttpSpanExporter, boolean expectedResult) { - List spans = Collections.singletonList(generateFakeSpan()); - CompletableResultCode resultCode = otlpHttpSpanExporter.export(spans); - resultCode.join(10, TimeUnit.SECONDS); - assertThat(resultCode.isSuccess()).isEqualTo(expectedResult); - List resourceSpans = - Arrays.stream(ResourceSpansMarshaler.create(spans)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - return ResourceSpans.parseFrom(bos.toByteArray()); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) - .collect(Collectors.toList()); - return ExportTraceServiceRequest.newBuilder().addAllResourceSpans(resourceSpans).build(); - } - - private static HttpResponse successResponse() { - ExportTraceServiceResponse exportTraceServiceResponse = - ExportTraceServiceResponse.newBuilder().build(); - return buildResponse(HttpStatus.OK, exportTraceServiceResponse); - } - - private static HttpResponse buildResponse(HttpStatus httpStatus, T message) { - return HttpResponse.of(httpStatus, APPLICATION_PROTOBUF, message.toByteArray()); - } - - private static SpanData generateFakeSpan() { - long duration = TimeUnit.MILLISECONDS.toNanos(900); - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + duration; - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create( - "00000000000000000000000000abc123", - "0000000000def456", - TraceFlags.getDefault(), - TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(startNs) - .setEndEpochNanos(endNs) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) - .build(); - } -} diff --git a/exporters/otlp/all/README.md b/exporters/otlp/all/README.md deleted file mode 100644 index fdfb211013a..00000000000 --- a/exporters/otlp/all/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry - OTLP Exporter - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp diff --git a/exporters/otlp/all/build.gradle.kts b/exporters/otlp/all/build.gradle.kts index 657b1065d57..d16be56b911 100644 --- a/exporters/otlp/all/build.gradle.kts +++ b/exporters/otlp/all/build.gradle.kts @@ -5,12 +5,208 @@ plugins { id("otel.jmh-conventions") id("otel.animalsniffer-conventions") } +apply() -description = "OpenTelemetry Protocol Exporters" +description = "OpenTelemetry Protocol (OTLP) Exporters" otelJava.moduleName.set("io.opentelemetry.exporter.otlp") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator.config", "io.opentelemetry.sdk.autoconfigure.spi")) +// io.grpc and org.jspecify.annotations are not OSGi bundles; must use unversioned optional. +otelJava.osgiUnversionedOptionalPackages.set(listOf("io.grpc", "org.jspecify.annotations")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) base.archivesName.set("opentelemetry-exporter-otlp") dependencies { - api(project(":exporters:otlp:trace")) - api(project(":exporters:otlp:metrics")) + api(project(":sdk:trace")) + api(project(":sdk:metrics")) + api(project(":sdk:logs")) + + implementation(project(":exporters:otlp:common")) + implementation(project(":exporters:sender:okhttp")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + + compileOnly(project(":api:incubator")) + + annotationProcessor("com.google.auto.value:auto-value") + + compileOnly("io.grpc:grpc-stub") + + testImplementation(project(":exporters:otlp:testing-internal")) + testImplementation(project(":sdk-extensions:autoconfigure-spi")) + testImplementation("com.linecorp.armeria:armeria-junit5") + testImplementation("com.linecorp.armeria:armeria-grpc-protocol") + testImplementation("io.grpc:grpc-stub") + testImplementation("com.google.api.grpc:proto-google-common-protos") + + jmhImplementation(project(":sdk:testing")) + jmhImplementation(project(":exporters:sender:grpc-managed-channel")) + jmhImplementation("com.linecorp.armeria:armeria") + jmhImplementation("com.linecorp.armeria:armeria-grpc") + jmhImplementation("io.opentelemetry.proto:opentelemetry-proto") + jmhRuntimeOnly("com.squareup.okhttp3:okhttp") + jmhRuntimeOnly("io.grpc:grpc-netty") +} + +val testJavaVersion = project.findProperty("testJavaVersion") as String? + +testing { + suites { + listOf( + "LATEST", + "4.11.0" + ).forEach { + register("testOkHttpVersion$it") { + sources { + java { + setSrcDirs(listOf("src/testDefaultSender/java")) + } + } + dependencies { + implementation(project(":exporters:sender:okhttp")) + implementation(project(":exporters:otlp:testing-internal")) + + implementation(platform("com.squareup.okhttp3:okhttp-bom")) { + // Only impose dependency constraint if not testing the LATEST version, which is defined in /dependencyManagement/build.gradle.kts + if (!it.equals("LATEST")) { + version { + strictly(it) + } + } + } + + implementation("com.squareup.okhttp3:okhttp") + implementation("io.grpc:grpc-stub") + } + + targets { + all { + testTask { + // Only enable test suite for non-LATEST in GitHub CI (CI=true) + enabled = it.equals("LATEST") || "true".equals(System.getenv("CI")) + systemProperty("expected.okhttp.version", it) + } + } + } + } + } + + register("testGrpcNetty") { + dependencies { + implementation(project(":exporters:sender:grpc-managed-channel")) + implementation(project(":exporters:otlp:testing-internal")) + + implementation("io.grpc:grpc-netty") + implementation("io.grpc:grpc-stub") + implementation("io.grpc:grpc-inprocess") + } + targets { + all { + testTask { + systemProperty( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + "io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider" + ) + } + } + } + } + register("testGrpcNettyShaded") { + dependencies { + implementation(project(":exporters:sender:grpc-managed-channel")) + implementation(project(":exporters:otlp:testing-internal")) + + implementation("io.grpc:grpc-netty-shaded") + implementation("io.grpc:grpc-stub") + implementation("io.grpc:grpc-inprocess") + } + targets { + all { + testTask { + systemProperty( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + "io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider" + ) + } + } + } + } + register("testGrpcOkhttp") { + dependencies { + implementation(project(":exporters:sender:grpc-managed-channel")) + implementation(project(":exporters:otlp:testing-internal")) + + implementation("io.grpc:grpc-okhttp") + implementation("io.grpc:grpc-stub") + implementation("io.grpc:grpc-inprocess") + } + targets { + all { + testTask { + systemProperty( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + "io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider" + ) + } + } + } + } + register("testJdkHttpSender") { + dependencies { + implementation(project(":exporters:sender:jdk")) + implementation(project(":exporters:otlp:testing-internal")) + + implementation("io.grpc:grpc-stub") + } + targets { + all { + testTask { + systemProperty( + "io.opentelemetry.sdk.common.export.HttpSenderProvider", + "io.opentelemetry.exporter.sender.jdk.internal.JdkHttpSenderProvider" + ) + enabled = !testJavaVersion.equals("8") + } + } + } + } + register("testNoSender") { + targets { + all { + testTask { + classpath = classpath.filter { !it.name.startsWith("opentelemetry-exporter-sender-okhttp") } + } + } + } + } + register("testSpanPipeline") { + dependencies { + implementation("io.opentelemetry.proto:opentelemetry-proto") + implementation("com.linecorp.armeria:armeria-grpc-protocol") + implementation("com.linecorp.armeria:armeria-junit5") + } + } + } +} + +tasks { + check { + dependsOn( + testing.suites.filter { + // Mainly to conveniently profile through IDEA. Don't add to check task, it's for + // manual invocation. + name != "testSpanPipeline" + }, + ) + } +} + +afterEvaluate { + tasks.named("compileTestJdkHttpSenderJava") { + options.release.set(11) + } } diff --git a/exporters/otlp/all/src/jmh/java/io/opentelemetry/exporter/otlp/trace/OltpExporterBenchmark.java b/exporters/otlp/all/src/jmh/java/io/opentelemetry/exporter/otlp/trace/OltpExporterBenchmark.java new file mode 100644 index 00000000000..cf54ae6e6f9 --- /dev/null +++ b/exporters/otlp/all/src/jmh/java/io/opentelemetry/exporter/otlp/trace/OltpExporterBenchmark.java @@ -0,0 +1,173 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.trace; + +import com.linecorp.armeria.common.HttpResponse; +import com.linecorp.armeria.server.Server; +import com.linecorp.armeria.server.grpc.GrpcService; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.stub.StreamObserver; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.HttpExporter; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSender; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; +import io.opentelemetry.proto.collector.trace.v1.TraceServiceGrpc; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 20, time = 1) +@Measurement(iterations = 20, time = 1) +@Fork(1) +@State(Scope.Benchmark) +@SuppressWarnings("NonFinalStaticField") +public class OltpExporterBenchmark { + private static final Server server = + Server.builder() + .service( + GrpcService.builder() + .addService( + new TraceServiceGrpc.TraceServiceImplBase() { + @Override + public void export( + ExportTraceServiceRequest request, + StreamObserver responseObserver) { + responseObserver.onNext(ExportTraceServiceResponse.getDefaultInstance()); + responseObserver.onCompleted(); + } + }) + .build()) + .service("/v1/traces", (ctx, req) -> HttpResponse.of(200)) + .http(0) + .build(); + + private static ManagedChannel defaultGrpcChannel; + + private static GrpcExporter upstreamGrpcExporter; + private static GrpcExporter okhttpGrpcSender; + private static HttpExporter httpExporter; + + @Setup(Level.Trial) + public void setUp() { + server.start().join(); + + defaultGrpcChannel = + ManagedChannelBuilder.forAddress("localhost", server.activeLocalPort()) + .usePlaintext() + .build(); + upstreamGrpcExporter = + new GrpcExporter( + new UpstreamGrpcSender( + defaultGrpcChannel, + "opentelemetry.proto.collector.trace.v1.TraceService/Export", + null, + /* shutdownChannel= */ false, + Duration.ofNanos(10), + Collections::emptyMap, + null), + InternalTelemetryVersion.LATEST, + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER), + MeterProvider::noop, + URI.create("http://localhost"), + GrpcExporterBuilder.DEFAULT_MAX_REQUEST_MESSAGE_SIZE); + + okhttpGrpcSender = + new GrpcExporter( + new OkHttpGrpcSender( + URI.create("http://localhost:" + server.activeLocalPort()) + .resolve("opentelemetry.proto.collector.trace.v1.TraceService/Export") + .toString(), + null, + Duration.ofNanos(10), + Duration.ofNanos(10), + Collections::emptyMap, + null, + null, + null, + null, + Long.MAX_VALUE, + null), + InternalTelemetryVersion.LATEST, + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER), + MeterProvider::noop, + URI.create("http://localhost"), + GrpcExporterBuilder.DEFAULT_MAX_REQUEST_MESSAGE_SIZE); + + httpExporter = + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER, + "http://localhost:" + server.activeLocalPort() + "/v1/traces") + .build(); + } + + @TearDown(Level.Trial) + public void tearDown() { + upstreamGrpcExporter.shutdown().join(10, TimeUnit.SECONDS); + okhttpGrpcSender.shutdown().join(10, TimeUnit.SECONDS); + httpExporter.shutdown().join(10, TimeUnit.SECONDS); + defaultGrpcChannel.shutdownNow(); + server.stop().join(); + } + + @Benchmark + public CompletableResultCode defaultGrpcExporter(RequestMarshalState state) { + CompletableResultCode result = + upstreamGrpcExporter + .export(state.traceRequestMarshaler, state.numSpans) + .join(10, TimeUnit.SECONDS); + if (!result.isSuccess()) { + throw new AssertionError(); + } + return result; + } + + @Benchmark + public CompletableResultCode okhttpGrpcExporter(RequestMarshalState state) { + CompletableResultCode result = + okhttpGrpcSender + .export(state.traceRequestMarshaler, state.numSpans) + .join(10, TimeUnit.SECONDS); + if (!result.isSuccess()) { + throw new AssertionError(); + } + return result; + } + + @Benchmark + public CompletableResultCode httpExporter(RequestMarshalState state) { + CompletableResultCode result = + httpExporter.export(state.traceRequestMarshaler, state.numSpans).join(10, TimeUnit.SECONDS); + if (!result.isSuccess()) { + throw new AssertionError(); + } + return result; + } +} diff --git a/exporters/otlp/trace/src/jmh/java/io/opentelemetry/exporter/otlp/trace/RequestMarshalState.java b/exporters/otlp/all/src/jmh/java/io/opentelemetry/exporter/otlp/trace/RequestMarshalState.java similarity index 100% rename from exporters/otlp/trace/src/jmh/java/io/opentelemetry/exporter/otlp/trace/RequestMarshalState.java rename to exporters/otlp/all/src/jmh/java/io/opentelemetry/exporter/otlp/trace/RequestMarshalState.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporter.java new file mode 100644 index 00000000000..9a6c7c923bc --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporter.java @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.logs; + +import io.opentelemetry.exporter.internal.otlp.logs.LogReusableDataMarshaler; +import io.opentelemetry.exporter.otlp.internal.HttpExporter; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** + * Exports logs using OTLP via HTTP, using OpenTelemetry's protobuf model. + * + * @since 1.27.0 + */ +@ThreadSafe +public final class OtlpHttpLogRecordExporter implements LogRecordExporter { + + private final HttpExporterBuilder builder; + private final HttpExporter delegate; + private final LogReusableDataMarshaler marshaler; + + OtlpHttpLogRecordExporter( + HttpExporterBuilder builder, HttpExporter delegate, MemoryMode memoryMode) { + this.builder = builder; + this.delegate = delegate; + this.marshaler = new LogReusableDataMarshaler(memoryMode, delegate::export); + } + + /** + * Returns a new {@link OtlpHttpLogRecordExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpHttpLogRecordExporter} instance. + */ + public static OtlpHttpLogRecordExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpHttpLogRecordExporterBuilder builder() { + return new OtlpHttpLogRecordExporterBuilder(); + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + * + * @since 1.29.0 + */ + public OtlpHttpLogRecordExporterBuilder toBuilder() { + return new OtlpHttpLogRecordExporterBuilder(builder.copy(), marshaler.getMemoryMode()); + } + + /** + * Submits all the given logs in a single batch to the OpenTelemetry collector. + * + * @param logs the list of sampled Logs to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection logs) { + return marshaler.export(logs); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** Shutdown the exporter. */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpHttpLogRecordExporter{", "}"); + joiner.add(builder.toString(false)); + joiner.add("memoryMode=" + marshaler.getMemoryMode()); + return joiner.toString(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterBuilder.java new file mode 100644 index 00000000000..c8a0469410b --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterBuilder.java @@ -0,0 +1,317 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.logs; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Builder utility for {@link OtlpHttpLogRecordExporter}. + * + * @since 1.27.0 + */ +public final class OtlpHttpLogRecordExporterBuilder { + + private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/logs"; + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; + + private final HttpExporterBuilder delegate; + private MemoryMode memoryMode; + + OtlpHttpLogRecordExporterBuilder(HttpExporterBuilder delegate, MemoryMode memoryMode) { + this.delegate = delegate; + this.memoryMode = memoryMode; + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeaders); + } + + OtlpHttpLogRecordExporterBuilder() { + this( + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_LOG_EXPORTER, DEFAULT_ENDPOINT), + DEFAULT_MEMORY_MODE); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, + * defaults to {@value HttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. + */ + public OtlpHttpLogRecordExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, + * defaults to {@value HttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. + */ + public OtlpHttpLogRecordExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value HttpExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.33.0 + */ + public OtlpHttpLogRecordExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value HttpExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.33.0 + */ + public OtlpHttpLogRecordExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP HTTP request body size in bytes. If unset, defaults to 64 MiB. A value of + * 0 means no limit. + * + * @since 1.67.0 + */ + public OtlpHttpLogRecordExporterBuilder setMaxRequestBodySize(long maxRequestBodySizeBytes) { + checkArgument(maxRequestBodySizeBytes >= 0, "maxRequestBodySizeBytes must be non-negative"); + delegate.setMaxRequestBodySize(maxRequestBodySizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The + * endpoint must start with either http:// or https://, and include the full HTTP path. + */ + public OtlpHttpLogRecordExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpHttpLogRecordExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. + */ + public OtlpHttpLogRecordExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeaders(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. + * + * @since 1.33.0 + */ + public OtlpHttpLogRecordExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpHttpLogRecordExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpHttpLogRecordExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + */ + public OtlpHttpLogRecordExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + * + * @since 1.28.0 + */ + public OtlpHttpLogRecordExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Sets the proxy options. Proxying is disabled by default. + * + * @since 1.36.0 + */ + public OtlpHttpLogRecordExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + requireNonNull(proxyOptions, "proxyOptions"); + delegate.setProxyOptions(proxyOptions); + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, uses + * {@link GlobalOpenTelemetry#getMeterProvider()}. + */ + public OtlpHttpLogRecordExporterBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + setMeterProvider(() -> meterProvider); + return this; + } + + /** + * Sets the {@link MeterProvider} supplier used to collect metrics related to export. If not set, + * uses {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.32.0 + */ + public OtlpHttpLogRecordExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + requireNonNull(meterProviderSupplier, "meterProviderSupplier"); + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which self-monitoring metrics this exporter + * collects. + * + * @since 1.51.0 + */ + public OtlpHttpLogRecordExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + requireNonNull(schemaVersion, "schemaVersion"); + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link #DEFAULT_MEMORY_MODE}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + * + * @since 1.39.0 + */ + public OtlpHttpLogRecordExporterBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + * + * @since 1.48.0 + */ + public OtlpHttpLogRecordExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpHttpLogRecordExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + * + * @since 1.49.0 + */ + public OtlpHttpLogRecordExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions. Omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + public OtlpHttpLogRecordExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpHttpLogRecordExporter build() { + return new OtlpHttpLogRecordExporter(delegate, delegate.build(), memoryMode); + } +} diff --git a/exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/package-info.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/package-info.java similarity index 100% rename from exporters/otlp-http/logs/src/main/java/io/opentelemetry/exporter/otlp/http/logs/package-info.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/logs/package-info.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporter.java new file mode 100644 index 00000000000..8e7560ea169 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporter.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.metrics; + +import io.opentelemetry.exporter.internal.otlp.metrics.MetricReusableDataMarshaler; +import io.opentelemetry.exporter.otlp.internal.HttpExporter; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** + * Exports metrics using OTLP via HTTP, using OpenTelemetry's protobuf model. + * + * @since 1.14.0 + */ +@ThreadSafe +public final class OtlpHttpMetricExporter implements MetricExporter { + + private final HttpExporterBuilder builder; + private final HttpExporter delegate; + // Visible for testing + final AggregationTemporalitySelector aggregationTemporalitySelector; + // Visible for testing + final DefaultAggregationSelector defaultAggregationSelector; + private final MetricReusableDataMarshaler marshaler; + + OtlpHttpMetricExporter( + HttpExporterBuilder builder, + HttpExporter delegate, + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector, + MemoryMode memoryMode) { + this.builder = builder; + this.delegate = delegate; + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + this.defaultAggregationSelector = defaultAggregationSelector; + this.marshaler = new MetricReusableDataMarshaler(memoryMode, delegate::export); + } + + /** + * Returns a new {@link OtlpHttpMetricExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpHttpMetricExporter} instance. + */ + public static OtlpHttpMetricExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpHttpMetricExporterBuilder builder() { + return new OtlpHttpMetricExporterBuilder(); + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + * + * @since 1.29.0 + */ + public OtlpHttpMetricExporterBuilder toBuilder() { + return new OtlpHttpMetricExporterBuilder( + builder.copy(), + aggregationTemporalitySelector, + defaultAggregationSelector, + marshaler.getMemoryMode()); + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); + } + + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return defaultAggregationSelector.getDefaultAggregation(instrumentType); + } + + @Override + public MemoryMode getMemoryMode() { + return marshaler.getMemoryMode(); + } + + /** + * Submits all the given metrics in a single batch to the OpenTelemetry collector. + * + * @param metrics the list of sampled Metrics to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection metrics) { + return marshaler.export(metrics); + } + + /** + * The OTLP exporter does not batch metrics, so this method will immediately return with success. + * + * @return always Success + */ + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** Shutdown the exporter. */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpHttpMetricExporter{", "}"); + joiner.add(builder.toString(false)); + joiner.add( + "aggregationTemporalitySelector=" + + AggregationTemporalitySelector.asString(aggregationTemporalitySelector)); + joiner.add( + "defaultAggregationSelector=" + + DefaultAggregationSelector.asString(defaultAggregationSelector)); + joiner.add("memoryMode=" + marshaler.getMemoryMode()); + return joiner.toString(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java new file mode 100644 index 00000000000..a505e82ea6c --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilder.java @@ -0,0 +1,386 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.metrics; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.time.Duration; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Builder utility for {@link OtlpHttpMetricExporter}. + * + * @since 1.14.0 + */ +public final class OtlpHttpMetricExporterBuilder { + + private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/metrics"; + + private static final AggregationTemporalitySelector DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = + AggregationTemporalitySelector.alwaysCumulative(); + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; + + private final HttpExporterBuilder delegate; + + private AggregationTemporalitySelector aggregationTemporalitySelector; + private DefaultAggregationSelector defaultAggregationSelector; + private MemoryMode memoryMode; + + OtlpHttpMetricExporterBuilder( + HttpExporterBuilder delegate, + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector, + MemoryMode memoryMode) { + this.delegate = delegate; + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + this.defaultAggregationSelector = defaultAggregationSelector; + this.memoryMode = memoryMode; + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeaders); + } + + OtlpHttpMetricExporterBuilder() { + this( + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_METRIC_EXPORTER, DEFAULT_ENDPOINT), + DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR, + DefaultAggregationSelector.getDefault(), + DEFAULT_MEMORY_MODE); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of metrics. If + * unset, defaults to {@value HttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. + */ + public OtlpHttpMetricExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of metrics. If + * unset, defaults to {@value HttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. + */ + public OtlpHttpMetricExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value HttpExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.33.0 + */ + public OtlpHttpMetricExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value HttpExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.33.0 + */ + public OtlpHttpMetricExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP HTTP request body size in bytes. If unset, defaults to 64 MiB. A value of + * 0 means no limit. + * + * @since 1.67.0 + */ + public OtlpHttpMetricExporterBuilder setMaxRequestBodySize(long maxRequestBodySizeBytes) { + checkArgument(maxRequestBodySizeBytes >= 0, "maxRequestBodySizeBytes must be non-negative"); + delegate.setMaxRequestBodySize(maxRequestBodySizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The + * endpoint must start with either http:// or https://, and include the full HTTP path. + */ + public OtlpHttpMetricExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpHttpMetricExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. + */ + public OtlpHttpMetricExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeaders(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. + * + * @since 1.33.0 + */ + public OtlpHttpMetricExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpHttpMetricExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpHttpMetricExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + * + * @since 1.26.0 + */ + public OtlpHttpMetricExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Set the {@link AggregationTemporalitySelector} used for {@link + * MetricExporter#getAggregationTemporality(InstrumentType)}. + * + *

    If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}. + * + *

    {@link AggregationTemporalitySelector#deltaPreferred()} is a common configuration for delta + * backends. + */ + public OtlpHttpMetricExporterBuilder setAggregationTemporalitySelector( + AggregationTemporalitySelector aggregationTemporalitySelector) { + requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector"); + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + return this; + } + + /** + * Set the {@link DefaultAggregationSelector} used for {@link + * MetricExporter#getDefaultAggregation(InstrumentType)}. + * + *

    If unset, defaults to {@link DefaultAggregationSelector#getDefault()}. + * + * @since 1.16.0 + */ + public OtlpHttpMetricExporterBuilder setDefaultAggregationSelector( + DefaultAggregationSelector defaultAggregationSelector) { + requireNonNull(defaultAggregationSelector, "defaultAggregationSelector"); + this.defaultAggregationSelector = defaultAggregationSelector; + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + * + * @since 1.28.0 + */ + public OtlpHttpMetricExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Sets the proxy options. Proxying is disabled by default. + * + * @since 1.36.0 + */ + public OtlpHttpMetricExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + requireNonNull(proxyOptions, "proxyOptions"); + delegate.setProxyOptions(proxyOptions); + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which self-monitoring metrics this exporter + * collects. + * + * @since 1.51.0 + */ + public OtlpHttpMetricExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + requireNonNull(schemaVersion, "schemaVersion"); + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, uses + * {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.50.0 + */ + public OtlpHttpMetricExporterBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + delegate.setMeterProvider(() -> meterProvider); + return this; + } + + /** + * Sets the {@link MeterProvider} supplier to use to collect metrics related to export. If not + * set, uses {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.50.0 + */ + public OtlpHttpMetricExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + requireNonNull(meterProviderSupplier, "meterProvider"); + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link #DEFAULT_MEMORY_MODE}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. Additionally, the value is used for {@link MetricExporter#getMemoryMode()}, + * which sends a signal to the metrics SDK to reuse memory when possible. This is safe and + * desirable for most use cases, but should be used with caution of wrapping and delegating to the + * exporter. It is not safe for the wrapping exporter to hold onto references to {@link + * MetricData} batches since the same data structures will be reused in subsequent calls to {@link + * MetricExporter#export(Collection)}. + * + * @since 1.39.0 + */ + public OtlpHttpMetricExporterBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + * + * @since 1.48.0 + */ + public OtlpHttpMetricExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpHttpMetricExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + * + * @since 1.49.0 + */ + public OtlpHttpMetricExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions. Omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + public OtlpHttpMetricExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + OtlpHttpMetricExporterBuilder exportAsJson() { + delegate.exportAsJson(); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpHttpMetricExporter build() { + return new OtlpHttpMetricExporter( + delegate, + delegate.build(), + aggregationTemporalitySelector, + defaultAggregationSelector, + memoryMode); + } +} diff --git a/exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/package-info.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/package-info.java similarity index 100% rename from exporters/otlp-http/metrics/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/package-info.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/metrics/package-info.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporter.java new file mode 100644 index 00000000000..327afe3f642 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporter.java @@ -0,0 +1,103 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.trace; + +import io.opentelemetry.exporter.internal.otlp.traces.SpanReusableDataMarshaler; +import io.opentelemetry.exporter.otlp.internal.HttpExporter; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** + * Exports spans using OTLP via HTTP, using OpenTelemetry's protobuf model. + * + * @since 1.5.0 + */ +@ThreadSafe +public final class OtlpHttpSpanExporter implements SpanExporter { + + private final HttpExporterBuilder builder; + private final HttpExporter delegate; + private final SpanReusableDataMarshaler marshaler; + + OtlpHttpSpanExporter(HttpExporterBuilder builder, HttpExporter delegate, MemoryMode memoryMode) { + this.builder = builder; + this.delegate = delegate; + this.marshaler = new SpanReusableDataMarshaler(memoryMode, delegate::export); + } + + /** + * Returns a new {@link OtlpHttpSpanExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpHttpSpanExporter} instance. + */ + public static OtlpHttpSpanExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpHttpSpanExporterBuilder builder() { + return new OtlpHttpSpanExporterBuilder(); + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + * + * @since 1.29.0 + */ + public OtlpHttpSpanExporterBuilder toBuilder() { + return new OtlpHttpSpanExporterBuilder(builder.copy(), marshaler.getMemoryMode()); + } + + /** + * Submits all the given spans in a single batch to the OpenTelemetry collector. + * + * @param spans the list of sampled Spans to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection spans) { + return marshaler.export(spans); + } + + /** + * The OTLP exporter does not batch spans, so this method will immediately return with success. + * + * @return always Success + */ + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** Shutdown the exporter, releasing any resources and preventing subsequent exports. */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpHttpSpanExporter{", "}"); + joiner.add(builder.toString(false)); + joiner.add("memoryMode=" + marshaler.getMemoryMode()); + return joiner.toString(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterBuilder.java new file mode 100644 index 00000000000..a2d9925dc37 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterBuilder.java @@ -0,0 +1,318 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.trace; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Builder utility for {@link OtlpHttpSpanExporter}. + * + * @since 1.5.0 + */ +public final class OtlpHttpSpanExporterBuilder { + + private static final String DEFAULT_ENDPOINT = "http://localhost:4318/v1/traces"; + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; + + private final HttpExporterBuilder delegate; + private MemoryMode memoryMode; + + OtlpHttpSpanExporterBuilder(HttpExporterBuilder delegate, MemoryMode memoryMode) { + this.delegate = delegate; + this.memoryMode = memoryMode; + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeaders); + } + + OtlpHttpSpanExporterBuilder() { + this( + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER, DEFAULT_ENDPOINT), + DEFAULT_MEMORY_MODE); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of spans. If + * unset, defaults to {@value HttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. + */ + public OtlpHttpSpanExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of spans. If + * unset, defaults to {@value HttpExporterBuilder#DEFAULT_TIMEOUT_SECS}s. + */ + public OtlpHttpSpanExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value HttpExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.33.0 + */ + public OtlpHttpSpanExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value HttpExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.33.0 + */ + public OtlpHttpSpanExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP HTTP request body size in bytes. If unset, defaults to 64 MiB. A value of + * 0 means no limit. + * + * @since 1.67.0 + */ + public OtlpHttpSpanExporterBuilder setMaxRequestBodySize(long maxRequestBodySizeBytes) { + checkArgument(maxRequestBodySizeBytes >= 0, "maxRequestBodySizeBytes must be non-negative"); + delegate.setMaxRequestBodySize(maxRequestBodySizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT}. The + * endpoint must start with either http:// or https://, and include the full HTTP path. + */ + public OtlpHttpSpanExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpHttpSpanExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. + */ + public OtlpHttpSpanExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeaders(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. + * + * @since 1.33.0 + */ + public OtlpHttpSpanExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpHttpSpanExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpHttpSpanExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + * + * @since 1.26.0 + */ + public OtlpHttpSpanExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + * + * @since 1.28.0 + */ + public OtlpHttpSpanExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Sets the proxy options. Proxying is disabled by default. + * + * @since 1.36.0 + */ + public OtlpHttpSpanExporterBuilder setProxy(ProxyOptions proxyOptions) { + requireNonNull(proxyOptions, "proxyOptions"); + delegate.setProxyOptions(proxyOptions); + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, uses + * {@link GlobalOpenTelemetry#getMeterProvider()}. + */ + public OtlpHttpSpanExporterBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + setMeterProvider(() -> meterProvider); + return this; + } + + /** + * Sets the {@link MeterProvider} supplier to use to collect metrics related to export. If not + * set, uses {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.32.0 + */ + public OtlpHttpSpanExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + requireNonNull(meterProviderSupplier, "meterProviderSupplier"); + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which self-monitoring metrics this exporter + * collects. + * + * @since 1.51.0 + */ + public OtlpHttpSpanExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + requireNonNull(schemaVersion, "schemaVersion"); + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link #DEFAULT_MEMORY_MODE}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + * + * @since 1.39.0 + */ + public OtlpHttpSpanExporterBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + * + * @since 1.48.0 + */ + public OtlpHttpSpanExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpHttpSpanExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + * + * @since 1.49.0 + */ + public OtlpHttpSpanExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions. Omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + public OtlpHttpSpanExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpHttpSpanExporter build() { + return new OtlpHttpSpanExporter(delegate, delegate.build(), memoryMode); + } +} diff --git a/exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/package-info.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/package-info.java similarity index 100% rename from exporters/otlp-http/trace/src/main/java/io/opentelemetry/exporter/otlp/http/trace/package-info.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/http/trace/package-info.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/CompressorUtil.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/CompressorUtil.java new file mode 100644 index 00000000000..93bc7c8f137 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/CompressorUtil.java @@ -0,0 +1,77 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.stream.Collectors.joining; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.common.export.Compressor; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * Utilities for resolving SPI {@link Compressor}s. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class CompressorUtil { + + private static final GzipCompressor gzipCompressor = new GzipCompressor(); + private static final Map compressorRegistry = + buildCompressorRegistry( + ComponentLoader.forClassLoader(CompressorUtil.class.getClassLoader())); + + private CompressorUtil() {} + + /** + * Validate that the {@code compressionMethod} is "none" or matches a registered compressor. + * + * @return {@code null} if {@code compressionMethod} is "none" or the registered compressor + * @throws IllegalArgumentException if no match is found + */ + @Nullable + public static Compressor validateAndResolveCompressor(String compressionMethod) { + return validateAndResolveCompressor(compressionMethod, null); + } + + /** + * Validate that the {@code compressionMethod} is "none" or matches a registered compressor. + * + * @param compressionMethod the compression method to validate and resolve + * @param componentLoader the component loader to use for loading SPI implementations, or null to + * use the default + * @return {@code null} if {@code compressionMethod} is "none" or the registered compressor + * @throws IllegalArgumentException if no match is found + */ + @Nullable + public static Compressor validateAndResolveCompressor( + String compressionMethod, @Nullable ComponentLoader componentLoader) { + Map registry = + componentLoader == null ? compressorRegistry : buildCompressorRegistry(componentLoader); + + Set supportedEncodings = registry.keySet(); + Compressor compressor = registry.get(compressionMethod); + checkArgument( + "none".equals(compressionMethod) || compressor != null, + "Unsupported compressionMethod. Compression method must be \"none\" or one of: " + + supportedEncodings.stream().collect(joining(",", "[", "]"))); + return compressor; + } + + private static Map buildCompressorRegistry(ComponentLoader componentLoader) { + Map compressors = new HashMap<>(); + for (Compressor compressor : componentLoader.load(Compressor.class)) { + compressors.put(compressor.getEncoding(), compressor); + } + // Hardcode gzip compressor + compressors.put(gzipCompressor.getEncoding(), gzipCompressor); + return compressors; + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporter.java new file mode 100644 index 00000000000..76d3d1dac76 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporter.java @@ -0,0 +1,187 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.FailedExportException; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.metrics.ExporterInstrumentation; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import java.io.IOException; +import java.net.URI; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Generic gRPC exporter. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@SuppressWarnings("checkstyle:JavadocMethod") +public final class GrpcExporter { + + private static final Logger internalLogger = Logger.getLogger(GrpcExporter.class.getName()); + + private final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); + + // We only log unimplemented once since it's a configuration issue that won't be recovered. + private final AtomicBoolean loggedUnimplemented = new AtomicBoolean(); + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + private final String type; + private final GrpcSender grpcSender; + private final ExporterInstrumentation exporterMetrics; + private final long maxRequestMessageSize; + + public GrpcExporter( + GrpcSender grpcSender, + InternalTelemetryVersion internalTelemetryVersion, + StandardComponentId componentId, + Supplier meterProviderSupplier, + URI endpoint, + long maxRequestMessageSize) { + this.type = componentId.getStandardType().signal().logFriendlyName(); + this.grpcSender = grpcSender; + this.exporterMetrics = + new ExporterInstrumentation( + internalTelemetryVersion, meterProviderSupplier, componentId, endpoint); + this.maxRequestMessageSize = maxRequestMessageSize; + } + + public CompletableResultCode export(Marshaler exportRequest, int numItems) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + + ExporterInstrumentation.Recording metricRecording = + exporterMetrics.startRecordingExport(numItems); + + int requestMessageSize = exportRequest.getBinarySerializedSize(); + if (requestMessageSize > maxRequestMessageSize) { + return failRequestTooLarge(metricRecording, requestMessageSize); + } + + MessageWriter messageWriter = exportRequest.toBinaryMessageWriter(); + + CompletableResultCode result = new CompletableResultCode(); + + grpcSender.send( + messageWriter, + grpcResponse -> onResponse(result, metricRecording, grpcResponse, numItems), + throwable -> onError(result, metricRecording, numItems, throwable)); + + return result; + } + + private CompletableResultCode failRequestTooLarge( + ExporterInstrumentation.Recording metricRecording, long requestMessageSize) { + String errorMessage = + "Failed to export " + + type + + "s. Request message size " + + requestMessageSize + + " exceeded limit of " + + maxRequestMessageSize + + " bytes"; + IOException exception = new IOException(errorMessage); + metricRecording.finishFailed(exception); + logger.log(Level.WARNING, errorMessage); + return CompletableResultCode.ofExceptionalFailure( + FailedExportException.grpcFailedExceptionally(exception)); + } + + private void onResponse( + CompletableResultCode result, + ExporterInstrumentation.Recording metricRecording, + GrpcResponse grpcResponse, + int numItems) { + GrpcStatusCode statusCode = grpcResponse.getStatusCode(); + + metricRecording.setGrpcStatusCode(statusCode); + + if (statusCode == GrpcStatusCode.OK) { + metricRecording.finishSuccessful(); + result.succeed(); + return; + } + + metricRecording.finishFailed(String.valueOf(statusCode.getValue())); + switch (statusCode) { + case UNIMPLEMENTED: + if (loggedUnimplemented.compareAndSet(false, true)) { + GrpcExporterUtil.logUnimplemented( + internalLogger, type, grpcResponse.getStatusDescription()); + } + break; + case UNAVAILABLE: + logger.log( + levelOnFailure(Level.SEVERE), + "Failed to export " + + numItems + + " " + + type + + "s. Server is UNAVAILABLE. " + + "Make sure your collector is running and reachable from this network. " + + "Full error message:" + + grpcResponse.getStatusDescription()); + break; + default: + logger.log( + levelOnFailure(Level.WARNING), + "Failed to export " + + numItems + + " " + + type + + "s. Server responded with gRPC status code " + + statusCode.getValue() + + ". Error message: " + + grpcResponse.getStatusDescription()); + break; + } + result.failExceptionally(FailedExportException.grpcFailedWithResponse(grpcResponse)); + } + + private void onError( + CompletableResultCode result, + ExporterInstrumentation.Recording metricRecording, + int numItems, + Throwable e) { + metricRecording.finishFailed(e); + logger.log( + levelOnFailure(Level.SEVERE), + "Failed to export " + numItems + " " + type + "s. The request could not be executed.", + e); + if (logger.isLoggable(Level.FINEST)) { + logger.log( + Level.FINEST, "Failed to export " + numItems + " " + type + "s. Details follow:", e); + } + result.failExceptionally(FailedExportException.grpcFailedExceptionally(e)); + } + + // Failures after shutdown are typically caused by in-flight requests being cancelled by + // shutdown() and are not actionable, so demote them to FINE. + private Level levelOnFailure(Level defaultLevel) { + return isShutdown.get() ? Level.FINE : defaultLevel; + } + + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + return CompletableResultCode.ofSuccess(); + } + return grpcSender.shutdown(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java new file mode 100644 index 00000000000..e55d17bed9b --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilder.java @@ -0,0 +1,307 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.internal.SenderUtil.resolveGrpcSenderProvider; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.EndpointUtil; +import io.opentelemetry.exporter.internal.TlsConfigHelper; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcSenderProvider; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.StringJoiner; +import java.util.concurrent.ExecutorService; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * A builder for {@link GrpcExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@SuppressWarnings("JavadocMethod") +public class GrpcExporterBuilder { + + public static final long DEFAULT_CONNECT_TIMEOUT_SECS = 10; + public static final long DEFAULT_MAX_REQUEST_MESSAGE_SIZE = 64 * 1024L * 1024L; + + private static final Logger LOGGER = Logger.getLogger(GrpcExporterBuilder.class.getName()); + + private final StandardComponentId.ExporterType exporterType; + private final String fullMethodName; + + private Duration timeout; + private Duration connectTimeout = Duration.ofSeconds(DEFAULT_CONNECT_TIMEOUT_SECS); + private URI endpoint; + @Nullable private Compressor compressor; + private final Map constantHeaders = new HashMap<>(); + private Supplier> headerSupplier = Collections::emptyMap; + private TlsConfigHelper tlsConfigHelper = new TlsConfigHelper(); + @Nullable private RetryPolicy retryPolicy = RetryPolicy.getDefault(); + private Supplier meterProviderSupplier = + () -> GlobalOpenTelemetry.getOrNoop().getMeterProvider(); + private InternalTelemetryVersion internalTelemetryVersion = InternalTelemetryVersion.LEGACY; + + private ComponentLoader componentLoader = + ComponentLoader.forClassLoader(GrpcExporterBuilder.class.getClassLoader()); + @Nullable private ExecutorService executorService; + private long maxRequestMessageSize = DEFAULT_MAX_REQUEST_MESSAGE_SIZE; + @Nullable private List enabledProtocols; + + // Use Object type since gRPC may not be on the classpath. + @Nullable private Object grpcChannel; + + public GrpcExporterBuilder( + StandardComponentId.ExporterType exporterType, + Duration defaultTimeout, + URI defaultEndpoint, + String fullMethodName) { + this.exporterType = exporterType; + this.fullMethodName = fullMethodName; + timeout = defaultTimeout; + endpoint = defaultEndpoint; + } + + public GrpcExporterBuilder setChannel(ManagedChannel channel) { + this.grpcChannel = channel; + return this; + } + + public GrpcExporterBuilder setTimeout(Duration timeout) { + this.timeout = timeout.toNanos() == 0 ? Duration.ofNanos(Long.MAX_VALUE) : timeout; + return this; + } + + public GrpcExporterBuilder setConnectTimeout(Duration timeout) { + connectTimeout = timeout.toNanos() == 0 ? Duration.ofNanos(Long.MAX_VALUE) : timeout; + return this; + } + + public GrpcExporterBuilder setEndpoint(String endpoint) { + this.endpoint = EndpointUtil.validateEndpoint(endpoint); + return this; + } + + public GrpcExporterBuilder setCompression(@Nullable Compressor compressor) { + this.compressor = compressor; + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Support for additional compression + * methods is available by implementing {@link Compressor} SPI. + */ + public GrpcExporterBuilder setCompression(String compressionMethod) { + Compressor compressor = + CompressorUtil.validateAndResolveCompressor(compressionMethod, componentLoader); + return setCompression(compressor); + } + + public GrpcExporterBuilder setTrustManagerFromCerts(byte[] trustedCertificatesPem) { + tlsConfigHelper.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + public GrpcExporterBuilder setKeyManagerFromCerts(byte[] privateKeyPem, byte[] certificatePem) { + tlsConfigHelper.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + public GrpcExporterBuilder setSslContext(SSLContext sslContext, X509TrustManager trustManager) { + tlsConfigHelper.setSslContext(sslContext, trustManager); + return this; + } + + public GrpcExporterBuilder addConstantHeader(String key, String value) { + constantHeaders.put(key, value); + return this; + } + + public GrpcExporterBuilder setHeadersSupplier(Supplier> headerSupplier) { + this.headerSupplier = headerSupplier; + return this; + } + + public GrpcExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + public GrpcExporterBuilder setMeterProvider(Supplier meterProviderSupplier) { + this.meterProviderSupplier = meterProviderSupplier; + return this; + } + + public GrpcExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion internalTelemetryVersion) { + this.internalTelemetryVersion = internalTelemetryVersion; + return this; + } + + public GrpcExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + this.componentLoader = componentLoader; + return this; + } + + public GrpcExporterBuilder setExecutorService(ExecutorService executorService) { + this.executorService = executorService; + return this; + } + + public GrpcExporterBuilder setMaxRequestMessageSize(long maxRequestMessageSize) { + this.maxRequestMessageSize = + maxRequestMessageSize == 0 ? Long.MAX_VALUE : maxRequestMessageSize; + return this; + } + + public GrpcExporterBuilder setEnabledProtocols(@Nullable List enabledProtocols) { + this.enabledProtocols = enabledProtocols; + return this; + } + + @SuppressWarnings("BuilderReturnThis") + public GrpcExporterBuilder copy() { + GrpcExporterBuilder copy = + new GrpcExporterBuilder(exporterType, timeout, endpoint, fullMethodName); + + copy.timeout = timeout; + copy.connectTimeout = connectTimeout; + copy.endpoint = endpoint; + copy.compressor = compressor; + copy.constantHeaders.putAll(constantHeaders); + copy.headerSupplier = headerSupplier; + copy.tlsConfigHelper = tlsConfigHelper.copy(); + if (retryPolicy != null) { + copy.retryPolicy = retryPolicy.toBuilder().build(); + } + copy.meterProviderSupplier = meterProviderSupplier; + copy.internalTelemetryVersion = internalTelemetryVersion; + copy.grpcChannel = grpcChannel; + copy.componentLoader = componentLoader; + copy.maxRequestMessageSize = maxRequestMessageSize; + copy.enabledProtocols = enabledProtocols; + return copy; + } + + public GrpcExporter build() { + Supplier>> headerSupplier = + () -> { + Map> result = new HashMap<>(); + Map supplierResult = this.headerSupplier.get(); + if (supplierResult != null) { + supplierResult.forEach( + (key, value) -> result.put(key, Collections.singletonList(value))); + } + constantHeaders.forEach((key, value) -> + result.merge( + key, + Collections.singletonList(value), + (v1, v2) -> { + List merged = new ArrayList<>(v1); + merged.addAll(v2); + return merged; + })); + return result; + }; + + boolean isPlainHttp = "http".equals(endpoint.getScheme()); + GrpcSenderProvider grpcSenderProvider = resolveGrpcSenderProvider(componentLoader); + GrpcSender grpcSender = + grpcSenderProvider.createSender( + ImmutableGrpcSenderConfig.create( + endpoint, + fullMethodName, + compressor, + timeout, + connectTimeout, + headerSupplier, + retryPolicy, + isPlainHttp ? null : tlsConfigHelper.getSslContext(), + isPlainHttp ? null : tlsConfigHelper.getTrustManager(), + executorService, + grpcChannel, + // 4mb to align with spec guidance - even though we don't do anything with the + // response today, we will so better to have future-looking memory profile + 4 * 1024L * 1024L, + enabledProtocols)); + LOGGER.log(Level.FINE, "Using GrpcSender: " + grpcSender.getClass().getName()); + + return new GrpcExporter( + grpcSender, + internalTelemetryVersion, + ComponentId.generateLazy(exporterType), + meterProviderSupplier, + endpoint, + maxRequestMessageSize); + } + + public String toString(boolean includePrefixAndSuffix) { + StringJoiner joiner = + includePrefixAndSuffix + ? new StringJoiner(", ", "GrpcExporterBuilder{", "}") + : new StringJoiner(", "); + joiner.add("endpoint=" + endpoint.toString()); + joiner.add("fullMethodName=" + fullMethodName); + joiner.add("timeoutNanos=" + timeout.toNanos()); + joiner.add("connectTimeoutNanos=" + connectTimeout.toNanos()); + joiner.add( + "compressorEncoding=" + + Optional.ofNullable(compressor).map(Compressor::getEncoding).orElse(null)); + StringJoiner headersJoiner = new StringJoiner(", ", "Headers{", "}"); + constantHeaders.forEach((key, value) -> headersJoiner.add(key + "=OBFUSCATED")); + Map headers = headerSupplier.get(); + if (headers != null) { + headers.forEach((key, value) -> headersJoiner.add(key + "=OBFUSCATED")); + } + joiner.add("headers=" + headersJoiner); + if (retryPolicy != null) { + joiner.add("retryPolicy=" + retryPolicy); + } + if (enabledProtocols != null) { + joiner.add("enabledProtocols=" + enabledProtocols); + } + if (grpcChannel != null) { + joiner.add("grpcChannel=" + grpcChannel); + } + joiner.add("componentLoader=" + componentLoader); + if (executorService != null) { + joiner.add("executorService=" + executorService); + } + joiner.add("maxRequestMessageSize=" + maxRequestMessageSize); + joiner.add("exporterType=" + exporterType.toString()); + joiner.add("internalTelemetrySchemaVersion=" + internalTelemetryVersion); + // Note: omit tlsConfigHelper because we can't log the configuration in any readable way + // Note: omit meterProviderSupplier because we can't log the configuration in any readable way + return joiner.toString(); + } + + @Override + public String toString() { + return toString(true); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterUtil.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterUtil.java new file mode 100644 index 00000000000..93e9519bd4b --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterUtil.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.exporter.internal.marshal.CodedInputStream; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class GrpcExporterUtil { + + static void logUnimplemented(Logger logger, String type, @Nullable String fullErrorMessage) { + + // hopefully temporary special handling for profile signal as it evolves towards stability. + if ("profile".equals(type)) { + logger.log( + Level.SEVERE, + "Failed to export profile. The profile signal type is still under development " + + "and the endpoint you are connecting to may not support it yet, " + + "or may support a different version. " + + "Full error message: " + + fullErrorMessage); + return; + } + + String envVar; + switch (type) { + case "span": + envVar = "OTEL_TRACES_EXPORTER"; + break; + case "metric": + envVar = "OTEL_METRICS_EXPORTER"; + break; + case "log": + envVar = "OTEL_LOGS_EXPORTER"; + break; + default: + throw new IllegalStateException( + "Unrecognized type, this is a programming bug in the OpenTelemetry SDK"); + } + + logger.log( + Level.SEVERE, + "Failed to export " + + type + + "s. Server responded with UNIMPLEMENTED. " + + "This usually means that your collector is not configured with an otlp " + + "receiver in the \"pipelines\" section of the configuration. " + + "If export is not desired and you are using OpenTelemetry autoconfiguration or the javaagent, " + + "disable export by setting " + + envVar + + "=none. " + + "Full error message: " + + fullErrorMessage); + } + + private GrpcExporterUtil() {} + + /** Parses the message out of a serialized gRPC Status. */ + public static String getStatusMessage(byte[] serializedStatus) throws IOException { + CodedInputStream input = CodedInputStream.newInstance(serializedStatus); + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 18: + return input.readStringRequireUtf8(); + default: + input.skipField(tag); + break; + } + } + // Serialized Status proto had no message, proto always defaults to empty string when not found. + return ""; + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GzipCompressor.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GzipCompressor.java new file mode 100644 index 00000000000..fc791bb2925 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/GzipCompressor.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.sdk.common.export.Compressor; +import java.io.IOException; +import java.io.OutputStream; +import java.util.zip.GZIPOutputStream; + +/** + * Gzip {@link Compressor}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class GzipCompressor implements Compressor { + + public GzipCompressor() {} + + @Override + public String getEncoding() { + return "gzip"; + } + + @Override + public OutputStream compress(OutputStream outputStream) throws IOException { + return new GZIPOutputStream(outputStream); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporter.java new file mode 100644 index 00000000000..c6d7715913e --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporter.java @@ -0,0 +1,241 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.FailedExportException; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.metrics.ExporterInstrumentation; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.HttpResponse; +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * An exporter for http/protobuf or http/json using a signal-specific Marshaler. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@SuppressWarnings("checkstyle:JavadocMethod") +public final class HttpExporter { + // Limit logged response body text to avoid flooding warnings with large payloads. + private static final int MAX_RESPONSE_BODY_LOG_LENGTH = 1024; + + private static final Logger internalLogger = Logger.getLogger(HttpExporter.class.getName()); + + private final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + private final String type; + private final HttpSender httpSender; + private final ExporterInstrumentation exporterMetrics; + private final boolean exportAsJson; + private final long maxRequestBodySize; + + public HttpExporter( + StandardComponentId componentId, + HttpSender httpSender, + Supplier meterProviderSupplier, + InternalTelemetryVersion internalTelemetryVersion, + URI endpoint, + boolean exportAsJson, + long maxRequestBodySize) { + this.type = componentId.getStandardType().signal().logFriendlyName(); + this.httpSender = httpSender; + this.exporterMetrics = + new ExporterInstrumentation( + internalTelemetryVersion, meterProviderSupplier, componentId, endpoint); + this.exportAsJson = exportAsJson; + this.maxRequestBodySize = maxRequestBodySize; + } + + public CompletableResultCode export(Marshaler exportRequest, int numItems) { + if (isShutdown.get()) { + return CompletableResultCode.ofFailure(); + } + + ExporterInstrumentation.Recording metricRecording = + exporterMetrics.startRecordingExport(numItems); + + MessageWriter messageWriter = + exportAsJson ? exportRequest.toJsonMessageWriter() : exportRequest.toBinaryMessageWriter(); + + long requestBodySize; + try { + requestBodySize = getRequestBodySize(messageWriter); + } catch (IOException e) { + return failRequestBodySizeComputation(metricRecording, e); + } + if (requestBodySize > maxRequestBodySize) { + return failRequestTooLarge(metricRecording, requestBodySize); + } + + CompletableResultCode result = new CompletableResultCode(); + + httpSender.send( + messageWriter, + httpResponse -> onResponse(result, metricRecording, httpResponse, numItems), + throwable -> onError(result, metricRecording, numItems, throwable)); + + return result; + } + + private CompletableResultCode failRequestTooLarge( + ExporterInstrumentation.Recording metricRecording, long requestBodySize) { + String errorMessage = + "Failed to export " + + type + + "s. Request body size " + + requestBodySize + + " exceeded limit of " + + maxRequestBodySize + + " bytes"; + IOException exception = new IOException(errorMessage); + metricRecording.finishFailed(exception); + logger.log(Level.WARNING, errorMessage); + return CompletableResultCode.ofExceptionalFailure( + FailedExportException.httpFailedExceptionally(exception)); + } + + private CompletableResultCode failRequestBodySizeComputation( + ExporterInstrumentation.Recording metricRecording, IOException exception) { + metricRecording.finishFailed(exception); + logger.log( + Level.SEVERE, + "Failed to export " + type + "s. The request body size could not be computed.", + exception); + return CompletableResultCode.ofExceptionalFailure( + FailedExportException.httpFailedExceptionally(exception)); + } + + private static long getRequestBodySize(MessageWriter messageWriter) throws IOException { + int contentLength = messageWriter.getContentLength(); + if (contentLength >= 0) { + return contentLength; + } + + CountingOutputStream countingOutputStream = new CountingOutputStream(); + messageWriter.writeMessage(countingOutputStream); + return countingOutputStream.getCount(); + } + + private static final class CountingOutputStream extends OutputStream { + private long count; + + @Override + public void write(int b) { + count++; + } + + @Override + public void write(byte[] b, int off, int len) { + count += len; + } + + private long getCount() { + return count; + } + } + + private void onResponse( + CompletableResultCode result, + ExporterInstrumentation.Recording metricRecording, + HttpResponse httpResponse, + int numItems) { + int statusCode = httpResponse.getStatusCode(); + + metricRecording.setHttpStatusCode(statusCode); + + if (statusCode >= 200 && statusCode < 300) { + metricRecording.finishSuccessful(); + result.succeed(); + return; + } + + metricRecording.finishFailed(String.valueOf(statusCode)); + + byte[] body = httpResponse.getResponseBody(); + + String status = extractErrorStatus(httpResponse.getStatusMessage(), body); + + logger.log( + levelOnFailure(Level.WARNING), + "Failed to export " + + numItems + + " " + + type + + "s. Server responded with HTTP status code " + + statusCode + + ". Error message: " + + status); + + result.failExceptionally(FailedExportException.httpFailedWithResponse(httpResponse)); + } + + // Failures after shutdown are typically caused by in-flight requests being cancelled by + // shutdown() and are not actionable, so demote them to FINE. + private Level levelOnFailure(Level defaultLevel) { + return isShutdown.get() ? Level.FINE : defaultLevel; + } + + private void onError( + CompletableResultCode result, + ExporterInstrumentation.Recording metricRecording, + int numItems, + Throwable e) { + metricRecording.finishFailed(e); + logger.log( + levelOnFailure(Level.SEVERE), + "Failed to export " + numItems + " " + type + "s. The request could not be executed.", + e); + result.failExceptionally(FailedExportException.httpFailedExceptionally(e)); + } + + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + logger.log(Level.INFO, "Calling shutdown() multiple times."); + return CompletableResultCode.ofSuccess(); + } + return httpSender.shutdown(); + } + + private static String extractErrorStatus(String statusMessage, @Nullable byte[] responseBody) { + if (responseBody == null) { + return "Response body missing, HTTP status message: " + statusMessage; + } + if (responseBody.length == 0) { + return "Response body has 0 length, HTTP status message: " + statusMessage; + } + try { + return GrpcExporterUtil.getStatusMessage(responseBody); + } catch (IOException e) { + return extractResponseBodyMessage(responseBody, statusMessage); + } + } + + private static String extractResponseBodyMessage(byte[] responseBody, String statusMessage) { + int lengthToRead = Math.min(responseBody.length, MAX_RESPONSE_BODY_LOG_LENGTH); + String responseBodyText = + new String(responseBody, 0, lengthToRead, StandardCharsets.UTF_8).trim(); + if (responseBodyText.isEmpty()) { + return "HTTP status message: " + statusMessage; + } + return "Response body: " + responseBodyText + ", HTTP status message: " + statusMessage; + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java new file mode 100644 index 00000000000..6e30f973f5b --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilder.java @@ -0,0 +1,320 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.EndpointUtil; +import io.opentelemetry.exporter.internal.SenderUtil; +import io.opentelemetry.exporter.internal.TlsConfigHelper; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.HttpSenderProvider; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.StringJoiner; +import java.util.concurrent.ExecutorService; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * A builder for {@link HttpExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@SuppressWarnings("checkstyle:JavadocMethod") +public final class HttpExporterBuilder { + public static final long DEFAULT_TIMEOUT_SECS = 10; + public static final long DEFAULT_CONNECT_TIMEOUT_SECS = 10; + public static final long DEFAULT_MAX_REQUEST_BODY_SIZE = 64 * 1024L * 1024L; + + private static final Logger LOGGER = Logger.getLogger(HttpExporterBuilder.class.getName()); + + private StandardComponentId.ExporterType exporterType; + + private URI endpoint; + + private Duration timeout = Duration.ofSeconds(DEFAULT_TIMEOUT_SECS); + @Nullable private Compressor compressor; + private Duration connectTimeout = Duration.ofSeconds(DEFAULT_CONNECT_TIMEOUT_SECS); + @Nullable private ProxyOptions proxyOptions; + private boolean exportAsJson = false; + private final Map constantHeaders = new HashMap<>(); + private Supplier> headerSupplier = Collections::emptyMap; + + private TlsConfigHelper tlsConfigHelper = new TlsConfigHelper(); + @Nullable private RetryPolicy retryPolicy = RetryPolicy.getDefault(); + private Supplier meterProviderSupplier = + () -> GlobalOpenTelemetry.getOrNoop().getMeterProvider(); + private InternalTelemetryVersion internalTelemetryVersion = InternalTelemetryVersion.LEGACY; + private ComponentLoader componentLoader = + ComponentLoader.forClassLoader(HttpExporterBuilder.class.getClassLoader()); + @Nullable private ExecutorService executorService; + private long maxRequestBodySize = DEFAULT_MAX_REQUEST_BODY_SIZE; + @Nullable private List enabledProtocols; + + public HttpExporterBuilder( + StandardComponentId.ExporterType exporterType, String defaultEndpoint) { + this(exporterType, EndpointUtil.validateEndpoint(defaultEndpoint)); + } + + HttpExporterBuilder(StandardComponentId.ExporterType exporterType, URI endpoint) { + this.exporterType = exporterType; + this.endpoint = endpoint; + } + + public HttpExporterBuilder setTimeout(Duration duration) { + timeout = duration.toNanos() == 0 ? Duration.ofNanos(Long.MAX_VALUE) : duration; + return this; + } + + public HttpExporterBuilder setConnectTimeout(Duration duration) { + connectTimeout = duration.toNanos() == 0 ? Duration.ofNanos(Long.MAX_VALUE) : duration; + return this; + } + + public HttpExporterBuilder setEndpoint(String endpoint) { + this.endpoint = EndpointUtil.validateEndpoint(endpoint); + return this; + } + + public HttpExporterBuilder setCompression(@Nullable Compressor compressor) { + this.compressor = compressor; + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Support for additional compression + * methods is available by implementing {@link Compressor}. + */ + public HttpExporterBuilder setCompression(String compressionMethod) { + Compressor compressor = + CompressorUtil.validateAndResolveCompressor(compressionMethod, componentLoader); + return setCompression(compressor); + } + + public HttpExporterBuilder addConstantHeaders(String key, String value) { + constantHeaders.put(key, value); + return this; + } + + public HttpExporterBuilder setHeadersSupplier(Supplier> headerSupplier) { + this.headerSupplier = headerSupplier; + return this; + } + + public HttpExporterBuilder setTrustManagerFromCerts(byte[] trustedCertificatesPem) { + tlsConfigHelper.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + public HttpExporterBuilder setKeyManagerFromCerts(byte[] privateKeyPem, byte[] certificatePem) { + tlsConfigHelper.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + public HttpExporterBuilder setSslContext(SSLContext sslContext, X509TrustManager trustManager) { + tlsConfigHelper.setSslContext(sslContext, trustManager); + return this; + } + + public HttpExporterBuilder setMeterProvider(Supplier meterProviderSupplier) { + this.meterProviderSupplier = meterProviderSupplier; + return this; + } + + public HttpExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion internalTelemetryVersion) { + this.internalTelemetryVersion = internalTelemetryVersion; + return this; + } + + public HttpExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + this.retryPolicy = retryPolicy; + return this; + } + + public HttpExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + this.proxyOptions = proxyOptions; + return this; + } + + public HttpExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + this.componentLoader = componentLoader; + return this; + } + + public HttpExporterBuilder setExecutorService(ExecutorService executorService) { + this.executorService = executorService; + return this; + } + + public HttpExporterBuilder setMaxRequestBodySize(long maxRequestBodySize) { + this.maxRequestBodySize = maxRequestBodySize == 0 ? Long.MAX_VALUE : maxRequestBodySize; + return this; + } + + public HttpExporterBuilder setEnabledProtocols(@Nullable List enabledProtocols) { + this.enabledProtocols = enabledProtocols; + return this; + } + + public HttpExporterBuilder exportAsJson() { + this.exportAsJson = true; + exporterType = mapToJsonTypeIfPossible(exporterType); + return this; + } + + private static StandardComponentId.ExporterType mapToJsonTypeIfPossible( + StandardComponentId.ExporterType componentType) { + switch (componentType) { + case OTLP_HTTP_SPAN_EXPORTER: + return StandardComponentId.ExporterType.OTLP_HTTP_JSON_SPAN_EXPORTER; + case OTLP_HTTP_LOG_EXPORTER: + return StandardComponentId.ExporterType.OTLP_HTTP_JSON_LOG_EXPORTER; + case OTLP_HTTP_METRIC_EXPORTER: + return StandardComponentId.ExporterType.OTLP_HTTP_JSON_METRIC_EXPORTER; + default: + return componentType; + } + } + + @SuppressWarnings("BuilderReturnThis") + public HttpExporterBuilder copy() { + HttpExporterBuilder copy = new HttpExporterBuilder(exporterType, endpoint); + copy.timeout = timeout; + copy.connectTimeout = connectTimeout; + copy.exportAsJson = exportAsJson; + copy.compressor = compressor; + copy.constantHeaders.putAll(constantHeaders); + copy.headerSupplier = headerSupplier; + copy.tlsConfigHelper = tlsConfigHelper.copy(); + if (retryPolicy != null) { + copy.retryPolicy = retryPolicy.toBuilder().build(); + } + copy.meterProviderSupplier = meterProviderSupplier; + copy.internalTelemetryVersion = internalTelemetryVersion; + copy.proxyOptions = proxyOptions; + copy.componentLoader = componentLoader; + copy.maxRequestBodySize = maxRequestBodySize; + copy.enabledProtocols = enabledProtocols; + return copy; + } + + public HttpExporter build() { + Supplier>> headerSupplier = + () -> { + Map> result = new HashMap<>(); + Map supplierResult = this.headerSupplier.get(); + if (supplierResult != null) { + supplierResult.forEach( + (key, value) -> result.put(key, Collections.singletonList(value))); + } + constantHeaders.forEach((key, value) -> + result.merge( + key, + Collections.singletonList(value), + (v1, v2) -> { + List merged = new ArrayList<>(v1); + merged.addAll(v2); + return merged; + })); + return result; + }; + + boolean isPlainHttp = endpoint.getScheme().equals("http"); + HttpSenderProvider httpSenderProvider = SenderUtil.resolveHttpSenderProvider(componentLoader); + HttpSender httpSender = + httpSenderProvider.createSender( + ImmutableHttpSenderConfig.create( + endpoint, + exportAsJson ? "application/json" : "application/x-protobuf", + compressor, + timeout, + connectTimeout, + headerSupplier, + proxyOptions, + retryPolicy, + isPlainHttp ? null : tlsConfigHelper.getSslContext(), + isPlainHttp ? null : tlsConfigHelper.getTrustManager(), + executorService, + // 4mb to align with spec guidance - even though we don't do anything with the + // response today, we will so better to have future-looking memory profile + 4 * 1024L * 1024L, + enabledProtocols)); + LOGGER.log(Level.FINE, "Using HttpSender: " + httpSender.getClass().getName()); + + return new HttpExporter( + ComponentId.generateLazy(exporterType), + httpSender, + meterProviderSupplier, + internalTelemetryVersion, + endpoint, + exportAsJson, + maxRequestBodySize); + } + + public String toString(boolean includePrefixAndSuffix) { + StringJoiner joiner = + includePrefixAndSuffix + ? new StringJoiner(", ", "HttpExporterBuilder{", "}") + : new StringJoiner(", "); + joiner.add("endpoint=" + endpoint); + joiner.add("timeoutNanos=" + timeout.toNanos()); + joiner.add("proxyOptions=" + proxyOptions); + joiner.add( + "compressorEncoding=" + + Optional.ofNullable(compressor).map(Compressor::getEncoding).orElse(null)); + joiner.add("connectTimeoutNanos=" + connectTimeout.toNanos()); + joiner.add("exportAsJson=" + exportAsJson); + StringJoiner headersJoiner = new StringJoiner(", ", "Headers{", "}"); + constantHeaders.forEach((key, value) -> headersJoiner.add(key + "=OBFUSCATED")); + Map headers = headerSupplier.get(); + if (headers != null) { + headers.forEach((key, value) -> headersJoiner.add(key + "=OBFUSCATED")); + } + joiner.add("headers=" + headersJoiner); + if (retryPolicy != null) { + joiner.add("retryPolicy=" + retryPolicy); + } + if (enabledProtocols != null) { + joiner.add("enabledProtocols=" + enabledProtocols); + } + joiner.add("componentLoader=" + componentLoader); + if (executorService != null) { + joiner.add("executorService=" + executorService); + } + joiner.add("maxRequestBodySize=" + maxRequestBodySize); + joiner.add("exporterType=" + exporterType); + joiner.add("internalTelemetrySchemaVersion=" + internalTelemetryVersion); + // Note: omit tlsConfigHelper because we can't log the configuration in any readable way + // Note: omit meterProviderSupplier because we can't log the configuration in any readable way + return joiner.toString(); + } + + @Override + public String toString() { + return toString(true); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/ImmutableGrpcSenderConfig.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/ImmutableGrpcSenderConfig.java new file mode 100644 index 00000000000..58607906a82 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/ImmutableGrpcSenderConfig.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.exporter.internal.grpc.ExtendedGrpcSenderConfig; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +@AutoValue +public abstract class ImmutableGrpcSenderConfig implements ExtendedGrpcSenderConfig { + + @SuppressWarnings("TooManyParameters") + public static ImmutableGrpcSenderConfig create( + URI endpoint, + String fullMethodName, + @Nullable Compressor compressor, + Duration timeoutNanos, + Duration connectTimeoutNanos, + Supplier>> headersSupplier, + @Nullable RetryPolicy retryPolicy, + @Nullable SSLContext sslContext, + @Nullable X509TrustManager trustManager, + @Nullable ExecutorService executorService, + @Nullable Object managedChannel, + long maxResponseBodySize, + @Nullable List enabledProtocols) { + return new AutoValue_ImmutableGrpcSenderConfig( + endpoint, + fullMethodName, + compressor, + timeoutNanos, + connectTimeoutNanos, + headersSupplier, + retryPolicy, + sslContext, + trustManager, + executorService, + managedChannel, + maxResponseBodySize, + enabledProtocols); + } + + @Override + public abstract long getMaxResponseBodySize(); + + @Override + @Nullable + public abstract List getEnabledProtocols(); +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/ImmutableHttpSenderConfig.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/ImmutableHttpSenderConfig.java new file mode 100644 index 00000000000..1f2ac4856d4 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/ImmutableHttpSenderConfig.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.HttpSenderConfig; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +@AutoValue +abstract class ImmutableHttpSenderConfig implements HttpSenderConfig { + + @SuppressWarnings("TooManyParameters") + static HttpSenderConfig create( + URI endpoint, + String contentType, + @Nullable Compressor compressor, + Duration timeoutNanos, + Duration connectTimeoutNanos, + Supplier>> headerSupplier, + @Nullable ProxyOptions proxyOptions, + @Nullable RetryPolicy retryPolicy, + @Nullable SSLContext sslContext, + @Nullable X509TrustManager trustManager, + @Nullable ExecutorService executorService, + long maxResponseBodySize, + @Nullable List enabledProtocols) { + return new AutoValue_ImmutableHttpSenderConfig( + endpoint, + contentType, + compressor, + timeoutNanos, + connectTimeoutNanos, + headerSupplier, + proxyOptions, + retryPolicy, + sslContext, + trustManager, + executorService, + maxResponseBodySize, + enabledProtocols); + } + + @Override + public abstract long getMaxResponseBodySize(); + + @Override + @Nullable + public abstract List getEnabledProtocols(); +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/InternalTelemetryConfiguration.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/InternalTelemetryConfiguration.java new file mode 100644 index 00000000000..89af16ccbb4 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/InternalTelemetryConfiguration.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import java.util.Locale; + +/** + * Reads the desired SDK internal telemetry version from {@link ConfigProperties}. + * + *

    This is the same as {@code io.opentelemetry.sdk.autoconfigure.InternalTelemetryConfiguration}. + * Any changes should be reflected there as well. + */ +final class InternalTelemetryConfiguration { + + static InternalTelemetryVersion getVersion(ConfigProperties config) { + String version = config.getString("otel.experimental.sdk.telemetry.version"); + if (version == null) { + return InternalTelemetryVersion.LEGACY; + } + + switch (version.toLowerCase(Locale.ROOT)) { + case "legacy": + return InternalTelemetryVersion.LEGACY; + case "latest": + return InternalTelemetryVersion.LATEST; + default: + throw new ConfigurationException("Invalid sdk telemetry version: " + version); + } + } + + private InternalTelemetryConfiguration() {} +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtil.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtil.java new file mode 100644 index 00000000000..5948edb3b3e --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtil.java @@ -0,0 +1,279 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class OtlpConfigUtil { + + private static final Logger logger = Logger.getLogger(OtlpConfigUtil.class.getName()); + + public static final String DATA_TYPE_TRACES = "traces"; + public static final String DATA_TYPE_METRICS = "metrics"; + public static final String DATA_TYPE_LOGS = "logs"; + + public static final String PROTOCOL_GRPC = "grpc"; + public static final String PROTOCOL_HTTP_PROTOBUF = "http/protobuf"; + + /** Determine the configured OTLP protocol for the {@code dataType}. */ + public static String getOtlpProtocol(String dataType, ConfigProperties config) { + String protocol = config.getString("otel.exporter.otlp." + dataType + ".protocol"); + if (protocol != null) { + return protocol; + } + return config.getString("otel.exporter.otlp.protocol", PROTOCOL_GRPC); + } + + /** Invoke the setters with the OTLP configuration for the {@code dataType}. */ + @SuppressWarnings("TooManyParameters") + public static void configureOtlpExporterBuilder( + String dataType, + ConfigProperties config, + Consumer setComponentLoader, + Consumer setEndpoint, + BiConsumer addHeader, + Consumer setCompression, + Consumer setTimeout, + Consumer setTrustedCertificates, + BiConsumer setClientTls, + Consumer setRetryPolicy, + Consumer setMemoryMode, + Consumer setInternalTelemetryVersion) { + setComponentLoader.accept(config.getComponentLoader()); + + String protocol = getOtlpProtocol(dataType, config); + boolean isHttpProtobuf = protocol.equals(PROTOCOL_HTTP_PROTOBUF); + URL endpoint = + validateEndpoint( + config.getString("otel.exporter.otlp." + dataType + ".endpoint"), isHttpProtobuf); + if (endpoint != null) { + if (endpoint.getPath().isEmpty()) { + endpoint = createUrl(endpoint, "/"); + } + } else { + endpoint = validateEndpoint(config.getString("otel.exporter.otlp.endpoint"), isHttpProtobuf); + if (endpoint != null && isHttpProtobuf) { + String path = endpoint.getPath(); + if (!path.endsWith("/")) { + path += "/"; + } + path += signalPath(dataType); + endpoint = createUrl(endpoint, path); + } + } + if (endpoint != null) { + setEndpoint.accept(endpoint.toString()); + } + + configureOtlpHeaders(config, dataType, addHeader); + + String compression = config.getString("otel.exporter.otlp." + dataType + ".compression"); + if (compression == null) { + compression = config.getString("otel.exporter.otlp.compression"); + } + if (compression != null) { + setCompression.accept(compression); + } + + Duration timeout = config.getDuration("otel.exporter.otlp." + dataType + ".timeout"); + if (timeout == null) { + timeout = config.getDuration("otel.exporter.otlp.timeout"); + } + if (timeout != null) { + setTimeout.accept(timeout); + } + + InternalTelemetryVersion telemetryVersion = InternalTelemetryConfiguration.getVersion(config); + setInternalTelemetryVersion.accept(telemetryVersion); + + String certificatePath = + config.getString( + determinePropertyByType(config, "otel.exporter.otlp", dataType, "certificate")); + String clientKeyPath = + config.getString( + determinePropertyByType(config, "otel.exporter.otlp", dataType, "client.key")); + String clientKeyChainPath = + config.getString( + determinePropertyByType(config, "otel.exporter.otlp", dataType, "client.certificate")); + + if (clientKeyPath != null && clientKeyChainPath == null) { + throw new ConfigurationException( + "client key provided without client certificate - both client key and client certificate must be set"); + } else if (clientKeyPath == null && clientKeyChainPath != null) { + throw new ConfigurationException( + "client certificate provided without client key - both client key and client_certificate must be set"); + } + + byte[] certificateBytes = readFileBytes(certificatePath); + if (certificateBytes != null) { + setTrustedCertificates.accept(certificateBytes); + } + + byte[] clientKeyBytes = readFileBytes(clientKeyPath); + byte[] clientKeyChainBytes = readFileBytes(clientKeyChainPath); + + if (clientKeyBytes != null && clientKeyChainBytes != null) { + setClientTls.accept(clientKeyBytes, clientKeyChainBytes); + } + + Boolean retryDisabled = config.getBoolean("otel.java.exporter.otlp.retry.disabled"); + if (retryDisabled != null && retryDisabled) { + setRetryPolicy.accept(null); + } + + ExporterBuilderUtil.configureExporterMemoryMode(config, setMemoryMode); + } + + @SuppressWarnings("JdkObsolete") // Recommended alternative was introduced in java 10 + static void configureOtlpHeaders( + ConfigProperties config, String dataType, BiConsumer addHeader) { + Map headers = config.getMap("otel.exporter.otlp." + dataType + ".headers"); + if (headers.isEmpty()) { + headers = config.getMap("otel.exporter.otlp.headers"); + } + for (Map.Entry entry : headers.entrySet()) { + String key = entry.getKey(); + String value = entry.getValue(); + try { + // headers are encoded as URL - see + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#specifying-headers-via-environment-variables + addHeader.accept(key, URLDecoder.decode(value, StandardCharsets.UTF_8.name())); + } catch (Exception e) { + throw new ConfigurationException("Cannot decode header value for header: " + key, e); + } + } + } + + private static URL createUrl(URL context, String spec) { + try { + return new URL(context, spec); + } catch (MalformedURLException e) { + throw new ConfigurationException("Unexpected exception creating URL.", e); + } + } + + @Nullable + static URL validateEndpoint(@Nullable String endpoint, boolean isHttpProtobuf) { + if (endpoint == null) { + return null; + } + URL endpointUrl; + try { + endpointUrl = new URL(endpoint); + } catch (MalformedURLException e) { + throw new ConfigurationException("OTLP endpoint must be a valid URL: " + endpoint, e); + } + if (!endpointUrl.getProtocol().equals("http") && !endpointUrl.getProtocol().equals("https")) { + throw new ConfigurationException( + "OTLP endpoint scheme must be http or https: " + endpointUrl.getProtocol()); + } + if (endpointUrl.getQuery() != null) { + throw new ConfigurationException( + "OTLP endpoint must not have a query string: " + endpointUrl.getQuery()); + } + if (endpointUrl.getRef() != null) { + throw new ConfigurationException( + "OTLP endpoint must not have a fragment: " + endpointUrl.getRef()); + } + if (!isHttpProtobuf + && (!endpointUrl.getPath().isEmpty() && !endpointUrl.getPath().equals("/"))) { + throw new ConfigurationException( + "OTLP endpoint must not have a path: " + endpointUrl.getPath()); + } + if ((endpointUrl.getPort() == 4317 && isHttpProtobuf) + || (endpointUrl.getPort() == 4318 && !isHttpProtobuf)) { + int expectedPort = isHttpProtobuf ? 4318 : 4317; + String protocol = isHttpProtobuf ? PROTOCOL_HTTP_PROTOBUF : PROTOCOL_GRPC; + logger.warning( + "OTLP exporter endpoint port is likely incorrect for protocol version \"" + + protocol + + "\". The endpoint " + + endpointUrl + + " has port " + + endpointUrl.getPort() + + ". Typically, the \"" + + protocol + + "\" version of OTLP uses port " + + expectedPort + + "."); + } + return endpointUrl; + } + + @Nullable + static byte[] readFileBytes(@Nullable String filePath) { + if (filePath == null) { + return null; + } + File file = new File(filePath); + if (!file.exists()) { + throw new ConfigurationException("Invalid OTLP certificate/key path: " + filePath); + } + try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { + long length = raf.length(); + if (length > Integer.MAX_VALUE) { + throw new ConfigurationException("File too large: " + filePath); + } + byte[] bytes = new byte[(int) length]; + raf.readFully(bytes); + return bytes; + } catch (IOException e) { + throw new ConfigurationException("Error reading content of file (" + filePath + ")", e); + } + } + + private static String determinePropertyByType( + ConfigProperties config, String prefix, String dataType, String suffix) { + String propertyToRead = prefix + "." + dataType + "." + suffix; + if (configContainsKey(config, propertyToRead)) { + return propertyToRead; + } + return prefix + "." + suffix; + } + + private static boolean configContainsKey(ConfigProperties config, String propertyToRead) { + return config.getString(propertyToRead) != null; + } + + private static String signalPath(String dataType) { + switch (dataType) { + case DATA_TYPE_METRICS: + return "v1/metrics"; + case DATA_TYPE_TRACES: + return "v1/traces"; + case DATA_TYPE_LOGS: + return "v1/logs"; + default: + throw new IllegalArgumentException( + "Cannot determine signal path for unrecognized data type: " + dataType); + } + } + + private OtlpConfigUtil() {} +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java new file mode 100644 index 00000000000..d3f30b22d3a --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpDeclarativeConfigUtil.java @@ -0,0 +1,178 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.configureOtlpHeaders; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.readFileBytes; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.validateEndpoint; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.IncubatingExporterBuilderUtil; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ExtendedDeclarativeConfigProperties; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.net.URL; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class OtlpDeclarativeConfigUtil { + + /** Determine the configured OTLP protocol for the {@code dataType}. */ + public static String getStructuredConfigOtlpProtocol(DeclarativeConfigProperties config) { + // NOTE: The default OTLP protocol is different for declarative config than for env var / system + // property based config. This is intentional. OpenTelemetry changed the default protocol + // recommendation from grpc to http/protobuf, but the autoconfigure's env var / system property + // based config did not update to reflect this before stabilizing, and changing is a breaking + // change requiring a major version bump. Declarative config is not yet stable and therefore can + // switch to the current default recommendation, which aligns also aligns with the behavior of + // the OpenTelemetry Java Agent 2.x+. + return config.getString("protocol", PROTOCOL_HTTP_PROTOBUF); + } + + /** Invoke the setters with the OTLP configuration for the {@code dataType}. */ + @SuppressWarnings("TooManyParameters") + public static void configureOtlpExporterBuilder( + String dataType, + DeclarativeConfigProperties baseConfig, + Consumer setComponentLoader, + Consumer setEndpoint, + BiConsumer addHeader, + Consumer setCompression, + Consumer setTimeout, + Consumer setTrustedCertificates, + BiConsumer setClientTls, + Consumer setRetryPolicy, + Consumer setMemoryMode, + Consumer setMaxRequestSize, + boolean isHttpProtobuf, + Consumer internalTelemetryVersionConsumer, + Runnable setNoopMeterProvider) { + checkArgument( + baseConfig instanceof ExtendedDeclarativeConfigProperties, + "Expected ExtendedDeclarativeConfigProperties"); + ExtendedDeclarativeConfigProperties config = (ExtendedDeclarativeConfigProperties) baseConfig; + + setComponentLoader.accept(config.getComponentLoader()); + + URL endpoint = validateEndpoint(config.getString("endpoint"), isHttpProtobuf); + if (endpoint != null) { + setEndpoint.accept(endpoint.toString()); + } + + String headerList = config.getString("headers_list"); + if (headerList != null) { + ConfigProperties headersListConfig = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.headers", headerList)); + configureOtlpHeaders(headersListConfig, dataType, addHeader); + } + + List headers = config.getStructuredList("headers"); + if (headers != null) { + headers.forEach(header -> { + String name = header.getString("name"); + String value = header.getString("value"); + if (name != null && value != null) { + addHeader.accept(name, value); + } + }); + } + + String compression = config.getString("compression"); + if (compression != null) { + setCompression.accept(compression); + } + + Integer timeoutMs = config.getInt("timeout"); + if (timeoutMs != null) { + setTimeout.accept(Duration.ofMillis(timeoutMs)); + } + + Integer maxRequestSize = config.getInt("max_request_size"); + if (maxRequestSize != null) { + setMaxRequestSize.accept(maxRequestSize.longValue()); + } + + DeclarativeConfigProperties tls = + config.getStructured("tls", DeclarativeConfigProperties.empty()); + String certificatePath = tls.getString("ca_file"); + String clientKeyPath = tls.getString("key_file"); + String clientKeyChainPath = tls.getString("cert_file"); + + if (clientKeyPath != null && clientKeyChainPath == null) { + throw new ConfigurationException( + "client_key_file provided without client_certificate_file - both client_key_file and client_certificate_file must be set"); + } else if (clientKeyPath == null && clientKeyChainPath != null) { + throw new ConfigurationException( + "client_certificate_file provided without client_key_file - both client_key_file and client_certificate_file must be set"); + } + byte[] certificateBytes = readFileBytes(certificatePath); + if (certificateBytes != null) { + setTrustedCertificates.accept(certificateBytes); + } + byte[] clientKeyBytes = readFileBytes(clientKeyPath); + byte[] clientKeyChainBytes = readFileBytes(clientKeyChainPath); + if (clientKeyBytes != null && clientKeyChainBytes != null) { + setClientTls.accept(clientKeyBytes, clientKeyChainBytes); + } + + IncubatingExporterBuilderUtil.configureExporterMemoryMode(config, setMemoryMode); + + // InternalTelemetryVersion defaults to disabled (i.e. null) until semantic conventions are + // stable. To disable, set a noop meter provider. + InternalTelemetryVersion telemetryVersion = + getInternalTelemetryVersion(config.getConfigProvider()); + if (telemetryVersion == null) { + setNoopMeterProvider.run(); + } else { + internalTelemetryVersionConsumer.accept(telemetryVersion); + } + } + + @Nullable + private static InternalTelemetryVersion getInternalTelemetryVersion( + ConfigProvider configProvider) { + String internalTelemetryVersion = + configProvider.getInstrumentationConfig("otel_sdk").getString("internal_telemetry_version"); + if (internalTelemetryVersion == null) { + return null; + } + switch (internalTelemetryVersion.toLowerCase(Locale.ROOT)) { + case "legacy": + return InternalTelemetryVersion.LEGACY; + case "latest": + return InternalTelemetryVersion.LATEST; + default: + throw new DeclarativeConfigException( + "Invalid sdk telemetry version: " + internalTelemetryVersion); + } + } + + private static void checkArgument(boolean isValid, String message) { + if (!isValid) { + throw new IllegalArgumentException(message); + } + } + + private OtlpDeclarativeConfigUtil() {} +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcLogRecordExporterComponentProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcLogRecordExporterComponentProvider.java new file mode 100644 index 00000000000..c96456ae282 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcLogRecordExporterComponentProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_LOGS; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpGrpcLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpGrpcLogRecordExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return LogRecordExporter.class; + } + + @Override + public String getName() { + return "otlp_grpc"; + } + + @Override + public LogRecordExporter create(DeclarativeConfigProperties config) { + OtlpGrpcLogRecordExporterBuilder builder = grpcBuilder(); + + OtlpDeclarativeConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_LOGS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setMaxRequestMessageSize, + /* isHttpProtobuf= */ false, + builder::setInternalTelemetryVersion, + () -> builder.setMeterProvider(MeterProvider::noop)); + + return builder.build(); + } + + // Visible for testing + OtlpGrpcLogRecordExporterBuilder grpcBuilder() { + return OtlpGrpcLogRecordExporter.builder(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcMetricExporterComponentProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcMetricExporterComponentProvider.java new file mode 100644 index 00000000000..e2c22d93be8 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcMetricExporterComponentProvider.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_METRICS; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.IncubatingExporterBuilderUtil; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpGrpcMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpGrpcMetricExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return MetricExporter.class; + } + + @Override + public String getName() { + return "otlp_grpc"; + } + + @Override + public MetricExporter create(DeclarativeConfigProperties config) { + OtlpGrpcMetricExporterBuilder builder = grpcBuilder(); + + OtlpDeclarativeConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_METRICS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setMaxRequestMessageSize, + /* isHttpProtobuf= */ false, + builder::setInternalTelemetryVersion, + () -> builder.setMeterProvider(MeterProvider::noop)); + IncubatingExporterBuilderUtil.configureOtlpAggregationTemporality( + config, builder::setAggregationTemporalitySelector); + IncubatingExporterBuilderUtil.configureOtlpHistogramDefaultAggregation( + config, builder::setDefaultAggregationSelector); + + return builder.build(); + } + + // Visible for testing + OtlpGrpcMetricExporterBuilder grpcBuilder() { + return OtlpGrpcMetricExporter.builder(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcSpanExporterComponentProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcSpanExporterComponentProvider.java new file mode 100644 index 00000000000..f25e86f3b82 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpGrpcSpanExporterComponentProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_TRACES; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpGrpcSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpGrpcSpanExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return SpanExporter.class; + } + + @Override + public String getName() { + return "otlp_grpc"; + } + + @Override + public SpanExporter create(DeclarativeConfigProperties config) { + OtlpGrpcSpanExporterBuilder builder = grpcBuilder(); + + OtlpDeclarativeConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_TRACES, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setMaxRequestMessageSize, + /* isHttpProtobuf= */ false, + builder::setInternalTelemetryVersion, + () -> builder.setMeterProvider(MeterProvider::noop)); + + return builder.build(); + } + + // Visible for testing + OtlpGrpcSpanExporterBuilder grpcBuilder() { + return OtlpGrpcSpanExporter.builder(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpLogRecordExporterComponentProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpLogRecordExporterComponentProvider.java new file mode 100644 index 00000000000..67d686b87f8 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpLogRecordExporterComponentProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_LOGS; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpHttpLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpHttpLogRecordExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return LogRecordExporter.class; + } + + @Override + public String getName() { + return "otlp_http"; + } + + @Override + public LogRecordExporter create(DeclarativeConfigProperties config) { + OtlpHttpLogRecordExporterBuilder builder = httpBuilder(); + + OtlpDeclarativeConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_LOGS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setMaxRequestBodySize, + /* isHttpProtobuf= */ true, + builder::setInternalTelemetryVersion, + () -> builder.setMeterProvider(MeterProvider::noop)); + + return builder.build(); + } + + // Visible for testing + OtlpHttpLogRecordExporterBuilder httpBuilder() { + return OtlpHttpLogRecordExporter.builder(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpMetricExporterComponentProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpMetricExporterComponentProvider.java new file mode 100644 index 00000000000..768d871c7c1 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpMetricExporterComponentProvider.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_METRICS; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.IncubatingExporterBuilderUtil; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpHttpMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpHttpMetricExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return MetricExporter.class; + } + + @Override + public String getName() { + return "otlp_http"; + } + + @Override + public MetricExporter create(DeclarativeConfigProperties config) { + OtlpHttpMetricExporterBuilder builder = httpBuilder(); + + OtlpDeclarativeConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_METRICS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setMaxRequestBodySize, + /* isHttpProtobuf= */ true, + builder::setInternalTelemetryVersion, + () -> builder.setMeterProvider(MeterProvider::noop)); + IncubatingExporterBuilderUtil.configureOtlpAggregationTemporality( + config, builder::setAggregationTemporalitySelector); + IncubatingExporterBuilderUtil.configureOtlpHistogramDefaultAggregation( + config, builder::setDefaultAggregationSelector); + + return builder.build(); + } + + // Visible for testing + OtlpHttpMetricExporterBuilder httpBuilder() { + return OtlpHttpMetricExporter.builder(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpSpanExporterComponentProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpSpanExporterComponentProvider.java new file mode 100644 index 00000000000..76c9f6edd5d --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpHttpSpanExporterComponentProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_TRACES; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +/** + * Declarative configuration SPI implementation for {@link OtlpHttpSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpHttpSpanExporterComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return SpanExporter.class; + } + + @Override + public String getName() { + return "otlp_http"; + } + + @Override + public SpanExporter create(DeclarativeConfigProperties config) { + OtlpHttpSpanExporterBuilder builder = httpBuilder(); + + OtlpDeclarativeConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_TRACES, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setMaxRequestBodySize, + /* isHttpProtobuf= */ true, + builder::setInternalTelemetryVersion, + () -> builder.setMeterProvider(MeterProvider::noop)); + + return builder.build(); + } + + // Visible for testing + OtlpHttpSpanExporterBuilder httpBuilder() { + return OtlpHttpSpanExporter.builder(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProvider.java new file mode 100644 index 00000000000..6a478db1984 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProvider.java @@ -0,0 +1,103 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_LOGS; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_GRPC; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.concurrent.atomic.AtomicReference; + +/** + * {@link LogRecordExporter} SPI implementation for {@link OtlpGrpcLogRecordExporter} and {@link + * OtlpHttpLogRecordExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider, AutoConfigureListener { + + private final AtomicReference meterProviderRef = + new AtomicReference<>(MeterProvider.noop()); + + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + String protocol = OtlpConfigUtil.getOtlpProtocol(DATA_TYPE_LOGS, config); + + if (protocol.equals(PROTOCOL_HTTP_PROTOBUF)) { + OtlpHttpLogRecordExporterBuilder builder = httpBuilder(); + + OtlpConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_LOGS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setInternalTelemetryVersion); + builder.setMeterProvider(meterProviderRef::get); + + return builder.build(); + } else if (protocol.equals(PROTOCOL_GRPC)) { + OtlpGrpcLogRecordExporterBuilder builder = grpcBuilder(); + + OtlpConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_LOGS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setInternalTelemetryVersion); + builder.setMeterProvider(meterProviderRef::get); + + return builder.build(); + } + throw new ConfigurationException("Unsupported OTLP logs protocol: " + protocol); + } + + @Override + public String getName() { + return "otlp"; + } + + // Visible for testing + OtlpHttpLogRecordExporterBuilder httpBuilder() { + return OtlpHttpLogRecordExporter.builder(); + } + + // Visible for testing + OtlpGrpcLogRecordExporterBuilder grpcBuilder() { + return OtlpGrpcLogRecordExporter.builder(); + } + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) { + meterProviderRef.set(sdk.getMeterProvider()); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProvider.java new file mode 100644 index 00000000000..35039182f23 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProvider.java @@ -0,0 +1,112 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_METRICS; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_GRPC; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.concurrent.atomic.AtomicReference; + +/** + * {@link MetricExporter} SPI implementation for {@link OtlpGrpcMetricExporter} and {@link + * OtlpHttpMetricExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpMetricExporterProvider + implements ConfigurableMetricExporterProvider, AutoConfigureListener { + + private final AtomicReference meterProviderRef = + new AtomicReference<>(MeterProvider.noop()); + + @Override + public MetricExporter createExporter(ConfigProperties config) { + String protocol = OtlpConfigUtil.getOtlpProtocol(DATA_TYPE_METRICS, config); + + if (protocol.equals(PROTOCOL_HTTP_PROTOBUF)) { + OtlpHttpMetricExporterBuilder builder = httpBuilder(); + + OtlpConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_METRICS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setInternalTelemetryVersion); + ExporterBuilderUtil.configureOtlpAggregationTemporality( + config, builder::setAggregationTemporalitySelector); + ExporterBuilderUtil.configureOtlpHistogramDefaultAggregation( + config, builder::setDefaultAggregationSelector); + builder.setMeterProvider(meterProviderRef::get); + + return builder.build(); + } else if (protocol.equals(PROTOCOL_GRPC)) { + OtlpGrpcMetricExporterBuilder builder = grpcBuilder(); + + OtlpConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_METRICS, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setInternalTelemetryVersion); + ExporterBuilderUtil.configureOtlpAggregationTemporality( + config, builder::setAggregationTemporalitySelector); + ExporterBuilderUtil.configureOtlpHistogramDefaultAggregation( + config, builder::setDefaultAggregationSelector); + builder.setMeterProvider(meterProviderRef::get); + + return builder.build(); + } + throw new ConfigurationException("Unsupported OTLP metrics protocol: " + protocol); + } + + @Override + public String getName() { + return "otlp"; + } + + // Visible for testing + OtlpHttpMetricExporterBuilder httpBuilder() { + return OtlpHttpMetricExporter.builder(); + } + + // Visible for testing + OtlpGrpcMetricExporterBuilder grpcBuilder() { + return OtlpGrpcMetricExporter.builder(); + } + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) { + meterProviderRef.set(sdk.getMeterProvider()); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProvider.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProvider.java new file mode 100644 index 00000000000..f4467a2f601 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProvider.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_TRACES; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_GRPC; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.concurrent.atomic.AtomicReference; + +/** + * {@link SpanExporter} SPI implementation for {@link OtlpGrpcSpanExporter} and {@link + * OtlpHttpSpanExporter}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OtlpSpanExporterProvider + implements ConfigurableSpanExporterProvider, AutoConfigureListener { + + private final AtomicReference meterProviderRef = + new AtomicReference<>(MeterProvider.noop()); + + @Override + public SpanExporter createExporter(ConfigProperties config) { + String protocol = OtlpConfigUtil.getOtlpProtocol(DATA_TYPE_TRACES, config); + if (protocol.equals(PROTOCOL_HTTP_PROTOBUF)) { + OtlpHttpSpanExporterBuilder builder = httpBuilder(); + + OtlpConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_TRACES, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setInternalTelemetryVersion); + builder.setMeterProvider(meterProviderRef::get); + + return builder.build(); + } else if (protocol.equals(PROTOCOL_GRPC)) { + OtlpGrpcSpanExporterBuilder builder = grpcBuilder(); + + OtlpConfigUtil.configureOtlpExporterBuilder( + DATA_TYPE_TRACES, + config, + builder::setComponentLoader, + builder::setEndpoint, + builder::addHeader, + builder::setCompression, + builder::setTimeout, + builder::setTrustedCertificates, + builder::setClientTls, + builder::setRetryPolicy, + builder::setMemoryMode, + builder::setInternalTelemetryVersion); + builder.setMeterProvider(meterProviderRef::get); + + return builder.build(); + } + throw new ConfigurationException("Unsupported OTLP traces protocol: " + protocol); + } + + @Override + public String getName() { + return "otlp"; + } + + // Visible for testing + OtlpHttpSpanExporterBuilder httpBuilder() { + return OtlpHttpSpanExporter.builder(); + } + + // Visible for testing + OtlpGrpcSpanExporterBuilder grpcBuilder() { + return OtlpGrpcSpanExporter.builder(); + } + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) { + meterProviderRef.set(sdk.getMeterProvider()); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgent.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgent.java new file mode 100644 index 00000000000..d35ddd38622 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgent.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import io.opentelemetry.sdk.common.internal.OtelVersion; +import java.util.function.BiConsumer; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class OtlpUserAgent { + + private static final String userAgent = "OTel-OTLP-Exporter-Java/" + OtelVersion.VERSION; + + /** + * Return an OTLP {@code User-Agent} header value of the form {@code "OTel OTLP Exporter + * Java/{version}"}. + * + * @see OTLP + * Exporter User Agent + */ + public static String getUserAgent() { + return userAgent; + } + + /** + * Call the {@code consumer with} an OTLP {@code User-Agent} header value of the form {@code "OTel + * OTLP Exporter Java/{version}"}. + * + * @see OTLP + * Exporter User Agent + */ + public static void addUserAgentHeader(BiConsumer consumer) { + consumer.accept("User-Agent", userAgent); + } + + private OtlpUserAgent() {} +} diff --git a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/ExportLogsServiceResponse.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/ExportLogsServiceResponse.java similarity index 100% rename from exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/ExportLogsServiceResponse.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/ExportLogsServiceResponse.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporter.java new file mode 100644 index 00000000000..76ed5660096 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporter.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.logs; + +import io.opentelemetry.exporter.internal.otlp.logs.LogReusableDataMarshaler; +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** + * Exports logs using OTLP via gRPC, using OpenTelemetry's protobuf model. + * + * @since 1.27.0 + */ +@ThreadSafe +public final class OtlpGrpcLogRecordExporter implements LogRecordExporter { + + private final GrpcExporterBuilder builder; + private final GrpcExporter delegate; + private final LogReusableDataMarshaler marshaler; + + /** + * Returns a new {@link OtlpGrpcLogRecordExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpGrpcLogRecordExporter} instance. + */ + public static OtlpGrpcLogRecordExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpGrpcLogRecordExporterBuilder builder() { + return new OtlpGrpcLogRecordExporterBuilder(); + } + + OtlpGrpcLogRecordExporter( + GrpcExporterBuilder builder, GrpcExporter delegate, MemoryMode memoryMode) { + this.builder = builder; + this.delegate = delegate; + this.marshaler = new LogReusableDataMarshaler(memoryMode, delegate::export); + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + * + * @since 1.29.0 + */ + public OtlpGrpcLogRecordExporterBuilder toBuilder() { + return new OtlpGrpcLogRecordExporterBuilder(builder.copy(), marshaler.getMemoryMode()); + } + + /** + * Submits all the given logs in a single batch to the OpenTelemetry collector. + * + * @param logs the list of sampled logs to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection logs) { + return marshaler.export(logs); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately + * cancelled. + */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpGrpcLogRecordExporter{", "}"); + joiner.add(builder.toString(false)); + joiner.add("memoryMode=" + marshaler.getMemoryMode()); + return joiner.toString(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporterBuilder.java new file mode 100644 index 00000000000..17760c71590 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporterBuilder.java @@ -0,0 +1,344 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.logs; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Builder for {@link OtlpGrpcLogRecordExporter}. + * + * @since 1.27.0 + */ +public final class OtlpGrpcLogRecordExporterBuilder { + + private static final String GRPC_FULL_METHOD_NAME = + "opentelemetry.proto.collector.logs.v1.LogsService/Export"; + + private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; + private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); + private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; + + // Visible for testing + final GrpcExporterBuilder delegate; + private MemoryMode memoryMode; + + OtlpGrpcLogRecordExporterBuilder(GrpcExporterBuilder delegate, MemoryMode memoryMode) { + this.delegate = delegate; + this.memoryMode = memoryMode; + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeader); + } + + OtlpGrpcLogRecordExporterBuilder() { + this( + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_LOG_EXPORTER, + DEFAULT_TIMEOUT, + DEFAULT_ENDPOINT, + GRPC_FULL_METHOD_NAME), + DEFAULT_MEMORY_MODE); + } + + /** + * Sets the managed channel to use when communicating with the backend. Takes precedence over + * {@link #setEndpoint(String)} if both are called. + * + *

    Note: calling this overrides the spec compliant {@code User-Agent} header. To ensure spec + * compliance, set {@link io.grpc.ManagedChannelBuilder#userAgent(String)} to {@link + * OtlpUserAgent#getUserAgent()} when building the channel. + * + * @param channel the channel to use + * @return this builder's instance + * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the + * methods on this builder, please file an issue to let us know what it is. + */ + @Deprecated + public OtlpGrpcLogRecordExporterBuilder setChannel(ManagedChannel channel) { + delegate.setChannel(channel); + return this; + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, + * defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcLogRecordExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, + * defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcLogRecordExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.36.0 + */ + public OtlpGrpcLogRecordExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.36.0 + */ + public OtlpGrpcLogRecordExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP gRPC request message size in bytes. If unset, defaults to 64 MiB. A value + * of 0 means no limit. + * + * @since 1.67.0 + */ + public OtlpGrpcLogRecordExporterBuilder setMaxRequestMessageSize( + long maxRequestMessageSizeBytes) { + checkArgument( + maxRequestMessageSizeBytes >= 0, "maxRequestMessageSizeBytes must be non-negative"); + delegate.setMaxRequestMessageSize(maxRequestMessageSizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The + * endpoint must start with either http:// or https://. + */ + public OtlpGrpcLogRecordExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpGrpcLogRecordExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpGrpcLogRecordExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpGrpcLogRecordExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + */ + public OtlpGrpcLogRecordExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. Applicable + * only if {@link OtlpGrpcLogRecordExporterBuilder#setChannel(ManagedChannel)} is not used to set + * channel. + * + * @param key header key + * @param value header value + * @return this builder's instance + */ + public OtlpGrpcLogRecordExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeader(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. Applicable only if + * {@link OtlpGrpcLogRecordExporterBuilder#setChannel(ManagedChannel)} is not used to set channel. + * + * @since 1.33.0 + */ + public OtlpGrpcLogRecordExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + * + * @since 1.28.0 + */ + public OtlpGrpcLogRecordExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, uses + * {@link GlobalOpenTelemetry#getMeterProvider()}. + */ + public OtlpGrpcLogRecordExporterBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + setMeterProvider(() -> meterProvider); + return this; + } + + /** + * Sets the {@link MeterProvider} supplier used to collect metrics related to export. If not set, + * uses {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.32.0 + */ + public OtlpGrpcLogRecordExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + requireNonNull(meterProviderSupplier, "meterProviderSupplier"); + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which self-monitoring metrics this exporter + * collects. + * + * @since 1.51.0 + */ + public OtlpGrpcLogRecordExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + requireNonNull(schemaVersion, "schemaVersion"); + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link #DEFAULT_MEMORY_MODE}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + * + * @since 1.39.0 + */ + public OtlpGrpcLogRecordExporterBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + * + * @since 1.48.0 + */ + public OtlpGrpcLogRecordExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpGrpcLogRecordExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + * + * @since 1.49.0 + */ + public OtlpGrpcLogRecordExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions. Omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + public OtlpGrpcLogRecordExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpGrpcLogRecordExporter build() { + return new OtlpGrpcLogRecordExporter(delegate, delegate.build(), memoryMode); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/package-info.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/package-info.java new file mode 100644 index 00000000000..8986518bd46 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/logs/package-info.java @@ -0,0 +1,10 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** OpenTelemetry exporter which sends log data to OpenTelemetry collector via OTLP gRPC. */ +@ParametersAreNonnullByDefault +package io.opentelemetry.exporter.otlp.logs; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/ExportMetricsServiceResponse.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/ExportMetricsServiceResponse.java similarity index 100% rename from exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/ExportMetricsServiceResponse.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/ExportMetricsServiceResponse.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporter.java new file mode 100644 index 00000000000..04c6f2c44d9 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporter.java @@ -0,0 +1,147 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import io.opentelemetry.exporter.internal.otlp.metrics.MetricReusableDataMarshaler; +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** + * Exports metrics using OTLP via gRPC, using OpenTelemetry's protobuf model. + * + * @since 1.14.0 + */ +@ThreadSafe +public final class OtlpGrpcMetricExporter implements MetricExporter { + + private final GrpcExporterBuilder builder; + private final GrpcExporter delegate; + // Visible for testing + final AggregationTemporalitySelector aggregationTemporalitySelector; + // Visible for testing + final DefaultAggregationSelector defaultAggregationSelector; + private final MetricReusableDataMarshaler marshaler; + + /** + * Returns a new {@link OtlpGrpcMetricExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpGrpcMetricExporter} instance. + */ + public static OtlpGrpcMetricExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpGrpcMetricExporterBuilder builder() { + return new OtlpGrpcMetricExporterBuilder(); + } + + OtlpGrpcMetricExporter( + GrpcExporterBuilder builder, + GrpcExporter delegate, + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector, + MemoryMode memoryMode) { + this.builder = builder; + this.delegate = delegate; + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + this.defaultAggregationSelector = defaultAggregationSelector; + this.marshaler = new MetricReusableDataMarshaler(memoryMode, delegate::export); + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + * + * @since 1.29.0 + */ + public OtlpGrpcMetricExporterBuilder toBuilder() { + return new OtlpGrpcMetricExporterBuilder( + builder.copy(), + aggregationTemporalitySelector, + defaultAggregationSelector, + marshaler.getMemoryMode()); + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); + } + + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return defaultAggregationSelector.getDefaultAggregation(instrumentType); + } + + @Override + public MemoryMode getMemoryMode() { + return marshaler.getMemoryMode(); + } + + /** + * Submits all the given metrics in a single batch to the OpenTelemetry collector. + * + * @param metrics the list of Metrics to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection metrics) { + return marshaler.export(metrics); + } + + /** + * The OTLP exporter does not batch metrics, so this method will immediately return with success. + * + * @return always Success + */ + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately + * cancelled. The channel is forcefully closed after a timeout. + */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpGrpcMetricExporter{", "}"); + joiner.add(builder.toString(false)); + joiner.add( + "aggregationTemporalitySelector=" + + AggregationTemporalitySelector.asString(aggregationTemporalitySelector)); + joiner.add( + "defaultAggregationSelector=" + + DefaultAggregationSelector.asString(defaultAggregationSelector)); + joiner.add("memoryMode=" + marshaler.getMemoryMode()); + return joiner.toString(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilder.java new file mode 100644 index 00000000000..6570305118c --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilder.java @@ -0,0 +1,406 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.net.URI; +import java.time.Duration; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Builder utility for this exporter. + * + * @since 1.14.0 + */ +public final class OtlpGrpcMetricExporterBuilder { + + private static final String GRPC_FULL_METHOD_NAME = + "opentelemetry.proto.collector.metrics.v1.MetricsService/Export"; + + private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; + private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); + private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); + private static final AggregationTemporalitySelector DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = + AggregationTemporalitySelector.alwaysCumulative(); + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; + + // Visible for testing + final GrpcExporterBuilder delegate; + + private AggregationTemporalitySelector aggregationTemporalitySelector; + private DefaultAggregationSelector defaultAggregationSelector; + private MemoryMode memoryMode; + + OtlpGrpcMetricExporterBuilder( + GrpcExporterBuilder delegate, + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector, + MemoryMode memoryMode) { + this.delegate = delegate; + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + this.defaultAggregationSelector = defaultAggregationSelector; + this.memoryMode = memoryMode; + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeader); + } + + OtlpGrpcMetricExporterBuilder() { + this( + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_METRIC_EXPORTER, + DEFAULT_TIMEOUT, + DEFAULT_ENDPOINT, + GRPC_FULL_METHOD_NAME), + DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR, + DefaultAggregationSelector.getDefault(), + DEFAULT_MEMORY_MODE); + } + + /** + * Sets the managed channel to use when communicating with the backend. Takes precedence over + * {@link #setEndpoint(String)} if both are called. + * + *

    Note: calling this overrides the spec compliant {@code User-Agent} header. To ensure spec + * compliance, set {@link io.grpc.ManagedChannelBuilder#userAgent(String)} to {@link + * OtlpUserAgent#getUserAgent()} when building the channel. + * + * @param channel the channel to use + * @return this builder's instance + * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the + * methods on this builder, please file an issue to let us know what it is. + */ + @Deprecated + public OtlpGrpcMetricExporterBuilder setChannel(ManagedChannel channel) { + delegate.setChannel(channel); + return this; + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of metrics. If + * unset, defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcMetricExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of metrics. If + * unset, defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcMetricExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.36.0 + */ + public OtlpGrpcMetricExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.36.0 + */ + public OtlpGrpcMetricExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP gRPC request message size in bytes. If unset, defaults to 64 MiB. A value + * of 0 means no limit. + * + * @since 1.67.0 + */ + public OtlpGrpcMetricExporterBuilder setMaxRequestMessageSize(long maxRequestMessageSizeBytes) { + checkArgument( + maxRequestMessageSizeBytes >= 0, "maxRequestMessageSizeBytes must be non-negative"); + delegate.setMaxRequestMessageSize(maxRequestMessageSizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The + * endpoint must start with either http:// or https://. + */ + public OtlpGrpcMetricExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpGrpcMetricExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpGrpcMetricExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpGrpcMetricExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + * + * @since 1.26.0 + */ + public OtlpGrpcMetricExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. Applicable + * only if {@link OtlpGrpcMetricExporterBuilder#setChannel(ManagedChannel)} is not used to set + * channel. + * + * @param key header key + * @param value header value + * @return this builder's instance + */ + public OtlpGrpcMetricExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeader(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. Applicable only if + * {@link OtlpGrpcMetricExporterBuilder#setChannel(ManagedChannel)} is not used to set channel. + * + * @since 1.33.0 + */ + public OtlpGrpcMetricExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Set the {@link AggregationTemporalitySelector} used for {@link + * MetricExporter#getAggregationTemporality(InstrumentType)}. + * + *

    If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}. + * + *

    {@link AggregationTemporalitySelector#deltaPreferred()} is a common configuration for delta + * backends. + */ + public OtlpGrpcMetricExporterBuilder setAggregationTemporalitySelector( + AggregationTemporalitySelector aggregationTemporalitySelector) { + requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector"); + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + return this; + } + + /** + * Set the {@link DefaultAggregationSelector} used for {@link + * MetricExporter#getDefaultAggregation(InstrumentType)}. + * + *

    If unset, defaults to {@link DefaultAggregationSelector#getDefault()}. + * + * @since 1.16.0 + */ + public OtlpGrpcMetricExporterBuilder setDefaultAggregationSelector( + DefaultAggregationSelector defaultAggregationSelector) { + requireNonNull(defaultAggregationSelector, "defaultAggregationSelector"); + this.defaultAggregationSelector = defaultAggregationSelector; + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + * + * @since 1.28.0 + */ + public OtlpGrpcMetricExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which self-monitoring metrics this exporter + * collects. + * + * @since 1.51.0 + */ + public OtlpGrpcMetricExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + requireNonNull(schemaVersion, "schemaVersion"); + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, uses + * {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.50.0 + */ + public OtlpGrpcMetricExporterBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + delegate.setMeterProvider(() -> meterProvider); + return this; + } + + /** + * Sets the {@link MeterProvider} supplier to use to collect metrics related to export. If not + * set, uses {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.50.0 + */ + public OtlpGrpcMetricExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + requireNonNull(meterProviderSupplier, "meterProvider"); + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link #DEFAULT_MEMORY_MODE}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. Additionally, the value is used for {@link MetricExporter#getMemoryMode()}, + * which sends a signal to the metrics SDK to reuse memory when possible. This is safe and + * desirable for most use cases, but should be used with caution of wrapping and delegating to the + * exporter. It is not safe for the wrapping exporter to hold onto references to {@link + * MetricData} batches since the same data structures will be reused in subsequent calls to {@link + * MetricExporter#export(Collection)}. + * + * @since 1.39.0 + */ + public OtlpGrpcMetricExporterBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + * + * @since 1.48.0 + */ + public OtlpGrpcMetricExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpGrpcMetricExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + * + * @since 1.49.0 + */ + public OtlpGrpcMetricExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions. Omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + public OtlpGrpcMetricExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpGrpcMetricExporter build() { + return new OtlpGrpcMetricExporter( + delegate, + delegate.build(), + aggregationTemporalitySelector, + defaultAggregationSelector, + memoryMode); + } +} diff --git a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/package-info.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/package-info.java similarity index 100% rename from exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/package-info.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/metrics/package-info.java diff --git a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/ExportTraceServiceResponse.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/ExportTraceServiceResponse.java similarity index 100% rename from exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/ExportTraceServiceResponse.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/ExportTraceServiceResponse.java diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporter.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporter.java new file mode 100644 index 00000000000..f33376e7b62 --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporter.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.trace; + +import io.opentelemetry.exporter.internal.otlp.traces.SpanReusableDataMarshaler; +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** Exports spans using OTLP via gRPC, using OpenTelemetry's protobuf model. */ +@ThreadSafe +public final class OtlpGrpcSpanExporter implements SpanExporter { + + private final GrpcExporterBuilder builder; + private final GrpcExporter delegate; + private final SpanReusableDataMarshaler marshaler; + + /** + * Returns a new {@link OtlpGrpcSpanExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpGrpcSpanExporter} instance. + */ + public static OtlpGrpcSpanExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpGrpcSpanExporterBuilder builder() { + return new OtlpGrpcSpanExporterBuilder(); + } + + OtlpGrpcSpanExporter(GrpcExporterBuilder builder, GrpcExporter delegate, MemoryMode memoryMode) { + this.builder = builder; + this.delegate = delegate; + this.marshaler = new SpanReusableDataMarshaler(memoryMode, delegate::export); + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + * + * @since 1.29.0 + */ + public OtlpGrpcSpanExporterBuilder toBuilder() { + return new OtlpGrpcSpanExporterBuilder(builder.copy(), marshaler.getMemoryMode()); + } + + /** + * Submits all the given spans in a single batch to the OpenTelemetry collector. + * + * @param spans the list of sampled Spans to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection spans) { + return marshaler.export(spans); + } + + /** + * The OTLP exporter does not batch spans, so this method will immediately return with success. + * + * @return always Success + */ + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately + * cancelled. + */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpGrpcSpanExporter{", "}"); + joiner.add(builder.toString(false)); + joiner.add("memoryMode=" + marshaler.getMemoryMode()); + return joiner.toString(); + } +} diff --git a/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterBuilder.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterBuilder.java new file mode 100644 index 00000000000..4fb4841573e --- /dev/null +++ b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterBuilder.java @@ -0,0 +1,341 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.trace; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** Builder utility for this exporter. */ +public final class OtlpGrpcSpanExporterBuilder { + + // Visible for testing + static final String GRPC_FULL_METHOD_NAME = + "opentelemetry.proto.collector.trace.v1.TraceService/Export"; + + private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; + private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); + private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; + + // Visible for testing + final GrpcExporterBuilder delegate; + private MemoryMode memoryMode; + + OtlpGrpcSpanExporterBuilder(GrpcExporterBuilder delegate, MemoryMode memoryMode) { + this.delegate = delegate; + this.memoryMode = memoryMode; + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeader); + } + + OtlpGrpcSpanExporterBuilder() { + this( + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER, + DEFAULT_TIMEOUT, + DEFAULT_ENDPOINT, + GRPC_FULL_METHOD_NAME), + DEFAULT_MEMORY_MODE); + } + + /** + * Sets the managed channel to use when communicating with the backend. Takes precedence over + * {@link #setEndpoint(String)} if both are called. + * + *

    Note: calling this overrides the spec compliant {@code User-Agent} header. To ensure spec + * compliance, set {@link io.grpc.ManagedChannelBuilder#userAgent(String)} to {@link + * OtlpUserAgent#getUserAgent()} when building the channel. + * + * @param channel the channel to use + * @return this builder's instance + * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the + * methods on this builder, please file an issue to let us know what it is. + */ + @Deprecated + public OtlpGrpcSpanExporterBuilder setChannel(ManagedChannel channel) { + delegate.setChannel(channel); + return this; + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of spans. If + * unset, defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcSpanExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of spans. If + * unset, defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcSpanExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.36.0 + */ + public OtlpGrpcSpanExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + * + * @since 1.36.0 + */ + public OtlpGrpcSpanExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP gRPC request message size in bytes. If unset, defaults to 64 MiB. A value + * of 0 means no limit. + * + * @since 1.67.0 + */ + public OtlpGrpcSpanExporterBuilder setMaxRequestMessageSize(long maxRequestMessageSizeBytes) { + checkArgument( + maxRequestMessageSizeBytes >= 0, "maxRequestMessageSizeBytes must be non-negative"); + delegate.setMaxRequestMessageSize(maxRequestMessageSizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The + * endpoint must start with either http:// or https://. + */ + public OtlpGrpcSpanExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpGrpcSpanExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpGrpcSpanExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpGrpcSpanExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + * + * @since 1.26.0 + */ + public OtlpGrpcSpanExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. Applicable + * only if {@link OtlpGrpcSpanExporterBuilder#setChannel(ManagedChannel)} is not used to set + * channel. + * + * @param key header key + * @param value header value + * @return this builder's instance + */ + public OtlpGrpcSpanExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeader(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. Applicable only if + * {@link OtlpGrpcSpanExporterBuilder#setChannel(ManagedChannel)} is not used to set channel. + * + * @since 1.33.0 + */ + public OtlpGrpcSpanExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + * + * @since 1.28.0 + */ + public OtlpGrpcSpanExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, uses + * {@link GlobalOpenTelemetry#getMeterProvider()}. + */ + public OtlpGrpcSpanExporterBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + setMeterProvider(() -> meterProvider); + return this; + } + + /** + * Sets the {@link MeterProvider} supplier used to collect metrics related to export. If not set, + * uses {@link GlobalOpenTelemetry#getMeterProvider()}. + * + * @since 1.32.0 + */ + public OtlpGrpcSpanExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + requireNonNull(meterProviderSupplier, "meterProviderSupplier"); + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which self-monitoring metrics this exporter + * collects. + * + * @since 1.51.0 + */ + public OtlpGrpcSpanExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + requireNonNull(schemaVersion, "schemaVersion"); + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + /** + * Set the {@link MemoryMode}. If unset, defaults to {@link #DEFAULT_MEMORY_MODE}. + * + *

    When memory mode is {@link MemoryMode#REUSABLE_DATA}, serialization is optimized to reduce + * memory allocation. + * + * @since 1.39.0 + */ + public OtlpGrpcSpanExporterBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + * + * @since 1.48.0 + */ + public OtlpGrpcSpanExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpGrpcSpanExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + * + * @since 1.49.0 + */ + public OtlpGrpcSpanExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions. Omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + public OtlpGrpcSpanExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpGrpcSpanExporter build() { + return new OtlpGrpcSpanExporter(delegate, delegate.build(), memoryMode); + } +} diff --git a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/package-info.java b/exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/package-info.java similarity index 100% rename from exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/package-info.java rename to exporters/otlp/all/src/main/java/io/opentelemetry/exporter/otlp/trace/package-info.java diff --git a/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..1eb742e89c5 --- /dev/null +++ b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,7 @@ +io.opentelemetry.exporter.otlp.internal.OtlpGrpcSpanExporterComponentProvider +io.opentelemetry.exporter.otlp.internal.OtlpGrpcMetricExporterComponentProvider +io.opentelemetry.exporter.otlp.internal.OtlpGrpcLogRecordExporterComponentProvider +io.opentelemetry.exporter.otlp.internal.OtlpHttpSpanExporterComponentProvider +io.opentelemetry.exporter.otlp.internal.OtlpHttpMetricExporterComponentProvider +io.opentelemetry.exporter.otlp.internal.OtlpHttpLogRecordExporterComponentProvider + diff --git a/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider new file mode 100644 index 00000000000..d789ed482c7 --- /dev/null +++ b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.otlp.internal.OtlpLogRecordExporterProvider diff --git a/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider new file mode 100644 index 00000000000..93d8d0ee99a --- /dev/null +++ b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.otlp.internal.OtlpMetricExporterProvider diff --git a/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider new file mode 100644 index 00000000000..29112b59867 --- /dev/null +++ b/exporters/otlp/all/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.otlp.internal.OtlpSpanExporterProvider diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilderTest.java new file mode 100644 index 00000000000..4e9e4615898 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterBuilderTest.java @@ -0,0 +1,240 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.metrics; + +import static io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData.createDoubleGauge; +import static java.util.Collections.singleton; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.linecorp.armeria.common.HttpResponse; +import com.linecorp.armeria.common.HttpStatus; +import com.linecorp.armeria.server.ServerBuilder; +import com.linecorp.armeria.testing.junit5.server.ServerExtension; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongCounterBuilder; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.Mockito; + +class OtlpHttpMetricExporterBuilderTest { + + private static final Collection DATA_SET = + singleton( + createDoubleGauge( + Resource.empty(), + InstrumentationScopeInfo.create("test"), + "test", + "test", + "test", + ImmutableGaugeData.empty())); + + @RegisterExtension + private static final ServerExtension server = + new ServerExtension() { + @Override + protected void configure(ServerBuilder sb) { + sb.service("/v1/metrics", (ctx, req) -> HttpResponse.of(HttpStatus.OK)); + sb.http(0); + } + }; + + private final SdkMeterProvider meterProvider = mock(SdkMeterProvider.class); + private final Meter meter = mock(Meter.class); + private final LongCounterBuilder counterBuilder = mock(LongCounterBuilder.class); + private final LongCounter counter = mock(LongCounter.class); + + @BeforeEach + void setup() { + GlobalOpenTelemetry.resetForTest(); + } + + @AfterEach + void cleanup() { + GlobalOpenTelemetry.resetForTest(); + } + + @Test + void setMeterProvider_null() { + OtlpHttpMetricExporterBuilder builder = OtlpHttpMetricExporter.builder(); + assertThrows( + NullPointerException.class, + () -> builder.setMeterProvider((MeterProvider) null), + "MeterProvider must not be null"); + assertThrows( + NullPointerException.class, + () -> builder.setMeterProvider((Supplier) null), + "MeterProvider must not be null"); + } + + @Test + void setMeterProvider() { + when(meterProvider.get(any())).thenReturn(meter); + when(meter.counterBuilder(any())).thenReturn(counterBuilder); + when(counterBuilder.build()).thenReturn(counter); + + try (OtlpHttpMetricExporter exporter = + OtlpHttpMetricExporter.builder() + .setMeterProvider(meterProvider) + .setEndpoint("http://localhost:" + server.httpPort() + "/v1/metrics") + .build()) { + verifyNoInteractions(meterProvider, meter, counterBuilder, counter); + + // Collection before MeterProvider is initialized. + when(meterProvider.get(any())).thenReturn(MeterProvider.noop().get("test")); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verifyNoInteractions(meter, counterBuilder, counter); + + // Collection after MeterProvider is initialized. + when(meterProvider.get(any())).thenReturn(meter); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verify(meter).counterBuilder("otlp.exporter.seen"); + verify(meter).counterBuilder("otlp.exporter.exported"); + verify(counter, times(2)).add(eq(1L), any()); + verifyNoMoreInteractions(meter, counter); + } + } + + @Test + void setMeterProvider_supplier() { + when(meterProvider.get(any())).thenReturn(meter); + when(meter.counterBuilder(any())).thenReturn(counterBuilder); + when(counterBuilder.build()).thenReturn(counter); + + @SuppressWarnings("unchecked") + Supplier provider = mock(Supplier.class); + try (OtlpHttpMetricExporter exporter = + OtlpHttpMetricExporter.builder() + .setMeterProvider(provider) + .setEndpoint("http://localhost:" + server.httpPort() + "/v1/metrics") + .build()) { + verifyNoInteractions(provider, meterProvider, meter, counterBuilder, counter); + + // Collection before MeterProvider is initialized. + when(provider.get()).thenReturn(MeterProvider.noop()); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verifyNoInteractions(meterProvider, meter, counterBuilder, counter); + + // Collection after MeterProvider is initialized. + when(provider.get()).thenReturn(meterProvider); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verify(meter).counterBuilder("otlp.exporter.seen"); + verify(meter).counterBuilder("otlp.exporter.exported"); + verify(counter, times(2)).add(eq(1L), any()); + verifyNoMoreInteractions(meter, counter); + } + } + + @Test + void setMeterProvider_defaultGlobal() { + GlobalOpenTelemetry.set( + new OpenTelemetry() { + @Override + public MeterProvider getMeterProvider() { + return meterProvider; + } + + @Override + public TracerProvider getTracerProvider() { + return TracerProvider.noop(); + } + + @Override + public ContextPropagators getPropagators() { + return ContextPropagators.noop(); + } + }); + when(meterProvider.get(any())).thenReturn(meter); + when(meter.counterBuilder(any())).thenReturn(counterBuilder); + when(counterBuilder.build()).thenReturn(counter); + + try (OtlpHttpMetricExporter exporter = + OtlpHttpMetricExporter.builder() + .setEndpoint("http://localhost:" + server.httpPort() + "/v1/metrics") + .build()) { + verifyNoInteractions(meterProvider, meter, counterBuilder, counter); + + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verify(meter).counterBuilder("otlp.exporter.seen"); + verify(meter).counterBuilder("otlp.exporter.exported"); + verify(counter, times(2)).add(eq(1L), any()); + verifyNoMoreInteractions(meter, counter); + } + } + + @Test + void setMeterProvider_noMocks() { + AtomicReference meterProviderAtomicReference = new AtomicReference<>(); + SdkMeterProviderBuilder builder = + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.create( + OtlpHttpMetricExporter.builder() + .setMeterProvider(meterProviderAtomicReference::get) + .build())); + meterProviderAtomicReference.set(builder.build()); + meterProviderAtomicReference.get().close(); + } + + @Test + void verifyToBuilderPreservesSettings() { + AggregationTemporalitySelector temporalitySelector = + Mockito.mock(AggregationTemporalitySelector.class); + DefaultAggregationSelector defaultAggregationSelector = + Mockito.mock(DefaultAggregationSelector.class); + + OtlpHttpMetricExporter original = + OtlpHttpMetricExporter.builder() + .setMemoryMode(MemoryMode.IMMUTABLE_DATA) + .setAggregationTemporalitySelector(temporalitySelector) + .setDefaultAggregationSelector(defaultAggregationSelector) + .build(); + + OtlpHttpMetricExporter copy = original.toBuilder().build(); + + assertThat(copy.getMemoryMode()).isEqualTo(MemoryMode.IMMUTABLE_DATA); + assertThat(copy.aggregationTemporalitySelector).isSameAs(temporalitySelector); + assertThat(copy.defaultAggregationSelector).isSameAs(defaultAggregationSelector); + + original.close(); + copy.close(); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/CompressorUtilTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/CompressorUtilTest.java new file mode 100644 index 00000000000..c7164ef26be --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/CompressorUtilTest.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.common.ComponentLoader; +import java.net.URL; +import java.net.URLClassLoader; +import org.junit.jupiter.api.Test; + +class CompressorUtilTest { + + private final ComponentLoader componentLoader = + ComponentLoader.forClassLoader(CompressorUtilTest.class.getClassLoader()); + + @Test + void validateAndResolveCompressor_none() { + assertThat(CompressorUtil.validateAndResolveCompressor("none")).isNull(); + } + + @Test + void validateAndResolveCompressor_gzip() { + assertThat(CompressorUtil.validateAndResolveCompressor("gzip")) + .isInstanceOf(GzipCompressor.class); + } + + @Test + void validateAndResolveCompressor_invalid() { + assertThatThrownBy(() -> CompressorUtil.validateAndResolveCompressor("invalid")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported compressionMethod"); + } + + @Test + void validateAndResolveCompressor_withClassLoader_none() { + assertThat(CompressorUtil.validateAndResolveCompressor("none", componentLoader)).isNull(); + } + + @Test + void validateAndResolveCompressor_withClassLoader_gzip() { + assertThat(CompressorUtil.validateAndResolveCompressor("gzip", componentLoader)) + .isInstanceOf(GzipCompressor.class); + } + + @Test + void validateAndResolveCompressor_withClassLoader_invalid() { + assertThatThrownBy( + () -> CompressorUtil.validateAndResolveCompressor("invalid", componentLoader)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported compressionMethod"); + } + + @Test + void validateAndResolveCompressor_emptyClassLoader() { + // Create a class loader that cannot load Compressor services + ComponentLoader emptyComponentLoader = + ComponentLoader.forClassLoader(new URLClassLoader(new URL[0], null)); + + // Gzip should still work because it's hardcoded + assertThat(CompressorUtil.validateAndResolveCompressor("gzip", emptyComponentLoader)) + .isInstanceOf(GzipCompressor.class); + + // None should still work because it doesn't require loading services + assertThat(CompressorUtil.validateAndResolveCompressor("none", emptyComponentLoader)).isNull(); + + // Any SPI-based compressor should not be available + assertThatThrownBy( + () -> CompressorUtil.validateAndResolveCompressor("base64", emptyComponentLoader)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported compressionMethod"); + } + + @Test + void validateAndResolveCompressor_delegatesCorrectly() { + // Test that single-parameter method delegates to two-parameter method + assertThat(CompressorUtil.validateAndResolveCompressor("gzip")) + .isEqualTo(CompressorUtil.validateAndResolveCompressor("gzip", componentLoader)); + + assertThat(CompressorUtil.validateAndResolveCompressor("none")) + .isEqualTo(CompressorUtil.validateAndResolveCompressor("none", componentLoader)); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilderTest.java new file mode 100644 index 00000000000..95f0f1c83e1 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterBuilderTest.java @@ -0,0 +1,104 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.net.URL; +import java.net.URLClassLoader; +import java.time.Duration; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class GrpcExporterBuilderTest { + + private GrpcExporterBuilder builder; + + @BeforeEach + void setUp() { + builder = + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER, + Duration.ZERO, + URI.create("http://localhost:4317"), + "service/method"); + } + + @Test + void compressionDefault() { + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionNone() { + builder.setCompression((Compressor) null); + + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionGzip() { + builder.setCompression(new GzipCompressor()); + + assertThat(builder).extracting("compressor").isInstanceOf(GzipCompressor.class); + } + + @Test + void compressionEnabledAndDisabled() { + builder.setCompression(new GzipCompressor()).setCompression((Compressor) null); + + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionString_none() { + builder.setCompression("none"); + + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionString_gzip() { + builder.setCompression("gzip"); + + assertThat(builder).extracting("compressor").isInstanceOf(GzipCompressor.class); + } + + @Test + void compressionString_invalid() { + assertThatThrownBy(() -> builder.setCompression("invalid-compression")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported compressionMethod"); + } + + @Test + void compressionString_usesServiceClassLoader() { + // Create a class loader that cannot load Compressor services + ComponentLoader emptyComponentLoader = + ComponentLoader.forClassLoader(new URLClassLoader(new URL[0], null)); + builder.setComponentLoader(emptyComponentLoader); + + // This should still work because gzip compressor is hardcoded + builder.setCompression("gzip"); + assertThat(builder).extracting("compressor").isInstanceOf(GzipCompressor.class); + + // This should still work because "none" doesn't require loading services + builder.setCompression("none"); + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void maxRequestMessageSize() { + builder.setMaxRequestMessageSize(1234); + + assertThat(builder).extracting("maxRequestMessageSize").isEqualTo(1234L); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java new file mode 100644 index 00000000000..60bd32ee181 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java @@ -0,0 +1,256 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.sdk.common.export.GrpcStatusCode.UNAVAILABLE; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.Mockito; + +class GrpcExporterTest { + + @ParameterizedTest + @EnumSource + @SuppressLogger(GrpcExporter.class) + void testInternalTelemetry(StandardComponentId.ExporterType exporterType) { + String signalMetricPrefix; + String expectedUnit; + switch (exporterType.signal()) { + case SPAN: + signalMetricPrefix = "otel.sdk.exporter.span."; + expectedUnit = "{span}"; + break; + case LOG: + signalMetricPrefix = "otel.sdk.exporter.log."; + expectedUnit = "{log_record}"; + break; + case METRIC: + signalMetricPrefix = "otel.sdk.exporter.metric_data_point."; + expectedUnit = "{data_point}"; + break; + case PROFILE: + return; // Not yet supported + default: + throw new IllegalStateException(); + } + + InMemoryMetricReader inMemoryMetrics = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(inMemoryMetrics).build()) { + + StandardComponentId id = ComponentId.generateLazy(exporterType); + + Attributes expectedAttributes = + Attributes.builder() + .put(SemConvConstants.OTEL_COMPONENT_TYPE, id.getTypeName()) + .put(SemConvConstants.OTEL_COMPONENT_NAME, id.getComponentName()) + .put(SemConvConstants.SERVER_ADDRESS, "testing") + .put(SemConvConstants.SERVER_PORT, 1234) + .build(); + + GrpcSender mockSender = Mockito.mock(GrpcSender.class); + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter emptyMessageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + }; + Mockito.when(mockMarshaller.toBinaryMessageWriter()).thenReturn(emptyMessageWriter); + + GrpcExporter exporter = + new GrpcExporter( + mockSender, + InternalTelemetryVersion.LATEST, + id, + () -> meterProvider, + URI.create("http://testing:1234"), + GrpcExporterBuilder.DEFAULT_MAX_REQUEST_MESSAGE_SIZE); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(1) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.isNotMonotonic() + .hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42)))); + + onResponse.accept(grpcResponse(GrpcStatusCode.OK)); + + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + + exporter.export(mockMarshaller, 42); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + onResponse.accept(grpcResponse(UNAVAILABLE)); + + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + exporter.export(mockMarshaller, 15); + + doAnswer( + invoc -> { + Consumer onError = invoc.getArgument(2); + onError.accept(new IOException("Computer says no")); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + exporter.export(mockMarshaller, 7); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(3) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName(signalMetricPrefix + "exported") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.ERROR_TYPE, + "" + UNAVAILABLE.getValue()) + .build()) + .hasValue(15), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasValue(7)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasUnit("s") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.RPC_STATUS_CODE, + GrpcStatusCode.OK.name()) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put( + SemConvConstants.ERROR_TYPE, + "" + UNAVAILABLE.getValue()) + .put(SemConvConstants.RPC_STATUS_CODE, UNAVAILABLE.name()) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasBucketCounts(1)))); + } + } + + @Test + @SuppressLogger(GrpcExporter.class) + void export_requestMessageTooLargeFailsBeforeSend() { + GrpcSender mockSender = Mockito.mock(GrpcSender.class); + GrpcExporter exporter = + new GrpcExporter( + mockSender, + InternalTelemetryVersion.LATEST, + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER), + MeterProvider::noop, + URI.create("http://testing:1234"), + 1); + + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + Mockito.when(mockMarshaller.getBinarySerializedSize()).thenReturn(2); + + CompletableResultCode result = exporter.export(mockMarshaller, 1); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .hasMessageContaining( + "Failed to export spans. Request message size 2 exceeded limit of 1 bytes"); + verifyNoInteractions(mockSender); + } + + private static GrpcResponse grpcResponse(GrpcStatusCode statusCode) { + return new GrpcResponse() { + @Override + public GrpcStatusCode getStatusCode() { + return statusCode; + } + + @Override + @Nullable + public String getStatusDescription() { + return null; + } + + @Override + public byte[] getResponseMessage() { + return new byte[0]; + } + }; + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterUtilTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterUtilTest.java new file mode 100644 index 00000000000..466d88c0b4a --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterUtilTest.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.Any; +import com.google.protobuf.ByteString; +import com.google.rpc.Status; +import java.io.IOException; +import org.junit.jupiter.api.Test; + +class GrpcExporterUtilTest { + + @Test + void parseMessage() throws Exception { + assertThat( + GrpcExporterUtil.getStatusMessage( + Status.newBuilder().setMessage("test").build().toByteArray())) + .isEqualTo("test"); + assertThat( + GrpcExporterUtil.getStatusMessage( + Status.newBuilder().setCode(2).setMessage("test2").build().toByteArray())) + .isEqualTo("test2"); + assertThat( + GrpcExporterUtil.getStatusMessage( + Status.newBuilder() + .setCode(2) + .setMessage("test3") + .addDetails(Any.newBuilder().setValue(ByteString.copyFromUtf8("any")).build()) + .build() + .toByteArray())) + .isEqualTo("test3"); + assertThat( + GrpcExporterUtil.getStatusMessage( + Status.newBuilder() + .setCode(2) + .addDetails(Any.newBuilder().setValue(ByteString.copyFromUtf8("any")).build()) + .build() + .toByteArray())) + .isEmpty(); + assertThat(GrpcExporterUtil.getStatusMessage(Status.getDefaultInstance().toByteArray())) + .isEmpty(); + assertThatThrownBy(() -> GrpcExporterUtil.getStatusMessage(new byte[] {0, 1, 3, 0})) + .isInstanceOf(IOException.class); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilderTest.java new file mode 100644 index 00000000000..8e016ed5aa1 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterBuilderTest.java @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URL; +import java.net.URLClassLoader; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class HttpExporterBuilderTest { + + private HttpExporterBuilder builder; + + @BeforeEach + void setUp() { + builder = + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER, "http://localhost:4318"); + } + + @Test + void compressionDefault() { + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionNone() { + builder.setCompression((Compressor) null); + + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionGzip() { + builder.setCompression(new GzipCompressor()); + + assertThat(builder).extracting("compressor").isInstanceOf(GzipCompressor.class); + } + + @Test + void compressionEnabledAndDisabled() { + builder.setCompression(new GzipCompressor()).setCompression((Compressor) null); + + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionString_none() { + builder.setCompression("none"); + + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void compressionString_gzip() { + builder.setCompression("gzip"); + + assertThat(builder).extracting("compressor").isInstanceOf(GzipCompressor.class); + } + + @Test + void compressionString_invalid() { + assertThatThrownBy(() -> builder.setCompression("invalid-compression")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unsupported compressionMethod"); + } + + @Test + void compressionString_usesServiceClassLoader() { + // Create a class loader that cannot load Compressor services + ComponentLoader emptyComponentLoader = + ComponentLoader.forClassLoader(new URLClassLoader(new URL[0], null)); + builder.setComponentLoader(emptyComponentLoader); + + // This should still work because gzip compressor is hardcoded + builder.setCompression("gzip"); + assertThat(builder).extracting("compressor").isInstanceOf(GzipCompressor.class); + + // This should still work because "none" doesn't require loading services + builder.setCompression("none"); + assertThat(builder).extracting("compressor").isNull(); + } + + @Test + void maxRequestBodySize() { + builder.setMaxRequestBodySize(1234); + + assertThat(builder).extracting("maxRequestBodySize").isEqualTo(1234L); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java new file mode 100644 index 00000000000..3e8fcf31dac --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java @@ -0,0 +1,446 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.HttpResponse; +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.mockito.Mockito; + +class HttpExporterTest { + + @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(HttpExporter.class); + + @ParameterizedTest + @EnumSource + @SuppressLogger(HttpExporter.class) + void testInternalTelemetry(StandardComponentId.ExporterType exporterType) { + String signalMetricPrefix; + String expectedUnit; + switch (exporterType.signal()) { + case SPAN: + signalMetricPrefix = "otel.sdk.exporter.span."; + expectedUnit = "{span}"; + break; + case LOG: + signalMetricPrefix = "otel.sdk.exporter.log."; + expectedUnit = "{log_record}"; + break; + case METRIC: + signalMetricPrefix = "otel.sdk.exporter.metric_data_point."; + expectedUnit = "{data_point}"; + break; + case PROFILE: + return; // Not yet supported + default: + throw new IllegalStateException(); + } + + InMemoryMetricReader inMemoryMetrics = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(inMemoryMetrics).build()) { + + StandardComponentId id = ComponentId.generateLazy(exporterType); + + Attributes expectedAttributes = + Attributes.builder() + .put(SemConvConstants.OTEL_COMPONENT_TYPE, id.getTypeName()) + .put(SemConvConstants.OTEL_COMPONENT_NAME, id.getComponentName()) + .put(SemConvConstants.SERVER_ADDRESS, "testing") + .put(SemConvConstants.SERVER_PORT, 1234) + .build(); + + HttpSender mockSender = Mockito.mock(HttpSender.class); + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter emptyMessageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + }; + Mockito.when(mockMarshaller.toBinaryMessageWriter()).thenReturn(emptyMessageWriter); + Mockito.when(mockMarshaller.toJsonMessageWriter()).thenReturn(emptyMessageWriter); + + HttpExporter exporter = + new HttpExporter( + id, + mockSender, + () -> meterProvider, + InternalTelemetryVersion.LATEST, + URI.create("http://testing:1234"), + false, + HttpExporterBuilder.DEFAULT_MAX_REQUEST_BODY_SIZE); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(1) + .anySatisfy(metric -> + assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.isNotMonotonic() + .hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42)))); + + onResponse.accept(new FakeHttpResponse(200, "Ok")); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + + exporter.export(mockMarshaller, 42); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + onResponse.accept(new FakeHttpResponse(404, "Not Found")); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + exporter.export(mockMarshaller, 15); + + doAnswer( + invoc -> { + Consumer onError = invoc.getArgument(2); + onError.accept(new IOException("Computer says no")); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + exporter.export(mockMarshaller, 7); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(3) + .anySatisfy(metric -> + assertThat(metric) + .hasName(signalMetricPrefix + "inflight") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(0)))) + .anySatisfy(metric -> + assertThat(metric) + .hasName(signalMetricPrefix + "exported") + .hasUnit(expectedUnit) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> pa.hasAttributes(expectedAttributes).hasValue(42), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "404") + .build()) + .hasValue(15), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasValue(7)))) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasUnit("s") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying( + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.HTTP_RESPONSE_STATUS_CODE, 200) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "404") + .put(SemConvConstants.HTTP_RESPONSE_STATUS_CODE, 404) + .build()) + .hasBucketCounts(1), + pa -> + pa.hasAttributes( + expectedAttributes.toBuilder() + .put(SemConvConstants.ERROR_TYPE, "java.io.IOException") + .build()) + .hasBucketCounts(1)))); + } + } + + @Test + @SuppressLogger(HttpExporter.class) + void export_httpJsonErrorBodyUsesBodyTextWithoutGrpcParseWarning() { + HttpSender mockSender = Mockito.mock(HttpSender.class); + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter emptyMessageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + }; + Mockito.when(mockMarshaller.toBinaryMessageWriter()).thenReturn(emptyMessageWriter); + + HttpExporter exporter = + new HttpExporter( + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER), + mockSender, + MeterProvider::noop, + InternalTelemetryVersion.LATEST, + URI.create("http://testing:1234"), + false, + HttpExporterBuilder.DEFAULT_MAX_REQUEST_BODY_SIZE); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + onResponse.accept( + new FakeHttpResponse( + 500, + "Internal Server Error", + "{\"error\":\"grpc not supported\"}".getBytes(StandardCharsets.UTF_8))); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + + assertThat(exporter.export(mockMarshaller, 1).join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + + logs.assertContains("Response body: {\"error\":\"grpc not supported\"}"); + logs.assertDoesNotContain("Unable to parse response body"); + } + + @Test + @SuppressLogger(HttpExporter.class) + void export_requestBodyTooLargeFailsBeforeSend() { + HttpSender mockSender = Mockito.mock(HttpSender.class); + HttpExporter exporter = + new HttpExporter( + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER), + mockSender, + MeterProvider::noop, + InternalTelemetryVersion.LATEST, + URI.create("http://testing:1234"), + false, + 1); + + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter messageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) throws IOException { + output.write(new byte[] {1, 2}); + } + + @Override + public int getContentLength() { + return 2; + } + }; + Mockito.when(mockMarshaller.toBinaryMessageWriter()).thenReturn(messageWriter); + + CompletableResultCode result = exporter.export(mockMarshaller, 1); + + Assertions.assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + Assertions.assertThat(result.getFailureThrowable()) + .hasMessageContaining( + "Failed to export spans. Request body size 2 exceeded limit of 1 bytes"); + verifyNoInteractions(mockSender); + } + + @Test + @SuppressLogger(HttpExporter.class) + void export_nullErrorBodyUsesMissingBodyMessage() { + HttpSender mockSender = Mockito.mock(HttpSender.class); + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter emptyMessageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + }; + Mockito.when(mockMarshaller.toBinaryMessageWriter()).thenReturn(emptyMessageWriter); + HttpExporter exporter = + new HttpExporter( + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER), + mockSender, + MeterProvider::noop, + InternalTelemetryVersion.LATEST, + URI.create("http://testing:1234"), + false, + HttpExporterBuilder.DEFAULT_MAX_REQUEST_BODY_SIZE); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + onResponse.accept(new FakeHttpResponse(500, "Internal Server Error", null)); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + + assertThat(exporter.export(mockMarshaller, 1).join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + + logs.assertContains("Response body missing, HTTP status message: Internal Server Error"); + } + + @Test + @SuppressLogger(HttpExporter.class) + void export_whitespaceErrorBodyFallsBackToStatusMessage() { + HttpSender mockSender = Mockito.mock(HttpSender.class); + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter emptyMessageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + }; + Mockito.when(mockMarshaller.toBinaryMessageWriter()).thenReturn(emptyMessageWriter); + HttpExporter exporter = + new HttpExporter( + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER), + mockSender, + MeterProvider::noop, + InternalTelemetryVersion.LATEST, + URI.create("http://testing:1234"), + false, + HttpExporterBuilder.DEFAULT_MAX_REQUEST_BODY_SIZE); + + doAnswer( + invoc -> { + Consumer onResponse = invoc.getArgument(1); + onResponse.accept( + new FakeHttpResponse( + 500, "Internal Server Error", " ".getBytes(StandardCharsets.UTF_8))); + return null; + }) + .when(mockSender) + .send(any(), any(), any()); + + assertThat(exporter.export(mockMarshaller, 1).join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + + logs.assertContains("HTTP status message: Internal Server Error"); + logs.assertDoesNotContain("Response body:"); + } + + @Test + @SuppressLogger(HttpExporter.class) + void export_unknownRequestBodyTooLargeFailsBeforeSend() { + HttpSender mockSender = Mockito.mock(HttpSender.class); + HttpExporter exporter = + new HttpExporter( + ComponentId.generateLazy(StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER), + mockSender, + MeterProvider::noop, + InternalTelemetryVersion.LATEST, + URI.create("http://testing:1234"), + true, + 1); + + Marshaler mockMarshaller = Mockito.mock(Marshaler.class); + MessageWriter messageWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) throws IOException { + output.write(new byte[] {1, 2}); + } + + @Override + public int getContentLength() { + return -1; + } + }; + Mockito.when(mockMarshaller.toJsonMessageWriter()).thenReturn(messageWriter); + + CompletableResultCode result = exporter.export(mockMarshaller, 1); + + Assertions.assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + Assertions.assertThat(result.getFailureThrowable()) + .hasMessageContaining( + "Failed to export spans. Request body size 2 exceeded limit of 1 bytes"); + verifyNoInteractions(mockSender); + } + + private static class FakeHttpResponse implements HttpResponse { + + final int statusCode; + final String statusMessage; + @Nullable final byte[] responseBody; + + FakeHttpResponse(int statusCode, String statusMessage) { + this(statusCode, statusMessage, new byte[0]); + } + + FakeHttpResponse(int statusCode, String statusMessage, @Nullable byte[] responseBody) { + this.statusCode = statusCode; + this.statusMessage = statusMessage; + this.responseBody = responseBody; + } + + @Override + public int getStatusCode() { + return statusCode; + } + + @Override + public String getStatusMessage() { + return statusMessage; + } + + @Override + @Nullable + public byte[] getResponseBody() { + return responseBody; + } + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java new file mode 100644 index 00000000000..d4972b56ad5 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpConfigUtilTest.java @@ -0,0 +1,473 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_LOGS; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_METRICS; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.DATA_TYPE_TRACES; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_GRPC; +import static io.opentelemetry.exporter.otlp.internal.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.ImmutableMap; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.event.LoggingEvent; + +class OtlpConfigUtilTest { + + @RegisterExtension + final LogCapturer logs = LogCapturer.create().captureForType(OtlpConfigUtil.class); + + private static final String GENERIC_ENDPOINT_KEY = "otel.exporter.otlp.endpoint"; + private static final String TRACES_ENDPOINT_KEY = "otel.exporter.otlp.traces.endpoint"; + private static final String METRICS_ENDPOINT_KEY = "otel.exporter.otlp.metrics.endpoint"; + private static final String LOGS_ENDPOINT_KEY = "otel.exporter.otlp.logs.endpoint"; + + @Test + void getOtlpProtocolDefault() { + assertThat( + OtlpConfigUtil.getOtlpProtocol( + DATA_TYPE_TRACES, DefaultConfigProperties.createFromMap(Collections.emptyMap()))) + .isEqualTo(PROTOCOL_GRPC); + + assertThat( + OtlpConfigUtil.getOtlpProtocol( + DATA_TYPE_TRACES, + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.exporter.otlp.protocol", "foo")))) + .isEqualTo("foo"); + + assertThat( + OtlpConfigUtil.getOtlpProtocol( + DATA_TYPE_TRACES, + DefaultConfigProperties.createFromMap( + ImmutableMap.of( + "otel.exporter.otlp.protocol", "foo", + "otel.exporter.otlp.traces.protocol", "bar")))) + .isEqualTo("bar"); + } + + @Test + void configureOtlpExporterBuilder_ValidEndpoints() { + assertThatCode( + configureEndpointCallable( + ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317"))) + .doesNotThrowAnyException(); + assertThatCode( + configureEndpointCallable( + ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317/"))) + .doesNotThrowAnyException(); + assertThatCode( + configureEndpointCallable(ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost"))) + .doesNotThrowAnyException(); + assertThatCode( + configureEndpointCallable(ImmutableMap.of(GENERIC_ENDPOINT_KEY, "https://localhost"))) + .doesNotThrowAnyException(); + assertThatCode( + configureEndpointCallable( + ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://foo:bar@localhost"))) + .doesNotThrowAnyException(); + assertThatCode( + configureEndpointCallable( + ImmutableMap.of( + GENERIC_ENDPOINT_KEY, + "http://localhost:4318/path", + "otel.exporter.otlp.protocol", + "http/protobuf"))) + .doesNotThrowAnyException(); + } + + @Test + void configureOtlpExporterBuilder_InvalidEndpoints() { + assertThatThrownBy(configureEndpointCallable(ImmutableMap.of(GENERIC_ENDPOINT_KEY, "/foo/bar"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("OTLP endpoint must be a valid URL:"); + assertThatThrownBy( + configureEndpointCallable( + ImmutableMap.of(GENERIC_ENDPOINT_KEY, "file://localhost:4317"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("OTLP endpoint scheme must be http or https:"); + assertThatThrownBy( + configureEndpointCallable( + ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317?foo=bar"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("OTLP endpoint must not have a query string:"); + assertThatThrownBy( + configureEndpointCallable( + ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317#fragment"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("OTLP endpoint must not have a fragment:"); + assertThatThrownBy( + configureEndpointCallable( + ImmutableMap.of( + GENERIC_ENDPOINT_KEY, + "http://localhost:4317/path", + "otel.exporter.otlp.protocol", + "grpc"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("OTLP endpoint must not have a path:"); + } + + @SuppressLogger(OtlpConfigUtil.class) + @ParameterizedTest + @MethodSource("misalignedOtlpPortArgs") + void configureOtlpExporterBuilder_MisalignedOtlpPort( + String protocol, String endpoint, @Nullable String expectedLog) { + configureEndpoint( + DATA_TYPE_TRACES, + ImmutableMap.of(GENERIC_ENDPOINT_KEY, endpoint, "otel.exporter.otlp.protocol", protocol)); + + List logMessages = + logs.getEvents().stream().map(LoggingEvent::getMessage).collect(toList()); + if (expectedLog == null) { + assertThat(logMessages).isEmpty(); + } else { + assertThat(logMessages).contains(expectedLog); + } + } + + private static Stream misalignedOtlpPortArgs() { + return Stream.of( + Arguments.argumentSet( + "http/protobuf port 4318 no warn", "http/protobuf", "http://localhost:4318/path", null), + Arguments.argumentSet( + "http/protobuf port 8080 no warn", "http/protobuf", "http://localhost:8080/path", null), + Arguments.argumentSet( + "http/protobuf no port no warn", "http/protobuf", "http://localhost/path", null), + Arguments.argumentSet( + "http/protobuf port 4317 warn", + "http/protobuf", + "http://localhost:4317/path", + "OTLP exporter endpoint port is likely incorrect for protocol version \"http/protobuf\". The endpoint http://localhost:4317/path has port 4317. Typically, the \"http/protobuf\" version of OTLP uses port 4318."), + Arguments.argumentSet("grpc port 4317 no warn", "grpc", "http://localhost:4317/", null), + Arguments.argumentSet("grpc port 8080 no warn", "grpc", "http://localhost:8080/", null), + Arguments.argumentSet("grpc no port no warn", "grpc", "http://localhost/", null), + Arguments.argumentSet( + "grpc port 4318 warn", + "grpc", + "http://localhost:4318/", + "OTLP exporter endpoint port is likely incorrect for protocol version \"grpc\". The endpoint http://localhost:4318/ has port 4318. Typically, the \"grpc\" version of OTLP uses port 4317.")); + } + + private static ThrowingCallable configureEndpointCallable(Map properties) { + return () -> configureEndpoint(DATA_TYPE_TRACES, properties); + } + + @Test + void configureOtlpExporterBuilder_HttpGenericEndpointKey() { + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/")) + .isEqualTo("http://localhost:4318/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo")) + .isEqualTo("http://localhost:4318/foo/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo/")) + .isEqualTo("http://localhost:4318/foo/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) + .isEqualTo("http://localhost:4318/v1/traces/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/metrics")) + .isEqualTo("http://localhost:4318/v1/metrics/v1/traces"); + + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/v1/metrics"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/")) + .isEqualTo("http://localhost:4318/v1/metrics"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo")) + .isEqualTo("http://localhost:4318/foo/v1/metrics"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo/")) + .isEqualTo("http://localhost:4318/foo/v1/metrics"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/metrics")) + .isEqualTo("http://localhost:4318/v1/metrics/v1/metrics"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) + .isEqualTo("http://localhost:4318/v1/traces/v1/metrics"); + + assertThat( + configureEndpointForHttp(DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/v1/logs"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/")) + .isEqualTo("http://localhost:4318/v1/logs"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo")) + .isEqualTo("http://localhost:4318/foo/v1/logs"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo/")) + .isEqualTo("http://localhost:4318/foo/v1/logs"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/logs")) + .isEqualTo("http://localhost:4318/v1/logs/v1/logs"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) + .isEqualTo("http://localhost:4318/v1/traces/v1/logs"); + } + + @Test + void configureOtlpExporterBuilder_HttpTracesEndpointKey() { + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318/")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) + .isEqualTo("http://localhost:4318/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318/foo/bar")) + .isEqualTo("http://localhost:4318/foo/bar"); + assertThat( + configureEndpoint( + DATA_TYPE_TRACES, + ImmutableMap.of( + "otel.exporter.otlp.protocol", + PROTOCOL_HTTP_PROTOBUF, + GENERIC_ENDPOINT_KEY, + "http://localhost:4318/foo/bar", + TRACES_ENDPOINT_KEY, + "http://localhost:4318/baz/qux"))) + .isEqualTo("http://localhost:4318/baz/qux"); + } + + @Test + void configureOtlpExporterBuilder_HttpMetricsEndpointKey() { + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318/")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) + .isEqualTo("http://localhost:4318/v1/traces"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318/foo/bar")) + .isEqualTo("http://localhost:4318/foo/bar"); + assertThat( + configureEndpoint( + DATA_TYPE_METRICS, + ImmutableMap.of( + "otel.exporter.otlp.protocol", + PROTOCOL_HTTP_PROTOBUF, + GENERIC_ENDPOINT_KEY, + "http://localhost:4318/foo/bar", + METRICS_ENDPOINT_KEY, + "http://localhost:4318/baz/qux"))) + .isEqualTo("http://localhost:4318/baz/qux"); + } + + @Test + void configureOtlpExporterBuilder_HttpLogsEndpointKey() { + assertThat(configureEndpointForHttp(DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/"); + assertThat(configureEndpointForHttp(DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp(DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318/")) + .isEqualTo("http://localhost:4318/"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318/v1/logs")) + .isEqualTo("http://localhost:4318/v1/logs"); + assertThat( + configureEndpointForHttp( + DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318/foo/bar")) + .isEqualTo("http://localhost:4318/foo/bar"); + assertThat( + configureEndpoint( + DATA_TYPE_LOGS, + ImmutableMap.of( + "otel.exporter.otlp.protocol", + PROTOCOL_HTTP_PROTOBUF, + GENERIC_ENDPOINT_KEY, + "http://localhost:4318/foo/bar", + LOGS_ENDPOINT_KEY, + "http://localhost:4318/baz/qux"))) + .isEqualTo("http://localhost:4318/baz/qux"); + } + + private static String configureEndpointForHttp( + String dataType, String endpointPropertyKey, String endpointPropertyValue) { + return configureEndpoint( + dataType, + ImmutableMap.of( + "otel.exporter.otlp.protocol", + PROTOCOL_HTTP_PROTOBUF, + endpointPropertyKey, + endpointPropertyValue)); + } + + /** Configure and return the endpoint for the data type using the given properties. */ + private static String configureEndpoint(String dataType, Map properties) { + AtomicReference endpoint = new AtomicReference<>(""); + + OtlpConfigUtil.configureOtlpExporterBuilder( + dataType, + DefaultConfigProperties.createFromMap(properties), + value -> {}, + endpoint::set, + (value1, value2) -> {}, + value -> {}, + value -> {}, + value -> {}, + (value1, value2) -> {}, + value -> {}, + value -> {}, + value -> {}); + + return endpoint.get(); + } + + @Test + void configureOtlpAggregationTemporality() { + assertThatThrownBy(() -> + configureAggregationTemporality( + ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "foo"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized aggregation temporality:"); + + assertThat( + configureAggregationTemporality( + ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "CUMULATIVE"))) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat( + configureAggregationTemporality( + ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "cumulative"))) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat( + configureAggregationTemporality( + ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "DELTA"))) + .isEqualTo(AggregationTemporality.DELTA); + assertThat( + configureAggregationTemporality( + ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "delta"))) + .isEqualTo(AggregationTemporality.DELTA); + } + + /** Configure and return the aggregation temporality using the given properties. */ + private static AggregationTemporality configureAggregationTemporality( + Map properties) { + AtomicReference temporalityRef = new AtomicReference<>(); + ConfigProperties config = DefaultConfigProperties.createFromMap(properties); + ExporterBuilderUtil.configureOtlpAggregationTemporality(config, temporalityRef::set); + // We apply the temporality selector to a HISTOGRAM instrument to simplify assertions + return temporalityRef.get().getAggregationTemporality(InstrumentType.HISTOGRAM); + } + + @Test + void configureOtlpHistogramDefaultAggregation() { + assertThatThrownBy(() -> + configureHistogramDefaultAggregation( + ImmutableMap.of("otel.exporter.otlp.metrics.default.histogram.aggregation", "foo"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized default histogram aggregation:"); + assertThat( + configureHistogramDefaultAggregation( + ImmutableMap.of( + "otel.exporter.otlp.metrics.default.histogram.aggregation", + "base2_exponential_bucket_histogram")) + .getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); + assertThat( + configureHistogramDefaultAggregation( + ImmutableMap.of( + "otel.exporter.otlp.metrics.default.histogram.aggregation", + "BASE2_EXPONENTIAL_BUCKET_HISTOGRAM")) + .getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); + + assertThat( + configureHistogramDefaultAggregation( + ImmutableMap.of( + "otel.exporter.otlp.metrics.default.histogram.aggregation", + "explicit_bucket_histogram"))) + .isNull(); + assertThat( + configureHistogramDefaultAggregation( + ImmutableMap.of( + "otel.exporter.otlp.metrics.default.histogram.aggregation", + "EXPLICIT_BUCKET_HISTOGRAM"))) + .isNull(); + } + + private static DefaultAggregationSelector configureHistogramDefaultAggregation( + Map properties) { + AtomicReference aggregationRef = new AtomicReference<>(); + ConfigProperties config = DefaultConfigProperties.createFromMap(properties); + ExporterBuilderUtil.configureOtlpHistogramDefaultAggregation(config, aggregationRef::set); + // We apply the temporality selector to a HISTOGRAM instrument to simplify assertions + return aggregationRef.get(); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java new file mode 100644 index 00000000000..887d9dd89b1 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpLogRecordExporterProviderTest.java @@ -0,0 +1,291 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.assertj.core.api.AbstractObjectAssert; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class OtlpLogRecordExporterProviderTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @Spy private OtlpLogRecordExporterProvider provider; + + @Spy private OtlpHttpLogRecordExporterBuilder httpBuilder; + + @Spy private OtlpGrpcLogRecordExporterBuilder grpcBuilder; + + private String certificatePath; + private String clientKeyPath; + private String clientCertificatePath; + + @BeforeEach + void setup(@TempDir Path tempDir) throws IOException, CertificateEncodingException { + doReturn(httpBuilder).when(provider).httpBuilder(); + doReturn(grpcBuilder).when(provider).grpcBuilder(); + + certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + } + + private static String createTempFileWithContent(Path dir, String filename, byte[] content) + throws IOException { + Path path = dir.resolve(filename); + Files.write(path, content); + return path.toString(); + } + + @Test + void getName() { + assertThat(provider.getName()).isEqualTo("otlp"); + } + + @Test + void createExporter_UnsupportedProtocol() { + assertThatThrownBy(() -> + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.protocol", "foo")))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unsupported OTLP logs protocol: foo"); + } + + @Test + void createExporter_NoMocks() { + // Verifies createExporter after resetting the spy overrides + Mockito.reset(provider); + try (LogRecordExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(Collections.emptyMap()))) { + assertThat(exporter).isInstanceOf(OtlpGrpcLogRecordExporter.class); + } + try (LogRecordExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.protocol", "http/protobuf")))) { + assertThat(exporter).isInstanceOf(OtlpHttpLogRecordExporter.class); + } + } + + @Test + void createExporter_GrpcDefaults() { + try (LogRecordExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(Collections.emptyMap()))) { + assertThat(exporter).isInstanceOf(OtlpGrpcLogRecordExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder, never()).setEndpoint(any()); + verify(grpcBuilder, never()).addHeader(any(), any()); + verify(grpcBuilder, never()).setCompression(any()); + verify(grpcBuilder, never()).setTimeout(any()); + verify(grpcBuilder, never()).setTrustedCertificates(any()); + verify(grpcBuilder, never()).setClientTls(any(), any()); + assertThat(grpcBuilder).extracting("delegate").extracting("retryPolicy").isNotNull(); + getMemoryMode(exporter).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + private static AbstractObjectAssert getMemoryMode(LogRecordExporter exporter) { + return assertThat(exporter).extracting("marshaler").extracting("memoryMode"); + } + + @Test + void createExporter_GrpcWithGeneralConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "15s"); + config.put("otel.java.exporter.otlp.retry.disabled", "true"); + + try (LogRecordExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpGrpcLogRecordExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder).setEndpoint("https://localhost:443/"); + verify(grpcBuilder).addHeader("header-key", "header-value"); + verify(grpcBuilder).setCompression("gzip"); + verify(grpcBuilder).setTimeout(Duration.ofSeconds(15)); + verify(grpcBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(grpcBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(grpcBuilder).extracting("delegate").extracting("retryPolicy").isNull(); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_GrpcWithSignalConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.endpoint", "https://dummy:443/"); + config.put("otel.exporter.otlp.logs.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", "dummy.cert"); + config.put("otel.exporter.otlp.logs.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", "dummy.key"); + config.put("otel.exporter.otlp.logs.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", "dummy-client.cert"); + config.put("otel.exporter.otlp.logs.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "dummy=value"); + config.put("otel.exporter.otlp.logs.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "none"); + config.put("otel.exporter.otlp.logs.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "1s"); + config.put("otel.exporter.otlp.logs.timeout", "15s"); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + + try (LogRecordExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpGrpcLogRecordExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder).setEndpoint("https://localhost:443/"); + verify(grpcBuilder).addHeader("header-key", "header-value"); + verify(grpcBuilder).setCompression("gzip"); + verify(grpcBuilder).setTimeout(Duration.ofSeconds(15)); + verify(grpcBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(grpcBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + getMemoryMode(exporter).isEqualTo(MemoryMode.IMMUTABLE_DATA); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_HttpDefaults() { + try (LogRecordExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.logs.protocol", "http/protobuf")))) { + assertThat(exporter).isInstanceOf(OtlpHttpLogRecordExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder, never()).setEndpoint(any()); + verify(httpBuilder, never()).addHeader(any(), any()); + verify(httpBuilder, never()).setCompression(any()); + verify(httpBuilder, never()).setTimeout(any()); + verify(httpBuilder, never()).setTrustedCertificates(any()); + verify(httpBuilder, never()).setClientTls(any(), any()); + assertThat(httpBuilder).extracting("delegate").extracting("retryPolicy").isNotNull(); + getMemoryMode(exporter).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_HttpWithGeneralConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.protocol", "http/protobuf"); + config.put("otel.exporter.otlp.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "15s"); + config.put("otel.java.exporter.otlp.retry.disabled", "true"); + + try (LogRecordExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpHttpLogRecordExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setEndpoint("https://localhost:443/v1/logs"); + verify(httpBuilder).addHeader("header-key", "header-value"); + verify(httpBuilder).setCompression("gzip"); + verify(httpBuilder).setTimeout(Duration.ofSeconds(15)); + verify(httpBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(httpBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(httpBuilder).extracting("delegate").extracting("retryPolicy").isNull(); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_HttpWithSignalConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.protocol", "grpc"); + config.put("otel.exporter.otlp.logs.protocol", "http/protobuf"); + config.put("otel.exporter.otlp.endpoint", "https://dummy:443/"); + config.put("otel.exporter.otlp.logs.endpoint", "https://localhost:443/v1/logs"); + config.put("otel.exporter.otlp.certificate", "dummy.cert"); + config.put("otel.exporter.otlp.logs.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", "dummy.key"); + config.put("otel.exporter.otlp.logs.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", "dummy-client.cert"); + config.put("otel.exporter.otlp.logs.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "dummy=value"); + config.put("otel.exporter.otlp.logs.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "none"); + config.put("otel.exporter.otlp.logs.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "1s"); + config.put("otel.exporter.otlp.logs.timeout", "15s"); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + + try (LogRecordExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpHttpLogRecordExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setEndpoint("https://localhost:443/v1/logs"); + verify(httpBuilder).addHeader("header-key", "header-value"); + verify(httpBuilder).setCompression("gzip"); + verify(httpBuilder).setTimeout(Duration.ofSeconds(15)); + verify(httpBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(httpBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + getMemoryMode(exporter).isEqualTo(MemoryMode.IMMUTABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java new file mode 100644 index 00000000000..58b6f59d276 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpMetricExporterProviderTest.java @@ -0,0 +1,399 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class OtlpMetricExporterProviderTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @Spy private OtlpMetricExporterProvider provider; + + @Spy private OtlpHttpMetricExporterBuilder httpBuilder; + + @Spy private OtlpGrpcMetricExporterBuilder grpcBuilder; + + private String certificatePath; + private String clientKeyPath; + private String clientCertificatePath; + + @BeforeEach + void setup(@TempDir Path tempDir) throws IOException, CertificateEncodingException { + doReturn(httpBuilder).when(provider).httpBuilder(); + doReturn(grpcBuilder).when(provider).grpcBuilder(); + + certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + } + + private static String createTempFileWithContent(Path dir, String filename, byte[] content) + throws IOException { + Path path = dir.resolve(filename); + Files.write(path, content); + return path.toString(); + } + + @Test + void getName() { + assertThat(provider.getName()).isEqualTo("otlp"); + } + + @Test + void createExporter_UnsupportedProtocol() { + assertThatThrownBy(() -> + provider.createExporter( + DefaultConfigProperties.createFromMap( + singletonMap("otel.exporter.otlp.protocol", "foo")))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unsupported OTLP metrics protocol: foo"); + } + + @Test + void createExporter_NoMocks() { + // Verifies createExporter after resetting the spy overrides + Mockito.reset(provider); + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(emptyMap()))) { + assertThat(exporter).isInstanceOf(OtlpGrpcMetricExporter.class); + } + try (MetricExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + singletonMap("otel.exporter.otlp.protocol", "http/protobuf")))) { + assertThat(exporter).isInstanceOf(OtlpHttpMetricExporter.class); + } + } + + @Test + void createExporter_GrpcDefaults() { + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(emptyMap()))) { + assertThat(exporter).isInstanceOf(OtlpGrpcMetricExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder, never()).setEndpoint(any()); + verify(grpcBuilder, never()).addHeader(any(), any()); + verify(grpcBuilder, never()).setCompression(any()); + verify(grpcBuilder, never()).setTimeout(any()); + verify(grpcBuilder, never()).setTrustedCertificates(any()); + verify(grpcBuilder, never()).setClientTls(any(), any()); + assertThat(grpcBuilder).extracting("delegate").extracting("retryPolicy").isNotNull(); + assertThat(exporter.getMemoryMode()).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_GrpcWithGeneralConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "15s"); + config.put("otel.java.exporter.otlp.retry.disabled", "true"); + + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpGrpcMetricExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder).setEndpoint("https://localhost:443/"); + verify(grpcBuilder).addHeader("header-key", "header-value"); + verify(grpcBuilder).setCompression("gzip"); + verify(grpcBuilder).setTimeout(Duration.ofSeconds(15)); + verify(grpcBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(grpcBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(grpcBuilder).extracting("delegate").extracting("retryPolicy").isNull(); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_GrpcWithSignalConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.endpoint", "https://dummy:443/"); + config.put("otel.exporter.otlp.metrics.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", "dummy.cert"); + config.put("otel.exporter.otlp.metrics.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", "dummy.key"); + config.put("otel.exporter.otlp.metrics.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", "dummy-client.cert"); + config.put("otel.exporter.otlp.metrics.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "dummy=value"); + config.put("otel.exporter.otlp.metrics.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "none"); + config.put("otel.exporter.otlp.metrics.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "1s"); + config.put("otel.exporter.otlp.metrics.timeout", "15s"); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpGrpcMetricExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder).setEndpoint("https://localhost:443/"); + verify(grpcBuilder).addHeader("header-key", "header-value"); + verify(grpcBuilder).setCompression("gzip"); + verify(grpcBuilder).setTimeout(Duration.ofSeconds(15)); + verify(grpcBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(grpcBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(exporter.getMemoryMode()).isEqualTo(MemoryMode.IMMUTABLE_DATA); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_HttpDefaults() { + try (MetricExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + singletonMap("otel.exporter.otlp.metrics.protocol", "http/protobuf")))) { + assertThat(exporter).isInstanceOf(OtlpHttpMetricExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setComponentLoader(any()); + verify(httpBuilder, never()).setEndpoint(any()); + verify(httpBuilder, never()).addHeader(any(), any()); + verify(httpBuilder, never()).setCompression(any()); + verify(httpBuilder, never()).setTimeout(any()); + verify(httpBuilder, never()).setTrustedCertificates(any()); + verify(httpBuilder, never()).setClientTls(any(), any()); + assertThat(httpBuilder).extracting("delegate").extracting("retryPolicy").isNotNull(); + assertThat(exporter.getMemoryMode()).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_HttpWithGeneralConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.protocol", "http/protobuf"); + config.put("otel.exporter.otlp.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "15s"); + config.put("otel.java.exporter.otlp.retry.disabled", "true"); + + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpHttpMetricExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setComponentLoader(any()); + verify(httpBuilder).setEndpoint("https://localhost:443/v1/metrics"); + verify(httpBuilder).addHeader("header-key", "header-value"); + verify(httpBuilder).setCompression("gzip"); + verify(httpBuilder).setTimeout(Duration.ofSeconds(15)); + verify(httpBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(httpBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(httpBuilder).extracting("delegate").extracting("retryPolicy").isNull(); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_HttpWithSignalConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.protocol", "grpc"); + config.put("otel.exporter.otlp.metrics.protocol", "http/protobuf"); + config.put("otel.exporter.otlp.endpoint", "https://dummy:443/"); + config.put("otel.exporter.otlp.metrics.endpoint", "https://localhost:443/v1/metrics"); + config.put("otel.exporter.otlp.certificate", "dummy.cert"); + config.put("otel.exporter.otlp.metrics.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", "dummy.key"); + config.put("otel.exporter.otlp.metrics.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", "dummy-client.cert"); + config.put("otel.exporter.otlp.metrics.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "dummy=value"); + config.put("otel.exporter.otlp.metrics.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "none"); + config.put("otel.exporter.otlp.metrics.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "1s"); + config.put("otel.exporter.otlp.metrics.timeout", "15s"); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpHttpMetricExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setComponentLoader(any()); + verify(httpBuilder).setEndpoint("https://localhost:443/v1/metrics"); + verify(httpBuilder).addHeader("header-key", "header-value"); + verify(httpBuilder).setCompression("gzip"); + verify(httpBuilder).setTimeout(Duration.ofSeconds(15)); + verify(httpBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(httpBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(exporter.getMemoryMode()).isEqualTo(MemoryMode.IMMUTABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void meterProviderRef_InitializedWithNoop() throws Exception { + AtomicReference meterProviderRef = getMeterProviderRef(provider); + + assertThat(meterProviderRef.get()).isSameAs(MeterProvider.noop()); + } + + @Test + void afterAutoConfigure_UpdatesMeterProviderRef() throws Exception { + OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().build(); + + AtomicReference meterProviderRef = getMeterProviderRef(provider); + assertThat(meterProviderRef.get()).isSameAs(MeterProvider.noop()); + + provider.afterAutoConfigure(sdk); + + assertThat(meterProviderRef.get()).isSameAs(sdk.getMeterProvider()); + } + + @Test + @SuppressWarnings("unchecked") + void createExporter_GrpcSetsMeterProviderSupplier() { + AtomicReference> capturedSupplier = new AtomicReference<>(); + + OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().build(); + provider.afterAutoConfigure(sdk); + + doAnswer( + invocation -> { + capturedSupplier.set(invocation.getArgument(0)); + return grpcBuilder; + }) + .when(grpcBuilder) + .setMeterProvider(any(Supplier.class)); + + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(emptyMap()))) { + + assertThat(exporter).isInstanceOf(OtlpGrpcMetricExporter.class); + assertThat(capturedSupplier.get()).isNotNull(); + assertThat(capturedSupplier.get().get()).isSameAs(sdk.getMeterProvider()); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + @SuppressWarnings("unchecked") + void createExporter_HttpSetsMeterProviderSupplier() { + AtomicReference> capturedSupplier = new AtomicReference<>(); + + OpenTelemetrySdk sdk = OpenTelemetrySdk.builder().build(); + provider.afterAutoConfigure(sdk); + + doAnswer( + invocation -> { + capturedSupplier.set(invocation.getArgument(0)); + return httpBuilder; + }) + .when(httpBuilder) + .setMeterProvider(any(Supplier.class)); + + try (MetricExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + singletonMap("otel.exporter.otlp.metrics.protocol", "http/protobuf")))) { + + assertThat(exporter).isInstanceOf(OtlpHttpMetricExporter.class); + assertThat(capturedSupplier.get()).isNotNull(); + assertThat(capturedSupplier.get().get()).isSameAs(sdk.getMeterProvider()); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + @SuppressWarnings("unchecked") + void meterProviderSupplier_ReturnsNoopBeforeAutoConfigure() { + AtomicReference> capturedSupplier = new AtomicReference<>(); + + doAnswer( + invocation -> { + capturedSupplier.set(invocation.getArgument(0)); + return grpcBuilder; + }) + .when(grpcBuilder) + .setMeterProvider(any(Supplier.class)); + + try (MetricExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(emptyMap()))) { + + assertThat(exporter).isInstanceOf(OtlpGrpcMetricExporter.class); + assertThat(capturedSupplier.get()).isNotNull(); + assertThat(capturedSupplier.get().get()).isSameAs(MeterProvider.noop()); + } + } + + @SuppressWarnings("unchecked") + private static AtomicReference getMeterProviderRef( + OtlpMetricExporterProvider provider) throws Exception { + Field field = OtlpMetricExporterProvider.class.getDeclaredField("meterProviderRef"); + field.setAccessible(true); + return (AtomicReference) field.get(provider); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java new file mode 100644 index 00000000000..837231e27c2 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpSpanExporterProviderTest.java @@ -0,0 +1,311 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.assertj.core.api.AbstractObjectAssert; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class OtlpSpanExporterProviderTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @Spy private OtlpSpanExporterProvider provider; + + @Spy private OtlpHttpSpanExporterBuilder httpBuilder; + + @Spy private OtlpGrpcSpanExporterBuilder grpcBuilder; + + private String certificatePath; + private String clientKeyPath; + private String clientCertificatePath; + + @BeforeEach + void setup(@TempDir Path tempDir) throws IOException, CertificateEncodingException { + doReturn(httpBuilder).when(provider).httpBuilder(); + doReturn(grpcBuilder).when(provider).grpcBuilder(); + + certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + } + + private static String createTempFileWithContent(Path dir, String filename, byte[] content) + throws IOException { + Path path = dir.resolve(filename); + Files.write(path, content); + return path.toString(); + } + + @Test + void getName() { + assertThat(provider.getName()).isEqualTo("otlp"); + } + + @Test + void createExporter_UnsupportedProtocol() { + assertThatThrownBy(() -> + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.protocol", "foo")))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unsupported OTLP traces protocol: foo"); + } + + @Test + void createExporter_NoMocks() { + // Verifies createExporter after resetting the spy overrides + Mockito.reset(provider); + try (SpanExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(Collections.emptyMap()))) { + assertThat(exporter).isInstanceOf(OtlpGrpcSpanExporter.class); + } + try (SpanExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.protocol", "http/protobuf")))) { + assertThat(exporter).isInstanceOf(OtlpHttpSpanExporter.class); + } + } + + @Test + void createExporter_GrpcDefaults() { + try (SpanExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(Collections.emptyMap()))) { + assertThat(exporter).isInstanceOf(OtlpGrpcSpanExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder, never()).setEndpoint(any()); + verify(grpcBuilder, never()).addHeader(any(), any()); + verify(grpcBuilder, never()).setCompression(any()); + verify(grpcBuilder, never()).setTimeout(any()); + verify(grpcBuilder, never()).setTrustedCertificates(any()); + verify(grpcBuilder, never()).setClientTls(any(), any()); + assertThat(grpcBuilder).extracting("delegate").extracting("retryPolicy").isNotNull(); + getMemoryMode(exporter).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + private static AbstractObjectAssert getMemoryMode(SpanExporter exporter) { + return assertThat(exporter).extracting("marshaler").extracting("memoryMode"); + } + + @Test + void createExporter_GrpcWithGeneralConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "15s"); + config.put("otel.java.exporter.otlp.retry.disabled", "true"); + + try (SpanExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpGrpcSpanExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder).setEndpoint("https://localhost:443/"); + verify(grpcBuilder).addHeader("header-key", "header-value"); + verify(grpcBuilder).setCompression("gzip"); + verify(grpcBuilder).setTimeout(Duration.ofSeconds(15)); + verify(grpcBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(grpcBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(grpcBuilder).extracting("delegate").extracting("retryPolicy").isNull(); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_GrpcWithSignalConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.endpoint", "https://dummy:443/"); + config.put("otel.exporter.otlp.traces.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", "dummy.cert"); + config.put("otel.exporter.otlp.traces.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", "dummy.key"); + config.put("otel.exporter.otlp.traces.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", "dummy-client.cert"); + config.put("otel.exporter.otlp.traces.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "dummy=value"); + config.put("otel.exporter.otlp.traces.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "none"); + config.put("otel.exporter.otlp.traces.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "1s"); + config.put("otel.exporter.otlp.traces.timeout", "15s"); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + + try (SpanExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpGrpcSpanExporter.class); + verify(grpcBuilder, times(1)).build(); + verify(grpcBuilder).setComponentLoader(any()); + verify(grpcBuilder).setEndpoint("https://localhost:443/"); + verify(grpcBuilder).addHeader("header-key", "header-value"); + verify(grpcBuilder).setCompression("gzip"); + verify(grpcBuilder).setTimeout(Duration.ofSeconds(15)); + verify(grpcBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(grpcBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + getMemoryMode(exporter).isEqualTo(MemoryMode.IMMUTABLE_DATA); + } + Mockito.verifyNoInteractions(httpBuilder); + } + + @Test + void createExporter_HttpDefaults() { + try (SpanExporter exporter = + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.traces.protocol", "http/protobuf")))) { + assertThat(exporter).isInstanceOf(OtlpHttpSpanExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setComponentLoader(any()); + verify(httpBuilder, never()).setEndpoint(any()); + verify(httpBuilder, never()).addHeader(any(), any()); + verify(httpBuilder, never()).setCompression(any()); + verify(httpBuilder, never()).setTimeout(any()); + verify(httpBuilder, never()).setTrustedCertificates(any()); + verify(httpBuilder, never()).setClientTls(any(), any()); + assertThat(httpBuilder).extracting("delegate").extracting("retryPolicy").isNotNull(); + getMemoryMode(exporter).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_HttpWithGeneralConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.protocol", "http/protobuf"); + config.put("otel.exporter.otlp.endpoint", "https://localhost:443/"); + config.put("otel.exporter.otlp.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", clientCertificatePath); + config.put( + "otel.exporter.otlp.headers", "header-key1=header%20value1,header-key2=header value2"); + config.put("otel.exporter.otlp.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "15s"); + config.put("otel.java.exporter.otlp.retry.disabled", "true"); + + try (SpanExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpHttpSpanExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setComponentLoader(any()); + verify(httpBuilder).setEndpoint("https://localhost:443/v1/traces"); + verify(httpBuilder).addHeader("header-key1", "header value1"); + verify(httpBuilder).addHeader("header-key2", "header value2"); + verify(httpBuilder).setCompression("gzip"); + verify(httpBuilder).setTimeout(Duration.ofSeconds(15)); + verify(httpBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(httpBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + assertThat(httpBuilder).extracting("delegate").extracting("retryPolicy").isNull(); + getMemoryMode(exporter).isEqualTo(MemoryMode.REUSABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_HttpWithSignalConfiguration() throws CertificateEncodingException { + Map config = new HashMap<>(); + config.put("otel.exporter.otlp.protocol", "grpc"); + config.put("otel.exporter.otlp.traces.protocol", "http/protobuf"); + config.put("otel.exporter.otlp.endpoint", "https://dummy:443/"); + config.put("otel.exporter.otlp.traces.endpoint", "https://localhost:443/v1/traces"); + config.put("otel.exporter.otlp.certificate", "dummy.cert"); + config.put("otel.exporter.otlp.traces.certificate", certificatePath); + config.put("otel.exporter.otlp.client.key", "dummy.key"); + config.put("otel.exporter.otlp.traces.client.key", clientKeyPath); + config.put("otel.exporter.otlp.client.certificate", "dummy-client.cert"); + config.put("otel.exporter.otlp.traces.client.certificate", clientCertificatePath); + config.put("otel.exporter.otlp.headers", "dummy=value"); + config.put("otel.exporter.otlp.traces.headers", "header-key=header-value"); + config.put("otel.exporter.otlp.compression", "none"); + config.put("otel.exporter.otlp.traces.compression", "gzip"); + config.put("otel.exporter.otlp.timeout", "1s"); + config.put("otel.exporter.otlp.traces.timeout", "15s"); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + + try (SpanExporter exporter = + provider.createExporter(DefaultConfigProperties.createFromMap(config))) { + assertThat(exporter).isInstanceOf(OtlpHttpSpanExporter.class); + verify(httpBuilder, times(1)).build(); + verify(httpBuilder).setComponentLoader(any()); + verify(httpBuilder).setEndpoint("https://localhost:443/v1/traces"); + verify(httpBuilder).addHeader("header-key", "header-value"); + verify(httpBuilder).setCompression("gzip"); + verify(httpBuilder).setTimeout(Duration.ofSeconds(15)); + verify(httpBuilder).setTrustedCertificates(serverTls.certificate().getEncoded()); + verify(httpBuilder) + .setClientTls(clientTls.privateKey().getEncoded(), clientTls.certificate().getEncoded()); + getMemoryMode(exporter).isEqualTo(MemoryMode.IMMUTABLE_DATA); + } + Mockito.verifyNoInteractions(grpcBuilder); + } + + @Test + void createExporter_decodingError() { + Assertions.assertThatThrownBy( + () -> { + provider.createExporter( + DefaultConfigProperties.createFromMap( + Collections.singletonMap( + "otel.exporter.otlp.headers", "header-key=Bearer%20s3cr3t%-1"))); + }) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Cannot decode header value for header: header-key"); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java new file mode 100644 index 00000000000..0cbb4adf4e7 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/internal/OtlpUserAgentTest.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class OtlpUserAgentTest { + + @Test + void getUserAgent() { + assertThat(OtlpUserAgent.getUserAgent()).matches("OTel-OTLP-Exporter-Java/1\\..*"); + } + + @Test + void addUserAgentHeader() { + AtomicReference keyRef = new AtomicReference<>(); + AtomicReference valueRef = new AtomicReference<>(); + OtlpUserAgent.addUserAgentHeader((key, value) -> { + keyRef.set(key); + valueRef.set(value); + }); + assertThat(keyRef.get()).isEqualTo("User-Agent"); + assertThat(valueRef.get()).matches("OTel-OTLP-Exporter-Java/1\\..*"); + } +} diff --git a/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilderTest.java b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilderTest.java new file mode 100644 index 00000000000..ea0d2dc4d19 --- /dev/null +++ b/exporters/otlp/all/src/test/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilderTest.java @@ -0,0 +1,254 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import static io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData.createDoubleGauge; +import static java.util.Collections.singleton; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import com.linecorp.armeria.server.ServerBuilder; +import com.linecorp.armeria.server.ServiceRequestContext; +import com.linecorp.armeria.server.grpc.protocol.AbstractUnaryGrpcService; +import com.linecorp.armeria.server.logging.LoggingService; +import com.linecorp.armeria.testing.junit5.server.ServerExtension; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongCounterBuilder; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.mockito.Mockito; + +class OtlpGrpcMetricExporterBuilderTest { + + private static final Collection DATA_SET = + singleton( + createDoubleGauge( + Resource.empty(), + InstrumentationScopeInfo.create("test"), + "test", + "test", + "test", + ImmutableGaugeData.empty())); + + @RegisterExtension + private static final ServerExtension server = + new ServerExtension() { + @Override + protected void configure(ServerBuilder sb) { + sb.service( + "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", + new AbstractUnaryGrpcService() { + @Override + protected CompletionStage handleMessage( + ServiceRequestContext ctx, byte[] message) { + return CompletableFuture.completedFuture( + ExportMetricsServiceResponse.getDefaultInstance().toByteArray()); + } + }); + sb.http(0); + sb.decorator(LoggingService.newDecorator()); + } + }; + + private final MeterProvider meterProvider = mock(MeterProvider.class); + private final Meter meter = mock(Meter.class); + private final LongCounterBuilder counterBuilder = mock(LongCounterBuilder.class); + private final LongCounter counter = mock(LongCounter.class); + + @BeforeEach + void setup() { + GlobalOpenTelemetry.resetForTest(); + } + + @AfterEach + void cleanup() { + GlobalOpenTelemetry.resetForTest(); + } + + @Test + void setMeterProvider_null() { + OtlpGrpcMetricExporterBuilder builder = OtlpGrpcMetricExporter.builder(); + assertThrows( + NullPointerException.class, + () -> builder.setMeterProvider((MeterProvider) null), + "MeterProvider must not be null"); + assertThrows( + NullPointerException.class, + () -> builder.setMeterProvider((Supplier) null), + "MeterProvider must not be null"); + } + + @Test + void setMeterProvider() { + when(meterProvider.get(any())).thenReturn(meter); + when(meter.counterBuilder(any())).thenReturn(counterBuilder); + when(counterBuilder.build()).thenReturn(counter); + + try (OtlpGrpcMetricExporter exporter = + OtlpGrpcMetricExporter.builder() + .setMeterProvider(meterProvider) + .setEndpoint("http://localhost:" + server.httpPort()) + .build()) { + verifyNoInteractions(meterProvider, meter, counterBuilder, counter); + + // Collection before MeterProvider is initialized. + when(meterProvider.get(any())).thenReturn(MeterProvider.noop().get("test")); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verifyNoInteractions(meter, counterBuilder, counter); + + // Collection after MeterProvider is initialized. + when(meterProvider.get(any())).thenReturn(meter); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verify(meter).counterBuilder("otlp.exporter.seen"); + verify(meter).counterBuilder("otlp.exporter.exported"); + verify(counter, times(2)).add(eq(1L), any()); + verifyNoMoreInteractions(meter, counter); + } + } + + @Test + void setMeterProvider_supplier() { + when(meterProvider.get(any())).thenReturn(meter); + when(meter.counterBuilder(any())).thenReturn(counterBuilder); + when(counterBuilder.build()).thenReturn(counter); + + @SuppressWarnings("unchecked") + Supplier provider = mock(Supplier.class); + try (OtlpGrpcMetricExporter exporter = + OtlpGrpcMetricExporter.builder() + .setMeterProvider(provider) + .setEndpoint("http://localhost:" + server.httpPort()) + .build()) { + verifyNoInteractions(provider, meterProvider, meter, counterBuilder, counter); + + // Collection before MeterProvider is initialized. + when(provider.get()).thenReturn(MeterProvider.noop()); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verifyNoInteractions(meterProvider, meter, counterBuilder, counter); + + // Collection after MeterProvider is initialized. + when(provider.get()).thenReturn(meterProvider); + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verify(meter).counterBuilder("otlp.exporter.seen"); + verify(meter).counterBuilder("otlp.exporter.exported"); + verify(counter, times(2)).add(eq(1L), any()); + verifyNoMoreInteractions(meter, counter); + } + } + + @Test + void setMeterProvider_defaultGlobal() { + GlobalOpenTelemetry.set( + new OpenTelemetry() { + @Override + public MeterProvider getMeterProvider() { + return meterProvider; + } + + @Override + public TracerProvider getTracerProvider() { + return TracerProvider.noop(); + } + + @Override + public ContextPropagators getPropagators() { + return ContextPropagators.noop(); + } + }); + when(meterProvider.get(any())).thenReturn(meter); + when(meter.counterBuilder(any())).thenReturn(counterBuilder); + when(counterBuilder.build()).thenReturn(counter); + + try (OtlpGrpcMetricExporter exporter = + OtlpGrpcMetricExporter.builder() + .setEndpoint("http://localhost:" + server.httpPort()) + .build()) { + verifyNoInteractions(meterProvider, meter, counterBuilder, counter); + + exporter.export(DATA_SET).join(10, TimeUnit.SECONDS); + + verify(meter).counterBuilder("otlp.exporter.seen"); + verify(meter).counterBuilder("otlp.exporter.exported"); + verify(counter, times(2)).add(eq(1L), any()); + verifyNoMoreInteractions(meter, counter); + } + } + + @Test + void setMeterProvider_noMocks() { + AtomicReference meterProviderAtomicReference = new AtomicReference<>(); + SdkMeterProviderBuilder builder = + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.create( + OtlpGrpcMetricExporter.builder() + .setMeterProvider(meterProviderAtomicReference::get) + .build())); + meterProviderAtomicReference.set(builder.build()); + meterProviderAtomicReference.get().close(); + } + + @Test + void verifyToBuilderPreservesSettings() { + AggregationTemporalitySelector temporalitySelector = + Mockito.mock(AggregationTemporalitySelector.class); + DefaultAggregationSelector defaultAggregationSelector = + Mockito.mock(DefaultAggregationSelector.class); + + OtlpGrpcMetricExporter original = + OtlpGrpcMetricExporter.builder() + .setMemoryMode(MemoryMode.IMMUTABLE_DATA) + .setAggregationTemporalitySelector(temporalitySelector) + .setDefaultAggregationSelector(defaultAggregationSelector) + .build(); + + OtlpGrpcMetricExporter copy = original.toBuilder().build(); + + assertThat(copy.getMemoryMode()).isEqualTo(MemoryMode.IMMUTABLE_DATA); + assertThat(copy.aggregationTemporalitySelector).isSameAs(temporalitySelector); + assertThat(copy.defaultAggregationSelector).isSameAs(defaultAggregationSelector); + + original.close(); + copy.close(); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/OkHttpVersionTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/OkHttpVersionTest.java new file mode 100644 index 00000000000..d3286ae9070 --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/OkHttpVersionTest.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assumptions.assumeThat; + +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.util.logging.Level; +import java.util.logging.Logger; +import okhttp3.OkHttp; +import org.junit.jupiter.api.Test; + +class OkHttpVersionTest { + + private static final Logger LOGGER = Logger.getLogger(OkHttpVersionTest.class.getName()); + + @Test + @SuppressLogger(OkHttpVersionTest.class) + void expectedOkHttpVersion() { + String expectedVersion = System.getProperty("expected.okhttp.version"); + LOGGER.log(Level.WARNING, "Testing okhttp version " + expectedVersion); + assumeThat(expectedVersion.equals("LATEST")).isFalse(); + assertThat(OkHttp.VERSION).isEqualTo(expectedVersion); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterOkHttpSenderTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterOkHttpSenderTest.java new file mode 100644 index 00000000000..1804543a02d --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterOkHttpSenderTest.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.logs; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractHttpTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.HttpLogRecordExporterBuilderWrapper; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.List; + +class OtlpHttpLogRecordExporterOkHttpSenderTest + extends AbstractHttpTelemetryExporterTest { + + protected OtlpHttpLogRecordExporterOkHttpSenderTest() { + super("log", "/v1/logs", ResourceLogs.getDefaultInstance()); + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return new HttpLogRecordExporterBuilderWrapper(OtlpHttpLogRecordExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return new HttpLogRecordExporterBuilderWrapper( + ((OtlpHttpLogRecordExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected LogRecordData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeLogRecordData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceLogsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java new file mode 100644 index 00000000000..aadff167009 --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterOkHttpSenderTest.java @@ -0,0 +1,129 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractHttpTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.HttpMetricExporterBuilderWrapper; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class OtlpHttpMetricExporterOkHttpSenderTest + extends AbstractHttpTelemetryExporterTest { + + protected OtlpHttpMetricExporterOkHttpSenderTest() { + super("metric", "/v1/metrics", ResourceMetrics.getDefaultInstance()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void validMetricConfig() { + assertThatCode(() -> + OtlpHttpMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) + .doesNotThrowAnyException(); + assertThat( + OtlpHttpMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat( + OtlpHttpMetricExporter.builder() + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + assertThat( + OtlpHttpMetricExporter.builder() + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.drop())) + .build() + .getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.drop()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void invalidMetricConfig() { + assertThatThrownBy( + () -> OtlpHttpMetricExporter.builder().setAggregationTemporalitySelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("aggregationTemporalitySelector"); + + assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setDefaultAggregationSelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("defaultAggregationSelector"); + } + + /** Test configuration specific to metric exporter. */ + @Test + void stringRepresentation() { + try (MetricExporter metricExporter = OtlpHttpMetricExporter.builder().build()) { + assertThat(metricExporter.toString()) + .matches( + "OtlpHttpMetricExporter\\{" + + "endpoint=http://localhost:4318/v1/metrics, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "proxyOptions=null, " + + "compressorEncoding=null, " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "exportAsJson=false, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}, " + + "retryPolicy=RetryPolicy\\{.*\\}, " + + "componentLoader=.*, " + + "exporterType=OTLP_HTTP_METRIC_EXPORTER, " + + "internalTelemetrySchemaVersion=LEGACY, " + + "aggregationTemporalitySelector=AggregationTemporalitySelector\\{.*\\}, " + + "defaultAggregationSelector=DefaultAggregationSelector\\{.*\\}, " + + "memoryMode=REUSABLE_DATA" + + "\\}"); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return new HttpMetricExporterBuilderWrapper(OtlpHttpMetricExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return new HttpMetricExporterBuilderWrapper( + ((OtlpHttpMetricExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected MetricData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeMetricData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceMetricsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterOkHttpSenderTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterOkHttpSenderTest.java new file mode 100644 index 00000000000..a68c2e5fd19 --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterOkHttpSenderTest.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.trace; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractHttpTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.HttpSpanExporterBuilderWrapper; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.proto.trace.v1.ResourceSpans; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class OtlpHttpSpanExporterOkHttpSenderTest + extends AbstractHttpTelemetryExporterTest { + + protected OtlpHttpSpanExporterOkHttpSenderTest() { + super("span", "/v1/traces", ResourceSpans.getDefaultInstance()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void stringRepresentation() { + try (SpanExporter spanExporter = OtlpHttpSpanExporter.builder().build()) { + assertThat(spanExporter.toString()) + .matches( + "OtlpHttpSpanExporter\\{" + + "endpoint=http://localhost:4318/v1/traces, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "proxyOptions=null, " + + "compressorEncoding=null, " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "exportAsJson=false, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}, " + + "retryPolicy=RetryPolicy\\{.*\\}, " + + "componentLoader=.*, " + + "exporterType=OTLP_HTTP_SPAN_EXPORTER, " + + "internalTelemetrySchemaVersion=LEGACY, " + + "memoryMode=REUSABLE_DATA" + + "\\}"); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return new HttpSpanExporterBuilderWrapper(OtlpHttpSpanExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return new HttpSpanExporterBuilderWrapper( + ((OtlpHttpSpanExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected SpanData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeSpanData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceSpansMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporterTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporterTest.java new file mode 100644 index 00000000000..de7845e8980 --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogRecordExporterTest.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSender; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcLogRecordExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcLogRecordExporterTest() { + super("log", ResourceLogs.getDefaultInstance()); + } + + @Test + void usingOkHttp() throws Exception { + try (Closeable exporter = OtlpGrpcLogRecordExporter.builder().build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(OkHttpGrpcSender.class); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return TelemetryExporterBuilder.wrap(OtlpGrpcLogRecordExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap( + ((OtlpGrpcLogRecordExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected LogRecordData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeLogRecordData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceLogsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java new file mode 100644 index 00000000000..cabe7bc60b2 --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java @@ -0,0 +1,135 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSender; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.io.Closeable; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class OtlpGrpcMetricExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcMetricExporterTest() { + super("metric", ResourceMetrics.getDefaultInstance()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void validMetricConfig() { + assertThatCode(() -> + OtlpGrpcMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) + .doesNotThrowAnyException(); + assertThat( + OtlpGrpcMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat( + OtlpGrpcMetricExporter.builder() + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + assertThat( + OtlpGrpcMetricExporter.builder() + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.drop())) + .build() + .getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.drop()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void invalidMetricConfig() { + assertThatThrownBy( + () -> OtlpGrpcMetricExporter.builder().setAggregationTemporalitySelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("aggregationTemporalitySelector"); + + assertThatThrownBy(() -> OtlpGrpcMetricExporter.builder().setDefaultAggregationSelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("defaultAggregationSelector"); + } + + /** Test configuration specific to metric exporter. */ + @Test + void stringRepresentation() { + try (MetricExporter metricExporter = OtlpGrpcMetricExporter.builder().build()) { + assertThat(metricExporter.toString()) + .matches( + "OtlpGrpcMetricExporter\\{" + + "endpoint=http://localhost:4317, " + + "fullMethodName=.*, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "compressorEncoding=null, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}, " + + "retryPolicy=RetryPolicy\\{.*\\}, " + + "componentLoader=.*, " + + "exporterType=OTLP_GRPC_METRIC_EXPORTER, " + + "internalTelemetrySchemaVersion=LEGACY, " + + "aggregationTemporalitySelector=AggregationTemporalitySelector\\{.*\\}, " + + "defaultAggregationSelector=DefaultAggregationSelector\\{.*\\}, " + + "memoryMode=REUSABLE_DATA" + + "\\}"); + } + } + + @Test + void usingOkHttp() throws Exception { + try (Closeable exporter = OtlpGrpcMetricExporter.builder().build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(OkHttpGrpcSender.class); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return TelemetryExporterBuilder.wrap(OtlpGrpcMetricExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcMetricExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected MetricData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeMetricData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceMetricsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/traces/OtlpGrpcSpanExporterTest.java b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/traces/OtlpGrpcSpanExporterTest.java new file mode 100644 index 00000000000..8d7a31c8e9f --- /dev/null +++ b/exporters/otlp/all/src/testDefaultSender/java/io/opentelemetry/exporter/otlp/traces/OtlpGrpcSpanExporterTest.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.traces; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSender; +import io.opentelemetry.proto.trace.v1.ResourceSpans; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.Closeable; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class OtlpGrpcSpanExporterTest extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcSpanExporterTest() { + super("span", ResourceSpans.getDefaultInstance()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void stringRepresentation() { + try (SpanExporter spanExporter = OtlpGrpcSpanExporter.builder().build()) { + assertThat(spanExporter.toString()) + .matches( + "OtlpGrpcSpanExporter\\{" + + "endpoint=http://localhost:4317, " + + "fullMethodName=.*, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "compressorEncoding=null, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}, " + + "retryPolicy=RetryPolicy\\{.*\\}, " + + "componentLoader=.*, " + + "exporterType=OTLP_GRPC_SPAN_EXPORTER, " + + "internalTelemetrySchemaVersion=LEGACY, " + + "memoryMode=REUSABLE_DATA" + + "\\}"); + } + } + + @Test + void usingOkHttp() throws Exception { + try (Closeable exporter = OtlpGrpcSpanExporter.builder().build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(OkHttpGrpcSender.class); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return TelemetryExporterBuilder.wrap(OtlpGrpcSpanExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcSpanExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected SpanData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeSpanData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceSpansMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyLogRecordExporterTest.java b/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyLogRecordExporterTest.java new file mode 100644 index 00000000000..a8bd6c128c1 --- /dev/null +++ b/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyLogRecordExporterTest.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcNettyLogRecordExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcNettyLogRecordExporterTest() { + super("log", ResourceLogs.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcLogRecordExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcLogRecordExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap( + ((OtlpGrpcLogRecordExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected LogRecordData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeLogRecordData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceLogsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyMetricExporterTest.java b/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyMetricExporterTest.java new file mode 100644 index 00000000000..b2088f5fc79 --- /dev/null +++ b/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyMetricExporterTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcNettyMetricExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcNettyMetricExporterTest() { + super("metric", ResourceMetrics.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcMetricExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcMetricExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcMetricExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected MetricData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeMetricData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceMetricsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettySpanExporterTest.java b/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettySpanExporterTest.java new file mode 100644 index 00000000000..078339a2aaa --- /dev/null +++ b/exporters/otlp/all/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettySpanExporterTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.trace; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.trace.v1.ResourceSpans; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcNettySpanExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcNettySpanExporterTest() { + super("span", ResourceSpans.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcSpanExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcSpanExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcSpanExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected SpanData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeSpanData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceSpansMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyShadedLogRecordExporterTest.java b/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyShadedLogRecordExporterTest.java new file mode 100644 index 00000000000..a8cbb43154b --- /dev/null +++ b/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyShadedLogRecordExporterTest.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcNettyShadedLogRecordExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcNettyShadedLogRecordExporterTest() { + super("log", ResourceLogs.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcLogRecordExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcLogRecordExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap( + ((OtlpGrpcLogRecordExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected LogRecordData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeLogRecordData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceLogsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyShadedMetricExporterTest.java b/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyShadedMetricExporterTest.java new file mode 100644 index 00000000000..7b9a8c39c9d --- /dev/null +++ b/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyShadedMetricExporterTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcNettyShadedMetricExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcNettyShadedMetricExporterTest() { + super("metric", ResourceMetrics.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcMetricExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcMetricExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcMetricExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected MetricData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeMetricData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceMetricsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettyShadedSpanExporterTest.java b/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettyShadedSpanExporterTest.java new file mode 100644 index 00000000000..ca7352f74e6 --- /dev/null +++ b/exporters/otlp/all/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettyShadedSpanExporterTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.trace; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.trace.v1.ResourceSpans; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcNettyShadedSpanExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcNettyShadedSpanExporterTest() { + super("span", ResourceSpans.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcSpanExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcSpanExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcSpanExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected SpanData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeSpanData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceSpansMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcOkHttpLogRecordExporterTest.java b/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcOkHttpLogRecordExporterTest.java new file mode 100644 index 00000000000..3464b391bbf --- /dev/null +++ b/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcOkHttpLogRecordExporterTest.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcOkHttpLogRecordExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcOkHttpLogRecordExporterTest() { + super("log", ResourceLogs.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcLogRecordExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcLogRecordExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap( + ((OtlpGrpcLogRecordExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected LogRecordData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeLogRecordData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceLogsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcOkHttpMetricExporterTest.java b/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcOkHttpMetricExporterTest.java new file mode 100644 index 00000000000..d4eab16a75d --- /dev/null +++ b/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcOkHttpMetricExporterTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.metrics; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcOkHttpMetricExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcOkHttpMetricExporterTest() { + super("metric", ResourceMetrics.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated featurea + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcMetricExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcMetricExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcMetricExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected MetricData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeMetricData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceMetricsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcOkHttpSpanExporterTest.java b/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcOkHttpSpanExporterTest.java new file mode 100644 index 00000000000..2e797890d65 --- /dev/null +++ b/exporters/otlp/all/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcOkHttpSpanExporterTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.trace; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.ManagedChannel; +import io.grpc.inprocess.InProcessChannelBuilder; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.ManagedChannelTelemetryExporterBuilder; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.proto.trace.v1.ResourceSpans; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.Closeable; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpGrpcOkHttpSpanExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcOkHttpSpanExporterTest() { + super("span", ResourceSpans.getDefaultInstance()); + } + + @Test + @SuppressWarnings("deprecation") // testing deprecated feature + void usingGrpc() throws Exception { + ManagedChannel channel = InProcessChannelBuilder.forName("test").build(); + try (Closeable exporter = OtlpGrpcSpanExporter.builder().setChannel(channel).build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(UpstreamGrpcSender.class); + } finally { + channel.shutdownNow(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return ManagedChannelTelemetryExporterBuilder.wrap( + TelemetryExporterBuilder.wrap(OtlpGrpcSpanExporter.builder())); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcSpanExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected SpanData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeSpanData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceSpansMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterJdkSenderTest.java b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterJdkSenderTest.java new file mode 100644 index 00000000000..9c1d92972d8 --- /dev/null +++ b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/logs/OtlpHttpLogRecordExporterJdkSenderTest.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.logs; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractHttpTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.HttpLogRecordExporterBuilderWrapper; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.List; + +class OtlpHttpLogRecordExporterJdkSenderTest + extends AbstractHttpTelemetryExporterTest { + + protected OtlpHttpLogRecordExporterJdkSenderTest() { + super("log", "/v1/logs", ResourceLogs.getDefaultInstance()); + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return new HttpLogRecordExporterBuilderWrapper(OtlpHttpLogRecordExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return new HttpLogRecordExporterBuilderWrapper( + ((OtlpHttpLogRecordExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected LogRecordData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeLogRecordData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceLogsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java new file mode 100644 index 00000000000..021831a4e89 --- /dev/null +++ b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/metrics/OtlpHttpMetricExporterJdkSenderTest.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractHttpTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.HttpMetricExporterBuilderWrapper; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.jdk.internal.JdkHttpSender; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class OtlpHttpMetricExporterJdkSenderTest + extends AbstractHttpTelemetryExporterTest { + + protected OtlpHttpMetricExporterJdkSenderTest() { + super("metric", "/v1/metrics", ResourceMetrics.getDefaultInstance()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void validMetricConfig() { + assertThatCode(() -> + OtlpHttpMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred())) + .doesNotThrowAnyException(); + assertThat( + OtlpHttpMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat( + OtlpHttpMetricExporter.builder() + .build() + .getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + assertThat( + OtlpHttpMetricExporter.builder() + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.drop())) + .build() + .getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.drop()); + } + + /** Test configuration specific to metric exporter. */ + @Test + void invalidMetricConfig() { + assertThatThrownBy( + () -> OtlpHttpMetricExporter.builder().setAggregationTemporalitySelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("aggregationTemporalitySelector"); + + assertThatThrownBy(() -> OtlpHttpMetricExporter.builder().setDefaultAggregationSelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("defaultAggregationSelector"); + } + + /** Test configuration specific to metric exporter. */ + @Test + void stringRepresentation() { + try (MetricExporter metricExporter = OtlpHttpMetricExporter.builder().build()) { + assertThat(metricExporter.toString()) + .matches( + "OtlpHttpMetricExporter\\{" + + "endpoint=http://localhost:4318/v1/metrics, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "proxyOptions=null, " + + "compressorEncoding=null, " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "exportAsJson=false, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}, " + + "retryPolicy=RetryPolicy\\{.*\\}, " + + "componentLoader=.*, " + + "exporterType=OTLP_HTTP_METRIC_EXPORTER, " + + "internalTelemetrySchemaVersion=LEGACY, " + + "aggregationTemporalitySelector=AggregationTemporalitySelector\\{.*\\}, " + + "defaultAggregationSelector=DefaultAggregationSelector\\{.*\\}, " + + "memoryMode=REUSABLE_DATA" + + "\\}"); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return new HttpMetricExporterBuilderWrapper(OtlpHttpMetricExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return new HttpMetricExporterBuilderWrapper( + ((OtlpHttpMetricExporter) exporter.unwrap()).toBuilder()); + } + + @Test + void isJdkHttpSender() { + TelemetryExporter exporter = exporterBuilder().build(); + + try { + assertThat(exporter.unwrap()) + .extracting("delegate") + .extracting("httpSender") + .isInstanceOf(JdkHttpSender.class); + } finally { + exporter.shutdown(); + } + } + + @Override + protected MetricData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeMetricData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceMetricsMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterJdkSenderTest.java b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterJdkSenderTest.java new file mode 100644 index 00000000000..4b546d1d796 --- /dev/null +++ b/exporters/otlp/all/src/testJdkHttpSender/java/io/opentelemetry/exporter/otlp/http/trace/OtlpHttpSpanExporterJdkSenderTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.http.trace; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractHttpTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil; +import io.opentelemetry.exporter.otlp.testing.internal.HttpSpanExporterBuilderWrapper; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.jdk.internal.JdkHttpSender; +import io.opentelemetry.proto.trace.v1.ResourceSpans; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.util.List; +import org.junit.jupiter.api.Test; + +class OtlpHttpSpanExporterJdkSenderTest + extends AbstractHttpTelemetryExporterTest { + + protected OtlpHttpSpanExporterJdkSenderTest() { + super("span", "/v1/traces", ResourceSpans.getDefaultInstance()); + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return new HttpSpanExporterBuilderWrapper(OtlpHttpSpanExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder(TelemetryExporter exporter) { + return new HttpSpanExporterBuilderWrapper( + ((OtlpHttpSpanExporter) exporter.unwrap()).toBuilder()); + } + + @Test + void isJdkHttpSender() { + TelemetryExporter exporter = exporterBuilder().build(); + + try { + assertThat(exporter.unwrap()) + .extracting("delegate") + .extracting("httpSender") + .isInstanceOf(JdkHttpSender.class); + } finally { + exporter.shutdown(); + } + } + + @Override + protected SpanData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeSpanData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceSpansMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java new file mode 100644 index 00000000000..76077386a60 --- /dev/null +++ b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/GrpcExporterTest.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import org.junit.jupiter.api.Test; + +class GrpcExporterTest { + + @Test + void build_NoGrpcSenderProvider() { + assertThatThrownBy(() -> + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER, + Duration.ofSeconds(10), + new URI("http://localhost"), + "service/method") + .build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "No GrpcSenderProvider found on classpath. Please add dependency on " + + "opentelemetry-exporter-sender-okhttp or opentelemetry-exporter-sender-grpc-managed-channel"); + } +} diff --git a/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java new file mode 100644 index 00000000000..a8e2c7013c7 --- /dev/null +++ b/exporters/otlp/all/src/testNoSender/java/io/opentelemetry/exporter/otlp/internal/HttpExporterTest.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.internal; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import org.junit.jupiter.api.Test; + +class HttpExporterTest { + + @Test + void build_NoHttpSenderProvider() { + assertThatThrownBy(() -> + new HttpExporterBuilder( + StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER, "http://localhost") + .build()) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "No HttpSenderProvider found on classpath. Please add dependency on " + + "opentelemetry-exporter-sender-okhttp or opentelemetry-exporter-sender-jdk"); + } +} diff --git a/exporters/otlp/trace/src/testSpanPipeline/java/io/opentelemetry/exporter/otlp/trace/SpanPipelineOtlpBenchmark.java b/exporters/otlp/all/src/testSpanPipeline/java/io/opentelemetry/exporter/otlp/trace/SpanPipelineOtlpBenchmark.java similarity index 90% rename from exporters/otlp/trace/src/testSpanPipeline/java/io/opentelemetry/exporter/otlp/trace/SpanPipelineOtlpBenchmark.java rename to exporters/otlp/all/src/testSpanPipeline/java/io/opentelemetry/exporter/otlp/trace/SpanPipelineOtlpBenchmark.java index 3fc1f5f9a5a..d64e3f29d51 100644 --- a/exporters/otlp/trace/src/testSpanPipeline/java/io/opentelemetry/exporter/otlp/trace/SpanPipelineOtlpBenchmark.java +++ b/exporters/otlp/all/src/testSpanPipeline/java/io/opentelemetry/exporter/otlp/trace/SpanPipelineOtlpBenchmark.java @@ -14,6 +14,7 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Scope; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.SdkTracerProvider; @@ -23,11 +24,12 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +@SuppressLogger(BatchSpanProcessor.class) class SpanPipelineOtlpBenchmark { private static final Resource RESOURCE = Resource.create( @@ -70,11 +72,11 @@ protected CompletionStage handleMessage( } }; - private static SdkTracerProvider tracerProvider; - private static Tracer tracer; + private SdkTracerProvider tracerProvider; + private Tracer tracer; - @BeforeAll - public static void setUp() { + @BeforeEach + public void setUp() { tracerProvider = SdkTracerProvider.builder() .setResource(RESOURCE) @@ -89,12 +91,12 @@ public static void setUp() { tracer = tracerProvider.get("benchmark"); } - @AfterAll - public static void tearDown() { + @AfterEach + public void tearDown() { tracerProvider.close(); } - private static void createSpan() { + private void createSpan() { Span span = tracer.spanBuilder("POST /search").startSpan(); try (Scope ignored = span.makeCurrent()) { span.setAllAttributes(SPAN_ATTRIBUTES); @@ -109,10 +111,10 @@ void runPipeline() { long endTimeNanos = startTimeNanos + TimeUnit.SECONDS.toNanos(60); try { while (System.nanoTime() < endTimeNanos) { - SpanPipelineOtlpBenchmark.createSpan(); + createSpan(); } } finally { - SpanPipelineOtlpBenchmark.tearDown(); + tearDown(); } } } diff --git a/exporters/otlp/common/README.md b/exporters/otlp/common/README.md deleted file mode 100644 index f0805343886..00000000000 --- a/exporters/otlp/common/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenTelemetry - OTLP Common - -[![Javadocs][javadoc-image]][javadoc-url] - -This module contains common utility code used by other OpenTelemetry OTLP modules, including conversion between OpenTelemetry API or SDK objects and proto objects. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-common.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-common diff --git a/exporters/otlp/common/build.gradle.kts b/exporters/otlp/common/build.gradle.kts index 0ee39d1d86a..b451b1757aa 100644 --- a/exporters/otlp/common/build.gradle.kts +++ b/exporters/otlp/common/build.gradle.kts @@ -9,67 +9,77 @@ plugins { } description = "OpenTelemetry Protocol Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.internal") +otelJava.moduleName.set("io.opentelemetry.exporter.internal.otlp") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) -val versions: Map by project +val versions = project.property("versions") as Map<*, *> dependencies { protoSource("io.opentelemetry.proto:opentelemetry-proto:${versions["io.opentelemetry.proto"]}") - api(project(":api:all")) + annotationProcessor("com.google.auto.value:auto-value") + + api(project(":exporters:common")) compileOnly(project(":sdk:metrics")) compileOnly(project(":sdk:trace")) compileOnly(project(":sdk:logs")) - - implementation("com.squareup.okhttp3:okhttp") - - // We include helpers shared by gRPC or okhttp exporters but do not want to impose these - // dependency on all of our consumers. - compileOnly("com.fasterxml.jackson.core:jackson-core") - compileOnly("io.grpc:grpc-netty") - compileOnly("io.grpc:grpc-netty-shaded") - compileOnly("io.grpc:grpc-okhttp") - compileOnly("io.grpc:grpc-stub") - - annotationProcessor("com.google.auto.value:auto-value") + compileOnly(project(":api:incubator")) testImplementation(project(":sdk:metrics")) testImplementation(project(":sdk:trace")) testImplementation(project(":sdk:logs")) testImplementation(project(":sdk:testing")) - testImplementation("com.fasterxml.jackson.core:jackson-databind") testImplementation("com.google.protobuf:protobuf-java-util") - testImplementation("com.linecorp.armeria:armeria-junit5") + testImplementation("com.google.guava:guava") testImplementation("io.opentelemetry.proto:opentelemetry-proto") - testImplementation("org.skyscreamer:jsonassert") - testImplementation("org.assertj:assertj-core") - - testImplementation("com.google.api.grpc:proto-google-common-protos") - testImplementation("io.grpc:grpc-testing") - testRuntimeOnly("io.grpc:grpc-netty-shaded") + jmhImplementation(project(":api:incubator")) jmhImplementation(project(":sdk:testing")) - jmhImplementation(project(":sdk-extensions:resources")) - jmhImplementation("com.fasterxml.jackson.core:jackson-core") jmhImplementation("io.opentelemetry.proto:opentelemetry-proto") - jmhRuntimeOnly("io.grpc:grpc-netty") + jmhImplementation("io.grpc:grpc-netty") +} + +testing { + suites { + register("testIncubating") { + dependencies { + implementation(project(":api:incubator")) + implementation(project(":sdk:testing")) + + implementation("com.google.protobuf:protobuf-java-util") + implementation("com.google.guava:guava") + implementation("io.opentelemetry.proto:opentelemetry-proto") + } + } + } +} + +tasks { + check { + dependsOn(testing.suites) + } } wire { root( "opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest", "opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest", - "opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest" + "opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest", + "opentelemetry.proto.collector.profiles.v1development.ExportProfilesServiceRequest", + "opentelemetry.proto.processcontext.v1development.ProcessContext" ) custom { - customHandlerClass = "io.opentelemetry.gradle.ProtoFieldsWireHandler" + schemaHandlerFactoryClass = "io.opentelemetry.gradle.ProtoFieldsWireHandlerFactory" } } -sourceSets { - main { - java.srcDir("$buildDir/generated/source/wire") +// Configure JMH jar to preserve multi-release jar attribute +// so StringMarshalBenchmark can use VarHandleStringEncoder +tasks.named("jmhJar") { + manifest { + attributes["Multi-Release"] = "true" } } diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java index 5bbc501700c..1a18de10e10 100644 --- a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/GrpcGzipBenchmark.java @@ -80,9 +80,8 @@ public class GrpcGzipBenchmark { .setDescription("gauge description") .setUnit("unit") .ofLongs() - .buildWithCallback( - measurement -> - measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); + .buildWithCallback(measurement -> + measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); LongCounter longCounter = meter1 .counterBuilder("counter") @@ -125,24 +124,23 @@ public class GrpcGzipBenchmark { List resourceMetrics = Arrays.stream(ResourceMetricsMarshaler.create(metricData)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - return ResourceMetrics.parseFrom(bos.toByteArray()); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) + .map(marshaler -> { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + return ResourceMetrics.parseFrom(bos.toByteArray()); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) .collect(Collectors.toList()); METRICS_REQUEST = ExportMetricsServiceRequest.newBuilder().addAllResourceMetrics(resourceMetrics).build(); } @Benchmark - public ByteArrayOutputStream gzipCompressor() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + public TestOutputStream gzipCompressor() throws IOException { + TestOutputStream baos = new TestOutputStream(); OutputStream gzos = GZIP_CODEC.compress(baos); METRICS_REQUEST.writeTo(gzos); gzos.close(); @@ -150,8 +148,8 @@ public ByteArrayOutputStream gzipCompressor() throws IOException { } @Benchmark - public ByteArrayOutputStream identityCompressor() throws IOException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); + public TestOutputStream identityCompressor() throws IOException { + TestOutputStream baos = new TestOutputStream(); OutputStream gzos = IDENTITY_CODEC.compress(baos); METRICS_REQUEST.writeTo(gzos); gzos.close(); diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/LogsRequestMarshalerBenchmark.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/LogsRequestMarshalerBenchmark.java new file mode 100644 index 00000000000..09bc21576c2 --- /dev/null +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/LogsRequestMarshalerBenchmark.java @@ -0,0 +1,146 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.incubator.logs.ExtendedLogger; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.exporter.internal.otlp.logs.LogsRequestMarshaler; +import io.opentelemetry.exporter.internal.otlp.logs.LowAllocationLogsRequestMarshaler; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import java.io.IOException; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 10, time = 1) +@Fork(1) +public class LogsRequestMarshalerBenchmark { + + private static final Collection LOGS; + private static final LowAllocationLogsRequestMarshaler MARSHALER = + new LowAllocationLogsRequestMarshaler(); + private static final TestOutputStream OUTPUT = new TestOutputStream(); + + static { + InMemoryLogRecordExporter logRecordExporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .setResource( + Resource.create( + Attributes.builder() + .put(AttributeKey.booleanKey("key_bool"), true) + .put(AttributeKey.stringKey("key_string"), "string") + .put(AttributeKey.longKey("key_int"), 100L) + .put(AttributeKey.doubleKey("key_double"), 100.3) + .put( + AttributeKey.stringArrayKey("key_string_array"), + Arrays.asList("string", "string")) + .put(AttributeKey.longArrayKey("key_long_array"), Arrays.asList(12L, 23L)) + .put( + AttributeKey.doubleArrayKey("key_double_array"), + Arrays.asList(12.3, 23.1)) + .put( + AttributeKey.booleanArrayKey("key_boolean_array"), + Arrays.asList(true, false)) + .build())) + .addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter)) + .build(); + + Logger logger1 = loggerProvider.get("logger"); + logger1 + .logRecordBuilder() + .setBody("Hello world from this log...") + .setAllAttributes( + Attributes.builder() + .put("key_bool", true) + .put("key_String", "string") + .put("key_int", 100L) + .put("key_double", 100.3) + .build()) + .setSeverity(Severity.INFO) + .setSeverityText("INFO") + .emit(); + + ((ExtendedLogger) logger1) + .logRecordBuilder() + .setEventName("namespace.my-event-name") + .setBody( + Value.of( + KeyValue.of("stringKey", Value.of("value")), + KeyValue.of("longKey", Value.of(1)), + KeyValue.of("doubleKey", Value.of(1.0)), + KeyValue.of("boolKey", Value.of(true)), + KeyValue.of("stringArrKey", Value.of(Value.of("value1"), Value.of("value2"))), + KeyValue.of("longArrKey", Value.of(Value.of(1), Value.of(2))), + KeyValue.of("doubleArrKey", Value.of(Value.of(1.0), Value.of(2.0))), + KeyValue.of("boolArrKey", Value.of(Value.of(true), Value.of(false))), + KeyValue.of( + "key", Value.of(Collections.singletonMap("childKey1", Value.of("value")))))) + .emit(); + + LOGS = logRecordExporter.getFinishedLogRecordItems(); + } + + @Benchmark + public int marshalStateful() throws IOException { + LogsRequestMarshaler marshaler = LogsRequestMarshaler.create(LOGS); + OUTPUT.reset(); + marshaler.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } + + @Benchmark + public int marshalStatefulJson() throws IOException { + LogsRequestMarshaler marshaler = LogsRequestMarshaler.create(LOGS); + OUTPUT.reset(); + marshaler.writeJsonTo(OUTPUT); + return OUTPUT.getCount(); + } + + @Benchmark + public int marshalStateless() throws IOException { + MARSHALER.initialize(LOGS); + try { + OUTPUT.reset(); + MARSHALER.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + MARSHALER.reset(); + } + } + + @Benchmark + public int marshalStatelessJson() throws IOException { + MARSHALER.initialize(LOGS); + try { + OUTPUT.reset(); + MARSHALER.writeJsonTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + MARSHALER.reset(); + } + } +} diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MarshalerInputStreamBenchmarks.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MarshalerInputStreamBenchmarks.java index 1953abe3a24..5fda5d75640 100644 --- a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MarshalerInputStreamBenchmarks.java +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MarshalerInputStreamBenchmarks.java @@ -33,7 +33,8 @@ public class MarshalerInputStreamBenchmarks { @Threads(1) public void marshalToNettyBuffer(RequestMarshalState state) throws IOException { MarshalerInputStream stream = - new MarshalerInputStream(TraceRequestMarshaler.create(state.spanDataList)); + new MarshalerInputStream( + TraceRequestMarshaler.create(state.spanDataList).toBinaryMessageWriter()); // Roughly reproduce how grpc-netty should behave. ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(stream.available()); stream.drainTo(new ByteBufOutputStream(buf)); @@ -44,7 +45,8 @@ public void marshalToNettyBuffer(RequestMarshalState state) throws IOException { @Threads(1) public void marshalToByteArray(RequestMarshalState state) throws IOException { MarshalerInputStream stream = - new MarshalerInputStream(TraceRequestMarshaler.create(state.spanDataList)); + new MarshalerInputStream( + TraceRequestMarshaler.create(state.spanDataList).toBinaryMessageWriter()); stream.drainTo(new ByteArrayOutputStream(stream.available())); } } diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java index c15a789809f..7ce2fa1a3c1 100644 --- a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/MetricsRequestMarshalerBenchmark.java @@ -13,12 +13,12 @@ import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.api.metrics.LongUpDownCounter; import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.exporter.internal.otlp.metrics.LowAllocationMetricsRequestMarshaler; import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Arrays; import java.util.Collection; @@ -39,6 +39,9 @@ public class MetricsRequestMarshalerBenchmark { private static final Collection METRICS; + private static final LowAllocationMetricsRequestMarshaler MARSHALER = + new LowAllocationMetricsRequestMarshaler(); + private static final TestOutputStream OUTPUT = new TestOutputStream(); static { InMemoryMetricReader metricReader = InMemoryMetricReader.create(); @@ -71,9 +74,8 @@ public class MetricsRequestMarshalerBenchmark { .setDescription("gauge description") .setUnit("unit") .ofLongs() - .buildWithCallback( - measurement -> - measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); + .buildWithCallback(measurement -> + measurement.record(5, Attributes.of(AttributeKey.stringKey("key"), "value"))); LongCounter longCounter = meter1 .counterBuilder("counter") @@ -117,10 +119,42 @@ public class MetricsRequestMarshalerBenchmark { } @Benchmark - public ByteArrayOutputStream marshaler() throws IOException { + public int marshalStateful() throws IOException { MetricsRequestMarshaler marshaler = MetricsRequestMarshaler.create(METRICS); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - marshaler.writeBinaryTo(bos); - return bos; + OUTPUT.reset(); + marshaler.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } + + @Benchmark + public int marshalStatefulJson() throws IOException { + MetricsRequestMarshaler marshaler = MetricsRequestMarshaler.create(METRICS); + OUTPUT.reset(); + marshaler.writeJsonTo(OUTPUT); + return OUTPUT.getCount(); + } + + @Benchmark + public int marshalStateless() throws IOException { + MARSHALER.initialize(METRICS); + try { + OUTPUT.reset(); + MARSHALER.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + MARSHALER.reset(); + } + } + + @Benchmark + public int marshalStatelessJson() throws IOException { + MARSHALER.initialize(METRICS); + try { + OUTPUT.reset(); + MARSHALER.writeJsonTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + MARSHALER.reset(); + } } } diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/RequestMarshalBenchmarks.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/RequestMarshalBenchmarks.java index b84b5ccca0e..fbdfa290011 100644 --- a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/RequestMarshalBenchmarks.java +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/RequestMarshalBenchmarks.java @@ -5,8 +5,8 @@ package io.opentelemetry.exporter.internal.otlp; +import io.opentelemetry.exporter.internal.otlp.traces.LowAllocationTraceRequestMarshaler; import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; @@ -25,29 +25,72 @@ @Fork(1) public class RequestMarshalBenchmarks { + private static final LowAllocationTraceRequestMarshaler MARSHALER = + new LowAllocationTraceRequestMarshaler(); + private static final TestOutputStream OUTPUT = new TestOutputStream(); + @Benchmark @Threads(1) - public ByteArrayOutputStream createCustomMarshal(RequestMarshalState state) { + public int createStatefulMarshaler(RequestMarshalState state) { TraceRequestMarshaler requestMarshaler = TraceRequestMarshaler.create(state.spanDataList); - return new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + return requestMarshaler.getBinarySerializedSize(); } @Benchmark @Threads(1) - public ByteArrayOutputStream marshalCustom(RequestMarshalState state) throws IOException { + public int marshalStatefulBinary(RequestMarshalState state) throws IOException { TraceRequestMarshaler requestMarshaler = TraceRequestMarshaler.create(state.spanDataList); - ByteArrayOutputStream customOutput = - new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); - requestMarshaler.writeBinaryTo(customOutput); - return customOutput; + OUTPUT.reset(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); } @Benchmark @Threads(1) - public ByteArrayOutputStream marshalJson(RequestMarshalState state) throws IOException { + public int marshalStatefulJson(RequestMarshalState state) throws IOException { TraceRequestMarshaler requestMarshaler = TraceRequestMarshaler.create(state.spanDataList); - ByteArrayOutputStream customOutput = new ByteArrayOutputStream(); - requestMarshaler.writeJsonTo(customOutput); - return customOutput; + OUTPUT.reset(); + requestMarshaler.writeJsonTo(OUTPUT); + return OUTPUT.getCount(); + } + + @Benchmark + @Threads(1) + public int createStatelessMarshaler(RequestMarshalState state) { + LowAllocationTraceRequestMarshaler requestMarshaler = MARSHALER; + requestMarshaler.initialize(state.spanDataList); + try { + return requestMarshaler.getBinarySerializedSize(); + } finally { + requestMarshaler.reset(); + } + } + + @Benchmark + @Threads(1) + public int marshalStatelessBinary(RequestMarshalState state) throws IOException { + LowAllocationTraceRequestMarshaler requestMarshaler = MARSHALER; + requestMarshaler.initialize(state.spanDataList); + try { + OUTPUT.reset(); + requestMarshaler.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + requestMarshaler.reset(); + } + } + + @Benchmark + @Threads(1) + public int marshalStatelessJson(RequestMarshalState state) throws IOException { + LowAllocationTraceRequestMarshaler requestMarshaler = MARSHALER; + requestMarshaler.initialize(state.spanDataList); + try { + OUTPUT.reset(); + requestMarshaler.writeJsonTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + requestMarshaler.reset(); + } } } diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/StringMarshalBenchmark.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/StringMarshalBenchmark.java new file mode 100644 index 00000000000..9dfa8467638 --- /dev/null +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/StringMarshalBenchmark.java @@ -0,0 +1,152 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StringEncoder; +import io.opentelemetry.exporter.internal.marshal.StringEncoderHolder; +import java.io.IOException; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 10, time = 1) +@Fork(1) +@State(Scope.Benchmark) +public class StringMarshalBenchmark { + + @Param({"FallbackStringEncoder", "UnsafeStringEncoder", "VarHandleStringEncoder"}) + private String encoderImplementation; + + private TestMarshaler marshaler; + private static final TestOutputStream OUTPUT = new TestOutputStream(); + + @Setup + public void setup() { + StringEncoder encoder; + switch (encoderImplementation) { + case "FallbackStringEncoder": + encoder = StringEncoderHolder.createFallbackEncoder(); + break; + case "UnsafeStringEncoder": + encoder = StringEncoderHolder.createUnsafeEncoder(); + if (encoder == null) { + throw new IllegalStateException( + "UnsafeStringEncoder is not available (requires Java 9+)"); + } + break; + case "VarHandleStringEncoder": + encoder = StringEncoderHolder.createVarHandleEncoder(); + if (encoder == null) { + throw new IllegalStateException( + "VarHandleStringEncoder is not available (requires Java 9+" + + " and -jvmArgs=\"--add-opens=java.base/java.lang=ALL-UNNAMED\""); + } + break; + default: + throw new IllegalStateException("Unknown encoder implementation: " + encoderImplementation); + } + marshaler = new TestMarshaler(encoder); + } + + @Benchmark + @Threads(1) + public int marshalAsciiStringStateful(StringMarshalState state) throws IOException { + return marshalStateful(state.asciiString); + } + + @Benchmark + @Threads(1) + public int marshalLatin1StringStateful(StringMarshalState state) throws IOException { + return marshalStateful(state.latin1String); + } + + @Benchmark + @Threads(1) + public int marshalUnicodeStringStateful(StringMarshalState state) throws IOException { + return marshalStateful(state.unicodeString); + } + + private static int marshalStateful(String string) throws IOException { + OUTPUT.reset(); + Marshaler marshaler = StringAnyValueMarshaler.create(string); + marshaler.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } + + @Benchmark + @Threads(1) + public int marshalAsciiStringStateless(StringMarshalState state) throws IOException { + return marshalStateless(marshaler, state.asciiString); + } + + @Benchmark + @Threads(1) + public int marshalLatin1StringStateless(StringMarshalState state) throws IOException { + return marshalStateless(marshaler, state.latin1String); + } + + @Benchmark + @Threads(1) + public int marshalUnicodeStringStateless(StringMarshalState state) throws IOException { + return marshalStateless(marshaler, state.unicodeString); + } + + private static int marshalStateless(TestMarshaler marshaler, String string) throws IOException { + OUTPUT.reset(); + try { + marshaler.initialize(string); + marshaler.writeBinaryTo(OUTPUT); + return OUTPUT.getCount(); + } finally { + marshaler.reset(); + } + } + + private static class TestMarshaler extends Marshaler { + private final MarshalerContext context; + private int size; + private String value; + + TestMarshaler(StringEncoder encoder) { + context = new MarshalerContext(/* marshalStringNoAllocation= */ true, encoder); + } + + private void initialize(String string) { + value = string; + size = StringAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize(string, context); + } + + private void reset() { + context.reset(); + } + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + public void writeTo(Serializer output) throws IOException { + StringAnyValueStatelessMarshaler.INSTANCE.writeTo(output, value, context); + } + } +} diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/StringMarshalState.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/StringMarshalState.java new file mode 100644 index 00000000000..4d7e3aacd18 --- /dev/null +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/StringMarshalState.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; + +@State(Scope.Benchmark) +public class StringMarshalState { + + @Param("512") + int stringSize; + + String asciiString; + String latin1String; + String unicodeString; + + @Setup + public void setup() { + asciiString = makeString('a', stringSize); + latin1String = makeString('Γ€', stringSize); + unicodeString = makeString('βˆ†', stringSize); + } + + private static String makeString(char c, int size) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < size; i++) { + sb.append(c); + } + return sb.toString(); + } +} diff --git a/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/TestOutputStream.java b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/TestOutputStream.java new file mode 100644 index 00000000000..cfaba56ec3e --- /dev/null +++ b/exporters/otlp/common/src/jmh/java/io/opentelemetry/exporter/internal/otlp/TestOutputStream.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import java.io.OutputStream; + +class TestOutputStream extends OutputStream { + private int size; + private int count; + + TestOutputStream() { + this(-1); + } + + TestOutputStream(int size) { + this.size = size; + } + + @Override + public void write(int b) { + count++; + if (size > 0 && count > size) { + throw new IllegalStateException("max size exceeded"); + } + } + + void reset(int size) { + this.size = size; + this.count = 0; + } + + void reset() { + reset(-1); + } + + int getCount() { + return count; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/ExporterBuilderUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/ExporterBuilderUtil.java deleted file mode 100644 index d45bdb09283..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/ExporterBuilderUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal; - -import java.net.URI; -import java.net.URISyntaxException; - -/** - * Utilities for exporter builders. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class ExporterBuilderUtil { - - /** Validate OTLP endpoint. */ - public static URI validateEndpoint(String endpoint) { - URI uri; - try { - uri = new URI(endpoint); - } catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid endpoint, must be a URL: " + endpoint, e); - } - - if (uri.getScheme() == null - || (!uri.getScheme().equals("http") && !uri.getScheme().equals("https"))) { - throw new IllegalArgumentException( - "Invalid endpoint, must start with http:// or https://: " + uri); - } - return uri; - } - - private ExporterBuilderUtil() {} -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/ExporterMetrics.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/ExporterMetrics.java deleted file mode 100644 index bf9546532ba..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/ExporterMetrics.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal; - -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.LongCounter; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.MeterProvider; - -/** - * Helper for recording metrics from exporters. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public class ExporterMetrics { - - private static final AttributeKey ATTRIBUTE_KEY_TYPE = stringKey("type"); - private static final AttributeKey ATTRIBUTE_KEY_SUCCESS = booleanKey("success"); - - private final LongCounter seen; - private final LongCounter exported; - - private final Attributes seenAttrs; - private final Attributes successAttrs; - private final Attributes failedAttrs; - - private ExporterMetrics( - MeterProvider meterProvider, String exporterName, String type, String transportName) { - Meter meter = - meterProvider.get("io.opentelemetry.exporters." + exporterName + "-" + transportName); - seenAttrs = Attributes.builder().put(ATTRIBUTE_KEY_TYPE, type).build(); - seen = meter.counterBuilder(exporterName + ".exporter.seen").build(); - exported = meter.counterBuilder(exporterName + ".exporter.exported").build(); - successAttrs = seenAttrs.toBuilder().put(ATTRIBUTE_KEY_SUCCESS, true).build(); - failedAttrs = seenAttrs.toBuilder().put(ATTRIBUTE_KEY_SUCCESS, false).build(); - } - - /** Record number of records seen. */ - public void addSeen(long value) { - seen.add(value, seenAttrs); - } - - /** Record number of records which successfully exported. */ - public void addSuccess(long value) { - exported.add(value, successAttrs); - } - - /** Record number of records which failed to export. */ - public void addFailed(long value) { - exported.add(value, failedAttrs); - } - - /** Create an instance for recording gRPC exporter metrics. */ - public static ExporterMetrics createGrpc( - String exporterName, String type, MeterProvider meterProvider) { - return new ExporterMetrics(meterProvider, exporterName, type, "grpc"); - } - - /** Create an instance for recording gRPC OkHttp exporter metrics. */ - public static ExporterMetrics createGrpcOkHttp( - String exporterName, String type, MeterProvider meterProvider) { - return new ExporterMetrics(meterProvider, exporterName, type, "grpc-okhttp"); - } - - /** Create an instance for recording http/protobuf exporter metrics. */ - public static ExporterMetrics createHttpProtobuf( - String exporterName, String type, MeterProvider meterProvider) { - return new ExporterMetrics(meterProvider, exporterName, type, "http"); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/TlsUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/TlsUtil.java deleted file mode 100644 index 6f15d14b88b..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/TlsUtil.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal; - -import static java.util.Objects.requireNonNull; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.KeyFactory; -import java.security.KeyManagementException; -import java.security.KeyStore; -import java.security.KeyStoreException; -import java.security.NoSuchAlgorithmException; -import java.security.PrivateKey; -import java.security.UnrecoverableKeyException; -import java.security.cert.Certificate; -import java.security.cert.CertificateException; -import java.security.cert.CertificateFactory; -import java.security.cert.X509Certificate; -import java.security.spec.InvalidKeySpecException; -import java.security.spec.PKCS8EncodedKeySpec; -import java.util.ArrayList; -import java.util.List; -import javax.annotation.Nullable; -import javax.net.ssl.KeyManager; -import javax.net.ssl.KeyManagerFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509KeyManager; -import javax.net.ssl.X509TrustManager; - -/** - * Utilities for working with TLS. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class TlsUtil { - - private TlsUtil() {} - - /** Returns a {@link SSLSocketFactory} configured to use the given key and trust manager. */ - public static SSLSocketFactory sslSocketFactory( - @Nullable KeyManager keyManager, TrustManager trustManager) throws SSLException { - - SSLContext sslContext; - try { - sslContext = SSLContext.getInstance("TLS"); - if (keyManager == null) { - sslContext.init(null, new TrustManager[] {trustManager}, null); - } else { - sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null); - } - } catch (NoSuchAlgorithmException | KeyManagementException e) { - throw new SSLException( - "Could not set trusted certificates for TLS connection, are they valid " - + "X.509 in PEM format?", - e); - } - return sslContext.getSocketFactory(); - } - - /** - * Creates {@link KeyManager} initiaded by keystore containing single private key with matching - * certificate chain. - */ - public static X509KeyManager keyManager(byte[] privateKeyPem, byte[] certificatePem) - throws SSLException { - requireNonNull(privateKeyPem, "privateKeyPem"); - requireNonNull(certificatePem, "certificatePem"); - try { - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null); - KeyFactory factory = KeyFactory.getInstance("RSA"); - PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyPem); - PrivateKey key = factory.generatePrivate(keySpec); - - CertificateFactory cf = CertificateFactory.getInstance("X.509"); - - List chain = new ArrayList<>(); - - ByteArrayInputStream is = new ByteArrayInputStream(certificatePem); - while (is.available() > 0) { - chain.add(cf.generateCertificate(is)); - } - - ks.setKeyEntry("trusted", key, "".toCharArray(), chain.toArray(new Certificate[] {})); - - KeyManagerFactory kmf = - KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - kmf.init(ks, "".toCharArray()); - return (X509KeyManager) kmf.getKeyManagers()[0]; - } catch (CertificateException - | KeyStoreException - | IOException - | NoSuchAlgorithmException - | UnrecoverableKeyException - | InvalidKeySpecException e) { - throw new SSLException("Could not build KeyManagerFactory from clientKeysPem.", e); - } - } - - /** Returns a {@link TrustManager} for the given trusted certificates. */ - public static X509TrustManager trustManager(byte[] trustedCertificatesPem) throws SSLException { - requireNonNull(trustedCertificatesPem, "trustedCertificatesPem"); - try { - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - ks.load(null); - - ByteArrayInputStream is = new ByteArrayInputStream(trustedCertificatesPem); - CertificateFactory factory = CertificateFactory.getInstance("X.509"); - int i = 0; - while (is.available() > 0) { - X509Certificate cert = (X509Certificate) factory.generateCertificate(is); - ks.setCertificateEntry("cert_" + i, cert); - i++; - } - - TrustManagerFactory tmf = - TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); - tmf.init(ks); - return (X509TrustManager) tmf.getTrustManagers()[0]; - } catch (CertificateException | KeyStoreException | IOException | NoSuchAlgorithmException e) { - throw new SSLException("Could not build TrustManagerFactory from trustedCertificatesPem.", e); - } - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/DefaultGrpcExporter.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/DefaultGrpcExporter.java deleted file mode 100644 index 8a31f67bd4d..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/DefaultGrpcExporter.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.Futures; -import com.google.common.util.concurrent.MoreExecutors; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.ExporterMetrics; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ThrottlingLogger; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.checkerframework.checker.nullness.qual.Nullable; - -/** - * A {@link GrpcExporter} which uses the standard grpc-java library. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class DefaultGrpcExporter implements GrpcExporter { - - private static final Logger internalLogger = - Logger.getLogger(DefaultGrpcExporter.class.getName()); - - private final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); - - // We only log unavailable once since it's a configuration issue that won't be recovered. - private final AtomicBoolean loggedUnimplemented = new AtomicBoolean(); - - private final String type; - private final ExporterMetrics exporterMetrics; - private final ManagedChannel managedChannel; - private final MarshalerServiceStub stub; - private final long timeoutNanos; - - /** Creates a new {@link DefaultGrpcExporter}. */ - DefaultGrpcExporter( - String exporterName, - String type, - ManagedChannel channel, - MarshalerServiceStub stub, - MeterProvider meterProvider, - long timeoutNanos) { - this.type = type; - this.exporterMetrics = ExporterMetrics.createGrpc(exporterName, type, meterProvider); - this.managedChannel = channel; - this.timeoutNanos = timeoutNanos; - this.stub = stub; - } - - @Override - public CompletableResultCode export(T exportRequest, int numItems) { - exporterMetrics.addSeen(numItems); - - CompletableResultCode result = new CompletableResultCode(); - - MarshalerServiceStub stub = this.stub; - if (timeoutNanos > 0) { - stub = stub.withDeadlineAfter(timeoutNanos, TimeUnit.NANOSECONDS); - } - Futures.addCallback( - stub.export(exportRequest), - new FutureCallback() { - @Override - public void onSuccess(@Nullable Object unused) { - exporterMetrics.addSuccess(numItems); - result.succeed(); - } - - @Override - public void onFailure(Throwable t) { - exporterMetrics.addFailed(numItems); - Status status = Status.fromThrowable(t); - switch (status.getCode()) { - case UNIMPLEMENTED: - if (loggedUnimplemented.compareAndSet(false, true)) { - GrpcExporterUtil.logUnimplemented(internalLogger, type, status.getDescription()); - } - break; - case UNAVAILABLE: - logger.log( - Level.SEVERE, - "Failed to export " - + type - + "s. Server is UNAVAILABLE. " - + "Make sure your collector is running and reachable from this network. " - + "Full error message:" - + status.getDescription()); - break; - default: - logger.log( - Level.WARNING, - "Failed to export " - + type - + "s. Server responded with gRPC status code " - + status.getCode().value() - + ". Error message: " - + status.getDescription()); - break; - } - if (logger.isLoggable(Level.FINEST)) { - logger.log(Level.FINEST, "Failed to export " + type + "s. Details follow: " + t); - } - result.fail(); - } - }, - MoreExecutors.directExecutor()); - - return result; - } - - @Override - public CompletableResultCode shutdown() { - if (managedChannel.isTerminated()) { - return CompletableResultCode.ofSuccess(); - } - return ManagedChannelUtil.shutdownChannel(managedChannel); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/DefaultGrpcExporterBuilder.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/DefaultGrpcExporterBuilder.java deleted file mode 100644 index 95d3703090f..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/DefaultGrpcExporterBuilder.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import static io.grpc.Metadata.ASCII_STRING_MARSHALLER; -import static io.opentelemetry.exporter.internal.grpc.ManagedChannelUtil.toServiceConfig; - -import io.grpc.Codec; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Metadata; -import io.grpc.stub.MetadataUtils; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.ExporterBuilderUtil; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import javax.annotation.Nullable; -import javax.net.ssl.SSLException; - -/** - * A builder for {@link DefaultGrpcExporter}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class DefaultGrpcExporterBuilder - implements GrpcExporterBuilder { - - private final String exporterName; - private final String type; - private final Function> stubFactory; - private final String grpcServiceName; - - @Nullable private ManagedChannel channel; - private long timeoutNanos; - private URI endpoint; - private boolean compressionEnabled = false; - @Nullable private Metadata metadata; - @Nullable private byte[] trustedCertificatesPem; - @Nullable private byte[] privateKeyPem; - @Nullable private byte[] certificatePem; - @Nullable RetryPolicy retryPolicy; - private MeterProvider meterProvider = MeterProvider.noop(); - - /** Creates a new {@link DefaultGrpcExporterBuilder}. */ - // Visible for testing - public DefaultGrpcExporterBuilder( - String exporterName, - String type, - Function> stubFactory, - long defaultTimeoutSecs, - URI defaultEndpoint, - String grpcServiceName) { - this.exporterName = exporterName; - this.type = type; - this.stubFactory = stubFactory; - this.grpcServiceName = grpcServiceName; - timeoutNanos = TimeUnit.SECONDS.toNanos(defaultTimeoutSecs); - endpoint = defaultEndpoint; - } - - @Override - public DefaultGrpcExporterBuilder setChannel(ManagedChannel channel) { - this.channel = channel; - return this; - } - - @Override - public DefaultGrpcExporterBuilder setTimeout(long timeout, TimeUnit unit) { - timeoutNanos = unit.toNanos(timeout); - return this; - } - - @Override - public DefaultGrpcExporterBuilder setTimeout(Duration timeout) { - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - @Override - public DefaultGrpcExporterBuilder setEndpoint(String endpoint) { - this.endpoint = ExporterBuilderUtil.validateEndpoint(endpoint); - return this; - } - - @Override - public DefaultGrpcExporterBuilder setCompression(String compressionMethod) { - this.compressionEnabled = true; - return this; - } - - @Override - public DefaultGrpcExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - this.trustedCertificatesPem = trustedCertificatesPem; - return this; - } - - @Override - public GrpcExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - this.privateKeyPem = privateKeyPem; - this.certificatePem = certificatePem; - return this; - } - - @Override - public DefaultGrpcExporterBuilder addHeader(String key, String value) { - if (metadata == null) { - metadata = new Metadata(); - } - metadata.put(Metadata.Key.of(key, ASCII_STRING_MARSHALLER), value); - return this; - } - - @Override - public GrpcExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - @Override - public GrpcExporterBuilder setMeterProvider(MeterProvider meterProvider) { - this.meterProvider = meterProvider; - return this; - } - - @Override - public GrpcExporter build() { - ManagedChannel channel = this.channel; - if (channel == null) { - ManagedChannelBuilder managedChannelBuilder = - ManagedChannelBuilder.forTarget(endpoint.getAuthority()); - - if (endpoint.getScheme().equals("https")) { - managedChannelBuilder.useTransportSecurity(); - } else { - managedChannelBuilder.usePlaintext(); - } - - if (metadata != null) { - managedChannelBuilder.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata)); - } - - if (trustedCertificatesPem != null) { - try { - ManagedChannelUtil.setClientKeysAndTrustedCertificatesPem( - managedChannelBuilder, privateKeyPem, certificatePem, trustedCertificatesPem); - } catch (SSLException e) { - throw new IllegalStateException( - "Could not set trusted certificates for gRPC TLS connection, are they valid " - + "X.509 in PEM format?", - e); - } - } - - if (retryPolicy != null) { - managedChannelBuilder.defaultServiceConfig(toServiceConfig(grpcServiceName, retryPolicy)); - } - - channel = managedChannelBuilder.build(); - } - - Codec codec = compressionEnabled ? new Codec.Gzip() : Codec.Identity.NONE; - MarshalerServiceStub stub = - stubFactory.apply(channel).withCompression(codec.getMessageEncoding()); - return new DefaultGrpcExporter<>( - exporterName, type, channel, stub, meterProvider, timeoutNanos); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporter.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporter.java deleted file mode 100644 index 8add9ede976..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporter.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import java.net.URI; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * An exporter of a {@link Marshaler} using the gRPC wire format. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface GrpcExporter { - - /** Returns a new {@link GrpcExporterBuilder}. */ - static GrpcExporterBuilder builder( - String exporterName, - String type, - long defaultTimeoutSecs, - URI defaultEndpoint, - Supplier>> stubFactory, - String grpcServiceName, - String grpcEndpointPath) { - return GrpcExporterUtil.exporterBuilder( - exporterName, - type, - defaultTimeoutSecs, - defaultEndpoint, - stubFactory, - grpcServiceName, - grpcEndpointPath); - } - - /** - * Exports the {@code exportRequest} which is a request {@link Marshaler} for {@code numItems} - * items. - */ - CompletableResultCode export(T exportRequest, int numItems); - - /** Shuts the exporter down. */ - CompletableResultCode shutdown(); -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporterBuilder.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporterBuilder.java deleted file mode 100644 index 8dbe616d106..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporterBuilder.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.grpc.ManagedChannel; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** - * A builder for {@link GrpcExporter}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface GrpcExporterBuilder { - GrpcExporterBuilder setChannel(ManagedChannel channel); - - GrpcExporterBuilder setTimeout(long timeout, TimeUnit unit); - - GrpcExporterBuilder setTimeout(Duration timeout); - - GrpcExporterBuilder setEndpoint(String endpoint); - - GrpcExporterBuilder setCompression(String compressionMethod); - - GrpcExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem); - - GrpcExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem); - - GrpcExporterBuilder addHeader(String key, String value); - - GrpcExporterBuilder setRetryPolicy(RetryPolicy retryPolicy); - - GrpcExporterBuilder setMeterProvider(MeterProvider meterProvider); - - GrpcExporter build(); -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporterUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporterUtil.java deleted file mode 100644 index e21f94d6779..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcExporterUtil.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import java.net.URI; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; - -final class GrpcExporterUtil { - - private static final boolean USE_OKHTTP; - - static { - boolean useOkhttp = true; - // Use the OkHttp exporter unless grpc-stub is on the classpath. - try { - Class.forName("io.grpc.stub.AbstractStub"); - useOkhttp = false; - } catch (ClassNotFoundException e) { - // Fall through - } - USE_OKHTTP = useOkhttp; - } - - static GrpcExporterBuilder exporterBuilder( - String exporterName, - String type, - long defaultTimeoutSecs, - URI defaultEndpoint, - Supplier>> stubFactory, - String grpcServiceName, - String grpcEndpointPath) { - if (USE_OKHTTP) { - return new OkHttpGrpcExporterBuilder<>( - exporterName, type, grpcEndpointPath, defaultTimeoutSecs, defaultEndpoint); - } else { - return new DefaultGrpcExporterBuilder<>( - exporterName, - type, - stubFactory.get(), - defaultTimeoutSecs, - defaultEndpoint, - grpcServiceName); - } - } - - static void logUnimplemented(Logger logger, String type, @Nullable String fullErrorMessage) { - String envVar; - switch (type) { - case "span": - envVar = "OTLP_TRACES_EXPORTER"; - break; - case "metric": - envVar = "OTLP_METRICS_EXPORTER"; - break; - case "log": - envVar = "OTLP_LOGS_EXPORTER"; - break; - default: - throw new IllegalStateException( - "Unrecognized type, this is a programming bug in the OpenTelemetry SDK"); - } - - logger.log( - Level.SEVERE, - "Failed to export " - + type - + "s. Server responded with UNIMPLEMENTED. " - + "This usually means that your collector is not configured with an otlp " - + "receiver in the \"pipelines\" section of the configuration. " - + "If export is not desired and you are using OpenTelemetry autoconfiguration or the javaagent, " - + "disable export by setting " - + envVar - + "=none. " - + "Full error message: " - + fullErrorMessage); - } - - private GrpcExporterUtil() {} -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcRequestBody.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcRequestBody.java deleted file mode 100644 index 0fb28914a80..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcRequestBody.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import java.io.IOException; -import javax.annotation.Nullable; -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okio.Buffer; -import okio.BufferedSink; -import okio.GzipSink; -import okio.Okio; - -/** - * A {@link RequestBody} for reading from a {@link Marshaler} and writing in gRPC wire format. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class GrpcRequestBody extends RequestBody { - - private static final int HEADER_LENGTH = 5; - - private static final byte UNCOMPRESSED_FLAG = 0; - private static final byte COMPRESSED_FLAG = 1; - - private static final MediaType GRPC_MEDIA_TYPE = MediaType.parse("application/grpc"); - - private final Marshaler marshaler; - private final int messageSize; - private final int contentLength; - private final boolean compressed; - - /** Creates a new {@link GrpcRequestBody}. */ - public GrpcRequestBody(Marshaler marshaler, boolean compressed) { - this.marshaler = marshaler; - this.compressed = compressed; - - messageSize = marshaler.getBinarySerializedSize(); - if (compressed) { - // Content length not known since we want to compress on the I/O thread. - contentLength = -1; - } else { - contentLength = HEADER_LENGTH + messageSize; - } - } - - @Nullable - @Override - public MediaType contentType() { - return GRPC_MEDIA_TYPE; - } - - @Override - public long contentLength() { - return contentLength; - } - - @Override - public void writeTo(BufferedSink sink) throws IOException { - if (!compressed) { - sink.writeByte(UNCOMPRESSED_FLAG); - sink.writeInt(messageSize); - marshaler.writeBinaryTo(sink.outputStream()); - } else { - try (Buffer compressedBody = new Buffer()) { - try (BufferedSink gzipSink = Okio.buffer(new GzipSink(compressedBody))) { - marshaler.writeBinaryTo(gzipSink.outputStream()); - } - sink.writeByte(COMPRESSED_FLAG); - int compressedBytes = (int) compressedBody.size(); - sink.writeInt(compressedBytes); - sink.write(compressedBody, compressedBytes); - } - } - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcStatusUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcStatusUtil.java deleted file mode 100644 index a906f65684b..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/GrpcStatusUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.opentelemetry.exporter.internal.marshal.CodedInputStream; -import java.io.IOException; - -/** - * Utilities for working with gRPC status without requiring dependencies on gRPC. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class GrpcStatusUtil { - - public static final String GRPC_STATUS_CANCELLED = "1"; - public static final String GRPC_STATUS_DEADLINE_EXCEEDED = "4"; - public static final String GRPC_STATUS_RESOURCE_EXHAUSTED = "8"; - public static final String GRPC_STATUS_ABORTED = "10"; - public static final String GRPC_STATUS_OUT_OF_RANGE = "11"; - public static final String GRPC_STATUS_UNIMPLEMENTED = "12"; - public static final String GRPC_STATUS_UNAVAILABLE = "14"; - public static final String GRPC_STATUS_DATA_LOSS = "15"; - - /** Parses the message out of a serialized gRPC Status. */ - public static String getStatusMessage(byte[] serializedStatus) throws IOException { - CodedInputStream input = CodedInputStream.newInstance(serializedStatus); - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 18: - return input.readStringRequireUtf8(); - default: - input.skipField(tag); - break; - } - } - // Serialized Status proto had no message, proto always defaults to empty string when not found. - return ""; - } - - private GrpcStatusUtil() {} -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/ManagedChannelUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/ManagedChannelUtil.java deleted file mode 100644 index ce8972b6c61..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/ManagedChannelUtil.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import static java.util.Objects.requireNonNull; -import static java.util.stream.Collectors.toList; - -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.netty.GrpcSslContexts; -import io.grpc.netty.NettyChannelBuilder; -import io.opentelemetry.exporter.internal.TlsUtil; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.sdk.common.CompletableResultCode; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import javax.net.ssl.SSLException; -import javax.net.ssl.X509KeyManager; -import javax.net.ssl.X509TrustManager; - -/** - * Utilities for working with gRPC channels. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class ManagedChannelUtil { - - private static final Logger logger = Logger.getLogger(ManagedChannelUtil.class.getName()); - - /** - * Configure the channel builder to trust the certificates. The {@code byte[]} should contain an - * X.509 certificate collection in PEM format. - * - * @throws SSLException if error occur processing the certificates - */ - public static void setClientKeysAndTrustedCertificatesPem( - ManagedChannelBuilder managedChannelBuilder, - @Nullable byte[] privateKeyPem, - @Nullable byte[] certificatePem, - byte[] trustedCertificatesPem) - throws SSLException { - requireNonNull(managedChannelBuilder, "managedChannelBuilder"); - requireNonNull(trustedCertificatesPem, "trustedCertificatesPem"); - - X509TrustManager tmf = TlsUtil.trustManager(trustedCertificatesPem); - X509KeyManager kmf = null; - if (privateKeyPem != null && certificatePem != null) { - kmf = TlsUtil.keyManager(privateKeyPem, certificatePem); - } - - // gRPC does not abstract TLS configuration so we need to check the implementation and act - // accordingly. - if (managedChannelBuilder.getClass().getName().equals("io.grpc.netty.NettyChannelBuilder")) { - NettyChannelBuilder nettyBuilder = (NettyChannelBuilder) managedChannelBuilder; - nettyBuilder.sslContext( - GrpcSslContexts.forClient().keyManager(kmf).trustManager(tmf).build()); - } else if (managedChannelBuilder - .getClass() - .getName() - .equals("io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder")) { - io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder nettyBuilder = - (io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder) managedChannelBuilder; - nettyBuilder.sslContext( - io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts.forClient() - .trustManager(tmf) - .keyManager(kmf) - .build()); - } else if (managedChannelBuilder - .getClass() - .getName() - .equals("io.grpc.okhttp.OkHttpChannelBuilder")) { - io.grpc.okhttp.OkHttpChannelBuilder okHttpBuilder = - (io.grpc.okhttp.OkHttpChannelBuilder) managedChannelBuilder; - okHttpBuilder.sslSocketFactory(TlsUtil.sslSocketFactory(kmf, tmf)); - } else { - throw new SSLException( - "TLS certificate configuration not supported for unrecognized ManagedChannelBuilder " - + managedChannelBuilder.getClass().getName()); - } - } - - /** - * Convert the {@link RetryPolicy} into a gRPC service config for the {@code serviceName}. The - * resulting map can be passed to {@link ManagedChannelBuilder#defaultServiceConfig(Map)}. - */ - public static Map toServiceConfig(String serviceName, RetryPolicy retryPolicy) { - List retryableStatusCodes = - RetryUtil.retryableGrpcStatusCodes().stream().map(Double::parseDouble).collect(toList()); - - Map retryConfig = new HashMap<>(); - retryConfig.put("retryableStatusCodes", retryableStatusCodes); - retryConfig.put("maxAttempts", (double) retryPolicy.getMaxAttempts()); - retryConfig.put("initialBackoff", retryPolicy.getInitialBackoff().toMillis() / 1000.0 + "s"); - retryConfig.put("maxBackoff", retryPolicy.getMaxBackoff().toMillis() / 1000.0 + "s"); - retryConfig.put("backoffMultiplier", retryPolicy.getBackoffMultiplier()); - - Map methodConfig = new HashMap<>(); - methodConfig.put( - "name", Collections.singletonList(Collections.singletonMap("service", serviceName))); - methodConfig.put("retryPolicy", retryConfig); - - return Collections.singletonMap("methodConfig", Collections.singletonList(methodConfig)); - } - - /** Shutdown the gRPC channel. */ - public static CompletableResultCode shutdownChannel(ManagedChannel managedChannel) { - CompletableResultCode result = new CompletableResultCode(); - managedChannel.shutdown(); - // Remove thread creation if gRPC adds an asynchronous shutdown API. - // https://github.com/grpc/grpc-java/issues/8432 - Thread thread = - new Thread( - () -> { - try { - managedChannel.awaitTermination(10, TimeUnit.SECONDS); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - logger.log(Level.WARNING, "Failed to shutdown the gRPC channel", e); - result.fail(); - } - result.succeed(); - }); - thread.setDaemon(true); - thread.setName("grpc-cleanup"); - thread.start(); - return result; - } - - private ManagedChannelUtil() {} -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerServiceStub.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerServiceStub.java deleted file mode 100644 index 2fe9e1685ad..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/MarshalerServiceStub.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import com.google.common.util.concurrent.ListenableFuture; -import io.grpc.CallOptions; -import io.grpc.Channel; -import io.grpc.stub.AbstractFutureStub; -import io.opentelemetry.exporter.internal.marshal.Marshaler; - -/** - * A gRPC stub that uses a {@link Marshaler}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public abstract class MarshalerServiceStub< - T extends Marshaler, U, S extends MarshalerServiceStub> - extends AbstractFutureStub { - protected MarshalerServiceStub(Channel channel, CallOptions callOptions) { - super(channel, callOptions); - } - - public abstract ListenableFuture export(T request); -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/OkHttpGrpcExporter.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/OkHttpGrpcExporter.java deleted file mode 100644 index 2041bbd9494..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/OkHttpGrpcExporter.java +++ /dev/null @@ -1,258 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: - -/* - * Copyright 2014 The gRPC Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.ExporterMetrics; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ThrottlingLogger; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; - -/** - * A {@link GrpcExporter} which uses OkHttp instead of grpc-java. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class OkHttpGrpcExporter implements GrpcExporter { - - private static final String GRPC_STATUS = "grpc-status"; - private static final String GRPC_MESSAGE = "grpc-message"; - - private static final Logger internalLogger = Logger.getLogger(OkHttpGrpcExporter.class.getName()); - - private final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); - - // We only log unimplemented once since it's a configuration issue that won't be recovered. - private final AtomicBoolean loggedUnimplemented = new AtomicBoolean(); - - private final String type; - private final ExporterMetrics exporterMetrics; - private final OkHttpClient client; - private final String endpoint; - private final Headers headers; - private final boolean compressionEnabled; - - /** Creates a new {@link OkHttpGrpcExporter}. */ - OkHttpGrpcExporter( - String exporterName, - String type, - OkHttpClient client, - MeterProvider meterProvider, - String endpoint, - Headers headers, - boolean compressionEnabled) { - this.type = type; - this.exporterMetrics = ExporterMetrics.createGrpcOkHttp(exporterName, type, meterProvider); - this.client = client; - this.endpoint = endpoint; - this.headers = headers; - this.compressionEnabled = compressionEnabled; - } - - @Override - public CompletableResultCode export(T exportRequest, int numItems) { - exporterMetrics.addSeen(numItems); - - Request.Builder requestBuilder = new Request.Builder().url(endpoint).headers(headers); - - RequestBody requestBody = new GrpcRequestBody(exportRequest, compressionEnabled); - requestBuilder.post(requestBody); - - CompletableResultCode result = new CompletableResultCode(); - - client - .newCall(requestBuilder.build()) - .enqueue( - new Callback() { - @Override - public void onFailure(Call call, IOException e) { - exporterMetrics.addFailed(numItems); - logger.log( - Level.SEVERE, - "Failed to export " - + type - + "s. The request could not be executed. Full error message: " - + e.getMessage()); - result.fail(); - } - - @Override - public void onResponse(Call call, Response response) { - // Response body is empty but must be consumed to access trailers. - try { - response.body().bytes(); - } catch (IOException e) { - logger.log( - Level.WARNING, - "Failed to export " + type + "s, could not consume server response.", - e); - exporterMetrics.addFailed(numItems); - result.fail(); - return; - } - - String status = grpcStatus(response); - if ("0".equals(status)) { - exporterMetrics.addSuccess(numItems); - result.succeed(); - return; - } - - exporterMetrics.addFailed(numItems); - - String codeMessage = - status != null - ? "gRPC status code " + status - : "HTTP status code " + response.code(); - String errorMessage = grpcMessage(response); - - if (GrpcStatusUtil.GRPC_STATUS_UNIMPLEMENTED.equals(status)) { - if (loggedUnimplemented.compareAndSet(false, true)) { - GrpcExporterUtil.logUnimplemented(internalLogger, type, errorMessage); - } - } else if (GrpcStatusUtil.GRPC_STATUS_UNAVAILABLE.equals(status)) { - logger.log( - Level.SEVERE, - "Failed to export " - + type - + "s. Server is UNAVAILABLE. " - + "Make sure your collector is running and reachable from this network. " - + "Full error message:" - + errorMessage); - } else { - logger.log( - Level.WARNING, - "Failed to export " - + type - + "s. Server responded with " - + codeMessage - + ". Error message: " - + errorMessage); - } - result.fail(); - } - }); - - return result; - } - - @Nullable - private static String grpcStatus(Response response) { - // Status can either be in the headers or trailers depending on error - String grpcStatus = response.header(GRPC_STATUS); - if (grpcStatus == null) { - try { - grpcStatus = response.trailers().get(GRPC_STATUS); - } catch (IOException e) { - // Could not read a status, this generally means the HTTP status is the error. - return null; - } - } - return grpcStatus; - } - - private static String grpcMessage(Response response) { - String message = response.header(GRPC_MESSAGE); - if (message == null) { - try { - message = response.trailers().get(GRPC_MESSAGE); - } catch (IOException e) { - // Fall through - } - } - if (message != null) { - return unescape(message); - } - // Couldn't get message for some reason, use the HTTP status. - return response.message(); - } - - @Override - public CompletableResultCode shutdown() { - client.dispatcher().cancelAll(); - client.dispatcher().executorService().shutdownNow(); - client.connectionPool().evictAll(); - return CompletableResultCode.ofSuccess(); - } - - /** Whether response is retriable or not. */ - public static boolean isRetryable(Response response) { - // Only retry on gRPC codes which will always come with an HTTP success - if (!response.isSuccessful()) { - return false; - } - - // We don't check trailers for retry since retryable error codes always come with response - // headers, not trailers, in practice. - String grpcStatus = response.header(GRPC_STATUS); - return RetryUtil.retryableGrpcStatusCodes().contains(grpcStatus); - } - - // From grpc-java - - /** Unescape the provided ascii to a unicode {@link String}. */ - private static String unescape(String value) { - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c < ' ' || c >= '~' || (c == '%' && i + 2 < value.length())) { - return doUnescape(value.getBytes(StandardCharsets.US_ASCII)); - } - } - return value; - } - - private static String doUnescape(byte[] value) { - ByteBuffer buf = ByteBuffer.allocate(value.length); - for (int i = 0; i < value.length; ) { - if (value[i] == '%' && i + 2 < value.length) { - try { - buf.put((byte) Integer.parseInt(new String(value, i + 1, 2, StandardCharsets.UTF_8), 16)); - i += 3; - continue; - } catch (NumberFormatException e) { - // ignore, fall through, just push the bytes. - } - } - buf.put(value[i]); - i += 1; - } - return new String(buf.array(), 0, buf.position(), StandardCharsets.UTF_8); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/OkHttpGrpcExporterBuilder.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/OkHttpGrpcExporterBuilder.java deleted file mode 100644 index 119759c42ca..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/grpc/OkHttpGrpcExporterBuilder.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import io.grpc.ManagedChannel; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.ExporterBuilderUtil; -import io.opentelemetry.exporter.internal.TlsUtil; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.okhttp.OkHttpUtil; -import io.opentelemetry.exporter.internal.retry.RetryInterceptor; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; -import javax.net.ssl.SSLException; -import javax.net.ssl.X509KeyManager; -import javax.net.ssl.X509TrustManager; -import okhttp3.Headers; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; - -/** - * A builder for {@link OkHttpGrpcExporter}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class OkHttpGrpcExporterBuilder - implements GrpcExporterBuilder { - - private final String exporterName; - private final String type; - private final String grpcEndpointPath; - - private long timeoutNanos; - private URI endpoint; - private boolean compressionEnabled = false; - private final Headers.Builder headers = new Headers.Builder(); - @Nullable private byte[] trustedCertificatesPem; - @Nullable private byte[] privateKeyPem; - @Nullable private byte[] certificatePem; - @Nullable private RetryPolicy retryPolicy; - private MeterProvider meterProvider = MeterProvider.noop(); - - /** Creates a new {@link OkHttpGrpcExporterBuilder}. */ - // Visible for testing - public OkHttpGrpcExporterBuilder( - String exporterName, - String type, - String grpcEndpointPath, - long defaultTimeoutSecs, - URI defaultEndpoint) { - this.exporterName = exporterName; - this.type = type; - this.grpcEndpointPath = grpcEndpointPath; - timeoutNanos = TimeUnit.SECONDS.toNanos(defaultTimeoutSecs); - endpoint = defaultEndpoint; - } - - @Override - public OkHttpGrpcExporterBuilder setChannel(ManagedChannel channel) { - throw new UnsupportedOperationException("Only available on DefaultGrpcExporter"); - } - - @Override - public OkHttpGrpcExporterBuilder setTimeout(long timeout, TimeUnit unit) { - timeoutNanos = unit.toNanos(timeout); - return this; - } - - @Override - public OkHttpGrpcExporterBuilder setTimeout(Duration timeout) { - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - @Override - public OkHttpGrpcExporterBuilder setEndpoint(String endpoint) { - this.endpoint = ExporterBuilderUtil.validateEndpoint(endpoint); - return this; - } - - @Override - public OkHttpGrpcExporterBuilder setCompression(String compressionMethod) { - this.compressionEnabled = true; - return this; - } - - @Override - public OkHttpGrpcExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - this.trustedCertificatesPem = trustedCertificatesPem; - return this; - } - - @Override - public GrpcExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - this.privateKeyPem = privateKeyPem; - this.certificatePem = certificatePem; - return this; - } - - @Override - public OkHttpGrpcExporterBuilder addHeader(String key, String value) { - headers.add(key, value); - return this; - } - - @Override - public GrpcExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - @Override - public GrpcExporterBuilder setMeterProvider(MeterProvider meterProvider) { - this.meterProvider = meterProvider; - return this; - } - - @Override - public GrpcExporter build() { - OkHttpClient.Builder clientBuilder = - new OkHttpClient.Builder().dispatcher(OkHttpUtil.newDispatcher()); - - clientBuilder.callTimeout(Duration.ofNanos(timeoutNanos)); - - if (trustedCertificatesPem != null) { - try { - X509TrustManager trustManager = TlsUtil.trustManager(trustedCertificatesPem); - X509KeyManager keyManager = null; - if (privateKeyPem != null && certificatePem != null) { - keyManager = TlsUtil.keyManager(privateKeyPem, certificatePem); - } - clientBuilder.sslSocketFactory( - TlsUtil.sslSocketFactory(keyManager, trustManager), trustManager); - } catch (SSLException e) { - throw new IllegalStateException( - "Could not set trusted certificates, are they valid X.509 in PEM format?", e); - } - } - - String endpoint = this.endpoint.resolve(grpcEndpointPath).toString(); - if (endpoint.startsWith("http://")) { - clientBuilder.protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE)); - } else { - clientBuilder.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); - } - - headers.add("te", "trailers"); - if (compressionEnabled) { - headers.add("grpc-encoding", "gzip"); - } - - if (retryPolicy != null) { - clientBuilder.addInterceptor( - new RetryInterceptor(retryPolicy, OkHttpGrpcExporter::isRetryable)); - } - - return new OkHttpGrpcExporter<>( - exporterName, - type, - clientBuilder.build(), - meterProvider, - endpoint, - headers.build(), - compressionEnabled); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonSerializer.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonSerializer.java deleted file mode 100644 index 75430d69752..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/JsonSerializer.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.marshal; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.charset.StandardCharsets; -import java.util.List; - -final class JsonSerializer extends Serializer { - - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - - private final JsonGenerator generator; - - JsonSerializer(OutputStream output) throws IOException { - this(JSON_FACTORY.createGenerator(output)); - } - - JsonSerializer(JsonGenerator generator) { - this.generator = generator; - } - - @Override - protected void writeTraceId(ProtoFieldInfo field, String traceId) throws IOException { - generator.writeStringField(field.getJsonName(), traceId); - } - - @Override - protected void writeSpanId(ProtoFieldInfo field, String spanId) throws IOException { - generator.writeStringField(field.getJsonName(), spanId); - } - - @Override - public void writeBool(ProtoFieldInfo field, boolean value) throws IOException { - generator.writeBooleanField(field.getJsonName(), value); - } - - @Override - protected void writeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) throws IOException { - generator.writeStringField(field.getJsonName(), enumValue.getJsonName()); - } - - @Override - protected void writeUint32(ProtoFieldInfo field, int value) throws IOException { - generator.writeNumberField(field.getJsonName(), value); - } - - @Override - protected void writeSInt32(ProtoFieldInfo field, int value) throws IOException { - generator.writeNumberField(field.getJsonName(), value); - } - - @Override - protected void writeint32(ProtoFieldInfo field, int value) throws IOException { - generator.writeNumberField(field.getJsonName(), value); - } - - @Override - public void writeInt64(ProtoFieldInfo field, long value) throws IOException { - generator.writeStringField(field.getJsonName(), Long.toString(value)); - } - - @Override - protected void writeFixed64(ProtoFieldInfo field, long value) throws IOException { - generator.writeStringField(field.getJsonName(), Long.toString(value)); - } - - @Override - protected void writeFixed64Value(long value) throws IOException { - generator.writeString(Long.toString(value)); - } - - @Override - protected void writeUInt64Value(long value) throws IOException { - generator.writeString(Long.toString(value)); - } - - @Override - protected void writeFixed32(ProtoFieldInfo field, int value) throws IOException { - generator.writeNumberField(field.getJsonName(), value); - } - - @Override - public void writeDouble(ProtoFieldInfo field, double value) throws IOException { - generator.writeNumberField(field.getJsonName(), value); - } - - @Override - protected void writeDoubleValue(double value) throws IOException { - generator.writeNumber(value); - } - - @Override - public void writeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException { - generator.writeFieldName(field.getJsonName()); - // Marshalers encoded String into UTF-8 bytes to optimize for binary serialization where - // we are able to avoid the encoding process happening twice, one for size computation and one - // for actual writing. JsonGenerator actually has a writeUTF8String that would be able to accept - // this, but it only works when writing to an OutputStream, but not to a String like we do for - // writing to logs. It's wasteful to take a String, convert it to bytes, and convert back to - // the same String but we can see if this can be improved in the future. - generator.writeString(new String(utf8Bytes, StandardCharsets.UTF_8)); - } - - @Override - protected void writeBytes(ProtoFieldInfo field, byte[] value) throws IOException { - generator.writeBinaryField(field.getJsonName(), value); - } - - @Override - protected void writeStartMessage(ProtoFieldInfo field, int protoMessageSize) throws IOException { - generator.writeObjectFieldStart(field.getJsonName()); - } - - @Override - protected void writeEndMessage() throws IOException { - generator.writeEndObject(); - } - - @Override - protected void writeStartRepeatedPrimitive( - ProtoFieldInfo field, int protoSizePerElement, int numElements) throws IOException { - generator.writeArrayFieldStart(field.getJsonName()); - } - - @Override - protected void writeEndRepeatedPrimitive() throws IOException { - generator.writeEndArray(); - } - - @Override - protected void writeStartRepeatedVarint(ProtoFieldInfo field, int payloadSize) - throws IOException { - generator.writeArrayFieldStart(field.getJsonName()); - } - - @Override - protected void writeEndRepeatedVarint() throws IOException { - generator.writeEndArray(); - } - - @Override - public void serializeRepeatedMessage(ProtoFieldInfo field, Marshaler[] repeatedMessage) - throws IOException { - generator.writeArrayFieldStart(field.getJsonName()); - for (Marshaler marshaler : repeatedMessage) { - writeMessageValue(marshaler); - } - generator.writeEndArray(); - } - - @Override - public void serializeRepeatedMessage( - ProtoFieldInfo field, List repeatedMessage) throws IOException { - generator.writeArrayFieldStart(field.getJsonName()); - for (Marshaler marshaler : repeatedMessage) { - writeMessageValue(marshaler); - } - generator.writeEndArray(); - } - - // Not a field. - void writeMessageValue(Marshaler message) throws IOException { - generator.writeStartObject(); - message.writeTo(this); - generator.writeEndObject(); - } - - @Override - public void writeSerializedMessage(byte[] protoSerialized, String jsonSerialized) - throws IOException { - generator.writeRaw(jsonSerialized); - } - - @Override - public void close() throws IOException { - generator.close(); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Marshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Marshaler.java deleted file mode 100644 index 2e6fba4644c..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Marshaler.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.marshal; - -import com.fasterxml.jackson.core.JsonGenerator; -import java.io.IOException; -import java.io.OutputStream; - -/** - * Marshaler from an SDK structure to protobuf wire format. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public abstract class Marshaler { - - /** Marshals into the {@link OutputStream} in proto binary format. */ - public final void writeBinaryTo(OutputStream output) throws IOException { - try (Serializer serializer = new ProtoSerializer(output)) { - writeTo(serializer); - } - } - - /** Marshals into the {@link OutputStream} in proto JSON format. */ - public final void writeJsonTo(OutputStream output) throws IOException { - try (JsonSerializer serializer = new JsonSerializer(output)) { - serializer.writeMessageValue(this); - } - } - - /** Marshals into the {@link JsonGenerator} in proto JSON format. */ - public final void writeJsonTo(JsonGenerator output) throws IOException { - try (JsonSerializer serializer = new JsonSerializer(output)) { - serializer.writeMessageValue(this); - } - } - - /** Returns the number of bytes this Marshaler will write in proto binary format. */ - public abstract int getBinarySerializedSize(); - - protected abstract void writeTo(Serializer output) throws IOException; -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerUtil.java deleted file mode 100644 index 9f429499702..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/MarshalerUtil.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.marshal; - -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collection; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; -import javax.annotation.Nullable; - -/** - * Marshaler utilities. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class MarshalerUtil { - private static final int TRACE_ID_VALUE_SIZE = - CodedOutputStream.computeLengthDelimitedFieldSize(TraceId.getLength() / 2); - private static final int SPAN_ID_VALUE_SIZE = - CodedOutputStream.computeLengthDelimitedFieldSize(SpanId.getLength() / 2); - - private static final boolean JSON_AVAILABLE; - - static { - boolean jsonAvailable = false; - try { - Class.forName("com.fasterxml.jackson.core.JsonFactory"); - jsonAvailable = true; - } catch (ClassNotFoundException e) { - // Not available - } - JSON_AVAILABLE = jsonAvailable; - } - - private static final byte[] EMPTY_BYTES = new byte[0]; - - /** Groups SDK items by resource and instrumentation scope. */ - public static - Map>> groupByResourceAndScope( - Collection dataList, - Function getResource, - Function getInstrumentationScope, - Function createMarshaler) { - // expectedMaxSize of 8 means initial map capacity of 16 to match HashMap - IdentityHashMap>> result = - new IdentityHashMap<>(8); - for (T data : dataList) { - Map> scopeInfoListMap = - result.computeIfAbsent(getResource.apply(data), unused -> new IdentityHashMap<>(8)); - List marshalerList = - scopeInfoListMap.computeIfAbsent( - getInstrumentationScope.apply(data), unused -> new ArrayList<>()); - marshalerList.add(createMarshaler.apply(data)); - } - return result; - } - - /** Preserialize into JSON format. */ - public static String preserializeJsonFields(Marshaler marshaler) { - if (!MarshalerUtil.JSON_AVAILABLE) { - return ""; - } - - ByteArrayOutputStream jsonBos = new ByteArrayOutputStream(); - try { - marshaler.writeJsonTo(jsonBos); - } catch (IOException e) { - throw new UncheckedIOException( - "Serialization error, this is likely a bug in OpenTelemetry.", e); - } - - // We effectively cache `writeTo`, however Jackson would not allow us to only write out - // fields - // which is what writeTo does. So we need to write to an object but skip the object start - // / - // end. - byte[] jsonBytes = jsonBos.toByteArray(); - return new String(jsonBytes, 1, jsonBytes.length - 2, StandardCharsets.UTF_8); - } - - /** Returns the size of a repeated fixed64 field. */ - public static int sizeRepeatedFixed64(ProtoFieldInfo field, List values) { - return sizeRepeatedFixed64(field, values.size()); - } - - private static int sizeRepeatedFixed64(ProtoFieldInfo field, int numValues) { - if (numValues == 0) { - return 0; - } - int dataSize = WireFormat.FIXED64_SIZE * numValues; - int size = 0; - size += field.getTagSize(); - size += CodedOutputStream.computeLengthDelimitedFieldSize(dataSize); - return size; - } - - /** - * Returns the size of a repeated uint64 field. - * - *

    Packed repeated fields contain the tag, an integer representing the incoming payload size, - * and an actual payload of repeated varints. - */ - public static int sizeRepeatedUInt64(ProtoFieldInfo field, long[] values) { - if (values.length == 0) { - return 0; - } - - int payloadSize = 0; - for (long v : values) { - payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); - } - - // tag size + payload indicator size + actual payload size - return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(payloadSize) + payloadSize; - } - - /** Returns the size of a repeated double field. */ - public static int sizeRepeatedDouble(ProtoFieldInfo field, List values) { - // Same as fixed64. - return sizeRepeatedFixed64(field, values.size()); - } - - /** Returns the size of a repeated message field. */ - public static int sizeRepeatedMessage( - ProtoFieldInfo field, T[] repeatedMessage) { - int size = 0; - int fieldTagSize = field.getTagSize(); - for (Marshaler message : repeatedMessage) { - int fieldSize = message.getBinarySerializedSize(); - size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; - } - return size; - } - - /** Returns the size of a repeated message field. */ - public static int sizeRepeatedMessage( - ProtoFieldInfo field, List repeatedMessage) { - int size = 0; - int fieldTagSize = field.getTagSize(); - for (Marshaler message : repeatedMessage) { - int fieldSize = message.getBinarySerializedSize(); - size += fieldTagSize + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; - } - return size; - } - - /** Returns the size of a message field. */ - public static int sizeMessage(ProtoFieldInfo field, Marshaler message) { - int fieldSize = message.getBinarySerializedSize(); - return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(fieldSize) + fieldSize; - } - - /** Returns the size of a bool field. */ - public static int sizeBool(ProtoFieldInfo field, boolean value) { - if (!value) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeBoolSizeNoTag(value); - } - - /** Returns the size of a int64 field. */ - public static int sizeInt64(ProtoFieldInfo field, long message) { - if (message == 0) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeInt64SizeNoTag(message); - } - - /** Returns the size of a uint32 field. */ - public static int sizeUInt32(ProtoFieldInfo field, int message) { - if (message == 0) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeUInt32SizeNoTag(message); - } - - /** Returns the size of a sint32 field. */ - public static int sizeSInt32(ProtoFieldInfo field, int message) { - if (message == 0) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeSInt32SizeNoTag(message); - } - - /** Returns the size of a int32 field. */ - public static int sizeInt32(ProtoFieldInfo field, int message) { - if (message == 0) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeInt32SizeNoTag(message); - } - - /** Returns the size of a double field. */ - public static int sizeDouble(ProtoFieldInfo field, double value) { - if (value == 0D) { - return 0; - } - return sizeDoubleOptional(field, value); - } - /** Returns the size of a double field. */ - public static int sizeDoubleOptional(ProtoFieldInfo field, double value) { - return field.getTagSize() + CodedOutputStream.computeDoubleSizeNoTag(value); - } - - /** Returns the size of a fixed64 field. */ - public static int sizeFixed64(ProtoFieldInfo field, long value) { - if (value == 0L) { - return 0; - } - return sizeFixed64Optional(field, value); - } - /** Returns the size of a fixed64 field. */ - public static int sizeFixed64Optional(ProtoFieldInfo field, long value) { - return field.getTagSize() + CodedOutputStream.computeFixed64SizeNoTag(value); - } - - /** Returns the size of a fixed32 field. */ - public static int sizeFixed32(ProtoFieldInfo field, int message) { - if (message == 0L) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeFixed32SizeNoTag(message); - } - - /** Returns the size of a bytes field. */ - public static int sizeBytes(ProtoFieldInfo field, byte[] message) { - if (message.length == 0) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeByteArraySizeNoTag(message); - } - - /** Returns the size of a enum field. */ - // Assumes OTLP always defines the first item in an enum with number 0, which it does and will. - public static int sizeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) { - int number = enumValue.getEnumNumber(); - if (number == 0) { - return 0; - } - return field.getTagSize() + CodedOutputStream.computeEnumSizeNoTag(number); - } - - /** Returns the size of a trace_id field. */ - public static int sizeTraceId(ProtoFieldInfo field, @Nullable String traceId) { - if (traceId == null) { - return 0; - } - return field.getTagSize() + TRACE_ID_VALUE_SIZE; - } - - /** Returns the size of a span_id field. */ - public static int sizeSpanId(ProtoFieldInfo field, @Nullable String spanId) { - if (spanId == null) { - return 0; - } - return field.getTagSize() + SPAN_ID_VALUE_SIZE; - } - - /** Converts the string to utf8 bytes for encoding. */ - public static byte[] toBytes(@Nullable String value) { - if (value == null || value.isEmpty()) { - return EMPTY_BYTES; - } - return value.getBytes(StandardCharsets.UTF_8); - } - - private MarshalerUtil() {} -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoSerializer.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoSerializer.java deleted file mode 100644 index df8304beaa9..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/ProtoSerializer.java +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.marshal; - -import io.opentelemetry.api.internal.OtelEncodingUtils; -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.TraceId; -import java.io.IOException; -import java.io.OutputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** Serializer for the protobuf binary wire format. */ -final class ProtoSerializer extends Serializer implements AutoCloseable { - - // Cache ID conversion to bytes since we know it's common to use the same ID multiple times within - // a single export (trace ID and parent span ID). - // In practice, there is often only one thread that calls this code in the BatchSpanProcessor so - // reusing buffers for the thread is almost free. Even with multiple threads, it should still be - // worth it and is common practice in serialization libraries such as Jackson. - private static final ThreadLocal> THREAD_LOCAL_ID_CACHE = new ThreadLocal<>(); - - private final CodedOutputStream output; - private final Map idCache; - - ProtoSerializer(OutputStream output) { - this.output = CodedOutputStream.newInstance(output); - idCache = getIdCache(); - } - - @Override - protected void writeTraceId(ProtoFieldInfo field, String traceId) throws IOException { - byte[] traceIdBytes = - idCache.computeIfAbsent( - traceId, id -> OtelEncodingUtils.bytesFromBase16(id, TraceId.getLength())); - writeBytes(field, traceIdBytes); - } - - @Override - protected void writeSpanId(ProtoFieldInfo field, String spanId) throws IOException { - byte[] spanIdBytes = - idCache.computeIfAbsent( - spanId, id -> OtelEncodingUtils.bytesFromBase16(id, SpanId.getLength())); - writeBytes(field, spanIdBytes); - } - - @Override - public void writeBool(ProtoFieldInfo field, boolean value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeBoolNoTag(value); - } - - @Override - protected void writeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeEnumNoTag(enumValue.getEnumNumber()); - } - - @Override - protected void writeUint32(ProtoFieldInfo field, int value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeUInt32NoTag(value); - } - - @Override - protected void writeSInt32(ProtoFieldInfo field, int value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeSInt32NoTag(value); - } - - @Override - protected void writeint32(ProtoFieldInfo field, int value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeInt32NoTag(value); - } - - @Override - public void writeInt64(ProtoFieldInfo field, long value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeInt64NoTag(value); - } - - @Override - protected void writeFixed64(ProtoFieldInfo field, long value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeFixed64NoTag(value); - } - - @Override - protected void writeFixed64Value(long value) throws IOException { - output.writeFixed64NoTag(value); - } - - @Override - protected void writeUInt64Value(long value) throws IOException { - output.writeUInt64NoTag(value); - } - - @Override - protected void writeFixed32(ProtoFieldInfo field, int value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeFixed32NoTag(value); - } - - @Override - public void writeDouble(ProtoFieldInfo field, double value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeDoubleNoTag(value); - } - - @Override - protected void writeDoubleValue(double value) throws IOException { - output.writeDoubleNoTag(value); - } - - @Override - public void writeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException { - writeBytes(field, utf8Bytes); - } - - @Override - protected void writeBytes(ProtoFieldInfo field, byte[] value) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeByteArrayNoTag(value); - } - - @Override - protected void writeStartMessage(ProtoFieldInfo field, int protoMessageSize) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeUInt32NoTag(protoMessageSize); - } - - @Override - protected void writeEndMessage() { - // Do nothing - } - - @Override - protected void writeStartRepeatedPrimitive( - ProtoFieldInfo field, int protoSizePerElement, int numElements) throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeUInt32NoTag(protoSizePerElement * numElements); - } - - @Override - protected void writeEndRepeatedPrimitive() { - // Do nothing - } - - @Override - protected void writeStartRepeatedVarint(ProtoFieldInfo field, int payloadSize) - throws IOException { - output.writeUInt32NoTag(field.getTag()); - output.writeUInt32NoTag(payloadSize); - } - - @Override - protected void writeEndRepeatedVarint() { - // Do nothing - } - - @Override - public void serializeRepeatedMessage(ProtoFieldInfo field, Marshaler[] repeatedMessage) - throws IOException { - for (Marshaler message : repeatedMessage) { - serializeMessage(field, message); - } - } - - @Override - public void serializeRepeatedMessage( - ProtoFieldInfo field, List repeatedMessage) throws IOException { - for (Marshaler message : repeatedMessage) { - serializeMessage(field, message); - } - } - - @Override - public void writeSerializedMessage(byte[] protoSerialized, String jsonSerialized) - throws IOException { - output.writeRawBytes(protoSerialized); - } - - @Override - public void close() throws IOException { - output.flush(); - idCache.clear(); - } - - private static Map getIdCache() { - Map result = THREAD_LOCAL_ID_CACHE.get(); - if (result == null) { - result = new HashMap<>(); - THREAD_LOCAL_ID_CACHE.set(result); - } - return result; - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java deleted file mode 100644 index dd2de68967f..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/marshal/Serializer.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.marshal; - -import java.io.IOException; -import java.util.List; -import javax.annotation.Nullable; - -/** - * Serializer to use when converting from an SDK data object into a protobuf output format. Unlike - * {@link CodedOutputStream}, which strictly encodes data into the protobuf binary format, this - * - *

      - *
    • Handles proto3 semantics of not outputting the value when it matches the default of a field - *
    • Can be implemented to serialize into protobuf JSON format (not binary) - *
    - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public abstract class Serializer implements AutoCloseable { - - Serializer() {} - - /** Serializes a trace ID field. */ - public void serializeTraceId(ProtoFieldInfo field, @Nullable String traceId) throws IOException { - if (traceId == null) { - return; - } - writeTraceId(field, traceId); - } - - protected abstract void writeTraceId(ProtoFieldInfo field, String traceId) throws IOException; - - /** Serializes a span ID field. */ - public void serializeSpanId(ProtoFieldInfo field, @Nullable String spanId) throws IOException { - if (spanId == null) { - return; - } - writeSpanId(field, spanId); - } - - protected abstract void writeSpanId(ProtoFieldInfo field, String spanId) throws IOException; - - /** Serializes a protobuf {@code bool} field. */ - public void serializeBool(ProtoFieldInfo field, boolean value) throws IOException { - if (!value) { - return; - } - writeBool(field, value); - } - - /** Writes a protobuf {@code bool} field, even if it matches the default value. */ - public abstract void writeBool(ProtoFieldInfo field, boolean value) throws IOException; - - /** Serializes a protobuf {@code enum} field. */ - public void serializeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) throws IOException { - if (enumValue.getEnumNumber() == 0) { - return; - } - writeEnum(field, enumValue); - } - - protected abstract void writeEnum(ProtoFieldInfo field, ProtoEnumInfo enumValue) - throws IOException; - - /** Serializes a protobuf {@code uint32} field. */ - public void serializeUInt32(ProtoFieldInfo field, int value) throws IOException { - if (value == 0) { - return; - } - writeUint32(field, value); - } - - protected abstract void writeUint32(ProtoFieldInfo field, int value) throws IOException; - - /** Serializes a protobuf {@code sint32} field. */ - public void serializeSInt32(ProtoFieldInfo field, int value) throws IOException { - if (value == 0) { - return; - } - writeSInt32(field, value); - } - - protected abstract void writeSInt32(ProtoFieldInfo info, int value) throws IOException; - - /** Serializes a protobuf {@code uint32} field. */ - public void serializeInt32(ProtoFieldInfo field, int value) throws IOException { - if (value == 0) { - return; - } - writeint32(field, value); - } - - protected abstract void writeint32(ProtoFieldInfo field, int value) throws IOException; - - /** Serializes a protobuf {@code int64} field. */ - public void serializeInt64(ProtoFieldInfo field, long value) throws IOException { - if (value == 0) { - return; - } - writeInt64(field, value); - } - - /** Writes a protobuf {@code int64} field, even if it matches the default value. */ - public abstract void writeInt64(ProtoFieldInfo field, long value) throws IOException; - - /** Serializes a protobuf {@code fixed64} field. */ - public void serializeFixed64(ProtoFieldInfo field, long value) throws IOException { - if (value == 0) { - return; - } - writeFixed64(field, value); - } - - /** Serializes a protobuf {@code fixed64} field. */ - public void serializeFixed64Optional(ProtoFieldInfo field, long value) throws IOException { - writeFixed64(field, value); - } - - protected abstract void writeFixed64(ProtoFieldInfo field, long value) throws IOException; - - protected abstract void writeFixed64Value(long value) throws IOException; - - protected abstract void writeUInt64Value(long value) throws IOException; - - /** Serializes a protobuf {@code fixed32} field. */ - public void serializeFixed32(ProtoFieldInfo field, int value) throws IOException { - if (value == 0) { - return; - } - writeFixed32(field, value); - } - - protected abstract void writeFixed32(ProtoFieldInfo field, int value) throws IOException; - - /** Serializes a proto buf {@code double} field. */ - public void serializeDouble(ProtoFieldInfo field, double value) throws IOException { - if (value == 0D) { - return; - } - writeDouble(field, value); - } - /** Serializes a proto buf {@code double} field. */ - public void serializeDoubleOptional(ProtoFieldInfo field, double value) throws IOException { - writeDouble(field, value); - } - - /** Writes a protobuf {@code double} field, even if it matches the default value. */ - public abstract void writeDouble(ProtoFieldInfo field, double value) throws IOException; - - protected abstract void writeDoubleValue(double value) throws IOException; - - /** - * Serializes a protobuf {@code string} field. {@code utf8Bytes} is the UTF8 encoded bytes of the - * string to serialize. - */ - public void serializeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException { - if (utf8Bytes.length == 0) { - return; - } - writeString(field, utf8Bytes); - } - - /** Writes a protobuf {@code string} field, even if it matches the default value. */ - public abstract void writeString(ProtoFieldInfo field, byte[] utf8Bytes) throws IOException; - - /** Serializes a protobuf {@code bytes} field. */ - public void serializeBytes(ProtoFieldInfo field, byte[] value) throws IOException { - if (value.length == 0) { - return; - } - writeBytes(field, value); - } - - protected abstract void writeBytes(ProtoFieldInfo field, byte[] value) throws IOException; - - protected abstract void writeStartMessage(ProtoFieldInfo field, int protoMessageSize) - throws IOException; - - protected abstract void writeEndMessage() throws IOException; - - /** Serializes a protobuf embedded {@code message}. */ - public void serializeMessage(ProtoFieldInfo field, Marshaler message) throws IOException { - writeStartMessage(field, message.getBinarySerializedSize()); - message.writeTo(this); - writeEndMessage(); - } - - protected abstract void writeStartRepeatedPrimitive( - ProtoFieldInfo field, int protoSizePerElement, int numElements) throws IOException; - - protected abstract void writeEndRepeatedPrimitive() throws IOException; - - protected abstract void writeStartRepeatedVarint(ProtoFieldInfo field, int payloadSize) - throws IOException; - - protected abstract void writeEndRepeatedVarint() throws IOException; - - /** Serializes a {@code repeated fixed64} field. */ - public void serializeRepeatedFixed64(ProtoFieldInfo field, List values) throws IOException { - if (values.isEmpty()) { - return; - } - writeStartRepeatedPrimitive(field, WireFormat.FIXED64_SIZE, values.size()); - for (long value : values) { - writeFixed64Value(value); - } - writeEndRepeatedPrimitive(); - } - - /** Serializes a {@code repeated fixed64} field. */ - public void serializeRepeatedFixed64(ProtoFieldInfo field, long[] values) throws IOException { - if (values.length == 0) { - return; - } - writeStartRepeatedPrimitive(field, WireFormat.FIXED64_SIZE, values.length); - for (long value : values) { - writeFixed64Value(value); - } - writeEndRepeatedPrimitive(); - } - - /** Serializes a {@code repeated uint64} field. */ - public void serializeRepeatedUInt64(ProtoFieldInfo field, long[] values) throws IOException { - if (values.length == 0) { - return; - } - - int payloadSize = 0; - for (long v : values) { - payloadSize += CodedOutputStream.computeUInt64SizeNoTag(v); - } - - writeStartRepeatedVarint(field, payloadSize); - for (long value : values) { - writeUInt64Value(value); - } - writeEndRepeatedVarint(); - } - - /** Serializes a {@code repeated double} field. */ - public void serializeRepeatedDouble(ProtoFieldInfo field, List values) - throws IOException { - if (values.isEmpty()) { - return; - } - writeStartRepeatedPrimitive(field, WireFormat.FIXED64_SIZE, values.size()); - for (double value : values) { - writeDoubleValue(value); - } - writeEndRepeatedPrimitive(); - } - - /** Serializes {@code repeated message} field. */ - public abstract void serializeRepeatedMessage(ProtoFieldInfo field, Marshaler[] repeatedMessage) - throws IOException; - - /** Serializes {@code repeated message} field. */ - public abstract void serializeRepeatedMessage( - ProtoFieldInfo field, List repeatedMessage) throws IOException; - - /** Writes the value for a message field that has been pre-serialized. */ - public abstract void writeSerializedMessage(byte[] protoSerialized, String jsonSerialized) - throws IOException; - - @Override - public abstract void close() throws IOException; -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/JsonRequestBody.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/JsonRequestBody.java deleted file mode 100644 index 6f5b0f4cafb..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/JsonRequestBody.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.okhttp; - -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import java.io.IOException; -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okio.BufferedSink; - -final class JsonRequestBody extends RequestBody { - private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json"); - - private final Marshaler marshaler; - - /** Creates a new {@link JsonRequestBody}. */ - public JsonRequestBody(Marshaler marshaler) { - this.marshaler = marshaler; - } - - @Override - public long contentLength() { - return -1; - } - - @Override - public MediaType contentType() { - return JSON_MEDIA_TYPE; - } - - @Override - public void writeTo(BufferedSink bufferedSink) throws IOException { - marshaler.writeJsonTo(bufferedSink.outputStream()); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpExporter.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpExporter.java deleted file mode 100644 index b5dd386bc96..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpExporter.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.okhttp; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.ExporterMetrics; -import io.opentelemetry.exporter.internal.grpc.GrpcStatusUtil; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ThrottlingLogger; -import java.io.IOException; -import java.util.function.Function; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import okhttp3.Call; -import okhttp3.Callback; -import okhttp3.Headers; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; -import okio.BufferedSink; -import okio.GzipSink; -import okio.Okio; - -/** - * An exporter for http/protobuf or http/json using a signal-specific Marshaler. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@SuppressWarnings("checkstyle:JavadocMethod") -public final class OkHttpExporter { - - private static final Logger internalLogger = Logger.getLogger(OkHttpExporter.class.getName()); - - private final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); - - private final String type; - private final OkHttpClient client; - private final String endpoint; - @Nullable private final Headers headers; - private final boolean compressionEnabled; - private final Function requestBodyCreator; - - private final ExporterMetrics exporterMetrics; - - OkHttpExporter( - String exporterName, - String type, - OkHttpClient client, - MeterProvider meterProvider, - String endpoint, - @Nullable Headers headers, - boolean compressionEnabled, - boolean exportAsJson) { - this.type = type; - this.client = client; - this.endpoint = endpoint; - this.headers = headers; - this.compressionEnabled = compressionEnabled; - this.requestBodyCreator = exportAsJson ? JsonRequestBody::new : ProtoRequestBody::new; - this.exporterMetrics = ExporterMetrics.createHttpProtobuf(exporterName, type, meterProvider); - } - - public CompletableResultCode export(T exportRequest, int numItems) { - exporterMetrics.addSeen(numItems); - - Request.Builder requestBuilder = new Request.Builder().url(endpoint); - if (headers != null) { - requestBuilder.headers(headers); - } - RequestBody requestBody = requestBodyCreator.apply(exportRequest); - if (compressionEnabled) { - requestBuilder.addHeader("Content-Encoding", "gzip"); - requestBuilder.post(gzipRequestBody(requestBody)); - } else { - requestBuilder.post(requestBody); - } - - CompletableResultCode result = new CompletableResultCode(); - - client - .newCall(requestBuilder.build()) - .enqueue( - new Callback() { - @Override - public void onFailure(Call call, IOException e) { - exporterMetrics.addFailed(numItems); - logger.log( - Level.SEVERE, - "Failed to export " - + type - + "s. The request could not be executed. Full error message: " - + e.getMessage()); - result.fail(); - } - - @Override - public void onResponse(Call call, Response response) { - try (ResponseBody body = response.body()) { - if (response.isSuccessful()) { - exporterMetrics.addSuccess(numItems); - result.succeed(); - return; - } - - exporterMetrics.addFailed(numItems); - int code = response.code(); - - String status = extractErrorStatus(response, body); - - logger.log( - Level.WARNING, - "Failed to export " - + type - + "s. Server responded with HTTP status code " - + code - + ". Error message: " - + status); - result.fail(); - } - } - }); - - return result; - } - - public CompletableResultCode shutdown() { - CompletableResultCode result = CompletableResultCode.ofSuccess(); - client.dispatcher().cancelAll(); - client.dispatcher().executorService().shutdownNow(); - client.connectionPool().evictAll(); - return result; - } - - static boolean isRetryable(Response response) { - return RetryUtil.retryableHttpResponseCodes().contains(response.code()); - } - - private static RequestBody gzipRequestBody(RequestBody requestBody) { - return new RequestBody() { - @Override - public MediaType contentType() { - return requestBody.contentType(); - } - - @Override - public long contentLength() { - return -1; - } - - @Override - public void writeTo(BufferedSink bufferedSink) throws IOException { - BufferedSink gzipSink = Okio.buffer(new GzipSink(bufferedSink)); - requestBody.writeTo(gzipSink); - gzipSink.close(); - } - }; - } - - private static String extractErrorStatus(Response response, @Nullable ResponseBody responseBody) { - if (responseBody == null) { - return "Response body missing, HTTP status message: " + response.message(); - } - try { - return GrpcStatusUtil.getStatusMessage(responseBody.bytes()); - } catch (IOException e) { - return "Unable to parse response body, HTTP status message: " + response.message(); - } - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpExporterBuilder.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpExporterBuilder.java deleted file mode 100644 index c44b35bd157..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpExporterBuilder.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.okhttp; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.ExporterBuilderUtil; -import io.opentelemetry.exporter.internal.TlsUtil; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryInterceptor; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; -import javax.net.ssl.SSLException; -import javax.net.ssl.X509KeyManager; -import javax.net.ssl.X509TrustManager; -import okhttp3.Headers; -import okhttp3.OkHttpClient; - -/** - * A builder for {@link OkHttpExporter}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@SuppressWarnings("checkstyle:JavadocMethod") -public final class OkHttpExporterBuilder { - public static final long DEFAULT_TIMEOUT_SECS = 10; - - private final String exporterName; - private final String type; - - private String endpoint; - - private long timeoutNanos = TimeUnit.SECONDS.toNanos(DEFAULT_TIMEOUT_SECS); - private boolean compressionEnabled = false; - private boolean exportAsJson = false; - @Nullable private Headers.Builder headersBuilder; - @Nullable private byte[] trustedCertificatesPem; - @Nullable private byte[] privateKeyPem; - @Nullable private byte[] certificatePem; - @Nullable private RetryPolicy retryPolicy; - private MeterProvider meterProvider = MeterProvider.noop(); - - public OkHttpExporterBuilder(String exporterName, String type, String defaultEndpoint) { - this.exporterName = exporterName; - this.type = type; - - endpoint = defaultEndpoint; - } - - public OkHttpExporterBuilder setTimeout(long timeout, TimeUnit unit) { - timeoutNanos = unit.toNanos(timeout); - return this; - } - - public OkHttpExporterBuilder setTimeout(Duration timeout) { - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - public OkHttpExporterBuilder setEndpoint(String endpoint) { - URI uri = ExporterBuilderUtil.validateEndpoint(endpoint); - this.endpoint = uri.toString(); - return this; - } - - public OkHttpExporterBuilder setCompression(String compressionMethod) { - if (compressionMethod.equals("gzip")) { - this.compressionEnabled = true; - } - return this; - } - - public OkHttpExporterBuilder addHeader(String key, String value) { - if (headersBuilder == null) { - headersBuilder = new Headers.Builder(); - } - headersBuilder.add(key, value); - return this; - } - - public OkHttpExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - this.trustedCertificatesPem = trustedCertificatesPem; - return this; - } - - public OkHttpExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - this.privateKeyPem = privateKeyPem; - this.certificatePem = certificatePem; - return this; - } - - public OkHttpExporterBuilder setMeterProvider(MeterProvider meterProvider) { - this.meterProvider = meterProvider; - return this; - } - - public OkHttpExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - this.retryPolicy = retryPolicy; - return this; - } - - public OkHttpExporterBuilder exportAsJson() { - this.exportAsJson = true; - return this; - } - - public OkHttpExporter build() { - OkHttpClient.Builder clientBuilder = - new OkHttpClient.Builder() - .dispatcher(OkHttpUtil.newDispatcher()) - .callTimeout(Duration.ofNanos(timeoutNanos)); - - if (trustedCertificatesPem != null) { - try { - X509TrustManager trustManager = TlsUtil.trustManager(trustedCertificatesPem); - X509KeyManager keyManager = null; - if (privateKeyPem != null && certificatePem != null) { - keyManager = TlsUtil.keyManager(privateKeyPem, certificatePem); - } - clientBuilder.sslSocketFactory( - TlsUtil.sslSocketFactory(keyManager, trustManager), trustManager); - } catch (SSLException e) { - throw new IllegalStateException( - "Could not set trusted certificate for OTLP HTTP connection, are they valid X.509 in PEM format?", - e); - } - } - - Headers headers = headersBuilder == null ? null : headersBuilder.build(); - - if (retryPolicy != null) { - clientBuilder.addInterceptor(new RetryInterceptor(retryPolicy, OkHttpExporter::isRetryable)); - } - - return new OkHttpExporter<>( - exporterName, - type, - clientBuilder.build(), - meterProvider, - endpoint, - headers, - compressionEnabled, - exportAsJson); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpUtil.java deleted file mode 100644 index 419acf2df1d..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/OkHttpUtil.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.okhttp; - -import io.opentelemetry.sdk.internal.DaemonThreadFactory; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import okhttp3.Dispatcher; - -/** - * Utilities for OkHttp. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class OkHttpUtil { - - /** Returns a {@link Dispatcher} using daemon threads, otherwise matching the OkHttp default. */ - public static Dispatcher newDispatcher() { - return new Dispatcher( - new ThreadPoolExecutor( - 0, - Integer.MAX_VALUE, - 60, - TimeUnit.SECONDS, - new SynchronousQueue<>(), - new DaemonThreadFactory("okhttp-dispatch"))); - } - - private OkHttpUtil() {} -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/ProtoRequestBody.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/ProtoRequestBody.java deleted file mode 100644 index 81581207995..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/ProtoRequestBody.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.okhttp; - -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import java.io.IOException; -import okhttp3.MediaType; -import okhttp3.RequestBody; -import okio.BufferedSink; - -/** - * A {@link RequestBody} for reading from a {@link Marshaler}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -final class ProtoRequestBody extends RequestBody { - - private static final MediaType PROTOBUF_MEDIA_TYPE = MediaType.parse("application/x-protobuf"); - - private final Marshaler marshaler; - private final int contentLength; - - /** Creates a new {@link ProtoRequestBody}. */ - public ProtoRequestBody(Marshaler marshaler) { - this.marshaler = marshaler; - contentLength = marshaler.getBinarySerializedSize(); - } - - @Override - public long contentLength() { - return contentLength; - } - - @Override - public MediaType contentType() { - return PROTOBUF_MEDIA_TYPE; - } - - @Override - public void writeTo(BufferedSink bufferedSink) throws IOException { - marshaler.writeBinaryTo(bufferedSink.outputStream()); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/package-info.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/package-info.java deleted file mode 100644 index fa262be08bb..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/okhttp/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** Utilities for HTTP exporters. */ -@ParametersAreNonnullByDefault -package io.opentelemetry.exporter.internal.okhttp; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AnyValueMarshaler.java new file mode 100644 index 00000000000..16fc7941622 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AnyValueMarshaler.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import java.nio.ByteBuffer; +import java.util.List; + +/** + * Utility methods for obtaining AnyValue marshaler. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AnyValueMarshaler { + + private AnyValueMarshaler() {} + + @SuppressWarnings("unchecked") + public static MarshalerWithSize create(Value value) { + switch (value.getType()) { + case STRING: + return StringAnyValueMarshaler.create((String) value.getValue()); + case BOOLEAN: + return BoolAnyValueMarshaler.create((boolean) value.getValue()); + case LONG: + return IntAnyValueMarshaler.create((long) value.getValue()); + case DOUBLE: + return DoubleAnyValueMarshaler.create((double) value.getValue()); + case ARRAY: + return ArrayAnyValueMarshaler.createAnyValue((List>) value.getValue()); + case KEY_VALUE_LIST: + return KeyValueListAnyValueMarshaler.create((List) value.getValue()); + case BYTES: + return BytesAnyValueMarshaler.create((Value) value); + case EMPTY: + return EmptyAnyValueMarshaler.INSTANCE; + } + throw new IllegalArgumentException("Unsupported Value type: " + value.getType()); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..d3f9ead674b --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AnyValueStatelessMarshaler.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; + +/** + * A Marshaler of {@link Value}. See {@link AnyValueMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AnyValueStatelessMarshaler implements StatelessMarshaler> { + + public static final AnyValueStatelessMarshaler INSTANCE = new AnyValueStatelessMarshaler(); + + private AnyValueStatelessMarshaler() {} + + @SuppressWarnings("unchecked") + @Override + public void writeTo(Serializer output, Value value, MarshalerContext context) + throws IOException { + switch (value.getType()) { + case STRING: + StringAnyValueStatelessMarshaler.INSTANCE.writeTo( + output, (String) value.getValue(), context); + return; + case BOOLEAN: + BoolAnyValueStatelessMarshaler.INSTANCE.writeTo( + output, (Boolean) value.getValue(), context); + return; + case LONG: + IntAnyValueStatelessMarshaler.INSTANCE.writeTo(output, (Long) value.getValue(), context); + return; + case DOUBLE: + DoubleAnyValueStatelessMarshaler.INSTANCE.writeTo( + output, (Double) value.getValue(), context); + return; + case ARRAY: + output.serializeMessageWithContext( + AnyValue.ARRAY_VALUE, + (List>) value.getValue(), + ArrayAnyValueStatelessMarshaler.INSTANCE, + context); + return; + case KEY_VALUE_LIST: + output.serializeMessageWithContext( + AnyValue.KVLIST_VALUE, + (List) value.getValue(), + KeyValueListAnyValueStatelessMarshaler.INSTANCE, + context); + return; + case BYTES: + BytesAnyValueStatelessMarshaler.INSTANCE.writeTo( + output, (Value) value, context); + return; + case EMPTY: + // no field to write + return; + } + // Error prone ensures the switch statement is complete, otherwise only can happen with + // unaligned versions which are not supported. + throw new IllegalArgumentException("Unsupported value type."); + } + + @SuppressWarnings("unchecked") + @Override + public int getBinarySerializedSize(Value value, MarshalerContext context) { + switch (value.getType()) { + case STRING: + return StringAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (String) value.getValue(), context); + case BOOLEAN: + return BoolAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Boolean) value.getValue(), context); + case LONG: + return IntAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Long) value.getValue(), context); + case DOUBLE: + return DoubleAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Double) value.getValue(), context); + case ARRAY: + return StatelessMarshalerUtil.sizeMessageWithContext( + AnyValue.ARRAY_VALUE, + (List>) value.getValue(), + ArrayAnyValueStatelessMarshaler.INSTANCE, + context); + case KEY_VALUE_LIST: + return StatelessMarshalerUtil.sizeMessageWithContext( + AnyValue.KVLIST_VALUE, + (List) value.getValue(), + KeyValueListAnyValueStatelessMarshaler.INSTANCE, + context); + case BYTES: + return BytesAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Value) value, context); + case EMPTY: + return 0; + } + // Error prone ensures the switch statement is complete, otherwise only can happen with + // unaligned versions which are not supported. + throw new IllegalArgumentException("Unsupported value type."); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ArrayAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ArrayAnyValueMarshaler.java new file mode 100644 index 00000000000..9b9ba2fc26e --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ArrayAnyValueMarshaler.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import io.opentelemetry.proto.common.v1.internal.ArrayValue; +import java.io.IOException; +import java.util.List; +import java.util.function.Function; + +final class ArrayAnyValueMarshaler extends MarshalerWithSize { + private final Marshaler value; + + private ArrayAnyValueMarshaler(ArrayValueMarshaler value) { + super(calculateSize(value)); + this.value = value; + } + + static MarshalerWithSize createAnyValue(List> values) { + return createInternal(values, AnyValueMarshaler::create); + } + + static MarshalerWithSize createString(List values) { + return createInternal(values, StringAnyValueMarshaler::create); + } + + static MarshalerWithSize createBool(List values) { + return createInternal(values, BoolAnyValueMarshaler::create); + } + + static MarshalerWithSize createInt(List values) { + return createInternal(values, IntAnyValueMarshaler::create); + } + + static MarshalerWithSize createDouble(List values) { + return createInternal(values, DoubleAnyValueMarshaler::create); + } + + private static MarshalerWithSize createInternal( + List values, Function initializer) { + int len = values.size(); + Marshaler[] marshalers = new Marshaler[len]; + for (int i = 0; i < len; i++) { + marshalers[i] = initializer.apply(values.get(i)); + } + return new ArrayAnyValueMarshaler(new ArrayValueMarshaler(marshalers)); + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.serializeMessage(AnyValue.ARRAY_VALUE, value); + } + + private static int calculateSize(Marshaler value) { + return MarshalerUtil.sizeMessage(AnyValue.ARRAY_VALUE, value); + } + + private static class ArrayValueMarshaler extends MarshalerWithSize { + + private final Marshaler[] values; + + private ArrayValueMarshaler(Marshaler[] values) { + super(calculateSize(values)); + this.values = values; + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.serializeRepeatedMessage(ArrayValue.VALUES, values); + } + + private static int calculateSize(Marshaler[] values) { + return MarshalerUtil.sizeRepeatedMessage(ArrayValue.VALUES, values); + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ArrayAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ArrayAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..d6b9b117add --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ArrayAnyValueStatelessMarshaler.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.common.v1.internal.ArrayValue; +import java.io.IOException; +import java.util.List; + +/** A Marshaler of array values. See {@link ArrayAnyValueMarshaler}. */ +final class ArrayAnyValueStatelessMarshaler implements StatelessMarshaler>> { + + static final ArrayAnyValueStatelessMarshaler INSTANCE = new ArrayAnyValueStatelessMarshaler(); + + private ArrayAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, List> value, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + ArrayValue.VALUES, value, AnyValueStatelessMarshaler.INSTANCE, context); + } + + @Override + public int getBinarySerializedSize(List> value, MarshalerContext context) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ArrayValue.VALUES, value, AnyValueStatelessMarshaler.INSTANCE, context); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeArrayAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeArrayAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..db92ca1e7dc --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeArrayAnyValueStatelessMarshaler.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.AttributeType; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.common.v1.internal.ArrayValue; +import java.io.IOException; +import java.util.List; + +/** See {@link ArrayAnyValueMarshaler}. */ +final class AttributeArrayAnyValueStatelessMarshaler + implements StatelessMarshaler2> { + static final AttributeArrayAnyValueStatelessMarshaler INSTANCE = + new AttributeArrayAnyValueStatelessMarshaler<>(); + + private AttributeArrayAnyValueStatelessMarshaler() {} + + @SuppressWarnings("unchecked") + @Override + public void writeTo(Serializer output, AttributeType type, List list, MarshalerContext context) + throws IOException { + switch (type) { + case STRING_ARRAY: + output.serializeRepeatedMessageWithContext( + ArrayValue.VALUES, + (List) list, + StringAnyValueStatelessMarshaler.INSTANCE, + context); + return; + case LONG_ARRAY: + output.serializeRepeatedMessageWithContext( + ArrayValue.VALUES, (List) list, IntAnyValueStatelessMarshaler.INSTANCE, context); + return; + case BOOLEAN_ARRAY: + output.serializeRepeatedMessageWithContext( + ArrayValue.VALUES, + (List) list, + BoolAnyValueStatelessMarshaler.INSTANCE, + context); + return; + case DOUBLE_ARRAY: + output.serializeRepeatedMessageWithContext( + ArrayValue.VALUES, + (List) list, + DoubleAnyValueStatelessMarshaler.INSTANCE, + context); + return; + default: + throw new IllegalArgumentException("Unsupported attribute type."); + } + } + + @SuppressWarnings("unchecked") + @Override + public int getBinarySerializedSize(AttributeType type, List list, MarshalerContext context) { + switch (type) { + case STRING_ARRAY: + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ArrayValue.VALUES, + (List) list, + StringAnyValueStatelessMarshaler.INSTANCE, + context); + case LONG_ARRAY: + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ArrayValue.VALUES, (List) list, IntAnyValueStatelessMarshaler.INSTANCE, context); + case BOOLEAN_ARRAY: + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ArrayValue.VALUES, + (List) list, + BoolAnyValueStatelessMarshaler.INSTANCE, + context); + case DOUBLE_ARRAY: + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ArrayValue.VALUES, + (List) list, + DoubleAnyValueStatelessMarshaler.INSTANCE, + context); + default: + throw new IllegalArgumentException("Unsupported attribute type."); + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java new file mode 100644 index 00000000000..3f3ff738074 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValue.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import java.util.ArrayList; +import java.util.List; + +/** + * Key-value pair of {@link AttributeKey} key and its corresponding value. + * + *

    Conceptually if {@link Attributes} is a Map, then this is a Map.Entry. Note that whilst {@link + * KeyValue} is similar, this class holds type information on the Key rather than the value. + * + *

    NOTE: This class is only used in the profiling signal, and exists in this module and package + * because its a common dependency of the modules that use it. Long term, it probably makes more + * sense to live in {@code opentelemetry-sdk-profiles} once such a module exists. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface AttributeKeyValue { + + /** Returns a {@link AttributeKeyValue} for the given {@link AttributeKey} and {@code value}. */ + static AttributeKeyValue of(AttributeKey attributeKey, T value) { + return AttributeKeyValueImpl.create(attributeKey, value); + } + + /** Returns a List corresponding to the provided Map. This is a copy, not a view. */ + @SuppressWarnings("unchecked") + static List> of(Attributes attributes) { + List> result = new ArrayList<>(attributes.size()); + attributes.forEach((key, value) -> { + result.add(of((AttributeKey) key, (T) value)); + }); + return result; + } + + /** Returns the key. */ + AttributeKey getAttributeKey(); + + /** Returns the value. */ + T getValue(); +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueImpl.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueImpl.java new file mode 100644 index 00000000000..c4f6cdf89ca --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueImpl.java @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.AttributeKey; + +@AutoValue +abstract class AttributeKeyValueImpl implements AttributeKeyValue { + + AttributeKeyValueImpl() {} + + static AttributeKeyValueImpl create(AttributeKey attributeKey, T value) { + return new AutoValue_AttributeKeyValueImpl(attributeKey, value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueStatelessMarshaler.java new file mode 100644 index 00000000000..fb1e5557d5b --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueStatelessMarshaler.java @@ -0,0 +1,153 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.AttributeType; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.internal.InternalAttributeKeyImpl; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import io.opentelemetry.proto.common.v1.internal.KeyValue; +import java.io.IOException; +import java.util.List; + +/** + * A Marshaler of key value pairs. See {@link KeyValueMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AttributeKeyValueStatelessMarshaler + implements StatelessMarshaler2, Object> { + public static final AttributeKeyValueStatelessMarshaler INSTANCE = + new AttributeKeyValueStatelessMarshaler(); + private static final byte[] EMPTY_BYTES = new byte[0]; + + private AttributeKeyValueStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, AttributeKey attributeKey, Object value, MarshalerContext context) + throws IOException { + if (attributeKey.getKey().isEmpty()) { + output.serializeString(KeyValue.KEY, EMPTY_BYTES); + } else if (attributeKey instanceof InternalAttributeKeyImpl) { + byte[] keyUtf8 = ((InternalAttributeKeyImpl) attributeKey).getKeyUtf8(); + output.serializeString(KeyValue.KEY, keyUtf8); + } else { + output.serializeStringWithContext(KeyValue.KEY, attributeKey.getKey(), context); + } + output.serializeMessageWithContext( + KeyValue.VALUE, attributeKey, value, ValueStatelessMarshaler.INSTANCE, context); + } + + @Override + public int getBinarySerializedSize( + AttributeKey attributeKey, Object value, MarshalerContext context) { + int size = 0; + if (!attributeKey.getKey().isEmpty()) { + if (attributeKey instanceof InternalAttributeKeyImpl) { + byte[] keyUtf8 = ((InternalAttributeKeyImpl) attributeKey).getKeyUtf8(); + size += MarshalerUtil.sizeBytes(KeyValue.KEY, keyUtf8); + } else { + size += + StatelessMarshalerUtil.sizeStringWithContext( + KeyValue.KEY, attributeKey.getKey(), context); + } + } + size += + StatelessMarshalerUtil.sizeMessageWithContext( + KeyValue.VALUE, attributeKey, value, ValueStatelessMarshaler.INSTANCE, context); + + return size; + } + + private static class ValueStatelessMarshaler + implements StatelessMarshaler2, Object> { + static final ValueStatelessMarshaler INSTANCE = new ValueStatelessMarshaler(); + + @SuppressWarnings("unchecked") + @Override + public int getBinarySerializedSize( + AttributeKey attributeKey, Object value, MarshalerContext context) { + AttributeType attributeType = attributeKey.getType(); + switch (attributeType) { + case STRING: + return StringAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (String) value, context); + case LONG: + return IntAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Long) value, context); + case BOOLEAN: + return BoolAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Boolean) value, context); + case DOUBLE: + return DoubleAnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Double) value, context); + case STRING_ARRAY: + case LONG_ARRAY: + case BOOLEAN_ARRAY: + case DOUBLE_ARRAY: + return StatelessMarshalerUtil.sizeMessageWithContext( + AnyValue.ARRAY_VALUE, + attributeType, + (List) value, + AttributeArrayAnyValueStatelessMarshaler.INSTANCE, + context); + case VALUE: + return AnyValueStatelessMarshaler.INSTANCE.getBinarySerializedSize( + (Value) value, context); + } + // Error prone ensures the switch statement is complete, otherwise only can happen with + // unaligned versions which are not supported. + throw new IllegalArgumentException("Unsupported attribute type."); + } + + @SuppressWarnings("unchecked") + @Override + public void writeTo( + Serializer output, AttributeKey attributeKey, Object value, MarshalerContext context) + throws IOException { + AttributeType attributeType = attributeKey.getType(); + switch (attributeType) { + case STRING: + StringAnyValueStatelessMarshaler.INSTANCE.writeTo(output, (String) value, context); + return; + case LONG: + IntAnyValueStatelessMarshaler.INSTANCE.writeTo(output, (Long) value, context); + return; + case BOOLEAN: + BoolAnyValueStatelessMarshaler.INSTANCE.writeTo(output, (Boolean) value, context); + return; + case DOUBLE: + DoubleAnyValueStatelessMarshaler.INSTANCE.writeTo(output, (Double) value, context); + return; + case STRING_ARRAY: + case LONG_ARRAY: + case BOOLEAN_ARRAY: + case DOUBLE_ARRAY: + output.serializeMessageWithContext( + AnyValue.ARRAY_VALUE, + attributeType, + (List) value, + AttributeArrayAnyValueStatelessMarshaler.INSTANCE, + context); + return; + case VALUE: + AnyValueStatelessMarshaler.INSTANCE.writeTo(output, (Value) value, context); + return; + } + // Error prone ensures the switch statement is complete, otherwise only can happen with + // unaligned versions which are not supported. + throw new IllegalArgumentException("Unsupported attribute type."); + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BoolAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BoolAnyValueMarshaler.java new file mode 100644 index 00000000000..2293c0c0e58 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BoolAnyValueMarshaler.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +final class BoolAnyValueMarshaler extends MarshalerWithSize { + + private final boolean value; + + private BoolAnyValueMarshaler(boolean value) { + super(calculateSize(value)); + this.value = value; + } + + static MarshalerWithSize create(boolean value) { + return new BoolAnyValueMarshaler(value); + } + + @Override + public void writeTo(Serializer output) throws IOException { + // Do not call serialize* method because we always have to write the message tag even if the + // value is empty since it's a oneof. + output.writeBool(AnyValue.BOOL_VALUE, value); + } + + private static int calculateSize(boolean value) { + return AnyValue.BOOL_VALUE.getTagSize() + CodedOutputStream.computeBoolSizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BoolAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BoolAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..950aaa39f7d --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BoolAnyValueStatelessMarshaler.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +/** See {@link BoolAnyValueMarshaler}. */ +final class BoolAnyValueStatelessMarshaler implements StatelessMarshaler { + static final BoolAnyValueStatelessMarshaler INSTANCE = new BoolAnyValueStatelessMarshaler(); + + private BoolAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, Boolean value, MarshalerContext context) + throws IOException { + output.writeBool(AnyValue.BOOL_VALUE, value); + } + + @Override + public int getBinarySerializedSize(Boolean value, MarshalerContext context) { + return AnyValue.BOOL_VALUE.getTagSize() + CodedOutputStream.computeBoolSizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BytesAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BytesAnyValueMarshaler.java new file mode 100644 index 00000000000..516159141a1 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BytesAnyValueMarshaler.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; +import java.nio.ByteBuffer; + +final class BytesAnyValueMarshaler extends MarshalerWithSize { + + private final byte[] value; + + private BytesAnyValueMarshaler(byte[] value) { + super(calculateSize(value)); + this.value = value; + } + + static MarshalerWithSize create(Value value) { + ByteBuffer buf = value.getValue(); + byte[] bytes = new byte[buf.remaining()]; + // getValue() above returns a new ByteBuffer, so mutating its position here is safe + buf.get(bytes); + return new BytesAnyValueMarshaler(bytes); + } + + @Override + public void writeTo(Serializer output) throws IOException { + // Do not call serialize* method because we always have to write the message tag even if the + // value is empty since it's a oneof. + output.writeBytes(AnyValue.BYTES_VALUE, value); + } + + private static int calculateSize(byte[] value) { + return AnyValue.BYTES_VALUE.getTagSize() + CodedOutputStream.computeByteArraySizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BytesAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BytesAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..c7afff7756b --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/BytesAnyValueStatelessMarshaler.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; +import java.nio.ByteBuffer; + +/** See {@link BytesAnyValueMarshaler}. */ +final class BytesAnyValueStatelessMarshaler implements StatelessMarshaler> { + static final BytesAnyValueStatelessMarshaler INSTANCE = new BytesAnyValueStatelessMarshaler(); + + private BytesAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, Value value, MarshalerContext context) + throws IOException { + byte[] bytes = context.getData(byte[].class); + output.writeBytes(AnyValue.BYTES_VALUE, bytes); + } + + @Override + public int getBinarySerializedSize(Value value, MarshalerContext context) { + ByteBuffer buf = value.getValue(); + byte[] bytes = new byte[buf.remaining()]; + // getValue() above returns a new ByteBuffer, so mutating its position here is safe + buf.get(bytes); + context.addData(bytes); + return AnyValue.BYTES_VALUE.getTagSize() + CodedOutputStream.computeByteArraySizeNoTag(bytes); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/DoubleAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/DoubleAnyValueMarshaler.java new file mode 100644 index 00000000000..5837976c92d --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/DoubleAnyValueMarshaler.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +final class DoubleAnyValueMarshaler extends MarshalerWithSize { + + private final double value; + + private DoubleAnyValueMarshaler(double value) { + super(calculateSize(value)); + this.value = value; + } + + static MarshalerWithSize create(double value) { + return new DoubleAnyValueMarshaler(value); + } + + @Override + public void writeTo(Serializer output) throws IOException { + // Do not call serialize* method because we always have to write the message tag even if the + // value is empty since it's a oneof. + output.writeDouble(AnyValue.DOUBLE_VALUE, value); + } + + private static int calculateSize(double value) { + return AnyValue.DOUBLE_VALUE.getTagSize() + CodedOutputStream.computeDoubleSizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/DoubleAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/DoubleAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..7403b241ab2 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/DoubleAnyValueStatelessMarshaler.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +/** See {@link DoubleAnyValueMarshaler}. */ +final class DoubleAnyValueStatelessMarshaler implements StatelessMarshaler { + static final DoubleAnyValueStatelessMarshaler INSTANCE = new DoubleAnyValueStatelessMarshaler(); + + private DoubleAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, Double value, MarshalerContext context) + throws IOException { + output.writeDouble(AnyValue.DOUBLE_VALUE, value); + } + + @Override + public int getBinarySerializedSize(Double value, MarshalerContext context) { + return AnyValue.DOUBLE_VALUE.getTagSize() + CodedOutputStream.computeDoubleSizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/EmptyAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/EmptyAnyValueMarshaler.java new file mode 100644 index 00000000000..d7ee4242475 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/EmptyAnyValueMarshaler.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; + +/** + * A Marshaler of empty {@link io.opentelemetry.proto.common.v1.internal.AnyValue}. Represents an + * AnyValue with no field set. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class EmptyAnyValueMarshaler extends MarshalerWithSize { + + static final EmptyAnyValueMarshaler INSTANCE = new EmptyAnyValueMarshaler(); + + private EmptyAnyValueMarshaler() { + super(0); + } + + @Override + public void writeTo(Serializer output) { + // no field to write + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/EntityRefMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/EntityRefMarshaler.java new file mode 100644 index 00000000000..d11ac55fa16 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/EntityRefMarshaler.java @@ -0,0 +1,83 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.internal.StringUtils; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.EntityRef; +import io.opentelemetry.sdk.resources.internal.Entity; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import javax.annotation.Nullable; + +/** + * A Marshaler of {@link io.opentelemetry.sdk.resources.internal.Entity}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class EntityRefMarshaler extends MarshalerWithSize { + @Nullable private final byte[] schemaUrlUtf8; + private final byte[] typeUtf8; + private final byte[][] idKeysUtf8; + private final byte[][] descriptionKeysUtf8; + + @Override + protected void writeTo(Serializer output) throws IOException { + if (schemaUrlUtf8 != null) { + output.writeString(EntityRef.SCHEMA_URL, schemaUrlUtf8); + } + output.writeString(EntityRef.TYPE, typeUtf8); + output.writeRepeatedString(EntityRef.ID_KEYS, idKeysUtf8); + output.writeRepeatedString(EntityRef.DESCRIPTION_KEYS, descriptionKeysUtf8); + } + + /** Constructs an entity reference marshaler from a full entity. */ + static EntityRefMarshaler createForEntity(Entity e) { + byte[] schemaUrlUtf8 = null; + if (!StringUtils.isNullOrEmpty(e.getSchemaUrl())) { + schemaUrlUtf8 = e.getSchemaUrl().getBytes(StandardCharsets.UTF_8); + } + return new EntityRefMarshaler( + schemaUrlUtf8, + e.getType().getBytes(StandardCharsets.UTF_8), + e.getId().asMap().keySet().stream() + .map(key -> key.getKey().getBytes(StandardCharsets.UTF_8)) + .toArray(byte[][]::new), + e.getDescription().asMap().keySet().stream() + .map(key -> key.getKey().getBytes(StandardCharsets.UTF_8)) + .toArray(byte[][]::new)); + } + + private EntityRefMarshaler( + @Nullable byte[] schemaUrlUtf8, + byte[] typeUtf8, + byte[][] idKeysUtf8, + byte[][] descriptionKeysUtf8) { + super(calculateSize(schemaUrlUtf8, typeUtf8, idKeysUtf8, descriptionKeysUtf8)); + this.schemaUrlUtf8 = schemaUrlUtf8; + this.typeUtf8 = typeUtf8; + this.idKeysUtf8 = idKeysUtf8; + this.descriptionKeysUtf8 = descriptionKeysUtf8; + } + + private static int calculateSize( + @Nullable byte[] schemaUrlUtf8, + byte[] typeUtf8, + byte[][] idKeysUtf8, + byte[][] descriptionKeysUtf8) { + int size = 0; + if (schemaUrlUtf8 != null) { + size += MarshalerUtil.sizeBytes(EntityRef.SCHEMA_URL, schemaUrlUtf8); + } + size += MarshalerUtil.sizeBytes(EntityRef.TYPE, typeUtf8); + size += MarshalerUtil.sizeRepeatedString(EntityRef.ID_KEYS, idKeysUtf8); + size += MarshalerUtil.sizeRepeatedString(EntityRef.DESCRIPTION_KEYS, descriptionKeysUtf8); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/InstrumentationScopeMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/InstrumentationScopeMarshaler.java new file mode 100644 index 00000000000..c5466cad479 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/InstrumentationScopeMarshaler.java @@ -0,0 +1,101 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.context.internal.shaded.WeakConcurrentMap; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.InstrumentationScope; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; + +/** + * A Marshaler of {@link InstrumentationScopeInfo}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class InstrumentationScopeMarshaler extends MarshalerWithSize { + + private static final WeakConcurrentMap + SCOPE_MARSHALER_CACHE = new WeakConcurrentMap.WithInlinedExpunction<>(); + + private final byte[] serializedBinary; + private final String serializedJson; + + /** Returns a Marshaler for InstrumentationScopeInfo. */ + public static InstrumentationScopeMarshaler create(InstrumentationScopeInfo scopeInfo) { + InstrumentationScopeMarshaler cached = SCOPE_MARSHALER_CACHE.get(scopeInfo); + if (cached == null) { + // Since WeakConcurrentMap doesn't support computeIfAbsent, we may end up doing the conversion + // a few times until the cache gets filled which is fine. + byte[] name = MarshalerUtil.toBytes(scopeInfo.getName()); + byte[] version = MarshalerUtil.toBytes(scopeInfo.getVersion()); + KeyValueMarshaler[] attributes = + KeyValueMarshaler.createForAttributes(scopeInfo.getAttributes()); + + RealInstrumentationScopeMarshaler realMarshaler = + new RealInstrumentationScopeMarshaler(name, version, attributes); + + ByteArrayOutputStream binaryBos = + new ByteArrayOutputStream(realMarshaler.getBinarySerializedSize()); + + try { + realMarshaler.writeBinaryTo(binaryBos); + } catch (IOException e) { + throw new UncheckedIOException( + "Serialization error, this is likely a bug in OpenTelemetry.", e); + } + + String json = MarshalerUtil.preserializeJsonFields(realMarshaler); + + cached = new InstrumentationScopeMarshaler(binaryBos.toByteArray(), json); + SCOPE_MARSHALER_CACHE.put(scopeInfo, cached); + } + return cached; + } + + private InstrumentationScopeMarshaler(byte[] binary, String json) { + super(binary.length); + serializedBinary = binary; + serializedJson = json; + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.writeSerializedMessage(serializedBinary, serializedJson); + } + + private static final class RealInstrumentationScopeMarshaler extends MarshalerWithSize { + + private final byte[] name; + private final byte[] version; + private final KeyValueMarshaler[] attributes; + + RealInstrumentationScopeMarshaler(byte[] name, byte[] version, KeyValueMarshaler[] attributes) { + super(computeSize(name, version, attributes)); + this.name = name; + this.version = version; + this.attributes = attributes; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeString(InstrumentationScope.NAME, name); + output.serializeString(InstrumentationScope.VERSION, version); + output.serializeRepeatedMessage(InstrumentationScope.ATTRIBUTES, attributes); + } + + private static int computeSize(byte[] name, byte[] version, KeyValueMarshaler[] attributes) { + return MarshalerUtil.sizeBytes(InstrumentationScope.NAME, name) + + MarshalerUtil.sizeBytes(InstrumentationScope.VERSION, version) + + MarshalerUtil.sizeRepeatedMessage(InstrumentationScope.ATTRIBUTES, attributes); + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/InstrumentationScopeMarshaller.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/InstrumentationScopeMarshaller.java deleted file mode 100644 index 1478e880b36..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/InstrumentationScopeMarshaller.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.otlp; - -import io.opentelemetry.context.internal.shaded.WeakConcurrentMap; -import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; -import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; -import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.proto.common.v1.internal.InstrumentationScope; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; - -/** - * A Marshaler of {@link InstrumentationScopeInfo}. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class InstrumentationScopeMarshaller extends MarshalerWithSize { - - private static final WeakConcurrentMap - SCOPE_MARSHALER_CACHE = new WeakConcurrentMap.WithInlinedExpunction<>(); - - private final byte[] serializedBinary; - private final String serializedJson; - - /** Returns a Marshaler for InstrumentationScopeInfo. */ - public static InstrumentationScopeMarshaller create(InstrumentationScopeInfo scopeInfo) { - InstrumentationScopeMarshaller cached = SCOPE_MARSHALER_CACHE.get(scopeInfo); - if (cached == null) { - // Since WeakConcurrentMap doesn't support computeIfAbsent, we may end up doing the conversion - // a few times until the cache gets filled which is fine. - byte[] name = MarshalerUtil.toBytes(scopeInfo.getName()); - byte[] version = MarshalerUtil.toBytes(scopeInfo.getVersion()); - - RealInstrumentationScopeMarshaler realMarshaler = - new RealInstrumentationScopeMarshaler(name, version); - - ByteArrayOutputStream binaryBos = - new ByteArrayOutputStream(realMarshaler.getBinarySerializedSize()); - - try { - realMarshaler.writeBinaryTo(binaryBos); - } catch (IOException e) { - throw new UncheckedIOException( - "Serialization error, this is likely a bug in OpenTelemetry.", e); - } - - String json = MarshalerUtil.preserializeJsonFields(realMarshaler); - - cached = new InstrumentationScopeMarshaller(binaryBos.toByteArray(), json); - SCOPE_MARSHALER_CACHE.put(scopeInfo, cached); - } - return cached; - } - - private InstrumentationScopeMarshaller(byte[] binary, String json) { - super(binary.length); - serializedBinary = binary; - serializedJson = json; - } - - @Override - public void writeTo(Serializer output) throws IOException { - output.writeSerializedMessage(serializedBinary, serializedJson); - } - - private static final class RealInstrumentationScopeMarshaler extends MarshalerWithSize { - - private final byte[] name; - private final byte[] version; - - RealInstrumentationScopeMarshaler(byte[] name, byte[] version) { - super(computeSize(name, version)); - this.name = name; - this.version = version; - } - - @Override - protected void writeTo(Serializer output) throws IOException { - output.serializeString(InstrumentationScope.NAME, name); - output.serializeString(InstrumentationScope.VERSION, version); - } - - private static int computeSize(byte[] name, byte[] version) { - return MarshalerUtil.sizeBytes(InstrumentationScope.NAME, name) - + MarshalerUtil.sizeBytes(InstrumentationScope.VERSION, version); - } - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/IntAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/IntAnyValueMarshaler.java new file mode 100644 index 00000000000..498c60e76bb --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/IntAnyValueMarshaler.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +final class IntAnyValueMarshaler extends MarshalerWithSize { + + private final long value; + + private IntAnyValueMarshaler(long value) { + super(calculateSize(value)); + this.value = value; + } + + static MarshalerWithSize create(long value) { + return new IntAnyValueMarshaler(value); + } + + @Override + public void writeTo(Serializer output) throws IOException { + // Do not call serialize* method because we always have to write the message tag even if the + // value is empty since it's a oneof. + output.writeInt64(AnyValue.INT_VALUE, value); + } + + private static int calculateSize(long value) { + return AnyValue.INT_VALUE.getTagSize() + CodedOutputStream.computeInt64SizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/IntAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/IntAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..407a586ec80 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/IntAnyValueStatelessMarshaler.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +/** See {@link IntAnyValueMarshaler}. */ +final class IntAnyValueStatelessMarshaler implements StatelessMarshaler { + static final IntAnyValueStatelessMarshaler INSTANCE = new IntAnyValueStatelessMarshaler(); + + private IntAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, Long value, MarshalerContext context) throws IOException { + output.writeInt64(AnyValue.INT_VALUE, value); + } + + @Override + public int getBinarySerializedSize(Long value, MarshalerContext context) { + return AnyValue.INT_VALUE.getTagSize() + CodedOutputStream.computeInt64SizeNoTag(value); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueListAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueListAnyValueMarshaler.java new file mode 100644 index 00000000000..1fb20cc269c --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueListAnyValueMarshaler.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import io.opentelemetry.proto.common.v1.internal.KeyValueList; +import java.io.IOException; +import java.util.List; + +final class KeyValueListAnyValueMarshaler extends MarshalerWithSize { + + private final Marshaler value; + + KeyValueListAnyValueMarshaler(KeyValueListMarshaler value) { + super(calculateSize(value)); + this.value = value; + } + + static MarshalerWithSize create(List values) { + int len = values.size(); + KeyValueMarshaler[] marshalers = new KeyValueMarshaler[values.size()]; + for (int i = 0; i < len; i++) { + marshalers[i] = KeyValueMarshaler.createForKeyValue(values.get(i)); + } + return new KeyValueListAnyValueMarshaler(new KeyValueListMarshaler(marshalers)); + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.serializeMessage(AnyValue.KVLIST_VALUE, value); + } + + private static int calculateSize(Marshaler value) { + return MarshalerUtil.sizeMessage(AnyValue.KVLIST_VALUE, value); + } + + static class KeyValueListMarshaler extends MarshalerWithSize { + + private final Marshaler[] values; + + KeyValueListMarshaler(KeyValueMarshaler[] values) { + super(calculateSize(values)); + this.values = values; + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.serializeRepeatedMessage(KeyValueList.VALUES, values); + } + + private static int calculateSize(Marshaler[] values) { + return MarshalerUtil.sizeRepeatedMessage(KeyValueList.VALUES, values); + } + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueListAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueListAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..6bb7ef8d210 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueListAnyValueStatelessMarshaler.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.common.v1.internal.KeyValueList; +import java.io.IOException; +import java.util.List; + +/** A Marshaler of key value pairs. See {@link KeyValueListAnyValueMarshaler}. */ +final class KeyValueListAnyValueStatelessMarshaler implements StatelessMarshaler> { + + static final KeyValueListAnyValueStatelessMarshaler INSTANCE = + new KeyValueListAnyValueStatelessMarshaler(); + + private KeyValueListAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, List value, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + KeyValueList.VALUES, value, KeyValueStatelessMarshaler.INSTANCE, context); + } + + @Override + public int getBinarySerializedSize(List value, MarshalerContext context) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + KeyValueList.VALUES, value, KeyValueStatelessMarshaler.INSTANCE, context); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java index dabd27cbb02..b2f77128b73 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueMarshaler.java @@ -7,51 +7,86 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.internal.InternalAttributeKeyImpl; -import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; import io.opentelemetry.exporter.internal.marshal.Marshaler; import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.proto.common.v1.internal.AnyValue; -import io.opentelemetry.proto.common.v1.internal.ArrayValue; -import io.opentelemetry.proto.common.v1.internal.KeyValue; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.function.BiConsumer; +import java.util.function.Consumer; /** - * A Marshaler of {@link Attributes}. + * A Marshaler of key value pairs. * *

    This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ public final class KeyValueMarshaler extends MarshalerWithSize { + private static final byte[] EMPTY_BYTES = new byte[0]; private static final KeyValueMarshaler[] EMPTY_REPEATED = new KeyValueMarshaler[0]; + private final byte[] keyUtf8; + private final Marshaler value; + + KeyValueMarshaler(byte[] keyUtf8, Marshaler value) { + super(calculateSize(keyUtf8, value)); + this.keyUtf8 = keyUtf8; + this.value = value; + } + + /** Returns Marshaler for the given KeyValue. */ + public static KeyValueMarshaler createForKeyValue(KeyValue keyValue) { + return new KeyValueMarshaler( + keyValue.getKey().getBytes(StandardCharsets.UTF_8), + AnyValueMarshaler.create(keyValue.getValue())); + } + /** Returns Marshalers for the given Attributes. */ - public static KeyValueMarshaler[] createRepeated(Attributes attributes) { + @SuppressWarnings("AvoidObjectArrays") + public static KeyValueMarshaler[] createForAttributes(Attributes attributes) { if (attributes.isEmpty()) { return EMPTY_REPEATED; } - KeyValueMarshaler[] attributeMarshalers = new KeyValueMarshaler[attributes.size()]; + KeyValueMarshaler[] marshalers = new KeyValueMarshaler[attributes.size()]; attributes.forEach( new BiConsumer, Object>() { int index = 0; @Override public void accept(AttributeKey attributeKey, Object o) { - attributeMarshalers[index++] = KeyValueMarshaler.create(attributeKey, o); + marshalers[index++] = create(attributeKey, o); } }); - return attributeMarshalers; + return marshalers; } - private final byte[] keyUtf8; - private final Marshaler value; + @SuppressWarnings("AvoidObjectArrays") + public static KeyValueMarshaler[] createRepeated(List> items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + KeyValueMarshaler[] keyValueMarshalers = new KeyValueMarshaler[items.size()]; + items.forEach(item -> + new Consumer>() { + int index = 0; + + @Override + public void accept(AttributeKeyValue attributeKeyValue) { + keyValueMarshalers[index++] = + KeyValueMarshaler.create( + attributeKeyValue.getAttributeKey(), attributeKeyValue.getValue()); + } + }); + return keyValueMarshalers; + } @SuppressWarnings("unchecked") private static KeyValueMarshaler create(AttributeKey attributeKey, Object value) { @@ -65,188 +100,44 @@ private static KeyValueMarshaler create(AttributeKey attributeKey, Object val } switch (attributeKey.getType()) { case STRING: - return new KeyValueMarshaler( - keyUtf8, new StringAnyValueMarshaler(MarshalerUtil.toBytes((String) value))); + return new KeyValueMarshaler(keyUtf8, StringAnyValueMarshaler.create((String) value)); case LONG: - return new KeyValueMarshaler(keyUtf8, new Int64AnyValueMarshaler((long) value)); + return new KeyValueMarshaler(keyUtf8, IntAnyValueMarshaler.create((long) value)); case BOOLEAN: - return new KeyValueMarshaler(keyUtf8, new BoolAnyValueMarshaler((boolean) value)); + return new KeyValueMarshaler(keyUtf8, BoolAnyValueMarshaler.create((boolean) value)); case DOUBLE: - return new KeyValueMarshaler(keyUtf8, new AnyDoubleFieldMarshaler((double) value)); + return new KeyValueMarshaler(keyUtf8, DoubleAnyValueMarshaler.create((double) value)); case STRING_ARRAY: return new KeyValueMarshaler( - keyUtf8, - new ArrayAnyValueMarshaler(ArrayValueMarshaler.createString((List) value))); + keyUtf8, ArrayAnyValueMarshaler.createString((List) value)); case LONG_ARRAY: - return new KeyValueMarshaler( - keyUtf8, - new ArrayAnyValueMarshaler(ArrayValueMarshaler.createInt64((List) value))); + return new KeyValueMarshaler(keyUtf8, ArrayAnyValueMarshaler.createInt((List) value)); case BOOLEAN_ARRAY: return new KeyValueMarshaler( - keyUtf8, - new ArrayAnyValueMarshaler(ArrayValueMarshaler.createBool((List) value))); + keyUtf8, ArrayAnyValueMarshaler.createBool((List) value)); case DOUBLE_ARRAY: return new KeyValueMarshaler( - keyUtf8, - new ArrayAnyValueMarshaler(ArrayValueMarshaler.createDouble((List) value))); + keyUtf8, ArrayAnyValueMarshaler.createDouble((List) value)); + case VALUE: + return new KeyValueMarshaler(keyUtf8, AnyValueMarshaler.create((Value) value)); } // Error prone ensures the switch statement is complete, otherwise only can happen with // unaligned versions which are not supported. throw new IllegalArgumentException("Unsupported attribute type."); } - private KeyValueMarshaler(byte[] keyUtf8, Marshaler value) { - super(calculateSize(keyUtf8, value)); - this.keyUtf8 = keyUtf8; - this.value = value; - } - @Override public void writeTo(Serializer output) throws IOException { - output.serializeString(KeyValue.KEY, keyUtf8); - output.serializeMessage(KeyValue.VALUE, value); + output.serializeString(io.opentelemetry.proto.common.v1.internal.KeyValue.KEY, keyUtf8); + output.serializeMessage(io.opentelemetry.proto.common.v1.internal.KeyValue.VALUE, value); } private static int calculateSize(byte[] keyUtf8, Marshaler value) { int size = 0; - size += MarshalerUtil.sizeBytes(KeyValue.KEY, keyUtf8); - size += MarshalerUtil.sizeMessage(KeyValue.VALUE, value); + size += + MarshalerUtil.sizeBytes(io.opentelemetry.proto.common.v1.internal.KeyValue.KEY, keyUtf8); + size += + MarshalerUtil.sizeMessage(io.opentelemetry.proto.common.v1.internal.KeyValue.VALUE, value); return size; } - - private static class BoolAnyValueMarshaler extends MarshalerWithSize { - - private final boolean value; - - BoolAnyValueMarshaler(boolean value) { - super(calculateSize(value)); - this.value = value; - } - - @Override - public void writeTo(Serializer output) throws IOException { - // Do not call serialize* method because we always have to write the message tag even if the - // value is empty since it's a oneof. - output.writeBool(AnyValue.BOOL_VALUE, value); - } - - private static int calculateSize(boolean value) { - return AnyValue.BOOL_VALUE.getTagSize() + CodedOutputStream.computeBoolSizeNoTag(value); - } - } - - private static class Int64AnyValueMarshaler extends MarshalerWithSize { - - private final long value; - - Int64AnyValueMarshaler(long value) { - super(calculateSize(value)); - this.value = value; - } - - @Override - public void writeTo(Serializer output) throws IOException { - // Do not call serialize* method because we always have to write the message tag even if the - // value is empty since it's a oneof. - output.writeInt64(AnyValue.INT_VALUE, value); - } - - private static int calculateSize(long value) { - return AnyValue.INT_VALUE.getTagSize() + CodedOutputStream.computeInt64SizeNoTag(value); - } - } - - private static class AnyDoubleFieldMarshaler extends MarshalerWithSize { - - private final double value; - - AnyDoubleFieldMarshaler(double value) { - super(calculateSize(value)); - this.value = value; - } - - @Override - public void writeTo(Serializer output) throws IOException { - // Do not call serialize* method because we always have to write the message tag even if the - // value is empty since it's a oneof. - output.writeDouble(AnyValue.DOUBLE_VALUE, value); - } - - private static int calculateSize(double value) { - return AnyValue.DOUBLE_VALUE.getTagSize() + CodedOutputStream.computeDoubleSizeNoTag(value); - } - } - - private static class ArrayAnyValueMarshaler extends MarshalerWithSize { - private final Marshaler value; - - private ArrayAnyValueMarshaler(Marshaler value) { - super(calculateSize(value)); - this.value = value; - } - - @Override - public void writeTo(Serializer output) throws IOException { - output.serializeMessage(AnyValue.ARRAY_VALUE, value); - } - - private static int calculateSize(Marshaler value) { - return MarshalerUtil.sizeMessage(AnyValue.ARRAY_VALUE, value); - } - } - - private static class ArrayValueMarshaler extends MarshalerWithSize { - - static ArrayValueMarshaler createString(List values) { - int len = values.size(); - Marshaler[] marshalers = new StringAnyValueMarshaler[len]; - for (int i = 0; i < len; i++) { - marshalers[i] = new StringAnyValueMarshaler(values.get(i).getBytes(StandardCharsets.UTF_8)); - } - return new ArrayValueMarshaler(marshalers); - } - - static ArrayValueMarshaler createBool(List values) { - int len = values.size(); - Marshaler[] marshalers = new BoolAnyValueMarshaler[len]; - for (int i = 0; i < len; i++) { - marshalers[i] = new BoolAnyValueMarshaler(values.get(i)); - } - return new ArrayValueMarshaler(marshalers); - } - - static ArrayValueMarshaler createInt64(List values) { - int len = values.size(); - Marshaler[] marshalers = new Int64AnyValueMarshaler[len]; - for (int i = 0; i < len; i++) { - marshalers[i] = new Int64AnyValueMarshaler(values.get(i)); - } - return new ArrayValueMarshaler(marshalers); - } - - static ArrayValueMarshaler createDouble(List values) { - int len = values.size(); - Marshaler[] marshalers = new AnyDoubleFieldMarshaler[len]; - for (int i = 0; i < len; i++) { - marshalers[i] = new AnyDoubleFieldMarshaler(values.get(i)); - } - return new ArrayValueMarshaler(marshalers); - } - - private final Marshaler[] values; - - private ArrayValueMarshaler(Marshaler[] values) { - super(calculateSize(values)); - this.values = values; - } - - @Override - public void writeTo(Serializer output) throws IOException { - output.serializeRepeatedMessage(ArrayValue.VALUES, values); - } - - private static int calculateSize(Marshaler[] values) { - return MarshalerUtil.sizeRepeatedMessage(ArrayValue.VALUES, values); - } - } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueStatelessMarshaler.java new file mode 100644 index 00000000000..6d124b02b07 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/KeyValueStatelessMarshaler.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import java.io.IOException; + +/** + * A Marshaler of key value pairs. See {@link KeyValueMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class KeyValueStatelessMarshaler implements StatelessMarshaler { + + public static final KeyValueStatelessMarshaler INSTANCE = new KeyValueStatelessMarshaler(); + private static final byte[] EMPTY_BYTES = new byte[0]; + + private KeyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, KeyValue value, MarshalerContext context) + throws IOException { + String key = value.getKey(); + if (key.isEmpty()) { + output.serializeString(io.opentelemetry.proto.common.v1.internal.KeyValue.KEY, EMPTY_BYTES); + } else { + output.serializeStringWithContext( + io.opentelemetry.proto.common.v1.internal.KeyValue.KEY, key, context); + } + output.serializeMessageWithContext( + io.opentelemetry.proto.common.v1.internal.KeyValue.VALUE, + value.getValue(), + AnyValueStatelessMarshaler.INSTANCE, + context); + } + + @Override + public int getBinarySerializedSize(KeyValue value, MarshalerContext context) { + int size = 0; + String key = value.getKey(); + if (!key.isEmpty()) { + size += + StatelessMarshalerUtil.sizeStringWithContext( + io.opentelemetry.proto.common.v1.internal.KeyValue.KEY, key, context); + } + size += + StatelessMarshalerUtil.sizeMessageWithContext( + io.opentelemetry.proto.common.v1.internal.KeyValue.VALUE, + value.getValue(), + AnyValueStatelessMarshaler.INSTANCE, + context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshaler.java index 259f0070000..73b3df96e09 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshaler.java @@ -10,6 +10,7 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.proto.resource.v1.internal.Resource; +import io.opentelemetry.sdk.resources.internal.EntityUtil; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; @@ -36,7 +37,11 @@ public static ResourceMarshaler create(io.opentelemetry.sdk.resources.Resource r // a few times until the cache gets filled which is fine. RealResourceMarshaler realMarshaler = - new RealResourceMarshaler(KeyValueMarshaler.createRepeated(resource.getAttributes())); + new RealResourceMarshaler( + KeyValueMarshaler.createForAttributes(resource.getAttributes()), + EntityUtil.getEntities(resource).stream() + .map(EntityRefMarshaler::createForEntity) + .toArray(EntityRefMarshaler[]::new)); ByteArrayOutputStream binaryBos = new ByteArrayOutputStream(realMarshaler.getBinarySerializedSize()); @@ -69,19 +74,26 @@ public void writeTo(Serializer output) throws IOException { private static final class RealResourceMarshaler extends MarshalerWithSize { private final KeyValueMarshaler[] attributes; + private final EntityRefMarshaler[] entityRefs; - private RealResourceMarshaler(KeyValueMarshaler[] attributes) { - super(calculateSize(attributes)); + private RealResourceMarshaler(KeyValueMarshaler[] attributes, EntityRefMarshaler[] entityRefs) { + super(calculateSize(attributes, entityRefs)); this.attributes = attributes; + this.entityRefs = entityRefs; } @Override protected void writeTo(Serializer output) throws IOException { output.serializeRepeatedMessage(Resource.ATTRIBUTES, attributes); + output.serializeRepeatedMessage(Resource.ENTITY_REFS, entityRefs); } - private static int calculateSize(KeyValueMarshaler[] attributeMarshalers) { - return MarshalerUtil.sizeRepeatedMessage(Resource.ATTRIBUTES, attributeMarshalers); + private static int calculateSize( + KeyValueMarshaler[] attributeMarshalers, EntityRefMarshaler[] entityRefs) { + int size = 0; + size += MarshalerUtil.sizeRepeatedMessage(Resource.ATTRIBUTES, attributeMarshalers); + size += MarshalerUtil.sizeRepeatedMessage(Resource.ENTITY_REFS, entityRefs); + return size; } } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueMarshaler.java index 81e1ab2c7be..1b3db2da32c 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueMarshaler.java @@ -6,6 +6,7 @@ package io.opentelemetry.exporter.internal.otlp; import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.proto.common.v1.internal.AnyValue; @@ -17,19 +18,21 @@ *

    This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ -public final class StringAnyValueMarshaler extends MarshalerWithSize { +final class StringAnyValueMarshaler extends MarshalerWithSize { private final byte[] valueUtf8; - public StringAnyValueMarshaler(byte[] valueUtf8) { + private StringAnyValueMarshaler(byte[] valueUtf8) { super(calculateSize(valueUtf8)); this.valueUtf8 = valueUtf8; } + static MarshalerWithSize create(String value) { + return new StringAnyValueMarshaler(MarshalerUtil.toBytes(value)); + } + @Override public void writeTo(Serializer output) throws IOException { - // Do not call serialize* method because we always have to write the message tag even if the - // value is empty since it's a oneof. output.writeString(AnyValue.STRING_VALUE, valueUtf8); } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueStatelessMarshaler.java new file mode 100644 index 00000000000..19fa98bc2e4 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/StringAnyValueStatelessMarshaler.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import io.opentelemetry.exporter.internal.marshal.CodedOutputStream; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.common.v1.internal.AnyValue; +import java.io.IOException; + +/** + * A Marshaler of string-valued {@link AnyValue}. See {@link StringAnyValueMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class StringAnyValueStatelessMarshaler implements StatelessMarshaler { + static final StringAnyValueStatelessMarshaler INSTANCE = new StringAnyValueStatelessMarshaler(); + + private StringAnyValueStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, String value, MarshalerContext context) + throws IOException { + output.writeStringWithContext(AnyValue.STRING_VALUE, value, context); + } + + @Override + public int getBinarySerializedSize(String value, MarshalerContext context) { + int utf8Size = StatelessMarshalerUtil.getUtf8Size(value, context); + return AnyValue.STRING_VALUE.getTagSize() + + CodedOutputStream.computeUInt32SizeNoTag(utf8Size) + + utf8Size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsMarshaler.java index 8a424a51fb5..6a7b437e8c6 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsMarshaler.java @@ -9,18 +9,18 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaller; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; import io.opentelemetry.proto.logs.v1.internal.ScopeLogs; import java.io.IOException; import java.util.List; final class InstrumentationScopeLogsMarshaler extends MarshalerWithSize { - private final InstrumentationScopeMarshaller instrumentationScope; + private final InstrumentationScopeMarshaler instrumentationScope; private final List logMarshalers; private final byte[] schemaUrlUtf8; InstrumentationScopeLogsMarshaler( - InstrumentationScopeMarshaller instrumentationScope, + InstrumentationScopeMarshaler instrumentationScope, byte[] schemaUrlUtf8, List logMarshalers) { super(calculateSize(instrumentationScope, schemaUrlUtf8, logMarshalers)); @@ -37,7 +37,7 @@ public void writeTo(Serializer output) throws IOException { } private static int calculateSize( - InstrumentationScopeMarshaller instrumentationScope, + InstrumentationScopeMarshaler instrumentationScope, byte[] schemaUrlUtf8, List logMarshalers) { int size = 0; diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsStatelessMarshaler.java new file mode 100644 index 00000000000..60789604b3e --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/InstrumentationScopeLogsStatelessMarshaler.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; +import io.opentelemetry.proto.logs.v1.internal.ScopeLogs; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.IOException; +import java.util.List; + +/** See {@link InstrumentationScopeLogsMarshaler}. */ +final class InstrumentationScopeLogsStatelessMarshaler + implements StatelessMarshaler2> { + static final InstrumentationScopeLogsStatelessMarshaler INSTANCE = + new InstrumentationScopeLogsStatelessMarshaler(); + + @Override + public void writeTo( + Serializer output, + InstrumentationScopeInfo instrumentationScope, + List logs, + MarshalerContext context) + throws IOException { + InstrumentationScopeMarshaler instrumentationScopeMarshaler = + context.getData(InstrumentationScopeMarshaler.class); + + output.serializeMessage(ScopeLogs.SCOPE, instrumentationScopeMarshaler); + output.serializeRepeatedMessageWithContext( + ScopeLogs.LOG_RECORDS, logs, LogStatelessMarshaler.INSTANCE, context); + output.serializeStringWithContext( + ScopeLogs.SCHEMA_URL, instrumentationScope.getSchemaUrl(), context); + } + + @Override + public int getBinarySerializedSize( + InstrumentationScopeInfo instrumentationScope, + List logs, + MarshalerContext context) { + InstrumentationScopeMarshaler instrumentationScopeMarshaler = + InstrumentationScopeMarshaler.create(instrumentationScope); + context.addData(instrumentationScopeMarshaler); + + int size = 0; + size += MarshalerUtil.sizeMessage(ScopeLogs.SCOPE, instrumentationScopeMarshaler); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ScopeLogs.LOG_RECORDS, logs, LogStatelessMarshaler.INSTANCE, context); + size += + StatelessMarshalerUtil.sizeStringWithContext( + ScopeLogs.SCHEMA_URL, instrumentationScope.getSchemaUrl(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogMarshaler.java index f5fa3d60b3e..48a38808cb1 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogMarshaler.java @@ -5,6 +5,7 @@ package io.opentelemetry.exporter.internal.otlp.logs; +import io.opentelemetry.api.logs.Severity; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceFlags; @@ -13,11 +14,11 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.ProtoEnumInfo; import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.otlp.AnyValueMarshaler; import io.opentelemetry.exporter.internal.otlp.KeyValueMarshaler; -import io.opentelemetry.exporter.internal.otlp.StringAnyValueMarshaler; import io.opentelemetry.proto.logs.v1.internal.LogRecord; import io.opentelemetry.proto.logs.v1.internal.SeverityNumber; -import io.opentelemetry.sdk.logs.data.Severity; +import io.opentelemetry.sdk.logs.data.LogRecordData; import java.io.IOException; import javax.annotation.Nullable; @@ -26,50 +27,58 @@ final class LogMarshaler extends MarshalerWithSize { private static final String INVALID_SPAN_ID = SpanId.getInvalid(); private final long timeUnixNano; + private final long observedTimeUnixNano; private final ProtoEnumInfo severityNumber; private final byte[] severityText; - private final MarshalerWithSize anyValueMarshaler; + @Nullable private final MarshalerWithSize anyValueMarshaler; private final KeyValueMarshaler[] attributeMarshalers; private final int droppedAttributesCount; private final TraceFlags traceFlags; @Nullable private final String traceId; @Nullable private final String spanId; + private final byte[] eventName; - static LogMarshaler create(io.opentelemetry.sdk.logs.data.LogData logData) { + static LogMarshaler create(LogRecordData logRecordData) { KeyValueMarshaler[] attributeMarshalers = - KeyValueMarshaler.createRepeated(logData.getAttributes()); + KeyValueMarshaler.createForAttributes(logRecordData.getAttributes()); + int attributeSize = logRecordData.getAttributes().size(); - // For now, map all the bodies to String AnyValue. - StringAnyValueMarshaler anyValueMarshaler = - new StringAnyValueMarshaler(MarshalerUtil.toBytes(logData.getBody().asString())); + MarshalerWithSize bodyMarshaler = + logRecordData.getBodyValue() == null + ? null + : AnyValueMarshaler.create(logRecordData.getBodyValue()); - SpanContext spanContext = logData.getSpanContext(); + SpanContext spanContext = logRecordData.getSpanContext(); return new LogMarshaler( - logData.getEpochNanos(), - toProtoSeverityNumber(logData.getSeverity()), - MarshalerUtil.toBytes(logData.getSeverityText()), - anyValueMarshaler, + logRecordData.getTimestampEpochNanos(), + logRecordData.getObservedTimestampEpochNanos(), + toProtoSeverityNumber(logRecordData.getSeverity()), + MarshalerUtil.toBytes(logRecordData.getSeverityText()), + bodyMarshaler, attributeMarshalers, - // TODO (trask) implement droppedAttributesCount in LogRecord - 0, + logRecordData.getTotalAttributeCount() - attributeSize, spanContext.getTraceFlags(), spanContext.getTraceId().equals(INVALID_TRACE_ID) ? null : spanContext.getTraceId(), - spanContext.getSpanId().equals(INVALID_SPAN_ID) ? null : spanContext.getSpanId()); + spanContext.getSpanId().equals(INVALID_SPAN_ID) ? null : spanContext.getSpanId(), + MarshalerUtil.toBytes(logRecordData.getEventName())); } private LogMarshaler( long timeUnixNano, + long observedTimeUnixNano, ProtoEnumInfo severityNumber, byte[] severityText, - MarshalerWithSize anyValueMarshaler, + @Nullable MarshalerWithSize anyValueMarshaler, KeyValueMarshaler[] attributeMarshalers, int droppedAttributesCount, TraceFlags traceFlags, @Nullable String traceId, - @Nullable String spanId) { + @Nullable String spanId, + byte[] eventName) { super( calculateSize( timeUnixNano, + observedTimeUnixNano, severityNumber, severityText, anyValueMarshaler, @@ -77,8 +86,10 @@ private LogMarshaler( droppedAttributesCount, traceFlags, traceId, - spanId)); + spanId, + eventName)); this.timeUnixNano = timeUnixNano; + this.observedTimeUnixNano = observedTimeUnixNano; this.traceId = traceId; this.spanId = spanId; this.traceFlags = traceFlags; @@ -87,51 +98,66 @@ private LogMarshaler( this.anyValueMarshaler = anyValueMarshaler; this.attributeMarshalers = attributeMarshalers; this.droppedAttributesCount = droppedAttributesCount; + this.eventName = eventName; } @Override protected void writeTo(Serializer output) throws IOException { output.serializeFixed64(LogRecord.TIME_UNIX_NANO, timeUnixNano); + output.serializeFixed64(LogRecord.OBSERVED_TIME_UNIX_NANO, observedTimeUnixNano); + output.serializeEnum(LogRecord.SEVERITY_NUMBER, severityNumber); output.serializeString(LogRecord.SEVERITY_TEXT, severityText); - output.serializeMessage(LogRecord.BODY, anyValueMarshaler); + if (anyValueMarshaler != null) { + output.serializeMessage(LogRecord.BODY, anyValueMarshaler); + } output.serializeRepeatedMessage(LogRecord.ATTRIBUTES, attributeMarshalers); output.serializeUInt32(LogRecord.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); - output.serializeFixed32(LogRecord.FLAGS, toUnsignedInt(traceFlags.asByte())); + output.serializeByteAsFixed32(LogRecord.FLAGS, traceFlags.asByte()); output.serializeTraceId(LogRecord.TRACE_ID, traceId); output.serializeSpanId(LogRecord.SPAN_ID, spanId); + + output.serializeString(LogRecord.EVENT_NAME, eventName); } private static int calculateSize( long timeUnixNano, + long observedTimeUnixNano, ProtoEnumInfo severityNumber, byte[] severityText, - MarshalerWithSize anyValueMarshaler, + @Nullable MarshalerWithSize anyValueMarshaler, KeyValueMarshaler[] attributeMarshalers, int droppedAttributesCount, TraceFlags traceFlags, @Nullable String traceId, - @Nullable String spanId) { + @Nullable String spanId, + byte[] eventName) { int size = 0; size += MarshalerUtil.sizeFixed64(LogRecord.TIME_UNIX_NANO, timeUnixNano); + size += MarshalerUtil.sizeFixed64(LogRecord.OBSERVED_TIME_UNIX_NANO, observedTimeUnixNano); + size += MarshalerUtil.sizeEnum(LogRecord.SEVERITY_NUMBER, severityNumber); size += MarshalerUtil.sizeBytes(LogRecord.SEVERITY_TEXT, severityText); - size += MarshalerUtil.sizeMessage(LogRecord.BODY, anyValueMarshaler); + if (anyValueMarshaler != null) { + size += MarshalerUtil.sizeMessage(LogRecord.BODY, anyValueMarshaler); + } size += MarshalerUtil.sizeRepeatedMessage(LogRecord.ATTRIBUTES, attributeMarshalers); size += MarshalerUtil.sizeUInt32(LogRecord.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); - size += MarshalerUtil.sizeFixed32(LogRecord.FLAGS, toUnsignedInt(traceFlags.asByte())); + size += MarshalerUtil.sizeByteAsFixed32(LogRecord.FLAGS, traceFlags.asByte()); size += MarshalerUtil.sizeTraceId(LogRecord.TRACE_ID, traceId); size += MarshalerUtil.sizeSpanId(LogRecord.SPAN_ID, spanId); + + size += MarshalerUtil.sizeBytes(LogRecord.EVENT_NAME, eventName); return size; } @@ -192,9 +218,4 @@ static ProtoEnumInfo toProtoSeverityNumber(Severity severity) { // NB: Should not be possible with aligned versions. return SeverityNumber.SEVERITY_NUMBER_UNSPECIFIED; } - - /** Vendored {@link Byte#toUnsignedInt(byte)} to support Android. */ - private static int toUnsignedInt(byte x) { - return ((int) x) & 0xff; - } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java new file mode 100644 index 00000000000..e43684fe030 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogReusableDataMarshaler.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.Collection; +import java.util.Deque; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.function.BiFunction; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class LogReusableDataMarshaler { + + private final Deque marshalerPool = + new ConcurrentLinkedDeque<>(); + + private final MemoryMode memoryMode; + private final BiFunction doExport; + + public LogReusableDataMarshaler( + MemoryMode memoryMode, BiFunction doExport) { + this.memoryMode = memoryMode; + this.doExport = doExport; + } + + public MemoryMode getMemoryMode() { + return memoryMode; + } + + public CompletableResultCode export(Collection logs) { + if (memoryMode == MemoryMode.REUSABLE_DATA) { + LowAllocationLogsRequestMarshaler marshaler = marshalerPool.poll(); + if (marshaler == null) { + marshaler = new LowAllocationLogsRequestMarshaler(); + } + LowAllocationLogsRequestMarshaler exportMarshaler = marshaler; + exportMarshaler.initialize(logs); + return doExport + .apply(exportMarshaler, logs.size()) + .whenComplete(() -> { + exportMarshaler.reset(); + marshalerPool.add(exportMarshaler); + }); + } + // MemoryMode == MemoryMode.IMMUTABLE_DATA + LogsRequestMarshaler request = LogsRequestMarshaler.create(logs); + return doExport.apply(request, logs.size()); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogStatelessMarshaler.java new file mode 100644 index 00000000000..340842664ad --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogStatelessMarshaler.java @@ -0,0 +1,108 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import static io.opentelemetry.exporter.internal.otlp.logs.LogMarshaler.toProtoSeverityNumber; + +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AnyValueStatelessMarshaler; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.logs.v1.internal.LogRecord; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.IOException; + +/** See {@link LogMarshaler}. */ +final class LogStatelessMarshaler implements StatelessMarshaler { + + private static final String INVALID_TRACE_ID = TraceId.getInvalid(); + private static final String INVALID_SPAN_ID = SpanId.getInvalid(); + + static final LogStatelessMarshaler INSTANCE = new LogStatelessMarshaler(); + + @Override + public void writeTo(Serializer output, LogRecordData log, MarshalerContext context) + throws IOException { + output.serializeFixed64(LogRecord.TIME_UNIX_NANO, log.getTimestampEpochNanos()); + output.serializeFixed64( + LogRecord.OBSERVED_TIME_UNIX_NANO, log.getObservedTimestampEpochNanos()); + output.serializeEnum(LogRecord.SEVERITY_NUMBER, toProtoSeverityNumber(log.getSeverity())); + output.serializeStringWithContext(LogRecord.SEVERITY_TEXT, log.getSeverityText(), context); + if (log.getBodyValue() != null) { + output.serializeMessageWithContext( + LogRecord.BODY, log.getBodyValue(), AnyValueStatelessMarshaler.INSTANCE, context); + } + + output.serializeRepeatedMessageWithContext( + LogRecord.ATTRIBUTES, + log.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + output.serializeUInt32( + LogRecord.DROPPED_ATTRIBUTES_COUNT, + log.getTotalAttributeCount() - log.getAttributes().size()); + + SpanContext spanContext = log.getSpanContext(); + output.serializeByteAsFixed32(LogRecord.FLAGS, spanContext.getTraceFlags().asByte()); + if (!spanContext.getTraceId().equals(INVALID_TRACE_ID)) { + output.serializeTraceId(LogRecord.TRACE_ID, spanContext.getTraceId(), context); + } + if (!spanContext.getSpanId().equals(INVALID_SPAN_ID)) { + output.serializeSpanId(LogRecord.SPAN_ID, spanContext.getSpanId(), context); + } + output.serializeStringWithContext(LogRecord.EVENT_NAME, log.getEventName(), context); + } + + @Override + public int getBinarySerializedSize(LogRecordData log, MarshalerContext context) { + int size = 0; + + size += MarshalerUtil.sizeFixed64(LogRecord.TIME_UNIX_NANO, log.getTimestampEpochNanos()); + size += + MarshalerUtil.sizeFixed64( + LogRecord.OBSERVED_TIME_UNIX_NANO, log.getObservedTimestampEpochNanos()); + size += + MarshalerUtil.sizeEnum(LogRecord.SEVERITY_NUMBER, toProtoSeverityNumber(log.getSeverity())); + size += + StatelessMarshalerUtil.sizeStringWithContext( + LogRecord.SEVERITY_TEXT, log.getSeverityText(), context); + if (log.getBodyValue() != null) { + size += + StatelessMarshalerUtil.sizeMessageWithContext( + LogRecord.BODY, log.getBodyValue(), AnyValueStatelessMarshaler.INSTANCE, context); + } + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + LogRecord.ATTRIBUTES, + log.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + + int droppedAttributesCount = log.getTotalAttributeCount() - log.getAttributes().size(); + size += MarshalerUtil.sizeUInt32(LogRecord.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + + SpanContext spanContext = log.getSpanContext(); + size += MarshalerUtil.sizeByteAsFixed32(LogRecord.FLAGS, spanContext.getTraceFlags().asByte()); + if (!spanContext.getTraceId().equals(INVALID_TRACE_ID)) { + size += MarshalerUtil.sizeTraceId(LogRecord.TRACE_ID, spanContext.getTraceId()); + } + if (!spanContext.getSpanId().equals(INVALID_SPAN_ID)) { + size += MarshalerUtil.sizeSpanId(LogRecord.SPAN_ID, spanContext.getSpanId()); + } + + size += + StatelessMarshalerUtil.sizeStringWithContext( + LogRecord.EVENT_NAME, log.getEventName(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshaler.java index d02bc1f2c31..b1f4b5cd36d 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshaler.java @@ -10,13 +10,13 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.proto.collector.logs.v1.internal.ExportLogsServiceRequest; -import io.opentelemetry.sdk.logs.data.LogData; +import io.opentelemetry.sdk.logs.data.LogRecordData; import io.opentelemetry.sdk.trace.data.SpanData; import java.io.IOException; import java.util.Collection; /** - * {@link Marshaler} to convert SDK {@link LogData} to OTLP ExportLogsServiceRequest. + * {@link Marshaler} to convert SDK {@link LogRecordData} to OTLP ExportLogsServiceRequest. * *

    This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. @@ -29,7 +29,7 @@ public final class LogsRequestMarshaler extends MarshalerWithSize { * Returns a {@link LogsRequestMarshaler} that can be used to convert the provided {@link * SpanData} into a serialized OTLP ExportLogsServiceRequest. */ - public static LogsRequestMarshaler create(Collection logs) { + public static LogsRequestMarshaler create(Collection logs) { return new LogsRequestMarshaler(ResourceLogsMarshaler.create(logs)); } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LowAllocationLogsRequestMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LowAllocationLogsRequestMarshaler.java new file mode 100644 index 00000000000..f3bee53f061 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/LowAllocationLogsRequestMarshaler.java @@ -0,0 +1,107 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.collector.logs.v1.internal.ExportLogsServiceRequest; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * {@link Marshaler} to convert SDK {@link LogRecordData} to OTLP ExportLogsServiceRequest. See + * {@link LogsRequestMarshaler}. + * + *

    Example usage: + * + *

    {@code
    + * void marshal(LowAllocationLogRequestMarshaler requestMarshaler, OutputStream output,
    + *     List logDataList) throws IOException {
    + *   requestMarshaler.initialize(logDataList);
    + *   try {
    + *     requestMarshaler.writeBinaryTo(output);
    + *   } finally {
    + *     requestMarshaler.reset();
    + *   }
    + * }
    + * }
    + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class LowAllocationLogsRequestMarshaler extends Marshaler { + private static final MarshalerContext.Key RESOURCE_LOG_SIZE_CALCULATOR_KEY = + MarshalerContext.key(); + private static final MarshalerContext.Key RESOURCE_LOG_WRITER_KEY = MarshalerContext.key(); + + private final MarshalerContext context = new MarshalerContext(); + + @SuppressWarnings("NullAway") + private Map>> resourceAndScopeMap; + + private int size; + + public void initialize(Collection logDataList) { + resourceAndScopeMap = groupByResourceAndScope(context, logDataList); + size = calculateSize(context, resourceAndScopeMap); + } + + public void reset() { + context.reset(); + } + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + public void writeTo(Serializer output) throws IOException { + // serializing can be retried, reset the indexes, so we could call writeTo multiple times + context.resetReadIndex(); + output.serializeRepeatedMessageWithContext( + ExportLogsServiceRequest.RESOURCE_LOGS, + resourceAndScopeMap, + ResourceLogsStatelessMarshaler.INSTANCE, + context, + RESOURCE_LOG_WRITER_KEY); + } + + private static int calculateSize( + MarshalerContext context, + Map>> resourceAndScopeMap) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ExportLogsServiceRequest.RESOURCE_LOGS, + resourceAndScopeMap, + ResourceLogsStatelessMarshaler.INSTANCE, + context, + RESOURCE_LOG_SIZE_CALCULATOR_KEY); + } + + private static Map>> + groupByResourceAndScope(MarshalerContext context, Collection logDataList) { + + if (logDataList.isEmpty()) { + return Collections.emptyMap(); + } + + return StatelessMarshalerUtil.groupByResourceAndScope( + logDataList, + // TODO(anuraaga): Replace with an internal SdkData type of interface that exposes these + // two. + LogRecordData::getResource, + LogRecordData::getInstrumentationScopeInfo, + context); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsMarshaler.java index 64207c7aeba..c71840ef8a9 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsMarshaler.java @@ -9,11 +9,11 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaller; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; import io.opentelemetry.proto.logs.v1.internal.ResourceLogs; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; +import io.opentelemetry.sdk.logs.data.LogRecordData; import io.opentelemetry.sdk.resources.Resource; import java.io.IOException; import java.util.Collection; @@ -32,7 +32,8 @@ public final class ResourceLogsMarshaler extends MarshalerWithSize { private final InstrumentationScopeLogsMarshaler[] instrumentationScopeLogsMarshalers; /** Returns Marshalers of ResourceLogs created by grouping the provided logRecords. */ - public static ResourceLogsMarshaler[] create(Collection logs) { + @SuppressWarnings("AvoidObjectArrays") + public static ResourceLogsMarshaler[] create(Collection logs) { Map>> resourceAndScopeMap = groupByResourceAndScope(logs); @@ -41,14 +42,14 @@ public static ResourceLogsMarshaler[] create(Collection logs) { int posResource = 0; for (Map.Entry>> entry : resourceAndScopeMap.entrySet()) { - InstrumentationScopeLogsMarshaler[] instrumentationLibrarySpansMarshalers = + InstrumentationScopeLogsMarshaler[] instrumentationScopeLogsMarshalers = new InstrumentationScopeLogsMarshaler[entry.getValue().size()]; int posInstrumentation = 0; for (Map.Entry> entryIs : entry.getValue().entrySet()) { - instrumentationLibrarySpansMarshalers[posInstrumentation++] = + instrumentationScopeLogsMarshalers[posInstrumentation++] = new InstrumentationScopeLogsMarshaler( - InstrumentationScopeMarshaller.create(entryIs.getKey()), + InstrumentationScopeMarshaler.create(entryIs.getKey()), MarshalerUtil.toBytes(entryIs.getKey().getSchemaUrl()), entryIs.getValue()); } @@ -56,7 +57,7 @@ public static ResourceLogsMarshaler[] create(Collection logs) { new ResourceLogsMarshaler( ResourceMarshaler.create(entry.getKey()), MarshalerUtil.toBytes(entry.getKey().getSchemaUrl()), - instrumentationLibrarySpansMarshalers); + instrumentationScopeLogsMarshalers); } return resourceLogsMarshalers; @@ -93,13 +94,11 @@ private static int calculateSize( } private static Map>> - groupByResourceAndScope(Collection logs) { + groupByResourceAndScope(Collection logs) { return MarshalerUtil.groupByResourceAndScope( logs, - // TODO(anuraaga): Replace with an internal SdkData type of interface that exposes these - // two. - LogData::getResource, - LogData::getInstrumentationScopeInfo, + LogRecordData::getResource, + LogRecordData::getInstrumentationScopeInfo, LogMarshaler::create); } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsStatelessMarshaler.java new file mode 100644 index 00000000000..ba128c880c7 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/logs/ResourceLogsStatelessMarshaler.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; +import io.opentelemetry.proto.logs.v1.internal.ResourceLogs; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * A Marshaler of ResourceLogs. See {@link ResourceLogsMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ResourceLogsStatelessMarshaler + implements StatelessMarshaler2>> { + static final ResourceLogsStatelessMarshaler INSTANCE = new ResourceLogsStatelessMarshaler(); + private static final MarshalerContext.Key SCOPE_LOG_WRITER_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key SCOPE_LOG_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + + @Override + public void writeTo( + Serializer output, + Resource resource, + Map> scopeMap, + MarshalerContext context) + throws IOException { + ResourceMarshaler resourceMarshaler = context.getData(ResourceMarshaler.class); + output.serializeMessage(ResourceLogs.RESOURCE, resourceMarshaler); + + output.serializeRepeatedMessageWithContext( + ResourceLogs.SCOPE_LOGS, + scopeMap, + InstrumentationScopeLogsStatelessMarshaler.INSTANCE, + context, + SCOPE_LOG_WRITER_KEY); + + output.serializeStringWithContext(ResourceLogs.SCHEMA_URL, resource.getSchemaUrl(), context); + } + + @Override + public int getBinarySerializedSize( + Resource resource, + Map> scopeMap, + MarshalerContext context) { + + int size = 0; + + ResourceMarshaler resourceMarshaler = ResourceMarshaler.create(resource); + context.addData(resourceMarshaler); + size += MarshalerUtil.sizeMessage(ResourceLogs.RESOURCE, resourceMarshaler); + + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ResourceLogs.SCOPE_LOGS, + scopeMap, + InstrumentationScopeLogsStatelessMarshaler.INSTANCE, + context, + SCOPE_LOG_SIZE_CALCULATOR_KEY); + + size += + StatelessMarshalerUtil.sizeStringWithContext( + ResourceLogs.SCHEMA_URL, resource.getSchemaUrl(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarMarshaler.java index ed4956ec9a8..44ad6fb5bc1 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarMarshaler.java @@ -11,6 +11,7 @@ import io.opentelemetry.exporter.internal.marshal.ProtoFieldInfo; import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.exporter.internal.otlp.KeyValueMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.Exemplar; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.LongExemplarData; @@ -37,22 +38,15 @@ static ExemplarMarshaler[] createRepeated(List exemplars return marshalers; } - private static ExemplarMarshaler create(ExemplarData exemplar) { + // Visible for testing + static ExemplarMarshaler create(ExemplarData exemplar) { KeyValueMarshaler[] attributeMarshalers = - KeyValueMarshaler.createRepeated(exemplar.getFilteredAttributes()); - - ProtoFieldInfo valueField; - if (exemplar instanceof LongExemplarData) { - valueField = io.opentelemetry.proto.metrics.v1.internal.Exemplar.AS_INT; - } else { - assert exemplar instanceof DoubleExemplarData; - valueField = io.opentelemetry.proto.metrics.v1.internal.Exemplar.AS_DOUBLE; - } + KeyValueMarshaler.createForAttributes(exemplar.getFilteredAttributes()); return new ExemplarMarshaler( exemplar.getEpochNanos(), exemplar, - valueField, + toProtoExemplarValueType(exemplar), exemplar.getSpanContext(), attributeMarshalers); } @@ -72,25 +66,22 @@ private ExemplarMarshaler( } @Override + @SuppressWarnings("ReferenceEquality") public void writeTo(Serializer output) throws IOException { - output.serializeFixed64( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.TIME_UNIX_NANO, timeUnixNano); - if (valueField == io.opentelemetry.proto.metrics.v1.internal.Exemplar.AS_INT) { + output.serializeFixed64(Exemplar.TIME_UNIX_NANO, timeUnixNano); + if (valueField == Exemplar.AS_INT) { output.serializeFixed64Optional(valueField, ((LongExemplarData) value).getValue()); } else { output.serializeDoubleOptional(valueField, ((DoubleExemplarData) value).getValue()); } if (spanContext.isValid()) { - output.serializeSpanId( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.SPAN_ID, spanContext.getSpanId()); - output.serializeTraceId( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.TRACE_ID, spanContext.getTraceId()); + output.serializeSpanId(Exemplar.SPAN_ID, spanContext.getSpanId()); + output.serializeTraceId(Exemplar.TRACE_ID, spanContext.getTraceId()); } - output.serializeRepeatedMessage( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.FILTERED_ATTRIBUTES, - filteredAttributeMarshalers); + output.serializeRepeatedMessage(Exemplar.FILTERED_ATTRIBUTES, filteredAttributeMarshalers); } + @SuppressWarnings("ReferenceEquality") private static int calculateSize( long timeUnixNano, ProtoFieldInfo valueField, @@ -98,27 +89,28 @@ private static int calculateSize( SpanContext spanContext, KeyValueMarshaler[] filteredAttributeMarshalers) { int size = 0; - size += - MarshalerUtil.sizeFixed64( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.TIME_UNIX_NANO, timeUnixNano); - if (valueField == io.opentelemetry.proto.metrics.v1.internal.Exemplar.AS_INT) { + size += MarshalerUtil.sizeFixed64(Exemplar.TIME_UNIX_NANO, timeUnixNano); + if (valueField == Exemplar.AS_INT) { size += MarshalerUtil.sizeFixed64Optional(valueField, ((LongExemplarData) value).getValue()); } else { size += MarshalerUtil.sizeDoubleOptional(valueField, ((DoubleExemplarData) value).getValue()); } if (spanContext.isValid()) { - size += - MarshalerUtil.sizeSpanId( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.SPAN_ID, spanContext.getSpanId()); - size += - MarshalerUtil.sizeTraceId( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.TRACE_ID, - spanContext.getTraceId()); + size += MarshalerUtil.sizeSpanId(Exemplar.SPAN_ID, spanContext.getSpanId()); + size += MarshalerUtil.sizeTraceId(Exemplar.TRACE_ID, spanContext.getTraceId()); } size += MarshalerUtil.sizeRepeatedMessage( - io.opentelemetry.proto.metrics.v1.internal.Exemplar.FILTERED_ATTRIBUTES, - filteredAttributeMarshalers); + Exemplar.FILTERED_ATTRIBUTES, filteredAttributeMarshalers); return size; } + + static ProtoFieldInfo toProtoExemplarValueType(ExemplarData exemplar) { + if (exemplar instanceof LongExemplarData) { + return Exemplar.AS_INT; + } else { + assert exemplar instanceof DoubleExemplarData; + return Exemplar.AS_DOUBLE; + } + } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarStatelessMarshaler.java new file mode 100644 index 00000000000..356b917702f --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExemplarStatelessMarshaler.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import static io.opentelemetry.exporter.internal.otlp.metrics.ExemplarMarshaler.toProtoExemplarValueType; + +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.ProtoFieldInfo; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.Exemplar; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import java.io.IOException; + +/** See {@link ExemplarMarshaler}. */ +final class ExemplarStatelessMarshaler implements StatelessMarshaler { + static final ExemplarStatelessMarshaler INSTANCE = new ExemplarStatelessMarshaler(); + + private ExemplarStatelessMarshaler() {} + + @Override + @SuppressWarnings("ReferenceEquality") + public void writeTo(Serializer output, ExemplarData exemplar, MarshalerContext context) + throws IOException { + output.serializeFixed64(Exemplar.TIME_UNIX_NANO, exemplar.getEpochNanos()); + ProtoFieldInfo valueField = toProtoExemplarValueType(exemplar); + if (valueField == Exemplar.AS_INT) { + output.serializeFixed64Optional(valueField, ((LongExemplarData) exemplar).getValue()); + } else { + output.serializeDoubleOptional(valueField, ((DoubleExemplarData) exemplar).getValue()); + } + SpanContext spanContext = exemplar.getSpanContext(); + if (spanContext.isValid()) { + output.serializeSpanId(Exemplar.SPAN_ID, spanContext.getSpanId(), context); + output.serializeTraceId(Exemplar.TRACE_ID, spanContext.getTraceId(), context); + } + output.serializeRepeatedMessageWithContext( + Exemplar.FILTERED_ATTRIBUTES, + exemplar.getFilteredAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + } + + @Override + @SuppressWarnings("ReferenceEquality") + public int getBinarySerializedSize(ExemplarData exemplar, MarshalerContext context) { + int size = 0; + size += MarshalerUtil.sizeFixed64(Exemplar.TIME_UNIX_NANO, exemplar.getEpochNanos()); + ProtoFieldInfo valueField = toProtoExemplarValueType(exemplar); + if (valueField == Exemplar.AS_INT) { + size += + MarshalerUtil.sizeFixed64Optional(valueField, ((LongExemplarData) exemplar).getValue()); + } else { + size += + MarshalerUtil.sizeDoubleOptional(valueField, ((DoubleExemplarData) exemplar).getValue()); + } + SpanContext spanContext = exemplar.getSpanContext(); + if (spanContext.isValid()) { + size += MarshalerUtil.sizeSpanId(Exemplar.SPAN_ID, spanContext.getSpanId()); + size += MarshalerUtil.sizeTraceId(Exemplar.TRACE_ID, spanContext.getTraceId()); + } + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Exemplar.FILTERED_ATTRIBUTES, + exemplar.getFilteredAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsMarshaler.java index be88437d370..c692bd061e8 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsMarshaler.java @@ -9,8 +9,9 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.proto.metrics.v1.internal.ExponentialHistogramDataPoint; -import io.opentelemetry.sdk.internal.PrimitiveLongList; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.common.internal.PrimitiveLongList; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; import java.io.IOException; import java.util.List; @@ -35,16 +36,29 @@ private ExponentialHistogramBucketsMarshaler(int offset, List counts) { @Override protected void writeTo(Serializer output) throws IOException { output.serializeSInt32(ExponentialHistogramDataPoint.Buckets.OFFSET, offset); - output.serializeRepeatedUInt64( - ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, PrimitiveLongList.toArray(counts)); + if (counts instanceof DynamicPrimitiveLongList) { + output.serializeRepeatedUInt64( + ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, (DynamicPrimitiveLongList) counts); + } else { + output.serializeRepeatedUInt64( + ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, PrimitiveLongList.toArray(counts)); + } } - private static int calculateSize(int offset, List counts) { + static int calculateSize(int offset, List counts) { int size = 0; size += MarshalerUtil.sizeSInt32(ExponentialHistogramDataPoint.Buckets.OFFSET, offset); - size += - MarshalerUtil.sizeRepeatedUInt64( - ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, PrimitiveLongList.toArray(counts)); + if (counts instanceof DynamicPrimitiveLongList) { + size += + MarshalerUtil.sizeRepeatedUInt64( + ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, + (DynamicPrimitiveLongList) counts); + } else { + size += + MarshalerUtil.sizeRepeatedUInt64( + ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, + PrimitiveLongList.toArray(counts)); + } return size; } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsStatelessMarshaler.java new file mode 100644 index 00000000000..74e3f809916 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramBucketsStatelessMarshaler.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.ExponentialHistogramDataPoint; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.common.internal.PrimitiveLongList; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import java.io.IOException; +import java.util.List; + +/** See {@link ExponentialHistogramBucketsMarshaler}. */ +final class ExponentialHistogramBucketsStatelessMarshaler + implements StatelessMarshaler { + static final ExponentialHistogramBucketsStatelessMarshaler INSTANCE = + new ExponentialHistogramBucketsStatelessMarshaler(); + + private ExponentialHistogramBucketsStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, ExponentialHistogramBuckets buckets, MarshalerContext context) + throws IOException { + output.serializeSInt32(ExponentialHistogramDataPoint.Buckets.OFFSET, buckets.getOffset()); + List counts = buckets.getBucketCounts(); + if (counts instanceof DynamicPrimitiveLongList) { + output.serializeRepeatedUInt64( + ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, (DynamicPrimitiveLongList) counts); + } else { + output.serializeRepeatedUInt64( + ExponentialHistogramDataPoint.Buckets.BUCKET_COUNTS, PrimitiveLongList.toArray(counts)); + } + } + + @Override + public int getBinarySerializedSize( + ExponentialHistogramBuckets buckets, MarshalerContext context) { + return ExponentialHistogramBucketsMarshaler.calculateSize( + buckets.getOffset(), buckets.getBucketCounts()); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointMarshaler.java index 05f70010f78..36fcb76d33a 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointMarshaler.java @@ -10,7 +10,7 @@ import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.exporter.internal.otlp.KeyValueMarshaler; import io.opentelemetry.proto.metrics.v1.internal.ExponentialHistogramDataPoint; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; import java.io.IOException; import java.util.Collection; @@ -83,7 +83,7 @@ private ExponentialHistogramDataPointMarshaler( } static ExponentialHistogramDataPointMarshaler create(ExponentialHistogramPointData point) { - KeyValueMarshaler[] attributes = KeyValueMarshaler.createRepeated(point.getAttributes()); + KeyValueMarshaler[] attributes = KeyValueMarshaler.createForAttributes(point.getAttributes()); ExemplarMarshaler[] exemplars = ExemplarMarshaler.createRepeated(point.getExemplars()); ExponentialHistogramBucketsMarshaler positiveBuckets = @@ -124,7 +124,7 @@ protected void writeTo(Serializer output) throws IOException { output.serializeFixed64(ExponentialHistogramDataPoint.START_TIME_UNIX_NANO, startTimeUnixNano); output.serializeFixed64(ExponentialHistogramDataPoint.TIME_UNIX_NANO, timeUnixNano); output.serializeFixed64(ExponentialHistogramDataPoint.COUNT, count); - output.serializeDouble(ExponentialHistogramDataPoint.SUM, sum); + output.serializeDoubleOptional(ExponentialHistogramDataPoint.SUM, sum); if (hasMin) { output.serializeDoubleOptional(ExponentialHistogramDataPoint.MIN, min); } @@ -161,7 +161,7 @@ private static int calculateSize( size += MarshalerUtil.sizeFixed64(ExponentialHistogramDataPoint.TIME_UNIX_NANO, timeUnixNano); size += MarshalerUtil.sizeSInt32(ExponentialHistogramDataPoint.SCALE, scale); size += MarshalerUtil.sizeFixed64(ExponentialHistogramDataPoint.COUNT, count); - size += MarshalerUtil.sizeDouble(ExponentialHistogramDataPoint.SUM, sum); + size += MarshalerUtil.sizeDoubleOptional(ExponentialHistogramDataPoint.SUM, sum); if (hasMin) { size += MarshalerUtil.sizeDoubleOptional(ExponentialHistogramDataPoint.MIN, min); } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointStatelessMarshaler.java new file mode 100644 index 00000000000..bb4e9188e0b --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramDataPointStatelessMarshaler.java @@ -0,0 +1,113 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.ExponentialHistogramDataPoint; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import java.io.IOException; + +/** See {@link ExponentialHistogramDataPointMarshaler}. */ +final class ExponentialHistogramDataPointStatelessMarshaler + implements StatelessMarshaler { + static final ExponentialHistogramDataPointStatelessMarshaler INSTANCE = + new ExponentialHistogramDataPointStatelessMarshaler(); + + private ExponentialHistogramDataPointStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, ExponentialHistogramPointData point, MarshalerContext context) + throws IOException { + output.serializeFixed64( + ExponentialHistogramDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + output.serializeFixed64(ExponentialHistogramDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + output.serializeFixed64(ExponentialHistogramDataPoint.COUNT, point.getCount()); + output.serializeDoubleOptional(ExponentialHistogramDataPoint.SUM, point.getSum()); + if (point.hasMin()) { + output.serializeDoubleOptional(ExponentialHistogramDataPoint.MIN, point.getMin()); + } + if (point.hasMax()) { + output.serializeDoubleOptional(ExponentialHistogramDataPoint.MAX, point.getMax()); + } + output.serializeSInt32(ExponentialHistogramDataPoint.SCALE, point.getScale()); + output.serializeFixed64(ExponentialHistogramDataPoint.ZERO_COUNT, point.getZeroCount()); + output.serializeMessageWithContext( + ExponentialHistogramDataPoint.POSITIVE, + point.getPositiveBuckets(), + ExponentialHistogramBucketsStatelessMarshaler.INSTANCE, + context); + output.serializeMessageWithContext( + ExponentialHistogramDataPoint.NEGATIVE, + point.getNegativeBuckets(), + ExponentialHistogramBucketsStatelessMarshaler.INSTANCE, + context); + output.serializeRepeatedMessageWithContext( + ExponentialHistogramDataPoint.EXEMPLARS, + point.getExemplars(), + ExemplarStatelessMarshaler.INSTANCE, + context); + output.serializeRepeatedMessageWithContext( + ExponentialHistogramDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + } + + @Override + public int getBinarySerializedSize( + ExponentialHistogramPointData point, MarshalerContext context) { + int size = 0; + size += + MarshalerUtil.sizeFixed64( + ExponentialHistogramDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + size += + MarshalerUtil.sizeFixed64( + ExponentialHistogramDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + size += MarshalerUtil.sizeFixed64(ExponentialHistogramDataPoint.COUNT, point.getCount()); + size += MarshalerUtil.sizeDoubleOptional(ExponentialHistogramDataPoint.SUM, point.getSum()); + if (point.hasMin()) { + size += MarshalerUtil.sizeDoubleOptional(ExponentialHistogramDataPoint.MIN, point.getMin()); + } + if (point.hasMax()) { + size += MarshalerUtil.sizeDoubleOptional(ExponentialHistogramDataPoint.MAX, point.getMax()); + } + size += MarshalerUtil.sizeSInt32(ExponentialHistogramDataPoint.SCALE, point.getScale()); + size += + MarshalerUtil.sizeFixed64(ExponentialHistogramDataPoint.ZERO_COUNT, point.getZeroCount()); + size += + StatelessMarshalerUtil.sizeMessageWithContext( + ExponentialHistogramDataPoint.POSITIVE, + point.getPositiveBuckets(), + ExponentialHistogramBucketsStatelessMarshaler.INSTANCE, + context); + size += + StatelessMarshalerUtil.sizeMessageWithContext( + ExponentialHistogramDataPoint.NEGATIVE, + point.getNegativeBuckets(), + ExponentialHistogramBucketsStatelessMarshaler.INSTANCE, + context); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ExponentialHistogramDataPoint.EXEMPLARS, + point.getExemplars(), + ExemplarStatelessMarshaler.INSTANCE, + context); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ExponentialHistogramDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramMarshaler.java index c07096ee8ae..9ad9b10296a 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramMarshaler.java @@ -10,7 +10,7 @@ import io.opentelemetry.exporter.internal.marshal.ProtoEnumInfo; import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.proto.metrics.v1.internal.ExponentialHistogram; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; import java.io.IOException; /** diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramStatelessMarshaler.java new file mode 100644 index 00000000000..240f616a113 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ExponentialHistogramStatelessMarshaler.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.metrics.v1.internal.ExponentialHistogram; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; +import java.io.IOException; + +/** See {@link ExponentialHistogramMarshaler}. */ +final class ExponentialHistogramStatelessMarshaler + implements StatelessMarshaler { + static final ExponentialHistogramStatelessMarshaler INSTANCE = + new ExponentialHistogramStatelessMarshaler(); + private static final MarshalerContext.Key DATA_POINT_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key DATA_POINT_WRITER_KEY = MarshalerContext.key(); + + private ExponentialHistogramStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, ExponentialHistogramData histogram, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + ExponentialHistogram.DATA_POINTS, + histogram.getPoints(), + ExponentialHistogramDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_WRITER_KEY); + output.serializeEnum( + ExponentialHistogram.AGGREGATION_TEMPORALITY, + MetricsMarshalerUtil.mapToTemporality(histogram.getAggregationTemporality())); + } + + @Override + public int getBinarySerializedSize(ExponentialHistogramData histogram, MarshalerContext context) { + int size = 0; + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ExponentialHistogram.DATA_POINTS, + histogram.getPoints(), + ExponentialHistogramDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_SIZE_CALCULATOR_KEY); + size += + MarshalerUtil.sizeEnum( + ExponentialHistogram.AGGREGATION_TEMPORALITY, + MetricsMarshalerUtil.mapToTemporality(histogram.getAggregationTemporality())); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/GaugeStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/GaugeStatelessMarshaler.java new file mode 100644 index 00000000000..4db29e74e1c --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/GaugeStatelessMarshaler.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.metrics.v1.internal.Gauge; +import io.opentelemetry.sdk.metrics.data.GaugeData; +import io.opentelemetry.sdk.metrics.data.PointData; +import java.io.IOException; + +/** See {@link GaugeMarshaler}. */ +final class GaugeStatelessMarshaler implements StatelessMarshaler> { + static final GaugeStatelessMarshaler INSTANCE = new GaugeStatelessMarshaler(); + private static final MarshalerContext.Key DATA_POINT_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key DATA_POINT_WRITER_KEY = MarshalerContext.key(); + + private GaugeStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, GaugeData gauge, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + Gauge.DATA_POINTS, + gauge.getPoints(), + NumberDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_WRITER_KEY); + } + + @Override + public int getBinarySerializedSize( + GaugeData gauge, MarshalerContext context) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Gauge.DATA_POINTS, + gauge.getPoints(), + NumberDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_SIZE_CALCULATOR_KEY); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramDataPointMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramDataPointMarshaler.java index b1a027a3455..c65a6adc4c4 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramDataPointMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramDataPointMarshaler.java @@ -10,7 +10,7 @@ import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.exporter.internal.otlp.KeyValueMarshaler; import io.opentelemetry.proto.metrics.v1.internal.HistogramDataPoint; -import io.opentelemetry.sdk.internal.PrimitiveLongList; +import io.opentelemetry.sdk.common.internal.PrimitiveLongList; import io.opentelemetry.sdk.metrics.data.HistogramPointData; import java.io.IOException; import java.util.Collection; @@ -41,7 +41,7 @@ static HistogramDataPointMarshaler[] createRepeated(Collection { + static final HistogramDataPointStatelessMarshaler INSTANCE = + new HistogramDataPointStatelessMarshaler(); + + private HistogramDataPointStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, HistogramPointData point, MarshalerContext context) + throws IOException { + output.serializeFixed64(HistogramDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + output.serializeFixed64(HistogramDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + output.serializeFixed64(HistogramDataPoint.COUNT, point.getCount()); + output.serializeDoubleOptional(HistogramDataPoint.SUM, point.getSum()); + if (point.hasMin()) { + output.serializeDoubleOptional(HistogramDataPoint.MIN, point.getMin()); + } + if (point.hasMax()) { + output.serializeDoubleOptional(HistogramDataPoint.MAX, point.getMax()); + } + output.serializeRepeatedFixed64(HistogramDataPoint.BUCKET_COUNTS, point.getCounts()); + output.serializeRepeatedDouble(HistogramDataPoint.EXPLICIT_BOUNDS, point.getBoundaries()); + output.serializeRepeatedMessageWithContext( + HistogramDataPoint.EXEMPLARS, + point.getExemplars(), + ExemplarStatelessMarshaler.INSTANCE, + context); + output.serializeRepeatedMessageWithContext( + HistogramDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + } + + @Override + public int getBinarySerializedSize(HistogramPointData point, MarshalerContext context) { + int size = 0; + size += + MarshalerUtil.sizeFixed64( + HistogramDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + size += MarshalerUtil.sizeFixed64(HistogramDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + size += MarshalerUtil.sizeFixed64(HistogramDataPoint.COUNT, point.getCount()); + size += MarshalerUtil.sizeDoubleOptional(HistogramDataPoint.SUM, point.getSum()); + if (point.hasMin()) { + size += MarshalerUtil.sizeDoubleOptional(HistogramDataPoint.MIN, point.getMin()); + } + if (point.hasMax()) { + size += MarshalerUtil.sizeDoubleOptional(HistogramDataPoint.MAX, point.getMax()); + } + size += MarshalerUtil.sizeRepeatedFixed64(HistogramDataPoint.BUCKET_COUNTS, point.getCounts()); + size += + MarshalerUtil.sizeRepeatedDouble(HistogramDataPoint.EXPLICIT_BOUNDS, point.getBoundaries()); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + HistogramDataPoint.EXEMPLARS, + point.getExemplars(), + ExemplarStatelessMarshaler.INSTANCE, + context); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + HistogramDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramStatelessMarshaler.java new file mode 100644 index 00000000000..2e3f65e188a --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/HistogramStatelessMarshaler.java @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.metrics.v1.internal.Histogram; +import io.opentelemetry.sdk.metrics.data.HistogramData; +import java.io.IOException; + +/** See {@link HistogramMarshaler}. */ +final class HistogramStatelessMarshaler implements StatelessMarshaler { + static final HistogramStatelessMarshaler INSTANCE = new HistogramStatelessMarshaler(); + private static final MarshalerContext.Key DATA_POINT_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key DATA_POINT_WRITER_KEY = MarshalerContext.key(); + + private HistogramStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, HistogramData histogram, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + Histogram.DATA_POINTS, + histogram.getPoints(), + HistogramDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_WRITER_KEY); + output.serializeEnum( + Histogram.AGGREGATION_TEMPORALITY, + MetricsMarshalerUtil.mapToTemporality(histogram.getAggregationTemporality())); + } + + @Override + public int getBinarySerializedSize(HistogramData histogram, MarshalerContext context) { + int size = 0; + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Histogram.DATA_POINTS, + histogram.getPoints(), + HistogramDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_SIZE_CALCULATOR_KEY); + size += + MarshalerUtil.sizeEnum( + Histogram.AGGREGATION_TEMPORALITY, + MetricsMarshalerUtil.mapToTemporality(histogram.getAggregationTemporality())); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsMarshaler.java index 7c598b730b9..c4d3ee7ebde 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsMarshaler.java @@ -9,18 +9,18 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaller; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; import io.opentelemetry.proto.metrics.v1.internal.ScopeMetrics; import java.io.IOException; import java.util.List; final class InstrumentationScopeMetricsMarshaler extends MarshalerWithSize { - private final InstrumentationScopeMarshaller instrumentationScope; + private final InstrumentationScopeMarshaler instrumentationScope; private final List metricMarshalers; private final byte[] schemaUrlUtf8; InstrumentationScopeMetricsMarshaler( - InstrumentationScopeMarshaller instrumentationScope, + InstrumentationScopeMarshaler instrumentationScope, byte[] schemaUrlUtf8, List metricMarshalers) { super(calculateSize(instrumentationScope, schemaUrlUtf8, metricMarshalers)); @@ -37,7 +37,7 @@ public void writeTo(Serializer output) throws IOException { } private static int calculateSize( - InstrumentationScopeMarshaller instrumentationScope, + InstrumentationScopeMarshaler instrumentationScope, byte[] schemaUrlUtf8, List metricMarshalers) { int size = 0; diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsStatelessMarshaler.java new file mode 100644 index 00000000000..921067a0b38 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/InstrumentationScopeMetricsStatelessMarshaler.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.ScopeMetrics; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.io.IOException; +import java.util.List; + +/** See {@link InstrumentationScopeMetricsMarshaler}. */ +final class InstrumentationScopeMetricsStatelessMarshaler + implements StatelessMarshaler2> { + static final InstrumentationScopeMetricsStatelessMarshaler INSTANCE = + new InstrumentationScopeMetricsStatelessMarshaler(); + + private InstrumentationScopeMetricsStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, + InstrumentationScopeInfo instrumentationScope, + List metrics, + MarshalerContext context) + throws IOException { + InstrumentationScopeMarshaler instrumentationScopeMarshaler = + context.getData(InstrumentationScopeMarshaler.class); + + output.serializeMessage(ScopeMetrics.SCOPE, instrumentationScopeMarshaler); + output.serializeRepeatedMessageWithContext( + ScopeMetrics.METRICS, metrics, MetricStatelessMarshaler.INSTANCE, context); + output.serializeStringWithContext( + ScopeMetrics.SCHEMA_URL, instrumentationScope.getSchemaUrl(), context); + } + + @Override + public int getBinarySerializedSize( + InstrumentationScopeInfo instrumentationScope, + List metrics, + MarshalerContext context) { + InstrumentationScopeMarshaler instrumentationScopeMarshaler = + InstrumentationScopeMarshaler.create(instrumentationScope); + context.addData(instrumentationScopeMarshaler); + + int size = 0; + size += MarshalerUtil.sizeMessage(ScopeMetrics.SCOPE, instrumentationScopeMarshaler); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ScopeMetrics.METRICS, metrics, MetricStatelessMarshaler.INSTANCE, context); + size += + StatelessMarshalerUtil.sizeStringWithContext( + ScopeMetrics.SCHEMA_URL, instrumentationScope.getSchemaUrl(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshaler.java new file mode 100644 index 00000000000..704642dc35a --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshaler.java @@ -0,0 +1,107 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.collector.metrics.v1.internal.ExportMetricsServiceRequest; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * {@link Marshaler} to convert SDK {@link MetricData} to OTLP ExportMetricsServiceRequest. See + * {@link MetricsRequestMarshaler}. + * + *

    Example usage: + * + *

    {@code
    + * void marshal(LowAllocationMetricsRequestMarshaler requestMarshaler, OutputStream output,
    + *     Collection metricDataList) throws IOException {
    + *   requestMarshaler.initialize(metricDataList);
    + *   try {
    + *     requestMarshaler.writeBinaryTo(output);
    + *   } finally {
    + *     requestMarshaler.reset();
    + *   }
    + * }
    + * }
    + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class LowAllocationMetricsRequestMarshaler extends Marshaler { + private static final MarshalerContext.Key RESOURCE_METRIC_SIZE_CALCULATOR_KEY = + MarshalerContext.key(); + private static final MarshalerContext.Key RESOURCE_METRIC_WRITER_KEY = MarshalerContext.key(); + + private final MarshalerContext context = new MarshalerContext(); + + @SuppressWarnings("NullAway") + private Map>> resourceAndScopeMap; + + private int size; + + public void initialize(Collection metricDataList) { + resourceAndScopeMap = groupByResourceAndScope(context, metricDataList); + size = calculateSize(context, resourceAndScopeMap); + } + + public void reset() { + context.reset(); + } + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + public void writeTo(Serializer output) throws IOException { + // serializing can be retried, reset the indexes, so we could call writeTo multiple times + context.resetReadIndex(); + output.serializeRepeatedMessageWithContext( + ExportMetricsServiceRequest.RESOURCE_METRICS, + resourceAndScopeMap, + ResourceMetricsStatelessMarshaler.INSTANCE, + context, + RESOURCE_METRIC_WRITER_KEY); + } + + private static int calculateSize( + MarshalerContext context, + Map>> resourceAndScopeMap) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ExportMetricsServiceRequest.RESOURCE_METRICS, + resourceAndScopeMap, + ResourceMetricsStatelessMarshaler.INSTANCE, + context, + RESOURCE_METRIC_SIZE_CALCULATOR_KEY); + } + + private static Map>> + groupByResourceAndScope(MarshalerContext context, Collection metricDataList) { + + if (metricDataList.isEmpty()) { + return Collections.emptyMap(); + } + + return StatelessMarshalerUtil.groupByResourceAndScope( + metricDataList, + // TODO(anuraaga): Replace with an internal SdkData type of interface that exposes these + // two. + MetricData::getResource, + MetricData::getInstrumentationScopeInfo, + context); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricMarshaler.java index b09f59c18b3..6b91a407c5f 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricMarshaler.java @@ -12,7 +12,6 @@ import io.opentelemetry.exporter.internal.marshal.Serializer; import io.opentelemetry.proto.metrics.v1.internal.Metric; import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; import java.io.IOException; final class MetricMarshaler extends MarshalerWithSize { @@ -57,8 +56,7 @@ static Marshaler create(MetricData metric) { dataField = Metric.HISTOGRAM; break; case EXPONENTIAL_HISTOGRAM: - dataMarshaler = - ExponentialHistogramMarshaler.create(ExponentialHistogramData.fromMetricData(metric)); + dataMarshaler = ExponentialHistogramMarshaler.create(metric.getExponentialHistogramData()); dataField = Metric.EXPONENTIAL_HISTOGRAM; } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java new file mode 100644 index 00000000000..42c48b6a690 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricReusableDataMarshaler.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.util.Collection; +import java.util.Deque; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.function.BiFunction; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class MetricReusableDataMarshaler { + + private final Deque marshalerPool = + new ConcurrentLinkedDeque<>(); + + private final MemoryMode memoryMode; + private final BiFunction doExport; + + public MetricReusableDataMarshaler( + MemoryMode memoryMode, BiFunction doExport) { + this.memoryMode = memoryMode; + this.doExport = doExport; + } + + public MemoryMode getMemoryMode() { + return memoryMode; + } + + public CompletableResultCode export(Collection metrics) { + if (memoryMode == MemoryMode.REUSABLE_DATA) { + LowAllocationMetricsRequestMarshaler marshaler = marshalerPool.poll(); + if (marshaler == null) { + marshaler = new LowAllocationMetricsRequestMarshaler(); + } + LowAllocationMetricsRequestMarshaler exportMarshaler = marshaler; + exportMarshaler.initialize(metrics); + return doExport + .apply(exportMarshaler, metrics.size()) + .whenComplete(() -> { + exportMarshaler.reset(); + marshalerPool.add(exportMarshaler); + }); + } + // MemoryMode == MemoryMode.IMMUTABLE_DATA + MetricsRequestMarshaler request = MetricsRequestMarshaler.create(metrics); + return doExport.apply(request, metrics.size()); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricStatelessMarshaler.java new file mode 100644 index 00000000000..4a2868ebe2c --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricStatelessMarshaler.java @@ -0,0 +1,212 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import static io.opentelemetry.sdk.metrics.data.MetricDataType.DOUBLE_GAUGE; +import static io.opentelemetry.sdk.metrics.data.MetricDataType.DOUBLE_SUM; +import static io.opentelemetry.sdk.metrics.data.MetricDataType.EXPONENTIAL_HISTOGRAM; +import static io.opentelemetry.sdk.metrics.data.MetricDataType.HISTOGRAM; +import static io.opentelemetry.sdk.metrics.data.MetricDataType.LONG_GAUGE; +import static io.opentelemetry.sdk.metrics.data.MetricDataType.LONG_SUM; +import static io.opentelemetry.sdk.metrics.data.MetricDataType.SUMMARY; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.metrics.v1.internal.Metric; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import java.io.IOException; +import java.util.EnumMap; +import java.util.Map; + +/** See {@link MetricMarshaler}. */ +final class MetricStatelessMarshaler implements StatelessMarshaler { + static final MetricStatelessMarshaler INSTANCE = new MetricStatelessMarshaler(); + private static final Map> METRIC_MARSHALERS = + new EnumMap<>(MetricDataType.class); + + static { + METRIC_MARSHALERS.put( + LONG_GAUGE, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.GAUGE, + metricData.getLongGaugeData(), + GaugeStatelessMarshaler.INSTANCE, + context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.GAUGE, metric.getLongGaugeData(), GaugeStatelessMarshaler.INSTANCE, context); + } + }); + METRIC_MARSHALERS.put( + DOUBLE_GAUGE, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.GAUGE, + metricData.getDoubleGaugeData(), + GaugeStatelessMarshaler.INSTANCE, + context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.GAUGE, + metric.getDoubleGaugeData(), + GaugeStatelessMarshaler.INSTANCE, + context); + } + }); + METRIC_MARSHALERS.put( + LONG_SUM, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.SUM, metricData.getLongSumData(), SumStatelessMarshaler.INSTANCE, context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.SUM, metric.getLongSumData(), SumStatelessMarshaler.INSTANCE, context); + } + }); + METRIC_MARSHALERS.put( + DOUBLE_SUM, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.SUM, metricData.getDoubleSumData(), SumStatelessMarshaler.INSTANCE, context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.SUM, metric.getDoubleSumData(), SumStatelessMarshaler.INSTANCE, context); + } + }); + METRIC_MARSHALERS.put( + SUMMARY, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.SUMMARY, + metricData.getSummaryData(), + SummaryStatelessMarshaler.INSTANCE, + context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.SUMMARY, + metric.getSummaryData(), + SummaryStatelessMarshaler.INSTANCE, + context); + } + }); + METRIC_MARSHALERS.put( + HISTOGRAM, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.HISTOGRAM, + metricData.getHistogramData(), + HistogramStatelessMarshaler.INSTANCE, + context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.HISTOGRAM, + metric.getHistogramData(), + HistogramStatelessMarshaler.INSTANCE, + context); + } + }); + METRIC_MARSHALERS.put( + EXPONENTIAL_HISTOGRAM, + new StatelessMarshaler() { + @Override + public int getBinarySerializedSize(MetricData metricData, MarshalerContext context) { + return StatelessMarshalerUtil.sizeMessageWithContext( + Metric.EXPONENTIAL_HISTOGRAM, + metricData.getExponentialHistogramData(), + ExponentialHistogramStatelessMarshaler.INSTANCE, + context); + } + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + output.serializeMessageWithContext( + Metric.EXPONENTIAL_HISTOGRAM, + metric.getExponentialHistogramData(), + ExponentialHistogramStatelessMarshaler.INSTANCE, + context); + } + }); + } + + private MetricStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, MetricData metric, MarshalerContext context) + throws IOException { + StatelessMarshaler metricMarshaler = METRIC_MARSHALERS.get(metric.getType()); + if (metricMarshaler == null) { + // Someone not using BOM to align versions as we require. Just skip the metric. + return; + } + + output.serializeStringWithContext(Metric.NAME, metric.getName(), context); + output.serializeStringWithContext(Metric.DESCRIPTION, metric.getDescription(), context); + output.serializeStringWithContext(Metric.UNIT, metric.getUnit(), context); + + metricMarshaler.writeTo(output, metric, context); + } + + @Override + public int getBinarySerializedSize(MetricData metric, MarshalerContext context) { + StatelessMarshaler metricMarshaler = METRIC_MARSHALERS.get(metric.getType()); + if (metricMarshaler == null) { + // Someone not using BOM to align versions as we require. Just skip the metric. + return 0; + } + + int size = 0; + size += StatelessMarshalerUtil.sizeStringWithContext(Metric.NAME, metric.getName(), context); + size += + StatelessMarshalerUtil.sizeStringWithContext( + Metric.DESCRIPTION, metric.getDescription(), context); + size += StatelessMarshalerUtil.sizeStringWithContext(Metric.UNIT, metric.getUnit(), context); + + size += metricMarshaler.getBinarySerializedSize(metric, context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointMarshaler.java index 3230f64873c..318130da80a 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointMarshaler.java @@ -40,21 +40,13 @@ static NumberDataPointMarshaler[] createRepeated(Collection static NumberDataPointMarshaler create(PointData point) { ExemplarMarshaler[] exemplarMarshalers = ExemplarMarshaler.createRepeated(point.getExemplars()); KeyValueMarshaler[] attributeMarshalers = - KeyValueMarshaler.createRepeated(point.getAttributes()); - - ProtoFieldInfo valueField; - if (point instanceof LongPointData) { - valueField = NumberDataPoint.AS_INT; - } else { - assert point instanceof DoublePointData; - valueField = NumberDataPoint.AS_DOUBLE; - } + KeyValueMarshaler.createForAttributes(point.getAttributes()); return new NumberDataPointMarshaler( point.getStartEpochNanos(), point.getEpochNanos(), point, - valueField, + toProtoPointValueType(point), exemplarMarshalers, attributeMarshalers); } @@ -76,6 +68,7 @@ private NumberDataPointMarshaler( } @Override + @SuppressWarnings("ReferenceEquality") public void writeTo(Serializer output) throws IOException { output.serializeFixed64(NumberDataPoint.START_TIME_UNIX_NANO, startTimeUnixNano); output.serializeFixed64(NumberDataPoint.TIME_UNIX_NANO, timeUnixNano); @@ -88,6 +81,7 @@ public void writeTo(Serializer output) throws IOException { output.serializeRepeatedMessage(NumberDataPoint.ATTRIBUTES, attributes); } + @SuppressWarnings("ReferenceEquality") private static int calculateSize( long startTimeUnixNano, long timeUnixNano, @@ -107,4 +101,13 @@ private static int calculateSize( size += MarshalerUtil.sizeRepeatedMessage(NumberDataPoint.ATTRIBUTES, attributes); return size; } + + static ProtoFieldInfo toProtoPointValueType(PointData pointData) { + if (pointData instanceof LongPointData) { + return NumberDataPoint.AS_INT; + } else { + assert pointData instanceof DoublePointData; + return NumberDataPoint.AS_DOUBLE; + } + } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointStatelessMarshaler.java new file mode 100644 index 00000000000..40bfd2304d0 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/NumberDataPointStatelessMarshaler.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import static io.opentelemetry.exporter.internal.otlp.metrics.NumberDataPointMarshaler.toProtoPointValueType; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.ProtoFieldInfo; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.NumberDataPoint; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.PointData; +import java.io.IOException; + +/** See {@link NumberDataPointMarshaler}. */ +final class NumberDataPointStatelessMarshaler implements StatelessMarshaler { + static final NumberDataPointStatelessMarshaler INSTANCE = new NumberDataPointStatelessMarshaler(); + + private NumberDataPointStatelessMarshaler() {} + + @Override + @SuppressWarnings("ReferenceEquality") + public void writeTo(Serializer output, PointData point, MarshalerContext context) + throws IOException { + output.serializeFixed64(NumberDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + output.serializeFixed64(NumberDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + ProtoFieldInfo valueField = toProtoPointValueType(point); + if (valueField == NumberDataPoint.AS_INT) { + output.serializeFixed64Optional(valueField, ((LongPointData) point).getValue()); + } else { + output.serializeDoubleOptional(valueField, ((DoublePointData) point).getValue()); + } + output.serializeRepeatedMessageWithContext( + NumberDataPoint.EXEMPLARS, + point.getExemplars(), + ExemplarStatelessMarshaler.INSTANCE, + context); + output.serializeRepeatedMessageWithContext( + NumberDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + } + + @Override + @SuppressWarnings("ReferenceEquality") + public int getBinarySerializedSize(PointData point, MarshalerContext context) { + int size = 0; + size += + MarshalerUtil.sizeFixed64(NumberDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + size += MarshalerUtil.sizeFixed64(NumberDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + ProtoFieldInfo valueField = toProtoPointValueType(point); + if (valueField == NumberDataPoint.AS_INT) { + size += MarshalerUtil.sizeFixed64Optional(valueField, ((LongPointData) point).getValue()); + } else { + size += MarshalerUtil.sizeDoubleOptional(valueField, ((DoublePointData) point).getValue()); + } + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + NumberDataPoint.EXEMPLARS, + point.getExemplars(), + ExemplarStatelessMarshaler.INSTANCE, + context); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + NumberDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsMarshaler.java index 4c584d24d01..9632c63ac0c 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsMarshaler.java @@ -9,7 +9,7 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaller; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; import io.opentelemetry.proto.metrics.v1.internal.ResourceMetrics; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; @@ -32,6 +32,7 @@ public final class ResourceMetricsMarshaler extends MarshalerWithSize { private final InstrumentationScopeMetricsMarshaler[] instrumentationScopeMetricsMarshalers; /** Returns Marshalers of ResourceMetrics created by grouping the provided metricData. */ + @SuppressWarnings("AvoidObjectArrays") public static ResourceMetricsMarshaler[] create(Collection metricDataList) { Map>> resourceAndScopeMap = groupByResourceAndScope(metricDataList); @@ -41,14 +42,14 @@ public static ResourceMetricsMarshaler[] create(Collection metricDat int posResource = 0; for (Map.Entry>> entry : resourceAndScopeMap.entrySet()) { - InstrumentationScopeMetricsMarshaler[] instrumentationLibrarySpansMarshalers = + InstrumentationScopeMetricsMarshaler[] instrumentationScopeMetricsMarshalers = new InstrumentationScopeMetricsMarshaler[entry.getValue().size()]; int posInstrumentation = 0; for (Map.Entry> entryIs : entry.getValue().entrySet()) { - instrumentationLibrarySpansMarshalers[posInstrumentation++] = + instrumentationScopeMetricsMarshalers[posInstrumentation++] = new InstrumentationScopeMetricsMarshaler( - InstrumentationScopeMarshaller.create(entryIs.getKey()), + InstrumentationScopeMarshaler.create(entryIs.getKey()), MarshalerUtil.toBytes(entryIs.getKey().getSchemaUrl()), entryIs.getValue()); } @@ -56,7 +57,7 @@ public static ResourceMetricsMarshaler[] create(Collection metricDat new ResourceMetricsMarshaler( ResourceMarshaler.create(entry.getKey()), MarshalerUtil.toBytes(entry.getKey().getSchemaUrl()), - instrumentationLibrarySpansMarshalers); + instrumentationScopeMetricsMarshalers); } return resourceMetricsMarshalers; diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsStatelessMarshaler.java new file mode 100644 index 00000000000..e25ab330587 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ResourceMetricsStatelessMarshaler.java @@ -0,0 +1,83 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.ResourceMetrics; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * A Marshaler of ResourceMetrics. See {@link ResourceMetricsMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ResourceMetricsStatelessMarshaler + implements StatelessMarshaler2>> { + static final ResourceMetricsStatelessMarshaler INSTANCE = new ResourceMetricsStatelessMarshaler(); + private static final MarshalerContext.Key SCOPE_METRIC_WRITER_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key SCOPE_METRIC_SIZE_CALCULATOR_KEY = + MarshalerContext.key(); + + private ResourceMetricsStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, + Resource resource, + Map> scopeMap, + MarshalerContext context) + throws IOException { + ResourceMarshaler resourceMarshaler = context.getData(ResourceMarshaler.class); + output.serializeMessage(ResourceMetrics.RESOURCE, resourceMarshaler); + + output.serializeRepeatedMessageWithContext( + ResourceMetrics.SCOPE_METRICS, + scopeMap, + InstrumentationScopeMetricsStatelessMarshaler.INSTANCE, + context, + SCOPE_METRIC_WRITER_KEY); + + output.serializeStringWithContext(ResourceMetrics.SCHEMA_URL, resource.getSchemaUrl(), context); + } + + @Override + public int getBinarySerializedSize( + Resource resource, + Map> scopeMap, + MarshalerContext context) { + + int size = 0; + + ResourceMarshaler resourceMarshaler = ResourceMarshaler.create(resource); + context.addData(resourceMarshaler); + size += MarshalerUtil.sizeMessage(ResourceMetrics.RESOURCE, resourceMarshaler); + + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ResourceMetrics.SCOPE_METRICS, + scopeMap, + InstrumentationScopeMetricsStatelessMarshaler.INSTANCE, + context, + SCOPE_METRIC_SIZE_CALCULATOR_KEY); + + size += + StatelessMarshalerUtil.sizeStringWithContext( + ResourceMetrics.SCHEMA_URL, resource.getSchemaUrl(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SumStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SumStatelessMarshaler.java new file mode 100644 index 00000000000..9a4ce569bee --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SumStatelessMarshaler.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.metrics.v1.internal.Sum; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.data.SumData; +import java.io.IOException; + +/** See {@link SumMarshaler}. */ +final class SumStatelessMarshaler implements StatelessMarshaler> { + static final SumStatelessMarshaler INSTANCE = new SumStatelessMarshaler(); + private static final MarshalerContext.Key DATA_POINT_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key DATA_POINT_WRITER_KEY = MarshalerContext.key(); + + @Override + public void writeTo(Serializer output, SumData sum, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + Sum.DATA_POINTS, + sum.getPoints(), + NumberDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_WRITER_KEY); + output.serializeEnum( + Sum.AGGREGATION_TEMPORALITY, + MetricsMarshalerUtil.mapToTemporality(sum.getAggregationTemporality())); + output.serializeBool(Sum.IS_MONOTONIC, sum.isMonotonic()); + } + + @Override + public int getBinarySerializedSize(SumData sum, MarshalerContext context) { + int size = 0; + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Sum.DATA_POINTS, + sum.getPoints(), + NumberDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_SIZE_CALCULATOR_KEY); + size += + MarshalerUtil.sizeEnum( + Sum.AGGREGATION_TEMPORALITY, + MetricsMarshalerUtil.mapToTemporality(sum.getAggregationTemporality())); + size += MarshalerUtil.sizeBool(Sum.IS_MONOTONIC, sum.isMonotonic()); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointMarshaler.java index cb38c86ed13..c0b6a1dcded 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointMarshaler.java @@ -20,7 +20,7 @@ final class SummaryDataPointMarshaler extends MarshalerWithSize { private final long count; private final double sum; private final ValueAtQuantileMarshaler[] quantileValues; - private final KeyValueMarshaler[] attributes; + private final MarshalerWithSize[] attributes; static SummaryDataPointMarshaler[] createRepeated(Collection points) { SummaryDataPointMarshaler[] marshalers = new SummaryDataPointMarshaler[points.size()]; @@ -34,8 +34,8 @@ static SummaryDataPointMarshaler[] createRepeated(Collection p static SummaryDataPointMarshaler create(SummaryPointData point) { ValueAtQuantileMarshaler[] quantileMarshalers = ValueAtQuantileMarshaler.createRepeated(point.getValues()); - KeyValueMarshaler[] attributeMarshalers = - KeyValueMarshaler.createRepeated(point.getAttributes()); + MarshalerWithSize[] attributeMarshalers = + KeyValueMarshaler.createForAttributes(point.getAttributes()); return new SummaryDataPointMarshaler( point.getStartEpochNanos(), @@ -52,7 +52,7 @@ private SummaryDataPointMarshaler( long count, double sum, ValueAtQuantileMarshaler[] quantileValues, - KeyValueMarshaler[] attributes) { + MarshalerWithSize[] attributes) { super(calculateSize(startTimeUnixNano, timeUnixNano, count, sum, quantileValues, attributes)); this.startTimeUnixNano = startTimeUnixNano; this.timeUnixNano = timeUnixNano; @@ -78,7 +78,7 @@ private static int calculateSize( long count, double sum, ValueAtQuantileMarshaler[] quantileValues, - KeyValueMarshaler[] attributes) { + MarshalerWithSize[] attributes) { int size = 0; size += MarshalerUtil.sizeFixed64(SummaryDataPoint.START_TIME_UNIX_NANO, startTimeUnixNano); size += MarshalerUtil.sizeFixed64(SummaryDataPoint.TIME_UNIX_NANO, timeUnixNano); diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointStatelessMarshaler.java new file mode 100644 index 00000000000..bcd2306bb13 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryDataPointStatelessMarshaler.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.SummaryDataPoint; +import io.opentelemetry.sdk.metrics.data.SummaryPointData; +import java.io.IOException; + +/** See {@link SummaryDataPointMarshaler}. */ +final class SummaryDataPointStatelessMarshaler implements StatelessMarshaler { + static final SummaryDataPointStatelessMarshaler INSTANCE = + new SummaryDataPointStatelessMarshaler(); + + private SummaryDataPointStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, SummaryPointData point, MarshalerContext context) + throws IOException { + output.serializeFixed64(SummaryDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + output.serializeFixed64(SummaryDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + output.serializeFixed64(SummaryDataPoint.COUNT, point.getCount()); + output.serializeDouble(SummaryDataPoint.SUM, point.getSum()); + output.serializeRepeatedMessageWithContext( + SummaryDataPoint.QUANTILE_VALUES, + point.getValues(), + ValueAtQuantileStatelessMarshaler.INSTANCE, + context); + output.serializeRepeatedMessageWithContext( + SummaryDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + } + + @Override + public int getBinarySerializedSize(SummaryPointData point, MarshalerContext context) { + int size = 0; + size += + MarshalerUtil.sizeFixed64( + SummaryDataPoint.START_TIME_UNIX_NANO, point.getStartEpochNanos()); + size += MarshalerUtil.sizeFixed64(SummaryDataPoint.TIME_UNIX_NANO, point.getEpochNanos()); + size += MarshalerUtil.sizeFixed64(SummaryDataPoint.COUNT, point.getCount()); + size += MarshalerUtil.sizeDouble(SummaryDataPoint.SUM, point.getSum()); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + SummaryDataPoint.QUANTILE_VALUES, + point.getValues(), + ValueAtQuantileStatelessMarshaler.INSTANCE, + context); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + SummaryDataPoint.ATTRIBUTES, + point.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryStatelessMarshaler.java new file mode 100644 index 00000000000..b15984592b8 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/SummaryStatelessMarshaler.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.metrics.v1.internal.Summary; +import io.opentelemetry.sdk.metrics.data.SummaryData; +import java.io.IOException; + +/** See {@link SummaryMarshaler}. */ +final class SummaryStatelessMarshaler implements StatelessMarshaler { + static final SummaryStatelessMarshaler INSTANCE = new SummaryStatelessMarshaler(); + private static final MarshalerContext.Key DATA_POINT_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key DATA_POINT_WRITER_KEY = MarshalerContext.key(); + + private SummaryStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, SummaryData summary, MarshalerContext context) + throws IOException { + output.serializeRepeatedMessageWithContext( + Summary.DATA_POINTS, + summary.getPoints(), + SummaryDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_WRITER_KEY); + } + + @Override + public int getBinarySerializedSize(SummaryData summary, MarshalerContext context) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Summary.DATA_POINTS, + summary.getPoints(), + SummaryDataPointStatelessMarshaler.INSTANCE, + context, + DATA_POINT_SIZE_CALCULATOR_KEY); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileMarshaler.java index 6f9ec38ef61..1c2e6ba09db 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileMarshaler.java @@ -42,7 +42,7 @@ public void writeTo(Serializer output) throws IOException { output.serializeDouble(SummaryDataPoint.ValueAtQuantile.VALUE, value); } - private static int calculateSize(double quantile, double value) { + static int calculateSize(double quantile, double value) { int size = 0; size += MarshalerUtil.sizeDouble(SummaryDataPoint.ValueAtQuantile.QUANTILE, quantile); size += MarshalerUtil.sizeDouble(SummaryDataPoint.ValueAtQuantile.VALUE, value); diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileStatelessMarshaler.java new file mode 100644 index 00000000000..ba1f0347865 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/metrics/ValueAtQuantileStatelessMarshaler.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.metrics.v1.internal.SummaryDataPoint; +import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; +import java.io.IOException; + +/** See {@link ValueAtQuantileMarshaler}. */ +final class ValueAtQuantileStatelessMarshaler implements StatelessMarshaler { + static final ValueAtQuantileStatelessMarshaler INSTANCE = new ValueAtQuantileStatelessMarshaler(); + + private ValueAtQuantileStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, ValueAtQuantile value, MarshalerContext context) + throws IOException { + output.serializeDouble(SummaryDataPoint.ValueAtQuantile.QUANTILE, value.getQuantile()); + output.serializeDouble(SummaryDataPoint.ValueAtQuantile.VALUE, value.getValue()); + } + + @Override + public int getBinarySerializedSize(ValueAtQuantile value, MarshalerContext context) { + return ValueAtQuantileMarshaler.calculateSize(value.getQuantile(), value.getValue()); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansMarshaler.java index bec24e09933..26af3ea3fd7 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansMarshaler.java @@ -8,18 +8,18 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaller; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; import io.opentelemetry.proto.trace.v1.internal.ScopeSpans; import java.io.IOException; import java.util.List; final class InstrumentationScopeSpansMarshaler extends MarshalerWithSize { - private final InstrumentationScopeMarshaller instrumentationScope; + private final InstrumentationScopeMarshaler instrumentationScope; private final List spanMarshalers; private final byte[] schemaUrlUtf8; InstrumentationScopeSpansMarshaler( - InstrumentationScopeMarshaller instrumentationScope, + InstrumentationScopeMarshaler instrumentationScope, byte[] schemaUrlUtf8, List spanMarshalers) { super(calculateSize(instrumentationScope, schemaUrlUtf8, spanMarshalers)); @@ -36,7 +36,7 @@ public void writeTo(Serializer output) throws IOException { } private static int calculateSize( - InstrumentationScopeMarshaller instrumentationScope, + InstrumentationScopeMarshaler instrumentationScope, byte[] schemaUrlUtf8, List spanMarshalers) { int size = 0; diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansStatelessMarshaler.java new file mode 100644 index 00000000000..decec18ea79 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/InstrumentationScopeSpansStatelessMarshaler.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; +import io.opentelemetry.proto.trace.v1.internal.ScopeSpans; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.IOException; +import java.util.List; + +/** See {@link InstrumentationScopeSpansMarshaler}. */ +final class InstrumentationScopeSpansStatelessMarshaler + implements StatelessMarshaler2> { + static final InstrumentationScopeSpansStatelessMarshaler INSTANCE = + new InstrumentationScopeSpansStatelessMarshaler(); + + private InstrumentationScopeSpansStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, + InstrumentationScopeInfo instrumentationScope, + List spans, + MarshalerContext context) + throws IOException { + InstrumentationScopeMarshaler instrumentationScopeMarshaler = + context.getData(InstrumentationScopeMarshaler.class); + + output.serializeMessage(ScopeSpans.SCOPE, instrumentationScopeMarshaler); + output.serializeRepeatedMessageWithContext( + ScopeSpans.SPANS, spans, SpanStatelessMarshaler.INSTANCE, context); + output.serializeStringWithContext( + ScopeSpans.SCHEMA_URL, instrumentationScope.getSchemaUrl(), context); + } + + @Override + public int getBinarySerializedSize( + InstrumentationScopeInfo instrumentationScope, + List spans, + MarshalerContext context) { + InstrumentationScopeMarshaler instrumentationScopeMarshaler = + InstrumentationScopeMarshaler.create(instrumentationScope); + context.addData(instrumentationScopeMarshaler); + + int size = 0; + size += MarshalerUtil.sizeMessage(ScopeSpans.SCOPE, instrumentationScopeMarshaler); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ScopeSpans.SPANS, spans, SpanStatelessMarshaler.INSTANCE, context); + size += + StatelessMarshalerUtil.sizeStringWithContext( + ScopeSpans.SCHEMA_URL, instrumentationScope.getSchemaUrl(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/LowAllocationTraceRequestMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/LowAllocationTraceRequestMarshaler.java new file mode 100644 index 00000000000..5da173f3c3a --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/LowAllocationTraceRequestMarshaler.java @@ -0,0 +1,107 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.collector.trace.v1.internal.ExportTraceServiceRequest; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * {@link Marshaler} to convert SDK {@link SpanData} to OTLP ExportTraceServiceRequest. See {@link + * TraceRequestMarshaler}. + * + *

    Example usage: + * + *

    {@code
    + * void marshal(LowAllocationTraceRequestMarshaler requestMarshaler, OutputStream output,
    + *     List spanList) throws IOException {
    + *   requestMarshaler.initialize(spanList);
    + *   try {
    + *     requestMarshaler.writeBinaryTo(output);
    + *   } finally {
    + *     requestMarshaler.reset();
    + *   }
    + * }
    + * }
    + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class LowAllocationTraceRequestMarshaler extends Marshaler { + private static final MarshalerContext.Key RESOURCE_SPAN_SIZE_CALCULATOR_KEY = + MarshalerContext.key(); + private static final MarshalerContext.Key RESOURCE_SPAN_WRITER_KEY = MarshalerContext.key(); + + private final MarshalerContext context = new MarshalerContext(); + + @SuppressWarnings("NullAway") + private Map>> resourceAndScopeMap; + + private int size; + + public void initialize(Collection spanDataList) { + resourceAndScopeMap = groupByResourceAndScope(context, spanDataList); + size = calculateSize(context, resourceAndScopeMap); + } + + public void reset() { + context.reset(); + } + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + public void writeTo(Serializer output) throws IOException { + // serializing can be retried, reset the indexes, so we could call writeTo multiple times + context.resetReadIndex(); + output.serializeRepeatedMessageWithContext( + ExportTraceServiceRequest.RESOURCE_SPANS, + resourceAndScopeMap, + ResourceSpansStatelessMarshaler.INSTANCE, + context, + RESOURCE_SPAN_WRITER_KEY); + } + + private static int calculateSize( + MarshalerContext context, + Map>> resourceAndScopeMap) { + return StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ExportTraceServiceRequest.RESOURCE_SPANS, + resourceAndScopeMap, + ResourceSpansStatelessMarshaler.INSTANCE, + context, + RESOURCE_SPAN_SIZE_CALCULATOR_KEY); + } + + private static Map>> + groupByResourceAndScope(MarshalerContext context, Collection spanDataList) { + + if (spanDataList.isEmpty()) { + return Collections.emptyMap(); + } + + return StatelessMarshalerUtil.groupByResourceAndScope( + spanDataList, + // TODO(anuraaga): Replace with an internal SdkData type of interface that exposes these + // two. + SpanData::getResource, + SpanData::getInstrumentationScopeInfo, + context); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansMarshaler.java index 047378fa07d..0e9d5a91e09 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansMarshaler.java @@ -8,7 +8,7 @@ import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.Serializer; -import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaller; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; import io.opentelemetry.proto.trace.v1.internal.ResourceSpans; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; @@ -31,6 +31,7 @@ public final class ResourceSpansMarshaler extends MarshalerWithSize { private final InstrumentationScopeSpansMarshaler[] instrumentationScopeSpansMarshalers; /** Returns Marshalers of ResourceSpans created by grouping the provided SpanData. */ + @SuppressWarnings("AvoidObjectArrays") public static ResourceSpansMarshaler[] create(Collection spanDataList) { Map>> resourceAndScopeMap = groupByResourceAndScope(spanDataList); @@ -47,7 +48,7 @@ public static ResourceSpansMarshaler[] create(Collection spanDataList) entry.getValue().entrySet()) { instrumentationScopeSpansMarshalers[posInstrumentation++] = new InstrumentationScopeSpansMarshaler( - InstrumentationScopeMarshaller.create(entryIs.getKey()), + InstrumentationScopeMarshaler.create(entryIs.getKey()), MarshalerUtil.toBytes(entryIs.getKey().getSchemaUrl()), entryIs.getValue()); } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansStatelessMarshaler.java new file mode 100644 index 00000000000..7ae30feb91d --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/ResourceSpansStatelessMarshaler.java @@ -0,0 +1,82 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler2; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; +import io.opentelemetry.proto.trace.v1.internal.ResourceSpans; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.IOException; +import java.util.List; +import java.util.Map; + +/** + * A Marshaler of ResourceSpans. See {@link ResourceSpansMarshaler}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ResourceSpansStatelessMarshaler + implements StatelessMarshaler2>> { + static final ResourceSpansStatelessMarshaler INSTANCE = new ResourceSpansStatelessMarshaler(); + private static final MarshalerContext.Key SCOPE_SPAN_WRITER_KEY = MarshalerContext.key(); + private static final MarshalerContext.Key SCOPE_SPAN_SIZE_CALCULATOR_KEY = MarshalerContext.key(); + + private ResourceSpansStatelessMarshaler() {} + + @Override + public void writeTo( + Serializer output, + Resource resource, + Map> scopeMap, + MarshalerContext context) + throws IOException { + ResourceMarshaler resourceMarshaler = context.getData(ResourceMarshaler.class); + output.serializeMessage(ResourceSpans.RESOURCE, resourceMarshaler); + + output.serializeRepeatedMessageWithContext( + ResourceSpans.SCOPE_SPANS, + scopeMap, + InstrumentationScopeSpansStatelessMarshaler.INSTANCE, + context, + SCOPE_SPAN_WRITER_KEY); + + output.serializeStringWithContext(ResourceSpans.SCHEMA_URL, resource.getSchemaUrl(), context); + } + + @Override + public int getBinarySerializedSize( + Resource resource, + Map> scopeMap, + MarshalerContext context) { + + int size = 0; + + ResourceMarshaler resourceMarshaler = ResourceMarshaler.create(resource); + context.addData(resourceMarshaler); + size += MarshalerUtil.sizeMessage(ResourceSpans.RESOURCE, resourceMarshaler); + + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + ResourceSpans.SCOPE_SPANS, + scopeMap, + InstrumentationScopeSpansStatelessMarshaler.INSTANCE, + context, + SCOPE_SPAN_SIZE_CALCULATOR_KEY); + + size += + StatelessMarshalerUtil.sizeStringWithContext( + ResourceSpans.SCHEMA_URL, resource.getSchemaUrl(), context); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventMarshaler.java index 03b208f3df0..2b2cc1d7775 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventMarshaler.java @@ -40,7 +40,7 @@ static SpanEventMarshaler create(EventData event) { return new SpanEventMarshaler( event.getEpochNanos(), MarshalerUtil.toBytes(event.getName()), - KeyValueMarshaler.createRepeated(event.getAttributes()), + KeyValueMarshaler.createForAttributes(event.getAttributes()), event.getTotalAttributeCount() - event.getAttributes().size()); } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventStatelessMarshaler.java new file mode 100644 index 00000000000..a1878c3099b --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanEventStatelessMarshaler.java @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.trace.v1.internal.Span; +import io.opentelemetry.sdk.trace.data.EventData; +import java.io.IOException; + +/** See {@link SpanEventMarshaler}. */ +final class SpanEventStatelessMarshaler implements StatelessMarshaler { + static final SpanEventStatelessMarshaler INSTANCE = new SpanEventStatelessMarshaler(); + + private SpanEventStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, EventData event, MarshalerContext context) + throws IOException { + output.serializeFixed64(Span.Event.TIME_UNIX_NANO, event.getEpochNanos()); + output.serializeStringWithContext(Span.Event.NAME, event.getName(), context); + output.serializeRepeatedMessageWithContext( + Span.Event.ATTRIBUTES, + event.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + int droppedAttributesCount = event.getTotalAttributeCount() - event.getAttributes().size(); + output.serializeUInt32(Span.Event.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + } + + @Override + public int getBinarySerializedSize(EventData event, MarshalerContext context) { + int size = 0; + size += MarshalerUtil.sizeFixed64(Span.Event.TIME_UNIX_NANO, event.getEpochNanos()); + size += StatelessMarshalerUtil.sizeStringWithContext(Span.Event.NAME, event.getName(), context); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Span.Event.ATTRIBUTES, + event.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + int droppedAttributesCount = event.getTotalAttributeCount() - event.getAttributes().size(); + size += MarshalerUtil.sizeUInt32(Span.Event.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanFlags.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanFlags.java new file mode 100644 index 00000000000..571be523492 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanFlags.java @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import io.opentelemetry.api.trace.TraceFlags; + +/** + * Represents the 32 bit span flags as + * specified in the proto definition. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class SpanFlags { + // As defined at: + // https://github.com/open-telemetry/opentelemetry-proto/blob/342e1d4c3a1fe43312823ffb53bd38327f263059/opentelemetry/proto/trace/v1/trace.proto#L351-L352 + static final int CONTEXT_HAS_IS_REMOTE_BIT = 0x00000100; + static final int CONTEXT_IS_REMOTE_BIT = 0x00000200; + static final int CONTEXT_IS_REMOTE_MASK = CONTEXT_HAS_IS_REMOTE_BIT | CONTEXT_IS_REMOTE_BIT; + + private SpanFlags() {} + + /** + * Returns the int (fixed32) representation of the {@link TraceFlags} enriched with the flags + * indicating a remote parent. + * + * @param isParentRemote indicates whether the parent context is remote + * @return the int (fixed32) representation of the {@link TraceFlags} enriched with the flags + * indicating a remote parent. + */ + public static int withParentIsRemoteFlags(TraceFlags traceFlags, boolean isParentRemote) { + byte byteRep = traceFlags.asByte(); + if (isParentRemote) { + return (byteRep & 0xff) | CONTEXT_IS_REMOTE_MASK; + } + return (byteRep & 0xff) | CONTEXT_HAS_IS_REMOTE_BIT; + } + + /** + * Returns the int (fixed32) representation of the 4 bytes flags with the + * has_parent_context_is_remote flag bit on. + * + * @return the int (fixed32) representation of the 4 bytes flags with the * + * has_parent_context_is_remote flag bit on. + */ + public static int getHasParentIsRemoteMask() { + return CONTEXT_HAS_IS_REMOTE_BIT; + } + + /** + * Checks whether the given flags contain information about parent context being remote or not. + * + * @param flags The int representation of the 32 bit span flags field defined in proto. + * @return True, if the given flags contain information about the span's parent context being + * remote, otherwise, false. + */ + public static boolean isKnownWhetherParentIsRemote(int flags) { + return (flags & CONTEXT_HAS_IS_REMOTE_BIT) != 0; + } + + /** + * Returns the int (fixed32) representation of the 4 bytes flags with the + * has_parent_context_is_remote and parent_context_is_remote flag bits on. + * + * @return the int (fixed32) representation of the 4 bytes flags with the + * has_parent_context_is_remote and parent_context_is_remote flag bits on. + */ + public static int getParentIsRemoteMask() { + return CONTEXT_IS_REMOTE_MASK; + } + + /** + * Checks whether in the given flags the parent is marked as remote. + * + * @param flags The int representation of the 32 bit span flags field defined in proto. + * @return True, if the given flags contain information about the span's parent context and the + * parent is marked as remote, otherwise false. + */ + public static boolean isParentRemote(int flags) { + return (flags & CONTEXT_IS_REMOTE_MASK) == CONTEXT_IS_REMOTE_MASK; + } + + /** + * Returns the W3C {@link TraceFlags} (least significant 8 bits) portion from the given 32 bit + * span flags fields. + * + * @param flags The int representation of the 32 bit span flags field defined in proto. + * @return the W3C {@link TraceFlags} (least significant 8 bits) portion from the given 32 bit + * span flags fields. + */ + public static TraceFlags getTraceFlags(int flags) { + return TraceFlags.fromByte((byte) (flags & 0xff)); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkMarshaler.java index 0579fb56e10..86db5e2c983 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkMarshaler.java @@ -5,8 +5,9 @@ package io.opentelemetry.exporter.internal.otlp.traces; -import static io.opentelemetry.api.trace.propagation.internal.W3CTraceContextEncoding.encodeTraceState; +import static io.opentelemetry.exporter.internal.otlp.traces.SpanMarshaler.encodeTraceState; +import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; @@ -15,17 +16,18 @@ import io.opentelemetry.proto.trace.v1.internal.Span; import io.opentelemetry.sdk.trace.data.LinkData; import java.io.IOException; -import java.nio.charset.StandardCharsets; import java.util.List; final class SpanLinkMarshaler extends MarshalerWithSize { private static final SpanLinkMarshaler[] EMPTY = new SpanLinkMarshaler[0]; - private static final byte[] EMPTY_BYTES = new byte[0]; + private final String traceId; private final String spanId; private final byte[] traceStateUtf8; private final KeyValueMarshaler[] attributeMarshalers; private final int droppedAttributesCount; + private final TraceFlags traceFlags; + private final boolean isLinkContextRemote; static SpanLinkMarshaler[] createRepeated(List links) { if (links.isEmpty()) { @@ -43,33 +45,42 @@ static SpanLinkMarshaler[] createRepeated(List links) { // Visible for testing static SpanLinkMarshaler create(LinkData link) { - TraceState traceState = link.getSpanContext().getTraceState(); - byte[] traceStateUtf8 = - traceState.isEmpty() - ? EMPTY_BYTES - : encodeTraceState(traceState).getBytes(StandardCharsets.UTF_8); + byte[] traceStateUtf8 = encodeSpanLinkTraceState(link); + return new SpanLinkMarshaler( link.getSpanContext().getTraceId(), link.getSpanContext().getSpanId(), + link.getSpanContext().getTraceFlags(), traceStateUtf8, - KeyValueMarshaler.createRepeated(link.getAttributes()), - link.getTotalAttributeCount() - link.getAttributes().size()); + KeyValueMarshaler.createForAttributes(link.getAttributes()), + link.getTotalAttributeCount() - link.getAttributes().size(), + link.getSpanContext().isRemote()); } private SpanLinkMarshaler( String traceId, String spanId, + TraceFlags traceFlags, byte[] traceStateUtf8, KeyValueMarshaler[] attributeMarshalers, - int droppedAttributesCount) { + int droppedAttributesCount, + boolean isLinkContextRemote) { super( calculateSize( - traceId, spanId, traceStateUtf8, attributeMarshalers, droppedAttributesCount)); + traceId, + spanId, + traceFlags, + traceStateUtf8, + attributeMarshalers, + droppedAttributesCount, + isLinkContextRemote)); this.traceId = traceId; this.spanId = spanId; + this.traceFlags = traceFlags; this.traceStateUtf8 = traceStateUtf8; this.attributeMarshalers = attributeMarshalers; this.droppedAttributesCount = droppedAttributesCount; + this.isLinkContextRemote = isLinkContextRemote; } @Override @@ -79,20 +90,32 @@ public void writeTo(Serializer output) throws IOException { output.serializeString(Span.Link.TRACE_STATE, traceStateUtf8); output.serializeRepeatedMessage(Span.Link.ATTRIBUTES, attributeMarshalers); output.serializeUInt32(Span.Link.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + output.serializeFixed32( + Span.Link.FLAGS, SpanFlags.withParentIsRemoteFlags(traceFlags, isLinkContextRemote)); } private static int calculateSize( String traceId, String spanId, + TraceFlags flags, byte[] traceStateUtf8, KeyValueMarshaler[] attributeMarshalers, - int droppedAttributesCount) { + int droppedAttributesCount, + boolean isLinkContextRemote) { int size = 0; size += MarshalerUtil.sizeTraceId(Span.Link.TRACE_ID, traceId); size += MarshalerUtil.sizeSpanId(Span.Link.SPAN_ID, spanId); size += MarshalerUtil.sizeBytes(Span.Link.TRACE_STATE, traceStateUtf8); size += MarshalerUtil.sizeRepeatedMessage(Span.Link.ATTRIBUTES, attributeMarshalers); size += MarshalerUtil.sizeUInt32(Span.Link.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + size += + MarshalerUtil.sizeFixed32( + Span.Link.FLAGS, SpanFlags.withParentIsRemoteFlags(flags, isLinkContextRemote)); return size; } + + static byte[] encodeSpanLinkTraceState(LinkData link) { + TraceState traceState = link.getSpanContext().getTraceState(); + return encodeTraceState(traceState); + } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkStatelessMarshaler.java new file mode 100644 index 00000000000..86d3aef37fb --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanLinkStatelessMarshaler.java @@ -0,0 +1,70 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import static io.opentelemetry.exporter.internal.otlp.traces.SpanLinkMarshaler.encodeSpanLinkTraceState; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.trace.v1.internal.Span; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.io.IOException; + +/** See {@link SpanLinkMarshaler}. */ +final class SpanLinkStatelessMarshaler implements StatelessMarshaler { + static final SpanLinkStatelessMarshaler INSTANCE = new SpanLinkStatelessMarshaler(); + + private SpanLinkStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, LinkData link, MarshalerContext context) + throws IOException { + output.serializeTraceId(Span.Link.TRACE_ID, link.getSpanContext().getTraceId(), context); + output.serializeSpanId(Span.Link.SPAN_ID, link.getSpanContext().getSpanId(), context); + output.serializeString(Span.Link.TRACE_STATE, context.getData(byte[].class)); + output.serializeRepeatedMessageWithContext( + Span.Link.ATTRIBUTES, + link.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + int droppedAttributesCount = link.getTotalAttributeCount() - link.getAttributes().size(); + output.serializeUInt32(Span.Link.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + output.serializeFixed32( + Span.Link.FLAGS, + SpanFlags.withParentIsRemoteFlags( + link.getSpanContext().getTraceFlags(), link.getSpanContext().isRemote())); + } + + @Override + public int getBinarySerializedSize(LinkData link, MarshalerContext context) { + byte[] traceStateUtf8 = encodeSpanLinkTraceState(link); + context.addData(traceStateUtf8); + + int size = 0; + size += MarshalerUtil.sizeTraceId(Span.Link.TRACE_ID, link.getSpanContext().getTraceId()); + size += MarshalerUtil.sizeSpanId(Span.Link.SPAN_ID, link.getSpanContext().getSpanId()); + size += MarshalerUtil.sizeBytes(Span.Link.TRACE_STATE, traceStateUtf8); + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Span.Link.ATTRIBUTES, + link.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + int droppedAttributesCount = link.getTotalAttributeCount() - link.getAttributes().size(); + size += MarshalerUtil.sizeUInt32(Span.Link.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + size += + MarshalerUtil.sizeFixed32( + Span.Link.FLAGS, + SpanFlags.withParentIsRemoteFlags( + link.getSpanContext().getTraceFlags(), link.getSpanContext().isRemote())); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanMarshaler.java index b487f262a3c..2e862c6cc69 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanMarshaler.java @@ -5,10 +5,10 @@ package io.opentelemetry.exporter.internal.otlp.traces; -import static io.opentelemetry.api.trace.propagation.internal.W3CTraceContextEncoding.encodeTraceState; - import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.propagation.internal.W3CTraceContextEncoding; import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; import io.opentelemetry.exporter.internal.marshal.ProtoEnumInfo; @@ -37,11 +37,13 @@ final class SpanMarshaler extends MarshalerWithSize { private final SpanLinkMarshaler[] spanLinkMarshalers; private final int droppedLinksCount; private final SpanStatusMarshaler spanStatusMarshaler; + private final TraceFlags flags; + private final boolean isParentContextRemote; // Because SpanMarshaler is always part of a repeated field, it cannot return "null". static SpanMarshaler create(SpanData spanData) { KeyValueMarshaler[] attributeMarshalers = - KeyValueMarshaler.createRepeated(spanData.getAttributes()); + KeyValueMarshaler.createForAttributes(spanData.getAttributes()); SpanEventMarshaler[] spanEventMarshalers = SpanEventMarshaler.createRepeated(spanData.getEvents()); SpanLinkMarshaler[] spanLinkMarshalers = SpanLinkMarshaler.createRepeated(spanData.getLinks()); @@ -51,11 +53,7 @@ static SpanMarshaler create(SpanData spanData) { ? spanData.getParentSpanContext().getSpanId() : null; - TraceState traceState = spanData.getSpanContext().getTraceState(); - byte[] traceStateUtf8 = - traceState.isEmpty() - ? EMPTY_BYTES - : encodeTraceState(traceState).getBytes(StandardCharsets.UTF_8); + byte[] traceStateUtf8 = encodeSpanTraceState(spanData); return new SpanMarshaler( spanData.getSpanContext().getTraceId(), @@ -72,7 +70,9 @@ static SpanMarshaler create(SpanData spanData) { spanData.getTotalRecordedEvents() - spanData.getEvents().size(), spanLinkMarshalers, spanData.getTotalRecordedLinks() - spanData.getLinks().size(), - SpanStatusMarshaler.create(spanData.getStatus())); + SpanStatusMarshaler.create(spanData.getStatus()), + spanData.getSpanContext().getTraceFlags(), + spanData.getParentSpanContext().isRemote()); } private SpanMarshaler( @@ -90,7 +90,9 @@ private SpanMarshaler( int droppedEventsCount, SpanLinkMarshaler[] spanLinkMarshalers, int droppedLinksCount, - SpanStatusMarshaler spanStatusMarshaler) { + SpanStatusMarshaler spanStatusMarshaler, + TraceFlags flags, + boolean isParentContextRemote) { super( calculateSize( traceId, @@ -107,7 +109,9 @@ private SpanMarshaler( droppedEventsCount, spanLinkMarshalers, droppedLinksCount, - spanStatusMarshaler)); + spanStatusMarshaler, + flags, + isParentContextRemote)); this.traceId = traceId; this.spanId = spanId; this.traceStateUtf8 = traceStateUtf8; @@ -123,6 +127,8 @@ private SpanMarshaler( this.spanLinkMarshalers = spanLinkMarshalers; this.droppedLinksCount = droppedLinksCount; this.spanStatusMarshaler = spanStatusMarshaler; + this.flags = flags; + this.isParentContextRemote = isParentContextRemote; } @Override @@ -148,6 +154,8 @@ public void writeTo(Serializer output) throws IOException { output.serializeUInt32(Span.DROPPED_LINKS_COUNT, droppedLinksCount); output.serializeMessage(Span.STATUS, spanStatusMarshaler); + output.serializeFixed32( + Span.FLAGS, SpanFlags.withParentIsRemoteFlags(flags, isParentContextRemote)); } private static int calculateSize( @@ -165,7 +173,9 @@ private static int calculateSize( int droppedEventsCount, SpanLinkMarshaler[] spanLinkMarshalers, int droppedLinksCount, - SpanStatusMarshaler spanStatusMarshaler) { + SpanStatusMarshaler spanStatusMarshaler, + TraceFlags flags, + boolean isParentContextRemote) { int size = 0; size += MarshalerUtil.sizeTraceId(Span.TRACE_ID, traceId); size += MarshalerUtil.sizeSpanId(Span.SPAN_ID, spanId); @@ -188,6 +198,9 @@ private static int calculateSize( size += MarshalerUtil.sizeUInt32(Span.DROPPED_LINKS_COUNT, droppedLinksCount); size += MarshalerUtil.sizeMessage(Span.STATUS, spanStatusMarshaler); + size += + MarshalerUtil.sizeFixed32( + Span.FLAGS, SpanFlags.withParentIsRemoteFlags(flags, isParentContextRemote)); return size; } @@ -208,4 +221,15 @@ static ProtoEnumInfo toProtoSpanKind(SpanKind kind) { // NB: Should not be possible with aligned versions. return Span.SpanKind.SPAN_KIND_UNSPECIFIED; } + + static byte[] encodeSpanTraceState(SpanData span) { + TraceState traceState = span.getSpanContext().getTraceState(); + return encodeTraceState(traceState); + } + + static byte[] encodeTraceState(TraceState traceState) { + return traceState.isEmpty() + ? EMPTY_BYTES + : W3CTraceContextEncoding.encodeTraceState(traceState).getBytes(StandardCharsets.UTF_8); + } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java new file mode 100644 index 00000000000..ff54280b610 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanReusableDataMarshaler.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.util.Collection; +import java.util.Deque; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.function.BiFunction; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public class SpanReusableDataMarshaler { + + private final Deque marshalerPool = + new ConcurrentLinkedDeque<>(); + + private final MemoryMode memoryMode; + private final BiFunction doExport; + + public SpanReusableDataMarshaler( + MemoryMode memoryMode, BiFunction doExport) { + this.memoryMode = memoryMode; + this.doExport = doExport; + } + + public MemoryMode getMemoryMode() { + return memoryMode; + } + + public CompletableResultCode export(Collection spans) { + if (memoryMode == MemoryMode.REUSABLE_DATA) { + LowAllocationTraceRequestMarshaler marshaler = marshalerPool.poll(); + if (marshaler == null) { + marshaler = new LowAllocationTraceRequestMarshaler(); + } + LowAllocationTraceRequestMarshaler exportMarshaler = marshaler; + exportMarshaler.initialize(spans); + return doExport + .apply(exportMarshaler, spans.size()) + .whenComplete(() -> { + exportMarshaler.reset(); + marshalerPool.add(exportMarshaler); + }); + } + // MemoryMode == MemoryMode.IMMUTABLE_DATA + TraceRequestMarshaler request = TraceRequestMarshaler.create(spans); + return doExport.apply(request, spans.size()); + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatelessMarshaler.java new file mode 100644 index 00000000000..acfa5cae85a --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatelessMarshaler.java @@ -0,0 +1,125 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import static io.opentelemetry.exporter.internal.otlp.traces.SpanMarshaler.encodeSpanTraceState; +import static io.opentelemetry.exporter.internal.otlp.traces.SpanMarshaler.toProtoSpanKind; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.exporter.internal.otlp.AttributeKeyValueStatelessMarshaler; +import io.opentelemetry.proto.trace.v1.internal.Span; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.io.IOException; + +/** See {@link SpanMarshaler}. */ +final class SpanStatelessMarshaler implements StatelessMarshaler { + static final SpanStatelessMarshaler INSTANCE = new SpanStatelessMarshaler(); + + private SpanStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, SpanData span, MarshalerContext context) + throws IOException { + output.serializeTraceId(Span.TRACE_ID, span.getTraceId(), context); + output.serializeSpanId(Span.SPAN_ID, span.getSpanId(), context); + + byte[] traceStateUtf8 = context.getData(byte[].class); + output.serializeString(Span.TRACE_STATE, traceStateUtf8); + String parentSpanId = + span.getParentSpanContext().isValid() ? span.getParentSpanContext().getSpanId() : null; + output.serializeSpanId(Span.PARENT_SPAN_ID, parentSpanId, context); + + output.serializeStringWithContext(Span.NAME, span.getName(), context); + output.serializeEnum(Span.KIND, toProtoSpanKind(span.getKind())); + + output.serializeFixed64(Span.START_TIME_UNIX_NANO, span.getStartEpochNanos()); + output.serializeFixed64(Span.END_TIME_UNIX_NANO, span.getEndEpochNanos()); + + output.serializeRepeatedMessageWithContext( + Span.ATTRIBUTES, + span.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + int droppedAttributesCount = span.getTotalAttributeCount() - span.getAttributes().size(); + output.serializeUInt32(Span.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + + output.serializeRepeatedMessageWithContext( + Span.EVENTS, span.getEvents(), SpanEventStatelessMarshaler.INSTANCE, context); + int droppedEventsCount = span.getTotalRecordedEvents() - span.getEvents().size(); + output.serializeUInt32(Span.DROPPED_EVENTS_COUNT, droppedEventsCount); + + output.serializeRepeatedMessageWithContext( + Span.LINKS, span.getLinks(), SpanLinkStatelessMarshaler.INSTANCE, context); + int droppedLinksCount = span.getTotalRecordedLinks() - span.getLinks().size(); + output.serializeUInt32(Span.DROPPED_LINKS_COUNT, droppedLinksCount); + + output.serializeMessageWithContext( + Span.STATUS, span.getStatus(), SpanStatusStatelessMarshaler.INSTANCE, context); + + output.serializeFixed32( + Span.FLAGS, + SpanFlags.withParentIsRemoteFlags( + span.getSpanContext().getTraceFlags(), span.getParentSpanContext().isRemote())); + } + + @Override + public int getBinarySerializedSize(SpanData span, MarshalerContext context) { + int size = 0; + size += MarshalerUtil.sizeTraceId(Span.TRACE_ID, span.getTraceId()); + size += MarshalerUtil.sizeSpanId(Span.SPAN_ID, span.getSpanId()); + + byte[] traceStateUtf8 = encodeSpanTraceState(span); + context.addData(traceStateUtf8); + + size += MarshalerUtil.sizeBytes(Span.TRACE_STATE, traceStateUtf8); + String parentSpanId = + span.getParentSpanContext().isValid() ? span.getParentSpanContext().getSpanId() : null; + size += MarshalerUtil.sizeSpanId(Span.PARENT_SPAN_ID, parentSpanId); + + size += StatelessMarshalerUtil.sizeStringWithContext(Span.NAME, span.getName(), context); + size += MarshalerUtil.sizeEnum(Span.KIND, toProtoSpanKind(span.getKind())); + + size += MarshalerUtil.sizeFixed64(Span.START_TIME_UNIX_NANO, span.getStartEpochNanos()); + size += MarshalerUtil.sizeFixed64(Span.END_TIME_UNIX_NANO, span.getEndEpochNanos()); + + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Span.ATTRIBUTES, + span.getAttributes(), + AttributeKeyValueStatelessMarshaler.INSTANCE, + context); + int droppedAttributesCount = span.getTotalAttributeCount() - span.getAttributes().size(); + size += MarshalerUtil.sizeUInt32(Span.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Span.EVENTS, span.getEvents(), SpanEventStatelessMarshaler.INSTANCE, context); + int droppedEventsCount = span.getTotalRecordedEvents() - span.getEvents().size(); + size += MarshalerUtil.sizeUInt32(Span.DROPPED_EVENTS_COUNT, droppedEventsCount); + + size += + StatelessMarshalerUtil.sizeRepeatedMessageWithContext( + Span.LINKS, span.getLinks(), SpanLinkStatelessMarshaler.INSTANCE, context); + int droppedLinksCount = span.getTotalRecordedLinks() - span.getLinks().size(); + size += MarshalerUtil.sizeUInt32(Span.DROPPED_LINKS_COUNT, droppedLinksCount); + + size += + StatelessMarshalerUtil.sizeMessageWithContext( + Span.STATUS, span.getStatus(), SpanStatusStatelessMarshaler.INSTANCE, context); + + size += + MarshalerUtil.sizeFixed32( + Span.FLAGS, + SpanFlags.withParentIsRemoteFlags( + span.getSpanContext().getTraceFlags(), span.getParentSpanContext().isRemote())); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusMarshaler.java index 0809e85c978..981bf481005 100644 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusMarshaler.java +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusMarshaler.java @@ -19,12 +19,7 @@ final class SpanStatusMarshaler extends MarshalerWithSize { private final byte[] descriptionUtf8; static SpanStatusMarshaler create(StatusData status) { - ProtoEnumInfo protoStatusCode = Status.StatusCode.STATUS_CODE_UNSET; - if (status.getStatusCode() == StatusCode.OK) { - protoStatusCode = Status.StatusCode.STATUS_CODE_OK; - } else if (status.getStatusCode() == StatusCode.ERROR) { - protoStatusCode = Status.StatusCode.STATUS_CODE_ERROR; - } + ProtoEnumInfo protoStatusCode = toProtoSpanStatus(status); byte[] description = MarshalerUtil.toBytes(status.getDescription()); return new SpanStatusMarshaler(protoStatusCode, description); } @@ -47,4 +42,14 @@ private static int computeSize(ProtoEnumInfo protoStatusCode, byte[] description size += MarshalerUtil.sizeEnum(Status.CODE, protoStatusCode); return size; } + + static ProtoEnumInfo toProtoSpanStatus(StatusData status) { + ProtoEnumInfo protoStatusCode = Status.StatusCode.STATUS_CODE_UNSET; + if (status.getStatusCode() == StatusCode.OK) { + protoStatusCode = Status.StatusCode.STATUS_CODE_OK; + } else if (status.getStatusCode() == StatusCode.ERROR) { + protoStatusCode = Status.StatusCode.STATUS_CODE_ERROR; + } + return protoStatusCode; + } } diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusStatelessMarshaler.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusStatelessMarshaler.java new file mode 100644 index 00000000000..0609c0e6829 --- /dev/null +++ b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/otlp/traces/SpanStatusStatelessMarshaler.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import static io.opentelemetry.exporter.internal.otlp.traces.SpanStatusMarshaler.toProtoSpanStatus; + +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.ProtoEnumInfo; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshalerUtil; +import io.opentelemetry.proto.trace.v1.internal.Status; +import io.opentelemetry.sdk.trace.data.StatusData; +import java.io.IOException; + +/** See {@link SpanStatusMarshaler}. */ +final class SpanStatusStatelessMarshaler implements StatelessMarshaler { + static final SpanStatusStatelessMarshaler INSTANCE = new SpanStatusStatelessMarshaler(); + + private SpanStatusStatelessMarshaler() {} + + @Override + public void writeTo(Serializer output, StatusData status, MarshalerContext context) + throws IOException { + ProtoEnumInfo protoStatusCode = toProtoSpanStatus(status); + + output.serializeStringWithContext(Status.MESSAGE, status.getDescription(), context); + output.serializeEnum(Status.CODE, protoStatusCode); + } + + @Override + public int getBinarySerializedSize(StatusData status, MarshalerContext context) { + ProtoEnumInfo protoStatusCode = toProtoSpanStatus(status); + + int size = 0; + size += + StatelessMarshalerUtil.sizeStringWithContext( + Status.MESSAGE, status.getDescription(), context); + size += MarshalerUtil.sizeEnum(Status.CODE, protoStatusCode); + + return size; + } +} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryInterceptor.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryInterceptor.java deleted file mode 100644 index a433b2f533c..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryInterceptor.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import okhttp3.Interceptor; -import okhttp3.Response; - -/** - * Retrier of OkHttp requests. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class RetryInterceptor implements Interceptor { - - private final RetryPolicy retryPolicy; - private final Function isRetryable; - private final Function isRetryableException; - private final Sleeper sleeper; - private final BoundedLongGenerator randomLong; - - /** Constructs a new retrier. */ - public RetryInterceptor(RetryPolicy retryPolicy, Function isRetryable) { - this( - retryPolicy, - isRetryable, - RetryInterceptor::isRetryableException, - TimeUnit.NANOSECONDS::sleep, - bound -> ThreadLocalRandom.current().nextLong(bound)); - } - - // Visible for testing - RetryInterceptor( - RetryPolicy retryPolicy, - Function isRetryable, - Function isRetryableException, - Sleeper sleeper, - BoundedLongGenerator randomLong) { - this.retryPolicy = retryPolicy; - this.isRetryable = isRetryable; - this.isRetryableException = isRetryableException; - this.sleeper = sleeper; - this.randomLong = randomLong; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Response response = null; - IOException exception = null; - int attempt = 0; - long nextBackoffNanos = retryPolicy.getInitialBackoff().toNanos(); - do { - if (attempt > 0) { - // Compute and sleep for backoff - // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff - long upperBoundNanos = Math.min(nextBackoffNanos, retryPolicy.getMaxBackoff().toNanos()); - long backoffNanos = randomLong.get(upperBoundNanos); - nextBackoffNanos = (long) (nextBackoffNanos * retryPolicy.getBackoffMultiplier()); - try { - sleeper.sleep(backoffNanos); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - break; // Break out and return response or throw - } - // Close response from previous attempt - if (response != null) { - response.close(); - } - } - - attempt++; - try { - response = chain.proceed(chain.request()); - } catch (IOException e) { - exception = e; - } - if (response != null && !Boolean.TRUE.equals(isRetryable.apply(response))) { - return response; - } - if (exception != null && !Boolean.TRUE.equals(isRetryableException.apply(exception))) { - throw exception; - } - } while (attempt < retryPolicy.getMaxAttempts()); - - if (response != null) { - return response; - } - throw exception; - } - - // Visible for testing - static boolean isRetryableException(IOException e) { - if (!(e instanceof SocketTimeoutException)) { - return false; - } - String message = e.getMessage(); - // Connect timeouts can produce SocketTimeoutExceptions with no message, or with "connect timed - // out" - return message == null || message.toLowerCase().contains("connect timed out"); - } - - // Visible for testing - interface BoundedLongGenerator { - long get(long bound); - } - - // Visible for testing - interface Sleeper { - void sleep(long delayNanos) throws InterruptedException; - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryPolicy.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryPolicy.java deleted file mode 100644 index 77f05712c68..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryPolicy.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import com.google.auto.value.AutoValue; -import java.time.Duration; - -/** - * This class is internal and is hence not for public use. Its APIs are unstable and can change at - * any time. - */ -@AutoValue -public abstract class RetryPolicy { - - private static final RetryPolicy DEFAULT = new RetryPolicyBuilder().build(); - - RetryPolicy() {} - - /** Return the default {@link RetryPolicy}. */ - public static RetryPolicy getDefault() { - return DEFAULT; - } - - /** Returns a new {@link RetryPolicyBuilder} to construct a {@link RetryPolicy}. */ - public static RetryPolicyBuilder builder() { - return new RetryPolicyBuilder(); - } - - /** Returns the max number of attempts, including the original request. */ - public abstract int getMaxAttempts(); - - /** Returns the initial backoff. */ - public abstract Duration getInitialBackoff(); - - /** Returns the max backoff. */ - public abstract Duration getMaxBackoff(); - - /** Returns the backoff multiplier. */ - public abstract double getBackoffMultiplier(); - - static RetryPolicy create( - int maxAttempts, Duration initialBackoff, Duration maxBackoff, double backoffMultiplier) { - return new AutoValue_RetryPolicy(maxAttempts, initialBackoff, maxBackoff, backoffMultiplier); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryPolicyBuilder.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryPolicyBuilder.java deleted file mode 100644 index 66bd84fa040..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryPolicyBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import java.time.Duration; - -/** - * This class is internal and is hence not for public use. Its APIs are unstable and can change at - * any time. - */ -public final class RetryPolicyBuilder { - - private static final int DEFAULT_MAX_ATTEMPTS = 5; - private static final Duration DEFAULT_INITIAL_BACKOFF = Duration.ofSeconds(1); - private static final Duration DEFAULT_MAX_BACKOFF = Duration.ofSeconds(5); - private static final double DEFAULT_BACKOFF_MULTIPLIER = 1.5; - - private int maxAttempts = DEFAULT_MAX_ATTEMPTS; - private Duration initialBackoff = DEFAULT_INITIAL_BACKOFF; - private Duration maxBackoff = DEFAULT_MAX_BACKOFF; - private double backoffMultiplier = DEFAULT_BACKOFF_MULTIPLIER; - - RetryPolicyBuilder() {} - - /** - * Set the maximum number of attempts, including the original request. Must be greater than 1 and - * less than 6. - */ - public RetryPolicyBuilder setMaxAttempts(int maxAttempts) { - checkArgument( - maxAttempts > 1 && maxAttempts < 6, "maxAttempts must be greater than 1 and less than 6"); - this.maxAttempts = maxAttempts; - return this; - } - - /** Set the initial backoff. Must be greater than 0. */ - public RetryPolicyBuilder setInitialBackoff(Duration initialBackoff) { - requireNonNull(initialBackoff, "initialBackoff"); - checkArgument(initialBackoff.toNanos() > 0, "initialBackoff must be greater than 0"); - this.initialBackoff = initialBackoff; - return this; - } - - /** Set the maximum backoff. Must be greater than 0. */ - public RetryPolicyBuilder setMaxBackoff(Duration maxBackoff) { - requireNonNull(maxBackoff, "maxBackoff"); - checkArgument(maxBackoff.toNanos() > 0, "maxBackoff must be greater than 0"); - this.maxBackoff = maxBackoff; - return this; - } - - /** Set the backoff multiplier. Must be greater than 0.0. */ - public RetryPolicyBuilder setBackoffMultiplier(double backoffMultiplier) { - checkArgument(backoffMultiplier > 0, "backoffMultiplier must be greater than 0"); - this.backoffMultiplier = backoffMultiplier; - return this; - } - - /** Build and return a {@link RetryPolicy} with the values of this builder. */ - public RetryPolicy build() { - return RetryPolicy.create(maxAttempts, initialBackoff, maxBackoff, backoffMultiplier); - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryUtil.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryUtil.java deleted file mode 100644 index f6489e5f8be..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/RetryUtil.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.grpc.GrpcStatusUtil; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder; -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -/** - * This class is internal and is hence not for public use. Its APIs are unstable and can change at - * any time. - */ -public class RetryUtil { - - private static final Set RETRYABLE_GRPC_STATUS_CODES; - private static final Set RETRYABLE_HTTP_STATUS_CODES = - Collections.unmodifiableSet(new HashSet<>(Arrays.asList(429, 502, 503, 504))); - - static { - Set retryableGrpcStatusCodes = new HashSet<>(); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_CANCELLED); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_DEADLINE_EXCEEDED); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_RESOURCE_EXHAUSTED); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_ABORTED); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_OUT_OF_RANGE); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_UNAVAILABLE); - retryableGrpcStatusCodes.add(GrpcStatusUtil.GRPC_STATUS_DATA_LOSS); - RETRYABLE_GRPC_STATUS_CODES = Collections.unmodifiableSet(retryableGrpcStatusCodes); - } - - private RetryUtil() {} - - /** Returns the retryable gRPC status codes. */ - public static Set retryableGrpcStatusCodes() { - return RETRYABLE_GRPC_STATUS_CODES; - } - - /** Returns the retryable HTTP status codes. */ - public static Set retryableHttpResponseCodes() { - return RETRYABLE_HTTP_STATUS_CODES; - } - - /** - * Reflectively access a {@link DefaultGrpcExporterBuilder}, {@link OkHttpGrpcExporterBuilder}, or - * {@link OkHttpExporterBuilder} instance in field called "delegate" of the instance, and set the - * {@link RetryPolicy}. - * - * @throws IllegalArgumentException if the instance does not contain a field called "delegate" of - * type {@link DefaultGrpcExporterBuilder} - */ - public static void setRetryPolicyOnDelegate(Object instance, RetryPolicy retryPolicy) { - try { - Field field = instance.getClass().getDeclaredField("delegate"); - field.setAccessible(true); - Object value = field.get(instance); - if (value instanceof DefaultGrpcExporterBuilder) { - ((DefaultGrpcExporterBuilder) value).setRetryPolicy(retryPolicy); - } else if (value instanceof OkHttpGrpcExporterBuilder) { - ((OkHttpGrpcExporterBuilder) value).setRetryPolicy(retryPolicy); - } else if (value instanceof OkHttpExporterBuilder) { - ((OkHttpExporterBuilder) value).setRetryPolicy(retryPolicy); - } else { - throw new IllegalArgumentException( - "delegate field is not type DefaultGrpcExporterBuilder or OkHttpGrpcExporterBuilder"); - } - } catch (NoSuchFieldException | IllegalAccessException e) { - throw new IllegalArgumentException("Unable to access delegate reflectively.", e); - } - } -} diff --git a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/package-info.java b/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/package-info.java deleted file mode 100644 index 7564da39e60..00000000000 --- a/exporters/otlp/common/src/main/java/io/opentelemetry/exporter/internal/retry/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** Logic for retrying of export requests. */ -@ParametersAreNonnullByDefault -package io.opentelemetry.exporter.internal.retry; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/grpc/GrpcStatusUtilTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/grpc/GrpcStatusUtilTest.java deleted file mode 100644 index 2537540e3dc..00000000000 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/grpc/GrpcStatusUtilTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.protobuf.Any; -import com.google.protobuf.ByteString; -import com.google.rpc.Status; -import java.io.IOException; -import org.junit.jupiter.api.Test; - -class GrpcStatusUtilTest { - - @Test - void parseMessage() throws Exception { - assertThat( - GrpcStatusUtil.getStatusMessage( - Status.newBuilder().setMessage("test").build().toByteArray())) - .isEqualTo("test"); - assertThat( - GrpcStatusUtil.getStatusMessage( - Status.newBuilder().setCode(2).setMessage("test2").build().toByteArray())) - .isEqualTo("test2"); - assertThat( - GrpcStatusUtil.getStatusMessage( - Status.newBuilder() - .setCode(2) - .setMessage("test3") - .addDetails(Any.newBuilder().setValue(ByteString.copyFromUtf8("any")).build()) - .build() - .toByteArray())) - .isEqualTo("test3"); - assertThat( - GrpcStatusUtil.getStatusMessage( - Status.newBuilder() - .setCode(2) - .addDetails(Any.newBuilder().setValue(ByteString.copyFromUtf8("any")).build()) - .build() - .toByteArray())) - .isEmpty(); - assertThat(GrpcStatusUtil.getStatusMessage(Status.getDefaultInstance().toByteArray())) - .isEmpty(); - assertThatThrownBy(() -> GrpcStatusUtil.getStatusMessage(new byte[] {0, 1, 3, 0})) - .isInstanceOf(IOException.class); - } -} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/grpc/ManagedChannelUtilTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/grpc/ManagedChannelUtilTest.java deleted file mode 100644 index 2b950c3dadd..00000000000 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/grpc/ManagedChannelUtilTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.grpc; - -import static org.assertj.core.api.Assertions.assertThatCode; - -import com.fasterxml.jackson.databind.ObjectMapper; -import io.grpc.ManagedChannelBuilder; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.util.Map; -import org.junit.jupiter.api.Test; -import org.skyscreamer.jsonassert.JSONAssert; - -class ManagedChannelUtilTest { - - @Test - void toServiceConfig() throws Exception { - // Validate that the map matches the protobuf to JSON translation of the - // grpc.service_config.ServiceConfig protobuf definition described at: - // https://github.com/grpc/grpc/blob/master/doc/service_config.md - Map serviceConfig = - ManagedChannelUtil.toServiceConfig( - "opentelemetry.proto.MyService", RetryPolicy.getDefault()); - String expectedServiceConfig = - "{\n" - + " \"methodConfig\": [{\n" - + " \"retryPolicy\": {\n" - + " \"backoffMultiplier\": 1.5,\n" - + " \"maxAttempts\": 5.0,\n" - + " \"initialBackoff\": \"1.0s\",\n" - + " \"retryableStatusCodes\": [1.0, 4.0, 8.0, 10.0, 11.0, 14.0, 15.0],\n" - + " \"maxBackoff\": \"5.0s\"\n" - + " },\n" - + " \"name\": [{\n" - + " \"service\": \"opentelemetry.proto.MyService\"\n" - + " }]\n" - + " }]\n" - + "}"; - JSONAssert.assertEquals( - expectedServiceConfig, new ObjectMapper().writeValueAsString(serviceConfig), false); - - // Validate that the map format does not throw when passed to managed channel builder. - // Any type mismatch will throw. - ManagedChannelBuilder builder = ManagedChannelBuilder.forTarget("localhost"); - assertThatCode(() -> builder.defaultServiceConfig(serviceConfig)).doesNotThrowAnyException(); - } -} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueTest.java new file mode 100644 index 00000000000..220b3845352 --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/AttributeKeyValueTest.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.AttributeType; +import io.opentelemetry.api.common.Attributes; +import java.util.Collections; +import java.util.List; +import nl.jqno.equalsverifier.EqualsVerifier; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +class AttributeKeyValueTest { + + @Test + void equalsVerifier() { + EqualsVerifier.forClass(AttributeKeyValue.class).verify(); + } + + @Test + void ofEmpty() { + assertThat(AttributeKeyValue.of(Attributes.empty())).isEmpty(); + } + + @Test + void ofOne() { + AttributeKeyValue input = AttributeKeyValue.of(AttributeKey.stringKey("foo"), "bar"); + Attributes attributes = Attributes.of(input.getAttributeKey(), input.getValue()); + List> list = AttributeKeyValue.of(attributes); + Assertions.assertThat(list).hasSize(1); + assertThat(list.get(0)).isEqualTo(input); + } + + @Test + void ofList() { + AttributeKeyValue> input = + AttributeKeyValue.of(AttributeKey.longArrayKey("foo"), Collections.emptyList()); + Attributes attributes = Attributes.of(input.getAttributeKey(), input.getValue()); + List> list = AttributeKeyValue.of(attributes); + Assertions.assertThat(list).hasSize(1); + assertThat(list.get(0).getAttributeKey().getType()).isEqualTo(AttributeType.LONG_ARRAY); + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/EntityRefMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/EntityRefMarshalerTest.java new file mode 100644 index 00000000000..fcf9907dfb1 --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/EntityRefMarshalerTest.java @@ -0,0 +1,86 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.proto.common.v1.EntityRef; +import io.opentelemetry.sdk.resources.internal.Entity; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class EntityRefMarshalerTest { + @Test + void toEntityRefs() { + Entity e = + Entity.builder("test", Attributes.builder().put("id.key", "id.value").build()) + .setSchemaUrl("test-url") + .setDescription(Attributes.builder().put("desc.key", "desc.value").build()) + .build(); + EntityRef proto = parse(EntityRef.getDefaultInstance(), EntityRefMarshaler.createForEntity(e)); + assertThat(proto.getType()).isEqualTo("test"); + assertThat(proto.getSchemaUrl()).isEqualTo("test-url"); + assertThat(proto.getIdKeysList()).containsExactly("id.key"); + assertThat(proto.getDescriptionKeysList()).containsExactly("desc.key"); + } + + @SuppressWarnings("unchecked") + private static T parse(T prototype, Marshaler marshaler) { + byte[] serialized = toByteArray(marshaler); + T result; + try { + result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + // Our marshaler should produce the exact same length of serialized output (for example, field + // default values are not outputted), so we check that here. The output itself may have slightly + // different ordering, mostly due to the way we don't output oneof values in field order all the + // time. If the lengths are equal and the resulting protos are equal, the marshaling is + // guaranteed to be valid. + assertThat(result.getSerializedSize()).isEqualTo(serialized.length); + + // Compare JSON + String json = toJson(marshaler); + Message.Builder builder = prototype.newBuilderForType(); + try { + JsonFormat.parser().merge(json, builder); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + assertThat(builder.build()).isEqualTo(result); + + return result; + } + + private static byte[] toByteArray(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return bos.toByteArray(); + } + + private static String toJson(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new String(bos.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshalerTest.java new file mode 100644 index 00000000000..1802ee41556 --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/ResourceMarshalerTest.java @@ -0,0 +1,105 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.proto.resource.v1.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class ResourceMarshalerTest { + + @Test + void marshalResourceWithEntities() { + Entity entity = + Entity.builder("process", Attributes.of(stringKey("process.pid"), "1234")) + .setDescription(Attributes.of(stringKey("process.executable.name"), "java")) + .setSchemaUrl("http://process.schema") + .build(); + + ResourceBuilder builder = + io.opentelemetry.sdk.resources.Resource.builder().put("service.name", "my-service"); + EntityUtil.addEntity(builder, entity); + EntityUtil.addEntity( + builder, Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build()); + io.opentelemetry.sdk.resources.Resource resourceWithEntity = builder.build(); + + Resource proto = + parse(Resource.getDefaultInstance(), ResourceMarshaler.create(resourceWithEntity)); + + assertThat(proto.getAttributesList().stream().map(a -> a.getKey())) + .containsExactlyInAnyOrder( + "service.name", "process.pid", "process.executable.name", "host.id"); + + assertThat(proto.getEntityRefsList()).hasSize(2); + assertThat(proto.getEntityRefs(0).getType()).isEqualTo("process"); + assertThat(proto.getEntityRefs(0).getSchemaUrl()).isEqualTo("http://process.schema"); + assertThat(proto.getEntityRefs(0).getIdKeysList()).containsExactly("process.pid"); + assertThat(proto.getEntityRefs(0).getDescriptionKeysList()) + .containsExactly("process.executable.name"); + assertThat(proto.getEntityRefs(1).getType()).isEqualTo("host"); + assertThat(proto.getEntityRefs(1).getSchemaUrl()).isEmpty(); + assertThat(proto.getEntityRefs(1).getIdKeysList()).containsExactly("host.id"); + assertThat(proto.getEntityRefs(1).getDescriptionKeysList()).isEmpty(); + } + + @SuppressWarnings("unchecked") + private static T parse(T prototype, Marshaler marshaler) { + byte[] serialized = toByteArray(marshaler); + T result; + try { + result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + assertThat(result.getSerializedSize()).isEqualTo(serialized.length); + + // Compare JSON + String json = toJson(marshaler); + Message.Builder protoBuilder = prototype.newBuilderForType(); + try { + JsonFormat.parser().merge(json, protoBuilder); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + assertThat(protoBuilder.build()).isEqualTo(result); + + return result; + } + + private static byte[] toByteArray(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return bos.toByteArray(); + } + + private static String toJson(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new String(bos.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/ValueMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/ValueMarshalerTest.java new file mode 100644 index 00000000000..66e1b36f178 --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/ValueMarshalerTest.java @@ -0,0 +1,215 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp; + +import static io.opentelemetry.api.common.Value.of; +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.ArrayValue; +import io.opentelemetry.proto.common.v1.KeyValueList; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@SuppressWarnings("BadImport") +class ValueMarshalerTest { + + @ParameterizedTest + @MethodSource("serializeAnyValueArgs") + void anyValueString_StatefulMarshaler(Value value, AnyValue expectedSerializedValue) { + MarshalerWithSize marshaler = AnyValueMarshaler.create(value); + AnyValue serializedValue = parse(AnyValue.getDefaultInstance(), marshaler); + assertThat(serializedValue).isEqualTo(expectedSerializedValue); + } + + @ParameterizedTest + @MethodSource("serializeAnyValueArgs") + void anyValueString_StatelessMarshaler(Value value, AnyValue expectedSerializedValue) { + Marshaler marshaler = createMarshaler(AnyValueStatelessMarshaler.INSTANCE, value); + AnyValue serializedValue = parse(AnyValue.getDefaultInstance(), marshaler); + assertThat(serializedValue).isEqualTo(expectedSerializedValue); + } + + private static Stream serializeAnyValueArgs() { + return Stream.of( + // primitives + arguments(of("str"), AnyValue.newBuilder().setStringValue("str").build()), + arguments(of(true), AnyValue.newBuilder().setBoolValue(true).build()), + arguments(of(1), AnyValue.newBuilder().setIntValue(1).build()), + arguments(of(1.1), AnyValue.newBuilder().setDoubleValue(1.1).build()), + // heterogeneous array + arguments( + of(of("str"), of(true), of(1), of(1.1)), + AnyValue.newBuilder() + .setArrayValue( + ArrayValue.newBuilder() + .addValues(AnyValue.newBuilder().setStringValue("str").build()) + .addValues(AnyValue.newBuilder().setBoolValue(true).build()) + .addValues(AnyValue.newBuilder().setIntValue(1).build()) + .addValues(AnyValue.newBuilder().setDoubleValue(1.1).build()) + .build()) + .build()), + // map + arguments( + of(KeyValue.of("key1", of("val1")), KeyValue.of("key2", of(2))), + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("key1") + .setValue(AnyValue.newBuilder().setStringValue("val1").build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("key2") + .setValue(AnyValue.newBuilder().setIntValue(2).build()) + .build()) + .build()) + .build()), + // map of maps + arguments( + of( + Collections.singletonMap( + "child", of(Collections.singletonMap("grandchild", of("str"))))), + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("child") + .setValue( + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + io.opentelemetry.proto.common.v1.KeyValue + .newBuilder() + .setKey("grandchild") + .setValue( + AnyValue.newBuilder() + .setStringValue("str") + .build()) + .build()) + .build()) + .build()) + .build()) + .build()) + .build()), + // bytes + arguments( + of("hello world".getBytes(StandardCharsets.UTF_8)), + AnyValue.newBuilder() + .setBytesValue(ByteString.copyFrom("hello world".getBytes(StandardCharsets.UTF_8))) + .build()), + // empty values + arguments(of(""), AnyValue.newBuilder().setStringValue("").build()), + arguments(of(false), AnyValue.newBuilder().setBoolValue(false).build()), + arguments(of(0), AnyValue.newBuilder().setIntValue(0).build()), + arguments(of(0.0), AnyValue.newBuilder().setDoubleValue(0.0).build()), + arguments( + Value.of(Collections.emptyList()), + AnyValue.newBuilder().setArrayValue(ArrayValue.newBuilder().build()).build()), + arguments( + of(Collections.emptyMap()), + AnyValue.newBuilder().setKvlistValue(KeyValueList.newBuilder().build()).build()), + arguments(of(new byte[0]), AnyValue.newBuilder().setBytesValue(ByteString.EMPTY).build()) + // TODO add test for true empty value + // after https://github.com/open-telemetry/opentelemetry-java/pull/7973 + // arguments(Value.empty(), AnyValue.newBuilder().build()) + ); + } + + @SuppressWarnings("unchecked") + private static T parse(T prototype, Marshaler marshaler) { + byte[] serialized = toByteArray(marshaler); + T result; + try { + result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + // Our marshaler should produce the exact same length of serialized output (for example, field + // default values are not outputted), so we check that here. The output itself may have slightly + // different ordering, mostly due to the way we don't output oneof values in field order all the + // tieme. If the lengths are equal and the resulting protos are equal, the marshaling is + // guaranteed to be valid. + assertThat(result.getSerializedSize()).isEqualTo(serialized.length); + + // We don't compare JSON strings due to some differences (particularly serializing enums as + // numbers instead of names). This may improve in the future but what matters is what we produce + // can be parsed. + String json = toJson(marshaler); + Message.Builder builder = prototype.newBuilderForType(); + try { + JsonFormat.parser().merge(json, builder); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + + assertThat(builder.build()).isEqualTo(result); + + return result; + } + + private static byte[] toByteArray(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return bos.toByteArray(); + } + + private static String toJson(Marshaler marshaler) { + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new String(bos.toByteArray(), StandardCharsets.UTF_8); + } + + private static Marshaler createMarshaler(StatelessMarshaler marshaler, T data) { + return new Marshaler() { + private final MarshalerContext context = new MarshalerContext(); + private final int size = marshaler.getBinarySerializedSize(data, context); + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + context.resetReadIndex(); + marshaler.writeTo(output, data, context); + } + }; + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerTest.java index 8051aab239e..41cbb7e48f9 100644 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerTest.java +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerTest.java @@ -13,13 +13,17 @@ import com.google.protobuf.util.JsonFormat; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.OtelEncodingUtils; +import io.opentelemetry.api.impl.Base16EncodingUtils; +import io.opentelemetry.api.logs.Severity; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; import io.opentelemetry.proto.common.v1.AnyValue; import io.opentelemetry.proto.common.v1.InstrumentationScope; import io.opentelemetry.proto.common.v1.KeyValue; @@ -27,9 +31,9 @@ import io.opentelemetry.proto.logs.v1.ResourceLogs; import io.opentelemetry.proto.logs.v1.ScopeLogs; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; +import io.opentelemetry.sdk.logs.data.LogRecordData; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UncheckedIOException; @@ -39,6 +43,8 @@ import java.util.Locale; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; class LogsRequestMarshalerTest { private static final byte[] TRACE_ID_BYTES = @@ -53,9 +59,15 @@ void toProtoResourceLogs() { ResourceLogsMarshaler[] resourceLogsMarshalers = ResourceLogsMarshaler.create( Collections.singleton( - LogDataBuilder.create( - Resource.builder().put("one", 1).setSchemaUrl("http://url").build(), - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) + TestLogRecordData.builder() + .setResource( + Resource.builder().put("one", 1).setSchemaUrl("http://url").build()) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("testLib") + .setVersion("1.0") + .setSchemaUrl("http://url") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build()) .setBody(BODY) .setSeverity(Severity.INFO) .setSeverityText("INFO") @@ -63,7 +75,9 @@ void toProtoResourceLogs() { SpanContext.create( TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) .setAttributes(Attributes.of(AttributeKey.booleanKey("key"), true)) - .setEpoch(12345, TimeUnit.NANOSECONDS) + .setTotalAttributeCount(2) + .setTimestamp(12345, TimeUnit.NANOSECONDS) + .setObservedTimestamp(6789, TimeUnit.NANOSECONDS) .build())); assertThat(resourceLogsMarshalers).hasSize(1); @@ -75,18 +89,30 @@ void toProtoResourceLogs() { ScopeLogs instrumentationLibraryLogs = onlyResourceLogs.getScopeLogs(0); assertThat(instrumentationLibraryLogs.getSchemaUrl()).isEqualTo("http://url"); assertThat(instrumentationLibraryLogs.getScope()) - .isEqualTo(InstrumentationScope.newBuilder().setName("testLib").setVersion("1.0").build()); + .isEqualTo( + InstrumentationScope.newBuilder() + .setName("testLib") + .setVersion("1.0") + .addAttributes( + KeyValue.newBuilder() + .setKey("key") + .setValue(AnyValue.newBuilder().setStringValue("value").build()) + .build()) + .build()); } - @Test - void toProtoLogRecord() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoLogRecord(MarshalerSource marshalerSource) { LogRecord logRecord = parse( LogRecord.getDefaultInstance(), - LogMarshaler.create( - LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) + marshalerSource.create( + TestLogRecordData.builder() + .setResource( + Resource.create(Attributes.builder().put("testKey", "testValue").build())) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation").setVersion("1").build()) .setBody(BODY) .setSeverity(Severity.INFO) .setSeverityText("INFO") @@ -94,7 +120,9 @@ void toProtoLogRecord() { SpanContext.create( TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) .setAttributes(Attributes.of(AttributeKey.booleanKey("key"), true)) - .setEpoch(12345, TimeUnit.NANOSECONDS) + .setTotalAttributeCount(2) + .setTimestamp(12345, TimeUnit.NANOSECONDS) + .setObservedTimestamp(6789, TimeUnit.NANOSECONDS) .build())); assertThat(logRecord.getTraceId().toByteArray()).isEqualTo(TRACE_ID_BYTES); @@ -107,19 +135,25 @@ void toProtoLogRecord() { .setKey("key") .setValue(AnyValue.newBuilder().setBoolValue(true).build()) .build()); + assertThat(logRecord.getDroppedAttributesCount()).isEqualTo(1); assertThat(logRecord.getTimeUnixNano()).isEqualTo(12345); + assertThat(logRecord.getObservedTimeUnixNano()).isEqualTo(6789); } - @Test - void toProtoLogRecord_MinimalFields() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoLogRecord_MinimalFields(MarshalerSource marshalerSource) { LogRecord logRecord = parse( LogRecord.getDefaultInstance(), - LogMarshaler.create( - LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setEpoch(12345, TimeUnit.NANOSECONDS) + marshalerSource.create( + TestLogRecordData.builder() + .setResource( + Resource.create(Attributes.builder().put("testKey", "testValue").build())) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation").setVersion("1").build()) + .setTimestamp(12345, TimeUnit.NANOSECONDS) + .setObservedTimestamp(6789, TimeUnit.NANOSECONDS) .build())); assertThat(logRecord.getTraceId()).isEmpty(); @@ -127,9 +161,11 @@ void toProtoLogRecord_MinimalFields() { assertThat(logRecord.getSeverityText()).isBlank(); assertThat(logRecord.getSeverityNumber().getNumber()) .isEqualTo(Severity.UNDEFINED_SEVERITY_NUMBER.getSeverityNumber()); - assertThat(logRecord.getBody()).isEqualTo(AnyValue.newBuilder().setStringValue("").build()); + assertThat(logRecord.getBody()).isEqualTo(AnyValue.newBuilder().build()); assertThat(logRecord.getAttributesList()).isEmpty(); + assertThat(logRecord.getDroppedAttributesCount()).isZero(); assertThat(logRecord.getTimeUnixNano()).isEqualTo(12345); + assertThat(logRecord.getObservedTimeUnixNano()).isEqualTo(6789); } @SuppressWarnings("unchecked") @@ -188,7 +224,7 @@ private static void fixSpanJsonIds(LogRecord.Builder span) { private static ByteString toHex(ByteString hexReadAsBase64) { String hex = Base64.getEncoder().encodeToString(hexReadAsBase64.toByteArray()).toLowerCase(Locale.ROOT); - return ByteString.copyFrom(OtelEncodingUtils.bytesFromBase16(hex, hex.length())); + return ByteString.copyFrom(Base16EncodingUtils.bytesFromBase16(hex, hex.length())); } private static byte[] toByteArray(Marshaler marshaler) { @@ -211,4 +247,39 @@ private static String toJson(Marshaler marshaler) { } return new String(bos.toByteArray(), StandardCharsets.UTF_8); } + + private static Marshaler createMarshaler(StatelessMarshaler marshaler, T data) { + return new Marshaler() { + private final MarshalerContext context = new MarshalerContext(); + private final int size = marshaler.getBinarySerializedSize(data, context); + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + context.resetReadIndex(); + marshaler.writeTo(output, data, context); + } + }; + } + + private enum MarshalerSource { + MARSHALER { + @Override + Marshaler create(LogRecordData logData) { + return LogMarshaler.create(logData); + } + }, + LOW_ALLOCATION_MARSHALER { + @Override + Marshaler create(LogRecordData logData) { + return createMarshaler(LogStatelessMarshaler.INSTANCE, logData); + } + }; + + abstract Marshaler create(LogRecordData logData); + } } diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LowAllocationLogRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LowAllocationLogRequestMarshalerTest.java new file mode 100644 index 00000000000..fe2bed86f5e --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/logs/LowAllocationLogRequestMarshalerTest.java @@ -0,0 +1,157 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class LowAllocationLogRequestMarshalerTest { + + private static final AttributeKey KEY_BOOL = AttributeKey.booleanKey("key_bool"); + private static final AttributeKey KEY_STRING = AttributeKey.stringKey("key_string"); + private static final AttributeKey KEY_INT = AttributeKey.longKey("key_int"); + private static final AttributeKey KEY_DOUBLE = AttributeKey.doubleKey("key_double"); + private static final AttributeKey> KEY_STRING_ARRAY = + AttributeKey.stringArrayKey("key_string_array"); + private static final AttributeKey> KEY_LONG_ARRAY = + AttributeKey.longArrayKey("key_long_array"); + private static final AttributeKey> KEY_DOUBLE_ARRAY = + AttributeKey.doubleArrayKey("key_double_array"); + private static final AttributeKey> KEY_BOOLEAN_ARRAY = + AttributeKey.booleanArrayKey("key_boolean_array"); + private static final AttributeKey> KEY_BYTES = AttributeKey.valueKey("key_bytes"); + private static final AttributeKey> KEY_MAP = AttributeKey.valueKey("key_map"); + private static final AttributeKey> KEY_HETEROGENEOUS_ARRAY = + AttributeKey.valueKey("key_heterogeneous_array"); + private static final AttributeKey> KEY_EMPTY = AttributeKey.valueKey("key_empty"); + private static final String BODY = "Hello world from this log..."; + + private static final Resource RESOURCE = + Resource.create( + Attributes.builder() + .put(KEY_BOOL, true) + .put(KEY_STRING, "string") + .put(KEY_INT, 100L) + .put(KEY_DOUBLE, 100.3) + .put(KEY_STRING_ARRAY, Arrays.asList("string", "string")) + .put(KEY_LONG_ARRAY, Arrays.asList(12L, 23L)) + .put(KEY_DOUBLE_ARRAY, Arrays.asList(12.3, 23.1)) + .put(KEY_BOOLEAN_ARRAY, Arrays.asList(true, false)) + .put(KEY_BYTES, Value.of(new byte[] {1, 2, 3})) + .put(KEY_MAP, Value.of(KeyValue.of("nested", Value.of("value")))) + .put(KEY_HETEROGENEOUS_ARRAY, Value.of(Value.of("string"), Value.of(123L))) + .put(KEY_EMPTY, Value.empty()) + .build()); + + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.create("name"); + private static final String TRACE_ID = "7b2e170db4df2d593ddb4ddf2ddf2d59"; + private static final String SPAN_ID = "170d3ddb4d23e81f"; + // Use a trace flags value with the high bit set (0x80) so the relative comparisons below catch + // sign extension of the byte flags into the OTLP fixed32 field. With a low value like 0x01 the + // sign-extension bug would be hidden. + private static final SpanContext SPAN_CONTEXT = + SpanContext.create( + TRACE_ID, SPAN_ID, TraceFlags.fromByte((byte) 0x80), TraceState.getDefault()); + + private final List logRecordDataList = createLogRecordDataList(); + + private static List createLogRecordDataList() { + List logRecordDataList = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + logRecordDataList.add(createLogRecordData()); + } + return logRecordDataList; + } + + private static LogRecordData createLogRecordData() { + return TestLogRecordData.builder() + .setResource(RESOURCE) + .setInstrumentationScopeInfo(INSTRUMENTATION_SCOPE_INFO) + .setBody(BODY) + .setSeverity(Severity.INFO) + .setSeverityText("INFO") + .setSpanContext(SPAN_CONTEXT) + .setAttributes( + Attributes.builder() + .put(KEY_BOOL, true) + .put(KEY_STRING, "string") + .put(KEY_INT, 100L) + .put(KEY_DOUBLE, 100.3) + .build()) + .setTotalAttributeCount(2) + .setTimestamp(12345, TimeUnit.NANOSECONDS) + .setObservedTimestamp(6789, TimeUnit.NANOSECONDS) + .build(); + } + + @Test + void validateOutput() throws Exception { + byte[] result; + { + LogsRequestMarshaler requestMarshaler = LogsRequestMarshaler.create(logRecordDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(customOutput); + result = customOutput.toByteArray(); + } + + byte[] lowAllocationResult; + { + LowAllocationLogsRequestMarshaler requestMarshaler = new LowAllocationLogsRequestMarshaler(); + requestMarshaler.initialize(logRecordDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(customOutput); + lowAllocationResult = customOutput.toByteArray(); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } + + @Test + void validateJsonOutput() throws Exception { + String result; + { + LogsRequestMarshaler requestMarshaler = LogsRequestMarshaler.create(logRecordDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeJsonTo(customOutput); + result = new String(customOutput.toByteArray(), StandardCharsets.UTF_8); + } + + String lowAllocationResult; + { + LowAllocationLogsRequestMarshaler requestMarshaler = new LowAllocationLogsRequestMarshaler(); + requestMarshaler.initialize(logRecordDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeJsonTo(customOutput); + lowAllocationResult = new String(customOutput.toByteArray(), StandardCharsets.UTF_8); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java new file mode 100644 index 00000000000..dfb20b9723b --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/LowAllocationMetricsRequestMarshalerTest.java @@ -0,0 +1,404 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.metrics; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.SummaryData; +import io.opentelemetry.sdk.metrics.data.SummaryPointData; +import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.junit.jupiter.params.support.ParameterDeclarations; + +class LowAllocationMetricsRequestMarshalerTest { + + @ParameterizedTest + @ArgumentsSource(MetricsProvider.class) + void validateOutput(Collection metrics) throws Exception { + byte[] result; + { + MetricsRequestMarshaler requestMarshaler = MetricsRequestMarshaler.create(metrics); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(customOutput); + result = customOutput.toByteArray(); + } + + byte[] lowAllocationResult; + { + LowAllocationMetricsRequestMarshaler requestMarshaler = + new LowAllocationMetricsRequestMarshaler(); + requestMarshaler.initialize(metrics); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(customOutput); + lowAllocationResult = customOutput.toByteArray(); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } + + @ParameterizedTest + @ArgumentsSource(MetricsProvider.class) + void validateJsonOutput(Collection metrics) throws Exception { + String result; + { + MetricsRequestMarshaler requestMarshaler = MetricsRequestMarshaler.create(metrics); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeJsonTo(customOutput); + result = new String(customOutput.toByteArray(), StandardCharsets.UTF_8); + } + + String lowAllocationResult; + { + LowAllocationMetricsRequestMarshaler requestMarshaler = + new LowAllocationMetricsRequestMarshaler(); + requestMarshaler.initialize(metrics); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeJsonTo(customOutput); + lowAllocationResult = new String(customOutput.toByteArray(), StandardCharsets.UTF_8); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } + + @ParameterizedTest + @ArgumentsSource(ExemplarProvider.class) + void validateExemplar(ExemplarData exemplar) throws Exception { + byte[] result; + { + Marshaler marshaler = ExemplarMarshaler.create(exemplar); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(marshaler.getBinarySerializedSize()); + marshaler.writeBinaryTo(customOutput); + result = customOutput.toByteArray(); + } + + byte[] lowAllocationResult; + { + MarshalerContext context = new MarshalerContext(); + class TestMarshaler extends MarshalerWithSize { + + TestMarshaler() { + super(ExemplarStatelessMarshaler.INSTANCE.getBinarySerializedSize(exemplar, context)); + } + + @Override + protected void writeTo(Serializer output) throws IOException { + ExemplarStatelessMarshaler.INSTANCE.writeTo(output, exemplar, context); + } + } + Marshaler marshaler = new TestMarshaler(); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(marshaler.getBinarySerializedSize()); + marshaler.writeBinaryTo(customOutput); + lowAllocationResult = customOutput.toByteArray(); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } + + @Test + void validateSummary() throws Exception { + List percentileValues = + Arrays.asList(ImmutableValueAtQuantile.create(3.0, 4.0)); + List points = + Arrays.asList( + ImmutableSummaryPointData.create( + 12345, 12346, Attributes.empty(), 1, 2.0, percentileValues)); + SummaryData summary = ImmutableSummaryData.create(points); + + byte[] result; + { + Marshaler marshaler = SummaryMarshaler.create(summary); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(marshaler.getBinarySerializedSize()); + marshaler.writeBinaryTo(customOutput); + result = customOutput.toByteArray(); + } + + byte[] lowAllocationResult; + { + MarshalerContext context = new MarshalerContext(); + class TestMarshaler extends MarshalerWithSize { + + TestMarshaler() { + super(SummaryStatelessMarshaler.INSTANCE.getBinarySerializedSize(summary, context)); + } + + @Override + protected void writeTo(Serializer output) throws IOException { + SummaryStatelessMarshaler.INSTANCE.writeTo(output, summary, context); + } + } + Marshaler marshaler = new TestMarshaler(); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(marshaler.getBinarySerializedSize()); + marshaler.writeBinaryTo(customOutput); + lowAllocationResult = customOutput.toByteArray(); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } + + private static Collection metrics(Consumer metricProducer) { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(metricReader) + .registerView( + InstrumentSelector.builder().setName("exponentialhistogram").build(), + View.builder() + .setAggregation(Aggregation.base2ExponentialBucketHistogram()) + .build()) + .setResource( + Resource.create( + Attributes.builder() + .put(AttributeKey.booleanKey("key_bool"), true) + .put(AttributeKey.stringKey("key_string"), "string") + .put(AttributeKey.longKey("key_int"), 100L) + .put(AttributeKey.doubleKey("key_double"), 100.3) + .put( + AttributeKey.stringArrayKey("key_string_array"), + Arrays.asList("string", "string")) + .put(AttributeKey.longArrayKey("key_long_array"), Arrays.asList(12L, 23L)) + .put( + AttributeKey.doubleArrayKey("key_double_array"), + Arrays.asList(12.3, 23.1)) + .put( + AttributeKey.booleanArrayKey("key_boolean_array"), + Arrays.asList(true, false)) + .put(AttributeKey.valueKey("key_bytes"), Value.of(new byte[] {1, 2, 3})) + .put( + AttributeKey.valueKey("key_map"), + Value.of(KeyValue.of("nested", Value.of("value")))) + .put( + AttributeKey.valueKey("key_heterogeneous_array"), + Value.of(Value.of("string"), Value.of(123L))) + .put(AttributeKey.valueKey("key_empty"), Value.empty()) + .build())) + .build(); + metricProducer.accept(meterProvider); + + return metricReader.collectAllMetrics(); + } + + private static class MetricsProvider implements ArgumentsProvider { + @Override + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) { + return Stream.of( + arguments( + named( + "long gauge", + metrics(meterProvider -> + meterProvider + .get("long gauge") + .gaugeBuilder("gauge") + .setDescription("gauge description") + .setUnit("unit") + .ofLongs() + .buildWithCallback(measurement -> + measurement.record( + 5, Attributes.of(AttributeKey.stringKey("key"), "value")))))), + arguments( + named( + "long counter", + metrics(meterProvider -> { + LongCounter longCounter = + meterProvider + .get("long counter") + .counterBuilder("counter") + .setDescription("counter description") + .setUnit("unit") + .build(); + longCounter.add(1); + longCounter.add(2, Attributes.of(AttributeKey.longKey("lives"), 9L)); + longCounter.add(3); + }))), + arguments( + named( + "long updowncounter", + metrics(meterProvider -> { + LongUpDownCounter longUpDownCounter = + meterProvider + .get("long updowncounter") + .upDownCounterBuilder("updowncounter") + .setDescription("updowncounter description") + .setUnit("unit") + .build(); + longUpDownCounter.add(1); + longUpDownCounter.add(-1, Attributes.of(AttributeKey.booleanKey("on"), true)); + longUpDownCounter.add(1); + }))), + arguments( + named( + "double gauge", + metrics(meterProvider -> + meterProvider + .get("double gauge") + .gaugeBuilder("doublegauge") + .setDescription("doublegauge") + .setUnit("unit") + .buildWithCallback(measurement -> measurement.record(5.0))))), + arguments( + named( + "double counter", + metrics(meterProvider -> { + DoubleCounter doubleCounter = + meterProvider + .get("double counter") + .counterBuilder("doublecounter") + .ofDoubles() + .build(); + doubleCounter.add(1.0); + doubleCounter.add(2.0); + }))), + arguments( + named( + "double updowncounter", + metrics(meterProvider -> { + DoubleUpDownCounter doubleUpDownCounter = + meterProvider + .get("double updowncounter") + .upDownCounterBuilder("doubleupdown") + .ofDoubles() + .build(); + doubleUpDownCounter.add(1.0); + doubleUpDownCounter.add(-1.0); + }))), + arguments( + named( + "double histogram", + metrics(meterProvider -> { + DoubleHistogram histogram = + meterProvider.get("double histogram").histogramBuilder("histogram").build(); + histogram.record(1.0); + histogram.record(2.0); + histogram.record(3.0); + histogram.record(4.0); + histogram.record(5.0); + }))), + arguments( + named( + "long histogram", + metrics(meterProvider -> { + LongHistogram histogram = + meterProvider + .get("long histogram") + .histogramBuilder("histogram") + .ofLongs() + .build(); + histogram.record(1); + histogram.record(2); + histogram.record(3); + histogram.record(4); + histogram.record(5); + }))), + arguments( + named( + "double exponential histogram", + metrics(meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("double exponential histogram") + .histogramBuilder("exponentialhistogram") + .build(); + histogram.record(1.0); + histogram.record(2.0); + histogram.record(3.0); + histogram.record(4.0); + histogram.record(5.0); + }))), + arguments( + named( + "long exponential histogram", + metrics(meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("long exponential histogram") + .histogramBuilder("exponentialhistogram") + .build(); + histogram.record(1); + histogram.record(2); + histogram.record(3); + histogram.record(4); + histogram.record(5); + })))); + } + } + + private static class ExemplarProvider implements ArgumentsProvider { + @Override + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) { + SpanContext spanContext = + SpanContext.create( + "7b2e170db4df2d593ddb4ddf2ddf2d59", + "170d3ddb4d23e81f", + TraceFlags.getSampled(), + TraceState.getDefault()); + + return Stream.of( + arguments( + named( + "double exemplar", + ImmutableDoubleExemplarData.create(Attributes.empty(), 12345, spanContext, 5.0))), + arguments( + named( + "long exemplar", + ImmutableLongExemplarData.create(Attributes.empty(), 12345, spanContext, 5)))); + } + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java index bb6068a02aa..f91b10e71c9 100644 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/metrics/MetricsRequestMarshalerTest.java @@ -17,11 +17,14 @@ import com.google.protobuf.Message; import com.google.protobuf.util.JsonFormat; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.OtelEncodingUtils; +import io.opentelemetry.api.impl.Base16EncodingUtils; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; import io.opentelemetry.proto.common.v1.AnyValue; import io.opentelemetry.proto.common.v1.InstrumentationScope; @@ -40,13 +43,18 @@ import io.opentelemetry.proto.metrics.v1.Summary; import io.opentelemetry.proto.metrics.v1.SummaryDataPoint; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.data.SummaryPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; @@ -57,9 +65,8 @@ import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramBuckets; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.MutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.MutableExponentialHistogramPointData; import io.opentelemetry.sdk.resources.Resource; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -71,7 +78,8 @@ import java.util.List; import java.util.Locale; import java.util.stream.Collectors; -import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; // Fill deprecated APIs before removing them after users get a chance to migrate. class MetricsRequestMarshalerTest { @@ -82,10 +90,12 @@ private static AnyValue stringValue(String v) { return AnyValue.newBuilder().setStringValue(v).build(); } - @Test - void dataPoint_withDefaultValues() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void dataPoint_withDefaultValues(MarshalerSource marshalerSource) { assertThat( toNumberDataPoints( + marshalerSource, singletonList( ImmutableLongPointData.create( 123, @@ -128,6 +138,7 @@ void dataPoint_withDefaultValues() { assertThat( toNumberDataPoints( + marshalerSource, singletonList( ImmutableDoublePointData.create( 123, @@ -169,11 +180,13 @@ void dataPoint_withDefaultValues() { .build()); } - @Test - void longDataPoints() { - assertThat(toNumberDataPoints(Collections.emptyList())).isEmpty(); + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void longDataPoints(MarshalerSource marshalerSource) { + assertThat(toNumberDataPoints(marshalerSource, Collections.emptyList())).isEmpty(); assertThat( toNumberDataPoints( + marshalerSource, singletonList( ImmutableLongPointData.create( 123, @@ -215,6 +228,7 @@ void longDataPoints() { .build()); assertThat( toNumberDataPoints( + marshalerSource, ImmutableList.of( ImmutableLongPointData.create(123, 456, Attributes.empty(), 5), ImmutableLongPointData.create(321, 654, KV_ATTR, 7)))) @@ -234,11 +248,13 @@ void longDataPoints() { .build()); } - @Test - void doubleDataPoints() { - assertThat(toNumberDataPoints(Collections.emptyList())).isEmpty(); + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void doubleDataPoints(MarshalerSource marshalerSource) { + assertThat(toNumberDataPoints(marshalerSource, Collections.emptyList())).isEmpty(); assertThat( toNumberDataPoints( + marshalerSource, singletonList(ImmutableDoublePointData.create(123, 456, KV_ATTR, 5.1)))) .containsExactly( NumberDataPoint.newBuilder() @@ -251,6 +267,7 @@ void doubleDataPoints() { .build()); assertThat( toNumberDataPoints( + marshalerSource, ImmutableList.of( ImmutableDoublePointData.create(123, 456, Attributes.empty(), 5.1), ImmutableDoublePointData.create(321, 654, KV_ATTR, 7.1)))) @@ -270,10 +287,12 @@ void doubleDataPoints() { .build()); } - @Test - void summaryDataPoints() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void summaryDataPoints(MarshalerSource marshalerSource) { assertThat( toSummaryDataPoints( + marshalerSource, singletonList( ImmutableSummaryPointData.create( 123, @@ -299,6 +318,7 @@ void summaryDataPoints() { .build()); assertThat( toSummaryDataPoints( + marshalerSource, ImmutableList.of( ImmutableSummaryPointData.create( 123, 456, Attributes.empty(), 7, 15.3, Collections.emptyList()), @@ -339,18 +359,22 @@ void summaryDataPoints() { .build()); } - @Test - void histogramDataPoints() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void histogramDataPoints(MarshalerSource marshalerSource) { assertThat( toHistogramDataPoints( + marshalerSource, ImmutableList.of( ImmutableHistogramPointData.create( 123, 456, KV_ATTR, 14.2, - null, - null, + /* hasMin= */ false, + 0, + /* hasMax= */ false, + 0, ImmutableList.of(1.0), ImmutableList.of(1L, 5L)), ImmutableHistogramPointData.create( @@ -358,7 +382,9 @@ void histogramDataPoints() { 456, Attributes.empty(), 15.3, + /* hasMin= */ true, 3.3, + /* hasMax= */ true, 12.0, ImmutableList.of(), ImmutableList.of(7L), @@ -410,31 +436,38 @@ void histogramDataPoints() { .build()); } - @Test - void exponentialHistogramDataPoints() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void exponentialHistogramDataPoints(MarshalerSource marshalerSource) { assertThat( toExponentialHistogramDataPoints( + marshalerSource, ImmutableList.of( - ExponentialHistogramPointData.create( + ImmutableExponentialHistogramPointData.create( 0, 123.4, 1, - null, - null, - new TestExponentialHistogramBuckets(0, Collections.emptyList()), - new TestExponentialHistogramBuckets(0, Collections.emptyList()), + /* hasMin= */ false, + 0, + /* hasMax= */ false, + 0, + ImmutableExponentialHistogramBuckets.create(0, 0, Collections.emptyList()), + ImmutableExponentialHistogramBuckets.create(0, 0, Collections.emptyList()), 123, 456, Attributes.empty(), Collections.emptyList()), - ExponentialHistogramPointData.create( + ImmutableExponentialHistogramPointData.create( 0, 123.4, 1, + /* hasMin= */ true, 3.3, + /* hasMax= */ true, 80.1, - new TestExponentialHistogramBuckets(1, ImmutableList.of(1L, 0L, 2L)), - new TestExponentialHistogramBuckets(0, Collections.emptyList()), + ImmutableExponentialHistogramBuckets.create( + 0, 1, ImmutableList.of(1L, 0L, 2L)), + ImmutableExponentialHistogramBuckets.create(0, 0, Collections.emptyList()), 123, 456, Attributes.of(stringKey("key"), "value"), @@ -498,10 +531,149 @@ void exponentialHistogramDataPoints() { .build()); } - @Test - void toProtoMetric_monotonic() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void exponentialHistogramZeroSum(MarshalerSource marshalerSource) { + assertThat( + toExponentialHistogramDataPoints( + marshalerSource, + ImmutableList.of( + ImmutableExponentialHistogramPointData.create( + 0, + 0, + 0, + /* hasMin= */ false, + 0, + /* hasMax= */ false, + 0, + ImmutableExponentialHistogramBuckets.create(0, 0, Collections.emptyList()), + ImmutableExponentialHistogramBuckets.create(0, 0, Collections.emptyList()), + 123, + 456, + Attributes.empty(), + Collections.emptyList())))) + .containsExactly( + ExponentialHistogramDataPoint.newBuilder() + .setStartTimeUnixNano(123) + .setTimeUnixNano(456) + .setCount(0) + .setScale(0) + .setSum(0) + .setZeroCount(0) + .setPositive( + ExponentialHistogramDataPoint.Buckets.newBuilder().setOffset(0)) // no buckets + .setNegative( + ExponentialHistogramDataPoint.Buckets.newBuilder().setOffset(0)) // no buckets + .build()); + } + + @SuppressWarnings("PointlessArithmeticExpression") + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void exponentialHistogramReusableDataPoints(MarshalerSource marshalerSource) { + assertThat( + toExponentialHistogramDataPoints( + marshalerSource, + ImmutableList.of( + new MutableExponentialHistogramPointData() + .set( + 0, + 123.4, + 1, + /* hasMin= */ false, + 0, + /* hasMax= */ false, + 0, + new MutableExponentialHistogramBuckets() + .set(0, 0, 0, DynamicPrimitiveLongList.empty()), + new MutableExponentialHistogramBuckets() + .set(0, 0, 0, DynamicPrimitiveLongList.empty()), + 123, + 456, + Attributes.empty(), + Collections.emptyList()), + new MutableExponentialHistogramPointData() + .set( + 0, + 123.4, + 1, + /* hasMin= */ true, + 3.3, + /* hasMax= */ true, + 80.1, + new MutableExponentialHistogramBuckets() + .set(0, 1, 1 + 0 + 2, DynamicPrimitiveLongList.of(1L, 0L, 2L)), + new MutableExponentialHistogramBuckets() + .set(0, 0, 0, DynamicPrimitiveLongList.empty()), + 123, + 456, + Attributes.of(stringKey("key"), "value"), + ImmutableList.of( + ImmutableDoubleExemplarData.create( + Attributes.of(stringKey("test"), "value"), + 2, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1.5)))))) + .containsExactly( + ExponentialHistogramDataPoint.newBuilder() + .setStartTimeUnixNano(123) + .setTimeUnixNano(456) + .setCount(1) + .setScale(0) + .setSum(123.4) + .setZeroCount(1) + .setPositive( + ExponentialHistogramDataPoint.Buckets.newBuilder().setOffset(0)) // no buckets + .setNegative( + ExponentialHistogramDataPoint.Buckets.newBuilder().setOffset(0)) // no buckets + .build(), + ExponentialHistogramDataPoint.newBuilder() + .setStartTimeUnixNano(123) + .setTimeUnixNano(456) + .setCount(4) // Counts in positive, negative, and zero count. + .addAllAttributes( + singletonList( + KeyValue.newBuilder().setKey("key").setValue(stringValue("value")).build())) + .setScale(0) + .setSum(123.4) + .setMin(3.3) + .setMax(80.1) + .setZeroCount(1) + .setPositive( + ExponentialHistogramDataPoint.Buckets.newBuilder() + .setOffset(1) + .addBucketCounts(1) + .addBucketCounts(0) + .addBucketCounts(2)) + .setNegative( + ExponentialHistogramDataPoint.Buckets.newBuilder().setOffset(0)) // no buckets + .addExemplars( + Exemplar.newBuilder() + .setTimeUnixNano(2) + .addFilteredAttributes( + KeyValue.newBuilder() + .setKey("test") + .setValue(stringValue("value")) + .build()) + .setSpanId(ByteString.copyFrom(new byte[] {0, 0, 0, 0, 0, 0, 0, 2})) + .setTraceId( + ByteString.copyFrom( + new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})) + .setAsDouble(1.5) + .build()) + .build()); + } + + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoMetric_monotonic(MarshalerSource marshalerSource) { assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createLongSum( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -537,6 +709,7 @@ void toProtoMetric_monotonic() { .build()); assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createDoubleSum( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -572,10 +745,12 @@ void toProtoMetric_monotonic() { .build()); } - @Test - void toProtoMetric_nonMonotonic() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoMetric_nonMonotonic(MarshalerSource marshalerSource) { assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createLongSum( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -611,6 +786,7 @@ void toProtoMetric_nonMonotonic() { .build()); assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createDoubleSum( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -646,10 +822,12 @@ void toProtoMetric_nonMonotonic() { .build()); } - @Test - void toProtoMetric_gauges() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoMetric_gauges(MarshalerSource marshalerSource) { assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createLongGauge( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -681,6 +859,7 @@ void toProtoMetric_gauges() { .build()); assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createDoubleGauge( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -712,10 +891,12 @@ void toProtoMetric_gauges() { .build()); } - @Test - void toProtoMetric_summary() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoMetric_summary(MarshalerSource marshalerSource) { assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createDoubleSummary( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -767,10 +948,12 @@ void toProtoMetric_summary() { .build()); } - @Test - void toProtoMetric_histogram() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoMetric_histogram(MarshalerSource marshalerSource) { assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createDoubleHistogram( Resource.empty(), InstrumentationScopeInfo.empty(), @@ -785,7 +968,9 @@ void toProtoMetric_histogram() { 456, KV_ATTR, 4.0, + /* hasMin= */ true, 1.0, + /* hasMax= */ true, 3.0, ImmutableList.of(), ImmutableList.of(33L))))))) @@ -817,29 +1002,33 @@ void toProtoMetric_histogram() { .build()); } - @Test - void toProtoMetric_exponentialHistogram() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoMetric_exponentialHistogram(MarshalerSource marshalerSource) { assertThat( toProtoMetric( + marshalerSource, ImmutableMetricData.createExponentialHistogram( Resource.empty(), InstrumentationScopeInfo.empty(), "name", "description", "1", - ExponentialHistogramData.create( + ImmutableExponentialHistogramData.create( AggregationTemporality.CUMULATIVE, singletonList( - ExponentialHistogramPointData.create( + ImmutableExponentialHistogramPointData.create( 20, 123.4, 257, + /* hasMin= */ true, 20.1, + /* hasMax= */ true, 44.3, - new TestExponentialHistogramBuckets( - -1, ImmutableList.of(0L, 128L, 1L << 32)), - new TestExponentialHistogramBuckets( - 1, ImmutableList.of(0L, 128L, 1L << 32)), + ImmutableExponentialHistogramBuckets.create( + 20, -1, ImmutableList.of(0L, 128L, 1L << 32)), + ImmutableExponentialHistogramBuckets.create( + 20, 1, ImmutableList.of(0L, 128L, 1L << 32)), 123, 456, KV_ATTR, @@ -885,8 +1074,9 @@ void toProtoMetric_exponentialHistogram() { .build()); } - @Test - void protoResourceMetrics() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void protoResourceMetrics(MarshalerSource marshalerSource) { Resource resource = Resource.create(Attributes.of(stringKey("ka"), "va"), "http://resource.url"); io.opentelemetry.proto.resource.v1.Resource resourceProto = @@ -898,9 +1088,21 @@ void protoResourceMetrics() { io.opentelemetry.proto.resource.v1.Resource emptyResourceProto = io.opentelemetry.proto.resource.v1.Resource.newBuilder().build(); InstrumentationScopeInfo instrumentationScopeInfo = - InstrumentationScopeInfo.create("name", "version", "http://url"); + InstrumentationScopeInfo.builder("name") + .setVersion("version") + .setSchemaUrl("http://url") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build(); InstrumentationScope scopeProto = - InstrumentationScope.newBuilder().setName("name").setVersion("version").build(); + InstrumentationScope.newBuilder() + .setName("name") + .setVersion("version") + .addAttributes( + KeyValue.newBuilder() + .setKey("key") + .setValue(AnyValue.newBuilder().setStringValue("value").build()) + .build()) + .build(); InstrumentationScope emptyScopeProto = InstrumentationScope.newBuilder().setName("").setVersion("").build(); Metric metricDoubleSum = @@ -929,6 +1131,7 @@ void protoResourceMetrics() { assertThat( toProtoResourceMetrics( + marshalerSource, ImmutableList.of( ImmutableMetricData.createDoubleSum( resource, @@ -1002,55 +1205,46 @@ void protoResourceMetrics() { }); } - private static List toNumberDataPoints(Collection points) { + private static List toNumberDataPoints( + MarshalerSource marshalerSource, Collection points) { return points.stream() - .map( - point -> - parse(NumberDataPoint.getDefaultInstance(), NumberDataPointMarshaler.create(point))) + .map(point -> parse(NumberDataPoint.getDefaultInstance(), marshalerSource.create(point))) .collect(Collectors.toList()); } - private static List toSummaryDataPoints(Collection points) { + private static List toSummaryDataPoints( + MarshalerSource marshalerSource, Collection points) { return points.stream() - .map( - point -> - parse( - SummaryDataPoint.getDefaultInstance(), SummaryDataPointMarshaler.create(point))) + .map(point -> parse(SummaryDataPoint.getDefaultInstance(), marshalerSource.create(point))) .collect(Collectors.toList()); } private static List toHistogramDataPoints( - Collection points) { + MarshalerSource marshalerSource, Collection points) { return points.stream() - .map( - point -> - parse( - HistogramDataPoint.getDefaultInstance(), - HistogramDataPointMarshaler.create(point))) + .map(point -> parse(HistogramDataPoint.getDefaultInstance(), marshalerSource.create(point))) .collect(Collectors.toList()); } private static List toExponentialHistogramDataPoints( - Collection points) { + MarshalerSource marshalerSource, Collection points) { return points.stream() - .map( - point -> - parse( - ExponentialHistogramDataPoint.getDefaultInstance(), - ExponentialHistogramDataPointMarshaler.create(point))) + .map(point -> + parse( + ExponentialHistogramDataPoint.getDefaultInstance(), marshalerSource.create(point))) .collect(Collectors.toList()); } - private static Metric toProtoMetric(MetricData metricData) { - return parse(Metric.getDefaultInstance(), MetricMarshaler.create(metricData)); + private static Metric toProtoMetric(MarshalerSource marshalerSource, MetricData metricData) { + return parse(Metric.getDefaultInstance(), marshalerSource.create(metricData)); } private static List toProtoResourceMetrics( - Collection metricDataList) { + MarshalerSource marshalerSource, Collection metricDataList) { ExportMetricsServiceRequest exportRequest = parse( ExportMetricsServiceRequest.getDefaultInstance(), - MetricsRequestMarshaler.create(metricDataList)); + marshalerSource.create(metricDataList)); return exportRequest.getResourceMetricsList(); } @@ -1113,7 +1307,7 @@ private static T parse(T prototype, Marshaler marshaler) { private static ByteString toHex(ByteString hexReadAsBase64) { String hex = Base64.getEncoder().encodeToString(hexReadAsBase64.toByteArray()).toLowerCase(Locale.ROOT); - return ByteString.copyFrom(OtelEncodingUtils.bytesFromBase16(hex, hex.length())); + return ByteString.copyFrom(Base16EncodingUtils.bytesFromBase16(hex, hex.length())); } private static byte[] toByteArray(Marshaler marshaler) { @@ -1137,33 +1331,100 @@ private static String toJson(Marshaler marshaler) { return new String(bos.toByteArray(), StandardCharsets.UTF_8); } - /** - * Helper class for creating Exponential Histogram bucket data directly without needing to record. - * Essentially, mocking out the bucket operations and downscaling. - */ - private static class TestExponentialHistogramBuckets implements ExponentialHistogramBuckets { + private static Marshaler createMarshaler(StatelessMarshaler marshaler, T data) { + return new Marshaler() { + private final MarshalerContext context = new MarshalerContext(); + private final int size = marshaler.getBinarySerializedSize(data, context); - private final int offset; - private final List bucketCounts; + @Override + public int getBinarySerializedSize() { + return size; + } - TestExponentialHistogramBuckets(int offset, List bucketCounts) { - this.offset = offset; - this.bucketCounts = bucketCounts; - } + @Override + protected void writeTo(Serializer output) throws IOException { + context.resetReadIndex(); + marshaler.writeTo(output, data, context); + } + }; + } - @Override - public int getOffset() { - return offset; - } + private enum MarshalerSource { + STATEFUL_MARSHALER { + @Override + Marshaler create(PointData point) { + return NumberDataPointMarshaler.create(point); + } - @Override - public List getBucketCounts() { - return bucketCounts; - } + @Override + Marshaler create(SummaryPointData point) { + return SummaryDataPointMarshaler.create(point); + } - @Override - public long getTotalCount() { - return getBucketCounts().stream().reduce(0L, Long::sum); - } + @Override + Marshaler create(HistogramPointData point) { + return HistogramDataPointMarshaler.create(point); + } + + @Override + Marshaler create(ExponentialHistogramPointData point) { + return ExponentialHistogramDataPointMarshaler.create(point); + } + + @Override + Marshaler create(MetricData metric) { + return MetricMarshaler.create(metric); + } + + @Override + Marshaler create(Collection metricDataList) { + return MetricsRequestMarshaler.create(metricDataList); + } + }, + STATELESS_MARSHALER { + @Override + Marshaler create(PointData point) { + return createMarshaler(NumberDataPointStatelessMarshaler.INSTANCE, point); + } + + @Override + Marshaler create(SummaryPointData point) { + return createMarshaler(SummaryDataPointStatelessMarshaler.INSTANCE, point); + } + + @Override + Marshaler create(HistogramPointData point) { + return createMarshaler(HistogramDataPointStatelessMarshaler.INSTANCE, point); + } + + @Override + Marshaler create(ExponentialHistogramPointData point) { + return createMarshaler(ExponentialHistogramDataPointStatelessMarshaler.INSTANCE, point); + } + + @Override + Marshaler create(MetricData metric) { + return createMarshaler(MetricStatelessMarshaler.INSTANCE, metric); + } + + @Override + Marshaler create(Collection metricDataList) { + LowAllocationMetricsRequestMarshaler marshaler = new LowAllocationMetricsRequestMarshaler(); + marshaler.initialize(metricDataList); + return marshaler; + } + }; + + abstract Marshaler create(PointData point); + + abstract Marshaler create(SummaryPointData point); + + abstract Marshaler create(HistogramPointData point); + + abstract Marshaler create(ExponentialHistogramPointData point); + + abstract Marshaler create(MetricData metric); + + abstract Marshaler create(Collection metricDataList); } } diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/LowAllocationTraceRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/LowAllocationTraceRequestMarshalerTest.java new file mode 100644 index 00000000000..833c14c4a97 --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/LowAllocationTraceRequestMarshalerTest.java @@ -0,0 +1,170 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.trace.TestSpanData; +import io.opentelemetry.sdk.trace.data.EventData; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.data.StatusData; +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +class LowAllocationTraceRequestMarshalerTest { + + private static final AttributeKey KEY_BOOL = AttributeKey.booleanKey("key_bool"); + private static final AttributeKey KEY_STRING = AttributeKey.stringKey("key_string"); + private static final AttributeKey KEY_INT = AttributeKey.longKey("key_int"); + private static final AttributeKey KEY_DOUBLE = AttributeKey.doubleKey("key_double"); + private static final AttributeKey> KEY_STRING_ARRAY = + AttributeKey.stringArrayKey("key_string_array"); + private static final AttributeKey> KEY_LONG_ARRAY = + AttributeKey.longArrayKey("key_long_array"); + private static final AttributeKey> KEY_DOUBLE_ARRAY = + AttributeKey.doubleArrayKey("key_double_array"); + private static final AttributeKey> KEY_BOOLEAN_ARRAY = + AttributeKey.booleanArrayKey("key_boolean_array"); + private static final AttributeKey> KEY_BYTES = AttributeKey.valueKey("key_bytes"); + private static final AttributeKey> KEY_MAP = AttributeKey.valueKey("key_map"); + private static final AttributeKey> KEY_HETEROGENEOUS_ARRAY = + AttributeKey.valueKey("key_heterogeneous_array"); + private static final AttributeKey> KEY_EMPTY = AttributeKey.valueKey("key_empty"); + private static final AttributeKey LINK_ATTR_KEY = AttributeKey.stringKey("link_attr_key"); + + private static final Resource RESOURCE = + Resource.create( + Attributes.builder() + .put(KEY_BOOL, true) + .put(KEY_STRING, "string") + .put(KEY_INT, 100L) + .put(KEY_DOUBLE, 100.3) + .put(KEY_STRING_ARRAY, Arrays.asList("string", "string")) + .put(KEY_LONG_ARRAY, Arrays.asList(12L, 23L)) + .put(KEY_DOUBLE_ARRAY, Arrays.asList(12.3, 23.1)) + .put(KEY_BOOLEAN_ARRAY, Arrays.asList(true, false)) + .put(KEY_BYTES, Value.of(new byte[] {1, 2, 3})) + .put(KEY_MAP, Value.of(KeyValue.of("nested", Value.of("value")))) + .put(KEY_HETEROGENEOUS_ARRAY, Value.of(Value.of("string"), Value.of(123L))) + .put(KEY_EMPTY, Value.empty()) + .build()); + + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.create("name"); + private static final String TRACE_ID = "7b2e170db4df2d593ddb4ddf2ddf2d59"; + private static final String SPAN_ID = "170d3ddb4d23e81f"; + private static final SpanContext SPAN_CONTEXT = + SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()); + + private final List spanDataList = createSpanDataList(); + + private static List createSpanDataList() { + List spanDataList = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + spanDataList.add(createSpanData()); + } + return spanDataList; + } + + private static SpanData createSpanData() { + return TestSpanData.builder() + .setResource(RESOURCE) + .setInstrumentationScopeInfo(INSTRUMENTATION_SCOPE_INFO) + .setHasEnded(true) + .setSpanContext(SPAN_CONTEXT) + .setParentSpanContext(SpanContext.getInvalid()) + .setName("GET /api/endpoint") + .setKind(SpanKind.SERVER) + .setStartEpochNanos(12345) + .setEndEpochNanos(12349) + .setAttributes( + Attributes.builder() + .put(KEY_BOOL, true) + .put(KEY_STRING, "string") + .put(KEY_INT, 100L) + .put(KEY_DOUBLE, 100.3) + .build()) + .setTotalAttributeCount(2) + .setEvents( + Arrays.asList( + EventData.create(12347, "my_event_1", Attributes.empty()), + EventData.create(12348, "my_event_2", Attributes.of(KEY_INT, 1234L)), + EventData.create(12349, "my_event_3", Attributes.empty()))) + .setTotalRecordedEvents(4) + .setLinks( + Arrays.asList( + LinkData.create(SPAN_CONTEXT), + LinkData.create(SPAN_CONTEXT, Attributes.of(LINK_ATTR_KEY, "value")))) + .setTotalRecordedLinks(3) + .setStatus(StatusData.ok()) + .build(); + } + + @Test + void validateOutput() throws Exception { + byte[] result; + { + TraceRequestMarshaler requestMarshaler = TraceRequestMarshaler.create(spanDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(customOutput); + result = customOutput.toByteArray(); + } + + byte[] lowAllocationResult; + { + LowAllocationTraceRequestMarshaler requestMarshaler = + new LowAllocationTraceRequestMarshaler(); + requestMarshaler.initialize(spanDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeBinaryTo(customOutput); + lowAllocationResult = customOutput.toByteArray(); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } + + @Test + void validateJsonOutput() throws Exception { + String result; + { + TraceRequestMarshaler requestMarshaler = TraceRequestMarshaler.create(spanDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeJsonTo(customOutput); + result = new String(customOutput.toByteArray(), StandardCharsets.UTF_8); + } + + String lowAllocationResult; + { + LowAllocationTraceRequestMarshaler requestMarshaler = + new LowAllocationTraceRequestMarshaler(); + requestMarshaler.initialize(spanDataList); + ByteArrayOutputStream customOutput = + new ByteArrayOutputStream(requestMarshaler.getBinarySerializedSize()); + requestMarshaler.writeJsonTo(customOutput); + lowAllocationResult = new String(customOutput.toByteArray(), StandardCharsets.UTF_8); + } + + assertThat(lowAllocationResult).isEqualTo(result); + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/SpanFlagsTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/SpanFlagsTest.java new file mode 100644 index 00000000000..481ffc2d23c --- /dev/null +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/SpanFlagsTest.java @@ -0,0 +1,121 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.traces; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.trace.TraceFlags; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link SpanFlags}. */ +public class SpanFlagsTest { + + @Test + void withParentIsRemoteFlags() { + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0xff), false)) + .isEqualTo(0x1ff); + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0x01), false)) + .isEqualTo(0x101); + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0x05), false)) + .isEqualTo(0x105); + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0x00), false)) + .isEqualTo(0x100); + + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0xff), true)) + .isEqualTo(0x3ff); + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0x01), true)) + .isEqualTo(0x301); + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0x05), true)) + .isEqualTo(0x305); + assertThat(SpanFlags.withParentIsRemoteFlags(TraceFlags.fromByte((byte) 0x00), true)) + .isEqualTo(0x300); + } + + @Test + void getTraceFlags() { + assertThat(SpanFlags.getTraceFlags(0x1ff)).isEqualTo(TraceFlags.fromByte((byte) 0xff)); + assertThat(SpanFlags.getTraceFlags(0xffffffff)).isEqualTo(TraceFlags.fromByte((byte) 0xff)); + assertThat(SpanFlags.getTraceFlags(0x000000ff)).isEqualTo(TraceFlags.fromByte((byte) 0xff)); + + assertThat(SpanFlags.getTraceFlags(0x100)).isEqualTo(TraceFlags.fromByte((byte) 0x00)); + assertThat(SpanFlags.getTraceFlags(0xffffff00)).isEqualTo(TraceFlags.fromByte((byte) 0x00)); + assertThat(SpanFlags.getTraceFlags(0x00000000)).isEqualTo(TraceFlags.fromByte((byte) 0x00)); + + assertThat(SpanFlags.getTraceFlags(0x101)).isEqualTo(TraceFlags.fromByte((byte) 0x01)); + assertThat(SpanFlags.getTraceFlags(0xffffff01)).isEqualTo(TraceFlags.fromByte((byte) 0x01)); + assertThat(SpanFlags.getTraceFlags(0x00000001)).isEqualTo(TraceFlags.fromByte((byte) 0x01)); + } + + @Test + void isKnownWhetherParentIsRemote() { + assertThat(SpanFlags.isKnownWhetherParentIsRemote(SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isTrue(); + assertThat( + SpanFlags.isKnownWhetherParentIsRemote( + 0x00000001 | SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isTrue(); + assertThat( + SpanFlags.isKnownWhetherParentIsRemote( + 0x10000000 | SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isTrue(); + assertThat( + SpanFlags.isKnownWhetherParentIsRemote( + 0x00000200 | SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isTrue(); + assertThat(SpanFlags.isKnownWhetherParentIsRemote(SpanFlags.CONTEXT_IS_REMOTE_MASK)).isTrue(); + assertThat(SpanFlags.isKnownWhetherParentIsRemote(0xffffffff)).isTrue(); + + assertThat(SpanFlags.isKnownWhetherParentIsRemote(~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isFalse(); + assertThat( + SpanFlags.isKnownWhetherParentIsRemote( + 0x00000001 & ~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isFalse(); + assertThat( + SpanFlags.isKnownWhetherParentIsRemote( + 0x10000000 & ~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isFalse(); + assertThat( + SpanFlags.isKnownWhetherParentIsRemote( + 0x00000200 & ~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isFalse(); + assertThat(SpanFlags.isKnownWhetherParentIsRemote(0x00000000)).isFalse(); + } + + @Test + void isParentRemote() { + assertThat( + SpanFlags.isParentRemote( + SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT | SpanFlags.CONTEXT_IS_REMOTE_BIT)) + .isTrue(); + assertThat( + SpanFlags.isParentRemote( + 0x00000001 | SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT | SpanFlags.CONTEXT_IS_REMOTE_BIT)) + .isTrue(); + assertThat( + SpanFlags.isParentRemote( + 0x10000000 | SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT | SpanFlags.CONTEXT_IS_REMOTE_BIT)) + .isTrue(); + assertThat( + SpanFlags.isParentRemote( + 0x00000200 | SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT | SpanFlags.CONTEXT_IS_REMOTE_BIT)) + .isTrue(); + assertThat(SpanFlags.isParentRemote(SpanFlags.CONTEXT_IS_REMOTE_MASK)).isTrue(); + assertThat(SpanFlags.isParentRemote(0xffffffff)).isTrue(); + + assertThat(SpanFlags.isParentRemote(SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)).isFalse(); + assertThat(SpanFlags.isParentRemote(~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)).isFalse(); + assertThat(SpanFlags.isParentRemote(SpanFlags.CONTEXT_IS_REMOTE_BIT)).isFalse(); + assertThat(SpanFlags.isParentRemote(~SpanFlags.CONTEXT_IS_REMOTE_BIT)).isFalse(); + assertThat( + SpanFlags.isParentRemote( + ~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT & ~SpanFlags.CONTEXT_IS_REMOTE_BIT)) + .isFalse(); + assertThat(SpanFlags.isParentRemote(0x00000200 & ~SpanFlags.CONTEXT_HAS_IS_REMOTE_BIT)) + .isFalse(); + assertThat(SpanFlags.isParentRemote(0x00000000)).isFalse(); + } +} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/TraceRequestMarshalerTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/TraceRequestMarshalerTest.java index 11d08af0655..8119eae8f45 100644 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/TraceRequestMarshalerTest.java +++ b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/otlp/traces/TraceRequestMarshalerTest.java @@ -18,7 +18,8 @@ import com.google.protobuf.Message; import com.google.protobuf.util.JsonFormat; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.OtelEncodingUtils; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.impl.Base16EncodingUtils; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.SpanKind; @@ -27,10 +28,14 @@ import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; import io.opentelemetry.proto.common.v1.AnyValue; import io.opentelemetry.proto.common.v1.ArrayValue; import io.opentelemetry.proto.common.v1.InstrumentationScope; import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.common.v1.KeyValueList; import io.opentelemetry.proto.trace.v1.ResourceSpans; import io.opentelemetry.proto.trace.v1.ScopeSpans; import io.opentelemetry.proto.trace.v1.Span; @@ -40,6 +45,7 @@ import io.opentelemetry.sdk.testing.trace.TestSpanData; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.StatusData; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -49,6 +55,8 @@ import java.util.Collections; import java.util.Locale; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; class TraceRequestMarshalerTest { @@ -56,7 +64,9 @@ class TraceRequestMarshalerTest { new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4}; private static final String TRACE_ID = TraceId.fromBytes(TRACE_ID_BYTES); private static final byte[] SPAN_ID_BYTES = new byte[] {0, 0, 0, 0, 4, 3, 2, 1}; + private static final byte[] PARENT_SPAN_ID_BYTES = new byte[] {0, 0, 0, 0, 5, 6, 7, 8}; private static final String SPAN_ID = SpanId.fromBytes(SPAN_ID_BYTES); + private static final String PARENT_SPAN_ID = SpanId.fromBytes(PARENT_SPAN_ID_BYTES); private static final String TRACE_STATE_VALUE = "baz=qux,foo=bar"; private static final SpanContext SPAN_CONTEXT = SpanContext.create( @@ -65,6 +75,10 @@ class TraceRequestMarshalerTest { TraceFlags.getSampled(), TraceState.builder().put("foo", "bar").put("baz", "qux").build()); + private static final SpanContext PARENT_SPAN_CONTEXT = + SpanContext.createFromRemoteParent( + TRACE_ID, PARENT_SPAN_ID, TraceFlags.getSampled(), TraceState.builder().build()); + @Test void toProtoResourceSpans() { ResourceSpansMarshaler[] resourceSpansMarshalers = @@ -80,7 +94,11 @@ void toProtoResourceSpans() { .setEndEpochNanos(12349) .setStatus(StatusData.unset()) .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) + InstrumentationScopeInfo.builder("testLib") + .setVersion("1.0") + .setSchemaUrl("http://url") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build()) .setResource( Resource.builder().put("one", 1).setSchemaUrl("http://url").build()) .build())); @@ -94,15 +112,25 @@ void toProtoResourceSpans() { ScopeSpans instrumentationLibrarySpans = onlyResourceSpans.getScopeSpans(0); assertThat(instrumentationLibrarySpans.getSchemaUrl()).isEqualTo("http://url"); assertThat(instrumentationLibrarySpans.getScope()) - .isEqualTo(InstrumentationScope.newBuilder().setName("testLib").setVersion("1.0").build()); + .isEqualTo( + InstrumentationScope.newBuilder() + .setName("testLib") + .setVersion("1.0") + .addAttributes( + KeyValue.newBuilder() + .setKey("key") + .setValue(AnyValue.newBuilder().setStringValue("value").build()) + .build()) + .build()); } - @Test - void toProtoSpan() { - Span span = + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpan(MarshalerSource marshalerSource) { + Span protoSpan = parse( Span.getDefaultInstance(), - SpanMarshaler.create( + marshalerSource.create( TestSpanData.builder() .setHasEnded(true) .setSpanContext(SPAN_CONTEXT) @@ -121,8 +149,23 @@ void toProtoSpan() { .put("long_array", 12L, 23L) .put("double_array", 12.3, 23.1) .put("boolean_array", true, false) + .put("bytes", Value.of(new byte[] {1, 2, 3})) + .put( + "map", + Value.of( + io.opentelemetry.api.common.KeyValue.of( + "nested", Value.of("value")))) + .put("heterogeneousArray", Value.of(Value.of("string"), Value.of(123L))) + .put("empty", Value.empty()) + .put("empty_string", "") + .put("false_value", false) + .put("zero_int", 0L) + .put("zero_double", 0.0) + .put("empty_array", Value.of(Collections.emptyList())) + .put("empty_map", Value.of(Collections.emptyMap())) + .put("empty_bytes", Value.of(new byte[] {})) .build()) - .setTotalAttributeCount(9) + .setTotalAttributeCount(20) .setEvents( Collections.singletonList( EventData.create(12347, "my_event", Attributes.empty()))) @@ -132,15 +175,19 @@ void toProtoSpan() { .setStatus(StatusData.ok()) .build())); - assertThat(span.getTraceId().toByteArray()).isEqualTo(TRACE_ID_BYTES); - assertThat(span.getSpanId().toByteArray()).isEqualTo(SPAN_ID_BYTES); - assertThat(span.getTraceState()).isEqualTo(TRACE_STATE_VALUE); - assertThat(span.getParentSpanId().toByteArray()).isEqualTo(new byte[] {}); - assertThat(span.getName()).isEqualTo("GET /api/endpoint"); - assertThat(span.getKind()).isEqualTo(SPAN_KIND_SERVER); - assertThat(span.getStartTimeUnixNano()).isEqualTo(12345); - assertThat(span.getEndTimeUnixNano()).isEqualTo(12349); - assertThat(span.getAttributesList()) + assertThat(protoSpan.getTraceId().toByteArray()).isEqualTo(TRACE_ID_BYTES); + assertThat(protoSpan.getSpanId().toByteArray()).isEqualTo(SPAN_ID_BYTES); + assertThat(protoSpan.getFlags() & 0xff) + .isEqualTo((SPAN_CONTEXT.getTraceFlags().asByte() & 0xff)); + assertThat(SpanFlags.isKnownWhetherParentIsRemote(protoSpan.getFlags())).isTrue(); + assertThat(SpanFlags.isParentRemote(protoSpan.getFlags())).isFalse(); + assertThat(protoSpan.getTraceState()).isEqualTo(TRACE_STATE_VALUE); + assertThat(protoSpan.getParentSpanId().toByteArray()).isEqualTo(new byte[] {}); + assertThat(protoSpan.getName()).isEqualTo("GET /api/endpoint"); + assertThat(protoSpan.getKind()).isEqualTo(SPAN_KIND_SERVER); + assertThat(protoSpan.getStartTimeUnixNano()).isEqualTo(12345); + assertThat(protoSpan.getEndTimeUnixNano()).isEqualTo(12349); + assertThat(protoSpan.getAttributesList()) .containsOnly( KeyValue.newBuilder() .setKey("key") @@ -201,21 +248,124 @@ void toProtoSpan() { .addValues(AnyValue.newBuilder().setBoolValue(false).build()) .build()) .build()) + .build(), + KeyValue.newBuilder() + .setKey("bytes") + .setValue( + AnyValue.newBuilder() + .setBytesValue(ByteString.copyFrom(new byte[] {1, 2, 3})) + .build()) + .build(), + KeyValue.newBuilder().setKey("empty").setValue(AnyValue.newBuilder().build()).build(), + KeyValue.newBuilder() + .setKey("heterogeneousArray") + .setValue( + AnyValue.newBuilder() + .setArrayValue( + ArrayValue.newBuilder() + .addValues(AnyValue.newBuilder().setStringValue("string").build()) + .addValues(AnyValue.newBuilder().setIntValue(123).build()) + .build()) + .build()) + .build(), + KeyValue.newBuilder() + .setKey("map") + .setValue( + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + KeyValue.newBuilder() + .setKey("nested") + .setValue( + AnyValue.newBuilder().setStringValue("value").build()) + .build()) + .build()) + .build()) + .build(), + KeyValue.newBuilder() + .setKey("empty_string") + .setValue(AnyValue.newBuilder().setStringValue("").build()) + .build(), + KeyValue.newBuilder() + .setKey("false_value") + .setValue(AnyValue.newBuilder().setBoolValue(false).build()) + .build(), + KeyValue.newBuilder() + .setKey("zero_int") + .setValue(AnyValue.newBuilder().setIntValue(0).build()) + .build(), + KeyValue.newBuilder() + .setKey("zero_double") + .setValue(AnyValue.newBuilder().setDoubleValue(0.0).build()) + .build(), + KeyValue.newBuilder() + .setKey("empty_array") + .setValue( + AnyValue.newBuilder().setArrayValue(ArrayValue.newBuilder().build()).build()) + .build(), + KeyValue.newBuilder() + .setKey("empty_map") + .setValue( + AnyValue.newBuilder().setKvlistValue(KeyValueList.newBuilder().build()).build()) + .build(), + KeyValue.newBuilder() + .setKey("empty_bytes") + .setValue( + AnyValue.newBuilder().setBytesValue(ByteString.copyFrom(new byte[] {})).build()) .build()); - assertThat(span.getDroppedAttributesCount()).isEqualTo(1); - assertThat(span.getEventsList()) + assertThat(protoSpan.getDroppedAttributesCount()).isEqualTo(1); + assertThat(protoSpan.getEventsList()) .containsExactly( Span.Event.newBuilder().setTimeUnixNano(12347).setName("my_event").build()); - assertThat(span.getDroppedEventsCount()).isEqualTo(2); // 3 - 1 - assertThat(span.getLinksList()) + assertThat(protoSpan.getDroppedEventsCount()).isEqualTo(2); // 3 - 1 + assertThat(protoSpan.getLinksList()) .containsExactly( Span.Link.newBuilder() .setTraceId(ByteString.copyFrom(TRACE_ID_BYTES)) .setSpanId(ByteString.copyFrom(SPAN_ID_BYTES)) + .setFlags( + (SPAN_CONTEXT.getTraceFlags().asByte() & 0xff) + | SpanFlags.getHasParentIsRemoteMask()) .setTraceState(encodeTraceState(SPAN_CONTEXT.getTraceState())) .build()); - assertThat(span.getDroppedLinksCount()).isEqualTo(1); // 2 - 1 - assertThat(span.getStatus()).isEqualTo(Status.newBuilder().setCode(STATUS_CODE_OK).build()); + assertThat(protoSpan.getDroppedLinksCount()).isEqualTo(1); // 2 - 1 + assertThat(protoSpan.getStatus()) + .isEqualTo(Status.newBuilder().setCode(STATUS_CODE_OK).build()); + } + + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpan_withRemoteParent(MarshalerSource marshalerSource) { + Span protoSpan = + parse( + Span.getDefaultInstance(), + marshalerSource.create( + TestSpanData.builder() + .setHasEnded(true) + .setSpanContext(SPAN_CONTEXT) + .setParentSpanContext(PARENT_SPAN_CONTEXT) + .setName("GET /api/endpoint") + .setKind(SpanKind.SERVER) + .setStartEpochNanos(12345) + .setEndEpochNanos(12349) + .setStatus(StatusData.ok()) + .build())); + + assertThat(protoSpan.getTraceId().toByteArray()).isEqualTo(TRACE_ID_BYTES); + assertThat(protoSpan.getSpanId().toByteArray()).isEqualTo(SPAN_ID_BYTES); + assertThat(protoSpan.getFlags() & 0xff) + .isEqualTo((SPAN_CONTEXT.getTraceFlags().asByte() & 0xff)); + assertThat(SpanFlags.isKnownWhetherParentIsRemote(protoSpan.getFlags())).isTrue(); + assertThat(SpanFlags.isParentRemote(protoSpan.getFlags())).isTrue(); + assertThat(protoSpan.getTraceState()).isEqualTo(TRACE_STATE_VALUE); + assertThat(protoSpan.getParentSpanId().toByteArray()).isEqualTo(PARENT_SPAN_ID_BYTES); + assertThat(protoSpan.getName()).isEqualTo("GET /api/endpoint"); + assertThat(protoSpan.getKind()).isEqualTo(SPAN_KIND_SERVER); + assertThat(protoSpan.getStartTimeUnixNano()).isEqualTo(12345); + assertThat(protoSpan.getEndTimeUnixNano()).isEqualTo(12349); + assertThat(protoSpan.getStatus()) + .isEqualTo(Status.newBuilder().setCode(STATUS_CODE_OK).build()); } @Test @@ -232,9 +382,10 @@ void toProtoSpanKind() { .isEqualTo(io.opentelemetry.proto.trace.v1.internal.Span.SpanKind.SPAN_KIND_CONSUMER); } - @Test - void toProtoStatus() { - assertThat(parse(Status.getDefaultInstance(), SpanStatusMarshaler.create(StatusData.unset()))) + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoStatus(MarshalerSource marshalerSource) { + assertThat(parse(Status.getDefaultInstance(), marshalerSource.create(StatusData.unset()))) .isEqualTo(Status.newBuilder().setCode(STATUS_CODE_UNSET).build()); assertThat( parse( @@ -253,12 +404,13 @@ void toProtoStatus() { .isEqualTo(Status.newBuilder().setCode(STATUS_CODE_OK).setMessage("OK_OVERRIDE").build()); } - @Test - void toProtoSpanEvent_WithoutAttributes() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpanEvent_WithoutAttributes(MarshalerSource marshalerSource) { assertThat( parse( Span.Event.getDefaultInstance(), - SpanEventMarshaler.create( + marshalerSource.create( EventData.create(12345, "test_without_attributes", Attributes.empty())))) .isEqualTo( Span.Event.newBuilder() @@ -267,12 +419,13 @@ void toProtoSpanEvent_WithoutAttributes() { .build()); } - @Test - void toProtoSpanEvent_WithAttributes() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpanEvent_WithAttributes(MarshalerSource marshalerSource) { assertThat( parse( Span.Event.getDefaultInstance(), - SpanEventMarshaler.create( + marshalerSource.create( EventData.create( 12345, "test_with_attributes", @@ -291,32 +444,57 @@ void toProtoSpanEvent_WithAttributes() { .build()); } - @Test - void toProtoSpanLink_WithoutAttributes() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpanLink_WithoutAttributes(MarshalerSource marshalerSource) { assertThat( parse( Span.Link.getDefaultInstance(), - SpanLinkMarshaler.create(LinkData.create(SPAN_CONTEXT)))) + marshalerSource.create(LinkData.create(SPAN_CONTEXT)))) .isEqualTo( Span.Link.newBuilder() .setTraceId(ByteString.copyFrom(TRACE_ID_BYTES)) .setSpanId(ByteString.copyFrom(SPAN_ID_BYTES)) + .setFlags( + (SPAN_CONTEXT.getTraceFlags().asByte() & 0xff) + | SpanFlags.getHasParentIsRemoteMask()) .setTraceState(TRACE_STATE_VALUE) .build()); } - @Test - void toProtoSpanLink_WithAttributes() { + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpanLink_WithRemoteContext(MarshalerSource marshalerSource) { + assertThat( + parse( + Span.Link.getDefaultInstance(), + marshalerSource.create(LinkData.create(PARENT_SPAN_CONTEXT)))) + .isEqualTo( + Span.Link.newBuilder() + .setTraceId(ByteString.copyFrom(TRACE_ID_BYTES)) + .setSpanId(ByteString.copyFrom(PARENT_SPAN_ID_BYTES)) + .setFlags( + (SPAN_CONTEXT.getTraceFlags().asByte() & 0xff) + | SpanFlags.getParentIsRemoteMask()) + .build()); + } + + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpanLink_WithAttributes(MarshalerSource marshalerSource) { assertThat( parse( Span.Link.getDefaultInstance(), - SpanLinkMarshaler.create( + marshalerSource.create( LinkData.create( SPAN_CONTEXT, Attributes.of(stringKey("key_string"), "string"), 5)))) .isEqualTo( Span.Link.newBuilder() .setTraceId(ByteString.copyFrom(TRACE_ID_BYTES)) .setSpanId(ByteString.copyFrom(SPAN_ID_BYTES)) + .setFlags( + (SPAN_CONTEXT.getTraceFlags().asByte() & 0xff) + | SpanFlags.getHasParentIsRemoteMask()) .setTraceState(TRACE_STATE_VALUE) .addAttributes( KeyValue.newBuilder() @@ -327,6 +505,37 @@ void toProtoSpanLink_WithAttributes() { .build()); } + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoSpanLink_WithInvalidContext(MarshalerSource marshalerSource) { + SpanContext context = + SpanContext.createFromRemoteParent( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.getSampled(), + TraceState.builder().put("vendor", "value").build()); + assertThat(context.isValid()).isFalse(); + assertThat( + parse( + Span.Link.getDefaultInstance(), + marshalerSource.create( + LinkData.create(context, Attributes.of(stringKey("message.id"), "123"), 2)))) + .isEqualTo( + Span.Link.newBuilder() + .setTraceId(ByteString.copyFrom(new byte[16])) + .setSpanId(ByteString.copyFrom(new byte[8])) + .setFlags( + (TraceFlags.getSampled().asByte() & 0xff) | SpanFlags.getParentIsRemoteMask()) + .setTraceState("vendor=value") + .addAttributes( + KeyValue.newBuilder() + .setKey("message.id") + .setValue(AnyValue.newBuilder().setStringValue("123").build()) + .build()) + .setDroppedAttributesCount(1) + .build()); + } + @SuppressWarnings("unchecked") private static T parse(T prototype, Marshaler marshaler) { byte[] serialized = toByteArray(marshaler); @@ -398,7 +607,7 @@ private static void fixLinkJsonIds(Span.Link.Builder link) { private static ByteString toHex(ByteString hexReadAsBase64) { String hex = Base64.getEncoder().encodeToString(hexReadAsBase64.toByteArray()).toLowerCase(Locale.ROOT); - return ByteString.copyFrom(OtelEncodingUtils.bytesFromBase16(hex, hex.length())); + return ByteString.copyFrom(Base16EncodingUtils.bytesFromBase16(hex, hex.length())); } private static byte[] toByteArray(Marshaler marshaler) { @@ -412,7 +621,6 @@ private static byte[] toByteArray(Marshaler marshaler) { } private static String toJson(Marshaler marshaler) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { marshaler.writeJsonTo(bos); @@ -421,4 +629,75 @@ private static String toJson(Marshaler marshaler) { } return new String(bos.toByteArray(), StandardCharsets.UTF_8); } + + private static Marshaler createMarshaler(StatelessMarshaler marshaler, T data) { + return new Marshaler() { + private final MarshalerContext context = new MarshalerContext(); + private final int size = marshaler.getBinarySerializedSize(data, context); + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + context.resetReadIndex(); + marshaler.writeTo(output, data, context); + } + }; + } + + private enum MarshalerSource { + STATEFUL_MARSHALER { + @Override + Marshaler create(SpanData spanData) { + return SpanMarshaler.create(spanData); + } + + @Override + Marshaler create(StatusData statusData) { + return SpanStatusMarshaler.create(statusData); + } + + @Override + Marshaler create(EventData eventData) { + return SpanEventMarshaler.create(eventData); + } + + @Override + Marshaler create(LinkData linkData) { + return SpanLinkMarshaler.create(linkData); + } + }, + STATELESS_MARSHALER { + @Override + Marshaler create(SpanData spanData) { + return createMarshaler(SpanStatelessMarshaler.INSTANCE, spanData); + } + + @Override + Marshaler create(StatusData statusData) { + return createMarshaler(SpanStatusStatelessMarshaler.INSTANCE, statusData); + } + + @Override + Marshaler create(EventData eventData) { + return createMarshaler(SpanEventStatelessMarshaler.INSTANCE, eventData); + } + + @Override + Marshaler create(LinkData linkData) { + return createMarshaler(SpanLinkStatelessMarshaler.INSTANCE, linkData); + } + }; + + abstract Marshaler create(SpanData spanData); + + abstract Marshaler create(StatusData statusData); + + abstract Marshaler create(EventData eventData); + + abstract Marshaler create(LinkData linkData); + } } diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryInterceptorTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryInterceptorTest.java deleted file mode 100644 index ac9a369f107..00000000000 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryInterceptorTest.java +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doNothing; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; -import static org.mockito.internal.verification.VerificationModeFactory.times; - -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; -import java.io.IOException; -import java.net.SocketTimeoutException; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class RetryInterceptorTest { - - @RegisterExtension static final MockWebServerExtension server = new MockWebServerExtension(); - - @Mock private RetryInterceptor.Sleeper sleeper; - @Mock private RetryInterceptor.BoundedLongGenerator random; - private Function isRetryableException; - - private RetryInterceptor retrier; - private OkHttpClient client; - - @BeforeEach - void setUp() { - // Note: cannot replace this with lambda or method reference because we need to spy on it - isRetryableException = - spy( - new Function() { - @Override - public Boolean apply(IOException exception) { - return RetryInterceptor.isRetryableException(exception); - } - }); - retrier = - new RetryInterceptor( - RetryPolicy.builder() - .setBackoffMultiplier(1.6) - .setInitialBackoff(Duration.ofSeconds(1)) - .setMaxBackoff(Duration.ofSeconds(2)) - .setMaxAttempts(5) - .build(), - r -> !r.isSuccessful(), - isRetryableException, - sleeper, - random); - client = new OkHttpClient.Builder().addInterceptor(retrier).build(); - } - - @Test - void noRetry() throws Exception { - server.enqueue(HttpResponse.of(HttpStatus.OK)); - - try (Response response = sendRequest()) { - assertThat(response.isSuccessful()).isTrue(); - } - - verifyNoInteractions(random); - verifyNoInteractions(sleeper); - } - - @ParameterizedTest - // Test is mostly same for 5 or more attempts since it's the max. We check the backoff timings and - // handling of max attempts by checking both. - @ValueSource(ints = {5, 6}) - void backsOff(int attempts) throws Exception { - succeedOnAttempt(attempts); - - // Will backoff 4 times - when(random.get((long) (TimeUnit.SECONDS.toNanos(1) * Math.pow(1.6, 0)))).thenReturn(100L); - when(random.get((long) (TimeUnit.SECONDS.toNanos(1) * Math.pow(1.6, 1)))).thenReturn(50L); - // Capped - when(random.get(TimeUnit.SECONDS.toNanos(2))).thenReturn(500L).thenReturn(510L); - - doNothing().when(sleeper).sleep(100); - doNothing().when(sleeper).sleep(50); - doNothing().when(sleeper).sleep(500); - doNothing().when(sleeper).sleep(510); - - try (Response response = sendRequest()) { - if (attempts <= 5) { - assertThat(response.isSuccessful()).isTrue(); - } else { - assertThat(response.isSuccessful()).isFalse(); - } - } - - for (int i = 0; i < 5; i++) { - server.takeRequest(0, TimeUnit.NANOSECONDS); - } - } - - @Test - void interrupted() throws Exception { - succeedOnAttempt(5); - - // Backs off twice, second is interrupted - when(random.get((long) (TimeUnit.SECONDS.toNanos(1) * Math.pow(1.6, 0)))).thenReturn(100L); - when(random.get((long) (TimeUnit.SECONDS.toNanos(1) * Math.pow(1.6, 1)))).thenReturn(50L); - - doNothing().when(sleeper).sleep(100); - doThrow(new InterruptedException()).when(sleeper).sleep(50); - - try (Response response = sendRequest()) { - assertThat(response.isSuccessful()).isFalse(); - } - - for (int i = 0; i < 2; i++) { - server.takeRequest(0, TimeUnit.NANOSECONDS); - } - } - - @Test - void connectTimeout() throws Exception { - client = connectTimeoutClient(); - when(random.get(anyLong())).thenReturn(1L); - doNothing().when(sleeper).sleep(anyLong()); - - // Connecting to a non-routable IP address to trigger connection timeout - assertThatThrownBy( - () -> - client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) - .isInstanceOf(SocketTimeoutException.class); - - verify(isRetryableException, times(5)).apply(any()); - // Should retry maxAttempts, and sleep maxAttempts - 1 times - verify(sleeper, times(4)).sleep(anyLong()); - } - - @Test - void nonRetryableException() throws InterruptedException { - client = connectTimeoutClient(); - // Override isRetryableException so that no exception is retryable - when(isRetryableException.apply(any())).thenReturn(false); - - // Connecting to a non-routable IP address to trigger connection timeout - assertThatThrownBy( - () -> - client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) - .isInstanceOf(SocketTimeoutException.class); - - verify(isRetryableException, times(1)).apply(any()); - verify(sleeper, never()).sleep(anyLong()); - } - - private OkHttpClient connectTimeoutClient() { - return new OkHttpClient.Builder() - .connectTimeout(Duration.ofMillis(10)) - .addInterceptor(retrier) - .build(); - } - - @Test - void isRetryableException() { - // Should retry on connection timeouts, where error message is "Connect timed out" or "connect - // timed out" - assertThat( - RetryInterceptor.isRetryableException(new SocketTimeoutException("Connect timed out"))) - .isTrue(); - assertThat( - RetryInterceptor.isRetryableException(new SocketTimeoutException("connect timed out"))) - .isTrue(); - // Shouldn't retry on read timeouts, where error message is "Read timed out" - assertThat(RetryInterceptor.isRetryableException(new SocketTimeoutException("Read timed out"))) - .isFalse(); - // Shouldn't retry on write timeouts, where error message is "timeout", or other IOException - assertThat(RetryInterceptor.isRetryableException(new SocketTimeoutException("timeout"))) - .isFalse(); - assertThat(RetryInterceptor.isRetryableException(new SocketTimeoutException())).isTrue(); - assertThat(RetryInterceptor.isRetryableException(new IOException("error"))).isFalse(); - } - - private Response sendRequest() throws IOException { - return client.newCall(new Request.Builder().url(server.httpUri().toString()).build()).execute(); - } - - private static void succeedOnAttempt(int attempt) { - for (int i = 1; i < attempt; i++) { - server.enqueue(HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR)); - } - server.enqueue(HttpResponse.of(HttpStatus.OK)); - } -} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryPolicyTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryPolicyTest.java deleted file mode 100644 index f54926ca769..00000000000 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryPolicyTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import java.time.Duration; -import org.junit.jupiter.api.Test; - -class RetryPolicyTest { - - @Test - void defaultRetryPolicy() { - assertThat(RetryPolicy.getDefault().getMaxAttempts()).isEqualTo(5); - assertThat(RetryPolicy.getDefault().getInitialBackoff()).isEqualTo(Duration.ofSeconds(1)); - assertThat(RetryPolicy.getDefault().getMaxBackoff()).isEqualTo(Duration.ofSeconds(5)); - assertThat(RetryPolicy.getDefault().getBackoffMultiplier()).isEqualTo(1.5); - } - - @Test - void build() { - RetryPolicy retryPolicy = - RetryPolicy.builder() - .setMaxAttempts(2) - .setInitialBackoff(Duration.ofMillis(2)) - .setMaxBackoff(Duration.ofSeconds(1)) - .setBackoffMultiplier(1.1) - .build(); - assertThat(retryPolicy.getMaxAttempts()).isEqualTo(2); - assertThat(retryPolicy.getInitialBackoff()).isEqualTo(Duration.ofMillis(2)); - assertThat(retryPolicy.getMaxBackoff()).isEqualTo(Duration.ofSeconds(1)); - assertThat(retryPolicy.getBackoffMultiplier()).isEqualTo(1.1); - } - - @Test - void invalidRetryPolicy() { - assertThatThrownBy(() -> RetryPolicy.builder().setMaxAttempts(1)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> RetryPolicy.builder().setMaxAttempts(6)) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> RetryPolicy.builder().setInitialBackoff(null)) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy(() -> RetryPolicy.builder().setInitialBackoff(Duration.ofMillis(0))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> RetryPolicy.builder().setMaxBackoff(null)) - .isInstanceOf(NullPointerException.class); - assertThatThrownBy(() -> RetryPolicy.builder().setMaxBackoff(Duration.ofMillis(0))) - .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> RetryPolicy.builder().setBackoffMultiplier(0)) - .isInstanceOf(IllegalArgumentException.class); - } -} diff --git a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryUtilTest.java b/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryUtilTest.java deleted file mode 100644 index 039e6f33db8..00000000000 --- a/exporters/otlp/common/src/test/java/io/opentelemetry/exporter/internal/retry/RetryUtilTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.internal.retry; - -import static org.assertj.core.api.Assertions.as; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporterBuilder; -import java.net.URI; -import java.net.URISyntaxException; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.jupiter.api.Test; - -class RetryUtilTest { - - @Test - void setRetryPolicyOnDelegate_DefaultGrpcExporterBuilder() throws URISyntaxException { - RetryPolicy retryPolicy = RetryPolicy.getDefault(); - DefaultGrpcExporterBuilder builder = - new DefaultGrpcExporterBuilder<>( - "otlp", "test", unused -> null, 0, new URI("http://localhost"), "test"); - - RetryUtil.setRetryPolicyOnDelegate(new WithDelegate(builder), retryPolicy); - - assertThat(builder) - .extracting("retryPolicy", as(InstanceOfAssertFactories.type(RetryPolicy.class))) - .isEqualTo(retryPolicy); - } - - @Test - void setRetryPolicyOnDelegate_OkHttpGrpcExporterBuilder() throws URISyntaxException { - RetryPolicy retryPolicy = RetryPolicy.getDefault(); - OkHttpGrpcExporterBuilder builder = - new OkHttpGrpcExporterBuilder<>("otlp", "test", "/test", 0, new URI("http://localhost")); - - RetryUtil.setRetryPolicyOnDelegate(new WithDelegate(builder), retryPolicy); - - assertThat(builder) - .extracting("retryPolicy", as(InstanceOfAssertFactories.type(RetryPolicy.class))) - .isEqualTo(retryPolicy); - } - - @Test - void setRetryPolicyOnDelegate_OkHttpExporterBuilder() { - RetryPolicy retryPolicy = RetryPolicy.getDefault(); - OkHttpExporterBuilder builder = - new OkHttpExporterBuilder<>("otlp", "test", "http://localhost:4318/test"); - RetryUtil.setRetryPolicyOnDelegate(new WithDelegate(builder), retryPolicy); - - assertThat(builder) - .extracting("retryPolicy", as(InstanceOfAssertFactories.type(RetryPolicy.class))) - .isEqualTo(retryPolicy); - } - - @Test - void setRetryPolicyOnDelegate_InvalidUsage() { - assertThatThrownBy( - () -> RetryUtil.setRetryPolicyOnDelegate(new Object(), RetryPolicy.getDefault())) - .hasMessageContaining("Unable to access delegate reflectively"); - assertThatThrownBy( - () -> - RetryUtil.setRetryPolicyOnDelegate( - new WithDelegate(new Object()), RetryPolicy.getDefault())) - .hasMessageContaining( - "delegate field is not type DefaultGrpcExporterBuilder or OkHttpGrpcExporterBuilder"); - } - - @SuppressWarnings({"UnusedVariable", "FieldCanBeLocal"}) - private static class WithDelegate { - private final Object delegate; - - private WithDelegate(Object delegate) { - this.delegate = delegate; - } - } -} diff --git a/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java b/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java new file mode 100644 index 00000000000..1b5e92fba0c --- /dev/null +++ b/exporters/otlp/common/src/testIncubating/java/io/opentelemetry/exporter/internal/otlp/logs/LogsRequestMarshalerIncubatingTest.java @@ -0,0 +1,305 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.internal.otlp.logs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.impl.Base16EncodingUtils; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerContext; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.marshal.StatelessMarshaler; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.ArrayValue; +import io.opentelemetry.proto.common.v1.KeyValueList; +import io.opentelemetry.proto.logs.v1.LogRecord; +import io.opentelemetry.proto.logs.v1.ResourceLogs; +import io.opentelemetry.proto.logs.v1.ScopeLogs; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +class LogsRequestMarshalerIncubatingTest { + private static final byte[] TRACE_ID_BYTES = + new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4}; + private static final String TRACE_ID = TraceId.fromBytes(TRACE_ID_BYTES); + private static final byte[] SPAN_ID_BYTES = new byte[] {0, 0, 0, 0, 4, 3, 2, 1}; + private static final String SPAN_ID = SpanId.fromBytes(SPAN_ID_BYTES); + private static final String EVENT_NAME = "hello"; + private static final String BODY = "Hello world from this log..."; + + // Marshalers should not throw if the incubator is on the class path, but are called with + // LogRecordData instances which are not ExtendedLogRecordData. + // See: https://github.com/open-telemetry/opentelemetry-java/issues/7363 + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoLogRecord_NotExtendedLogRecordData_DoesNotThrow(MarshalerSource marshalerSource) { + assertThatCode(() -> + parse( + LogRecord.getDefaultInstance(), + marshalerSource.create(TestLogRecordData.builder().build()))) + .doesNotThrowAnyException(); + } + + @ParameterizedTest + @EnumSource(MarshalerSource.class) + void toProtoLogRecord(MarshalerSource marshalerSource) { + LogRecord logRecord = + parse( + LogRecord.getDefaultInstance(), + marshalerSource.create( + TestLogRecordData.builder() + .setResource( + Resource.create(Attributes.builder().put("testKey", "testValue").build())) + .setInstrumentationScopeInfo( + InstrumentationScopeInfo.builder("instrumentation").setVersion("1").build()) + .setBody(BODY) + .setSeverity(Severity.INFO) + .setSeverityText("INFO") + .setSpanContext( + SpanContext.create( + TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) + .setTotalAttributeCount(11) + .setTimestamp(12345, TimeUnit.NANOSECONDS) + .setObservedTimestamp(6789, TimeUnit.NANOSECONDS) + .setEventName(EVENT_NAME) + .setAttributes( + Attributes.builder() + .put("str_key", "str_value") + .put("str_arr_key", "str_value1", "str_value2") + .put("bool_key", true) + .put("bool_arr_key", true, false) + .put("double_key", 1.1) + .put("double_arr_key", 1.1, 2.2) + .put("int_key", 1) + .put("int_arr_key", 1, 2) + .put( + "value_key", + Value.of( + KeyValue.of("bool_key", Value.of(true)), + KeyValue.of("double_key", Value.of(1.1)), + KeyValue.of("int_key", Value.of(1)), + KeyValue.of( + "value_key", + Value.of(KeyValue.of("str_key", Value.of("str_value")))), + KeyValue.of("str_key", Value.of("str_value")))) + .build()) + .build())); + + assertThat(logRecord.getTraceId().toByteArray()).isEqualTo(TRACE_ID_BYTES); + assertThat(logRecord.getSpanId().toByteArray()).isEqualTo(SPAN_ID_BYTES); + assertThat(logRecord.getSeverityText()).isEqualTo("INFO"); + + assertThat(logRecord.getBody()).isEqualTo(AnyValue.newBuilder().setStringValue(BODY).build()); + assertThat(logRecord.getDroppedAttributesCount()).isEqualTo(2); + assertThat(logRecord.getTimeUnixNano()).isEqualTo(12345); + assertThat(logRecord.getObservedTimeUnixNano()).isEqualTo(6789); + assertThat(logRecord.getEventName()).isEqualTo(EVENT_NAME); + assertThat(logRecord.getAttributesList()) + .containsExactlyInAnyOrder( + keyValue("str_key", anyValue("str_value")), + keyValue( + "str_arr_key", + anyValue(Arrays.asList(anyValue("str_value1"), anyValue("str_value2")))), + keyValue("bool_key", anyValue(true)), + keyValue("bool_arr_key", anyValue(Arrays.asList(anyValue(true), anyValue(false)))), + keyValue("double_key", anyValue(1.1)), + keyValue("double_arr_key", anyValue(Arrays.asList(anyValue(1.1), anyValue(2.2)))), + keyValue("int_key", anyValue(1)), + keyValue("int_arr_key", anyValue(Arrays.asList(anyValue(1), anyValue(2)))), + keyValue( + "value_key", + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues(keyValue("bool_key", anyValue(true))) + .addValues(keyValue("double_key", anyValue(1.1))) + .addValues(keyValue("int_key", anyValue(1))) + .addValues( + keyValue( + "value_key", + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + keyValue("str_key", anyValue("str_value"))) + .build()) + .build())) + .addValues(keyValue("str_key", anyValue("str_value"))) + .build()) + .build())); + } + + private static AnyValue anyValue(String value) { + return AnyValue.newBuilder().setStringValue(value).build(); + } + + private static AnyValue anyValue(long value) { + return AnyValue.newBuilder().setIntValue(value).build(); + } + + private static AnyValue anyValue(double value) { + return AnyValue.newBuilder().setDoubleValue(value).build(); + } + + private static AnyValue anyValue(boolean value) { + return AnyValue.newBuilder().setBoolValue(value).build(); + } + + private static AnyValue anyValue(List value) { + return AnyValue.newBuilder() + .setArrayValue(ArrayValue.newBuilder().addAllValues(value).build()) + .build(); + } + + private static io.opentelemetry.proto.common.v1.KeyValue keyValue(String key, AnyValue anyValue) { + return io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey(key) + .setValue(anyValue) + .build(); + } + + @SuppressWarnings("unchecked") + private static T parse(T prototype, Marshaler marshaler) { + byte[] serialized = toByteArray(marshaler); + T result; + try { + result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + // Our marshaler should produce the exact same length of serialized output (for example, field + // default values are not outputted), so we check that here. The output itself may have slightly + // different ordering, mostly due to the way we don't output oneof values in field order all the + // tieme. If the lengths are equal and the resulting protos are equal, the marshaling is + // guaranteed to be valid. + assertThat(result.getSerializedSize()).isEqualTo(serialized.length); + + // We don't compare JSON strings due to some differences (particularly serializing enums as + // numbers instead of names). This may improve in the future but what matters is what we produce + // can be parsed. + Message.Builder builder = prototype.newBuilderForType(); + try { + String json = toJson(marshaler); + JsonFormat.parser().merge(json, builder); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + + // Hackily swap out "hex as base64" decoded IDs with correct ones since no JSON protobuf + // libraries currently support customizing on the parse side. + if (result instanceof LogRecord) { + fixSpanJsonIds((LogRecord.Builder) builder); + } + + if (result instanceof ResourceLogs) { + ResourceLogs.Builder fixed = (ResourceLogs.Builder) builder; + for (ScopeLogs.Builder ill : fixed.getScopeLogsBuilderList()) { + for (LogRecord.Builder span : ill.getLogRecordsBuilderList()) { + fixSpanJsonIds(span); + } + } + } + + assertThat(builder.build()).isEqualTo(result); + + return result; + } + + private static void fixSpanJsonIds(LogRecord.Builder span) { + span.setTraceId(toHex(span.getTraceId())); + span.setSpanId(toHex(span.getSpanId())); + } + + @SuppressWarnings("UnusedMethod") + private static ByteString toHex(ByteString hexReadAsBase64) { + String hex = + Base64.getEncoder().encodeToString(hexReadAsBase64.toByteArray()).toLowerCase(Locale.ROOT); + return ByteString.copyFrom(Base16EncodingUtils.bytesFromBase16(hex, hex.length())); + } + + private static byte[] toByteArray(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return bos.toByteArray(); + } + + private static String toJson(Marshaler marshaler) { + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new String(bos.toByteArray(), StandardCharsets.UTF_8); + } + + private static Marshaler createMarshaler(StatelessMarshaler marshaler, T data) { + return new Marshaler() { + private final MarshalerContext context = new MarshalerContext(); + private final int size = marshaler.getBinarySerializedSize(data, context); + + @Override + public int getBinarySerializedSize() { + return size; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + context.resetReadIndex(); + marshaler.writeTo(output, data, context); + } + }; + } + + private enum MarshalerSource { + MARSHALER { + @Override + Marshaler create(LogRecordData logData) { + return LogMarshaler.create(logData); + } + }, + LOW_ALLOCATION_MARSHALER { + @Override + Marshaler create(LogRecordData logData) { + return createMarshaler(LogStatelessMarshaler.INSTANCE, logData); + } + }; + + abstract Marshaler create(LogRecordData logData); + } +} diff --git a/exporters/otlp/logs/build.gradle.kts b/exporters/otlp/logs/build.gradle.kts deleted file mode 100644 index 166a639bfac..00000000000 --- a/exporters/otlp/logs/build.gradle.kts +++ /dev/null @@ -1,54 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Protocol Logs Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.logs") - -dependencies { - api(project(":sdk:logs")) - - implementation(project(":exporters:otlp:common")) - - compileOnly("io.grpc:grpc-stub") - - testImplementation(project(":exporters:otlp:testing-internal")) -} - -testing { - suites { - val testGrpcNetty by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-netty") - implementation("io.grpc:grpc-stub") - } - } - val testGrpcNettyShaded by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-netty-shaded") - implementation("io.grpc:grpc-stub") - } - } - val testGrpcOkhttp by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-okhttp") - implementation("io.grpc:grpc-stub") - } - } - } -} - -tasks { - named("check") { - dependsOn(testing.suites) - } -} diff --git a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/MarshalerLogsServiceGrpc.java b/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/MarshalerLogsServiceGrpc.java deleted file mode 100644 index c2a952e8fdc..00000000000 --- a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/MarshalerLogsServiceGrpc.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import static io.grpc.MethodDescriptor.generateFullMethodName; - -import com.google.common.util.concurrent.ListenableFuture; -import io.grpc.CallOptions; -import io.grpc.Channel; -import io.grpc.MethodDescriptor; -import io.grpc.stub.ClientCalls; -import io.opentelemetry.exporter.internal.grpc.MarshalerInputStream; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.otlp.logs.LogsRequestMarshaler; -import java.io.InputStream; - -// Adapted from the protoc generated code for LogsServiceGrpc. -final class MarshalerLogsServiceGrpc { - - private static final String SERVICE_NAME = "opentelemetry.proto.collector.logs.v1.LogsService"; - - private static final MethodDescriptor.Marshaller REQUEST_MARSHALLER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(LogsRequestMarshaler value) { - return new MarshalerInputStream(value); - } - - @Override - public LogsRequestMarshaler parse(InputStream stream) { - throw new UnsupportedOperationException("Only for serializing"); - } - }; - - private static final MethodDescriptor.Marshaller RESPONSE_MARSHALER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(ExportLogsServiceResponse value) { - throw new UnsupportedOperationException("Only for parsing"); - } - - @Override - public ExportLogsServiceResponse parse(InputStream stream) { - return ExportLogsServiceResponse.INSTANCE; - } - }; - - private static final MethodDescriptor - getExportMethod = - MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.UNARY) - .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Export")) - .setRequestMarshaller(REQUEST_MARSHALLER) - .setResponseMarshaller(RESPONSE_MARSHALER) - .build(); - - static LogsServiceFutureStub newFutureStub(Channel channel) { - return LogsServiceFutureStub.newStub(LogsServiceFutureStub::new, channel); - } - - static final class LogsServiceFutureStub - extends MarshalerServiceStub< - LogsRequestMarshaler, ExportLogsServiceResponse, LogsServiceFutureStub> { - private LogsServiceFutureStub(Channel channel, CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected MarshalerLogsServiceGrpc.LogsServiceFutureStub build( - Channel channel, CallOptions callOptions) { - return new MarshalerLogsServiceGrpc.LogsServiceFutureStub(channel, callOptions); - } - - @Override - public ListenableFuture export(LogsRequestMarshaler request) { - return ClientCalls.futureUnaryCall( - getChannel().newCall(getExportMethod, getCallOptions()), request); - } - } - - private MarshalerLogsServiceGrpc() {} -} diff --git a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporter.java b/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporter.java deleted file mode 100644 index 089bdb80c21..00000000000 --- a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporter.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.otlp.logs.LogsRequestMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import java.util.Collection; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports logs using OTLP via gRPC, using OpenTelemetry's protobuf model. */ -@ThreadSafe -public final class OtlpGrpcLogExporter implements LogExporter { - - private final GrpcExporter delegate; - - /** - * Returns a new {@link OtlpGrpcLogExporter} reading the configuration values from the environment - * and from system properties. System properties override values defined in the environment. If a - * configuration value is missing, it uses the default value. - * - * @return a new {@link OtlpGrpcLogExporter} instance. - */ - public static OtlpGrpcLogExporter getDefault() { - return builder().build(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static OtlpGrpcLogExporterBuilder builder() { - return new OtlpGrpcLogExporterBuilder(); - } - - OtlpGrpcLogExporter(GrpcExporter delegate) { - this.delegate = delegate; - } - - /** - * Submits all the given logs in a single batch to the OpenTelemetry collector. - * - * @param logs the list of sampled logs to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection logs) { - LogsRequestMarshaler request = LogsRequestMarshaler.create(logs); - return delegate.export(request, logs.size()); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately - * cancelled. - */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } -} diff --git a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporterBuilder.java b/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporterBuilder.java deleted file mode 100644 index 18369abb9d4..00000000000 --- a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporterBuilder.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.grpc.ManagedChannel; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.grpc.GrpcExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.logs.LogsRequestMarshaler; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder for {@link OtlpGrpcLogExporter}. */ -public final class OtlpGrpcLogExporterBuilder { - - private static final String GRPC_SERVICE_NAME = - "opentelemetry.proto.collector.logs.v1.LogsService"; - // Visible for testing - static final String GRPC_ENDPOINT_PATH = "/" + GRPC_SERVICE_NAME + "/Export"; - - private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; - private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); - private static final long DEFAULT_TIMEOUT_SECS = 10; - - // Visible for testing - final GrpcExporterBuilder delegate; - - OtlpGrpcLogExporterBuilder() { - delegate = - GrpcExporter.builder( - "otlp", - "log", - DEFAULT_TIMEOUT_SECS, - DEFAULT_ENDPOINT, - () -> MarshalerLogsServiceGrpc::newFutureStub, - GRPC_SERVICE_NAME, - GRPC_ENDPOINT_PATH); - } - - /** - * Sets the managed chanel to use when communicating with the backend. Takes precedence over - * {@link #setEndpoint(String)} if both are called. - * - * @param channel the channel to use - * @return this builder's instance - * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the - * methods on this builder, please file an issue to let us know what it is. - */ - @Deprecated - public OtlpGrpcLogExporterBuilder setChannel(ManagedChannel channel) { - delegate.setChannel(channel); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, - * defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpGrpcLogExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of logs. If unset, - * defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpGrpcLogExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - delegate.setTimeout(timeout); - return this; - } - - /** - * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The - * endpoint must start with either http:// or https://. - */ - public OtlpGrpcLogExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the method used to compress payloads. If unset, compression is disabled. Currently - * supported compression methods include "gzip" and "none". - */ - public OtlpGrpcLogExporterBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - delegate.setCompression(compressionMethod); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public OtlpGrpcLogExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** - * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled. - */ - public OtlpGrpcLogExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Add header to request. Optional. Applicable only if {@link - * OtlpGrpcLogExporterBuilder#setChannel(ManagedChannel)} is not used to set channel. - * - * @param key header key - * @param value header value - * @return this builder's instance - */ - public OtlpGrpcLogExporterBuilder addHeader(String key, String value) { - delegate.addHeader(key, value); - return this; - } - - /** - * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, metrics - * will not be collected. - */ - public OtlpGrpcLogExporterBuilder setMeterProvider(MeterProvider meterProvider) { - requireNonNull(meterProvider, "meterProvider"); - delegate.setMeterProvider(meterProvider); - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance - */ - public OtlpGrpcLogExporter build() { - return new OtlpGrpcLogExporter(delegate.build()); - } -} diff --git a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/package-info.java b/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/package-info.java deleted file mode 100644 index 218c6860905..00000000000 --- a/exporters/otlp/logs/src/main/java/io/opentelemetry/exporter/otlp/logs/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** OpenTelemetry exporter which sends span data to OpenTelemetry collector via OTLP gRPC. */ -@ParametersAreNonnullByDefault -package io.opentelemetry.exporter.otlp.logs; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/otlp/logs/src/test/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporterTest.java b/exporters/otlp/logs/src/test/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporterTest.java deleted file mode 100644 index adf0bca498f..00000000000 --- a/exporters/otlp/logs/src/test/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcLogExporterTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.logs.v1.ResourceLogs; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcLogExporterTest extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcLogExporterTest() { - super("log", ResourceLogs.getDefaultInstance()); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpGrpcLogExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void usingOkHttp() { - assertThat(OtlpGrpcLogExporter.builder().delegate) - .isInstanceOf(OkHttpGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcLogExporterBuilder builder = OtlpGrpcLogExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected LogData generateFakeTelemetry() { - return LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setEpoch(Instant.now()) - .setSeverity(Severity.ERROR) - .setSeverityText("really severe") - .setBody("message") - .setAttributes(Attributes.builder().put("animal", "cat").build()) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceLogsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/logs/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyLogExporterTest.java b/exporters/otlp/logs/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyLogExporterTest.java deleted file mode 100644 index c9147874356..00000000000 --- a/exporters/otlp/logs/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyLogExporterTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.logs.v1.ResourceLogs; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettyLogExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcNettyLogExporterTest() { - super("log", ResourceLogs.getDefaultInstance()); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpGrpcLogExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcLogExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcLogExporterBuilder builder = OtlpGrpcLogExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected LogData generateFakeTelemetry() { - return LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setEpoch(Instant.now()) - .setSeverity(Severity.ERROR) - .setSeverityText("really severe") - .setBody("message") - .setAttributes(Attributes.builder().put("animal", "cat").build()) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceLogsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/logs/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyShadedLogExporterTest.java b/exporters/otlp/logs/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyShadedLogExporterTest.java deleted file mode 100644 index b30f8a4292a..00000000000 --- a/exporters/otlp/logs/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyShadedLogExporterTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.logs.v1.ResourceLogs; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettyShadedLogExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcNettyShadedLogExporterTest() { - super("log", ResourceLogs.getDefaultInstance()); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcLogExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcLogExporterBuilder builder = OtlpGrpcLogExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected LogData generateFakeTelemetry() { - return LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setEpoch(Instant.now()) - .setSeverity(Severity.ERROR) - .setSeverityText("really severe") - .setBody("message") - .setAttributes(Attributes.builder().put("animal", "cat").build()) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceLogsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/logs/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyOkHttpLogExporterTest.java b/exporters/otlp/logs/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyOkHttpLogExporterTest.java deleted file mode 100644 index c2066a6e2f1..00000000000 --- a/exporters/otlp/logs/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/logs/OtlpGrpcNettyOkHttpLogExporterTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.logs; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.logs.ResourceLogsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.logs.v1.ResourceLogs; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.time.Instant; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettyOkHttpLogExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcNettyOkHttpLogExporterTest() { - super("log", ResourceLogs.getDefaultInstance()); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcLogExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcLogExporterBuilder builder = OtlpGrpcLogExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected LogData generateFakeTelemetry() { - return LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setEpoch(Instant.now()) - .setSeverity(Severity.ERROR) - .setSeverityText("really severe") - .setBody("message") - .setAttributes(Attributes.builder().put("animal", "cat").build()) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceLogsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/metrics/README.md b/exporters/otlp/metrics/README.md deleted file mode 100644 index a3b75a9b26f..00000000000 --- a/exporters/otlp/metrics/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenTelemetry - OTLP Metrics Exporter - gRPC - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry exporter, sending metrics data to OpenTelemetry collector via gRPC. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-metrics.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-metrics diff --git a/exporters/otlp/metrics/build.gradle.kts b/exporters/otlp/metrics/build.gradle.kts deleted file mode 100644 index 76c4ce872ff..00000000000 --- a/exporters/otlp/metrics/build.gradle.kts +++ /dev/null @@ -1,54 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Protocol Metrics Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.metrics") - -dependencies { - api(project(":sdk:metrics")) - - implementation(project(":exporters:otlp:common")) - - compileOnly("io.grpc:grpc-stub") - - testImplementation(project(":exporters:otlp:testing-internal")) -} - -testing { - suites { - val testGrpcNetty by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-netty") - implementation("io.grpc:grpc-stub") - } - } - val testGrpcNettyShaded by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-netty-shaded") - implementation("io.grpc:grpc-stub") - } - } - val testGrpcOkhttp by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-okhttp") - implementation("io.grpc:grpc-stub") - } - } - } -} - -tasks { - check { - dependsOn(testing.suites) - } -} diff --git a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/MarshalerMetricsServiceGrpc.java b/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/MarshalerMetricsServiceGrpc.java deleted file mode 100644 index 0ba134cc9b7..00000000000 --- a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/MarshalerMetricsServiceGrpc.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import static io.grpc.MethodDescriptor.generateFullMethodName; - -import com.google.common.util.concurrent.ListenableFuture; -import io.grpc.CallOptions; -import io.grpc.Channel; -import io.grpc.MethodDescriptor; -import io.grpc.stub.ClientCalls; -import io.opentelemetry.exporter.internal.grpc.MarshalerInputStream; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; -import java.io.InputStream; - -// Adapted from the protoc generated code for MetricsServiceGrpc. -final class MarshalerMetricsServiceGrpc { - - private static final String SERVICE_NAME = - "opentelemetry.proto.collector.metrics.v1.MetricsService"; - - private static final MethodDescriptor.Marshaller REQUEST_MARSHALLER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(MetricsRequestMarshaler value) { - return new MarshalerInputStream(value); - } - - @Override - public MetricsRequestMarshaler parse(InputStream stream) { - throw new UnsupportedOperationException("Only for serializing"); - } - }; - - private static final MethodDescriptor.Marshaller - RESPONSE_MARSHALER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(ExportMetricsServiceResponse value) { - throw new UnsupportedOperationException("Only for parsing"); - } - - @Override - public ExportMetricsServiceResponse parse(InputStream stream) { - return ExportMetricsServiceResponse.INSTANCE; - } - }; - - private static final MethodDescriptor - getExportMethod = - MethodDescriptor.newBuilder() - .setType(MethodDescriptor.MethodType.UNARY) - .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Export")) - .setRequestMarshaller(REQUEST_MARSHALLER) - .setResponseMarshaller(RESPONSE_MARSHALER) - .build(); - - static MetricsServiceFutureStub newFutureStub(Channel channel) { - return MetricsServiceFutureStub.newStub(MetricsServiceFutureStub::new, channel); - } - - static final class MetricsServiceFutureStub - extends MarshalerServiceStub< - MetricsRequestMarshaler, ExportMetricsServiceResponse, MetricsServiceFutureStub> { - private MetricsServiceFutureStub(Channel channel, CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected MarshalerMetricsServiceGrpc.MetricsServiceFutureStub build( - Channel channel, CallOptions callOptions) { - return new MarshalerMetricsServiceGrpc.MetricsServiceFutureStub(channel, callOptions); - } - - @Override - public ListenableFuture export(MetricsRequestMarshaler request) { - return ClientCalls.futureUnaryCall( - getChannel().newCall(getExportMethod, getCallOptions()), request); - } - } - - private MarshalerMetricsServiceGrpc() {} -} diff --git a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporter.java b/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporter.java deleted file mode 100644 index dee669af090..00000000000 --- a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporter.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import java.util.Collection; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports metrics using OTLP via gRPC, using OpenTelemetry's protobuf model. */ -@ThreadSafe -public final class OtlpGrpcMetricExporter implements MetricExporter { - - private final GrpcExporter delegate; - private final AggregationTemporalitySelector aggregationTemporalitySelector; - - /** - * Returns a new {@link OtlpGrpcMetricExporter} reading the configuration values from the - * environment and from system properties. System properties override values defined in the - * environment. If a configuration value is missing, it uses the default value. - * - * @return a new {@link OtlpGrpcMetricExporter} instance. - */ - public static OtlpGrpcMetricExporter getDefault() { - return builder().build(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static OtlpGrpcMetricExporterBuilder builder() { - return new OtlpGrpcMetricExporterBuilder(); - } - - OtlpGrpcMetricExporter( - GrpcExporter delegate, - AggregationTemporalitySelector aggregationTemporalitySelector) { - this.delegate = delegate; - this.aggregationTemporalitySelector = aggregationTemporalitySelector; - } - - @Override - public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); - } - - /** - * Submits all the given metrics in a single batch to the OpenTelemetry collector. - * - * @param metrics the list of Metrics to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection metrics) { - MetricsRequestMarshaler request = MetricsRequestMarshaler.create(metrics); - - return delegate.export(request, metrics.size()); - } - - /** - * The OTLP exporter does not batch metrics, so this method will immediately return with success. - * - * @return always Success - */ - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately - * cancelled. The channel is forcefully closed after a timeout. - */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } -} diff --git a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilder.java b/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilder.java deleted file mode 100644 index 75cf1b860c8..00000000000 --- a/exporters/otlp/metrics/src/main/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterBuilder.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.grpc.GrpcExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.metrics.MetricsRequestMarshaler; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder utility for this exporter. */ -public final class OtlpGrpcMetricExporterBuilder { - - private static final String GRPC_SERVICE_NAME = - "opentelemetry.proto.collector.metrics.v1.MetricsService"; - // Visible for testing - static final String GRPC_ENDPOINT_PATH = "/" + GRPC_SERVICE_NAME + "/Export"; - - private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; - private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); - private static final long DEFAULT_TIMEOUT_SECS = 10; - private static final AggregationTemporalitySelector DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = - AggregationTemporalitySelector.alwaysCumulative(); - - // Visible for testing - final GrpcExporterBuilder delegate; - - private AggregationTemporalitySelector aggregationTemporalitySelector = - DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; - - OtlpGrpcMetricExporterBuilder() { - delegate = - GrpcExporter.builder( - "otlp", - "metric", - DEFAULT_TIMEOUT_SECS, - DEFAULT_ENDPOINT, - () -> MarshalerMetricsServiceGrpc::newFutureStub, - GRPC_SERVICE_NAME, - GRPC_ENDPOINT_PATH); - } - - /** - * Sets the managed chanel to use when communicating with the backend. Takes precedence over - * {@link #setEndpoint(String)} if both are called. - * - * @param channel the channel to use - * @return this builder's instance - * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the - * methods on this builder, please file an issue to let us know what it is. - */ - @Deprecated - public OtlpGrpcMetricExporterBuilder setChannel(ManagedChannel channel) { - delegate.setChannel(channel); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of metrics. If - * unset, defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpGrpcMetricExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of metrics. If - * unset, defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpGrpcMetricExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - delegate.setTimeout(timeout); - return this; - } - - /** - * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The - * endpoint must start with either http:// or https://. - */ - public OtlpGrpcMetricExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the method used to compress payloads. If unset, compression is disabled. Currently - * supported compression methods include "gzip" and "none". - */ - public OtlpGrpcMetricExporterBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - delegate.setCompression(compressionMethod); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public OtlpGrpcMetricExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** - * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled. - */ - public OtlpGrpcMetricExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Add header to request. Optional. Applicable only if {@link - * OtlpGrpcMetricExporterBuilder#setChannel(ManagedChannel)} is not used to set channel. - * - * @param key header key - * @param value header value - * @return this builder's instance - */ - public OtlpGrpcMetricExporterBuilder addHeader(String key, String value) { - delegate.addHeader(key, value); - return this; - } - - /** - * Set the {@link AggregationTemporalitySelector} used for {@link - * MetricExporter#getAggregationTemporality(InstrumentType)}. - * - *

    If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}. - * - *

    {@link AggregationTemporalitySelector#deltaPreferred()} is a common configuration for delta - * backends. - */ - public OtlpGrpcMetricExporterBuilder setAggregationTemporalitySelector( - AggregationTemporalitySelector aggregationTemporalitySelector) { - requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector"); - this.aggregationTemporalitySelector = aggregationTemporalitySelector; - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance - */ - public OtlpGrpcMetricExporter build() { - return new OtlpGrpcMetricExporter(delegate.build(), aggregationTemporalitySelector); - } -} diff --git a/exporters/otlp/metrics/src/test/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java b/exporters/otlp/metrics/src/test/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java deleted file mode 100644 index e11a3147fdd..00000000000 --- a/exporters/otlp/metrics/src/test/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcMetricExporterTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.metrics.v1.ResourceMetrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcMetricExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcMetricExporterTest() { - super("metric", ResourceMetrics.getDefaultInstance()); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpGrpcMetricExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void usingOkHttp() { - assertThat(OtlpGrpcMetricExporter.builder().delegate) - .isInstanceOf(OkHttpGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcMetricExporterBuilder builder = OtlpGrpcMetricExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected MetricData generateFakeTelemetry() { - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + TimeUnit.MILLISECONDS.toNanos(900); - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - startNs, endNs, Attributes.of(stringKey("k"), "v"), 5)))); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceMetricsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/metrics/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyMetricExporterTest.java b/exporters/otlp/metrics/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyMetricExporterTest.java deleted file mode 100644 index 94f2d6e2976..00000000000 --- a/exporters/otlp/metrics/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyMetricExporterTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.metrics.v1.ResourceMetrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettyMetricExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcNettyMetricExporterTest() { - super("metric", ResourceMetrics.getDefaultInstance()); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpGrpcMetricExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcMetricExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcMetricExporterBuilder builder = OtlpGrpcMetricExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected MetricData generateFakeTelemetry() { - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + TimeUnit.MILLISECONDS.toNanos(900); - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - startNs, endNs, Attributes.of(stringKey("k"), "v"), 5)))); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceMetricsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/metrics/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyShadedMetricExporterTest.java b/exporters/otlp/metrics/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyShadedMetricExporterTest.java deleted file mode 100644 index d38c0e1913e..00000000000 --- a/exporters/otlp/metrics/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcNettyShadedMetricExporterTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.metrics.v1.ResourceMetrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettyShadedMetricExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcNettyShadedMetricExporterTest() { - super("metric", ResourceMetrics.getDefaultInstance()); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcMetricExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcMetricExporterBuilder builder = OtlpGrpcMetricExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected MetricData generateFakeTelemetry() { - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + TimeUnit.MILLISECONDS.toNanos(900); - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - startNs, endNs, Attributes.of(stringKey("k"), "v"), 5)))); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceMetricsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/metrics/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcOkHttpMetricExporterTest.java b/exporters/otlp/metrics/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcOkHttpMetricExporterTest.java deleted file mode 100644 index 448dab89edc..00000000000 --- a/exporters/otlp/metrics/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/metrics/OtlpGrpcOkHttpMetricExporterTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.metrics.ResourceMetricsMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.metrics.v1.ResourceMetrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcOkHttpMetricExporterTest - extends AbstractGrpcTelemetryExporterTest { - - OtlpGrpcOkHttpMetricExporterTest() { - super("metric", ResourceMetrics.getDefaultInstance()); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcMetricExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcMetricExporterBuilder builder = OtlpGrpcMetricExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected MetricData generateFakeTelemetry() { - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + TimeUnit.MILLISECONDS.toNanos(900); - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - startNs, endNs, Attributes.of(stringKey("k"), "v"), 5)))); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceMetricsMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/profiles/build.gradle.kts b/exporters/otlp/profiles/build.gradle.kts new file mode 100644 index 00000000000..ccd965fba5f --- /dev/null +++ b/exporters/otlp/profiles/build.gradle.kts @@ -0,0 +1,28 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry - Profiles Exporter" +otelJava.moduleName.set("io.opentelemetry.exporter.otlp.profiles") + +val versions = project.property("versions") as Map<*, *> + +dependencies { + api(project(":sdk:common")) + api(project(":sdk:profiles")) + api(project(":exporters:common")) + implementation(project(":exporters:otlp:common")) + + implementation(project(":exporters:otlp:all")) + compileOnly("io.grpc:grpc-stub") + + testCompileOnly("com.google.guava:guava") + testImplementation("com.google.protobuf:protobuf-java-util") + testImplementation("io.opentelemetry.proto:opentelemetry-proto") + testImplementation(project(":exporters:otlp:testing-internal")) + testImplementation(project(":exporters:sender:okhttp")) + testImplementation("io.grpc:grpc-stub") +} diff --git a/exporters/otlp/logs/gradle.properties b/exporters/otlp/profiles/gradle.properties similarity index 100% rename from exporters/otlp/logs/gradle.properties rename to exporters/otlp/profiles/gradle.properties diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ExportProfilesServiceResponse.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ExportProfilesServiceResponse.java new file mode 100644 index 00000000000..ce0ce3c6d65 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ExportProfilesServiceResponse.java @@ -0,0 +1,15 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +// A Java object to correspond to the gRPC response for the ProfilesService.Export method. If fields +// are added to the type in the future, this can be converted to an actual class. +// +// It may seem like Void could be used instead but gRPC does not allow response values to be +// null. +enum ExportProfilesServiceResponse { + INSTANCE; +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/FunctionMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/FunctionMarshaler.java new file mode 100644 index 00000000000..22ccb061850 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/FunctionMarshaler.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Function; +import io.opentelemetry.sdk.profiles.data.FunctionData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class FunctionMarshaler extends MarshalerWithSize { + + private static final FunctionMarshaler[] EMPTY_REPEATED = new FunctionMarshaler[0]; + + private final int nameStringIndex; + private final int systemNameStringIndex; + private final int filenameStringIndex; + private final long startLine; + + static FunctionMarshaler create(FunctionData functionData) { + return new FunctionMarshaler( + functionData.getNameStringIndex(), + functionData.getSystemNameStringIndex(), + functionData.getFilenameStringIndex(), + functionData.getStartLine()); + } + + static FunctionMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + FunctionMarshaler[] functionMarshalers = new FunctionMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(FunctionData functionData) { + functionMarshalers[index++] = FunctionMarshaler.create(functionData); + } + }); + return functionMarshalers; + } + + private FunctionMarshaler( + int nameStringIndex, int systemNameStringIndex, int filenameStringIndex, long startLine) { + super(calculateSize(nameStringIndex, systemNameStringIndex, filenameStringIndex, startLine)); + this.nameStringIndex = nameStringIndex; + this.systemNameStringIndex = systemNameStringIndex; + this.filenameStringIndex = filenameStringIndex; + this.startLine = startLine; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeInt32(Function.NAME_STRINDEX, nameStringIndex); + output.serializeInt32(Function.SYSTEM_NAME_STRINDEX, systemNameStringIndex); + output.serializeInt32(Function.FILENAME_STRINDEX, filenameStringIndex); + output.serializeInt64(Function.START_LINE, startLine); + } + + private static int calculateSize( + int nameStringIndex, int systemNameStringIndex, int filenameStringIndex, long startLine) { + int size = 0; + size += MarshalerUtil.sizeInt32(Function.NAME_STRINDEX, nameStringIndex); + size += MarshalerUtil.sizeInt32(Function.SYSTEM_NAME_STRINDEX, systemNameStringIndex); + size += MarshalerUtil.sizeInt32(Function.FILENAME_STRINDEX, filenameStringIndex); + size += MarshalerUtil.sizeInt64(Function.START_LINE, startLine); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/InstrumentationScopeProfilesMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/InstrumentationScopeProfilesMarshaler.java new file mode 100644 index 00000000000..8f7e2edea44 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/InstrumentationScopeProfilesMarshaler.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; +import io.opentelemetry.proto.profiles.v1development.internal.ScopeProfiles; +import java.io.IOException; +import java.util.List; + +final class InstrumentationScopeProfilesMarshaler extends MarshalerWithSize { + + private final InstrumentationScopeMarshaler instrumentationScope; + private final List profileMarshalers; + private final byte[] schemaUrlUtf8; + + InstrumentationScopeProfilesMarshaler( + InstrumentationScopeMarshaler instrumentationScope, + byte[] schemaUrlUtf8, + List profileMarshalers) { + super(calculateSize(instrumentationScope, schemaUrlUtf8, profileMarshalers)); + this.instrumentationScope = instrumentationScope; + this.schemaUrlUtf8 = schemaUrlUtf8; + this.profileMarshalers = profileMarshalers; + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.serializeMessage(ScopeProfiles.SCOPE, instrumentationScope); + output.serializeRepeatedMessage(ScopeProfiles.PROFILES, profileMarshalers); + output.serializeString(ScopeProfiles.SCHEMA_URL, schemaUrlUtf8); + } + + private static int calculateSize( + InstrumentationScopeMarshaler instrumentationScope, + byte[] schemaUrlUtf8, + List profileMarshalers) { + int size = 0; + size += MarshalerUtil.sizeMessage(ScopeProfiles.SCOPE, instrumentationScope); + size += MarshalerUtil.sizeRepeatedMessage(ScopeProfiles.PROFILES, profileMarshalers); + size += MarshalerUtil.sizeBytes(ScopeProfiles.SCHEMA_URL, schemaUrlUtf8); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/KeyValueAndUnitMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/KeyValueAndUnitMarshaler.java new file mode 100644 index 00000000000..413b0443244 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/KeyValueAndUnitMarshaler.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.otlp.AnyValueMarshaler; +import io.opentelemetry.proto.profiles.v1development.internal.KeyValueAndUnit; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class KeyValueAndUnitMarshaler extends MarshalerWithSize { + + private static final KeyValueAndUnitMarshaler[] EMPTY_REPEATED = new KeyValueAndUnitMarshaler[0]; + + private final int keyStringIndex; + private final Marshaler valueMarshaler; + private final int unitStringIndex; + + static KeyValueAndUnitMarshaler create(KeyValueAndUnitData keyValueAndUnitData) { + Marshaler valueMarshaler = AnyValueMarshaler.create(keyValueAndUnitData.getValue()); + return new KeyValueAndUnitMarshaler( + keyValueAndUnitData.getKeyStringIndex(), + valueMarshaler, + keyValueAndUnitData.getUnitStringIndex()); + } + + static KeyValueAndUnitMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + KeyValueAndUnitMarshaler[] keyValueAndUnitMarshalers = + new KeyValueAndUnitMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(KeyValueAndUnitData keyValueAndUnitData) { + keyValueAndUnitMarshalers[index++] = + KeyValueAndUnitMarshaler.create(keyValueAndUnitData); + } + }); + return keyValueAndUnitMarshalers; + } + + private KeyValueAndUnitMarshaler( + int keyStringIndex, Marshaler valueMarshaler, int unitStringIndex) { + super(calculateSize(keyStringIndex, valueMarshaler, unitStringIndex)); + this.keyStringIndex = keyStringIndex; + this.valueMarshaler = valueMarshaler; + this.unitStringIndex = unitStringIndex; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeInt32(KeyValueAndUnit.KEY_STRINDEX, keyStringIndex); + output.serializeMessage(KeyValueAndUnit.VALUE, valueMarshaler); + output.serializeInt32(KeyValueAndUnit.UNIT_STRINDEX, unitStringIndex); + } + + private static int calculateSize( + int keyStringIndex, Marshaler valueMarshaler, int unitStringIndex) { + int size = 0; + size += MarshalerUtil.sizeInt32(KeyValueAndUnit.KEY_STRINDEX, keyStringIndex); + size += MarshalerUtil.sizeMessage(KeyValueAndUnit.VALUE, valueMarshaler); + size += MarshalerUtil.sizeInt32(KeyValueAndUnit.UNIT_STRINDEX, unitStringIndex); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LineMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LineMarshaler.java new file mode 100644 index 00000000000..4c84c62b84b --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LineMarshaler.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Line; +import io.opentelemetry.sdk.profiles.data.LineData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class LineMarshaler extends MarshalerWithSize { + + private static final LineMarshaler[] EMPTY_REPEATED = new LineMarshaler[0]; + + private final int functionIndex; + private final long line; + private final long column; + + static LineMarshaler create(LineData lineData) { + return new LineMarshaler(lineData.getFunctionIndex(), lineData.getLine(), lineData.getColumn()); + } + + static LineMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + LineMarshaler[] lineMarshalers = new LineMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(LineData lineData) { + lineMarshalers[index++] = LineMarshaler.create(lineData); + } + }); + return lineMarshalers; + } + + private LineMarshaler(int functionIndex, long line, long column) { + super(calculateSize(functionIndex, line, column)); + this.functionIndex = functionIndex; + this.line = line; + this.column = column; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeInt32(Line.FUNCTION_INDEX, functionIndex); + output.serializeInt64(Line.LINE, line); + output.serializeInt64(Line.COLUMN, column); + } + + private static int calculateSize(int functionIndex, long line, long column) { + int size = 0; + size += MarshalerUtil.sizeInt32(Line.FUNCTION_INDEX, functionIndex); + size += MarshalerUtil.sizeInt64(Line.LINE, line); + size += MarshalerUtil.sizeInt64(Line.COLUMN, column); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LinkMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LinkMarshaler.java new file mode 100644 index 00000000000..9c67f6f66a3 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LinkMarshaler.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.api.impl.Base16EncodingUtils; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Link; +import io.opentelemetry.sdk.profiles.data.LinkData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class LinkMarshaler extends MarshalerWithSize { + + private static final LinkMarshaler[] EMPTY_REPEATED = new LinkMarshaler[0]; + + private final byte[] traceId; + private final byte[] spanId; + + static LinkMarshaler create(LinkData linkData) { + // in tracing this conversion is handled by utility methods on SpanContext, + // but we don't have a SpanContext here... + byte[] traceId = + Base16EncodingUtils.bytesFromBase16(linkData.getTraceId(), TraceId.getLength()); + byte[] spanId = Base16EncodingUtils.bytesFromBase16(linkData.getSpanId(), SpanId.getLength()); + + return new LinkMarshaler(traceId, spanId); + } + + static LinkMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + LinkMarshaler[] linkMarshalers = new LinkMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(LinkData linkData) { + linkMarshalers[index++] = LinkMarshaler.create(linkData); + } + }); + return linkMarshalers; + } + + private LinkMarshaler(byte[] traceId, byte[] spanId) { + super(calculateSize(traceId, spanId)); + this.traceId = traceId; + this.spanId = spanId; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeBytes(Link.TRACE_ID, traceId); + output.serializeBytes(Link.SPAN_ID, spanId); + } + + private static int calculateSize(byte[] traceId, byte[] spanId) { + int size = 0; + size += MarshalerUtil.sizeBytes(Link.TRACE_ID, traceId); + size += MarshalerUtil.sizeBytes(Link.SPAN_ID, spanId); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LocationMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LocationMarshaler.java new file mode 100644 index 00000000000..2222a0f87fd --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/LocationMarshaler.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Location; +import io.opentelemetry.sdk.profiles.data.LocationData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class LocationMarshaler extends MarshalerWithSize { + + private static final LocationMarshaler[] EMPTY_REPEATED = new LocationMarshaler[0]; + + private final int mappingIndex; + private final long address; + private final LineMarshaler[] lineMarshalers; + private final List attributeIndices; + + static LocationMarshaler create(LocationData locationData) { + return new LocationMarshaler( + locationData.getMappingIndex(), + locationData.getAddress(), + LineMarshaler.createRepeated(locationData.getLines()), + locationData.getAttributeIndices()); + } + + static LocationMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + LocationMarshaler[] locationMarshalers = new LocationMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(LocationData locationData) { + locationMarshalers[index++] = LocationMarshaler.create(locationData); + } + }); + return locationMarshalers; + } + + private LocationMarshaler( + int mappingIndex, + long address, + LineMarshaler[] lineMarshalers, + List attributeIndices) { + super(calculateSize(mappingIndex, address, lineMarshalers, attributeIndices)); + this.mappingIndex = mappingIndex; + this.address = address; + this.lineMarshalers = lineMarshalers; + this.attributeIndices = attributeIndices; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeInt32(Location.MAPPING_INDEX, mappingIndex); + output.serializeUInt64(Location.ADDRESS, address); + output.serializeRepeatedMessage(Location.LINES, lineMarshalers); + output.serializeRepeatedInt32(Location.ATTRIBUTE_INDICES, attributeIndices); + } + + private static int calculateSize( + int mappingIndex, + long address, + LineMarshaler[] lineMarshalers, + List attributeIndices) { + int size = 0; + size += MarshalerUtil.sizeInt32(Location.MAPPING_INDEX, mappingIndex); + size += MarshalerUtil.sizeUInt64(Location.ADDRESS, address); + size += MarshalerUtil.sizeRepeatedMessage(Location.LINES, lineMarshalers); + size += MarshalerUtil.sizeRepeatedInt32(Location.ATTRIBUTE_INDICES, attributeIndices); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/MappingMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/MappingMarshaler.java new file mode 100644 index 00000000000..2a737483bf0 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/MappingMarshaler.java @@ -0,0 +1,91 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Mapping; +import io.opentelemetry.sdk.profiles.data.MappingData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class MappingMarshaler extends MarshalerWithSize { + + private static final MappingMarshaler[] EMPTY_REPEATED = new MappingMarshaler[0]; + + private final long memoryStart; + private final long memoryLimit; + private final long fileOffset; + private final int filenameIndex; + private final List attributeIndices; + + static MappingMarshaler create(MappingData mappingData) { + return new MappingMarshaler( + mappingData.getMemoryStart(), + mappingData.getMemoryLimit(), + mappingData.getFileOffset(), + mappingData.getFilenameStringIndex(), + mappingData.getAttributeIndices()); + } + + static MappingMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + MappingMarshaler[] mappingMarshalers = new MappingMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(MappingData mappingData) { + mappingMarshalers[index++] = MappingMarshaler.create(mappingData); + } + }); + return mappingMarshalers; + } + + private MappingMarshaler( + long memoryStart, + long memoryLimit, + long fileOffset, + int filenameIndex, + List attributeIndices) { + super(calculateSize(memoryStart, memoryLimit, fileOffset, filenameIndex, attributeIndices)); + this.memoryStart = memoryStart; + this.memoryLimit = memoryLimit; + this.fileOffset = fileOffset; + this.filenameIndex = filenameIndex; + this.attributeIndices = attributeIndices; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeUInt64(Mapping.MEMORY_START, memoryStart); + output.serializeUInt64(Mapping.MEMORY_LIMIT, memoryLimit); + output.serializeUInt64(Mapping.FILE_OFFSET, fileOffset); + output.serializeInt32(Mapping.FILENAME_STRINDEX, filenameIndex); + output.serializeRepeatedInt32(Mapping.ATTRIBUTE_INDICES, attributeIndices); + } + + private static int calculateSize( + long memoryStart, + long memoryLimit, + long fileOffset, + int filenameIndex, + List attributeIndices) { + int size = 0; + size += MarshalerUtil.sizeUInt64(Mapping.MEMORY_START, memoryStart); + size += MarshalerUtil.sizeUInt64(Mapping.MEMORY_LIMIT, memoryLimit); + size += MarshalerUtil.sizeUInt64(Mapping.FILE_OFFSET, fileOffset); + size += MarshalerUtil.sizeInt32(Mapping.FILENAME_STRINDEX, filenameIndex); + size += MarshalerUtil.sizeRepeatedInt32(Mapping.ATTRIBUTE_INDICES, attributeIndices); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfileExporter.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfileExporter.java new file mode 100644 index 00000000000..745b2fae655 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfileExporter.java @@ -0,0 +1,96 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.profiles.ProfileExporter; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import java.util.Collection; +import java.util.StringJoiner; +import javax.annotation.concurrent.ThreadSafe; + +/** Exports profiles using OTLP via gRPC, using OpenTelemetry's protobuf model. */ +@ThreadSafe +public class OtlpGrpcProfileExporter implements ProfileExporter { + + private final GrpcExporterBuilder builder; + private final GrpcExporter delegate; + + /** + * Returns a new {@link OtlpGrpcProfileExporter} using the default values. + * + *

    To load configuration values from environment variables and system properties, use opentelemetry-sdk-extension-autoconfigure. + * + * @return a new {@link OtlpGrpcProfileExporter} instance. + */ + public static OtlpGrpcProfileExporter getDefault() { + return builder().build(); + } + + /** + * Returns a new builder instance for this exporter. + * + * @return a new builder instance for this exporter. + */ + public static OtlpGrpcProfilesExporterBuilder builder() { + return new OtlpGrpcProfilesExporterBuilder(); + } + + OtlpGrpcProfileExporter(GrpcExporterBuilder builder, GrpcExporter delegate) { + this.builder = builder; + this.delegate = delegate; + } + + /** + * Returns a builder with configuration values equal to those for this exporter. + * + *

    IMPORTANT: Be sure to {@link #shutdown()} this instance if it will no longer be used. + */ + public OtlpGrpcProfilesExporterBuilder toBuilder() { + return new OtlpGrpcProfilesExporterBuilder(builder.copy()); + } + + /** + * Submits all the given profiles in a single batch to the OpenTelemetry collector. + * + * @param profiles the list of sampled profiles to be exported. + * @return the result of the operation + */ + @Override + public CompletableResultCode export(Collection profiles) { + ProfilesRequestMarshaler request = ProfilesRequestMarshaler.create(profiles); + return delegate.export(request, profiles.size()); + } + + /** + * The OTLP exporter does not batch items, so this method will immediately return with success. + * + * @return always Success + */ + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** + * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately + * cancelled. + */ + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "OtlpGrpcProfileExporter{", "}"); + joiner.add(builder.toString(false)); + return joiner.toString(); + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfilesExporterBuilder.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfilesExporterBuilder.java new file mode 100644 index 00000000000..9f4f664514e --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfilesExporterBuilder.java @@ -0,0 +1,265 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.StandardComponentId; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** Builder utility for this exporter. */ +public final class OtlpGrpcProfilesExporterBuilder { + + private static final String GRPC_FULL_METHOD_NAME = + "opentelemetry.proto.collector.profiles.v1development.ProfilesService/Export"; + + private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; + private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); + private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); + + // TODO maybe make more efficient by adding support for MEMORY_MODE + + // Visible for testing + final GrpcExporterBuilder delegate; + + OtlpGrpcProfilesExporterBuilder(GrpcExporterBuilder delegate) { + this.delegate = delegate; + delegate.setMeterProvider(MeterProvider::noop); + OtlpUserAgent.addUserAgentHeader(delegate::addConstantHeader); + } + + OtlpGrpcProfilesExporterBuilder() { + this( + new GrpcExporterBuilder( + StandardComponentId.ExporterType.OTLP_GRPC_PROFILES_EXPORTER, + DEFAULT_TIMEOUT, + DEFAULT_ENDPOINT, + GRPC_FULL_METHOD_NAME)); + } + + /** + * Sets the managed channel to use when communicating with the backend. Takes precedence over + * {@link #setEndpoint(String)} if both are called. + * + *

    Note: calling this overrides the spec compliant {@code User-Agent} header. To ensure spec + * compliance, set {@link io.grpc.ManagedChannelBuilder#userAgent(String)} to {@link + * OtlpUserAgent#getUserAgent()} when building the channel. + * + * @param channel the channel to use + * @return this builder's instance + * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the + * methods on this builder, please file an issue to let us know what it is. + */ + @Deprecated + public OtlpGrpcProfilesExporterBuilder setChannel(ManagedChannel channel) { + delegate.setChannel(channel); + return this; + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of profiles. If + * unset, defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcProfilesExporterBuilder setTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for the collector to process an exported batch of profiles. If + * unset, defaults to {@link #DEFAULT_TIMEOUT}. + */ + public OtlpGrpcProfilesExporterBuilder setTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setTimeout(timeout); + return this; + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + */ + public OtlpGrpcProfilesExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + return setConnectTimeout(Duration.ofNanos(unit.toNanos(timeout))); + } + + /** + * Sets the maximum time to wait for new connections to be established. If unset, defaults to + * {@value GrpcExporterBuilder#DEFAULT_CONNECT_TIMEOUT_SECS}s. + */ + public OtlpGrpcProfilesExporterBuilder setConnectTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + delegate.setConnectTimeout(timeout); + return this; + } + + /** + * Sets the maximum OTLP gRPC request message size in bytes. If unset, defaults to 64 MiB. A value + * of 0 means no limit. + */ + public OtlpGrpcProfilesExporterBuilder setMaxRequestMessageSize(long maxRequestMessageSizeBytes) { + checkArgument( + maxRequestMessageSizeBytes >= 0, "maxRequestMessageSizeBytes must be non-negative"); + delegate.setMaxRequestMessageSize(maxRequestMessageSizeBytes); + return this; + } + + /** + * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The + * endpoint must start with either http:// or https://. + */ + public OtlpGrpcProfilesExporterBuilder setEndpoint(String endpoint) { + requireNonNull(endpoint, "endpoint"); + delegate.setEndpoint(endpoint); + return this; + } + + /** + * Sets the method used to compress payloads. If unset, compression is disabled. Compression + * method "gzip" and "none" are supported out of the box. Additional compression methods can be + * supported by providing custom {@link Compressor} implementations via the service loader. + */ + public OtlpGrpcProfilesExporterBuilder setCompression(String compressionMethod) { + requireNonNull(compressionMethod, "compressionMethod"); + delegate.setCompression(compressionMethod); + return this; + } + + /** + * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} + * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will + * use the system default trusted certificates. + */ + public OtlpGrpcProfilesExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { + delegate.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + */ + public OtlpGrpcProfilesExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + delegate.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + */ + public OtlpGrpcProfilesExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Add a constant header to requests. If the {@code key} collides with another constant header + * name or a one from {@link #setHeaders(Supplier)}, the values from both are included. + * + * @param key header key + * @param value header value + * @return this builder's instance + */ + public OtlpGrpcProfilesExporterBuilder addHeader(String key, String value) { + delegate.addConstantHeader(key, value); + return this; + } + + /** + * Set the supplier of headers to add to requests. If a key from the map collides with a constant + * from {@link #addHeader(String, String)}, the values from both are included. + */ + public OtlpGrpcProfilesExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeadersSupplier(headerSupplier); + return this; + } + + /** + * Set the retry policy, or {@code null} to disable retry. Retry policy is {@link + * RetryPolicy#getDefault()} by default + */ + public OtlpGrpcProfilesExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + return this; + } + + /** + * Set the {@link ClassLoader} used to load the sender API. Variant of {@link + * #setComponentLoader(ComponentLoader)}. + */ + public OtlpGrpcProfilesExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + requireNonNull(serviceClassLoader, "serviceClassLoader"); + return setComponentLoader(ComponentLoader.forClassLoader(serviceClassLoader)); + } + + /** Set the {@link ComponentLoader} used to load the sender API. */ + public OtlpGrpcProfilesExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + delegate.setComponentLoader(componentLoader); + return this; + } + + /** + * Set the {@link ExecutorService} used to execute requests. + * + *

    NOTE: By calling this method, you are opting into managing the lifecycle of the {@code + * executorService}. {@link ExecutorService#shutdown()} will NOT be called when this exporter is + * shutdown. + */ + public OtlpGrpcProfilesExporterBuilder setExecutorService(ExecutorService executorService) { + requireNonNull(executorService, "executorService"); + delegate.setExecutorService(executorService); + return this; + } + + /** + * Sets the TLS protocol versions to enable when connecting to an HTTPS endpoint. By default, OTLP + * exporters use the sender implementation's default protocol versions; omit this call to use that + * default. + * + *

    Protocol names follow the JSSE convention: {@code "TLSv1.2"}, {@code "TLSv1.3"}, etc. + * + *

    Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + */ + public OtlpGrpcProfilesExporterBuilder setEnabledProtocols(List enabledProtocols) { + requireNonNull(enabledProtocols, "enabledProtocols"); + checkArgument(!enabledProtocols.isEmpty(), "enabledProtocols must not be empty"); + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + /** + * Constructs a new instance of the exporter based on the builder's values. + * + * @return a new exporter's instance + */ + public OtlpGrpcProfileExporter build() { + return new OtlpGrpcProfileExporter(delegate, delegate.build()); + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfileMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfileMarshaler.java new file mode 100644 index 00000000000..8ef7cc9689c --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfileMarshaler.java @@ -0,0 +1,137 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Profile; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.util.List; + +final class ProfileMarshaler extends MarshalerWithSize { + + private final ValueTypeMarshaler sampleTypeMarshaler; + private final SampleMarshaler[] sampleMarshalers; + private final long timeNanos; + private final long durationNanos; + private final ValueTypeMarshaler periodTypeMarshaler; + private final long period; + private final byte[] profileId; + private final int droppedAttributesCount; + private final byte[] originalPayloadFormatUtf8; + private final ByteBuffer originalPayload; + private final List attributeIndices; + + static ProfileMarshaler create(ProfileData profileData) { + + ValueTypeMarshaler sampleTypeMarshaler = ValueTypeMarshaler.create(profileData.getSampleType()); + SampleMarshaler[] sampleMarshalers = SampleMarshaler.createRepeated(profileData.getSamples()); + ValueTypeMarshaler periodTypeMarshaler = ValueTypeMarshaler.create(profileData.getPeriodType()); + + int droppedAttributesCount = + profileData.getTotalAttributeCount() - profileData.getAttributeIndices().size(); + + return new ProfileMarshaler( + sampleTypeMarshaler, + sampleMarshalers, + profileData.getTimeNanos(), + profileData.getDurationNanos(), + periodTypeMarshaler, + profileData.getPeriod(), + profileData.getProfileIdBytes(), + droppedAttributesCount, + MarshalerUtil.toBytes(profileData.getOriginalPayloadFormat()), + profileData.getOriginalPayload(), + profileData.getAttributeIndices()); + } + + private ProfileMarshaler( + ValueTypeMarshaler sampleTypeMarshaler, + SampleMarshaler[] sampleMarshalers, + long timeNanos, + long durationNanos, + ValueTypeMarshaler periodTypeMarshaler, + long period, + byte[] profileId, + int droppedAttributesCount, + byte[] originalPayloadFormat, + ByteBuffer originalPayload, + List attributeIndices) { + super( + calculateSize( + sampleTypeMarshaler, + sampleMarshalers, + timeNanos, + durationNanos, + periodTypeMarshaler, + period, + profileId, + droppedAttributesCount, + originalPayloadFormat, + originalPayload, + attributeIndices)); + this.sampleTypeMarshaler = sampleTypeMarshaler; + this.sampleMarshalers = sampleMarshalers; + this.timeNanos = timeNanos; + this.durationNanos = durationNanos; + this.periodTypeMarshaler = periodTypeMarshaler; + this.period = period; + this.profileId = profileId; + this.attributeIndices = attributeIndices; + this.droppedAttributesCount = droppedAttributesCount; + this.originalPayloadFormatUtf8 = originalPayloadFormat; + this.originalPayload = originalPayload; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeMessage(Profile.SAMPLE_TYPE, sampleTypeMarshaler); + output.serializeRepeatedMessage(Profile.SAMPLES, sampleMarshalers); + output.serializeFixed64(Profile.TIME_UNIX_NANO, timeNanos); + output.serializeUInt64(Profile.DURATION_NANO, durationNanos); + output.serializeMessage(Profile.PERIOD_TYPE, periodTypeMarshaler); + output.serializeInt64(Profile.PERIOD, period); + + output.serializeBytes(Profile.PROFILE_ID, profileId); + output.serializeUInt32(Profile.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + output.serializeString(Profile.ORIGINAL_PAYLOAD_FORMAT, originalPayloadFormatUtf8); + output.serializeByteBuffer(Profile.ORIGINAL_PAYLOAD, originalPayload); + output.serializeRepeatedInt32(Profile.ATTRIBUTE_INDICES, attributeIndices); + } + + private static int calculateSize( + ValueTypeMarshaler sampleTypeMarshaler, + SampleMarshaler[] sampleMarshalers, + long timeNanos, + long durationNanos, + ValueTypeMarshaler periodTypeMarshaler, + long period, + byte[] profileId, + int droppedAttributesCount, + byte[] originalPayloadFormat, + ByteBuffer originalPayload, + List attributeIndices) { + int size; + size = 0; + size += MarshalerUtil.sizeMessage(Profile.SAMPLE_TYPE, sampleTypeMarshaler); + size += MarshalerUtil.sizeRepeatedMessage(Profile.SAMPLES, sampleMarshalers); + size += MarshalerUtil.sizeFixed64(Profile.TIME_UNIX_NANO, timeNanos); + size += MarshalerUtil.sizeUInt64(Profile.DURATION_NANO, durationNanos); + size += MarshalerUtil.sizeMessage(Profile.PERIOD_TYPE, periodTypeMarshaler); + size += MarshalerUtil.sizeInt64(Profile.PERIOD, period); + + size += MarshalerUtil.sizeBytes(Profile.PROFILE_ID, profileId); + size += MarshalerUtil.sizeUInt32(Profile.DROPPED_ATTRIBUTES_COUNT, droppedAttributesCount); + size += MarshalerUtil.sizeBytes(Profile.ORIGINAL_PAYLOAD_FORMAT, originalPayloadFormat); + size += MarshalerUtil.sizeByteBuffer(Profile.ORIGINAL_PAYLOAD, originalPayload); + size += MarshalerUtil.sizeRepeatedInt32(Profile.ATTRIBUTE_INDICES, attributeIndices); + + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfilesDictionaryMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfilesDictionaryMarshaler.java new file mode 100644 index 00000000000..15097c6712c --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfilesDictionaryMarshaler.java @@ -0,0 +1,119 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.ProfilesDictionary; +import io.opentelemetry.sdk.profiles.data.ProfilesDictionaryData; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +final class ProfilesDictionaryMarshaler extends MarshalerWithSize { + + private final MappingMarshaler[] mappingTableMarshalers; + private final LocationMarshaler[] locationTableMarshalers; + private final FunctionMarshaler[] functionTableMarshalers; + private final LinkMarshaler[] linkTableMarshalers; + private final byte[][] stringTable; + private final KeyValueAndUnitMarshaler[] attributeTableMarshalers; + private final StackMarshaler[] stackTableMarshalers; + + static ProfilesDictionaryMarshaler create(ProfilesDictionaryData profilesDictionaryData) { + + MappingMarshaler[] mappingMarshalers = + MappingMarshaler.createRepeated(profilesDictionaryData.getMappingTable()); + LocationMarshaler[] locationMarshalers = + LocationMarshaler.createRepeated(profilesDictionaryData.getLocationTable()); + FunctionMarshaler[] functionMarshalers = + FunctionMarshaler.createRepeated(profilesDictionaryData.getFunctionTable()); + LinkMarshaler[] linkMarshalers = + LinkMarshaler.createRepeated(profilesDictionaryData.getLinkTable()); + + byte[][] convertedStrings = new byte[profilesDictionaryData.getStringTable().size()][]; + for (int i = 0; i < profilesDictionaryData.getStringTable().size(); i++) { + convertedStrings[i] = + profilesDictionaryData.getStringTable().get(i).getBytes(StandardCharsets.UTF_8); + } + + KeyValueAndUnitMarshaler[] attributeTableMarshalers = + KeyValueAndUnitMarshaler.createRepeated(profilesDictionaryData.getAttributeTable()); + StackMarshaler[] stackTableMarshalers = + StackMarshaler.createRepeated(profilesDictionaryData.getStackTable()); + + return new ProfilesDictionaryMarshaler( + mappingMarshalers, + locationMarshalers, + functionMarshalers, + linkMarshalers, + convertedStrings, + attributeTableMarshalers, + stackTableMarshalers); + } + + private ProfilesDictionaryMarshaler( + MappingMarshaler[] mappingTableMarshalers, + LocationMarshaler[] locationTableMarshalers, + FunctionMarshaler[] functionTableMarshalers, + LinkMarshaler[] linkTableMarshalers, + byte[][] stringTableUtf8, + KeyValueAndUnitMarshaler[] attributeTableMarshalers, + StackMarshaler[] stackTableMarshalers) { + super( + calculateSize( + mappingTableMarshalers, + locationTableMarshalers, + functionTableMarshalers, + linkTableMarshalers, + stringTableUtf8, + attributeTableMarshalers, + stackTableMarshalers)); + this.mappingTableMarshalers = mappingTableMarshalers; + this.locationTableMarshalers = locationTableMarshalers; + this.functionTableMarshalers = functionTableMarshalers; + this.linkTableMarshalers = linkTableMarshalers; + this.stringTable = stringTableUtf8; + this.attributeTableMarshalers = attributeTableMarshalers; + this.stackTableMarshalers = stackTableMarshalers; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeRepeatedMessage(ProfilesDictionary.MAPPING_TABLE, mappingTableMarshalers); + output.serializeRepeatedMessage(ProfilesDictionary.LOCATION_TABLE, locationTableMarshalers); + output.serializeRepeatedMessage(ProfilesDictionary.FUNCTION_TABLE, functionTableMarshalers); + output.serializeRepeatedMessage(ProfilesDictionary.LINK_TABLE, linkTableMarshalers); + output.serializeRepeatedString(ProfilesDictionary.STRING_TABLE, stringTable); + output.serializeRepeatedMessage(ProfilesDictionary.ATTRIBUTE_TABLE, attributeTableMarshalers); + output.serializeRepeatedMessage(ProfilesDictionary.STACK_TABLE, stackTableMarshalers); + } + + private static int calculateSize( + MappingMarshaler[] mappingMarshalers, + LocationMarshaler[] locationMarshalers, + FunctionMarshaler[] functionMarshalers, + LinkMarshaler[] linkMarshalers, + byte[][] stringTable, + KeyValueAndUnitMarshaler[] attributeTableMarshalers, + StackMarshaler[] stackTableMarshalers) { + int size; + size = 0; + size += MarshalerUtil.sizeRepeatedMessage(ProfilesDictionary.MAPPING_TABLE, mappingMarshalers); + size += + MarshalerUtil.sizeRepeatedMessage(ProfilesDictionary.LOCATION_TABLE, locationMarshalers); + size += + MarshalerUtil.sizeRepeatedMessage(ProfilesDictionary.FUNCTION_TABLE, functionMarshalers); + size += MarshalerUtil.sizeRepeatedMessage(ProfilesDictionary.LINK_TABLE, linkMarshalers); + size += MarshalerUtil.sizeRepeatedString(ProfilesDictionary.STRING_TABLE, stringTable); + size += + MarshalerUtil.sizeRepeatedMessage( + ProfilesDictionary.ATTRIBUTE_TABLE, attributeTableMarshalers); + size += MarshalerUtil.sizeRepeatedMessage(ProfilesDictionary.STACK_TABLE, stackTableMarshalers); + + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfilesRequestMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfilesRequestMarshaler.java new file mode 100644 index 00000000000..9cc48b7e0a0 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ProfilesRequestMarshaler.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import static io.opentelemetry.proto.collector.profiles.v1development.internal.ExportProfilesServiceRequest.DICTIONARY; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.ProtoFieldInfo; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.collector.profiles.v1development.internal.ExportProfilesServiceRequest; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import io.opentelemetry.sdk.profiles.data.ProfilesDictionaryData; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; + +/** + * {@link Marshaler} to convert SDK {@link ProfileData} to OTLP ExportProfilesServiceRequest. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ProfilesRequestMarshaler extends MarshalerWithSize { + + private static final ProfilesDictionaryData EMPTY_DICTIONARY_DATA = + ProfilesDictionaryData.create( + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); + + private static final ProtoFieldInfo RESOURCE_PROFILES = + ExportProfilesServiceRequest.RESOURCE_PROFILES; + + private final ResourceProfilesMarshaler[] resourceProfilesMarshalers; + private final ProfilesDictionaryMarshaler profilesDictionaryMarshaler; + + /** + * Returns a {@link ProfilesRequestMarshaler} that can be used to convert the provided {@link + * ProfileData} into a serialized OTLP ExportProfilesServiceRequest. + */ + @SuppressWarnings("ReferenceEquality") + public static ProfilesRequestMarshaler create(Collection profileList) { + // Verify all profiles in batch have identical dictionary + ProfilesDictionaryData profilesDictionaryData = null; + for (ProfileData profileData : profileList) { + if (profilesDictionaryData == null) { + profilesDictionaryData = profileData.getProfileDictionaryData(); + } else if (profilesDictionaryData != profileData.getProfileDictionaryData()) { + throw new IllegalArgumentException( + "All profiles in batch must have identical ProfileDictionaryData"); + } + } + + ProfilesDictionaryMarshaler profilesDictionaryMarshaler = + ProfilesDictionaryMarshaler.create( + profilesDictionaryData == null ? EMPTY_DICTIONARY_DATA : profilesDictionaryData); + + return new ProfilesRequestMarshaler( + ResourceProfilesMarshaler.create(profileList), profilesDictionaryMarshaler); + } + + private ProfilesRequestMarshaler( + ResourceProfilesMarshaler[] resourceProfilesMarshalers, + ProfilesDictionaryMarshaler profilesDictionaryMarshaler) { + super(calculateSize(resourceProfilesMarshalers, profilesDictionaryMarshaler)); + this.resourceProfilesMarshalers = resourceProfilesMarshalers; + this.profilesDictionaryMarshaler = profilesDictionaryMarshaler; + } + + @Override + public void writeTo(Serializer output) throws IOException { + output.serializeRepeatedMessage(RESOURCE_PROFILES, resourceProfilesMarshalers); + output.serializeMessage(DICTIONARY, profilesDictionaryMarshaler); + } + + private static int calculateSize( + ResourceProfilesMarshaler[] resourceProfilesMarshalers, + ProfilesDictionaryMarshaler profilesDictionaryMarshaler) { + int size = 0; + size += MarshalerUtil.sizeRepeatedMessage(RESOURCE_PROFILES, resourceProfilesMarshalers); + size += MarshalerUtil.sizeMessage(DICTIONARY, profilesDictionaryMarshaler); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ResourceProfilesMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ResourceProfilesMarshaler.java new file mode 100644 index 00000000000..3f75bc1be20 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ResourceProfilesMarshaler.java @@ -0,0 +1,101 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.otlp.InstrumentationScopeMarshaler; +import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; +import io.opentelemetry.proto.profiles.v1development.internal.ResourceProfiles; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.Map; + +final class ResourceProfilesMarshaler extends MarshalerWithSize { + + private final ResourceMarshaler resourceMarshaler; + private final byte[] schemaUrl; + private final InstrumentationScopeProfilesMarshaler[] instrumentationScopeProfilesMarshalers; + + /** Returns Marshalers of ResourceProfiles created by grouping the provided Profiles. */ + @SuppressWarnings("AvoidObjectArrays") + static ResourceProfilesMarshaler[] create(Collection profiles) { + Map>> resourceAndScopeMap = + groupByResourceAndScope(profiles); + + ResourceProfilesMarshaler[] resourceProfilesMarshalers = + new ResourceProfilesMarshaler[resourceAndScopeMap.size()]; + int posResource = 0; + for (Map.Entry>> entry : + resourceAndScopeMap.entrySet()) { + InstrumentationScopeProfilesMarshaler[] instrumentationScopeProfilesMarshalers = + new InstrumentationScopeProfilesMarshaler[entry.getValue().size()]; + int posInstrumentation = 0; + + for (Map.Entry> entryIs : + entry.getValue().entrySet()) { + instrumentationScopeProfilesMarshalers[posInstrumentation++] = + new InstrumentationScopeProfilesMarshaler( + InstrumentationScopeMarshaler.create(entryIs.getKey()), + MarshalerUtil.toBytes(entryIs.getKey().getSchemaUrl()), + entryIs.getValue()); + } + + resourceProfilesMarshalers[posResource++] = + new ResourceProfilesMarshaler( + ResourceMarshaler.create(entry.getKey()), + MarshalerUtil.toBytes(entry.getKey().getSchemaUrl()), + instrumentationScopeProfilesMarshalers); + } + + return resourceProfilesMarshalers; + } + + private ResourceProfilesMarshaler( + ResourceMarshaler resourceMarshaler, + byte[] schemaUrl, + InstrumentationScopeProfilesMarshaler[] instrumentationScopeProfilesMarshalers) { + super(calculateSize(resourceMarshaler, schemaUrl, instrumentationScopeProfilesMarshalers)); + this.resourceMarshaler = resourceMarshaler; + this.schemaUrl = schemaUrl; + this.instrumentationScopeProfilesMarshalers = instrumentationScopeProfilesMarshalers; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeMessage(ResourceProfiles.RESOURCE, resourceMarshaler); + output.serializeRepeatedMessage( + ResourceProfiles.SCOPE_PROFILES, instrumentationScopeProfilesMarshalers); + output.serializeString(ResourceProfiles.SCHEMA_URL, schemaUrl); + } + + private static int calculateSize( + ResourceMarshaler resourceMarshaler, + byte[] schemaUrl, + InstrumentationScopeProfilesMarshaler[] instrumentationScopeProfilesMarshalers) { + int size = 0; + size += MarshalerUtil.sizeMessage(ResourceProfiles.RESOURCE, resourceMarshaler); + size += + MarshalerUtil.sizeRepeatedMessage( + ResourceProfiles.SCOPE_PROFILES, instrumentationScopeProfilesMarshalers); + size += MarshalerUtil.sizeBytes(ResourceProfiles.SCHEMA_URL, schemaUrl); + return size; + } + + private static Map>> + groupByResourceAndScope(Collection profiles) { + return MarshalerUtil.groupByResourceAndScope( + profiles, + ProfileData::getResource, + ProfileData::getInstrumentationScopeInfo, + ProfileMarshaler::create); + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/SampleMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/SampleMarshaler.java new file mode 100644 index 00000000000..000b6f09d54 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/SampleMarshaler.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Sample; +import io.opentelemetry.sdk.profiles.data.SampleData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class SampleMarshaler extends MarshalerWithSize { + + private static final SampleMarshaler[] EMPTY_REPEATED = new SampleMarshaler[0]; + + private final int stackIndex; + private final List attributeIndices; + private final int linkIndex; + + private final List values; + private final List timestamps; + + static SampleMarshaler create(SampleData sampleData) { + + return new SampleMarshaler( + sampleData.getStackIndex(), + sampleData.getAttributeIndices(), + sampleData.getLinkIndex(), + sampleData.getValues(), + sampleData.getTimestamps()); + } + + static SampleMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + SampleMarshaler[] sampleMarshalers = new SampleMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(SampleData sampleData) { + sampleMarshalers[index++] = SampleMarshaler.create(sampleData); + } + }); + return sampleMarshalers; + } + + private SampleMarshaler( + int stackIndex, + List attributeIndices, + int linkIndex, + List values, + List timestamps) { + super(calculateSize(stackIndex, attributeIndices, linkIndex, values, timestamps)); + this.stackIndex = stackIndex; + this.attributeIndices = attributeIndices; + this.linkIndex = linkIndex; + this.values = values; + this.timestamps = timestamps; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeInt32(Sample.STACK_INDEX, stackIndex); + output.serializeRepeatedInt32(Sample.ATTRIBUTE_INDICES, attributeIndices); + output.serializeInt32(Sample.LINK_INDEX, linkIndex); + output.serializeRepeatedInt64(Sample.VALUES, values); + output.serializeRepeatedFixed64(Sample.TIMESTAMPS_UNIX_NANO, timestamps); + } + + private static int calculateSize( + int stackIndex, + List attributeIndices, + int linkIndex, + List values, + List timestamps) { + int size; + size = 0; + size += MarshalerUtil.sizeInt32(Sample.STACK_INDEX, stackIndex); + size += MarshalerUtil.sizeRepeatedInt32(Sample.ATTRIBUTE_INDICES, attributeIndices); + size += MarshalerUtil.sizeInt32(Sample.LINK_INDEX, linkIndex); + size += MarshalerUtil.sizeRepeatedInt64(Sample.VALUES, values); + size += MarshalerUtil.sizeRepeatedFixed64(Sample.TIMESTAMPS_UNIX_NANO, timestamps); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/StackMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/StackMarshaler.java new file mode 100644 index 00000000000..1b0ab1130b7 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/StackMarshaler.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.Stack; +import io.opentelemetry.sdk.profiles.data.StackData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class StackMarshaler extends MarshalerWithSize { + + private static final StackMarshaler[] EMPTY_REPEATED = new StackMarshaler[0]; + + private final List locationIndices; + + static StackMarshaler create(StackData stackData) { + return new StackMarshaler(stackData.getLocationIndices()); + } + + static StackMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + StackMarshaler[] stackMarshalers = new StackMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(StackData stackData) { + stackMarshalers[index++] = StackMarshaler.create(stackData); + } + }); + return stackMarshalers; + } + + private StackMarshaler(List locationIndices) { + super(calculateSize(locationIndices)); + this.locationIndices = locationIndices; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeRepeatedInt32(Stack.LOCATION_INDICES, locationIndices); + } + + private static int calculateSize(List locationIndices) { + int size = 0; + size += MarshalerUtil.sizeRepeatedInt32(Stack.LOCATION_INDICES, locationIndices); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ValueTypeMarshaler.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ValueTypeMarshaler.java new file mode 100644 index 00000000000..846a66557d6 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/ValueTypeMarshaler.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.proto.profiles.v1development.internal.ValueType; +import io.opentelemetry.sdk.profiles.data.ValueTypeData; +import java.io.IOException; +import java.util.List; +import java.util.function.Consumer; + +final class ValueTypeMarshaler extends MarshalerWithSize { + + private static final ValueTypeMarshaler[] EMPTY_REPEATED = new ValueTypeMarshaler[0]; + + private final int typeStringIndex; + private final int unitStringIndex; + + static ValueTypeMarshaler create(ValueTypeData valueTypeData) { + return new ValueTypeMarshaler( + valueTypeData.getTypeStringIndex(), valueTypeData.getUnitStringIndex()); + } + + static ValueTypeMarshaler[] createRepeated(List items) { + if (items.isEmpty()) { + return EMPTY_REPEATED; + } + + ValueTypeMarshaler[] valueTypeMarshalers = new ValueTypeMarshaler[items.size()]; + items.forEach( + new Consumer() { + int index = 0; + + @Override + public void accept(ValueTypeData valueTypeData) { + valueTypeMarshalers[index++] = ValueTypeMarshaler.create(valueTypeData); + } + }); + return valueTypeMarshalers; + } + + private ValueTypeMarshaler(int typeStringIndex, int unitStringIndex) { + super(calculateSize(typeStringIndex, unitStringIndex)); + this.typeStringIndex = typeStringIndex; + this.unitStringIndex = unitStringIndex; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeInt32(ValueType.TYPE_STRINDEX, typeStringIndex); + output.serializeInt32(ValueType.UNIT_STRINDEX, unitStringIndex); + } + + private static int calculateSize(int typeStringIndex, int unitStringIndex) { + int size; + size = 0; + size += MarshalerUtil.sizeInt32(ValueType.TYPE_STRINDEX, typeStringIndex); + size += MarshalerUtil.sizeInt32(ValueType.UNIT_STRINDEX, unitStringIndex); + return size; + } +} diff --git a/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/package-info.java b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/package-info.java new file mode 100644 index 00000000000..ec0107701b5 --- /dev/null +++ b/exporters/otlp/profiles/src/main/java/io/opentelemetry/exporter/otlp/profiles/package-info.java @@ -0,0 +1,10 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** The data format to model profiles for export. */ +@ParametersAreNonnullByDefault +package io.opentelemetry.exporter.otlp.profiles; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/FakeTelemetryUtil.java b/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/FakeTelemetryUtil.java new file mode 100644 index 00000000000..4c68f1ef766 --- /dev/null +++ b/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/FakeTelemetryUtil.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import io.opentelemetry.sdk.profiles.data.ProfilesDictionaryData; +import io.opentelemetry.sdk.profiles.data.ValueTypeData; +import io.opentelemetry.sdk.resources.Resource; +import java.nio.ByteBuffer; +import java.util.Collections; + +// TODO eventually merge with io.opentelemetry.exporter.otlp.testing.internal.FakeTelemetryUtil +class FakeTelemetryUtil { + + private static final ProfilesDictionaryData EMPTY_PROFILE_DICTIONARY_DATA = + ProfilesDictionaryData.create( + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()); + + private FakeTelemetryUtil() {} + + private static final InstrumentationScopeInfo SCOPE_INFO = + InstrumentationScopeInfo.builder("testLib") + .setVersion("1.0") + .setSchemaUrl("http://url") + .build(); + + /** Generate a fake {@link ProfileData}. */ + static ProfileData generateFakeProfileData() { + String profileId = "0123456789abcdef0123456789abcdef"; + return ProfileData.create( + Resource.create(Attributes.empty()), + SCOPE_INFO, + EMPTY_PROFILE_DICTIONARY_DATA, + ValueTypeData.create(1, 2), + Collections.emptyList(), + 5L, + 6L, + ValueTypeData.create(1, 2), + 7L, + profileId, + 8, + "format", + ByteBuffer.wrap(new byte[] {4, 5}), + Collections.emptyList()); + } +} diff --git a/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfileExporterTest.java b/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfileExporterTest.java new file mode 100644 index 00000000000..cbb5ca98cbc --- /dev/null +++ b/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/OtlpGrpcProfileExporterTest.java @@ -0,0 +1,92 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; +import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSender; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.proto.profiles.v1development.ResourceProfiles; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import java.io.Closeable; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.slf4j.event.Level; +import org.slf4j.event.LoggingEvent; + +class OtlpGrpcProfileExporterTest + extends AbstractGrpcTelemetryExporterTest { + + OtlpGrpcProfileExporterTest() { + super("profile", ResourceProfiles.getDefaultInstance()); + } + + @Test + void usingOkHttp() throws Exception { + try (Closeable exporter = OtlpGrpcProfileExporter.builder().build()) { + assertThat(exporter).extracting("delegate.grpcSender").isInstanceOf(OkHttpGrpcSender.class); + } + } + + @Test + void stringRepresentationClassName() { + try (OtlpGrpcProfileExporter exporter = OtlpGrpcProfileExporter.builder().build()) { + assertThat(exporter.toString()).startsWith("OtlpGrpcProfileExporter{"); + } + } + + @Test + @Override // whilst profile signal type is in development it uses a different error message + @SuppressLogger(GrpcExporter.class) + protected void testExport_Unimplemented() { + addGrpcResponse(GrpcStatusCode.UNIMPLEMENTED, "UNIMPLEMENTED"); + + TelemetryExporter exporter = nonRetryingExporter(); + + try { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + + LoggingEvent log = logs.assertContains("The profile signal type is still under development"); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + } finally { + exporter.shutdown(); + } + } + + @Override + protected TelemetryExporterBuilder exporterBuilder() { + return TelemetryExporterBuilder.wrap(OtlpGrpcProfileExporter.builder()); + } + + @Override + protected TelemetryExporterBuilder toBuilder( + TelemetryExporter exporter) { + return TelemetryExporterBuilder.wrap(((OtlpGrpcProfileExporter) exporter.unwrap()).toBuilder()); + } + + @Override + protected ProfileData generateFakeTelemetry() { + return FakeTelemetryUtil.generateFakeProfileData(); + } + + @Override + protected Marshaler[] toMarshalers(List telemetry) { + return ResourceProfilesMarshaler.create(telemetry); + } +} diff --git a/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/ProfilesRequestMarshalerTest.java b/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/ProfilesRequestMarshalerTest.java new file mode 100644 index 00000000000..52f1d6decf6 --- /dev/null +++ b/exporters/otlp/profiles/src/test/java/io/opentelemetry/exporter/otlp/profiles/ProfilesRequestMarshalerTest.java @@ -0,0 +1,526 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.profiles; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.ByteString; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.InstrumentationScope; +import io.opentelemetry.proto.profiles.v1development.Function; +import io.opentelemetry.proto.profiles.v1development.KeyValueAndUnit; +import io.opentelemetry.proto.profiles.v1development.Line; +import io.opentelemetry.proto.profiles.v1development.Link; +import io.opentelemetry.proto.profiles.v1development.Location; +import io.opentelemetry.proto.profiles.v1development.Mapping; +import io.opentelemetry.proto.profiles.v1development.Profile; +import io.opentelemetry.proto.profiles.v1development.ResourceProfiles; +import io.opentelemetry.proto.profiles.v1development.Sample; +import io.opentelemetry.proto.profiles.v1development.ScopeProfiles; +import io.opentelemetry.proto.profiles.v1development.Stack; +import io.opentelemetry.proto.profiles.v1development.ValueType; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.profiles.data.FunctionData; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import io.opentelemetry.sdk.profiles.data.LineData; +import io.opentelemetry.sdk.profiles.data.LinkData; +import io.opentelemetry.sdk.profiles.data.LocationData; +import io.opentelemetry.sdk.profiles.data.MappingData; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import io.opentelemetry.sdk.profiles.data.ProfilesDictionaryData; +import io.opentelemetry.sdk.profiles.data.SampleData; +import io.opentelemetry.sdk.profiles.data.StackData; +import io.opentelemetry.sdk.profiles.data.ValueTypeData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class ProfilesRequestMarshalerTest { + + @Test + void compareFunctionMarshaling() { + FunctionData input = FunctionData.create(1, 2, 3, 4); + Function builderResult = + Function.newBuilder() + .setNameStrindex(1) + .setSystemNameStrindex(2) + .setFilenameStrindex(3) + .setStartLine(4) + .build(); + + Function roundTripResult = + parse(Function.getDefaultInstance(), FunctionMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedFunctionMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(FunctionData.create(1, 2, 3, 4)); + inputs.add(FunctionData.create(5, 6, 7, 8)); + + List builderResults = new ArrayList<>(); + builderResults.add( + Function.newBuilder() + .setNameStrindex(1) + .setSystemNameStrindex(2) + .setFilenameStrindex(3) + .setStartLine(4) + .build()); + builderResults.add( + Function.newBuilder() + .setNameStrindex(5) + .setSystemNameStrindex(6) + .setFilenameStrindex(7) + .setStartLine(8) + .build()); + + FunctionMarshaler[] marshalers = FunctionMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Function roundTripResult = parse(Function.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareLineMarshaling() { + LineData input = LineData.create(1, 2, 3); + Line builderResult = Line.newBuilder().setFunctionIndex(1).setLine(2).setColumn(3).build(); + + Line roundTripResult = parse(Line.getDefaultInstance(), LineMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedLineMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(LineData.create(1, 2, 3)); + inputs.add(LineData.create(4, 5, 6)); + + List builderResults = new ArrayList<>(); + builderResults.add(Line.newBuilder().setFunctionIndex(1).setLine(2).setColumn(3).build()); + builderResults.add(Line.newBuilder().setFunctionIndex(4).setLine(5).setColumn(6).build()); + + LineMarshaler[] marshalers = LineMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Line roundTripResult = parse(Line.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareKeyValueAndUnitMarshaling() { + KeyValueAndUnitData input = KeyValueAndUnitData.create(1, Value.of("foo"), 3); + KeyValueAndUnit builderResult = + KeyValueAndUnit.newBuilder() + .setKeyStrindex(1) + .setValue(AnyValue.newBuilder().setStringValue("foo").build()) + .setUnitStrindex(3) + .build(); + + KeyValueAndUnit roundTripResult = + parse(KeyValueAndUnit.getDefaultInstance(), KeyValueAndUnitMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedKeyValueAndUnitMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(KeyValueAndUnitData.create(1, Value.of("foo"), 3)); + inputs.add(KeyValueAndUnitData.create(4, Value.of("bar"), 6)); + + List builderResults = new ArrayList<>(); + builderResults.add( + KeyValueAndUnit.newBuilder() + .setKeyStrindex(1) + .setValue(AnyValue.newBuilder().setStringValue("foo").build()) + .setUnitStrindex(3) + .build()); + builderResults.add( + KeyValueAndUnit.newBuilder() + .setKeyStrindex(4) + .setValue(AnyValue.newBuilder().setStringValue("bar").build()) + .setUnitStrindex(6) + .build()); + + KeyValueAndUnitMarshaler[] marshalers = KeyValueAndUnitMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + KeyValueAndUnit roundTripResult = parse(KeyValueAndUnit.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareLinkMarshaling() { + String traceId = "0123456789abcdef0123456789abcdef"; + String spanId = "fedcba9876543210"; + LinkData input = LinkData.create(traceId, spanId); + Link builderResult = + Link.newBuilder() + .setTraceId(ByteString.fromHex(traceId)) + .setSpanId(ByteString.fromHex(spanId)) + .build(); + + Link roundTripResult = parse(Link.getDefaultInstance(), LinkMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedLinkMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(LinkData.create("0123456789abcdef0123456789abcdef", "fedcba9876543210")); + inputs.add(LinkData.create("123456789abcdef0123456789abcdef0", "edcba9876543210f")); + + List builderResults = new ArrayList<>(); + builderResults.add( + Link.newBuilder() + .setTraceId(ByteString.fromHex("0123456789abcdef0123456789abcdef")) + .setSpanId(ByteString.fromHex("fedcba9876543210")) + .build()); + builderResults.add( + Link.newBuilder() + .setTraceId(ByteString.fromHex("123456789abcdef0123456789abcdef0")) + .setSpanId(ByteString.fromHex("edcba9876543210f")) + .build()); + + LinkMarshaler[] marshalers = LinkMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Link roundTripResult = parse(Link.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareLocationMarshaling() { + LocationData input = LocationData.create(1, 2, Collections.emptyList(), listOf(4, 5)); + Location builderResult = + Location.newBuilder() + .setMappingIndex(1) + .setAddress(2) + .addAllAttributeIndices(listOf(4, 5)) + .build(); + + Location roundTripResult = + parse(Location.getDefaultInstance(), LocationMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedLocationMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(LocationData.create(1, 2, Collections.emptyList(), listOf(3, 4))); + inputs.add(LocationData.create(5, 6, Collections.emptyList(), listOf(7, 8))); + + List builderResults = new ArrayList<>(); + builderResults.add( + Location.newBuilder() + .setMappingIndex(1) + .setAddress(2) + .addAllAttributeIndices(listOf(3, 4)) + .build()); + builderResults.add( + Location.newBuilder() + .setMappingIndex(5) + .setAddress(6) + .addAllAttributeIndices(listOf(7, 8)) + .build()); + + LocationMarshaler[] marshalers = LocationMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Location roundTripResult = parse(Location.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareMappingMarshaling() { + MappingData input = MappingData.create(1, 2, 3, 4, listOf(5, 6)); + Mapping builderResult = + Mapping.newBuilder() + .setMemoryStart(1) + .setMemoryLimit(2) + .setFileOffset(3) + .setFilenameStrindex(4) + .addAllAttributeIndices(listOf(5, 6)) + .build(); + + Mapping roundTripResult = parse(Mapping.getDefaultInstance(), MappingMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedMappingMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(MappingData.create(1, 2, 3, 4, listOf(5, 6))); + inputs.add(MappingData.create(7, 8, 9, 10, listOf(11, 12))); + + List builderResults = new ArrayList<>(); + builderResults.add( + Mapping.newBuilder() + .setMemoryStart(1) + .setMemoryLimit(2) + .setFileOffset(3) + .setFilenameStrindex(4) + .addAllAttributeIndices(listOf(5, 6)) + .build()); + builderResults.add( + Mapping.newBuilder() + .setMemoryStart(7) + .setMemoryLimit(8) + .setFileOffset(9) + .setFilenameStrindex(10) + .addAllAttributeIndices(listOf(11, 12)) + .build()); + + MappingMarshaler[] marshalers = MappingMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Mapping roundTripResult = parse(Mapping.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareStackMarshaling() { + StackData input = StackData.create(listOf(1, 2)); + Stack builderResult = Stack.newBuilder().addAllLocationIndices(listOf(1, 2)).build(); + + Stack roundTripResult = parse(Stack.getDefaultInstance(), StackMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedStackMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(StackData.create(listOf(1, 2))); + inputs.add(StackData.create(listOf(3, 4))); + + List builderResults = new ArrayList<>(); + builderResults.add(Stack.newBuilder().addAllLocationIndices(listOf(1, 2)).build()); + builderResults.add(Stack.newBuilder().addAllLocationIndices(listOf(3, 4)).build()); + + StackMarshaler[] marshalers = StackMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Stack roundTripResult = parse(Stack.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareResourceProfilesMarshaling() { + + String profileId = "0123456789abcdef0123456789abcdef"; + ProfileData profileContainerData = + ProfileData.create( + Resource.create(Attributes.empty()), + InstrumentationScopeInfo.create("testscope"), + ProfilesDictionaryData.create( + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList(), + Collections.emptyList()), + ValueTypeData.create(1, 2), + Collections.emptyList(), + 5L, + 6L, + ValueTypeData.create(1, 2), + 7L, + profileId, + 8, + "format", + ByteBuffer.wrap(new byte[] {4, 5}), + Collections.emptyList()); + + Collection input = new ArrayList<>(); + input.add(profileContainerData); + + Profile profileContainer = + Profile.newBuilder() + .setSampleType(ValueType.newBuilder().setTypeStrindex(1).setUnitStrindex(2).build()) + .setTimeUnixNano(5) + .setDurationNano(6) + .setPeriodType(ValueType.newBuilder().setTypeStrindex(1).setUnitStrindex(2).build()) + .setPeriod(7) + .setProfileId(ByteString.fromHex(profileId)) + .setDroppedAttributesCount(8) + .setOriginalPayloadFormat("format") + .setOriginalPayload(ByteString.copyFrom(new byte[] {4, 5})) + .build(); + + ResourceProfiles builderResult = + ResourceProfiles.newBuilder() + .setResource(io.opentelemetry.proto.resource.v1.Resource.newBuilder().build()) + .addScopeProfiles( + ScopeProfiles.newBuilder() + .setScope(InstrumentationScope.newBuilder().setName("testscope").build()) + .addProfiles(profileContainer) + .build()) + .build(); + + ResourceProfilesMarshaler[] marshalers = ResourceProfilesMarshaler.create(input); + assertThat(marshalers.length).isEqualTo(1); + ResourceProfiles roundTripResult = parse(ResourceProfiles.getDefaultInstance(), marshalers[0]); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareSampleMarshaling() { + SampleData input = SampleData.create(1, listOf(2, 3), 4, listOf(5L, 6L), listOf(7L, 8L)); + Sample builderResult = + Sample.newBuilder() + .setStackIndex(1) + .addAllAttributeIndices(listOf(2, 3)) + .setLinkIndex(4) + .addAllValues(listOf(5L, 6L)) + .addAllTimestampsUnixNano(listOf(7L, 8L)) + .build(); + + Sample roundTripResult = parse(Sample.getDefaultInstance(), SampleMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedSampleMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(SampleData.create(1, listOf(2, 3), 4, listOf(5L, 6L), listOf(7L, 8L))); + inputs.add(SampleData.create(11, listOf(12, 13), 14, listOf(15L, 16L), listOf(17L, 18L))); + + List builderResults = new ArrayList<>(); + builderResults.add( + Sample.newBuilder() + .setStackIndex(1) + .addAllAttributeIndices(listOf(2, 3)) + .setLinkIndex(4) + .addAllValues(listOf(5L, 6L)) + .addAllTimestampsUnixNano(listOf(7L, 8L)) + .build()); + builderResults.add( + Sample.newBuilder() + .setStackIndex(11) + .addAllAttributeIndices(listOf(12, 13)) + .setLinkIndex(14) + .addAllValues(listOf(15L, 16L)) + .addAllTimestampsUnixNano(listOf(17L, 18L)) + .build()); + + SampleMarshaler[] marshalers = SampleMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + Sample roundTripResult = parse(Sample.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + @Test + void compareValueTypeMarshaling() { + ValueTypeData input = ValueTypeData.create(1, 2); + ValueType builderResult = ValueType.newBuilder().setTypeStrindex(1).setUnitStrindex(2).build(); + + ValueType roundTripResult = + parse(ValueType.getDefaultInstance(), ValueTypeMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @Test + void compareRepeatedValueTypeMarshaling() { + List inputs = new ArrayList<>(); + inputs.add(ValueTypeData.create(1, 2)); + inputs.add(ValueTypeData.create(3, 4)); + + List builderResults = new ArrayList<>(); + builderResults.add(ValueType.newBuilder().setTypeStrindex(1).setUnitStrindex(2).build()); + builderResults.add(ValueType.newBuilder().setTypeStrindex(3).setUnitStrindex(4).build()); + + ValueTypeMarshaler[] marshalers = ValueTypeMarshaler.createRepeated(inputs); + + for (int i = 0; i < marshalers.length; i++) { + ValueType roundTripResult = parse(ValueType.getDefaultInstance(), marshalers[i]); + assertThat(roundTripResult).isEqualTo(builderResults.get(i)); + } + } + + private static List listOf(T a, T b) { + ArrayList list = new ArrayList<>(); + list.add(a); + list.add(b); + return Collections.unmodifiableList(list); + } + + @SuppressWarnings("unchecked") // The prototype's builder produces the same message type T. + private static T parse(T prototype, Marshaler marshaler) { + byte[] serialized = toByteArray(marshaler); + T result; + try { + result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + // Our marshaler should produce the exact same length of serialized output (for example, field + // default values are not outputted), so we check that here. The output itself may have slightly + // different ordering, mostly due to the way we don't output oneof values in field order all the + // tieme. If the lengths are equal and the resulting protos are equal, the marshaling is + // guaranteed to be valid. + assertThat(result.getSerializedSize()).isEqualTo(serialized.length); + + // We don't compare JSON strings due to some differences (particularly serializing enums as + // numbers instead of names). This may improve in the future but what matters is what we produce + // can be parsed. + String json = toJson(marshaler); + Message.Builder builder = prototype.newBuilderForType(); + try { + JsonFormat.parser().merge(json, builder); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + + assertThat(builder.build()).isEqualTo(result); + + return result; + } + + private static byte[] toByteArray(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return bos.toByteArray(); + } + + private static String toJson(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new String(bos.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/exporters/otlp/testing-internal/build.gradle.kts b/exporters/otlp/testing-internal/build.gradle.kts index b32efe082c5..0c5f25c32c6 100644 --- a/exporters/otlp/testing-internal/build.gradle.kts +++ b/exporters/otlp/testing-internal/build.gradle.kts @@ -4,22 +4,43 @@ plugins { description = "OpenTelemetry Exporter Testing (Internal)" otelJava.moduleName.set("io.opentelemetry.exporter.otlp.testing.internal") +otelJava.requireSuppressWarningsExplanation.set(false) dependencies { api(project(":exporters:otlp:common")) api(project(":sdk:logs")) api(project(":sdk:metrics")) + api(project(":sdk:profiles")) api(project(":sdk:trace")) api(project(":sdk:testing")) + // ugly, but profiles doesn't have a separate API yet. + api(project(":exporters:otlp:profiles")) + + api(project(":exporters:otlp:all")) + + // Must be compileOnly so gRPC isn't on the classpath for non-gRPC tests. + compileOnly("io.grpc:grpc-stub") + compileOnly("io.grpc:grpc-netty") + compileOnly("io.grpc:grpc-netty-shaded") + compileOnly("io.grpc:grpc-okhttp") + implementation(project(":testing-internal")) api("io.opentelemetry.proto:opentelemetry-proto") api("org.junit.jupiter:junit-jupiter-api") + implementation("com.squareup.okhttp3:okhttp") implementation("org.junit.jupiter:junit-jupiter-params") + implementation("com.linecorp.armeria:armeria-grpc") implementation("com.linecorp.armeria:armeria-grpc-protocol") implementation("com.linecorp.armeria:armeria-junit5") implementation("io.github.netmikey.logunit:logunit-jul") implementation("org.assertj:assertj-core") + implementation("org.mock-server:mockserver-netty") +} + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false } diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java index 9e49648511f..14487429248 100644 --- a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractGrpcTelemetryExporterTest.java @@ -5,74 +5,140 @@ package io.opentelemetry.exporter.otlp.testing.internal; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.satisfies; +import static java.util.Objects.requireNonNull; +import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assumptions.assumeThat; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; -import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.AbstractMessageLite; import com.google.protobuf.Message; +import com.google.protobuf.Parser; +import com.linecorp.armeria.common.HttpData; +import com.linecorp.armeria.common.HttpHeaders; +import com.linecorp.armeria.common.HttpRequest; +import com.linecorp.armeria.common.HttpResponse; +import com.linecorp.armeria.common.HttpStatus; +import com.linecorp.armeria.common.MediaType; +import com.linecorp.armeria.common.ResponseHeaders; +import com.linecorp.armeria.common.TlsKeyPair; import com.linecorp.armeria.common.grpc.protocol.ArmeriaStatusException; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.server.ServiceRequestContext; -import com.linecorp.armeria.server.grpc.protocol.AbstractUnaryGrpcService; -import com.linecorp.armeria.server.logging.LoggingService; +import com.linecorp.armeria.server.SimpleDecoratingHttpService; +import com.linecorp.armeria.server.grpc.GrpcService; import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; import com.linecorp.armeria.testing.junit5.server.ServerExtension; import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporter; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter; +import io.grpc.Decompressor; +import io.grpc.DecompressorRegistry; +import io.grpc.ManagedChannel; +import io.grpc.stub.StreamObserver; +import io.opentelemetry.exporter.internal.FailedExportException; +import io.opentelemetry.exporter.internal.TlsUtil; import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; +import io.opentelemetry.exporter.otlp.internal.GrpcExporter; +import io.opentelemetry.exporter.otlp.internal.GrpcExporterBuilder; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse; +import io.opentelemetry.proto.collector.logs.v1.LogsServiceGrpc; import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; +import io.opentelemetry.proto.collector.metrics.v1.MetricsServiceGrpc; +import io.opentelemetry.proto.collector.profiles.v1development.ExportProfilesServiceRequest; +import io.opentelemetry.proto.collector.profiles.v1development.ExportProfilesServiceResponse; +import io.opentelemetry.proto.collector.profiles.v1development.ProfilesServiceGrpc; import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; +import io.opentelemetry.proto.collector.trace.v1.TraceServiceGrpc; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.assertj.AttributeAssertion; +import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.UncheckedIOException; +import java.lang.reflect.Field; +import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.security.cert.CertificateEncodingException; import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; +import java.util.Base64; import java.util.Collections; +import java.util.Enumeration; import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.GZIPOutputStream; import javax.annotation.Nullable; -import org.assertj.core.api.iterable.ThrowingExtractor; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; +import org.assertj.core.api.Assertions; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.support.ParameterDeclarations; import org.slf4j.event.Level; import org.slf4j.event.LoggingEvent; +/** Shared OTLP gRPC exporter tests for all telemetry signals. */ @TestInstance(TestInstance.Lifecycle.PER_CLASS) public abstract class AbstractGrpcTelemetryExporterTest { private static final ConcurrentLinkedQueue exportedResourceTelemetry = new ConcurrentLinkedQueue<>(); - private static final ConcurrentLinkedQueue grpcErrors = + private static final ConcurrentLinkedQueue grpcResponses = new ConcurrentLinkedQueue<>(); + private static final ConcurrentLinkedQueue grpcTrailerResponses = + new ConcurrentLinkedQueue<>(); + + private static volatile byte[] defaultResponseBytes = new byte[0]; + private static final AtomicInteger attempts = new AtomicInteger(); + private static final ConcurrentLinkedQueue httpRequests = + new ConcurrentLinkedQueue<>(); + + private static final AtomicInteger grpcEncodingServerAttempts = new AtomicInteger(); + + private static volatile String grpcEncodingServerEncoding = "brotli"; + @RegisterExtension @Order(1) static final SelfSignedCertificateExtension certificate = new SelfSignedCertificateExtension(); @@ -89,68 +155,136 @@ public abstract class AbstractGrpcTelemetryExporterTest { @Override protected void configure(ServerBuilder sb) { sb.service( - "/opentelemetry.proto.collector.trace.v1.TraceService/Export", - new CollectorService<>( - ExportTraceServiceRequest::parseFrom, - ExportTraceServiceRequest::getResourceSpansList, - ExportTraceServiceResponse.getDefaultInstance().toByteArray())); - sb.service( - "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", - new CollectorService<>( - ExportMetricsServiceRequest::parseFrom, - ExportMetricsServiceRequest::getResourceMetricsList, - ExportMetricsServiceResponse.getDefaultInstance().toByteArray())); - sb.service( - "/opentelemetry.proto.collector.logs.v1.LogsService/Export", - new CollectorService<>( - ExportLogsServiceRequest::parseFrom, - ExportLogsServiceRequest::getResourceLogsList, - ExportLogsServiceResponse.getDefaultInstance().toByteArray())); + GrpcService.builder() + .addService( + new LogsServiceGrpc.LogsServiceImplBase() { + @Override + public void export( + ExportLogsServiceRequest request, + StreamObserver responseObserver) { + exportedResourceTelemetry.addAll(request.getResourceLogsList()); + handleExport(responseObserver, ExportLogsServiceResponse.parser()); + } + }) + .addService( + new MetricsServiceGrpc.MetricsServiceImplBase() { + @Override + public void export( + ExportMetricsServiceRequest request, + StreamObserver responseObserver) { + exportedResourceTelemetry.addAll(request.getResourceMetricsList()); + handleExport(responseObserver, ExportMetricsServiceResponse.parser()); + } + }) + .addService( + new TraceServiceGrpc.TraceServiceImplBase() { + @Override + public void export( + ExportTraceServiceRequest request, + StreamObserver responseObserver) { + exportedResourceTelemetry.addAll(request.getResourceSpansList()); + handleExport(responseObserver, ExportTraceServiceResponse.parser()); + } + }) + .addService( + new ProfilesServiceGrpc.ProfilesServiceImplBase() { + @Override + public void export( + ExportProfilesServiceRequest request, + StreamObserver responseObserver) { + exportedResourceTelemetry.addAll(request.getResourceProfilesList()); + handleExport(responseObserver, ExportProfilesServiceResponse.parser()); + } + }) + .decompressorRegistry( + DecompressorRegistry.getDefaultInstance() + .with( + new Decompressor() { + @Override + public String getMessageEncoding() { + return "base64"; + } + + @Override + public InputStream decompress(InputStream is) { + return Base64.getDecoder().wrap(is); + } + }, + true)) + .build(), + service -> + new SimpleDecoratingHttpService(service) { + @Override + public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) + throws Exception { + httpRequests.add(req); + attempts.incrementAndGet(); + HttpResponse trailerResponse = grpcTrailerResponses.poll(); + if (trailerResponse != null) { + return trailerResponse; + } + return unwrap().serve(ctx, req); + } + }); sb.http(0); sb.https(0); - sb.tls(certificate.certificateFile(), certificate.privateKeyFile()); + sb.tls(TlsKeyPair.of(certificate.privateKey(), certificate.certificate())); sb.tlsCustomizer(ssl -> ssl.trustManager(clientCertificate.certificate())); - sb.decorator(LoggingService.newDecorator()); + // Uncomment for detailed request / response logs from server + // sb.decorator(LoggingService.newDecorator()); } }; - private static class CollectorService extends AbstractUnaryGrpcService { - private final ThrowingExtractor parse; - private final Function> getResourceTelemetry; - private final byte[] successResponse; - - private CollectorService( - ThrowingExtractor parse, - Function> getResourceTelemetry, - byte[] successResponse) { - this.parse = parse; - this.getResourceTelemetry = getResourceTelemetry; - this.successResponse = successResponse; - } - - @Override - protected CompletionStage handleMessage(ServiceRequestContext ctx, byte[] message) { - attempts.incrementAndGet(); - T request; + private static void handleExport( + StreamObserver responseObserver, Parser parser) { + GrpcServerResponse grpcResponse = grpcResponses.poll(); + if (grpcResponse != null && grpcResponse.error != null) { + responseObserver.onError(grpcResponse.error); + } else { try { - request = parse.extractThrows(message); - } catch (InvalidProtocolBufferException e) { + byte[] responseBytes = + grpcResponse != null && grpcResponse.responseBytes != null + ? grpcResponse.responseBytes + : defaultResponseBytes; + responseObserver.onNext(parser.parseFrom(responseBytes)); + } catch (IOException e) { throw new UncheckedIOException(e); } - exportedResourceTelemetry.addAll(getResourceTelemetry.apply(request)); - ArmeriaStatusException grpcError = grpcErrors.poll(); - if (grpcError != null) { - throw grpcError; - } - return CompletableFuture.completedFuture(successResponse); + responseObserver.onCompleted(); } } + // A minimal server that returns a configurable grpc-encoding to test encoding handling. + // The encoding is controlled via grpcEncodingServerEncoding (defaults to "brotli"). + // Both OkHttpGrpcSender (our code) and UpstreamGrpcSender (grpc-java framework) reject unknown + // encodings and fail the export with INTERNAL status. @RegisterExtension - LogCapturer logs = - LogCapturer.create() - .captureForType(usingOkHttp() ? OkHttpGrpcExporter.class : DefaultGrpcExporter.class); + @Order(4) + static final ServerExtension grpcEncodingServer = + new ServerExtension() { + @Override + protected void configure(ServerBuilder sb) { + sb.service( + "prefix:/", + (ctx, req) -> { + grpcEncodingServerAttempts.incrementAndGet(); + // gRPC frame: compressed flag=1, declared length=0 (no payload bytes follow) + byte[] frame = {1, 0, 0, 0, 0}; + return HttpResponse.of( + ResponseHeaders.builder(HttpStatus.OK) + .contentType(MediaType.parse("application/grpc+proto")) + .add("grpc-encoding", grpcEncodingServerEncoding) + .add("grpc-status", "0") + .build(), + HttpData.wrap(frame)); + }); + sb.http(0); + } + }; + + @RegisterExtension + protected LogCapturer logs = LogCapturer.create().captureForType(GrpcExporter.class); private final String type; private final U resourceTelemetryInstance; @@ -164,7 +298,36 @@ protected AbstractGrpcTelemetryExporterTest(String type, U resourceTelemetryInst @BeforeAll void setUp() { - exporter = exporterBuilder().setEndpoint(server.httpUri().toString()).build(); + exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + // We don't validate backoff time itself in these tests, just that retries + // occur. Keep the tests fast by using minimal backoff. + .setRetryPolicy( + RetryPolicy.getDefault().toBuilder() + .setMaxAttempts(2) + .setInitialBackoff(Duration.ofMillis(1)) + .build()) + .build(); + defaultResponseBytes = exporter.exportResponse(0).toByteArray(); + + // Sanity check that TLS files are in PEM format. + assertThat(certificate.certificateFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN CERTIFICATE-----"); + assertThat(certificate.privateKeyFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN PRIVATE KEY-----"); + assertThat(clientCertificate.certificateFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN CERTIFICATE-----"); + assertThat(clientCertificate.privateKeyFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN PRIVATE KEY-----"); } @AfterAll @@ -175,8 +338,30 @@ void tearDown() { @AfterEach void reset() { exportedResourceTelemetry.clear(); - grpcErrors.clear(); + grpcResponses.clear(); + grpcTrailerResponses.clear(); attempts.set(0); + httpRequests.clear(); + grpcEncodingServerAttempts.set(0); + grpcEncodingServerEncoding = "brotli"; + } + + @Test + void minimalChannel() { + // Test that UpstreamGrpcSender uses minimal fallback managed channel, so skip for + // OkHttpGrpcSender + assumeThat(exporter.unwrap()) + .extracting("delegate.grpcSender") + .matches(sender -> sender.getClass().getSimpleName().equals("UpstreamGrpcSender")); + // When no channel is explicitly set, should fall back to a minimally configured managed channel + try (TelemetryExporter exporter = exporterBuilder().build()) { + assertThat(exporter.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(exporter.unwrap()) + .extracting( + "delegate.grpcSender.channel", + as(InstanceOfAssertFactories.type(ManagedChannel.class))) + .satisfies(channel -> assertThat(channel.isShutdown()).isTrue()); + } } @Test @@ -185,6 +370,134 @@ void export() { assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); List expectedResourceTelemetry = toProto(telemetry); assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); + + // Assert request contains OTLP spec compliant User-Agent header + assertThat(httpRequests) + .singleElement() + .satisfies(req -> + assertThat(req.headers().get("User-Agent")).matches("OTel-OTLP-Exporter-Java/1\\..*")); + } + + @Test + // @SuppressLogger(HttpExporter.class) + void responseBodyBounds() { + // We have a 4mb hardcoded response body limit. Responses <= 4mb succeed. Responses >= 4mb + // fail. We can't test payloads exactly at 4mb because protobuf message lengths are finicky - + // its hard to create a message with an exact size. + + // Body below the limit, succeeds + addGrpcResponse(GrpcStatusCode.OK, null, exporter.exportResponse(100)); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isTrue(); + + // Body over the limit, fails with RESOURCE_EXHAUSTED + addGrpcResponse(GrpcStatusCode.OK, null, exporter.exportResponse(4 * 1024 * 1024 + 1)); + result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.GrpcExportException.class, + ex -> + assertThat(requireNonNull(ex.getResponse())) + .isNotNull() + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED))); + } + + @Test + @SuppressLogger(GrpcExporter.class) + void responseBodyBoundsGzipCompressed() throws IOException { + // Verify the body size limit is applied to the decompressed bytes, not the compressed wire + // bytes. The server compresses the response with gzip (because the sender advertises + // grpc-accept-encoding: gzip), so the wire bytes are well under 4MB while the decompressed + // bytes exceed it. + AbstractMessageLite responseMsg = exporter.exportResponse(4 * 1024 * 1024 + 1); + byte[] responseBytes = responseMsg.toByteArray(); + // Sanity: confirm payload is over the limit uncompressed but compresses well under the limit + assertThat(responseBytes).hasSizeGreaterThan(4 * 1024 * 1024); + ByteArrayOutputStream compressedBaos = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(compressedBaos)) { + gzip.write(responseBytes); + } + assertThat(compressedBaos.toByteArray()).hasSizeLessThan(4 * 1024 * 1024); + + addGrpcResponse(GrpcStatusCode.OK, null, responseMsg); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.GrpcExportException.class, + ex -> + assertThat(requireNonNull(ex.getResponse())) + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.RESOURCE_EXHAUSTED))); + } + + // Verifies that a response with an unrecognized grpc-encoding fails with INTERNAL rather than + // attempting to decompress with an unsupported algorithm. + @Test + @SuppressLogger(GrpcExporter.class) + void unsupportedGrpcMessageEncoding() { + try (TelemetryExporter testExporter = + exporterBuilder() + .setEndpoint(grpcEncodingServer.httpUri().toString()) + .setRetryPolicy(null) + .build()) { + CompletableResultCode result = + testExporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(grpcEncodingServerAttempts).hasValue(1); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.GrpcExportException.class, + ex -> + assertThat(requireNonNull(ex.getResponse())) + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.INTERNAL))); + } + } + + // Verifies that a response with flag=1 and grpc-encoding: identity is rejected with INTERNAL. + // Although identity is advertised in grpc-accept-encoding (meaning "no encoding applied"), + // a server setting the compressed flag to 1 is contradictory and should not be accepted. + @Test + @SuppressLogger(GrpcExporter.class) + void identityGrpcMessageEncodingWithCompressedFlagRejected() { + grpcEncodingServerEncoding = "identity"; + try (TelemetryExporter testExporter = + exporterBuilder() + .setEndpoint(grpcEncodingServer.httpUri().toString()) + .setRetryPolicy(null) + .build()) { + CompletableResultCode result = + testExporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(grpcEncodingServerAttempts).hasValue(1); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.GrpcExportException.class, + ex -> + assertThat(requireNonNull(ex.getResponse())) + .satisfies(grpcResponse -> + assertThat(grpcResponse.getStatusCode()) + .isEqualTo(GrpcStatusCode.INTERNAL))); + } } @Test @@ -198,102 +511,270 @@ void multipleItems() { assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); } + @Test + void compressionWithNone() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri().toString()).setCompression("none").build()) { + + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isTrue(); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.headers().get("grpc-encoding")).isNull()); + } + } + + @Test + void compressionWithGzip() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri().toString()).setCompression("gzip").build()) { + + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isTrue(); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.headers().get("grpc-encoding")).isEqualTo("gzip")); + } + } + + @Test + void compressionWithSpiCompressor() { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .setCompression("base64") + .build()) { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isTrue(); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.headers().get("grpc-encoding")).isEqualTo("base64")); + } + } + @Test void authorityWithAuth() { - TelemetryExporter exporter = - exporterBuilder().setEndpoint("http://foo:bar@localhost:" + server.httpPort()).build(); - try { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint("http://foo:bar@localhost:" + server.httpPort()).build()) { CompletableResultCode result = exporter.export(Collections.singletonList(generateFakeTelemetry())); assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); - } finally { - exporter.shutdown(); + } + } + + @Test + void withHeaders() { + AtomicInteger count = new AtomicInteger(); + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .addHeader("key1", "value1") + .setHeaders(() -> Collections.singletonMap("key2", "value" + count.incrementAndGet())) + .build()) { + // Export twice to ensure header supplier gets invoked twice + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + result = exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + + assertThat(httpRequests) + .satisfiesExactly( + req -> { + assertThat(req.headers().get("key1")).isEqualTo("value1"); + assertThat(req.headers().get("key2")).isEqualTo("value" + (count.get() - 1)); + }, + req -> { + assertThat(req.headers().get("key1")).isEqualTo("value1"); + assertThat(req.headers().get("key2")).isEqualTo("value" + count.get()); + }); } } @Test void tls() throws Exception { - TelemetryExporter exporter = + try (TelemetryExporter exporter = + exporterBuilder() + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .setClientTls( + certificate.privateKey().getEncoded(), certificate.certificate().getEncoded()) + .setEndpoint(server.httpsUri().toString()) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void tlsViaSslContext() throws Exception { + X509TrustManager trustManager = TlsUtil.trustManager(certificate.certificate().getEncoded()); + + X509KeyManager keyManager = + TlsUtil.keyManager( + certificate.privateKey().getEncoded(), certificate.certificate().getEncoded()); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null); + + try (TelemetryExporter exporter = + exporterBuilder() + .setSslContext(sslContext, trustManager) + .setEndpoint(server.httpsUri().toString()) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void enabledProtocols() throws Exception { + try (TelemetryExporter exporter = exporterBuilder() .setEndpoint(server.httpsUri().toString()) .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) - .build(); - try { + .setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3")) + .build()) { CompletableResultCode result = exporter.export(Collections.singletonList(generateFakeTelemetry())); assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); - } finally { - exporter.shutdown(); } } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) + @SuppressLogger(GrpcExporter.class) + void enabledProtocols_restrictedProtocolsFail() throws Exception { + assumeThat(System.getProperty("io.opentelemetry.sdk.common.export.GrpcSenderProvider")) + .as("enabledProtocols is not supported by UpstreamGrpcSenderProvider") + .isNotEqualTo( + "io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider"); + + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpsUri().toString()) + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .setEnabledProtocols(Collections.singletonList("TLSv1.1")) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + } + } + + @Test + @SuppressLogger(GrpcExporter.class) void tls_untrusted() { - TelemetryExporter exporter = - exporterBuilder().setEndpoint(server.httpsUri().toString()).build(); - try { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpsUri().toString()).build()) { CompletableResultCode result = exporter.export(Collections.singletonList(generateFakeTelemetry())); assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); - } finally { - exporter.shutdown(); } } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) void tls_badCert() { - assertThatThrownBy( - () -> - exporterBuilder() - .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8)) - .build()) + assertThatThrownBy(() -> + exporterBuilder() + .setEndpoint(server.httpsUri().toString()) + .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) .isInstanceOf(IllegalStateException.class) - .hasMessageContaining("Could not set trusted certificates"); + .hasMessageContaining("Error creating X509TrustManager with provided certs."); } - @Test - void clientTls() throws Exception { - TelemetryExporter exporter = + @ParameterizedTest + @ArgumentsSource(ClientPrivateKeyProvider.class) + void clientTls(byte[] privateKey) throws Exception { + try (TelemetryExporter exporter = exporterBuilder() .setEndpoint(server.httpsUri().toString()) .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) .setClientTls( - clientCertificate.privateKey().getEncoded(), - clientCertificate.certificate().getEncoded()) - .build(); - try { + privateKey, Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .build()) { CompletableResultCode result = exporter.export(Collections.singletonList(generateFakeTelemetry())); assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); - } finally { - exporter.shutdown(); + } + } + + private static class ClientPrivateKeyProvider implements ArgumentsProvider { + @Override + @SuppressWarnings("PrimitiveArrayPassedToVarargsMethod") + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) throws Exception { + return Stream.of( + arguments(named("PEM", Files.readAllBytes(clientCertificate.privateKeyFile().toPath()))), + arguments(named("DER", clientCertificate.privateKey().getEncoded()))); + } + } + + @Test + @SuppressLogger(GrpcExporter.class) + void connectTimeout() { + // UpstreamGrpcSender doesn't support connectTimeout, so we skip the test + assumeThat(exporter.unwrap()) + .extracting("delegate.grpcSender") + .matches(sender -> sender.getClass().getSimpleName().equals("OkHttpGrpcSender")); + + try (TelemetryExporter exporter = + exporterBuilder() + // Connecting to a non-routable IP address to trigger connection error + .setEndpoint("http://10.255.255.1") + .setConnectTimeout(Duration.ofMillis(1)) + .setRetryPolicy(null) + .build()) { + long startTimeMillis = System.currentTimeMillis(); + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + + assertThat(result.getFailureThrowable()) + .asInstanceOf( + InstanceOfAssertFactories.throwable(FailedExportException.GrpcExportException.class)) + .returns(false, Assertions.from(FailedExportException::failedWithResponse)) + .satisfies(ex -> { + assertThat(ex.getResponse()).isNull(); + assertThat(ex.getCause()).isNotNull(); + }); + + // Assert that the export request fails well before the default connect timeout of 10s + // Note: Connection failures to non-routable IPs can take 1-5 seconds depending on OS/network + assertThat(System.currentTimeMillis() - startTimeMillis) + .isLessThan(TimeUnit.SECONDS.toMillis(6)); } } @Test void deadlineSetPerExport() throws InterruptedException { - TelemetryExporter exporter = + try (TelemetryExporter exporter = exporterBuilder() .setEndpoint(server.httpUri().toString()) .setTimeout(Duration.ofMillis(1500)) - .build(); - try { + .build()) { TimeUnit.MILLISECONDS.sleep(2000); CompletableResultCode result = exporter.export(Collections.singletonList(generateFakeTelemetry())); assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); - } finally { - exporter.shutdown(); } } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) + @SuppressLogger(GrpcExporter.class) void exportAfterShutdown() { TelemetryExporter exporter = exporterBuilder().setEndpoint(server.httpUri().toString()).build(); @@ -304,212 +785,358 @@ void exportAfterShutdown() { .join(10, TimeUnit.SECONDS) .isSuccess()) .isFalse(); + assertThat(httpRequests).isEmpty(); } @Test + @SuppressLogger(GrpcExporter.class) void doubleShutdown() { TelemetryExporter exporter = exporterBuilder().setEndpoint(server.httpUri().toString()).build(); assertThat(exporter.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(logs.getEvents()).isEmpty(); assertThat(exporter.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) + @SuppressLogger(GrpcExporter.class) void error() { - addGrpcError(13, null); - assertThat( - exporter - .export(Collections.singletonList(generateFakeTelemetry())) - .join(10, TimeUnit.SECONDS) - .isSuccess()) - .isFalse(); - LoggingEvent log = - logs.assertContains( - "Failed to export " - + type - + "s. Server responded with gRPC status code 13. Error message:"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); + GrpcStatusCode statusCode = GrpcStatusCode.INTERNAL; + addGrpcResponse(statusCode, null); + + try (TelemetryExporter exporter = nonRetryingExporter()) { + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + + assertThat(result.isSuccess()).isFalse(); + + assertThat(result.getFailureThrowable()) + .asInstanceOf( + InstanceOfAssertFactories.throwable(FailedExportException.GrpcExportException.class)) + .returns(true, Assertions.from(FailedExportException::failedWithResponse)) + .satisfies(ex -> { + assertThat(ex.getResponse()) + .isNotNull() + .extracting(GrpcResponse::getStatusCode) + .isEqualTo(statusCode); + + assertThat(ex.getCause()).isNull(); + }); + + LoggingEvent log = + logs.assertContains( + "Failed to export 1 " + + type + + "s. Server responded with gRPC status code 13. Error message:"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + } + } + + @Test + @SuppressLogger(GrpcExporter.class) + void errorWithUnknownError() { + addGrpcResponse(GrpcStatusCode.UNKNOWN, null); + + try (TelemetryExporter exporter = nonRetryingExporter()) { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .getFailureThrowable()) + .asInstanceOf( + InstanceOfAssertFactories.throwable(FailedExportException.GrpcExportException.class)) + .returns(true, Assertions.from(FailedExportException::failedWithResponse)) + .satisfies(ex -> { + assertThat(ex.getResponse()).isNotNull(); + + assertThat(ex.getCause()).isNull(); + }); + } } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) + @SuppressLogger(GrpcExporter.class) void errorWithMessage() { - addGrpcError(8, "out of quota"); - assertThat( - exporter - .export(Collections.singletonList(generateFakeTelemetry())) - .join(10, TimeUnit.SECONDS) - .isSuccess()) - .isFalse(); - LoggingEvent log = - logs.assertContains( - "Failed to export " - + type - + "s. Server responded with gRPC status code 8. Error message: out of quota"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); + addGrpcResponse(GrpcStatusCode.RESOURCE_EXHAUSTED, "out of quota"); + + try (TelemetryExporter exporter = nonRetryingExporter()) { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + LoggingEvent log = + logs.assertContains( + "Failed to export 1 " + + type + + "s. Server responded with gRPC status code 8. Error message: out of quota"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + } } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) + @SuppressLogger(GrpcExporter.class) void errorWithEscapedMessage() { - addGrpcError(5, "γ‚―γƒžπŸ»"); + addGrpcResponse(GrpcStatusCode.NOT_FOUND, "γ‚―γƒžπŸ»"); + + try (TelemetryExporter exporter = nonRetryingExporter()) { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + LoggingEvent log = + logs.assertContains( + "Failed to export 1 " + + type + + "s. Server responded with gRPC status code 5. Error message: γ‚―γƒžπŸ»"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + } + } + + @Test + @SuppressLogger(GrpcExporter.class) + void testExport_Unavailable() { + addGrpcResponse(GrpcStatusCode.UNAVAILABLE, null); + + try (TelemetryExporter exporter = nonRetryingExporter()) { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + LoggingEvent log = + logs.assertContains( + "Failed to export 1 " + + type + + "s. Server is UNAVAILABLE. " + + "Make sure your collector is running and reachable from this network."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + } + } + + @Test + @SuppressLogger(GrpcExporter.class) + protected void testExport_Unimplemented() { + addGrpcResponse(GrpcStatusCode.UNIMPLEMENTED, "UNIMPLEMENTED"); + + try (TelemetryExporter exporter = nonRetryingExporter()) { + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + String envVar; + switch (type) { + case "span": + envVar = "OTEL_TRACES_EXPORTER"; + break; + case "metric": + envVar = "OTEL_METRICS_EXPORTER"; + break; + case "log": + envVar = "OTEL_LOGS_EXPORTER"; + break; + case "profile": + envVar = "OTEL_PROFILES_EXPORTER"; + break; + default: + throw new AssertionError(); + } + LoggingEvent log = + logs.assertContains( + "Failed to export " + + type + + "s. Server responded with UNIMPLEMENTED. " + + "This usually means that your collector is not configured with an otlp " + + "receiver in the \"pipelines\" section of the configuration. " + + "If export is not desired and you are using OpenTelemetry autoconfiguration " + + "or the javaagent, " + + "disable export by setting " + + envVar + + "=none. " + + "Full error message: UNIMPLEMENTED"); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + } + } + + @ParameterizedTest + @ValueSource(ints = {1, 4, 8, 10, 11, 14, 15}) + @SuppressLogger(GrpcExporter.class) + void retryableError(int code) { + addGrpcResponse(GrpcStatusCode.fromValue(code), null); + assertThat( exporter .export(Collections.singletonList(generateFakeTelemetry())) .join(10, TimeUnit.SECONDS) .isSuccess()) - .isFalse(); - LoggingEvent log = - logs.assertContains( - "Failed to export " - + type - + "s. Server responded with gRPC status code 5. Error message: γ‚―γƒžπŸ»"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); + .isTrue(); + + assertThat(attempts).hasValue(2); + } + + @ParameterizedTest + @ValueSource(ints = {1, 4, 8, 10, 11, 14, 15}) + @SuppressLogger(GrpcExporter.class) + void retryableErrorInTrailers(int code) { + // grpc-java commits the RPC on initial response headers, preventing trailer-based retries. + assumeThat(exporter.unwrap()) + .extracting("delegate.grpcSender") + .matches(sender -> sender.getClass().getSimpleName().equals("OkHttpGrpcSender")); + + grpcTrailerResponses.add( + HttpResponse.of( + ResponseHeaders.builder(HttpStatus.OK) + .contentType(MediaType.parse("application/grpc+proto")) + .build(), + HttpData.empty(), + HttpHeaders.of("grpc-status", Integer.toString(code)))); + + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + + assertThat(attempts).hasValue(2); + assertThat(result.isSuccess()).isTrue(); } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) - void testExport_Unavailable() { - addGrpcError(14, null); + @SuppressLogger(GrpcExporter.class) + void retryableError_tooManyAttempts() { + addGrpcResponse(GrpcStatusCode.CANCELLED, null); + addGrpcResponse(GrpcStatusCode.CANCELLED, null); + assertThat( exporter .export(Collections.singletonList(generateFakeTelemetry())) .join(10, TimeUnit.SECONDS) .isSuccess()) .isFalse(); - LoggingEvent log = - logs.assertContains( - "Failed to export " - + type - + "s. Server is UNAVAILABLE. " - + "Make sure your collector is running and reachable from this network."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); + + assertThat(attempts).hasValue(2); } - @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) - void testExport_Unimplemented() { - addGrpcError(12, "UNIMPLEMENTED"); + @ParameterizedTest + @ValueSource(ints = {2, 3, 5, 6, 7, 9, 12, 13, 16}) + @SuppressLogger(GrpcExporter.class) + void nonRetryableError(int code) { + addGrpcResponse(GrpcStatusCode.fromValue(code), null); + assertThat( exporter .export(Collections.singletonList(generateFakeTelemetry())) .join(10, TimeUnit.SECONDS) .isSuccess()) .isFalse(); - String envVar; - switch (type) { - case "span": - envVar = "OTLP_TRACES_EXPORTER"; - break; - case "metric": - envVar = "OTLP_METRICS_EXPORTER"; - break; - case "log": - envVar = "OTLP_LOGS_EXPORTER"; - break; - default: - throw new AssertionError(); - } - LoggingEvent log = - logs.assertContains( - "Failed to export " - + type - + "s. Server responded with UNIMPLEMENTED. " - + "This usually means that your collector is not configured with an otlp " - + "receiver in the \"pipelines\" section of the configuration. " - + "If export is not desired and you are using OpenTelemetry autoconfiguration or the javaagent, " - + "disable export by setting " - + envVar - + "=none. " - + "Full error message: UNIMPLEMENTED"); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - } - @ParameterizedTest - @ValueSource(ints = {1, 4, 8, 10, 11, 14, 15}) - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) - void retryableError(int code) { - addGrpcError(code, null); - - TelemetryExporter exporter = retryingExporter(); + assertThat(attempts).hasValue(1); + } - try { - assertThat( - exporter - .export(Collections.singletonList(generateFakeTelemetry())) - .join(10, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - } finally { - exporter.shutdown(); + @Test + void overrideHost() { + List telemetry = Collections.singletonList(generateFakeTelemetry()); + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .addHeader("host", "opentelemetry") + .build()) { + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); } + List expectedResourceTelemetry = toProto(telemetry); + assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); - assertThat(attempts).hasValue(2); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.authority()).isEqualTo("opentelemetry")); } @Test - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) - void retryableError_tooManyAttempts() { - addGrpcError(1, null); - addGrpcError(1, null); - - TelemetryExporter exporter = retryingExporter(); - - try { - assertThat( - exporter - .export(Collections.singletonList(generateFakeTelemetry())) - .join(10, TimeUnit.SECONDS) - .isSuccess()) - .isFalse(); - } finally { - exporter.shutdown(); + void overrideHostMixedCase() { + List telemetry = Collections.singletonList(generateFakeTelemetry()); + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .addHeader("Host", "opentelemetry") + .build()) { + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); } + List expectedResourceTelemetry = toProto(telemetry); + assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); - assertThat(attempts).hasValue(2); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.authority()).isEqualTo("opentelemetry")); } - @ParameterizedTest - @ValueSource(ints = {2, 3, 5, 6, 7, 9, 12, 13, 16}) - @SuppressLogger(OkHttpGrpcExporter.class) - @SuppressLogger(DefaultGrpcExporter.class) - void nonRetryableError(int code) { - addGrpcError(code, null); + @Test + void executorService() { + ExecutorServiceSpy executorService = + new ExecutorServiceSpy(Executors.newSingleThreadExecutor()); - TelemetryExporter exporter = retryingExporter(); + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .setExecutorService(executorService) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); - try { - assertThat( - exporter - .export(Collections.singletonList(generateFakeTelemetry())) - .join(10, TimeUnit.SECONDS) - .isSuccess()) - .isFalse(); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(executorService.getTaskCount()).isPositive(); } finally { - exporter.shutdown(); + // If setting executor, the user is responsible for calling shutdown + assertThat(executorService.isShutdown()).isFalse(); + executorService.shutdown(); } - - assertThat(attempts).hasValue(1); } @Test @SuppressWarnings("PreferJavaTimeOverload") void validConfig() { - assertThatCode(() -> exporterBuilder().setTimeout(0, TimeUnit.MILLISECONDS)) + // We must build exporters to test timeout settings, which intersect with underlying client + // implementations and may convert between Duration, int, and long, which may be susceptible to + // overflow exceptions. + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(0, TimeUnit.MILLISECONDS))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofMillis(0)))) + .doesNotThrowAnyException(); + assertThatCode(() -> + buildAndShutdown(exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.NANOSECONDS))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofNanos(Long.MAX_VALUE)))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.SECONDS))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(10, TimeUnit.MILLISECONDS))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofMillis(10)))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(0, TimeUnit.MILLISECONDS))) .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(0))) + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(Duration.ofMillis(0)))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(10, TimeUnit.MILLISECONDS))) .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(10, TimeUnit.MILLISECONDS)) + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(Duration.ofMillis(10)))) .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(10))) + assertThatCode(() -> buildAndShutdown(exporterBuilder().setMaxRequestSize(1))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setMaxRequestSize(0))) .doesNotThrowAnyException(); assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost:4317")) @@ -522,17 +1149,57 @@ void validConfig() { .doesNotThrowAnyException(); assertThatCode(() -> exporterBuilder().setCompression("gzip")).doesNotThrowAnyException(); + // SPI compressor available for this test but not packaged with OTLP exporter + assertThatCode(() -> exporterBuilder().setCompression("base64")).doesNotThrowAnyException(); assertThatCode(() -> exporterBuilder().setCompression("none")).doesNotThrowAnyException(); assertThatCode(() -> exporterBuilder().addHeader("foo", "bar").addHeader("baz", "qux")) .doesNotThrowAnyException(); assertThatCode( - () -> - exporterBuilder().setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) + () -> exporterBuilder().setTrustedCertificates(certificate.certificate().getEncoded())) + .doesNotThrowAnyException(); + + assertThatCode(() -> exporterBuilder().setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3"))) .doesNotThrowAnyException(); } + @Test + void customServiceClassLoader() { + ClassLoaderSpy classLoaderSpy = + new ClassLoaderSpy(AbstractHttpTelemetryExporterTest.class.getClassLoader()); + + try (TelemetryExporter exporter = + exporterBuilder() + .setServiceClassLoader(classLoaderSpy) + .setEndpoint(server.httpUri().toString()) + .build()) { + assertThat(classLoaderSpy.getResourcesNames) + .isEqualTo( + Collections.singletonList( + "META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider")); + } + } + + private static class ClassLoaderSpy extends ClassLoader { + private final List getResourcesNames = new ArrayList<>(); + + private ClassLoaderSpy(ClassLoader delegate) { + super(delegate); + } + + @Override + public Enumeration getResources(String name) throws IOException { + getResourcesNames.add(name); + return super.getResources(name); + } + } + + private void buildAndShutdown(TelemetryExporterBuilder builder) { + TelemetryExporter build = builder.build(); + build.shutdown().join(10, TimeUnit.MILLISECONDS); + } + @Test @SuppressWarnings({"PreferJavaTimeOverload", "NullAway"}) void invalidConfig() { @@ -545,6 +1212,23 @@ void invalidConfig() { assertThatThrownBy(() -> exporterBuilder().setTimeout(null)) .isInstanceOf(NullPointerException.class) .hasMessage("timeout"); + assertThatThrownBy(() -> + buildAndShutdown(exporterBuilder().setTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + .isInstanceOf(ArithmeticException.class); + + assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(-1, TimeUnit.MILLISECONDS)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("timeout must be non-negative"); + assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); + assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("timeout"); + assertThatThrownBy(() -> + buildAndShutdown( + exporterBuilder().setConnectTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + .isInstanceOf(ArithmeticException.class); assertThatThrownBy(() -> exporterBuilder().setEndpoint(null)) .isInstanceOf(NullPointerException.class) @@ -565,62 +1249,319 @@ void invalidConfig() { assertThatThrownBy(() -> exporterBuilder().setCompression("foo")) .isInstanceOf(IllegalArgumentException.class) .hasMessage( - "Unsupported compression method. Supported compression methods include: gzip, none."); + "Unsupported compressionMethod. Compression method must be \"none\" or one of: [base64,gzip]"); + assertThatThrownBy(() -> exporterBuilder().setMaxRequestSize(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxRequestMessageSizeBytes must be non-negative"); + + assertThatThrownBy(() -> exporterBuilder().setEnabledProtocols(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("enabledProtocols"); + assertThatThrownBy(() -> exporterBuilder().setEnabledProtocols(Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("enabledProtocols must not be empty"); + } + + @Test + void requestMessageSizeLimit() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri().toString()).setMaxRequestSize(1).build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .hasMessageContaining("Failed to export") + .hasMessageContaining("Request message size") + .hasMessageContaining("exceeded limit of 1 bytes"); + } + } + + @Test + void requestMessageSizeLimitDisabledWithZero() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri().toString()).setMaxRequestSize(0).build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void toBuilderEquality() + throws CertificateEncodingException, + IOException, + NoSuchFieldException, + IllegalAccessException { + try (TelemetryExporter exporter = + exporterBuilder() + .setTimeout(Duration.ofSeconds(5)) + .setEndpoint("http://localhost:4317") + .setCompression("gzip") + .addHeader("foo", "bar") + .setTrustedCertificates(certificate.certificate().getEncoded()) + .setClientTls( + Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), + Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .setRetryPolicy( + RetryPolicy.builder() + .setMaxAttempts(2) + .setMaxBackoff(Duration.ofSeconds(3)) + .setInitialBackoff(Duration.ofMillis(50)) + .setBackoffMultiplier(1.3) + .build()) + .setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3")) + .build()) { + Object unwrapped = exporter.unwrap(); + Field builderField = unwrapped.getClass().getDeclaredField("builder"); + builderField.setAccessible(true); + + // Builder copy should be equal to original when unchanged + TelemetryExporter copy = toBuilder(exporter).build(); + try { + assertThat(copy.unwrap()) + .extracting("builder") + .usingRecursiveComparison() + .withStrictTypeChecking() + .ignoringFields("tlsConfigHelper") + .isEqualTo(builderField.get(unwrapped)); + } finally { + copy.shutdown(); + } + + // Builder copy should NOT be equal when changed + copy = toBuilder(exporter).addHeader("baz", "qux").build(); + try { + assertThat(copy.unwrap()) + .extracting("builder") + .usingRecursiveComparison() + .withStrictTypeChecking() + .ignoringFields("tlsConfigHelper") + .isNotEqualTo(builderField.get(unwrapped)); + } finally { + copy.shutdown(); + } + } + } + + @Test + void stringRepresentation() throws IOException, CertificateEncodingException { + try (TelemetryExporter telemetryExporter = + exporterBuilder().setEndpoint("http://localhost:4317").build()) { + assertThat(telemetryExporter.unwrap().toString()) + .matches( + "OtlpGrpc[a-zA-Z]*Exporter\\{" + + "endpoint=http://localhost:4317, " + + "fullMethodName=.*, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "compressorEncoding=null, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}" + + ".*maxRequestMessageSize=" + + GrpcExporterBuilder.DEFAULT_MAX_REQUEST_MESSAGE_SIZE + + ".*" // Maybe additional grpcChannel field, signal specific fields + + "\\}"); + } + + try (TelemetryExporter telemetryExporter = + exporterBuilder() + .setTimeout(Duration.ofSeconds(5)) + .setConnectTimeout(Duration.ofSeconds(4)) + .setEndpoint("http://example:4317") + .setCompression("gzip") + .addHeader("foo", "bar") + .setTrustedCertificates(certificate.certificate().getEncoded()) + .setClientTls( + Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), + Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .setRetryPolicy( + RetryPolicy.builder() + .setMaxAttempts(2) + .setMaxBackoff(Duration.ofSeconds(3)) + .setInitialBackoff(Duration.ofMillis(50)) + .setBackoffMultiplier(1.3) + .build()) + .setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3")) + .build(); ) { + assertThat(telemetryExporter.unwrap().toString()) + .matches( + "OtlpGrpc[a-zA-Z]*Exporter\\{" + + "endpoint=http://example:4317, " + + "fullMethodName=.*, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(5) + + ", " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(4) + + ", " + + "compressorEncoding=gzip, " + + "headers=Headers\\{.*foo=OBFUSCATED.*\\}, " + + "retryPolicy=RetryPolicy\\{maxAttempts=2, initialBackoff=PT0\\.05S, " + + "maxBackoff=PT3S, backoffMultiplier=1\\.3, " + + "retryExceptionPredicate=null\\}" + + ".*maxRequestMessageSize=" + + GrpcExporterBuilder.DEFAULT_MAX_REQUEST_MESSAGE_SIZE + + ".*" // Maybe additional grpcChannel field, signal specific fields + + "\\}") + .contains("enabledProtocols=[TLSv1.2, TLSv1.3]"); + } + } + + @Test + void latestInternalTelemetry() { + // Profiles do not expose metrics yet, so skip + assumeThat(type).isNotEqualTo("profile"); + + InMemoryMetricReader inMemoryMetrics = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(inMemoryMetrics).build(); + TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .setMeterProvider(() -> meterProvider) + .setInternalTelemetryVersion(InternalTelemetryVersion.LATEST) + .build()) { + + List telemetry = Collections.singletonList(generateFakeTelemetry()); + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + + List expectedAttributes = + Arrays.asList( + satisfies( + SemConvConstants.OTEL_COMPONENT_TYPE, + str -> str.matches("otlp_grpc_(log|metric|span)_exporter")), + satisfies( + SemConvConstants.OTEL_COMPONENT_NAME, + str -> str.matches("otlp_grpc_(log|metric|span)_exporter/\\d+")), + satisfies( + SemConvConstants.SERVER_PORT, str -> str.isEqualTo(server.httpUri().getPort())), + satisfies( + SemConvConstants.SERVER_ADDRESS, + str -> str.isEqualTo(server.httpUri().getHost()))); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(3) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).inflight")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).exported")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying(expectedAttributes).hasBucketCounts(1)))); + } + } + + @Test + void legacyInternalTelemetry() { + // Profiles do not expose metrics yet, so skip + assumeThat(type).isNotEqualTo("profile"); + + InMemoryMetricReader inMemoryMetrics = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(inMemoryMetrics).build(); + TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri().toString()) + .setMeterProvider(() -> meterProvider) + .setInternalTelemetryVersion(InternalTelemetryVersion.LEGACY) + .build()) { + + List telemetry = Collections.singletonList(generateFakeTelemetry()); + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(2) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otlp.exporter.seen") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))) + .anySatisfy(metric -> + OpenTelemetryAssertions.assertThat(metric) + .hasName("otlp.exporter.exported") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))); + } } protected abstract TelemetryExporterBuilder exporterBuilder(); + protected abstract TelemetryExporterBuilder toBuilder(TelemetryExporter exporter); + protected abstract T generateFakeTelemetry(); protected abstract Marshaler[] toMarshalers(List telemetry); private List toProto(List telemetry) { return Arrays.stream(toMarshalers(telemetry)) - .map( - marshaler -> { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - marshaler.writeBinaryTo(bos); - @SuppressWarnings("unchecked") - U result = - (U) - resourceTelemetryInstance - .newBuilderForType() - .mergeFrom(bos.toByteArray()) - .build(); - return result; - } catch (IOException e) { - throw new UncheckedIOException(e); - } - }) + .map(marshaler -> { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + @SuppressWarnings("unchecked") + U result = + (U) + resourceTelemetryInstance + .newBuilderForType() + .mergeFrom(bos.toByteArray()) + .build(); + return result; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) .collect(Collectors.toList()); } - private TelemetryExporter retryingExporter() { - return exporterBuilder() - .setEndpoint(server.httpUri().toString()) - .setRetryPolicy( - RetryPolicy.builder() - .setMaxAttempts(2) - // We don't validate backoff time itself in these tests, just that retries - // occur. Keep the tests fast by using minimal backoff. - .setInitialBackoff(Duration.ofMillis(1)) - .setMaxBackoff(Duration.ofMillis(1)) - .setBackoffMultiplier(1) - .build()) - .build(); + protected TelemetryExporter nonRetryingExporter() { + return exporterBuilder().setEndpoint(server.httpUri().toString()).setRetryPolicy(null).build(); } - private static void addGrpcError(int code, @Nullable String message) { - grpcErrors.add(new ArmeriaStatusException(code, message)); + protected static void addGrpcResponse(GrpcStatusCode code, @Nullable String message) { + addGrpcResponse(code, message, null); } - private static boolean usingOkHttp() { - try { - Class.forName("io.grpc.stub.AbstractStub"); - return false; - } catch (ClassNotFoundException e) { - return true; + protected static void addGrpcResponse( + GrpcStatusCode code, + @Nullable String message, + @Nullable AbstractMessageLite bodyMessage) { + grpcResponses.add( + new GrpcServerResponse( + code == GrpcStatusCode.OK ? null : new ArmeriaStatusException(code.getValue(), message), + bodyMessage == null ? null : bodyMessage.toByteArray())); + } + + private static final class GrpcServerResponse { + @Nullable final ArmeriaStatusException error; + @Nullable final byte[] responseBytes; + + GrpcServerResponse(@Nullable ArmeriaStatusException error, @Nullable byte[] responseBytes) { + this.error = error; + this.responseBytes = responseBytes; } } } diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java new file mode 100644 index 00000000000..c3b6b99ab02 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/AbstractHttpTelemetryExporterTest.java @@ -0,0 +1,1335 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.satisfies; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import com.google.protobuf.AbstractMessageLite; +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.linecorp.armeria.common.HttpData; +import com.linecorp.armeria.common.HttpRequest; +import com.linecorp.armeria.common.HttpResponse; +import com.linecorp.armeria.common.HttpStatus; +import com.linecorp.armeria.common.MediaType; +import com.linecorp.armeria.common.RequestHeaders; +import com.linecorp.armeria.common.ResponseHeaders; +import com.linecorp.armeria.common.TlsKeyPair; +import com.linecorp.armeria.server.HttpService; +import com.linecorp.armeria.server.ServerBuilder; +import com.linecorp.armeria.server.ServiceRequestContext; +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import com.linecorp.armeria.testing.junit5.server.ServerExtension; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.FailedExportException; +import io.opentelemetry.exporter.internal.TlsUtil; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.exporter.otlp.internal.HttpExporter; +import io.opentelemetry.exporter.otlp.internal.HttpExporterBuilder; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.assertj.AttributeAssertion; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.reflect.Field; +import java.net.InetSocketAddress; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import java.util.zip.GZIPOutputStream; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; +import okio.Buffer; +import okio.GzipSource; +import okio.Okio; +import okio.Source; +import org.assertj.core.api.Assertions; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.assertj.core.api.iterable.ThrowingExtractor; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Order; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.support.ParameterDeclarations; +import org.mockserver.integration.ClientAndServer; +import org.slf4j.event.Level; +import org.slf4j.event.LoggingEvent; + +/** Shared OTLP HTTP exporter tests for all telemetry signals. */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public abstract class AbstractHttpTelemetryExporterTest { + + private static final ConcurrentLinkedQueue exportedResourceTelemetry = + new ConcurrentLinkedQueue<>(); + + private static final ConcurrentLinkedQueue httpErrors = + new ConcurrentLinkedQueue<>(); + + private static final AtomicInteger attempts = new AtomicInteger(); + + private static final ConcurrentLinkedQueue httpRequests = + new ConcurrentLinkedQueue<>(); + + private static volatile byte[] successResponseBytes = new byte[0]; + + @RegisterExtension + @Order(1) + static final SelfSignedCertificateExtension certificate = new SelfSignedCertificateExtension(); + + @RegisterExtension + @Order(2) + static final SelfSignedCertificateExtension clientCertificate = + new SelfSignedCertificateExtension(); + + @RegisterExtension + @Order(3) + static final ServerExtension server = + new ServerExtension() { + @Override + protected void configure(ServerBuilder sb) { + sb.service( + "/v1/traces", + new CollectorService<>( + ExportTraceServiceRequest::parseFrom, + ExportTraceServiceRequest::getResourceSpansList)); + sb.service( + "/v1/metrics", + new CollectorService<>( + ExportMetricsServiceRequest::parseFrom, + ExportMetricsServiceRequest::getResourceMetricsList)); + sb.service( + "/v1/logs", + new CollectorService<>( + ExportLogsServiceRequest::parseFrom, + ExportLogsServiceRequest::getResourceLogsList)); + + sb.http(0); + sb.https(0); + sb.tls(TlsKeyPair.of(certificate.privateKey(), certificate.certificate())); + sb.tlsCustomizer(ssl -> ssl.trustManager(clientCertificate.certificate())); + // Uncomment for detailed request / response logs from server + // sb.decorator(LoggingService.newDecorator()); + } + }; + + private static class CollectorService implements HttpService { + private final ThrowingExtractor parse; + private final Function> getResourceTelemetry; + + private CollectorService( + ThrowingExtractor parse, + Function> getResourceTelemetry) { + this.parse = parse; + this.getResourceTelemetry = getResourceTelemetry; + } + + @Override + public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) { + httpRequests.add(ctx.request()); + attempts.incrementAndGet(); + CompletableFuture responseFuture = + req.aggregate() + .thenApply(aggReq -> { + T request; + try { + byte[] requestBody = maybeInflate(aggReq.headers(), aggReq.content().array()); + request = parse.extractThrows(requestBody); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + exportedResourceTelemetry.addAll(getResourceTelemetry.apply(request)); + HttpResponse errorResponse = httpErrors.poll(); + return errorResponse != null + ? errorResponse + : HttpResponse.of( + HttpStatus.OK, + MediaType.parse("application/x-protobuf"), + successResponseBytes); + }); + return HttpResponse.of(responseFuture); + } + + private static byte[] maybeInflate(RequestHeaders requestHeaders, byte[] content) + throws IOException { + if (requestHeaders.contains("content-encoding", "gzip")) { + Buffer buffer = new Buffer(); + GzipSource gzipSource = new GzipSource(Okio.source(new ByteArrayInputStream(content))); + gzipSource.read(buffer, Integer.MAX_VALUE); + return buffer.readByteArray(); + } + if (requestHeaders.contains("content-encoding", "base64")) { + Buffer buffer = new Buffer(); + Source base64Source = + Okio.source(Base64.getDecoder().wrap(new ByteArrayInputStream(content))); + base64Source.read(buffer, Integer.MAX_VALUE); + return buffer.readByteArray(); + } + return content; + } + } + + @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(HttpExporter.class); + + private final String type; + private final String path; + private final U resourceTelemetryInstance; + + private TelemetryExporter exporter; + + protected AbstractHttpTelemetryExporterTest( + String type, String path, U resourceTelemetryInstance) { + this.type = type; + this.path = path; + this.resourceTelemetryInstance = resourceTelemetryInstance; + } + + @BeforeAll + void setUp() { + exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + // We don't validate backoff time itself in these tests, just that retries + // occur. Keep the tests fast by using minimal backoff. + .setRetryPolicy( + RetryPolicy.getDefault().toBuilder() + .setMaxAttempts(2) + .setInitialBackoff(Duration.ofMillis(1)) + .build()) + .build(); + successResponseBytes = exporter.exportResponse(0).toByteArray(); + + // Sanity check that TLS files are in PEM format. + assertThat(certificate.certificateFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN CERTIFICATE-----"); + assertThat(certificate.privateKeyFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN PRIVATE KEY-----"); + assertThat(clientCertificate.certificateFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN CERTIFICATE-----"); + assertThat(clientCertificate.privateKeyFile()) + .binaryContent() + .asString(StandardCharsets.UTF_8) + .startsWith("-----BEGIN PRIVATE KEY-----"); + } + + @AfterAll + void tearDown() { + exporter.shutdown(); + } + + @AfterEach + void reset() { + exportedResourceTelemetry.clear(); + httpErrors.clear(); + attempts.set(0); + httpRequests.clear(); + } + + @Test + void export() { + List telemetry = Collections.singletonList(generateFakeTelemetry()); + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + List expectedResourceTelemetry = toProto(telemetry); + assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); + + // Assert request contains OTLP spec compliant User-Agent header + assertThat(httpRequests) + .singleElement() + .satisfies(req -> + assertThat(req.headers().get("User-Agent")).matches("OTel-OTLP-Exporter-Java/1\\..*")); + } + + @Test + void multipleItems() { + List telemetry = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + telemetry.add(generateFakeTelemetry()); + } + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + List expectedResourceTelemetry = toProto(telemetry); + assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); + } + + @Test + void compressionWithNone() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri() + path).setCompression("none").build()) { + + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.headers().get("content-encoding")).isNull()); + } + } + + @Test + void compressionWithGzip() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri() + path).setCompression("gzip").build()) { + + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.headers().get("content-encoding")).isEqualTo("gzip")); + } + } + + @Test + void compressionWithSpiCompressor() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri() + path).setCompression("base64").build()) { + + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(httpRequests) + .singleElement() + .satisfies(req -> assertThat(req.headers().get("content-encoding")).isEqualTo("base64")); + } + } + + @Test + void authorityWithAuth() { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint("http://foo:bar@localhost:" + server.httpPort() + path) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void withHeaders() { + AtomicInteger count = new AtomicInteger(); + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .addHeader("key1", "value1") + .setHeaders(() -> Collections.singletonMap("key2", "value" + count.incrementAndGet())) + .build()) { + // Export twice to ensure header supplier gets invoked twice + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + result = exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + + assertThat(httpRequests) + .satisfiesExactly( + req -> { + assertThat(req.headers().get("key1")).isEqualTo("value1"); + assertThat(req.headers().get("key2")).isEqualTo("value" + (count.get() - 1)); + }, + req -> { + assertThat(req.headers().get("key1")).isEqualTo("value1"); + assertThat(req.headers().get("key2")).isEqualTo("value" + count.get()); + }); + } + } + + @Test + void tls() throws Exception { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void tlsViaSslContext() throws Exception { + X509TrustManager trustManager = TlsUtil.trustManager(certificate.certificate().getEncoded()); + + X509KeyManager keyManager = + TlsUtil.keyManager( + certificate.privateKey().getEncoded(), certificate.certificate().getEncoded()); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null); + + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setSslContext(sslContext, trustManager) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void enabledProtocols() throws Exception { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3")) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + @SuppressLogger(HttpExporter.class) + void enabledProtocols_restrictedProtocolsFail() throws Exception { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .setEnabledProtocols(Collections.singletonList("TLSv1.1")) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + } + } + + @Test + @SuppressLogger(HttpExporter.class) + void tls_untrusted() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpsUri() + path).build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + } + } + + @Test + void tls_badCert() { + assertThatThrownBy(() -> + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Error creating X509TrustManager with provided certs"); + } + + @ParameterizedTest + @ArgumentsSource(ClientPrivateKeyProvider.class) + void clientTls(byte[] privateKey) throws Exception { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpsUri() + path) + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .setClientTls( + privateKey, Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + private static class ClientPrivateKeyProvider implements ArgumentsProvider { + @Override + @SuppressWarnings("PrimitiveArrayPassedToVarargsMethod") + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) throws Exception { + return Stream.of( + arguments(named("PEM", Files.readAllBytes(clientCertificate.privateKeyFile().toPath()))), + arguments(named("DER", clientCertificate.privateKey().getEncoded()))); + } + } + + @Test + @SuppressLogger(HttpExporter.class) + void connectTimeout() { + try (TelemetryExporter exporter = + exporterBuilder() + // Connecting to a non-routable IP address to trigger connection error + .setEndpoint("http://10.255.255.1") + .setConnectTimeout(Duration.ofMillis(1)) + .setRetryPolicy(null) + .build()) { + long startTimeMillis = System.currentTimeMillis(); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + + assertThat(result.isSuccess()).isFalse(); + + assertThat(result.getFailureThrowable()) + .asInstanceOf( + InstanceOfAssertFactories.throwable(FailedExportException.HttpExportException.class)) + .returns(false, Assertions.from(FailedExportException::failedWithResponse)) + .satisfies(ex -> { + assertThat(ex.getResponse()).isNull(); + assertThat(ex.getCause()).isNotNull(); + }); + + // Assert that the export request fails well before the default connect timeout of 10s + // Note: Connection failures to non-routable IPs can take 1-5 seconds depending on OS/network + assertThat(System.currentTimeMillis() - startTimeMillis) + .isLessThan(TimeUnit.SECONDS.toMillis(6)); + } + } + + @Test + void deadlineSetPerExport() throws InterruptedException { + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .setTimeout(Duration.ofMillis(1500)) + .build()) { + TimeUnit.MILLISECONDS.sleep(2000); + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + @SuppressLogger(HttpExporter.class) + void exportAfterShutdown() { + TelemetryExporter exporter = exporterBuilder().setEndpoint(server.httpUri() + path).build(); + exporter.shutdown(); + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + assertThat(httpRequests).isEmpty(); + } + + @Test + @SuppressLogger(HttpExporter.class) + void doubleShutdown() { + int logsSizeBefore = logs.getEvents().size(); + TelemetryExporter exporter = exporterBuilder().setEndpoint(server.httpUri() + path).build(); + assertThat(exporter.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(logs.getEvents()).hasSize(logsSizeBefore); + logs.assertDoesNotContain("Calling shutdown() multiple times."); + assertThat(exporter.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + logs.assertContains("Calling shutdown() multiple times."); + } + + @Test + @SuppressLogger(HttpExporter.class) + void error() { + int statusCode = 500; + addHttpResponse(statusCode); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + + assertThat(result.isSuccess()).isFalse(); + + assertThat(result.getFailureThrowable()) + .asInstanceOf( + InstanceOfAssertFactories.throwable(FailedExportException.HttpExportException.class)) + .returns(true, Assertions.from(FailedExportException::failedWithResponse)) + .satisfies(ex -> { + assertThat(ex.getResponse()) + .isNotNull() + .satisfies(response -> { + assertThat(response) + .extracting(io.opentelemetry.sdk.common.export.HttpResponse::getStatusCode) + .isEqualTo(statusCode); + + assertThatCode(response::getResponseBody).doesNotThrowAnyException(); + }); + + assertThat(ex.getCause()).isNull(); + }); + + LoggingEvent log = + logs.assertContains( + "Failed to export 1 " + + type + + "s. Server responded with HTTP status code 500. Error message:"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + } + + @Test + @SuppressLogger(HttpExporter.class) + void responseBodyBounds() { + // We have a 4mb hardcoded response body limit. Responses <= 4mb succeed. Responses >= 4mb + // fail. We can't test payloads exactly at 4mb because protobuf message lengths are finicky - + // its hard to create a message with an exact size. + + // Body below the limit, succeeds + addHttpResponse(200, exporter.exportResponse(100)); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isTrue(); + + // Body over the limit, fails with RESOURCE_EXHAUSTED + addHttpResponse(200, exporter.exportResponse(4 * 1024 * 1024 + 1)); + result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.HttpExportException.class, + ex -> + assertThat(ex.getCause()) + .isNotNull() + .hasMessageContaining("HTTP response body exceeded limit of")); + } + + @Test + @SuppressLogger(HttpExporter.class) + void responseBodyBoundsGzipCompressed() throws IOException { + // Verify the body size limit is applied to the decompressed bytes, not the compressed wire + // bytes. The compressed body is well below the 4MB limit but decompresses to just over it. + byte[] payload = new byte[4 * 1024 * 1024 + 1]; + ByteArrayOutputStream compressedBaos = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(compressedBaos)) { + gzip.write(payload); + } + byte[] compressedBody = compressedBaos.toByteArray(); + + httpErrors.add( + HttpResponse.of( + ResponseHeaders.builder(HttpStatus.OK) + .contentType(MediaType.PLAIN_TEXT_UTF_8) + .add("Content-Encoding", "gzip") + .build(), + HttpData.wrap(compressedBody))); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.HttpExportException.class, + ex -> + assertThat(ex.getCause()) + .isNotNull() + .hasMessageContaining("HTTP response body exceeded limit of")); + } + + @Test + void identityResponseContentEncoding() { + // Server responds with Content-Encoding: identity, which means no encoding. The export should + // succeed just like a response with no Content-Encoding header. + AbstractMessageLite responseBody = exporter.exportResponse(0); + httpErrors.add( + HttpResponse.of( + ResponseHeaders.builder(HttpStatus.OK) + .contentType(MediaType.PLAIN_TEXT_UTF_8) + .add("Content-Encoding", "identity") + .build(), + HttpData.wrap(responseBody.toByteArray()))); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isTrue(); + } + + @Test + @SuppressLogger(HttpExporter.class) + void unsupportedResponseContentEncoding() { + // Server responds with a Content-Encoding that we don't support. The export should fail + // without retry. + httpErrors.add( + HttpResponse.of( + ResponseHeaders.builder(HttpStatus.OK) + .contentType(MediaType.PLAIN_TEXT_UTF_8) + .add("Content-Encoding", "brotli") + .build(), + HttpData.wrap(new byte[10]))); + CompletableResultCode result = + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(attempts).hasValue(1); + assertThat(result.getFailureThrowable()) + .isInstanceOfSatisfying( + FailedExportException.HttpExportException.class, + ex -> + assertThat(ex.getCause()) + .isNotNull() + .hasMessageContaining("Unsupported Content-Encoding")); + } + + @ParameterizedTest + @ValueSource(ints = {429, 502, 503, 504}) + void retryableError(int code) { + addHttpResponse(code); + + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isTrue(); + + assertThat(attempts).hasValue(2); + } + + @Test + @SuppressLogger(HttpExporter.class) + void retryableError_tooManyAttempts() { + addHttpResponse(502); + addHttpResponse(502); + + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + + assertThat(attempts).hasValue(2); + } + + @Test + void retryableError_retryAfterHonored() { + addHttpResponse(502, "0"); + + // Configure a large enough initial backoff so the elapsed time proves Retry-After is honored + // instead of waiting for the retry policy delay. + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .setRetryPolicy( + RetryPolicy.builder() + .setMaxAttempts(2) + .setInitialBackoff(Duration.ofSeconds(1)) + .setMaxBackoff(Duration.ofSeconds(1)) + .build()) + .build()) { + long startTimeNanos = System.nanoTime(); + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isTrue(); + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTimeNanos); + + assertThat(attempts).hasValue(2); + assertThat(elapsedMillis).isLessThan(750L); + } + } + + @Test + void retryableError_malformedRetryAfterFallsBack() { + addHttpResponse(503, "not-a-retry-after"); + + // Configure a large enough initial backoff so the elapsed time proves we fell back to the + // retry policy rather than the (malformed) Retry-After header. + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .setRetryPolicy( + RetryPolicy.builder() + .setMaxAttempts(2) + .setInitialBackoff(Duration.ofMillis(300)) + .setMaxBackoff(Duration.ofMillis(300)) + .build()) + .build()) { + long startTimeNanos = System.nanoTime(); + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isTrue(); + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTimeNanos); + + assertThat(attempts).hasValue(2); + // The malformed Retry-After header should be ignored, so the retry must wait at least a + // noticeable portion of the configured 300ms backoff. Keep a generous upper bound to avoid + // flaking in slow CI environments. + assertThat(elapsedMillis).isBetween(100L, 2_000L); + } + } + + @ParameterizedTest + @SuppressLogger(HttpExporter.class) + @ValueSource(ints = {400, 401, 403, 500, 501}) + void nonRetryableError(int code) { + addHttpResponse(code); + + assertThat( + exporter + .export(Collections.singletonList(generateFakeTelemetry())) + .join(10, TimeUnit.SECONDS) + .isSuccess()) + .isFalse(); + + assertThat(attempts).hasValue(1); + } + + @Test + void proxy() { + // configure mockserver to proxy to the local OTLP server + InetSocketAddress serverSocketAddress = server.httpSocketAddress(); + try (ClientAndServer clientAndServer = + ClientAndServer.startClientAndServer( + serverSocketAddress.getHostName(), serverSocketAddress.getPort()); + TelemetryExporter exporter = + exporterBuilder() + // Configure exporter with server endpoint, and proxy options to route through + // mockserver proxy + .setEndpoint(server.httpUri() + path) + .setProxyOptions( + ProxyOptions.create( + InetSocketAddress.createUnresolved("localhost", clientAndServer.getPort()))) + .build()) { + + List telemetry = Collections.singletonList(generateFakeTelemetry()); + + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + // assert that mock server received request + assertThat(clientAndServer.retrieveRecordedRequests(new org.mockserver.model.HttpRequest())) + .hasSize(1); + // assert that server received telemetry from proxy, and is as expected + List expectedResourceTelemetry = toProto(telemetry); + assertThat(exportedResourceTelemetry).containsExactlyElementsOf(expectedResourceTelemetry); + } + } + + @Test + void executorService() { + ExecutorServiceSpy executorService = + new ExecutorServiceSpy(Executors.newSingleThreadExecutor()); + + try (TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .setExecutorService(executorService) + .build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(executorService.getTaskCount()).isPositive(); + } finally { + // If setting executor, the user is responsible for calling shutdown + assertThat(executorService.isShutdown()).isFalse(); + executorService.shutdown(); + } + } + + @Test + @SuppressWarnings("PreferJavaTimeOverload") + void validConfig() { + // We must build exporters to test timeout settings, which intersect with underlying client + // implementations and may convert between Duration, int, and long, which may be susceptible to + // overflow exceptions. + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(0, TimeUnit.MILLISECONDS))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofMillis(0)))) + .doesNotThrowAnyException(); + assertThatCode(() -> + buildAndShutdown(exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.NANOSECONDS))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofNanos(Long.MAX_VALUE)))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setTimeout(Long.MAX_VALUE, TimeUnit.SECONDS))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(10, TimeUnit.MILLISECONDS))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setTimeout(Duration.ofMillis(10)))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(0, TimeUnit.MILLISECONDS))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(Duration.ofMillis(0)))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(10, TimeUnit.MILLISECONDS))) + .doesNotThrowAnyException(); + assertThatCode( + () -> buildAndShutdown(exporterBuilder().setConnectTimeout(Duration.ofMillis(10)))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setMaxRequestSize(1))) + .doesNotThrowAnyException(); + assertThatCode(() -> buildAndShutdown(exporterBuilder().setMaxRequestSize(0))) + .doesNotThrowAnyException(); + + assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost:4318")) + .doesNotThrowAnyException(); + assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost/")) + .doesNotThrowAnyException(); + assertThatCode(() -> exporterBuilder().setEndpoint("https://localhost/")) + .doesNotThrowAnyException(); + assertThatCode(() -> exporterBuilder().setEndpoint("http://foo:bar@localhost/")) + .doesNotThrowAnyException(); + + assertThatCode(() -> exporterBuilder().setCompression("gzip")).doesNotThrowAnyException(); + // SPI compressor available for this test but not packaged with OTLP exporter + assertThatCode(() -> exporterBuilder().setCompression("base64")).doesNotThrowAnyException(); + assertThatCode(() -> exporterBuilder().setCompression("none")).doesNotThrowAnyException(); + + assertThatCode(() -> exporterBuilder().addHeader("foo", "bar").addHeader("baz", "qux")) + .doesNotThrowAnyException(); + + assertThatCode( + () -> exporterBuilder().setTrustedCertificates(certificate.certificate().getEncoded())) + .doesNotThrowAnyException(); + + assertThatCode(() -> exporterBuilder().setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3"))) + .doesNotThrowAnyException(); + } + + private void buildAndShutdown(TelemetryExporterBuilder builder) { + TelemetryExporter build = builder.build(); + build.shutdown().join(10, TimeUnit.MILLISECONDS); + } + + @Test + @SuppressWarnings({"PreferJavaTimeOverload", "NullAway"}) + void invalidConfig() { + assertThatThrownBy(() -> exporterBuilder().setTimeout(-1, TimeUnit.MILLISECONDS)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("timeout must be non-negative"); + assertThatThrownBy(() -> exporterBuilder().setTimeout(1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); + assertThatThrownBy(() -> exporterBuilder().setTimeout(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("timeout"); + assertThatThrownBy(() -> + buildAndShutdown(exporterBuilder().setTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + .isInstanceOf(ArithmeticException.class); + + assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(-1, TimeUnit.MILLISECONDS)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("timeout must be non-negative"); + assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); + assertThatThrownBy(() -> exporterBuilder().setConnectTimeout(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("timeout"); + assertThatThrownBy(() -> + buildAndShutdown( + exporterBuilder().setConnectTimeout(Duration.ofSeconds(Long.MAX_VALUE)))) + .isInstanceOf(ArithmeticException.class); + + assertThatThrownBy(() -> exporterBuilder().setEndpoint(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("endpoint"); + assertThatThrownBy(() -> exporterBuilder().setEndpoint("😺://localhost")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid endpoint, must be a URL: 😺://localhost"); + assertThatThrownBy(() -> exporterBuilder().setEndpoint("localhost")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); + assertThatThrownBy(() -> exporterBuilder().setEndpoint("gopher://localhost")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); + + assertThatThrownBy(() -> exporterBuilder().setCompression(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("compressionMethod"); + assertThatThrownBy(() -> exporterBuilder().setCompression("foo")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage( + "Unsupported compressionMethod. Compression method must be \"none\" or one of: [base64,gzip]"); + assertThatThrownBy(() -> exporterBuilder().setMaxRequestSize(-1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxRequestBodySizeBytes must be non-negative"); + + assertThatThrownBy(() -> exporterBuilder().setEnabledProtocols(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("enabledProtocols"); + assertThatThrownBy(() -> exporterBuilder().setEnabledProtocols(Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("enabledProtocols must not be empty"); + } + + @Test + void requestBodySizeLimit() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri() + path).setMaxRequestSize(1).build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()) + .hasMessageContaining("Failed to export") + .hasMessageContaining("Request body size") + .hasMessageContaining("exceeded limit of 1 bytes"); + } + } + + @Test + void requestBodySizeLimitDisabledWithZero() { + try (TelemetryExporter exporter = + exporterBuilder().setEndpoint(server.httpUri() + path).setMaxRequestSize(0).build()) { + CompletableResultCode result = + exporter.export(Collections.singletonList(generateFakeTelemetry())); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + } + + @Test + void toBuilderEquality() + throws CertificateEncodingException, + IOException, + NoSuchFieldException, + IllegalAccessException { + try (TelemetryExporter exporter = + exporterBuilder() + .setTimeout(Duration.ofSeconds(5)) + .setConnectTimeout(Duration.ofSeconds(4)) + .setEndpoint("http://localhost:4318") + .setCompression("gzip") + .addHeader("foo", "bar") + .setTrustedCertificates(certificate.certificate().getEncoded()) + .setClientTls( + Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), + Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .setRetryPolicy( + RetryPolicy.builder() + .setMaxAttempts(2) + .setMaxBackoff(Duration.ofSeconds(3)) + .setInitialBackoff(Duration.ofMillis(50)) + .setBackoffMultiplier(1.3) + .build()) + .setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3")) + .setComponentLoader(ComponentLoader.forClassLoader(new ClassLoader() {})) + .build()) { + Object unwrapped = exporter.unwrap(); + Field builderField = unwrapped.getClass().getDeclaredField("builder"); + builderField.setAccessible(true); + + // Builder copy should be equal to original when unchanged + TelemetryExporter copy = toBuilder(exporter).build(); + try { + assertThat(copy.unwrap()) + .extracting("builder") + .usingRecursiveComparison() + .withStrictTypeChecking() + .ignoringFields("tlsConfigHelper") + .isEqualTo(builderField.get(unwrapped)); + } finally { + copy.shutdown(); + } + + // Builder copy should NOT be equal when changed + copy = toBuilder(exporter).addHeader("baz", "qux").build(); + try { + assertThat(copy.unwrap()) + .extracting("builder") + .usingRecursiveComparison() + .withStrictTypeChecking() + .ignoringFields("tlsConfigHelper") + .isNotEqualTo(builderField.get(unwrapped)); + } finally { + copy.shutdown(); + } + } + } + + @Test + void customServiceClassLoader() { + ClassLoaderSpy classLoaderSpy = + new ClassLoaderSpy(AbstractHttpTelemetryExporterTest.class.getClassLoader()); + + try (TelemetryExporter exporter = + exporterBuilder() + .setServiceClassLoader(classLoaderSpy) + .setEndpoint(server.httpUri() + path) + .build()) { + assertThat(classLoaderSpy.getResourcesNames) + .isEqualTo( + Collections.singletonList( + "META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider")); + } + } + + private static class ClassLoaderSpy extends ClassLoader { + private final List getResourcesNames = new ArrayList<>(); + + private ClassLoaderSpy(ClassLoader delegate) { + super(delegate); + } + + @Override + public Enumeration getResources(String name) throws IOException { + getResourcesNames.add(name); + return super.getResources(name); + } + } + + @Test + void stringRepresentation() throws IOException, CertificateEncodingException { + try (TelemetryExporter telemetryExporter = exporterBuilder().build(); ) { + assertThat(telemetryExporter.unwrap().toString()) + .matches( + "OtlpHttp[a-zA-Z]*Exporter\\{" + + "endpoint=http://localhost:4318/v1/[a-zA-Z]*, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "proxyOptions=null, " + + "compressorEncoding=null, " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(10) + + ", " + + "exportAsJson=false, " + + "headers=Headers\\{User-Agent=OBFUSCATED\\}" + + ".*maxRequestBodySize=" + + HttpExporterBuilder.DEFAULT_MAX_REQUEST_BODY_SIZE + + ".*" // Maybe additional signal specific fields + + "\\}"); + } + + try (TelemetryExporter telemetryExporter = + exporterBuilder() + .setTimeout(Duration.ofSeconds(5)) + .setConnectTimeout(Duration.ofSeconds(4)) + .setEndpoint("http://example:4318/v1/logs") + .setCompression("gzip") + .addHeader("foo", "bar") + .setTrustedCertificates(certificate.certificate().getEncoded()) + .setClientTls( + Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), + Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .setRetryPolicy( + RetryPolicy.builder() + .setMaxAttempts(2) + .setMaxBackoff(Duration.ofSeconds(3)) + .setInitialBackoff(Duration.ofMillis(50)) + .setBackoffMultiplier(1.3) + .build()) + .setEnabledProtocols(Arrays.asList("TLSv1.2", "TLSv1.3")) + .build()) { + assertThat(telemetryExporter.unwrap().toString()) + .matches( + "OtlpHttp[a-zA-Z]*Exporter\\{" + + "endpoint=http://example:4318/v1/[a-zA-Z]*, " + + "timeoutNanos=" + + TimeUnit.SECONDS.toNanos(5) + + ", " + + "proxyOptions=null, " + + "compressorEncoding=gzip, " + + "connectTimeoutNanos=" + + TimeUnit.SECONDS.toNanos(4) + + ", " + + "exportAsJson=false, " + + "headers=Headers\\{.*foo=OBFUSCATED.*\\}, " + + "retryPolicy=RetryPolicy\\{maxAttempts=2, initialBackoff=PT0\\.05S, " + + "maxBackoff=PT3S, backoffMultiplier=1\\.3, " + + "retryExceptionPredicate=null\\}" + + ".*maxRequestBodySize=" + + HttpExporterBuilder.DEFAULT_MAX_REQUEST_BODY_SIZE + + ".*" // Maybe additional signal specific fields + + "\\}") + .contains("enabledProtocols=[TLSv1.2, TLSv1.3]"); + } + } + + @Test + void latestInternalTelemetry() { + InMemoryMetricReader inMemoryMetrics = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(inMemoryMetrics).build(); + TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .setMeterProvider(() -> meterProvider) + .setInternalTelemetryVersion(InternalTelemetryVersion.LATEST) + .build()) { + List telemetry = Collections.singletonList(generateFakeTelemetry()); + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + + List expectedAttributes = + Arrays.asList( + satisfies( + SemConvConstants.OTEL_COMPONENT_TYPE, + str -> str.matches("otlp_http_(log|metric|span)_exporter")), + satisfies( + SemConvConstants.OTEL_COMPONENT_NAME, + str -> str.matches("otlp_http_(log|metric|span)_exporter/\\d+")), + satisfies( + SemConvConstants.SERVER_PORT, str -> str.isEqualTo(server.httpUri().getPort())), + satisfies( + SemConvConstants.SERVER_ADDRESS, + str -> str.isEqualTo(server.httpUri().getHost()))); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(3) + .anySatisfy(metric -> + assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).inflight")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + assertThat(metric) + .satisfies(m -> + assertThat(m.getName()) + .matches("otel.sdk.exporter.(span|metric_data_point|log).exported")) + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> pa.hasAttributesSatisfying(expectedAttributes)))) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otel.sdk.exporter.operation.duration") + .hasHistogramSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying(expectedAttributes).hasBucketCounts(1)))); + } + } + + @Test + void legacyInternalTelemetry() { + InMemoryMetricReader inMemoryMetrics = InMemoryMetricReader.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(inMemoryMetrics).build(); + TelemetryExporter exporter = + exporterBuilder() + .setEndpoint(server.httpUri() + path) + .setMeterProvider(() -> meterProvider) + .setInternalTelemetryVersion(InternalTelemetryVersion.LEGACY) + .build()) { + List telemetry = Collections.singletonList(generateFakeTelemetry()); + assertThat(exporter.export(telemetry).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + + assertThat(inMemoryMetrics.collectAllMetrics()) + .hasSize(2) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otlp.exporter.seen") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))) + .anySatisfy(metric -> + assertThat(metric) + .hasName("otlp.exporter.exported") + .hasLongSumSatisfying(ma -> + ma.hasPointsSatisfying(pa -> + pa.hasAttributesSatisfying( + satisfies( + stringKey("type"), str -> str.matches("log|span|metric")))))); + } + } + + protected abstract TelemetryExporterBuilder exporterBuilder(); + + protected abstract TelemetryExporterBuilder toBuilder(TelemetryExporter exporter); + + protected abstract T generateFakeTelemetry(); + + protected abstract Marshaler[] toMarshalers(List telemetry); + + private List toProto(List telemetry) { + return Arrays.stream(toMarshalers(telemetry)) + .map(marshaler -> { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + @SuppressWarnings("unchecked") + U result = + (U) + resourceTelemetryInstance + .newBuilderForType() + .mergeFrom(bos.toByteArray()) + .build(); + return result; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }) + .collect(Collectors.toList()); + } + + private static void addHttpResponse(int code) { + httpErrors.add(HttpResponse.of(code)); + } + + private static void addHttpResponse(int code, String retryAfter) { + httpErrors.add( + HttpResponse.of( + ResponseHeaders.builder(HttpStatus.valueOf(code)) + .add("Retry-After", retryAfter) + .build())); + } + + private static void addHttpResponse(int code, AbstractMessageLite bodyMessage) { + httpErrors.add( + HttpResponse.of( + HttpStatus.valueOf(code), MediaType.PLAIN_TEXT_UTF_8, bodyMessage.toByteArray())); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/ExecutorServiceSpy.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/ExecutorServiceSpy.java new file mode 100644 index 00000000000..f16cf99edb0 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/ExecutorServiceSpy.java @@ -0,0 +1,113 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import java.util.Collection; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.jetbrains.annotations.NotNull; + +class ExecutorServiceSpy implements ExecutorService { + + private final ExecutorService delegate; + private int taskCount; + + ExecutorServiceSpy(ExecutorService delegate) { + this.delegate = delegate; + } + + @Override + public void shutdown() { + delegate.shutdown(); + } + + @NotNull + @Override + public List shutdownNow() { + return delegate.shutdownNow(); + } + + @Override + public boolean isShutdown() { + return delegate.isShutdown(); + } + + @Override + public boolean isTerminated() { + return delegate.isTerminated(); + } + + @Override + public boolean awaitTermination(long timeout, @NotNull TimeUnit unit) + throws InterruptedException { + return delegate.awaitTermination(timeout, unit); + } + + @NotNull + @Override + public Future submit(@NotNull Callable task) { + taskCount++; + return delegate.submit(task); + } + + @NotNull + @Override + public Future submit(@NotNull Runnable task, T result) { + taskCount++; + return delegate.submit(task, result); + } + + @NotNull + @Override + public Future submit(@NotNull Runnable task) { + taskCount++; + return delegate.submit(task); + } + + @NotNull + @Override + public List> invokeAll(@NotNull Collection> tasks) + throws InterruptedException { + return delegate.invokeAll(tasks); + } + + @NotNull + @Override + public List> invokeAll( + @NotNull Collection> tasks, long timeout, @NotNull TimeUnit unit) + throws InterruptedException { + return delegate.invokeAll(tasks, timeout, unit); + } + + @NotNull + @Override + public T invokeAny(@NotNull Collection> tasks) + throws InterruptedException, ExecutionException { + return delegate.invokeAny(tasks); + } + + @Override + public T invokeAny( + @NotNull Collection> tasks, long timeout, @NotNull TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + return delegate.invokeAny(tasks, timeout, unit); + } + + @Override + public void execute(@NotNull Runnable command) { + taskCount++; + delegate.execute(command); + } + + public int getTaskCount() { + return taskCount; + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/FakeTelemetryUtil.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/FakeTelemetryUtil.java new file mode 100644 index 00000000000..f30fdabba50 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/FakeTelemetryUtil.java @@ -0,0 +1,97 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import io.opentelemetry.sdk.testing.trace.TestSpanData; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.data.StatusData; +import java.time.Instant; +import java.util.Collections; +import java.util.concurrent.TimeUnit; + +/** Creates sample telemetry for OTLP exporter tests. */ +public class FakeTelemetryUtil { + + private static final String TRACE_ID = "00000000000000000000000000abc123"; + private static final String SPAN_ID = "0000000000def456"; + private static final InstrumentationScopeInfo SCOPE_INFO = + InstrumentationScopeInfo.builder("testLib") + .setVersion("1.0") + .setSchemaUrl("http://url") + .build(); + + /** Generate a fake {@link MetricData}. */ + public static MetricData generateFakeMetricData() { + long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); + long endNs = startNs + TimeUnit.MILLISECONDS.toNanos(900); + return ImmutableMetricData.createLongSum( + Resource.empty(), + SCOPE_INFO, + "name", + "description", + "1", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create( + startNs, endNs, Attributes.of(stringKey("k"), "v"), 5)))); + } + + /** Generate a fake {@link SpanData}. */ + public static SpanData generateFakeSpanData() { + long duration = TimeUnit.MILLISECONDS.toNanos(900); + long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); + long endNs = startNs + duration; + return TestSpanData.builder() + .setHasEnded(true) + .setSpanContext( + SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) + .setName("GET /api/endpoint") + .setStartEpochNanos(startNs) + .setEndEpochNanos(endNs) + .setStatus(StatusData.ok()) + .setKind(SpanKind.SERVER) + .setLinks(Collections.emptyList()) + .setTotalRecordedLinks(0) + .setTotalRecordedEvents(0) + .setInstrumentationScopeInfo(SCOPE_INFO) + .build(); + } + + /** Generate a fake {@link LogRecordData}. */ + public static LogRecordData generateFakeLogRecordData() { + return TestLogRecordData.builder() + .setResource(Resource.getDefault()) + .setInstrumentationScopeInfo(SCOPE_INFO) + .setBody("log body") + .setAttributes(Attributes.builder().put("key", "value").build()) + .setSeverity(Severity.INFO) + .setSeverityText(Severity.INFO.name()) + .setTimestamp(Instant.now()) + .setObservedTimestamp(Instant.now().plusNanos(100)) + .build(); + } + + private FakeTelemetryUtil() {} +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcLogRecordExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcLogRecordExporterBuilderWrapper.java new file mode 100644 index 00000000000..3840cf4b639 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcLogRecordExporterBuilderWrapper.java @@ -0,0 +1,172 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +final class GrpcLogRecordExporterBuilderWrapper implements TelemetryExporterBuilder { + private final OtlpGrpcLogRecordExporterBuilder builder; + + GrpcLogRecordExporterBuilderWrapper(OtlpGrpcLogRecordExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestMessageSize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + throw new UnsupportedOperationException("ProxyOptions are not supported for gRPC"); + } + + @Override + @SuppressWarnings("deprecation") // testing deprecated functionality + public TelemetryExporterBuilder setChannel(Object channel) { + builder.setChannel((ManagedChannel) channel); + return this; + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader( + ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader( + ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService( + ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols( + List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + builder.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + builder.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcMetricExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcMetricExporterBuilderWrapper.java new file mode 100644 index 00000000000..5ff391bc6b0 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcMetricExporterBuilderWrapper.java @@ -0,0 +1,169 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +final class GrpcMetricExporterBuilderWrapper implements TelemetryExporterBuilder { + private final OtlpGrpcMetricExporterBuilder builder; + + GrpcMetricExporterBuilderWrapper(OtlpGrpcMetricExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestMessageSize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + throw new UnsupportedOperationException("ProxyOptions are not supported for gRPC"); + } + + @Override + @SuppressWarnings("deprecation") // testing deprecated functionality + public TelemetryExporterBuilder setChannel(Object channel) { + builder.setChannel((ManagedChannel) channel); + return this; + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader( + ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService(ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + builder.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + builder.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcProfilesExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcProfilesExporterBuilderWrapper.java new file mode 100644 index 00000000000..cf74630158d --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcProfilesExporterBuilderWrapper.java @@ -0,0 +1,169 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.profiles.OtlpGrpcProfilesExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +final class GrpcProfilesExporterBuilderWrapper implements TelemetryExporterBuilder { + private final OtlpGrpcProfilesExporterBuilder builder; + + GrpcProfilesExporterBuilderWrapper(OtlpGrpcProfilesExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestMessageSize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + throw new UnsupportedOperationException("ProxyOptions are not supported for gRPC"); + } + + @Override + @SuppressWarnings("deprecation") // testing deprecated functionality + public TelemetryExporterBuilder setChannel(Object channel) { + builder.setChannel((ManagedChannel) channel); + return this; + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader( + ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService(ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + // Not yet supported + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + // Not yet supported + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcSpanExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcSpanExporterBuilderWrapper.java new file mode 100644 index 00000000000..748948c8e38 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/GrpcSpanExporterBuilderWrapper.java @@ -0,0 +1,169 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.grpc.ManagedChannel; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** Wrapper of {@link OtlpGrpcSpanExporterBuilder} for use in integration tests. */ +final class GrpcSpanExporterBuilderWrapper implements TelemetryExporterBuilder { + private final OtlpGrpcSpanExporterBuilder builder; + + GrpcSpanExporterBuilderWrapper(OtlpGrpcSpanExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestMessageSize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + throw new UnsupportedOperationException("ProxyOptions are not supported for gRPC"); + } + + @Override + @SuppressWarnings("deprecation") // testing deprecated functionality + public TelemetryExporterBuilder setChannel(Object channel) { + builder.setChannel((ManagedChannel) channel); + return this; + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService(ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + builder.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + builder.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpLogRecordExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpLogRecordExporterBuilderWrapper.java new file mode 100644 index 00000000000..acf614a1c30 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpLogRecordExporterBuilderWrapper.java @@ -0,0 +1,172 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** Wrapper of {@link OtlpHttpLogRecordExporterBuilder} for use in integration tests. */ +public class HttpLogRecordExporterBuilderWrapper + implements TelemetryExporterBuilder { + private final OtlpHttpLogRecordExporterBuilder builder; + + public HttpLogRecordExporterBuilderWrapper(OtlpHttpLogRecordExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestBodySize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + builder.setProxyOptions(proxyOptions); + return this; + } + + @Override + public TelemetryExporterBuilder setChannel(Object channel) { + throw new UnsupportedOperationException("Not implemented"); + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader( + ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader( + ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService( + ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols( + List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + builder.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + builder.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpMetricExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpMetricExporterBuilderWrapper.java new file mode 100644 index 00000000000..6fe54691a69 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpMetricExporterBuilderWrapper.java @@ -0,0 +1,168 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** Wrapper of {@link OtlpHttpMetricExporterBuilder} for use in integration tests. */ +public class HttpMetricExporterBuilderWrapper implements TelemetryExporterBuilder { + private final OtlpHttpMetricExporterBuilder builder; + + public HttpMetricExporterBuilderWrapper(OtlpHttpMetricExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestBodySize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + builder.setProxyOptions(proxyOptions); + return this; + } + + @Override + public TelemetryExporterBuilder setChannel(Object channel) { + throw new UnsupportedOperationException("Not implemented"); + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader( + ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService(ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + builder.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + builder.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpSpanExporterBuilderWrapper.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpSpanExporterBuilderWrapper.java new file mode 100644 index 00000000000..c8a7ce29ddd --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/HttpSpanExporterBuilderWrapper.java @@ -0,0 +1,167 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** Wrapper of {@link OtlpHttpSpanExporterBuilder} for use in integration tests. */ +public class HttpSpanExporterBuilderWrapper implements TelemetryExporterBuilder { + private final OtlpHttpSpanExporterBuilder builder; + + public HttpSpanExporterBuilderWrapper(OtlpHttpSpanExporterBuilder builder) { + this.builder = builder; + } + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + builder.setEndpoint(endpoint); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + builder.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + builder.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + builder.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + builder.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + builder.setMaxRequestBodySize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + builder.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + builder.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders( + Supplier> headerSupplier) { + builder.setHeaders(headerSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + builder.setTrustedCertificates(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + builder.setSslContext(sslContext, trustManager); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls( + byte[] privateKeyPem, byte[] certificatePem) { + builder.setClientTls(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + builder.setRetryPolicy(retryPolicy); + return this; + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + builder.setProxy(proxyOptions); + return this; + } + + @Override + public TelemetryExporterBuilder setChannel(Object channel) { + throw new UnsupportedOperationException("Not implemented"); + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + builder.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + builder.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService(ExecutorService executorService) { + builder.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols) { + builder.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + builder.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + builder.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + return TelemetryExporter.wrap(builder.build()); + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/ManagedChannelTelemetryExporterBuilder.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/ManagedChannelTelemetryExporterBuilder.java new file mode 100644 index 00000000000..b2ba2ebc22a --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/ManagedChannelTelemetryExporterBuilder.java @@ -0,0 +1,345 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal; + +import static java.util.Collections.singletonList; +import static java.util.Collections.singletonMap; +import static java.util.Objects.requireNonNull; +import static java.util.stream.Collectors.toList; + +import com.google.protobuf.AbstractMessageLite; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.NettyChannelBuilder; +import io.grpc.okhttp.OkHttpChannelBuilder; +import io.netty.handler.ssl.SslContext; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.RetryUtil; +import io.opentelemetry.exporter.internal.TlsConfigHelper; +import io.opentelemetry.exporter.otlp.internal.OtlpUserAgent; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.net.URI; +import java.time.Duration; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.X509TrustManager; + +/** + * Wraps a {@link TelemetryExporterBuilder}, delegating methods to upstream gRPC's {@link + * ManagedChannel} where appropriate. + */ +public final class ManagedChannelTelemetryExporterBuilder + implements TelemetryExporterBuilder { + + public static ManagedChannelTelemetryExporterBuilder wrap( + TelemetryExporterBuilder delegate) { + return new ManagedChannelTelemetryExporterBuilder<>(delegate); + } + + private ManagedChannelTelemetryExporterBuilder(TelemetryExporterBuilder delegate) { + this.delegate = delegate; + } + + private final TelemetryExporterBuilder delegate; + + @Nullable private ManagedChannelBuilder channelBuilder; + + private final TlsConfigHelper tlsConfigHelper = new TlsConfigHelper(); + + @Override + public TelemetryExporterBuilder setEndpoint(String endpoint) { + delegate.setEndpoint(endpoint); + URI uri = URI.create(endpoint); + channelBuilder = ManagedChannelBuilder.forAddress(uri.getHost(), uri.getPort()); + if (!uri.getScheme().equals("https")) { + channelBuilder.usePlaintext(); + } + // User-Agent can only be set at the channel level with upstream gRPC client. If a user wants + // the User-Agent to be spec compliant they must manually set the user agent when building + // their channel. + channelBuilder.userAgent(OtlpUserAgent.getUserAgent()); + // Its user's responsibility to set the max inbound message size when building their channel. + channelBuilder.maxInboundMessageSize(4 * 1024 * 1024); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { + delegate.setTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setTimeout(Duration timeout) { + delegate.setTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit) { + delegate.setConnectTimeout(timeout, unit); + return this; + } + + @Override + public TelemetryExporterBuilder setConnectTimeout(Duration timeout) { + delegate.setConnectTimeout(timeout); + return this; + } + + @Override + public TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize) { + delegate.setMaxRequestSize(maxRequestSize); + return this; + } + + @Override + public TelemetryExporterBuilder setCompression(String compression) { + delegate.setCompression(compression); + return this; + } + + @Override + public TelemetryExporterBuilder addHeader(String key, String value) { + delegate.addHeader(key, value); + return this; + } + + @Override + public TelemetryExporterBuilder setHeaders(Supplier> headerSupplier) { + delegate.setHeaders(headerSupplier); + return this; + } + + // When a user provides a Channel, we are not in control of TLS or retry config and reimplement it + // here for use in tests. Technically we don't have to test them since they are out of the SDK's + // control, but it's probably worth verifying the baseline functionality anyways. + + @Override + public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { + delegate.setTrustedCertificates(certificates); + tlsConfigHelper.setTrustManagerFromCerts(certificates); + return this; + } + + @Override + public TelemetryExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + delegate.setClientTls(privateKeyPem, certificatePem); + tlsConfigHelper.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + @Override + public TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy) { + delegate.setRetryPolicy(retryPolicy); + if (retryPolicy == null) { + return this; + } + String grpcServiceName; + if (delegate instanceof GrpcLogRecordExporterBuilderWrapper) { + grpcServiceName = "opentelemetry.proto.collector.logs.v1.LogsService"; + } else if (delegate instanceof GrpcMetricExporterBuilderWrapper) { + grpcServiceName = "opentelemetry.proto.collector.metrics.v1.MetricsService"; + } else if (delegate instanceof GrpcSpanExporterBuilderWrapper) { + grpcServiceName = "opentelemetry.proto.collector.trace.v1.TraceService"; + } else { + throw new IllegalStateException("Can't happen"); + } + requireNonNull(channelBuilder, "channel"); + channelBuilder.defaultServiceConfig(toServiceConfig(grpcServiceName, retryPolicy)); + return this; + } + + /** + * Convert the {@link RetryPolicy} into a gRPC service config for the {@code serviceName}. The + * resulting map can be passed to {@link ManagedChannelBuilder#defaultServiceConfig(Map)}. + */ + private static Map toServiceConfig(String serviceName, RetryPolicy retryPolicy) { + List retryableStatusCodes = + RetryUtil.retryableGrpcStatusCodes().stream().map(Double::parseDouble).collect(toList()); + + Map retryConfig = new HashMap<>(); + retryConfig.put("retryableStatusCodes", retryableStatusCodes); + retryConfig.put("maxAttempts", (double) retryPolicy.getMaxAttempts()); + retryConfig.put("initialBackoff", retryPolicy.getInitialBackoff().toMillis() / 1000.0 + "s"); + retryConfig.put("maxBackoff", retryPolicy.getMaxBackoff().toMillis() / 1000.0 + "s"); + retryConfig.put("backoffMultiplier", retryPolicy.getBackoffMultiplier()); + + Map methodConfig = new HashMap<>(); + methodConfig.put("name", singletonList(singletonMap("service", serviceName))); + methodConfig.put("retryPolicy", retryConfig); + + return singletonMap("methodConfig", singletonList(methodConfig)); + } + + @Override + public TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions) { + delegate.setProxyOptions(proxyOptions); + return this; + } + + @Override + public TelemetryExporterBuilder setChannel(Object channel) { + throw new UnsupportedOperationException(); + } + + @Override + public TelemetryExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader) { + delegate.setServiceClassLoader(serviceClassLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader) { + delegate.setComponentLoader(componentLoader); + return this; + } + + @Override + public TelemetryExporterBuilder setExecutorService(ExecutorService executorService) { + delegate.setExecutorService(executorService); + return this; + } + + @Override + public TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols) { + delegate.setEnabledProtocols(enabledProtocols); + return this; + } + + @Override + public TelemetryExporterBuilder setMeterProvider( + Supplier meterProviderSupplier) { + delegate.setMeterProvider(meterProviderSupplier); + return this; + } + + @Override + public TelemetryExporterBuilder setInternalTelemetryVersion( + InternalTelemetryVersion schemaVersion) { + delegate.setInternalTelemetryVersion(schemaVersion); + return this; + } + + @Override + public TelemetryExporter build() { + Runnable shutdownCallback; + if (channelBuilder != null) { + try { + setSslContext(channelBuilder, tlsConfigHelper); + } catch (SSLException e) { + throw new IllegalStateException(e); + } + + ManagedChannel channel = channelBuilder.build(); + delegate.setChannel(channel); + shutdownCallback = channel::shutdownNow; + } else { + shutdownCallback = () -> {}; + } + + TelemetryExporter delegateExporter = delegate.build(); + return new TelemetryExporter() { + @Override + public Object unwrap() { + return delegateExporter.unwrap(); + } + + @Override + public CompletableResultCode export(Collection items) { + return delegateExporter.export(items); + } + + @Override + public CompletableResultCode shutdown() { + shutdownCallback.run(); + return delegateExporter.shutdown(); + } + + @Override + public AbstractMessageLite exportResponse(int minimumSize) { + return delegateExporter.exportResponse(minimumSize); + } + }; + } + + @Override + public TelemetryExporterBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + delegate.setSslContext(sslContext, trustManager); + tlsConfigHelper.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Configure the channel builder to trust the certificates. The {@code byte[]} should contain an + * X.509 certificate collection in PEM format. + * + * @throws SSLException if error occur processing the certificates + */ + private static void setSslContext( + ManagedChannelBuilder managedChannelBuilder, TlsConfigHelper tlsConfigHelper) + throws SSLException { + X509TrustManager trustManager = tlsConfigHelper.getTrustManager(); + if (trustManager == null) { + return; + } + + // gRPC does not abstract TLS configuration so we need to check the implementation and act + // accordingly. + String channelBuilderClassName = managedChannelBuilder.getClass().getName(); + switch (channelBuilderClassName) { + case "io.grpc.netty.NettyChannelBuilder": + { + NettyChannelBuilder nettyBuilder = (NettyChannelBuilder) managedChannelBuilder; + SslContext sslContext = + GrpcSslContexts.forClient() + .keyManager(tlsConfigHelper.getKeyManager()) + .trustManager(trustManager) + .build(); + nettyBuilder.sslContext(sslContext); + break; + } + case "io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder": + { + io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder nettyBuilder = + (io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder) managedChannelBuilder; + io.grpc.netty.shaded.io.netty.handler.ssl.SslContext sslContext = + io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts.forClient() + .trustManager(trustManager) + .keyManager(tlsConfigHelper.getKeyManager()) + .build(); + nettyBuilder.sslContext(sslContext); + break; + } + case "io.grpc.okhttp.OkHttpChannelBuilder": + SSLContext sslContext = tlsConfigHelper.getSslContext(); + if (sslContext == null) { + return; + } + OkHttpChannelBuilder okHttpBuilder = (OkHttpChannelBuilder) managedChannelBuilder; + okHttpBuilder.sslSocketFactory(sslContext.getSocketFactory()); + break; + default: + throw new SSLException( + "TLS certificate configuration not supported for unrecognized ManagedChannelBuilder " + + channelBuilderClassName); + } + } +} diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporter.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporter.java index db6eb1c8272..7fbdcf8a4ea 100644 --- a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporter.java +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporter.java @@ -5,20 +5,39 @@ package io.opentelemetry.exporter.otlp.testing.internal; +import com.google.common.base.Strings; +import com.google.protobuf.AbstractMessageLite; +import io.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess; +import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; +import io.opentelemetry.proto.collector.profiles.v1development.ExportProfilesPartialSuccess; +import io.opentelemetry.proto.collector.profiles.v1development.ExportProfilesServiceResponse; +import io.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.profiles.ProfileExporter; +import io.opentelemetry.sdk.profiles.data.ProfileData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SpanExporter; import java.util.Collection; +import java.util.concurrent.TimeUnit; -public interface TelemetryExporter { +/** A signal-independent exporter interface for shared OTLP exporter tests. */ +public interface TelemetryExporter extends AutoCloseable { /** Wraps a SpanExporter. */ static TelemetryExporter wrap(SpanExporter exporter) { return new TelemetryExporter() { + @Override + public Object unwrap() { + return exporter; + } + @Override public CompletableResultCode export(Collection items) { return exporter.export(items); @@ -28,12 +47,30 @@ public CompletableResultCode export(Collection items) { public CompletableResultCode shutdown() { return exporter.shutdown(); } + + @Override + public AbstractMessageLite exportResponse(int minimumSize) { + if (minimumSize == 0) { + return ExportTraceServiceResponse.getDefaultInstance(); + } + return ExportTraceServiceResponse.newBuilder() + .setPartialSuccess( + ExportTracePartialSuccess.newBuilder() + .setErrorMessage(Strings.repeat("x", minimumSize)) + .build()) + .build(); + } }; } /** Wraps a MetricExporter. */ static TelemetryExporter wrap(MetricExporter exporter) { return new TelemetryExporter() { + @Override + public Object unwrap() { + return exporter; + } + @Override public CompletableResultCode export(Collection items) { return exporter.export(items); @@ -43,14 +80,32 @@ public CompletableResultCode export(Collection items) { public CompletableResultCode shutdown() { return exporter.shutdown(); } + + @Override + public AbstractMessageLite exportResponse(int minimumSize) { + if (minimumSize == 0) { + return ExportMetricsServiceResponse.getDefaultInstance(); + } + return ExportMetricsServiceResponse.newBuilder() + .setPartialSuccess( + ExportMetricsPartialSuccess.newBuilder() + .setErrorMessage(Strings.repeat("x", minimumSize)) + .build()) + .build(); + } }; } - /** Wraps a LogExporter. */ - static TelemetryExporter wrap(LogExporter exporter) { - return new TelemetryExporter() { + /** Wraps a LogRecordExporter. */ + static TelemetryExporter wrap(LogRecordExporter exporter) { + return new TelemetryExporter() { + @Override + public Object unwrap() { + return exporter; + } + @Override - public CompletableResultCode export(Collection items) { + public CompletableResultCode export(Collection items) { return exporter.export(items); } @@ -58,10 +113,65 @@ public CompletableResultCode export(Collection items) { public CompletableResultCode shutdown() { return exporter.shutdown(); } + + @Override + public AbstractMessageLite exportResponse(int minimumSize) { + if (minimumSize == 0) { + return ExportLogsServiceResponse.getDefaultInstance(); + } + return ExportLogsServiceResponse.newBuilder() + .setPartialSuccess( + ExportLogsPartialSuccess.newBuilder() + .setErrorMessage(Strings.repeat("x", minimumSize)) + .build()) + .build(); + } }; } + /** Wraps a ProfilerExporter. */ + static TelemetryExporter wrap(ProfileExporter exporter) { + return new TelemetryExporter() { + @Override + public Object unwrap() { + return exporter; + } + + @Override + public CompletableResultCode export(Collection items) { + return exporter.export(items); + } + + @Override + public CompletableResultCode shutdown() { + return exporter.shutdown(); + } + + @Override + public AbstractMessageLite exportResponse(int minimumSize) { + if (minimumSize == 0) { + return ExportProfilesServiceResponse.getDefaultInstance(); + } + return ExportProfilesServiceResponse.newBuilder() + .setPartialSuccess( + ExportProfilesPartialSuccess.newBuilder() + .setErrorMessage(Strings.repeat("x", minimumSize)) + .build()) + .build(); + } + }; + } + + Object unwrap(); + CompletableResultCode export(Collection items); CompletableResultCode shutdown(); + + AbstractMessageLite exportResponse(int minimumSize); + + @Override + default void close() { + shutdown().join(10, TimeUnit.SECONDS); + } } diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporterBuilder.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporterBuilder.java index 92ed7bc96d3..63c74fa6dc8 100644 --- a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporterBuilder.java +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/TelemetryExporterBuilder.java @@ -5,26 +5,89 @@ package io.opentelemetry.exporter.otlp.testing.internal; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporterBuilder; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; +import io.opentelemetry.exporter.otlp.profiles.OtlpGrpcProfilesExporterBuilder; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import io.opentelemetry.sdk.trace.data.SpanData; import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; +/** A signal-independent exporter builder for shared OTLP exporter tests. */ public interface TelemetryExporterBuilder { + + static TelemetryExporterBuilder wrap(OtlpGrpcSpanExporterBuilder builder) { + return new GrpcSpanExporterBuilderWrapper(builder); + } + + static TelemetryExporterBuilder wrap(OtlpGrpcMetricExporterBuilder builder) { + return new GrpcMetricExporterBuilderWrapper(builder); + } + + static TelemetryExporterBuilder wrap(OtlpGrpcLogRecordExporterBuilder builder) { + return new GrpcLogRecordExporterBuilderWrapper(builder); + } + + static TelemetryExporterBuilder wrap(OtlpGrpcProfilesExporterBuilder builder) { + return new GrpcProfilesExporterBuilderWrapper(builder); + } + TelemetryExporterBuilder setEndpoint(String endpoint); TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit); TelemetryExporterBuilder setTimeout(Duration timeout); + TelemetryExporterBuilder setConnectTimeout(long timeout, TimeUnit unit); + + TelemetryExporterBuilder setConnectTimeout(Duration timeout); + + TelemetryExporterBuilder setMaxRequestSize(long maxRequestSize); + TelemetryExporterBuilder setCompression(String compression); TelemetryExporterBuilder addHeader(String key, String value); + TelemetryExporterBuilder setHeaders(Supplier> headerSupplier); + TelemetryExporterBuilder setTrustedCertificates(byte[] certificates); TelemetryExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem); - TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy); + TelemetryExporterBuilder setSslContext(SSLContext sslContext, X509TrustManager trustManager); + + TelemetryExporterBuilder setRetryPolicy(@Nullable RetryPolicy retryPolicy); + + TelemetryExporterBuilder setProxyOptions(ProxyOptions proxyOptions); + + TelemetryExporterBuilder setChannel(Object channel); + + TelemetryExporterBuilder setServiceClassLoader(ClassLoader serviceClassLoader); + + TelemetryExporterBuilder setComponentLoader(ComponentLoader componentLoader); + + TelemetryExporterBuilder setExecutorService(ExecutorService executorService); + + TelemetryExporterBuilder setEnabledProtocols(List enabledProtocols); + + TelemetryExporterBuilder setMeterProvider(Supplier meterProviderSupplier); + + TelemetryExporterBuilder setInternalTelemetryVersion(InternalTelemetryVersion schemaVersion); TelemetryExporter build(); } diff --git a/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/compressor/Base64Compressor.java b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/compressor/Base64Compressor.java new file mode 100644 index 00000000000..c4807c1aa08 --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/java/io/opentelemetry/exporter/otlp/testing/internal/compressor/Base64Compressor.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.otlp.testing.internal.compressor; + +import io.opentelemetry.sdk.common.export.Compressor; +import java.io.OutputStream; +import java.util.Base64; + +/** + * This exists to test the compressor SPI mechanism but does not actually compress data in any + * useful way. + */ +public final class Base64Compressor implements Compressor { + + public Base64Compressor() {} + + @Override + public String getEncoding() { + return "base64"; + } + + @Override + public OutputStream compress(OutputStream outputStream) { + return Base64.getEncoder().wrap(outputStream); + } +} diff --git a/exporters/otlp/testing-internal/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.Compressor b/exporters/otlp/testing-internal/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.Compressor new file mode 100644 index 00000000000..6f4ea65a9cd --- /dev/null +++ b/exporters/otlp/testing-internal/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.Compressor @@ -0,0 +1 @@ +io.opentelemetry.exporter.otlp.testing.internal.compressor.Base64Compressor diff --git a/exporters/otlp/trace/README.md b/exporters/otlp/trace/README.md deleted file mode 100644 index 99b16052486..00000000000 --- a/exporters/otlp/trace/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenTelemetry - OTLP Trace Exporter - gRPC - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry exporter, sending span data to OpenTelemetry collector via gRPC. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-otlp-trace.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-otlp-trace diff --git a/exporters/otlp/trace/build.gradle.kts b/exporters/otlp/trace/build.gradle.kts deleted file mode 100644 index 14a64dde1ab..00000000000 --- a/exporters/otlp/trace/build.gradle.kts +++ /dev/null @@ -1,75 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") - id("otel.jmh-conventions") -} - -description = "OpenTelemetry Protocol Trace Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.otlp.trace") - -dependencies { - api(project(":sdk:trace")) - - implementation(project(":exporters:otlp:common")) - - compileOnly("io.grpc:grpc-stub") - - testImplementation(project(":exporters:otlp:testing-internal")) - - jmhImplementation(project(":sdk:testing")) - jmhImplementation("com.linecorp.armeria:armeria") - jmhImplementation("com.linecorp.armeria:armeria-grpc") - jmhImplementation("io.opentelemetry.proto:opentelemetry-proto") - jmhRuntimeOnly("com.squareup.okhttp3:okhttp") - jmhRuntimeOnly("io.grpc:grpc-netty") -} - -testing { - suites { - val testGrpcNetty by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-netty") - implementation("io.grpc:grpc-stub") - } - } - val testGrpcNettyShaded by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-netty-shaded") - implementation("io.grpc:grpc-stub") - } - } - val testGrpcOkhttp by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp:testing-internal")) - - implementation("io.grpc:grpc-okhttp") - implementation("io.grpc:grpc-stub") - } - } - val testSpanPipeline by registering(JvmTestSuite::class) { - dependencies { - implementation("io.opentelemetry.proto:opentelemetry-proto") - implementation("com.linecorp.armeria:armeria-grpc-protocol") - implementation("com.linecorp.armeria:armeria-junit5") - } - } - } -} - -tasks { - check { - dependsOn( - testing.suites.filter { - // Mainly to conveniently profile through IDEA. Don't add to check task, it's for - // manual invocation. - name != "testSpanPipeline" - } - ) - } -} diff --git a/exporters/otlp/trace/src/jmh/java/io/opentelemetry/exporter/otlp/trace/GrpcExporterBenchmark.java b/exporters/otlp/trace/src/jmh/java/io/opentelemetry/exporter/otlp/trace/GrpcExporterBenchmark.java deleted file mode 100644 index e861233a32f..00000000000 --- a/exporters/otlp/trace/src/jmh/java/io/opentelemetry/exporter/otlp/trace/GrpcExporterBenchmark.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import com.linecorp.armeria.server.Server; -import com.linecorp.armeria.server.grpc.GrpcService; -import io.grpc.stub.StreamObserver; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; -import io.opentelemetry.proto.collector.trace.v1.TraceServiceGrpc; -import io.opentelemetry.sdk.common.CompletableResultCode; -import java.net.URI; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.TearDown; -import org.openjdk.jmh.annotations.Warmup; - -@BenchmarkMode({Mode.AverageTime}) -@OutputTimeUnit(TimeUnit.MICROSECONDS) -@Warmup(iterations = 20, time = 1) -@Measurement(iterations = 20, time = 1) -@Fork(1) -@State(Scope.Benchmark) -public class GrpcExporterBenchmark { - private static final Server server = - Server.builder() - .service( - GrpcService.builder() - .addService( - new TraceServiceGrpc.TraceServiceImplBase() { - @Override - public void export( - ExportTraceServiceRequest request, - StreamObserver responseObserver) { - responseObserver.onNext(ExportTraceServiceResponse.getDefaultInstance()); - responseObserver.onCompleted(); - } - }) - .build()) - .http(0) - .build(); - - private static GrpcExporter defaultGrpcExporter; - private static GrpcExporter okhttpGrpcExporter; - - @Setup(Level.Trial) - public void setUp() { - server.start().join(); - - defaultGrpcExporter = - new DefaultGrpcExporterBuilder<>( - "otlp", - "span", - MarshalerTraceServiceGrpc::newFutureStub, - 10, - URI.create("http://localhost:" + server.activeLocalPort()), - OtlpGrpcSpanExporterBuilder.GRPC_SERVICE_NAME) - .build(); - - okhttpGrpcExporter = - new OkHttpGrpcExporterBuilder( - "otlp", - "span", - OtlpGrpcSpanExporterBuilder.GRPC_ENDPOINT_PATH, - 10, - URI.create("http://localhost:" + server.activeLocalPort())) - .build(); - } - - @TearDown(Level.Trial) - public void tearDown() { - defaultGrpcExporter.shutdown().join(10, TimeUnit.SECONDS); - okhttpGrpcExporter.shutdown().join(10, TimeUnit.SECONDS); - server.stop().join(); - } - - @Benchmark - public CompletableResultCode defaultGrpcExporter(RequestMarshalState state) { - CompletableResultCode result = - defaultGrpcExporter - .export(state.traceRequestMarshaler, state.numSpans) - .join(10, TimeUnit.SECONDS); - if (!result.isSuccess()) { - throw new AssertionError(); - } - return result; - } - - @Benchmark - public CompletableResultCode okhttpGrpcExporter(RequestMarshalState state) { - CompletableResultCode result = - okhttpGrpcExporter - .export(state.traceRequestMarshaler, state.numSpans) - .join(10, TimeUnit.SECONDS); - if (!result.isSuccess()) { - throw new AssertionError(); - } - return result; - } -} diff --git a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/MarshalerTraceServiceGrpc.java b/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/MarshalerTraceServiceGrpc.java deleted file mode 100644 index 219b64077d4..00000000000 --- a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/MarshalerTraceServiceGrpc.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import static io.grpc.MethodDescriptor.generateFullMethodName; - -import io.grpc.MethodDescriptor; -import io.opentelemetry.exporter.internal.grpc.MarshalerInputStream; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import java.io.InputStream; - -// Adapted from the protoc generated code for TraceServiceGrpc. -final class MarshalerTraceServiceGrpc { - - private static final String SERVICE_NAME = "opentelemetry.proto.collector.trace.v1.TraceService"; - - private static final MethodDescriptor.Marshaller REQUEST_MARSHALLER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(TraceRequestMarshaler value) { - return new MarshalerInputStream(value); - } - - @Override - public TraceRequestMarshaler parse(InputStream stream) { - throw new UnsupportedOperationException("Only for serializing"); - } - }; - - private static final MethodDescriptor.Marshaller RESPONSE_MARSHALER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(ExportTraceServiceResponse value) { - throw new UnsupportedOperationException("Only for parsing"); - } - - @Override - public ExportTraceServiceResponse parse(InputStream stream) { - return ExportTraceServiceResponse.INSTANCE; - } - }; - - private static final io.grpc.MethodDescriptor - getExportMethod = - io.grpc.MethodDescriptor.newBuilder() - .setType(io.grpc.MethodDescriptor.MethodType.UNARY) - .setFullMethodName(generateFullMethodName(SERVICE_NAME, "Export")) - .setRequestMarshaller(REQUEST_MARSHALLER) - .setResponseMarshaller(RESPONSE_MARSHALER) - .build(); - - static TraceServiceFutureStub newFutureStub(io.grpc.Channel channel) { - return TraceServiceFutureStub.newStub(TraceServiceFutureStub::new, channel); - } - - static final class TraceServiceFutureStub - extends MarshalerServiceStub< - TraceRequestMarshaler, ExportTraceServiceResponse, TraceServiceFutureStub> { - private TraceServiceFutureStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) { - super(channel, callOptions); - } - - @java.lang.Override - protected MarshalerTraceServiceGrpc.TraceServiceFutureStub build( - io.grpc.Channel channel, io.grpc.CallOptions callOptions) { - return new MarshalerTraceServiceGrpc.TraceServiceFutureStub(channel, callOptions); - } - - @Override - public com.google.common.util.concurrent.ListenableFuture export( - TraceRequestMarshaler request) { - return io.grpc.stub.ClientCalls.futureUnaryCall( - getChannel().newCall(getExportMethod, getCallOptions()), request); - } - } - - private MarshalerTraceServiceGrpc() {} -} diff --git a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporter.java b/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporter.java deleted file mode 100644 index 5fa40bcbd40..00000000000 --- a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporter.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Collection; -import javax.annotation.concurrent.ThreadSafe; - -/** Exports spans using OTLP via gRPC, using OpenTelemetry's protobuf model. */ -@ThreadSafe -public final class OtlpGrpcSpanExporter implements SpanExporter { - - private final GrpcExporter delegate; - - /** - * Returns a new {@link OtlpGrpcSpanExporter} reading the configuration values from the - * environment and from system properties. System properties override values defined in the - * environment. If a configuration value is missing, it uses the default value. - * - * @return a new {@link OtlpGrpcSpanExporter} instance. - */ - public static OtlpGrpcSpanExporter getDefault() { - return builder().build(); - } - - /** - * Returns a new builder instance for this exporter. - * - * @return a new builder instance for this exporter. - */ - public static OtlpGrpcSpanExporterBuilder builder() { - return new OtlpGrpcSpanExporterBuilder(); - } - - OtlpGrpcSpanExporter(GrpcExporter delegate) { - this.delegate = delegate; - } - - /** - * Submits all the given spans in a single batch to the OpenTelemetry collector. - * - * @param spans the list of sampled Spans to be exported. - * @return the result of the operation - */ - @Override - public CompletableResultCode export(Collection spans) { - TraceRequestMarshaler request = TraceRequestMarshaler.create(spans); - - return delegate.export(request, spans.size()); - } - - /** - * The OTLP exporter does not batch spans, so this method will immediately return with success. - * - * @return always Success - */ - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately - * cancelled. - */ - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } -} diff --git a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterBuilder.java b/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterBuilder.java deleted file mode 100644 index c7a88afcd54..00000000000 --- a/exporters/otlp/trace/src/main/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterBuilder.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.grpc.ManagedChannel; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.grpc.GrpcExporter; -import io.opentelemetry.exporter.internal.grpc.GrpcExporterBuilder; -import io.opentelemetry.exporter.internal.otlp.traces.TraceRequestMarshaler; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder utility for this exporter. */ -public final class OtlpGrpcSpanExporterBuilder { - - // Visible for testing - static final String GRPC_SERVICE_NAME = "opentelemetry.proto.collector.trace.v1.TraceService"; - // Visible for testing - static final String GRPC_ENDPOINT_PATH = "/" + GRPC_SERVICE_NAME + "/Export"; - - private static final String DEFAULT_ENDPOINT_URL = "http://localhost:4317"; - private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); - private static final long DEFAULT_TIMEOUT_SECS = 10; - - // Visible for testing - final GrpcExporterBuilder delegate; - - OtlpGrpcSpanExporterBuilder() { - delegate = - GrpcExporter.builder( - "otlp", - "span", - DEFAULT_TIMEOUT_SECS, - DEFAULT_ENDPOINT, - () -> MarshalerTraceServiceGrpc::newFutureStub, - GRPC_SERVICE_NAME, - GRPC_ENDPOINT_PATH); - } - - /** - * Sets the managed chanel to use when communicating with the backend. Takes precedence over - * {@link #setEndpoint(String)} if both are called. - * - * @param channel the channel to use - * @return this builder's instance - * @deprecated Use {@link #setEndpoint(String)}. If you have a use case not satisfied by the - * methods on this builder, please file an issue to let us know what it is. - */ - @Deprecated - public OtlpGrpcSpanExporterBuilder setChannel(ManagedChannel channel) { - delegate.setChannel(channel); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of spans. If - * unset, defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpGrpcSpanExporterBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - delegate.setTimeout(timeout, unit); - return this; - } - - /** - * Sets the maximum time to wait for the collector to process an exported batch of spans. If - * unset, defaults to {@value DEFAULT_TIMEOUT_SECS}s. - */ - public OtlpGrpcSpanExporterBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - delegate.setTimeout(timeout); - return this; - } - - /** - * Sets the OTLP endpoint to connect to. If unset, defaults to {@value DEFAULT_ENDPOINT_URL}. The - * endpoint must start with either http:// or https://. - */ - public OtlpGrpcSpanExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); - return this; - } - - /** - * Sets the method used to compress payloads. If unset, compression is disabled. Currently - * supported compression methods include "gzip" and "none". - */ - public OtlpGrpcSpanExporterBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - delegate.setCompression(compressionMethod); - return this; - } - - /** - * Sets the certificate chain to use for verifying servers when TLS is enabled. The {@code byte[]} - * should contain an X.509 certificate collection in PEM format. If not set, TLS connections will - * use the system default trusted certificates. - */ - public OtlpGrpcSpanExporterBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { - delegate.setTrustedCertificates(trustedCertificatesPem); - return this; - } - - /** - * Sets ths client key and the certificate chain to use for verifying client when TLS is enabled. - */ - public OtlpGrpcSpanExporterBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - delegate.setClientTls(privateKeyPem, certificatePem); - return this; - } - - /** - * Add header to request. Optional. Applicable only if {@link - * OtlpGrpcSpanExporterBuilder#setChannel(ManagedChannel)} is not called. - * - * @param key header key - * @param value header value - * @return this builder's instance - */ - public OtlpGrpcSpanExporterBuilder addHeader(String key, String value) { - delegate.addHeader(key, value); - return this; - } - - /** - * Sets the {@link MeterProvider} to use to collect metrics related to export. If not set, metrics - * will not be collected. - */ - public OtlpGrpcSpanExporterBuilder setMeterProvider(MeterProvider meterProvider) { - requireNonNull(meterProvider, "meterProvider"); - delegate.setMeterProvider(meterProvider); - return this; - } - - /** - * Constructs a new instance of the exporter based on the builder's values. - * - * @return a new exporter's instance - */ - public OtlpGrpcSpanExporter build() { - return new OtlpGrpcSpanExporter(delegate.build()); - } -} diff --git a/exporters/otlp/trace/src/main/proto/README.md b/exporters/otlp/trace/src/main/proto/README.md deleted file mode 100644 index f36259bdd21..00000000000 --- a/exporters/otlp/trace/src/main/proto/README.md +++ /dev/null @@ -1 +0,0 @@ -Non-empty folder required for wire proto compiler. diff --git a/exporters/otlp/trace/src/test/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterTest.java b/exporters/otlp/trace/src/test/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterTest.java deleted file mode 100644 index bcdef53e205..00000000000 --- a/exporters/otlp/trace/src/test/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcSpanExporterTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.trace.v1.ResourceSpans; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcSpanExporterTest extends AbstractGrpcTelemetryExporterTest { - - private static final String TRACE_ID = "00000000000000000000000000abc123"; - private static final String SPAN_ID = "0000000000def456"; - - OtlpGrpcSpanExporterTest() { - super("span", ResourceSpans.getDefaultInstance()); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpGrpcSpanExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void usingOkHttp() { - assertThat(OtlpGrpcSpanExporter.builder().delegate) - .isInstanceOf(OkHttpGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected SpanData generateFakeTelemetry() { - long duration = TimeUnit.MILLISECONDS.toNanos(900); - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + duration; - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(startNs) - .setEndEpochNanos(endNs) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceSpansMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/trace/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettySpanExporterTest.java b/exporters/otlp/trace/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettySpanExporterTest.java deleted file mode 100644 index 8cba2e088cf..00000000000 --- a/exporters/otlp/trace/src/testGrpcNetty/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettySpanExporterTest.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.trace.v1.ResourceSpans; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettySpanExporterTest - extends AbstractGrpcTelemetryExporterTest { - - private static final String TRACE_ID = "00000000000000000000000000abc123"; - private static final String SPAN_ID = "0000000000def456"; - - OtlpGrpcNettySpanExporterTest() { - super("span", ResourceSpans.getDefaultInstance()); - } - - @Test - void testSetRetryPolicyOnDelegate() { - assertThatCode( - () -> - RetryUtil.setRetryPolicyOnDelegate( - OtlpGrpcSpanExporter.builder(), RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcSpanExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected SpanData generateFakeTelemetry() { - long duration = TimeUnit.MILLISECONDS.toNanos(900); - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + duration; - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(startNs) - .setEndEpochNanos(endNs) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceSpansMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/trace/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettyShadedSpanExporterTest.java b/exporters/otlp/trace/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettyShadedSpanExporterTest.java deleted file mode 100644 index 37e94a25eb6..00000000000 --- a/exporters/otlp/trace/src/testGrpcNettyShaded/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcNettyShadedSpanExporterTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.trace.v1.ResourceSpans; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcNettyShadedSpanExporterTest - extends AbstractGrpcTelemetryExporterTest { - - private static final String TRACE_ID = "00000000000000000000000000abc123"; - private static final String SPAN_ID = "0000000000def456"; - - OtlpGrpcNettyShadedSpanExporterTest() { - super("span", ResourceSpans.getDefaultInstance()); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcSpanExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected SpanData generateFakeTelemetry() { - long duration = TimeUnit.MILLISECONDS.toNanos(900); - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + duration; - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(startNs) - .setEndEpochNanos(endNs) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceSpansMarshaler.create(telemetry); - } -} diff --git a/exporters/otlp/trace/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcOkHttpSpanExporterTest.java b/exporters/otlp/trace/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcOkHttpSpanExporterTest.java deleted file mode 100644 index 24185caa4e6..00000000000 --- a/exporters/otlp/trace/src/testGrpcOkhttp/java/io/opentelemetry/exporter/otlp/trace/OtlpGrpcOkHttpSpanExporterTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.otlp.trace; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.otlp.traces.ResourceSpansMarshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.otlp.testing.internal.AbstractGrpcTelemetryExporterTest; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporter; -import io.opentelemetry.exporter.otlp.testing.internal.TelemetryExporterBuilder; -import io.opentelemetry.proto.trace.v1.ResourceSpans; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.time.Duration; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OtlpGrpcOkHttpSpanExporterTest - extends AbstractGrpcTelemetryExporterTest { - - private static final String TRACE_ID = "00000000000000000000000000abc123"; - private static final String SPAN_ID = "0000000000def456"; - - OtlpGrpcOkHttpSpanExporterTest() { - super("span", ResourceSpans.getDefaultInstance()); - } - - @Test - void usingGrpc() { - assertThat(OtlpGrpcSpanExporter.builder().delegate) - .isInstanceOf(DefaultGrpcExporterBuilder.class); - } - - @Override - protected TelemetryExporterBuilder exporterBuilder() { - OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder(); - return new TelemetryExporterBuilder() { - @Override - public TelemetryExporterBuilder setEndpoint(String endpoint) { - builder.setEndpoint(endpoint); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(long timeout, TimeUnit unit) { - builder.setTimeout(timeout, unit); - return this; - } - - @Override - public TelemetryExporterBuilder setTimeout(Duration timeout) { - builder.setTimeout(timeout); - return this; - } - - @Override - public TelemetryExporterBuilder setCompression(String compression) { - builder.setCompression(compression); - return this; - } - - @Override - public TelemetryExporterBuilder addHeader(String key, String value) { - builder.addHeader(key, value); - return this; - } - - @Override - public TelemetryExporterBuilder setTrustedCertificates(byte[] certificates) { - builder.setTrustedCertificates(certificates); - return this; - } - - @Override - public TelemetryExporterBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - builder.setClientTls(privateKeyPem, certificatePem); - return this; - } - - @Override - public TelemetryExporterBuilder setRetryPolicy(RetryPolicy retryPolicy) { - builder.delegate.setRetryPolicy(retryPolicy); - return this; - } - - @Override - public TelemetryExporter build() { - return TelemetryExporter.wrap(builder.build()); - } - }; - } - - @Override - protected SpanData generateFakeTelemetry() { - long duration = TimeUnit.MILLISECONDS.toNanos(900); - long startNs = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - long endNs = startNs + duration; - return TestSpanData.builder() - .setHasEnded(true) - .setSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setName("GET /api/endpoint") - .setStartEpochNanos(startNs) - .setEndEpochNanos(endNs) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setLinks(Collections.emptyList()) - .setTotalRecordedLinks(0) - .setTotalRecordedEvents(0) - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("testLib", "1.0", "http://url")) - .build(); - } - - @Override - protected Marshaler[] toMarshalers(List telemetry) { - return ResourceSpansMarshaler.create(telemetry); - } -} diff --git a/exporters/prometheus/README.md b/exporters/prometheus/README.md deleted file mode 100644 index af2e89660e5..00000000000 --- a/exporters/prometheus/README.md +++ /dev/null @@ -1,8 +0,0 @@ -# OpenTelemetry - Prometheus Exporter - -[![Javadocs][javadoc-image]][javadoc-url] - -This is the OpenTelemetry's Prometheus exporter, allowing Prometheus to query metrics data. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-prometheus.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-prometheus diff --git a/exporters/prometheus/build.gradle.kts b/exporters/prometheus/build.gradle.kts index 81ca190fa0b..ce3c7aa0d82 100644 --- a/exporters/prometheus/build.gradle.kts +++ b/exporters/prometheus/build.gradle.kts @@ -1,34 +1,44 @@ plugins { id("otel.java-conventions") id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") } description = "OpenTelemetry Prometheus Exporter" otelJava.moduleName.set("io.opentelemetry.exporter.prometheus") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator", "io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider", + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) dependencies { api(project(":sdk:metrics")) - compileOnly("com.sun.net.httpserver:http") + compileOnly(project(":api:incubator")) + implementation(project(":exporters:common")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + implementation("io.prometheus:prometheus-metrics-exporter-httpserver") { + exclude(group = "io.prometheus", module = "prometheus-metrics-exposition-formats") + } + implementation("io.prometheus:prometheus-metrics-exposition-formats-no-protobuf") + + compileOnly("com.google.auto.value:auto-value-annotations") + compileOnly("com.google.errorprone:error_prone_annotations") + annotationProcessor("com.google.auto.value:auto-value") + + testImplementation(project(":sdk:testing")) + testImplementation(project(":sdk-extensions:autoconfigure-spi")) + testImplementation("io.opentelemetry.proto:opentelemetry-proto") + testImplementation("com.sun.net.httpserver:http") testImplementation("com.google.guava:guava") testImplementation("com.linecorp.armeria:armeria") -} - -testing { - suites { - val integrationTest by registering(JvmTestSuite::class) { - dependencies { - implementation("com.fasterxml.jackson.jr:jackson-jr-stree") - implementation("com.google.guava:guava") - implementation("com.linecorp.armeria:armeria") - implementation("io.prometheus:simpleclient_httpserver") - implementation("org.testcontainers:junit-jupiter") - } - } - } + testImplementation("com.linecorp.armeria:armeria-junit5") + testImplementation("com.linecorp.armeria:armeria-grpc-protocol") + testImplementation("com.fasterxml.jackson.jr:jackson-jr-stree") + testImplementation("com.fasterxml.jackson.jr:jackson-jr-objects") + testImplementation("org.testcontainers:testcontainers-junit-jupiter") } tasks { @@ -41,7 +51,7 @@ tasks { testing { suites { - val testJpms by registering(JvmTestSuite::class) { + register("testJpms") { targets { all { testTask.configure { @@ -54,7 +64,7 @@ testing { } sourceSets { - val module by creating + val module = create("module") main { output.dir(mapOf("builtBy" to "compileModuleJava"), module.java.destinationDirectory) } @@ -81,7 +91,7 @@ tasks { exclude("module-info.java") } - val compileModuleJava by existing(JavaCompile::class) { + named("compileModuleJava") { with(options) { release.set(9) } diff --git a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/AbstractPrometheusIntegrationTest.java b/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/AbstractPrometheusIntegrationTest.java deleted file mode 100644 index a97bb6284b8..00000000000 --- a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/AbstractPrometheusIntegrationTest.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; -import static org.testcontainers.Testcontainers.exposeHostPorts; - -import com.fasterxml.jackson.core.TreeNode; -import com.fasterxml.jackson.jr.ob.JSON; -import com.fasterxml.jackson.jr.stree.JacksonJrsTreeCodec; -import com.fasterxml.jackson.jr.stree.JrsString; -import com.google.common.io.Resources; -import com.linecorp.armeria.client.WebClient; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.prometheus.client.exporter.HTTPServer; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.io.TempDir; -import org.slf4j.LoggerFactory; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.output.Slf4jLogConsumer; -import org.testcontainers.containers.wait.strategy.Wait; -import org.testcontainers.junit.jupiter.Testcontainers; -import org.testcontainers.utility.MountableFile; - -@Testcontainers(disabledWithoutDocker = true) -@TestInstance(TestInstance.Lifecycle.PER_CLASS) -abstract class AbstractPrometheusIntegrationTest { - - protected SdkMeterProvider meterProvider; - protected int port; - - private GenericContainer prometheus; - - @BeforeAll - void setUp(@TempDir Path tempDir) throws Exception { - exposeHostPorts(port); - - String promConfigTemplate = - Resources.toString(Resources.getResource("prom.yml"), StandardCharsets.UTF_8); - Path promConfig = tempDir.resolve("prom.yml"); - Files.write( - promConfig, - promConfigTemplate - .replace("{{APP_PORT}}", String.valueOf(port)) - .getBytes(StandardCharsets.UTF_8)); - - prometheus = - new GenericContainer<>("prom/prometheus:v2.30.3") - .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("prometheus"))) - .withExposedPorts(9090) - .waitingFor(Wait.forHttp("/-/ready")) - .withCopyFileToContainer(MountableFile.forHostPath(promConfig), "/etc/prom.yml") - .withCommand("--config.file", "/etc/prom.yml"); - prometheus.start(); - } - - @AfterAll - void tearDown() { - prometheus.stop(); - meterProvider.shutdown(); - } - - @Test - void endToEnd() { - Meter meter = meterProvider.meterBuilder("test").build(); - - meter - .counterBuilder("requests") - .build() - .add(3, Attributes.builder().put("animal", "bear").build()); - meter - .gaugeBuilder("lives") - .buildWithCallback( - result -> result.record(9, Attributes.builder().put("animal", "cat").build())); - - WebClient promClient = WebClient.of("http://localhost:" + prometheus.getMappedPort(9090)); - JSON json = JSON.builder().treeCodec(new JacksonJrsTreeCodec()).build(); - await() - .untilAsserted( - () -> { - TreeNode response = - json.treeFrom( - promClient - .get("/api/v1/query?query=requests_total") - .aggregate() - .join() - .contentUtf8()); - assertThat(response.get("status")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); - TreeNode result = response.get("data").get("result").get(0); - assertThat(result).isNotNull(); - assertThat(result.get("metric").get("__name__")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("requests_total")); - assertThat(result.get("metric").get("animal")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("bear")); - assertThat(result.get("value").get(1)) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("3")); - - response = - json.treeFrom( - promClient.get("/api/v1/query?query=lives").aggregate().join().contentUtf8()); - assertThat(response.get("status")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); - result = response.get("data").get("result").get(0); - assertThat(result).isNotNull(); - assertThat(result.get("metric").get("__name__")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("lives")); - assertThat(result.get("metric").get("animal")) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("cat")); - assertThat(result.get("value").get(1)) - .isInstanceOfSatisfying( - JrsString.class, s -> assertThat(s.getValue()).isEqualTo("9")); - }); - } - - static class PrometheusHttpServerIntegrationTest extends AbstractPrometheusIntegrationTest { - PrometheusHttpServerIntegrationTest() { - PrometheusHttpServer prometheusHttpServer = PrometheusHttpServer.builder().setPort(0).build(); - meterProvider = SdkMeterProvider.builder().registerMetricReader(prometheusHttpServer).build(); - port = prometheusHttpServer.getAddress().getPort(); - } - } - - static class PrometheusCollectorIntegrationTest extends AbstractPrometheusIntegrationTest { - private final HTTPServer server; - - // Tests deprecated class - @SuppressWarnings("deprecation") - PrometheusCollectorIntegrationTest() throws IOException { - server = new HTTPServer(0); - port = server.getPort(); - - meterProvider = - SdkMeterProvider.builder().registerMetricReader(PrometheusCollector.create()).build(); - } - - @AfterAll - void stopHttpServer() { - server.close(); - } - } -} diff --git a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/MetricAdapter.java b/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/MetricAdapter.java deleted file mode 100644 index 95b3376ea60..00000000000 --- a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/MetricAdapter.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import static io.prometheus.client.Collector.doubleToGoString; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.DoublePointData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.HistogramPointData; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; -import io.opentelemetry.sdk.metrics.data.LongPointData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.MetricDataType; -import io.opentelemetry.sdk.metrics.data.PointData; -import io.opentelemetry.sdk.metrics.data.SumData; -import io.opentelemetry.sdk.metrics.data.SummaryPointData; -import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; -import io.prometheus.client.Collector; -import io.prometheus.client.Collector.MetricFamilySamples; -import io.prometheus.client.Collector.MetricFamilySamples.Sample; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import javax.annotation.Nullable; - -/** - * Util methods to convert OpenTelemetry Metrics data models to Prometheus data models. - * - *

    Each OpenTelemetry {@link MetricData} will be converted to a Prometheus {@link - * MetricFamilySamples}, and each {@code Point} of the {@link MetricData} will be converted to - * Prometheus {@link Sample}s. - * - *

    {@code DoublePoint}, {@code LongPoint} will be converted to a single {@link Sample}. {@code - * Summary} will be converted to two {@link Sample}s (sum and count) plus the number of Percentile - * values {@code Sample}s - * - *

    Please note that Prometheus Metric and Label name can only have alphanumeric characters and - * underscore. All other characters will be sanitized by underscores. - */ -final class MetricAdapter { - - static final String SAMPLE_SUFFIX_COUNT = "_count"; - static final String SAMPLE_SUFFIX_SUM = "_sum"; - static final String SAMPLE_SUFFIX_BUCKET = "_bucket"; - static final String LABEL_NAME_QUANTILE = "quantile"; - static final String LABEL_NAME_LE = "le"; - - // Converts a MetricData to a Prometheus MetricFamilySamples. - static MetricFamilySamples toMetricFamilySamples(MetricData metricData) { - String cleanMetricName = cleanMetricName(metricData.getName()); - Collector.Type type = toMetricFamilyType(metricData); - - return new MetricFamilySamples( - cleanMetricName, - type, - metricData.getDescription(), - toSamples(cleanMetricName, metricData.getType(), Serializer.getPoints(metricData))); - } - - private static String cleanMetricName(String descriptorMetricName) { - return Collector.sanitizeMetricName(descriptorMetricName); - } - - static Collector.Type toMetricFamilyType(MetricData metricData) { - switch (metricData.getType()) { - case LONG_GAUGE: - case DOUBLE_GAUGE: - return Collector.Type.GAUGE; - case LONG_SUM: - SumData longSumData = metricData.getLongSumData(); - if (longSumData.isMonotonic() - && longSumData.getAggregationTemporality() == AggregationTemporality.CUMULATIVE) { - return Collector.Type.COUNTER; - } - return Collector.Type.GAUGE; - case DOUBLE_SUM: - SumData doubleSumData = metricData.getDoubleSumData(); - if (doubleSumData.isMonotonic() - && doubleSumData.getAggregationTemporality() == AggregationTemporality.CUMULATIVE) { - return Collector.Type.COUNTER; - } - return Collector.Type.GAUGE; - case SUMMARY: - return Collector.Type.SUMMARY; - case HISTOGRAM: - return Collector.Type.HISTOGRAM; - case EXPONENTIAL_HISTOGRAM: - return Collector.Type.UNKNOWN; // todo exporter for exponential histogram - } - return Collector.Type.UNKNOWN; - } - - static final Function sanitizer = new NameSanitizer(); - - // Converts a list of points from MetricData to a list of Prometheus Samples. - static List toSamples( - String name, MetricDataType type, Collection points) { - List samples = new ArrayList<>(estimateNumSamples(points.size(), type)); - - for (PointData pointData : points) { - Attributes attributes = pointData.getAttributes(); - List labelNames = new ArrayList<>(attributes.size()); - List labelValues = new ArrayList<>(attributes.size()); - attributes.forEach( - (key, value) -> { - String sanitizedLabelName = sanitizer.apply(key.getKey()); - labelNames.add(sanitizedLabelName); - // TODO: We want to create an error-log if there is overlap in toString of attribute - // values for the same key name. - labelValues.add(value == null ? "" : value.toString()); - }); - - switch (type) { - case DOUBLE_SUM: - case DOUBLE_GAUGE: - DoublePointData doublePoint = (DoublePointData) pointData; - samples.add( - createSample( - name, - labelNames, - labelValues, - doublePoint.getValue(), - // Prometheus doesn't support exemplars on SUM/GAUGE - null, - doublePoint.getEpochNanos())); - break; - case LONG_SUM: - case LONG_GAUGE: - LongPointData longPoint = (LongPointData) pointData; - samples.add( - createSample( - name, - labelNames, - labelValues, - (double) longPoint.getValue(), - // Prometheus doesn't support exemplars on SUM/GAUGE - null, - longPoint.getEpochNanos())); - break; - case SUMMARY: - addSummarySamples((SummaryPointData) pointData, name, labelNames, labelValues, samples); - break; - case HISTOGRAM: - addHistogramSamples( - (HistogramPointData) pointData, name, labelNames, labelValues, samples); - break; - case EXPONENTIAL_HISTOGRAM: - break; // todo - } - } - return samples; - } - - private static void addSummarySamples( - SummaryPointData doubleSummaryPoint, - String name, - List labelNames, - List labelValues, - List samples) { - samples.add( - createSample( - name + SAMPLE_SUFFIX_COUNT, - labelNames, - labelValues, - (double) doubleSummaryPoint.getCount(), - null, - doubleSummaryPoint.getEpochNanos())); - - samples.add( - createSample( - name + SAMPLE_SUFFIX_SUM, - labelNames, - labelValues, - doubleSummaryPoint.getSum(), - null, - doubleSummaryPoint.getEpochNanos())); - - List valueAtQuantiles = doubleSummaryPoint.getValues(); - List labelNamesWithQuantile = new ArrayList<>(labelNames.size()); - labelNamesWithQuantile.addAll(labelNames); - labelNamesWithQuantile.add(LABEL_NAME_QUANTILE); - for (ValueAtQuantile valueAtQuantile : valueAtQuantiles) { - List labelValuesWithQuantile = new ArrayList<>(labelValues.size()); - labelValuesWithQuantile.addAll(labelValues); - labelValuesWithQuantile.add(doubleToGoString(valueAtQuantile.getQuantile())); - samples.add( - createSample( - name, - labelNamesWithQuantile, - labelValuesWithQuantile, - valueAtQuantile.getValue(), - null, - doubleSummaryPoint.getEpochNanos())); - } - } - - private static void addHistogramSamples( - HistogramPointData histogramPointData, - String name, - List labelNames, - List labelValues, - List samples) { - samples.add( - createSample( - name + SAMPLE_SUFFIX_COUNT, - labelNames, - labelValues, - (double) histogramPointData.getCount(), - null, - histogramPointData.getEpochNanos())); - - samples.add( - createSample( - name + SAMPLE_SUFFIX_SUM, - labelNames, - labelValues, - histogramPointData.getSum(), - null, - histogramPointData.getEpochNanos())); - - List labelNamesWithLe = new ArrayList<>(labelNames.size() + 1); - labelNamesWithLe.addAll(labelNames); - labelNamesWithLe.add(LABEL_NAME_LE); - - long cumulativeCount = 0; - List counts = histogramPointData.getCounts(); - for (int i = 0; i < counts.size(); i++) { - List labelValuesWithLe = new ArrayList<>(labelValues.size() + 1); - // This is the upper boundary (inclusive). I.e. all values should be < this value (LE - - // Less-then-or-Equal). - double boundary = Serializer.getBucketUpperBound(histogramPointData, i); - labelValuesWithLe.addAll(labelValues); - labelValuesWithLe.add(doubleToGoString(boundary)); - - cumulativeCount += counts.get(i); - samples.add( - createSample( - name + SAMPLE_SUFFIX_BUCKET, - labelNamesWithLe, - labelValuesWithLe, - (double) cumulativeCount, - filterExemplars( - histogramPointData.getExemplars(), - Serializer.getBucketLowerBound(histogramPointData, i), - boundary), - histogramPointData.getEpochNanos())); - } - } - - @Nullable - private static ExemplarData filterExemplars( - Collection exemplars, double min, double max) { - ExemplarData result = null; - for (ExemplarData e : exemplars) { - double value = getExemplarValue(e); - if (value <= max && value > min) { - result = e; - } - } - return result; - } - - private static int estimateNumSamples(int numPoints, MetricDataType type) { - if (type == MetricDataType.SUMMARY) { - // count + sum + estimated 2 percentiles - return numPoints * 4; - } - return numPoints; - } - - private static Sample createSample( - String name, - List labelNames, - List labelValues, - double value, - @Nullable ExemplarData exemplar, - long timestampNanos) { - if (exemplar != null) { - return new Sample( - name, - labelNames, - labelValues, - value, - toPrometheusExemplar(exemplar), - TimeUnit.MILLISECONDS.convert(timestampNanos, TimeUnit.NANOSECONDS)); - } - return new Sample( - name, - labelNames, - labelValues, - value, - null, - TimeUnit.MILLISECONDS.convert(timestampNanos, TimeUnit.NANOSECONDS)); - } - - private static io.prometheus.client.exemplars.Exemplar toPrometheusExemplar( - ExemplarData exemplar) { - SpanContext spanContext = exemplar.getSpanContext(); - if (spanContext.isValid()) { - return new io.prometheus.client.exemplars.Exemplar( - getExemplarValue(exemplar), - // Convert to ms for prometheus, truncate nanosecond precision. - TimeUnit.NANOSECONDS.toMillis(exemplar.getEpochNanos()), - "trace_id", - spanContext.getTraceId(), - "span_id", - spanContext.getSpanId()); - } - return new io.prometheus.client.exemplars.Exemplar(getExemplarValue(exemplar)); - } - - private static double getExemplarValue(ExemplarData exemplar) { - return exemplar instanceof DoubleExemplarData - ? ((DoubleExemplarData) exemplar).getValue() - : (double) ((LongExemplarData) exemplar).getValue(); - } - - private MetricAdapter() {} -} diff --git a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/MetricAdapterTest.java b/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/MetricAdapterTest.java deleted file mode 100644 index 95dcef4cd9f..00000000000 --- a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/MetricAdapterTest.java +++ /dev/null @@ -1,822 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableList; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.MetricDataType; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; -import io.opentelemetry.sdk.resources.Resource; -import io.prometheus.client.Collector; -import io.prometheus.client.Collector.MetricFamilySamples; -import io.prometheus.client.Collector.MetricFamilySamples.Sample; -import io.prometheus.client.exemplars.Exemplar; -import io.prometheus.client.exporter.common.TextFormat; -import java.io.IOException; -import java.io.StringWriter; -import java.io.UncheckedIOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import org.assertj.core.presentation.StandardRepresentation; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link MetricAdapter}. */ -class MetricAdapterTest { - - private static final Attributes KP_VP_ATTR = Attributes.of(stringKey("kp"), "vp"); - - private static final MetricData MONOTONIC_CUMULATIVE_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData MONOTONIC_DELTA_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData NON_MONOTONIC_DELTA_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData MONOTONIC_CUMULATIVE_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData NON_MONOTONIC_CUMULATIVE_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData MONOTONIC_DELTA_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData NON_MONOTONIC_DELTA_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - - private static final MetricData DOUBLE_GAUGE = - ImmutableMetricData.createDoubleGauge( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableGaugeData.create( - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData LONG_GAUGE = - ImmutableMetricData.createLongGauge( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableGaugeData.create( - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))); - private static final MetricData SUMMARY = - ImmutableMetricData.createDoubleSummary( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSummaryData.create( - Collections.singletonList( - ImmutableSummaryPointData.create( - 1633947011000000000L, - 1633950672000000000L, - KP_VP_ATTR, - 5, - 7, - Arrays.asList( - ImmutableValueAtQuantile.create(0.9, 0.1), - ImmutableValueAtQuantile.create(0.99, 0.3)))))); - private static final MetricData HISTOGRAM = - ImmutableMetricData.createDoubleHistogram( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableHistogramData.create( - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableHistogramPointData.create( - 1633947011000000000L, - 1633950672000000000L, - KP_VP_ATTR, - 1.0, - null, - null, - Collections.emptyList(), - Collections.singletonList(2L), - Collections.singletonList( - ImmutableDoubleExemplarData.create( - Attributes.empty(), - TimeUnit.MILLISECONDS.toNanos(1L), - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - /* value= */ 4)))))); - - @Test - void monotonicCumulativeDoubleSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(MONOTONIC_CUMULATIVE_DOUBLE_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.COUNTER); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void nonMonotonicCumulativeDoubleSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void monotonicDeltaDoubleSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(MONOTONIC_DELTA_DOUBLE_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void nonMonotonicDeltaDoubleSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(NON_MONOTONIC_DELTA_DOUBLE_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void monotonicCumulativeLongSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(MONOTONIC_CUMULATIVE_LONG_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.COUNTER); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void nonMontonicCumulativeLongSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(NON_MONOTONIC_CUMULATIVE_LONG_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void monotonicDeltaLongSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(MONOTONIC_DELTA_LONG_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void nonMonotonicDeltaLongSum() { - MetricFamilySamples metricFamilySamples = - MetricAdapter.toMetricFamilySamples(NON_MONOTONIC_DELTA_LONG_SUM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void summary() { - MetricFamilySamples metricFamilySamples = MetricAdapter.toMetricFamilySamples(SUMMARY); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.SUMMARY); - assertThat(metricFamilySamples.samples).hasSize(4); - } - - @Test - void doubleGauge() { - MetricFamilySamples metricFamilySamples = MetricAdapter.toMetricFamilySamples(DOUBLE_GAUGE); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void longGauge() { - MetricFamilySamples metricFamilySamples = MetricAdapter.toMetricFamilySamples(LONG_GAUGE); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.GAUGE); - assertThat(metricFamilySamples.samples).hasSize(1); - } - - @Test - void histogram() { - MetricFamilySamples metricFamilySamples = MetricAdapter.toMetricFamilySamples(HISTOGRAM); - assertThat(metricFamilySamples.type).isEqualTo(Collector.Type.HISTOGRAM); - assertThat(metricFamilySamples.samples).hasSize(3); - } - - @Test - void toSamples_LongPoints() { - assertThat( - MetricAdapter.toSamples("full_name", MetricDataType.LONG_SUM, Collections.emptyList())) - .isEmpty(); - - assertThat( - MetricAdapter.toSamples( - "full_name", - MetricDataType.LONG_SUM, - ImmutableList.of( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, Attributes.empty(), 5), - ImmutableLongPointData.create( - 1633939689000000000L, 1633943350000000000L, KP_VP_ATTR, 7)))) - .containsExactly( - new Sample( - "full_name", - Collections.emptyList(), - Collections.emptyList(), - 5, - null, - 1633950672000L), - new Sample( - "full_name", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 7, - null, - 1633943350000L)); - - assertThat( - MetricAdapter.toSamples( - "full_name", - MetricDataType.LONG_GAUGE, - ImmutableList.of( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, Attributes.empty(), 5), - ImmutableLongPointData.create( - 1633939689000000000L, 1633943350000000000L, KP_VP_ATTR, 7)))) - .containsExactly( - new Sample( - "full_name", - Collections.emptyList(), - Collections.emptyList(), - 5, - null, - 1633950672000L), - new Sample( - "full_name", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 7, - null, - 1633943350000L)); - } - - @Test - void toSamples_DoublePoints() { - assertThat( - MetricAdapter.toSamples( - "full_name", MetricDataType.DOUBLE_SUM, Collections.emptyList())) - .isEmpty(); - - assertThat( - MetricAdapter.toSamples( - "full_name", - MetricDataType.DOUBLE_SUM, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, KP_VP_ATTR, 5)))) - .containsExactly( - new Sample( - "full_name", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 5, - null, - 1633950672000L)); - - assertThat( - MetricAdapter.toSamples( - "full_name", - MetricDataType.DOUBLE_GAUGE, - ImmutableList.of( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, Attributes.empty(), 5), - ImmutableDoublePointData.create( - 1633939689000000000L, 1633943350000000000L, KP_VP_ATTR, 7)))) - .containsExactly( - new Sample( - "full_name", - Collections.emptyList(), - Collections.emptyList(), - 5, - null, - 1633950672000L), - new Sample( - "full_name", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 7, - null, - 1633943350000L)); - } - - @Test - void toSamples_SummaryPoints() { - assertThat( - MetricAdapter.toSamples("full_name", MetricDataType.SUMMARY, Collections.emptyList())) - .isEmpty(); - - assertThat( - MetricAdapter.toSamples( - "full_name", - MetricDataType.SUMMARY, - ImmutableList.of( - ImmutableSummaryPointData.create( - 1633939689000000000L, - 1633943350000000000L, - KP_VP_ATTR, - 9, - 18.3, - ImmutableList.of(ImmutableValueAtQuantile.create(0.9, 1.1)))))) - .containsExactly( - new Sample( - "full_name_count", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 9, - null, - 1633943350000L), - new Sample( - "full_name_sum", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 18.3, - null, - 1633943350000L), - new Sample( - "full_name", - ImmutableList.of("kp", "quantile"), - ImmutableList.of("vp", "0.9"), - 1.1, - null, - 1633943350000L)); - - assertThat( - MetricAdapter.toSamples( - "full_name", - MetricDataType.SUMMARY, - ImmutableList.of( - ImmutableSummaryPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.empty(), - 7, - 15.3, - Collections.emptyList()), - ImmutableSummaryPointData.create( - 1633939689000000000L, - 1633943350000000000L, - KP_VP_ATTR, - 9, - 18.3, - ImmutableList.of( - ImmutableValueAtQuantile.create(0.9, 1.1), - ImmutableValueAtQuantile.create(0.99, 12.3)))))) - .containsExactly( - new Sample( - "full_name_count", - Collections.emptyList(), - Collections.emptyList(), - 7, - null, - 1633950672000L), - new Sample( - "full_name_sum", - Collections.emptyList(), - Collections.emptyList(), - 15.3, - null, - 1633950672000L), - new Sample( - "full_name_count", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 9, - null, - 1633943350000L), - new Sample( - "full_name_sum", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 18.3, - null, - 1633943350000L), - new Sample( - "full_name", - ImmutableList.of("kp", "quantile"), - ImmutableList.of("vp", "0.9"), - 1.1, - null, - 1633943350000L), - new Sample( - "full_name", - ImmutableList.of("kp", "quantile"), - ImmutableList.of("vp", "0.99"), - 12.3, - null, - 1633943350000L)); - } - - @Test - void toSamples_HistogramPoints() { - assertThat( - MetricAdapter.toSamples("full_name", MetricDataType.HISTOGRAM, Collections.emptyList())) - .isEmpty(); - - java.util.List result = - MetricAdapter.toSamples( - "full_name", - MetricDataType.HISTOGRAM, - ImmutableList.of( - ImmutableHistogramPointData.create( - 1633939689000000000L, - 1633943350000000000L, - KP_VP_ATTR, - 18.3, - 0.0, - 0.0, - ImmutableList.of(1.0), - ImmutableList.of(4L, 9L), - ImmutableList.of( - ImmutableDoubleExemplarData.create( - Attributes.empty(), - /*recordTime=*/ 0, - SpanContext.create( - "00000000000000000000000000000004", - "0000000000000003", - TraceFlags.getDefault(), - TraceState.getDefault()), - /*value=*/ 0), - ImmutableDoubleExemplarData.create( - Attributes.empty(), - /*recordTime=*/ TimeUnit.MILLISECONDS.toNanos(2), - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - /*value=*/ 2))))); - assertThat(result) - .withRepresentation(new ExemplarFriendlyRepresentation()) - .containsExactly( - new Sample( - "full_name_count", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 13, - null, - 1633943350000L), - new Sample( - "full_name_sum", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 18.3, - null, - 1633943350000L), - new Sample( - "full_name_bucket", - ImmutableList.of("kp", "le"), - ImmutableList.of("vp", "1.0"), - 4, - new Exemplar( - 0d, - 0L, - "trace_id", - "00000000000000000000000000000004", - "span_id", - "0000000000000003"), - 1633943350000L), - new Sample( - "full_name_bucket", - ImmutableList.of("kp", "le"), - ImmutableList.of("vp", "+Inf"), - 13, - new Exemplar( - 2d, - 2L, - "trace_id", - "00000000000000000000000000000001", - "span_id", - "0000000000000002"), - 1633943350000L)); - } - - @Test - void toMetricFamilySamples() { - MetricData metricData = MONOTONIC_CUMULATIVE_DOUBLE_SUM; - assertThat(MetricAdapter.toMetricFamilySamples(metricData)) - .isEqualTo( - new MetricFamilySamples( - "instrument_name", - Collector.Type.COUNTER, - metricData.getDescription(), - ImmutableList.of( - new Sample( - "instrument_name", - ImmutableList.of("kp"), - ImmutableList.of("vp"), - 5, - null, - 1633950672000L)))); - } - - @Test - void serialize() { - assertThat( - serialize004( - MONOTONIC_CUMULATIVE_DOUBLE_SUM, - NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM, - MONOTONIC_DELTA_DOUBLE_SUM, - NON_MONOTONIC_DELTA_DOUBLE_SUM, - MONOTONIC_CUMULATIVE_LONG_SUM, - NON_MONOTONIC_CUMULATIVE_LONG_SUM, - MONOTONIC_DELTA_LONG_SUM, - NON_MONOTONIC_DELTA_LONG_SUM, - DOUBLE_GAUGE, - LONG_GAUGE, - SUMMARY, - HISTOGRAM)) - .isEqualTo( - "# HELP instrument_name_total description\n" - + "# TYPE instrument_name_total counter\n" - + "instrument_name_total{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name_total description\n" - + "# TYPE instrument_name_total counter\n" - + "instrument_name_total{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name gauge\n" - + "instrument_name{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name summary\n" - + "instrument_name_count{kp=\"vp\",} 5.0 1633950672000\n" - + "instrument_name_sum{kp=\"vp\",} 7.0 1633950672000\n" - + "instrument_name{kp=\"vp\",quantile=\"0.9\",} 0.1 1633950672000\n" - + "instrument_name{kp=\"vp\",quantile=\"0.99\",} 0.3 1633950672000\n" - + "# HELP instrument_name description\n" - + "# TYPE instrument_name histogram\n" - + "instrument_name_count{kp=\"vp\",} 2.0 1633950672000\n" - + "instrument_name_sum{kp=\"vp\",} 1.0 1633950672000\n" - + "instrument_name_bucket{kp=\"vp\",le=\"+Inf\",} 2.0 1633950672000\n"); - - assertThat( - serializeOpenMetrics( - MONOTONIC_CUMULATIVE_DOUBLE_SUM, - NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM, - MONOTONIC_DELTA_DOUBLE_SUM, - NON_MONOTONIC_DELTA_DOUBLE_SUM, - MONOTONIC_CUMULATIVE_LONG_SUM, - NON_MONOTONIC_CUMULATIVE_LONG_SUM, - MONOTONIC_DELTA_LONG_SUM, - NON_MONOTONIC_DELTA_LONG_SUM, - DOUBLE_GAUGE, - LONG_GAUGE, - SUMMARY, - HISTOGRAM)) - .isEqualTo( - "# TYPE instrument_name counter\n" - + "# HELP instrument_name description\n" - + "instrument_name_total{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name counter\n" - + "# HELP instrument_name description\n" - + "instrument_name_total{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{kp=\"vp\"} 5.0 1633950672.000\n" - + "# TYPE instrument_name summary\n" - + "# HELP instrument_name description\n" - + "instrument_name_count{kp=\"vp\"} 5.0 1633950672.000\n" - + "instrument_name_sum{kp=\"vp\"} 7.0 1633950672.000\n" - + "instrument_name{kp=\"vp\",quantile=\"0.9\"} 0.1 1633950672.000\n" - + "instrument_name{kp=\"vp\",quantile=\"0.99\"} 0.3 1633950672.000\n" - + "# TYPE instrument_name histogram\n" - + "# HELP instrument_name description\n" - + "instrument_name_count{kp=\"vp\"} 2.0 1633950672.000\n" - + "instrument_name_sum{kp=\"vp\"} 1.0 1633950672.000\n" - + "instrument_name_bucket{kp=\"vp\",le=\"+Inf\"} 2.0 1633950672.000 # {span_id=\"0000000000000002\",trace_id=\"00000000000000000000000000000001\"} 4.0 0.001\n" - + "# EOF\n"); - } - - private static String serialize004(MetricData... metrics) { - StringWriter writer = new StringWriter(); - try { - TextFormat.write004( - writer, - Collections.enumeration( - Arrays.stream(metrics) - .map(MetricAdapter::toMetricFamilySamples) - .collect(Collectors.toList()))); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - return writer.toString(); - } - - private static String serializeOpenMetrics(MetricData... metrics) { - StringWriter writer = new StringWriter(); - try { - TextFormat.writeOpenMetrics100( - writer, - Collections.enumeration( - Arrays.stream(metrics) - .map(MetricAdapter::toMetricFamilySamples) - .collect(Collectors.toList()))); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - return writer.toString(); - } - - /** - * Make pretty-printing error messages nice, as prometheus doesn't output exemplars in toString. - */ - private static class ExemplarFriendlyRepresentation extends StandardRepresentation { - @Override - public String fallbackToStringOf(Object object) { - if (object instanceof Exemplar) { - return exemplarToString((Exemplar) object); - } - if (object instanceof Sample) { - Sample sample = (Sample) object; - if (sample.exemplar != null) { - StringBuilder sb = new StringBuilder(sample.toString()); - sb.append(" Exemplar=").append(exemplarToString(sample.exemplar)); - return sb.toString(); - } - } - if (object != null) { - return super.fallbackToStringOf(object); - } - return "null"; - } - /** Convert an exemplar into a human readable string. */ - private static String exemplarToString(Exemplar exemplar) { - StringBuilder sb = new StringBuilder("Exemplar{ value="); - sb.append(exemplar.getValue()); - sb.append(", ts="); - sb.append(exemplar.getTimestampMs()); - sb.append(", labels="); - for (int idx = 0; idx < exemplar.getNumberOfLabels(); ++idx) { - sb.append(exemplar.getLabelName(idx)); - sb.append("="); - sb.append(exemplar.getLabelValue(idx)); - sb.append(" "); - } - sb.append("}"); - return sb.toString(); - } - } -} diff --git a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/PrometheusCollector.java b/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/PrometheusCollector.java deleted file mode 100644 index 8e6d953e6c4..00000000000 --- a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/PrometheusCollector.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.CollectionRegistration; -import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import io.prometheus.client.Collector; -import io.prometheus.client.CollectorRegistry; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.function.Supplier; - -/** - * A reader of OpenTelemetry metrics that exports into Prometheus as a Collector. - * - *

    Usage: sdkMeterProvider.registerMetricReader(PrometheusCollector.create()); - * - * @deprecated This class was intended to fill OpenTelemetry metrics into a Prometheus registry. - * Instead, use {@link PrometheusHttpServer} to expose OpenTelemetry metrics as a Prometheus - * HTTP endpoint. If you generate metrics with Micrometer in addition to OpenTelemetry, also use - * - * Micrometer OpenTelemetry Integration to export Micrometer metrics together. If your use - * case is not handled by these, please file an issue to let us know. - */ -@Deprecated -public final class PrometheusCollector implements MetricReader { - - private final Collector collector; - private volatile MetricProducer metricProducer = MetricProducer.noop(); - - PrometheusCollector() { - this.collector = new CollectorImpl(() -> getMetricProducer().collectAllMetrics()); - this.collector.register(); - } - - /** - * Returns a new {@link PrometheusCollector} to be registered with a {@link - * io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder}. - */ - public static PrometheusCollector create() { - return new PrometheusCollector(); - } - - private MetricProducer getMetricProducer() { - return metricProducer; - } - - @Override - public void register(CollectionRegistration registration) { - this.metricProducer = MetricProducer.asMetricProducer(registration); - } - - @Override - public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return AggregationTemporality.CUMULATIVE; - } - - // Prometheus cannot flush. - @Override - public CompletableResultCode forceFlush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - CollectorRegistry.defaultRegistry.unregister(collector); - return CompletableResultCode.ofSuccess(); - } - - private static class CollectorImpl extends Collector { - - private final Supplier> metricSupplier; - - private CollectorImpl(Supplier> metricSupplier) { - this.metricSupplier = metricSupplier; - } - - @Override - public List collect() { - Collection allMetrics = metricSupplier.get(); - List allSamples = new ArrayList<>(allMetrics.size()); - for (MetricData metricData : allMetrics) { - allSamples.add(MetricAdapter.toMetricFamilySamples(metricData)); - } - return Collections.unmodifiableList(allSamples); - } - } -} diff --git a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/PrometheusCollectorTest.java b/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/PrometheusCollectorTest.java deleted file mode 100644 index 0284555bdf9..00000000000 --- a/exporters/prometheus/src/integrationTest/java/io/opentelemetry/exporter/prometheus/PrometheusCollectorTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.mockito.Mockito.when; - -import com.google.common.collect.ImmutableList; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import io.opentelemetry.sdk.resources.Resource; -import io.prometheus.client.CollectorRegistry; -import io.prometheus.client.exporter.common.TextFormat; -import java.io.IOException; -import java.io.StringWriter; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -// Tests deprecated class -@SuppressWarnings("deprecation") -class PrometheusCollectorTest { - @Mock MetricProducer metricProducer; - PrometheusCollector prometheusCollector; - - @BeforeEach - void setUp() { - // Apply the SDK metric producer registers with prometheus. - prometheusCollector = new PrometheusCollector(); - prometheusCollector.register(metricProducer); - } - - @Test - void registerWithSdkMeterProvider() { - assertThatCode( - () -> - SdkMeterProvider.builder() - .registerMetricReader(PrometheusCollector.create()) - .build() - .forceFlush() - .join(10, TimeUnit.SECONDS)) - .doesNotThrowAnyException(); - } - - @Test - void registerToDefault() throws IOException { - when(metricProducer.collectAllMetrics()).thenReturn(generateTestData()); - StringWriter stringWriter = new StringWriter(); - TextFormat.write004(stringWriter, CollectorRegistry.defaultRegistry.metricFamilySamples()); - assertThat(stringWriter.toString()) - .isEqualTo( - "# HELP grpc_name_total long_description\n" - + "# TYPE grpc_name_total counter\n" - + "grpc_name_total{kp=\"vp\",} 5.0 1633950672000\n" - + "# HELP http_name_total double_description\n" - + "# TYPE http_name_total counter\n" - + "http_name_total{kp=\"vp\",} 3.5 1633950672000\n"); - } - - private static ImmutableList generateTestData() { - return ImmutableList.of( - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("grpc", "version", null), - "grpc.name", - "long_description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(stringKey("kp"), "vp"), - 5)))), - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("http", "version", null), - "http.name", - "double_description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(stringKey("kp"), "vp"), - 3.5))))); - } -} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/NameSanitizer.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/NameSanitizer.java deleted file mode 100644 index 40465d30b07..00000000000 --- a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/NameSanitizer.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.Function; -import java.util.regex.Pattern; - -/** Sanitizes a metric or label name. */ -class NameSanitizer implements Function { - - static final NameSanitizer INSTANCE = new NameSanitizer(); - - private static final Pattern SANITIZE_PREFIX_PATTERN = Pattern.compile("^[^a-zA-Z_:]"); - private static final Pattern SANITIZE_BODY_PATTERN = Pattern.compile("[^a-zA-Z0-9_:]"); - - private final Function delegate; - private final Map cache = new ConcurrentHashMap<>(); - - NameSanitizer() { - this(NameSanitizer::sanitizeMetricName); - } - - // visible for testing - NameSanitizer(Function delegate) { - this.delegate = delegate; - } - - @Override - public String apply(String labelName) { - return cache.computeIfAbsent(labelName, delegate); - } - - private static String sanitizeMetricName(String metricName) { - return SANITIZE_BODY_PATTERN - .matcher(SANITIZE_PREFIX_PATTERN.matcher(metricName).replaceFirst("_")) - .replaceAll("_"); - } -} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java new file mode 100644 index 00000000000..79af0e49fce --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverter.java @@ -0,0 +1,1094 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.AttributeType; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.HistogramData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.SumData; +import io.opentelemetry.sdk.metrics.data.SummaryPointData; +import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; +import io.opentelemetry.sdk.resources.Resource; +import io.prometheus.metrics.model.snapshots.ClassicHistogramBuckets; +import io.prometheus.metrics.model.snapshots.CounterSnapshot; +import io.prometheus.metrics.model.snapshots.CounterSnapshot.CounterDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.Exemplar; +import io.prometheus.metrics.model.snapshots.Exemplars; +import io.prometheus.metrics.model.snapshots.GaugeSnapshot; +import io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.HistogramSnapshot; +import io.prometheus.metrics.model.snapshots.HistogramSnapshot.HistogramDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.InfoSnapshot; +import io.prometheus.metrics.model.snapshots.InfoSnapshot.InfoDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.Labels; +import io.prometheus.metrics.model.snapshots.MetricMetadata; +import io.prometheus.metrics.model.snapshots.MetricSnapshot; +import io.prometheus.metrics.model.snapshots.MetricSnapshots; +import io.prometheus.metrics.model.snapshots.NativeHistogramBuckets; +import io.prometheus.metrics.model.snapshots.Quantile; +import io.prometheus.metrics.model.snapshots.Quantiles; +import io.prometheus.metrics.model.snapshots.SummarySnapshot; +import io.prometheus.metrics.model.snapshots.SummarySnapshot.SummaryDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.Unit; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.StringJoiner; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; +import javax.annotation.Nullable; + +/** Convert OpenTelemetry {@link MetricData} to Prometheus {@link MetricSnapshots}. */ +final class Otel2PrometheusConverter { + + private static final Logger LOGGER = Logger.getLogger(Otel2PrometheusConverter.class.getName()); + private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(LOGGER); + // Prometheus limits the total UTF-8 character count across all exemplar label names and values + // to 128. See https://github.com/open-telemetry/opentelemetry-java/issues/6770 + private static final int EXEMPLAR_MAX_LABEL_SET_LENGTH = 128; + private static final String OTEL_SCOPE_NAME = "otel_scope_name"; + private static final String OTEL_SCOPE_VERSION = "otel_scope_version"; + private static final String OTEL_SCOPE_SCHEMA_URL = "otel_scope_schema_url"; + private static final String OTEL_SCOPE_ATTRIBUTE_PREFIX = "otel_scope_"; + private static final long NANOS_PER_MILLISECOND = TimeUnit.MILLISECONDS.toNanos(1); + static final int MAX_CACHE_SIZE = 10; + + private final boolean otelScopeLabelsEnabled; + private final boolean targetInfoMetricEnabled; + private final TranslationStrategy translationStrategy; + @Nullable private final Predicate allowedResourceAttributesFilter; + + /** + * Used only if addResourceAttributesAsLabels is true. Once the cache reaches {@link + * #MAX_CACHE_SIZE}, it is cleared to protect against unbounded conversion over time. + */ + private final Map>> resourceAttributesToAllowedKeysCache; + + /** + * Constructor with feature flag parameters. + * + * @param otelScopeLabelsEnabled whether to add OpenTelemetry scope labels to exported metrics + * @param targetInfoMetricEnabled whether to export the target_info metric with resource + * attributes + * @param allowedResourceAttributesFilter if not {@code null}, resource attributes with keys + * matching this predicate will be added as labels on each exported metric + */ + Otel2PrometheusConverter( + boolean otelScopeLabelsEnabled, + boolean targetInfoMetricEnabled, + TranslationStrategy translationStrategy, + @Nullable Predicate allowedResourceAttributesFilter) { + this.otelScopeLabelsEnabled = otelScopeLabelsEnabled; + this.targetInfoMetricEnabled = targetInfoMetricEnabled; + this.translationStrategy = translationStrategy; + this.allowedResourceAttributesFilter = allowedResourceAttributesFilter; + this.resourceAttributesToAllowedKeysCache = + allowedResourceAttributesFilter != null + ? new ConcurrentHashMap<>() + : Collections.emptyMap(); + } + + boolean isOtelScopeLabelsEnabled() { + return otelScopeLabelsEnabled; + } + + boolean isTargetInfoMetricEnabled() { + return targetInfoMetricEnabled; + } + + TranslationStrategy getTranslationStrategy() { + return translationStrategy; + } + + @Nullable + Predicate getAllowedResourceAttributesFilter() { + return allowedResourceAttributesFilter; + } + + MetricSnapshots convert(@Nullable Collection metricDataCollection) { + if (metricDataCollection == null || metricDataCollection.isEmpty()) { + return MetricSnapshots.of(); + } + Map snapshotsByName = new HashMap<>(metricDataCollection.size()); + Resource resource = null; + for (MetricData metricData : metricDataCollection) { + MetricSnapshot snapshot = convert(metricData); + if (snapshot == null) { + continue; + } + putOrMerge(snapshotsByName, snapshot); + if (resource == null) { + resource = metricData.getResource(); + } + } + if (resource != null && targetInfoMetricEnabled) { + putOrMerge(snapshotsByName, makeTargetInfo(resource)); + } + return new MetricSnapshots(snapshotsByName.values()); + } + + @Nullable + private MetricSnapshot convert(MetricData metricData) { + try { + return doConvert(metricData); + } catch (IllegalArgumentException e) { + throttlingLogger.log( + Level.WARNING, + "Failed to convert metric " + metricData.getName() + ". Dropping metric.", + e); + return null; + } + } + + @Nullable + private MetricSnapshot doConvert(MetricData metricData) { + // Note that AggregationTemporality.DELTA should never happen + // because PrometheusMetricReader#getAggregationTemporality returns CUMULATIVE. + + boolean isCounter = isMonotonicSum(metricData); + MetricMetadata metadata = convertMetadata(metricData, isCounter); + InstrumentationScopeInfo scope = metricData.getInstrumentationScopeInfo(); + switch (metricData.getType()) { + case LONG_GAUGE: + return convertLongGauge( + metadata, scope, metricData.getLongGaugeData().getPoints(), metricData.getResource()); + case DOUBLE_GAUGE: + return convertDoubleGauge( + metadata, scope, metricData.getDoubleGaugeData().getPoints(), metricData.getResource()); + case LONG_SUM: + SumData longSumData = metricData.getLongSumData(); + if (longSumData.getAggregationTemporality() == AggregationTemporality.DELTA) { + return null; + } else if (longSumData.isMonotonic()) { + return convertLongCounter( + metadata, scope, longSumData.getPoints(), metricData.getResource()); + } else { + return convertLongGauge( + metadata, scope, longSumData.getPoints(), metricData.getResource()); + } + case DOUBLE_SUM: + SumData doubleSumData = metricData.getDoubleSumData(); + if (doubleSumData.getAggregationTemporality() == AggregationTemporality.DELTA) { + return null; + } else if (doubleSumData.isMonotonic()) { + return convertDoubleCounter( + metadata, scope, doubleSumData.getPoints(), metricData.getResource()); + } else { + return convertDoubleGauge( + metadata, scope, doubleSumData.getPoints(), metricData.getResource()); + } + case HISTOGRAM: + HistogramData histogramData = metricData.getHistogramData(); + if (histogramData.getAggregationTemporality() == AggregationTemporality.DELTA) { + return null; + } else { + return convertHistogram( + metadata, scope, histogramData.getPoints(), metricData.getResource()); + } + case EXPONENTIAL_HISTOGRAM: + ExponentialHistogramData exponentialHistogramData = + metricData.getExponentialHistogramData(); + if (exponentialHistogramData.getAggregationTemporality() == AggregationTemporality.DELTA) { + return null; + } else { + return convertExponentialHistogram( + metadata, scope, exponentialHistogramData.getPoints(), metricData.getResource()); + } + case SUMMARY: + return convertSummary( + metadata, scope, metricData.getSummaryData().getPoints(), metricData.getResource()); + } + return null; + } + + private static boolean isMonotonicSum(MetricData metricData) { + switch (metricData.getType()) { + case LONG_SUM: + return metricData.getLongSumData().isMonotonic(); + case DOUBLE_SUM: + return metricData.getDoubleSumData().isMonotonic(); + default: + return false; + } + } + + private GaugeSnapshot convertLongGauge( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (LongPointData longData : dataPoints) { + data.add( + new GaugeDataPointSnapshot( + (double) longData.getValue(), + convertAttributes(resource, scope, longData.getAttributes()), + convertLongExemplar(longData.getExemplars()))); + } + return new GaugeSnapshot(metadata, data); + } + + private CounterSnapshot convertLongCounter( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (LongPointData longData : dataPoints) { + data.add( + new CounterDataPointSnapshot( + (double) longData.getValue(), + convertAttributes(resource, scope, longData.getAttributes()), + convertLongExemplar(longData.getExemplars()), + longData.getStartEpochNanos() / NANOS_PER_MILLISECOND)); + } + return new CounterSnapshot(metadata, data); + } + + private GaugeSnapshot convertDoubleGauge( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (DoublePointData doubleData : dataPoints) { + data.add( + new GaugeDataPointSnapshot( + doubleData.getValue(), + convertAttributes(resource, scope, doubleData.getAttributes()), + convertDoubleExemplar(doubleData.getExemplars()))); + } + return new GaugeSnapshot(metadata, data); + } + + private CounterSnapshot convertDoubleCounter( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (DoublePointData doubleData : dataPoints) { + data.add( + new CounterDataPointSnapshot( + doubleData.getValue(), + convertAttributes(resource, scope, doubleData.getAttributes()), + convertDoubleExemplar(doubleData.getExemplars()), + doubleData.getStartEpochNanos() / NANOS_PER_MILLISECOND)); + } + return new CounterSnapshot(metadata, data); + } + + private HistogramSnapshot convertHistogram( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (HistogramPointData histogramData : dataPoints) { + List boundaries = new ArrayList<>(histogramData.getBoundaries().size() + 1); + boundaries.addAll(histogramData.getBoundaries()); + boundaries.add(Double.POSITIVE_INFINITY); + data.add( + new HistogramDataPointSnapshot( + ClassicHistogramBuckets.of(boundaries, histogramData.getCounts()), + histogramData.getSum(), + convertAttributes(resource, scope, histogramData.getAttributes()), + convertDoubleExemplars(histogramData.getExemplars()), + histogramData.getStartEpochNanos() / NANOS_PER_MILLISECOND)); + } + return new HistogramSnapshot(metadata, data); + } + + @Nullable + private HistogramSnapshot convertExponentialHistogram( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (ExponentialHistogramPointData histogramData : dataPoints) { + int scale = histogramData.getScale(); + if (scale < -4) { + throttlingLogger.log( + Level.WARNING, + "Dropping histogram " + + metadata.getName() + + " with attributes " + + histogramData.getAttributes() + + " because it has scale < -4 which is unsupported in Prometheus"); + return null; + } + // Scale > 8 are not supported in Prometheus. Histograms with scale > 8 are scaled down to 8. + int scaleDown = scale > 8 ? scale - 8 : 0; + data.add( + new HistogramDataPointSnapshot( + scale - scaleDown, + histogramData.getZeroCount(), + 0L, + convertExponentialHistogramBuckets(histogramData.getPositiveBuckets(), scaleDown), + convertExponentialHistogramBuckets(histogramData.getNegativeBuckets(), scaleDown), + histogramData.getSum(), + convertAttributes(resource, scope, histogramData.getAttributes()), + convertDoubleExemplars(histogramData.getExemplars()), + histogramData.getStartEpochNanos() / NANOS_PER_MILLISECOND)); + } + return new HistogramSnapshot(metadata, data); + } + + private static NativeHistogramBuckets convertExponentialHistogramBuckets( + ExponentialHistogramBuckets buckets, int scaleDown) { + if (buckets.getBucketCounts().isEmpty()) { + return NativeHistogramBuckets.EMPTY; + } + List otelCounts = buckets.getBucketCounts(); + List indexes = new ArrayList<>(otelCounts.size()); + List counts = new ArrayList<>(otelCounts.size()); + int previousIndex = (buckets.getOffset() >> scaleDown) + 1; + long count = 0; + for (int i = 0; i < otelCounts.size(); i++) { + int index = ((buckets.getOffset() + i) >> scaleDown) + 1; + if (index > previousIndex) { + indexes.add(previousIndex); + counts.add(count); + previousIndex = index; + count = 0; + } + count += otelCounts.get(i); + } + indexes.add(previousIndex); + counts.add(count); + return NativeHistogramBuckets.of(indexes, counts); + } + + private SummarySnapshot convertSummary( + MetricMetadata metadata, + InstrumentationScopeInfo scope, + Collection dataPoints, + Resource resource) { + List data = new ArrayList<>(dataPoints.size()); + for (SummaryPointData summaryData : dataPoints) { + data.add( + new SummaryDataPointSnapshot( + summaryData.getCount(), + summaryData.getSum(), + convertQuantiles(summaryData.getValues()), + convertAttributes(resource, scope, summaryData.getAttributes()), + Exemplars.EMPTY, // Exemplars for Summaries not implemented yet. + summaryData.getStartEpochNanos() / NANOS_PER_MILLISECOND)); + } + return new SummarySnapshot(metadata, data); + } + + private static Quantiles convertQuantiles(List values) { + List result = new ArrayList<>(values.size()); + for (ValueAtQuantile value : values) { + result.add(new Quantile(value.getQuantile(), value.getValue())); + } + return Quantiles.of(result); + } + + @Nullable + private Exemplar convertLongExemplar(List exemplars) { + if (exemplars.isEmpty()) { + return null; + } else { + LongExemplarData exemplar = exemplars.get(0); + return convertExemplar((double) exemplar.getValue(), exemplar); + } + } + + /** Converts the first exemplar in the list if available, else returns {#code null}. */ + @Nullable + private Exemplar convertDoubleExemplar(List exemplars) { + if (exemplars.isEmpty()) { + return null; + } else { + DoubleExemplarData exemplar = exemplars.get(0); + return convertExemplar(exemplar.getValue(), exemplar); + } + } + + /** Converts the first exemplar in the list if available, else returns {#code null}. */ + private Exemplars convertDoubleExemplars(List exemplars) { + List result = new ArrayList<>(exemplars.size()); + for (DoubleExemplarData exemplar : exemplars) { + result.add(convertExemplar(exemplar.getValue(), exemplar)); + } + return Exemplars.of(result); + } + + private Exemplar convertExemplar(double value, ExemplarData exemplar) { + SpanContext spanContext = exemplar.getSpanContext(); + if (spanContext.isValid()) { + Labels labels = + convertAttributes( + null, // resource attributes are only copied for point's attributes + null, // scope attributes are only needed for point's attributes + exemplar.getFilteredAttributes(), + "trace_id", + spanContext.getTraceId(), + "span_id", + spanContext.getSpanId()); + if (labelSetLength(labels) > EXEMPLAR_MAX_LABEL_SET_LENGTH) { + // Drop filtered attributes to stay within Prometheus 128-char exemplar label limit, + // keeping trace_id and span_id which are the most valuable for correlation. + throttlingLogger.log( + Level.WARNING, + "Exemplar attributes exceeded Prometheus limit of " + + EXEMPLAR_MAX_LABEL_SET_LENGTH + + " UTF-8 characters; dropping filtered attributes."); + labels = + convertAttributes( + null, // resource attributes are only copied for point's attributes + null, // scope attributes are only needed for point's attributes + Attributes.empty(), + "trace_id", + spanContext.getTraceId(), + "span_id", + spanContext.getSpanId()); + } + return new Exemplar(value, labels, exemplar.getEpochNanos() / NANOS_PER_MILLISECOND); + } else { + Labels labels = + convertAttributes( + null, // resource attributes are only copied for point's attributes + null, // scope attributes are only needed for point's attributes + exemplar.getFilteredAttributes()); + if (labelSetLength(labels) > EXEMPLAR_MAX_LABEL_SET_LENGTH) { + throttlingLogger.log( + Level.WARNING, + "Exemplar attributes exceeded Prometheus limit of " + + EXEMPLAR_MAX_LABEL_SET_LENGTH + + " UTF-8 characters; dropping filtered attributes."); + labels = Labels.EMPTY; + } + return new Exemplar(value, labels, exemplar.getEpochNanos() / NANOS_PER_MILLISECOND); + } + } + + private static int labelSetLength(Labels labels) { + int length = 0; + for (int i = 0; i < labels.size(); i++) { + length += + labels.getName(i).codePointCount(0, labels.getName(i).length()) + + labels.getValue(i).codePointCount(0, labels.getValue(i).length()); + } + return length; + } + + private InfoSnapshot makeTargetInfo(Resource resource) { + return new InfoSnapshot( + MetricMetadata.builder().name("target").build(), + Collections.singletonList( + new InfoDataPointSnapshot( + convertAttributes( + null, // resource attributes are only copied for point's attributes + null, // scope attributes are only needed for point's attributes + resource.getAttributes())))); + } + + /** + * Convert OpenTelemetry attributes to Prometheus labels. + * + * @param resource optional resource (attributes) to be converted. + * @param scope will be converted to {@code otel_scope_*} labels. + * @param attributes the attributes to be converted. + * @param additionalAttributes optional list of key/value pairs, may be empty. + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + private Labels convertAttributes( + @Nullable Resource resource, + @Nullable InstrumentationScopeInfo scope, + Attributes attributes, + String... additionalAttributes) { + + List> allowedAttributeKeys = + allowedResourceAttributesFilter != null + ? filterAllowedResourceAttributeKeys(resource) + : Collections.emptyList(); + + Map labelNameToValue = buildAttributeLabels(attributes); + + // Additional attributes (exemplar trace_id and span_id) take precedence over attributes. + for (int i = 0; i < additionalAttributes.length; i += 2) { + labelNameToValue.put(requireNonNull(additionalAttributes[i]), additionalAttributes[i + 1]); + } + + if (scope != null && otelScopeLabelsEnabled) { + labelNameToValue.putIfAbsent(OTEL_SCOPE_NAME, scope.getName()); + if (scope.getVersion() != null) { + labelNameToValue.putIfAbsent(OTEL_SCOPE_VERSION, scope.getVersion()); + } + String schemaUrl = scope.getSchemaUrl(); + if (schemaUrl != null) { + labelNameToValue.putIfAbsent(OTEL_SCOPE_SCHEMA_URL, schemaUrl); + } + scope + .getAttributes() + .forEach((key, value) -> + labelNameToValue.putIfAbsent( + OTEL_SCOPE_ATTRIBUTE_PREFIX + key.getKey(), toLabelValue(key.getType(), value))); + } + + if (resource != null) { + addResourceAttributeLabels(labelNameToValue, resource.getAttributes(), allowedAttributeKeys); + } + + String[] names = new String[labelNameToValue.size()]; + String[] values = new String[labelNameToValue.size()]; + int[] pos = new int[] {0}; + labelNameToValue.forEach((name, value) -> { + names[pos[0]] = name; + values[pos[0]] = value; + pos[0] += 1; + }); + + return Labels.of(names, values); + } + + /** + * Builds a label map from metric attributes. + * + *

    In the common (no-collision) case, inserts directly with no extra allocation. When + * normalization maps two attribute keys to the same label name, their values are joined with ";" + * in lexicographic order of the original key names. + */ + private Map buildAttributeLabels(Attributes attributes) { + Map labels = new LinkedHashMap<>(); + if (!shouldEscape(translationStrategy)) { + attributes.forEach((key, value) -> + labels.put(convertLabelName(key.getKey()), toLabelValue(key.getType(), value))); + return labels; + } + + // Fast path: insert directly. Stop inserting on first detected collision but finish + // iterating so forEach can complete. + boolean[] hasCollision = {false}; + attributes.forEach((key, value) -> { + if (hasCollision[0]) { + return; + } + String labelName = convertLabelName(key.getKey()); + if (labels.containsKey(labelName)) { + hasCollision[0] = true; + } else { + labels.put(labelName, toLabelValue(key.getType(), value)); + } + }); + + if (!hasCollision[0]) { + return labels; // common case: done, no extra allocation + } + + // Collision path: discard partial state and rebuild with merged values. + labels.clear(); + Map> groups = new LinkedHashMap<>(); + attributes.forEach((key, value) -> + groups + .computeIfAbsent(convertLabelName(key.getKey()), ignored -> new ArrayList<>()) + .add(new OriginalLabelKeyValue(key.getKey(), toLabelValue(key.getType(), value)))); + groups.forEach((labelName, entries) -> labels.put(labelName, mergeValues(entries))); + return labels; + } + + /** + * Adds resource attribute labels into dest using putIfAbsent, so metric attributes take + * precedence. When normalization maps two resource attribute keys to the same label name, their + * values are joined with ";" in lexicographic order of the original key names. + */ + private void addResourceAttributeLabels( + Map dest, + Attributes resourceAttributes, + List> allowedAttributeKeys) { + if (allowedAttributeKeys.isEmpty()) { + return; + } + + if (!shouldEscape(translationStrategy)) { + for (AttributeKey attributeKey : allowedAttributeKeys) { + Object attributeValue = resourceAttributes.get(attributeKey); + if (attributeValue != null) { + dest.putIfAbsent( + convertLabelName(attributeKey.getKey()), + toLabelValue(attributeKey.getType(), attributeValue)); + } + } + return; + } + + // Fast path: build resource labels into a temp map to detect within-source collisions + // before applying them to dest with putIfAbsent. + Map resourceLabels = new LinkedHashMap<>(); + boolean hasCollision = false; + for (AttributeKey attributeKey : allowedAttributeKeys) { + Object attributeValue = resourceAttributes.get(attributeKey); + if (attributeValue != null) { + String labelName = convertLabelName(attributeKey.getKey()); + if (resourceLabels.containsKey(labelName)) { + hasCollision = true; + break; + } + resourceLabels.put(labelName, toLabelValue(attributeKey.getType(), attributeValue)); + } + } + + if (!hasCollision) { + resourceLabels.forEach(dest::putIfAbsent); + return; + } + + // Collision path: rebuild with merged values. + Map> groups = new LinkedHashMap<>(); + for (AttributeKey attributeKey : allowedAttributeKeys) { + Object attributeValue = resourceAttributes.get(attributeKey); + if (attributeValue != null) { + groups + .computeIfAbsent(convertLabelName(attributeKey.getKey()), ignored -> new ArrayList<>()) + .add( + new OriginalLabelKeyValue( + attributeKey.getKey(), toLabelValue(attributeKey.getType(), attributeValue))); + } + } + groups.forEach((labelName, entries) -> dest.putIfAbsent(labelName, mergeValues(entries))); + } + + /** Sorts entries by original key name and joins their values with ";". */ + private static String mergeValues(List entries) { + entries.sort(Comparator.comparing(OriginalLabelKeyValue::originalKey)); + return entries.stream().map(OriginalLabelKeyValue::value).collect(Collectors.joining(";")); + } + + private List> filterAllowedResourceAttributeKeys(@Nullable Resource resource) { + requireNonNull( + allowedResourceAttributesFilter, + "This method should only be called when allowedResourceAttributesFilter is not null."); + if (resource == null) { + return Collections.emptyList(); + } + + List> allowedAttributeKeys = + resourceAttributesToAllowedKeysCache.computeIfAbsent( + resource.getAttributes(), + resourceAttributes -> + resourceAttributes.asMap().keySet().stream() + .filter(o -> allowedResourceAttributesFilter.test(o.getKey())) + .collect(Collectors.toList())); + + if (resourceAttributesToAllowedKeysCache.size() > MAX_CACHE_SIZE) { + resourceAttributesToAllowedKeysCache.clear(); + } + return allowedAttributeKeys; + } + + private String convertLabelName(String key) { + if (shouldEscape(translationStrategy)) { + return convertLegacyLabelName(key); + } + return key; + } + + /** + * Normalize an attribute name to the legacy Prometheus label scheme. + * + *

    This mirrors {@code prometheus/otlptranslator}'s invalid-character collapsing rules, but we + * intentionally do not preserve {@code __...__} names because Prometheus Java rejects user label + * names that begin with {@code __}. + */ + private static String convertLegacyLabelName(String key) { + if (key.isEmpty()) { + throw new IllegalArgumentException("label name is empty"); + } + + // OTel owns OTLP-to-Prometheus translation. Prometheus Java validates and serializes names, + // but no longer owns this naming mangling. The OTel compatibility spec requires invalid + // attribute-name characters and repeated underscores to collapse to a single "_". Prometheus + // label names beginning with "__" are reserved for internal labels like "__name__" and + // scrape/relabel labels, and Prometheus Java rejects them as user labels, so do not preserve + // "__...__" reserved-looking names here. + StringBuilder result = new StringBuilder(key.length()); + boolean previousWasUnderscore = false; + for (int i = 0; i < key.length(); ) { + int codePoint = key.codePointAt(i); + if (isValidLegacyLabelChar(codePoint)) { + result.appendCodePoint(codePoint); + previousWasUnderscore = false; + } else if (!previousWasUnderscore) { + result.append('_'); + previousWasUnderscore = true; + } + i += Character.charCount(codePoint); + } + + String normalized = result.toString(); + if (Character.isDigit(normalized.charAt(0))) { + normalized = "key_" + normalized; + } + if (containsOnlyUnderscores(normalized)) { + throw new IllegalArgumentException( + "normalization for label name \"" + + key + + "\" resulted in invalid name \"" + + normalized + + "\""); + } + return normalized; + } + + private static boolean isValidLegacyLabelChar(int codePoint) { + return (codePoint >= 'a' && codePoint <= 'z') + || (codePoint >= 'A' && codePoint <= 'Z') + || (codePoint >= '0' && codePoint <= '9'); + } + + private static boolean containsOnlyUnderscores(String value) { + for (int i = 0; i < value.length(); i++) { + if (value.charAt(i) != '_') { + return false; + } + } + return true; + } + + private static String convertLegacyMetricName(String name) { + if (name.isEmpty()) { + throw new IllegalArgumentException("metric name is empty"); + } + + StringBuilder result = new StringBuilder(name.length()); + boolean previousWasUnderscore = false; + for (int i = 0; i < name.length(); ) { + int codePoint = name.codePointAt(i); + if (isValidLegacyMetricChar(codePoint, i) && codePoint != '_') { + result.appendCodePoint(codePoint); + previousWasUnderscore = false; + } else if (!previousWasUnderscore) { + result.append('_'); + previousWasUnderscore = true; + } + i += Character.charCount(codePoint); + } + return result.toString(); + } + + private static boolean isValidLegacyMetricChar(int codePoint, int index) { + return (codePoint >= 'a' && codePoint <= 'z') + || (codePoint >= 'A' && codePoint <= 'Z') + || codePoint == '_' + || codePoint == ':' + || (codePoint >= '0' && codePoint <= '9' && index > 0); + } + + private MetricMetadata convertMetadata(MetricData metricData, boolean isCounter) { + switch (translationStrategy) { + case UNDERSCORE_ESCAPING_WITH_SUFFIXES: + return convertMetadataEscapedWithSuffixes(metricData); + case UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES: + return convertMetadataEscapedWithoutSuffixes(metricData); + case NO_UTF8_ESCAPING_WITH_SUFFIXES: + return convertMetadataUtf8WithSuffixes(metricData, isCounter); + case NO_TRANSLATION: + return convertMetadataNoTranslation(metricData); + } + throw new IllegalStateException("Unknown strategy: " + translationStrategy); + } + + private static MetricMetadata convertMetadataEscapedWithSuffixes(MetricData metricData) { + String originalName = metricData.getName(); + String name = stripReservedMetricSuffixes(convertLegacyMetricName(originalName)); + String help = metricData.getDescription(); + Unit unit = PrometheusUnitsHelper.convertUnit(metricData.getUnit()); + if (unit != null && !name.endsWith(unit.toString())) { + name = name + "_" + unit; + } + validateNormalizedMetricName(originalName, name); + return MetricMetadata.builder().name(name).help(help).unit(unit).build(); + } + + private static MetricMetadata convertMetadataEscapedWithoutSuffixes(MetricData metricData) { + String originalName = metricData.getName(); + String name = stripReservedMetricSuffixes(convertLegacyMetricName(originalName)); + String help = metricData.getDescription(); + validateNormalizedMetricName(originalName, name); + return MetricMetadata.builder().name(name).help(help).build(); + } + + private static MetricMetadata convertMetadataUtf8WithSuffixes( + MetricData metricData, boolean isCounter) { + String name = metricData.getName(); + String help = metricData.getDescription(); + Unit unit = PrometheusUnitsHelper.convertUnit(metricData.getUnit()); + if (unit != null && !name.endsWith(unit.toString())) { + name = name + "_" + unit; + } + return MetricMetadata.builder() + .name(stripReservedMetricSuffixes(name)) + .help(help) + .unit(unit) + .counterSuffix(isCounter) + .build(); + } + + private static MetricMetadata convertMetadataNoTranslation(MetricData metricData) { + String name = stripReservedMetricSuffixes(metricData.getName()); + String help = metricData.getDescription(); + return MetricMetadata.builder().name(name).help(help).build(); + } + + private static String stripReservedMetricSuffixes(String name) { + boolean modified = true; + while (modified) { + modified = false; + for (String suffix : PrometheusUnitsHelper.RESERVED_SUFFIXES) { + if (name.equals(suffix)) { + return name.substring(1); + } + if (name.endsWith(suffix)) { + name = name.substring(0, name.length() - suffix.length()); + modified = true; + } + } + } + return name; + } + + private void putOrMerge(Map snapshotsByName, MetricSnapshot snapshot) { + MetricMetadata metadata = snapshot.getMetadata(); + String name = + shouldEscape(translationStrategy) ? metadata.getPrometheusName() : metadata.getName(); + if (snapshotsByName.containsKey(name)) { + MetricSnapshot merged = merge(snapshotsByName.get(name), snapshot); + if (merged != null) { + snapshotsByName.put(name, merged); + } + } else { + snapshotsByName.put(name, snapshot); + } + } + + private static boolean shouldEscape(TranslationStrategy translationStrategy) { + return translationStrategy == TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES + || translationStrategy == TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES; + } + + private static void validateNormalizedMetricName(String originalName, String normalizedName) { + if (normalizedName.isEmpty()) { + throw new IllegalArgumentException( + "normalization for metric \"" + originalName + "\" resulted in empty name"); + } + if (containsOnlyUnderscores(normalizedName)) { + throw new IllegalArgumentException( + "normalization for metric \"" + + originalName + + "\" resulted in invalid name \"" + + normalizedName + + "\""); + } + } + + /** + * OpenTelemetry may use the same metric name multiple times but in different instrumentation + * scopes. In that case, we try to merge the metrics. They will have different {@code + * otel_scope_name} attributes. However, merging is only possible if the metrics have the same + * type. If the type differs, we log a message and drop one of them. + */ + @Nullable + private MetricSnapshot merge(MetricSnapshot a, MetricSnapshot b) { + MetricMetadata metadata = mergeMetadata(a.getMetadata(), b.getMetadata()); + if (metadata == null) { + return null; + } + int numberOfDataPoints = a.getDataPoints().size() + b.getDataPoints().size(); + if (a instanceof GaugeSnapshot && b instanceof GaugeSnapshot) { + List dataPoints = new ArrayList<>(numberOfDataPoints); + dataPoints.addAll(((GaugeSnapshot) a).getDataPoints()); + dataPoints.addAll(((GaugeSnapshot) b).getDataPoints()); + return new GaugeSnapshot(metadata, dataPoints); + } else if (a instanceof CounterSnapshot && b instanceof CounterSnapshot) { + List dataPoints = new ArrayList<>(numberOfDataPoints); + dataPoints.addAll(((CounterSnapshot) a).getDataPoints()); + dataPoints.addAll(((CounterSnapshot) b).getDataPoints()); + return new CounterSnapshot(metadata, dataPoints); + } else if (a instanceof HistogramSnapshot && b instanceof HistogramSnapshot) { + List dataPoints = new ArrayList<>(numberOfDataPoints); + dataPoints.addAll(((HistogramSnapshot) a).getDataPoints()); + dataPoints.addAll(((HistogramSnapshot) b).getDataPoints()); + return new HistogramSnapshot(metadata, dataPoints); + } else if (a instanceof SummarySnapshot && b instanceof SummarySnapshot) { + List dataPoints = new ArrayList<>(numberOfDataPoints); + dataPoints.addAll(((SummarySnapshot) a).getDataPoints()); + dataPoints.addAll(((SummarySnapshot) b).getDataPoints()); + return new SummarySnapshot(metadata, dataPoints); + } else if (a instanceof InfoSnapshot && b instanceof InfoSnapshot) { + List dataPoints = new ArrayList<>(numberOfDataPoints); + dataPoints.addAll(((InfoSnapshot) a).getDataPoints()); + dataPoints.addAll(((InfoSnapshot) b).getDataPoints()); + return new InfoSnapshot(metadata, dataPoints); + } else { + throttlingLogger.log( + Level.WARNING, + "Conflicting metric name " + + a.getMetadata().getPrometheusName() + + ": Found one metric with type " + + typeString(a) + + " and one of type " + + typeString(b) + + ". Dropping the one with type " + + typeString(b) + + "."); + return null; + } + } + + @Nullable + private MetricMetadata mergeMetadata(MetricMetadata a, MetricMetadata b) { + String name = a.getPrometheusName(); + if (a.getName().equals(b.getName())) { + name = a.getName(); + } + String help = null; + if (a.getHelp() != null && a.getHelp().equals(b.getHelp())) { + help = a.getHelp(); + } + Unit unit = a.getUnit(); + if (unit != null && !unit.equals(b.getUnit())) { + throttlingLogger.log( + Level.WARNING, + "Conflicting metrics: Multiple metrics with name " + + name + + " but different units found. Dropping the one with unit " + + b.getUnit() + + "."); + return null; + } + return MetricMetadata.builder().name(name).help(help).unit(unit).build(); + } + + private static String typeString(MetricSnapshot snapshot) { + // Simple helper for a log message. + return snapshot.getClass().getSimpleName().replace("Snapshot", "").toLowerCase(Locale.ENGLISH); + } + + private static String toLabelValue(AttributeType type, Object attributeValue) { + switch (type) { + case STRING: + case BOOLEAN: + case LONG: + case DOUBLE: + return attributeValue.toString(); + case BOOLEAN_ARRAY: + case LONG_ARRAY: + case DOUBLE_ARRAY: + case STRING_ARRAY: + if (attributeValue instanceof List) { + return toJsonStr((List) attributeValue); + } else { + throw new IllegalStateException( + String.format( + "Unexpected label value of %s for %s", + attributeValue.getClass().getName(), type.name())); + } + case VALUE: + return ((Value) attributeValue).asString(); + } + throw new IllegalStateException("Unrecognized AttributeType: " + type); + } + + public static String toJsonStr(List attributeValue) { + StringJoiner joiner = new StringJoiner(",", "[", "]"); + for (int i = 0; i < attributeValue.size(); i++) { + Object value = attributeValue.get(i); + joiner.add(value instanceof String ? toJsonValidStr((String) value) : String.valueOf(value)); + } + return joiner.toString(); + } + + public static String toJsonValidStr(String str) { + StringBuilder sb = new StringBuilder(); + sb.append('"'); + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + if (c <= 0x1F) { + sb.append(String.format(Locale.ROOT, "\\u%04X", (int) c)); + } else { + sb.append(c); + } + } + } + sb.append('"'); + return sb.toString(); + } + + /** Stores the original attribute key and rendered value for one normalized label collision. */ + private static final class OriginalLabelKeyValue { + private final String originalKey; + private final String value; + + private OriginalLabelKeyValue(String originalKey, String value) { + this.originalKey = originalKey; + this.value = value; + } + + private String originalKey() { + return originalKey; + } + + private String value() { + return value; + } + } +} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServer.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServer.java index f828205e774..ee5aca82300 100644 --- a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServer.java +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServer.java @@ -10,52 +10,45 @@ package io.opentelemetry.exporter.prometheus; -import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.Authenticator; import com.sun.net.httpserver.HttpHandler; -import com.sun.net.httpserver.HttpServer; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import java.io.Closeable; +import io.prometheus.metrics.config.PrometheusProperties; +import io.prometheus.metrics.exporter.httpserver.HTTPServer; +import io.prometheus.metrics.model.registry.PrometheusRegistry; import java.io.IOException; -import java.io.OutputStream; import java.io.UncheckedIOException; -import java.net.HttpURLConnection; import java.net.InetSocketAddress; -import java.net.URLDecoder; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.StringJoiner; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.zip.GZIPOutputStream; import javax.annotation.Nullable; /** * A {@link MetricReader} that starts an HTTP server that will collect metrics and serialize to * Prometheus text format on request. */ -// Very similar to -// https://github.com/prometheus/client_java/blob/master/simpleclient_httpserver/src/main/java/io/prometheus/client/exporter/HTTPServer.java -public final class PrometheusHttpServer implements Closeable, MetricReader { +public final class PrometheusHttpServer implements MetricReader { - private static final DaemonThreadFactory THREAD_FACTORY = - new DaemonThreadFactory("prometheus-http"); + private final String host; + private final int port; + private final MemoryMode memoryMode; + private final DefaultAggregationSelector defaultAggregationSelector; - private final HttpServer server; - private final ExecutorService executor; - private volatile MetricProducer metricProducer = MetricProducer.noop(); + private final PrometheusHttpServerBuilder builder; + private final HTTPServer httpServer; + private final PrometheusMetricReader prometheusMetricReader; + private final PrometheusRegistry prometheusRegistry; /** * Returns a new {@link PrometheusHttpServer} which can be registered to an {@link @@ -71,74 +64,103 @@ public static PrometheusHttpServerBuilder builder() { return new PrometheusHttpServerBuilder(); } - PrometheusHttpServer(String host, int port) { + PrometheusHttpServer( + PrometheusHttpServerBuilder builder, + String host, + int port, + @Nullable ExecutorService executor, + PrometheusRegistry prometheusRegistry, + MemoryMode memoryMode, + @Nullable HttpHandler defaultHandler, + DefaultAggregationSelector defaultAggregationSelector, + @Nullable Authenticator authenticator, + TranslationStrategy translationStrategy, + PrometheusMetricReader prometheusMetricReader) { + this.host = host; + this.port = port; + this.memoryMode = memoryMode; + this.defaultAggregationSelector = defaultAggregationSelector; + this.builder = builder; + this.prometheusMetricReader = prometheusMetricReader; + this.prometheusRegistry = prometheusRegistry; + prometheusRegistry.register(prometheusMetricReader); + // When memory mode is REUSABLE_DATA, concurrent reads lead to data corruption. To prevent this, + // we configure prometheus with a single thread executor such that requests are handled + // sequentially. + if (memoryMode == MemoryMode.REUSABLE_DATA) { + executor = + new ThreadPoolExecutor( + 1, + 1, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(), + new DaemonThreadFactory("prometheus-http-server")); + } + HTTPServer.Builder httpServerBuilder = HTTPServer.builder(); + if (translationStrategy != TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES) { + // Intentionally enable OM2 without content negotiation so OpenMetrics responses keep the + // legacy OM1 content type while using OM2 name-preservation semantics. + PrometheusProperties prometheusProperties = + PrometheusProperties.builder().enableOpenMetrics2(om2 -> {}).build(); + httpServerBuilder = HTTPServer.builder(prometheusProperties); + } try { - server = HttpServer.create(new InetSocketAddress(host, port), 3); + this.httpServer = + httpServerBuilder + .hostname(host) + .port(port) + .executorService(executor) + .registry(prometheusRegistry) + .defaultHandler(defaultHandler) + .authenticator(authenticator) + .buildAndStart(); } catch (IOException e) { throw new UncheckedIOException("Could not create Prometheus HTTP server", e); } - server.createContext("/", new MetricsHandler(() -> getMetricProducer().collectAllMetrics())); - server.createContext( - "/metrics", new MetricsHandler(() -> getMetricProducer().collectAllMetrics())); - server.createContext("/-/healthy", HealthHandler.INSTANCE); - - executor = Executors.newFixedThreadPool(5, THREAD_FACTORY); - server.setExecutor(executor); - - start(); } - private MetricProducer getMetricProducer() { - return metricProducer; + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return prometheusMetricReader.getAggregationTemporality(instrumentType); } - private void start() { - // server.start must be called from a daemon thread for it to be a daemon. - if (Thread.currentThread().isDaemon()) { - server.start(); - return; - } - - Thread thread = THREAD_FACTORY.newThread(server::start); - thread.start(); - try { - thread.join(); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return defaultAggregationSelector.getDefaultAggregation(instrumentType); } @Override - public void register(CollectionRegistration registration) { - this.metricProducer = MetricProducer.asMetricProducer(registration); + public MemoryMode getMemoryMode() { + return memoryMode; } @Override - public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return AggregationTemporality.CUMULATIVE; + public void register(CollectionRegistration registration) { + prometheusMetricReader.register(registration); } @Override public CompletableResultCode forceFlush() { - return CompletableResultCode.ofSuccess(); + return prometheusMetricReader.forceFlush(); } @Override public CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); - Thread thread = - THREAD_FACTORY.newThread( - () -> { - try { - server.stop(10); - executor.shutdownNow(); - } catch (Throwable t) { - result.fail(); - return; - } - result.succeed(); - }); - thread.start(); + Runnable shutdownFunction = + () -> { + try { + prometheusRegistry.unregister(prometheusMetricReader); + httpServer.stop(); + prometheusMetricReader.shutdown().whenComplete(result::succeed); + } catch (Throwable t) { + result.fail(); + } + }; + Thread shutdownThread = new Thread(shutdownFunction, "prometheus-httpserver-shutdown"); + shutdownThread.setDaemon(true); + shutdownThread.start(); return result; } @@ -149,101 +171,26 @@ public void close() { @Override public String toString() { - return "PrometheusHttpServer{address=" + server.getAddress() + "}"; + StringJoiner joiner = new StringJoiner(",", "PrometheusHttpServer{", "}"); + joiner.add("host=" + host); + joiner.add("port=" + port); + joiner.add("metricReader=" + prometheusMetricReader.toString()); + joiner.add("memoryMode=" + memoryMode); + joiner.add( + "defaultAggregationSelector=" + + DefaultAggregationSelector.asString(defaultAggregationSelector)); + return joiner.toString(); } - // Visible for testing. - InetSocketAddress getAddress() { - return server.getAddress(); - } - - private static class MetricsHandler implements HttpHandler { - - private final Supplier> metricsSupplier; - - private MetricsHandler(Supplier> metricsSupplier) { - this.metricsSupplier = metricsSupplier; - } - - @Override - public void handle(HttpExchange exchange) throws IOException { - Collection metrics = metricsSupplier.get(); - Set requestedNames = parseQuery(exchange.getRequestURI().getRawQuery()); - Predicate filter = - requestedNames.isEmpty() ? unused -> true : requestedNames::contains; - Serializer serializer = - Serializer.create(exchange.getRequestHeaders().getFirst("Accept"), filter); - exchange.getResponseHeaders().set("Content-Type", serializer.contentType()); - - boolean compress = shouldUseCompression(exchange); - if (compress) { - exchange.getResponseHeaders().set("Content-Encoding", "gzip"); - } - - if (exchange.getRequestMethod().equals("HEAD")) { - exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1); - } else { - exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, 0); - OutputStream out; - if (compress) { - out = new GZIPOutputStream(exchange.getResponseBody()); - } else { - out = exchange.getResponseBody(); - } - serializer.write(metrics, out); - } - exchange.close(); - } - } - - private static boolean shouldUseCompression(HttpExchange exchange) { - List encodingHeaders = exchange.getRequestHeaders().get("Accept-Encoding"); - if (encodingHeaders == null) { - return false; - } - - for (String encodingHeader : encodingHeaders) { - String[] encodings = encodingHeader.split(","); - for (String encoding : encodings) { - if (encoding.trim().equalsIgnoreCase("gzip")) { - return true; - } - } - } - return false; - } - - private static Set parseQuery(@Nullable String query) throws IOException { - if (query == null) { - return Collections.emptySet(); - } - Set names = new HashSet<>(); - String[] pairs = query.split("&"); - for (String pair : pairs) { - int idx = pair.indexOf("="); - if (idx != -1 && URLDecoder.decode(pair.substring(0, idx), "UTF-8").equals("name[]")) { - names.add(URLDecoder.decode(pair.substring(idx + 1), "UTF-8")); - } - } - return names; + /** + * Returns a new {@link PrometheusHttpServerBuilder} with the same configuration as this instance. + */ + public PrometheusHttpServerBuilder toBuilder() { + return new PrometheusHttpServerBuilder(builder); } - private enum HealthHandler implements HttpHandler { - INSTANCE; - - private static final byte[] RESPONSE = "Exporter is Healthy.".getBytes(StandardCharsets.UTF_8); - private static final String CONTENT_LENGTH_VALUE = String.valueOf(RESPONSE.length); - - @Override - public void handle(HttpExchange exchange) throws IOException { - exchange.getResponseHeaders().set("Content-Length", CONTENT_LENGTH_VALUE); - if (exchange.getRequestMethod().equals("HEAD")) { - exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, -1); - } else { - exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, RESPONSE.length); - exchange.getResponseBody().write(RESPONSE); - } - exchange.close(); - } + // Visible for testing. + InetSocketAddress getAddress() { + return new InetSocketAddress(host, httpServer.getPort()); } } diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerBuilder.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerBuilder.java index 469929698ba..7daca69f322 100644 --- a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerBuilder.java +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerBuilder.java @@ -8,16 +8,58 @@ import static io.opentelemetry.api.internal.Utils.checkArgument; import static java.util.Objects.requireNonNull; +import com.sun.net.httpserver.Authenticator; +import com.sun.net.httpserver.HttpHandler; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.prometheus.metrics.model.registry.PrometheusRegistry; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Predicate; +import javax.annotation.Nullable; + /** A builder for {@link PrometheusHttpServer}. */ public final class PrometheusHttpServerBuilder { static final int DEFAULT_PORT = 9464; - private static final String DEFAULT_HOST = "0.0.0.0"; + private static final String DEFAULT_HOST = "localhost"; + private static final MemoryMode DEFAULT_MEMORY_MODE = MemoryMode.REUSABLE_DATA; - private String host = DEFAULT_HOST; + // Temporarily nullable to detect when it's not set and log warning about 0.0.0.0 -> localhost + // change + @Nullable private String host; private int port = DEFAULT_PORT; + private PrometheusRegistry prometheusRegistry = new PrometheusRegistry(); + private PrometheusMetricReaderBuilder metricReaderBuilder = PrometheusMetricReader.builder(); + @Nullable private ExecutorService executor; + private MemoryMode memoryMode = DEFAULT_MEMORY_MODE; + @Nullable private HttpHandler defaultHandler; + private DefaultAggregationSelector defaultAggregationSelector = + DefaultAggregationSelector.getDefault(); + @Nullable private Authenticator authenticator; + + PrometheusHttpServerBuilder() {} - /** Sets the host to bind to. If unset, defaults to {@value #DEFAULT_HOST}. */ + PrometheusHttpServerBuilder(PrometheusHttpServerBuilder builder) { + this.host = builder.host; + this.port = builder.port; + this.prometheusRegistry = builder.prometheusRegistry; + this.metricReaderBuilder = new PrometheusMetricReaderBuilder(builder.metricReaderBuilder); + this.executor = builder.executor; + this.memoryMode = builder.memoryMode; + this.defaultHandler = builder.defaultHandler; + this.defaultAggregationSelector = builder.defaultAggregationSelector; + this.authenticator = builder.authenticator; + } + + /** + * Sets the host to bind to. If unset, defaults to {@value #DEFAULT_HOST}. + * + *

    Previously defaulted to {@code 0.0.0.0}. To restore the old behavior, set host to {@code + * 0.0.0.0} explicitly. + */ public PrometheusHttpServerBuilder setHost(String host) { requireNonNull(host, "host"); checkArgument(!host.isEmpty(), "host must not be empty"); @@ -32,13 +74,142 @@ public PrometheusHttpServerBuilder setPort(int port) { return this; } + /** Sets the {@link ExecutorService} to be used for {@link PrometheusHttpServer}. */ + public PrometheusHttpServerBuilder setExecutor(ExecutorService executor) { + requireNonNull(executor, "executor"); + this.executor = executor; + return this; + } + + /** Sets the {@link PrometheusRegistry} to be used for {@link PrometheusHttpServer}. */ + public PrometheusHttpServerBuilder setPrometheusRegistry(PrometheusRegistry prometheusRegistry) { + requireNonNull(prometheusRegistry, "prometheusRegistry"); + this.prometheusRegistry = prometheusRegistry; + return this; + } + + /** Set if the {@code otel_scope_*} attributes are generated. Default is {@code true}. */ + public PrometheusHttpServerBuilder setOtelScopeLabelsEnabled(boolean otelScopeLabelsEnabled) { + metricReaderBuilder.setOtelScopeLabelsEnabled(otelScopeLabelsEnabled); + return this; + } + + /** Set if the {@code target_info} metric is generated. Default is {@code true}. */ + public PrometheusHttpServerBuilder setTargetInfoMetricEnabled(boolean targetInfoMetricEnabled) { + metricReaderBuilder.setTargetInfoMetricEnabled(targetInfoMetricEnabled); + return this; + } + + /** + * Sets the translation strategy for metric and label name conversion. + * + * @param translationStrategy the strategy to use + * @return this builder + * @see TranslationStrategy + */ + public PrometheusHttpServerBuilder setTranslationStrategy( + TranslationStrategy translationStrategy) { + requireNonNull(translationStrategy, "translationStrategy"); + metricReaderBuilder.setTranslationStrategy(translationStrategy); + return this; + } + + /** + * Set if the resource attributes should be added as labels on each exported metric. + * + *

    If set, resource attributes will be added as labels on each exported metric if their key + * tests positive (true) when passed through {@code resourceAttributesFilter}. + * + * @param resourceAttributesFilter a predicate that returns true if the resource attribute should + * be added as a label on each exported metric. The predicates input is the resource attribute + * key. + */ + public PrometheusHttpServerBuilder setAllowedResourceAttributesFilter( + Predicate resourceAttributesFilter) { + requireNonNull(resourceAttributesFilter, "resourceAttributesFilter"); + metricReaderBuilder.setAllowedResourceAttributesFilter(resourceAttributesFilter); + return this; + } + + /** + * Set the {@link MemoryMode}. + * + *

    If set to {@link MemoryMode#REUSABLE_DATA}, requests are served sequentially which is + * accomplished by overriding {@link #setExecutor(ExecutorService)} to {@link + * Executors#newSingleThreadExecutor()}. + */ + public PrometheusHttpServerBuilder setMemoryMode(MemoryMode memoryMode) { + requireNonNull(memoryMode, "memoryMode"); + this.memoryMode = memoryMode; + return this; + } + + /** + * Override the default handler for serving the "/", "/**" endpoint. + * + *

    This can be used to serve metrics on additional paths besides the default "/metrics". For + * example: + * PrometheusHttpServer.builder() + * .setPrometheusRegistry(prometheusRegistry) + * .setDefaultHandler(new MetricsHandler(prometheusRegistry)) + * .build() + * + */ + public PrometheusHttpServerBuilder setDefaultHandler(HttpHandler defaultHandler) { + requireNonNull(defaultHandler, "defaultHandler"); + this.defaultHandler = defaultHandler; + return this; + } + + /** + * Set the {@link DefaultAggregationSelector} used for {@link + * MetricExporter#getDefaultAggregation(InstrumentType)}. + * + *

    If unset, defaults to {@link DefaultAggregationSelector#getDefault()}. + */ + public PrometheusHttpServerBuilder setDefaultAggregationSelector( + DefaultAggregationSelector defaultAggregationSelector) { + requireNonNull(defaultAggregationSelector, "defaultAggregationSelector"); + this.defaultAggregationSelector = defaultAggregationSelector; + return this; + } + + /** + * Set the authenticator for {@link PrometheusHttpServer}. + * + *

    If unset, no authentication will be performed. + */ + public PrometheusHttpServerBuilder setAuthenticator(Authenticator authenticator) { + requireNonNull(authenticator, "authenticator"); + this.authenticator = authenticator; + return this; + } + /** * Returns a new {@link PrometheusHttpServer} with the configuration of this builder which can be * registered with a {@link io.opentelemetry.sdk.metrics.SdkMeterProvider}. */ public PrometheusHttpServer build() { - return new PrometheusHttpServer(host, port); + if (memoryMode == MemoryMode.REUSABLE_DATA && executor != null) { + throw new IllegalArgumentException( + "MemoryMode REUSEABLE_DATA cannot be used with custom executor, " + + "since data may be corrupted if reading metrics concurrently"); + } + String resolvedHost = host; + if (resolvedHost == null) { + resolvedHost = DEFAULT_HOST; + } + return new PrometheusHttpServer( + new PrometheusHttpServerBuilder(this), // copy to prevent modification + resolvedHost, + port, + executor, + prometheusRegistry, + memoryMode, + defaultHandler, + defaultAggregationSelector, + authenticator, + metricReaderBuilder.getTranslationStrategy(), + metricReaderBuilder.build()); } - - PrometheusHttpServerBuilder() {} } diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReader.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReader.java new file mode 100644 index 00000000000..82c1c643e36 --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReader.java @@ -0,0 +1,90 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.prometheus.metrics.model.registry.MultiCollector; +import io.prometheus.metrics.model.snapshots.MetricSnapshots; +import java.util.StringJoiner; +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** + * This is the bridge between Prometheus and OpenTelemetry. + * + *

    The {@link PrometheusMetricReader} is a Prometheus {@link MultiCollector} and can be + * registered with the {@link io.prometheus.metrics.model.registry.PrometheusRegistry + * PrometheusRegistry}. It's also an OpenTelemetry {@link MetricReader} and can be registered with a + * {@link io.opentelemetry.sdk.metrics.SdkMeterProvider SdkMeterProvider}. + */ +public class PrometheusMetricReader implements MetricReader, MultiCollector { + + private volatile CollectionRegistration collectionRegistration = CollectionRegistration.noop(); + private final Otel2PrometheusConverter converter; + + /** Returns a new {@link PrometheusMetricReader} with default configuration. */ + public static PrometheusMetricReader create() { + return builder().build(); + } + + /** Returns a new {@link PrometheusMetricReaderBuilder}. */ + public static PrometheusMetricReaderBuilder builder() { + return new PrometheusMetricReaderBuilder(); + } + + // Package-private constructor used by builder + PrometheusMetricReader( + @Nullable Predicate allowedResourceAttributesFilter, + boolean otelScopeLabelsEnabled, + boolean targetInfoMetricEnabled, + TranslationStrategy translationStrategy) { + this.converter = + new Otel2PrometheusConverter( + otelScopeLabelsEnabled, + targetInfoMetricEnabled, + translationStrategy, + allowedResourceAttributesFilter); + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + + @Override + public void register(CollectionRegistration registration) { + this.collectionRegistration = registration; + } + + @Override + public CompletableResultCode forceFlush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public MetricSnapshots collect() { + return converter.convert(collectionRegistration.collectAllMetrics()); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(",", "PrometheusMetricReader{", "}"); + joiner.add("otelScopeLabelsEnabled=" + converter.isOtelScopeLabelsEnabled()); + joiner.add("targetInfoMetricEnabled=" + converter.isTargetInfoMetricEnabled()); + joiner.add("translationStrategy=" + converter.getTranslationStrategy()); + joiner.add("allowedResourceAttributesFilter=" + converter.getAllowedResourceAttributesFilter()); + return joiner.toString(); + } +} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderBuilder.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderBuilder.java new file mode 100644 index 00000000000..56ed668b6af --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderBuilder.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static java.util.Objects.requireNonNull; + +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** Builder for {@link PrometheusMetricReader}. */ +public final class PrometheusMetricReaderBuilder { + + private boolean otelScopeLabelsEnabled = true; + private boolean targetInfoMetricEnabled = true; + private TranslationStrategy translationStrategy = + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES; + @Nullable private Predicate allowedResourceAttributesFilter; + + PrometheusMetricReaderBuilder() {} + + PrometheusMetricReaderBuilder(PrometheusMetricReaderBuilder metricReaderBuilder) { + this.otelScopeLabelsEnabled = metricReaderBuilder.otelScopeLabelsEnabled; + this.targetInfoMetricEnabled = metricReaderBuilder.targetInfoMetricEnabled; + this.translationStrategy = metricReaderBuilder.translationStrategy; + this.allowedResourceAttributesFilter = metricReaderBuilder.allowedResourceAttributesFilter; + } + + /** + * Sets whether to add OpenTelemetry scope labels (otel_scope_name, otel_scope_version, etc.) to + * exported metrics. Default is {@code true}. + * + * @param otelScopeLabelsEnabled whether to add scope labels + * @return this builder + */ + public PrometheusMetricReaderBuilder setOtelScopeLabelsEnabled(boolean otelScopeLabelsEnabled) { + this.otelScopeLabelsEnabled = otelScopeLabelsEnabled; + return this; + } + + /** + * Sets whether to export the target_info metric with resource attributes. Default is {@code + * true}. + * + * @param targetInfoMetricEnabled whether to export target_info metric + * @return this builder + */ + public PrometheusMetricReaderBuilder setTargetInfoMetricEnabled(boolean targetInfoMetricEnabled) { + this.targetInfoMetricEnabled = targetInfoMetricEnabled; + return this; + } + + /** + * Sets the translation strategy for metric and label name conversion. + * + * @param translationStrategy the strategy to use + * @return this builder + * @see TranslationStrategy + */ + public PrometheusMetricReaderBuilder setTranslationStrategy( + TranslationStrategy translationStrategy) { + requireNonNull(translationStrategy, "translationStrategy"); + this.translationStrategy = translationStrategy; + return this; + } + + /** + * Sets a filter to control which resource attributes are added as labels on each exported metric. + * If {@code null}, no resource attributes will be added as labels. Default is {@code null}. + * + * @param allowedResourceAttributesFilter predicate to filter resource attributes, or {@code null} + * @return this builder + */ + public PrometheusMetricReaderBuilder setAllowedResourceAttributesFilter( + @Nullable Predicate allowedResourceAttributesFilter) { + this.allowedResourceAttributesFilter = allowedResourceAttributesFilter; + return this; + } + + TranslationStrategy getTranslationStrategy() { + return translationStrategy; + } + + /** Builds a new {@link PrometheusMetricReader}. */ + public PrometheusMetricReader build() { + return new PrometheusMetricReader( + allowedResourceAttributesFilter, + otelScopeLabelsEnabled, + targetInfoMetricEnabled, + translationStrategy); + } +} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusType.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusType.java deleted file mode 100644 index 3cbf253a2af..00000000000 --- a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusType.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoublePointData; -import io.opentelemetry.sdk.metrics.data.LongPointData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.SumData; - -// Four types we use are same in prometheus and openmetrics format -enum PrometheusType { - GAUGE("gauge"), - COUNTER("counter"), - SUMMARY("summary"), - HISTOGRAM("histogram"); - - private final String typeString; - - PrometheusType(String typeString) { - this.typeString = typeString; - } - - static PrometheusType forMetric(MetricData metric) { - switch (metric.getType()) { - case LONG_GAUGE: - case DOUBLE_GAUGE: - return GAUGE; - case LONG_SUM: - SumData longSumData = metric.getLongSumData(); - if (longSumData.isMonotonic() - && longSumData.getAggregationTemporality() == AggregationTemporality.CUMULATIVE) { - return COUNTER; - } - return GAUGE; - case DOUBLE_SUM: - SumData doubleSumData = metric.getDoubleSumData(); - if (doubleSumData.isMonotonic() - && doubleSumData.getAggregationTemporality() == AggregationTemporality.CUMULATIVE) { - return COUNTER; - } - return GAUGE; - case SUMMARY: - return SUMMARY; - case HISTOGRAM: - case EXPONENTIAL_HISTOGRAM: - return HISTOGRAM; - } - throw new IllegalArgumentException( - "Unsupported metric type, this generally indicates version misalignment " - + "among opentelemetry dependencies. Please make sure to use opentelemetry-bom."); - } - - String getTypeString() { - return typeString; - } -} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusUnitsHelper.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusUnitsHelper.java new file mode 100644 index 00000000000..220706877d8 --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/PrometheusUnitsHelper.java @@ -0,0 +1,199 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import io.prometheus.metrics.model.snapshots.Unit; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Nullable; + +/** Convert OpenTelemetry unit names to Prometheus units. */ +class PrometheusUnitsHelper { + + static final String[] RESERVED_SUFFIXES = {"_total", "_created", "_bucket", "_info"}; + + private static final Map pluralNames = new ConcurrentHashMap<>(); + private static final Map singularNames = new ConcurrentHashMap<>(); + private static final Map predefinedUnits = new ConcurrentHashMap<>(); + + // See + // https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/c3b2997563106e11d39f66eec629fde25dce2bdd/pkg/translator/prometheus/normalize_name.go#L19-L19 + static { + // Time + initUnit("a", "years", "year"); + initUnit("mo", "months", "month"); + initUnit("wk", "weeks", "week"); + initUnit("d", "days", "day"); + initUnit("h", "hours", "hour"); + initUnit("min", "minutes", "minute"); + initUnit("s", "seconds", "second"); + initUnit("ms", "milliseconds", "millisecond"); + initUnit("us", "microseconds", "microsecond"); + initUnit("ns", "nanoseconds", "nanosecond"); + // Bytes + initUnit("By", "bytes", "byte"); + initUnit("KiBy", "kibibytes", "kibibyte"); + initUnit("MiBy", "mebibytes", "mebibyte"); + initUnit("GiBy", "gibibytes", "gibibyte"); + initUnit("TiBy", "tebibytes", "tebibyte"); + initUnit("kBy", "kilobytes", "kilobyte"); + initUnit("MBy", "megabytes", "megabyte"); + initUnit("GBy", "gigabytes", "gigabyte"); + initUnit("TBy", "terabytes", "terabyte"); + // SI + initUnit("m", "meters", "meter"); + initUnit("V", "volts", "volt"); + initUnit("A", "amperes", "ampere"); + initUnit("J", "joules", "joule"); + initUnit("W", "watts", "watt"); + initUnit("g", "grams", "gram"); + // Misc + initUnit("Cel", "celsius"); + initUnit("Hz", "hertz"); + initUnit("%", "percent"); + } + + private PrometheusUnitsHelper() {} + + private static void initUnit(String otelName, String pluralName) { + pluralNames.put(otelName, pluralName); + predefinedUnits.put(otelName, new Unit(pluralName)); + } + + private static void initUnit(String otelName, String pluralName, String singularName) { + initUnit(otelName, pluralName); + singularNames.put(otelName, singularName); + } + + @Nullable + static Unit convertUnit(String otelUnit) { + if (otelUnit.isEmpty() || otelUnit.equals("1")) { + return null; + } + if (otelUnit.contains("{")) { + otelUnit = removeAnnotations(otelUnit).trim(); + if (otelUnit.isEmpty() || otelUnit.equals("/") || otelUnit.equals("1")) { + return null; + } + } + if (predefinedUnits.containsKey(otelUnit)) { + return predefinedUnits.get(otelUnit); + } + if (otelUnit.contains("/")) { + String[] parts = otelUnit.split("/", 2); + String part1 = pluralNames.getOrDefault(parts[0], parts[0]).trim(); + String part2 = singularNames.getOrDefault(parts[1], parts[1]).trim(); + if (part1.isEmpty()) { + return unitOrNull("per_" + part2); + } else { + return unitOrNull(part1 + "_per_" + part2); + } + } + return unitOrNull(otelUnit); + } + + /** + * Removes each opening brace through the next closing brace in linear time. Nested opening braces + * do not start separate annotations. Unterminated annotations are retained, and the original + * string is returned without allocation if no complete annotation is found. + */ + private static String removeAnnotations(String unit) { + StringBuilder result = null; + int start = 0; + while (start < unit.length()) { + int annotationStart = unit.indexOf('{', start); + if (annotationStart == -1) { + break; + } + int annotationEnd = unit.indexOf('}', annotationStart + 1); + if (annotationEnd == -1) { + break; + } + if (result == null) { + result = new StringBuilder(unit.length()); + } + result.append(unit, start, annotationStart); + start = annotationEnd + 1; + } + if (result == null) { + return unit; + } + return result.append(unit, start, unit.length()).toString(); + } + + @Nullable + private static Unit unitOrNull(String name) { + String sanitized = sanitizeUnitName(name); + if (sanitized == null) { + return null; + } + sanitized = stripReservedUnitSuffixes(sanitized); + if (sanitized.isEmpty()) { + return null; + } + return new Unit(sanitized); + } + + // These helpers are adapted from Prometheus naming sanitization. We keep a local copy because + // the exporter still needs unit normalization behavior that fits the Prometheus Java model API. + @Nullable + private static String sanitizeUnitName(String unitName) { + if (unitName.isEmpty()) { + return null; + } + String sanitizedName = replaceIllegalCharsInUnitName(unitName); + while (sanitizedName.startsWith("_") || sanitizedName.startsWith(".")) { + sanitizedName = sanitizedName.substring(1); + } + while (sanitizedName.endsWith(".") || sanitizedName.endsWith("_")) { + sanitizedName = sanitizedName.substring(0, sanitizedName.length() - 1); + } + if (sanitizedName.isEmpty()) { + return null; + } + return sanitizedName; + } + + private static String replaceIllegalCharsInUnitName(String name) { + int length = name.length(); + char[] sanitized = new char[length]; + for (int i = 0; i < length; i++) { + char ch = name.charAt(i); + if (ch == ':' + || ch == '.' + || (ch >= 'a' && ch <= 'z') + || (ch >= 'A' && ch <= 'Z') + || (ch >= '0' && ch <= '9')) { + sanitized[i] = ch; + } else { + sanitized[i] = '_'; + } + } + return new String(sanitized); + } + + private static String stripReservedUnitSuffixes(String name) { + boolean modified = true; + while (modified) { + modified = false; + for (String suffix : RESERVED_SUFFIXES) { + String suffixWithoutUnderscore = suffix.substring(1); + if (name.equals(suffixWithoutUnderscore)) { + return ""; + } + if (name.endsWith(suffix)) { + name = name.substring(0, name.length() - suffix.length()); + modified = true; + } + } + while (name.endsWith("_") || name.endsWith(".")) { + name = name.substring(0, name.length() - 1); + modified = true; + } + } + return name; + } +} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Serializer.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Serializer.java deleted file mode 100644 index 9b0b2091528..00000000000 --- a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/Serializer.java +++ /dev/null @@ -1,543 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: - -/* - * Prometheus instrumentation library for JVM applications - * Copyright 2012-2015 The Prometheus Authors - * - * This product includes software developed at - * Boxever Ltd. (http://www.boxever.com/). - * - * This product includes software developed at - * SoundCloud Ltd. (http://soundcloud.com/). - * - * This product includes software developed as part of the - * Ocelli project by Netflix Inc. (https://github.com/Netflix/ocelli/). - */ - -package io.opentelemetry.exporter.prometheus; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.DoublePointData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.HistogramPointData; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; -import io.opentelemetry.sdk.metrics.data.LongPointData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.MetricDataType; -import io.opentelemetry.sdk.metrics.data.PointData; -import io.opentelemetry.sdk.metrics.data.SummaryPointData; -import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.UncheckedIOException; -import java.io.Writer; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.function.Predicate; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -/** Serializes metrics into Prometheus exposition formats. */ -// Adapted from -// https://github.com/prometheus/client_java/blob/master/simpleclient_common/src/main/java/io/prometheus/client/exporter/common/TextFormat.java -abstract class Serializer { - - static Serializer create(@Nullable String acceptHeader, Predicate filter) { - if (acceptHeader == null) { - return new Prometheus004Serializer(filter); - } - - for (String accepts : acceptHeader.split(",")) { - if ("application/openmetrics-text".equals(accepts.split(";")[0].trim())) { - return new OpenMetrics100Serializer(filter); - } - } - - return new Prometheus004Serializer(filter); - } - - private final Predicate metricNameFilter; - - Serializer(Predicate metricNameFilter) { - this.metricNameFilter = metricNameFilter; - } - - abstract String contentType(); - - abstract String headerName(String name, PrometheusType type); - - abstract void writeHelp(Writer writer, String description) throws IOException; - - abstract void writeTimestamp(Writer writer, long timestampNanos) throws IOException; - - abstract void writeExemplar( - Writer writer, - Collection exemplars, - double minExemplar, - double maxExemplar) - throws IOException; - - abstract void writeEof(Writer writer) throws IOException; - - final void write(Collection metrics, OutputStream output) throws IOException { - // Prometheus requires all metrics with the same name to be serialized together, so we need to - // group them. - // In particular, it is common for OpenTelemetry to report metrics with the same name from - // different libraries - // separately. - Map> metricsByName = - metrics.stream() - // Not supported in specification yet. - .filter(metric -> metric.getType() != MetricDataType.EXPONENTIAL_HISTOGRAM) - .filter(metric -> metricNameFilter.test(metricName(metric))) - .collect( - Collectors.groupingBy( - metric -> - headerName( - NameSanitizer.INSTANCE.apply(metric.getName()), - PrometheusType.forMetric(metric)), - LinkedHashMap::new, - Collectors.toList())); - try (Writer writer = - new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8))) { - for (Map.Entry> entry : metricsByName.entrySet()) { - write(entry.getValue(), entry.getKey(), writer); - } - writeEof(writer); - } - } - - private void write(List metrics, String headerName, Writer writer) - throws IOException { - // Write header based on first metric - PrometheusType type = PrometheusType.forMetric(metrics.get(0)); - String description = metrics.get(0).getDescription(); - - writer.write("# TYPE "); - writer.write(headerName); - writer.write(' '); - writer.write(type.getTypeString()); - writer.write('\n'); - - writer.write("# HELP "); - writer.write(headerName); - writer.write(' '); - writeHelp(writer, description); - writer.write('\n'); - - // Then write the metrics. - for (MetricData metric : metrics) { - write(metric, writer); - } - } - - private void write(MetricData metric, Writer writer) throws IOException { - String name = metricName(metric); - - for (PointData point : getPoints(metric)) { - switch (metric.getType()) { - case DOUBLE_SUM: - case DOUBLE_GAUGE: - writePoint( - writer, - name, - ((DoublePointData) point).getValue(), - point.getAttributes(), - point.getEpochNanos()); - break; - case LONG_SUM: - case LONG_GAUGE: - writePoint( - writer, - name, - (double) ((LongPointData) point).getValue(), - point.getAttributes(), - point.getEpochNanos()); - break; - case HISTOGRAM: - writeHistogram(writer, name, (HistogramPointData) point); - break; - case SUMMARY: - writeSummary(writer, name, (SummaryPointData) point); - break; - case EXPONENTIAL_HISTOGRAM: - throw new IllegalArgumentException("Can't happen"); - } - } - } - - private void writeHistogram(Writer writer, String name, HistogramPointData point) - throws IOException { - writePoint( - writer, - name + "_count", - (double) point.getCount(), - point.getAttributes(), - point.getEpochNanos()); - writePoint(writer, name + "_sum", point.getSum(), point.getAttributes(), point.getEpochNanos()); - - long cumulativeCount = 0; - List counts = point.getCounts(); - for (int i = 0; i < counts.size(); i++) { - // This is the upper boundary (inclusive). I.e. all values should be < this value (LE - - // Less-then-or-Equal). - double boundary = getBucketUpperBound(point, i); - - cumulativeCount += counts.get(i); - writePoint( - writer, - name + "_bucket", - (double) cumulativeCount, - point.getAttributes(), - point.getEpochNanos(), - "le", - boundary, - point.getExemplars(), - getBucketLowerBound(point, i), - boundary); - } - } - - /** - * Returns the lower bound of a bucket (all values would have been greater than). - * - * @param bucketIndex The bucket index, should match {@link HistogramPointData#getCounts()} index. - */ - static double getBucketLowerBound(HistogramPointData point, int bucketIndex) { - return bucketIndex > 0 ? point.getBoundaries().get(bucketIndex - 1) : Double.NEGATIVE_INFINITY; - } - - /** - * Returns the upper inclusive bound of a bucket (all values would have been less then or equal). - * - * @param bucketIndex The bucket index, should match {@link HistogramPointData#getCounts()} index. - */ - static double getBucketUpperBound(HistogramPointData point, int bucketIndex) { - List boundaries = point.getBoundaries(); - return (bucketIndex < boundaries.size()) - ? boundaries.get(bucketIndex) - : Double.POSITIVE_INFINITY; - } - - private void writeSummary(Writer writer, String name, SummaryPointData point) throws IOException { - writePoint( - writer, - name + "_count", - (double) point.getCount(), - point.getAttributes(), - point.getEpochNanos()); - writePoint(writer, name + "_sum", point.getSum(), point.getAttributes(), point.getEpochNanos()); - - List valueAtQuantiles = point.getValues(); - for (ValueAtQuantile valueAtQuantile : valueAtQuantiles) { - writePoint( - writer, - name, - valueAtQuantile.getValue(), - point.getAttributes(), - point.getEpochNanos(), - "quantile", - valueAtQuantile.getQuantile(), - Collections.emptyList(), - 0, - 0); - } - } - - private void writePoint( - Writer writer, String name, double value, Attributes attributes, long epochNanos) - throws IOException { - writer.write(name); - writeAttributes(writer, attributes); - writer.write(' '); - writeDouble(writer, value); - writer.write(' '); - writeTimestamp(writer, epochNanos); - writer.write('\n'); - } - - private void writePoint( - Writer writer, - String name, - double value, - Attributes attributes, - long epochNanos, - String additionalAttrKey, - double additionalAttrValue, - Collection exemplars, - double minExemplar, - double maxExemplar) - throws IOException { - writer.write(name); - writeAttributes(writer, attributes, additionalAttrKey, additionalAttrValue); - writer.write(' '); - writeDouble(writer, value); - writer.write(' '); - writeTimestamp(writer, epochNanos); - writeExemplar(writer, exemplars, minExemplar, maxExemplar); - writer.write('\n'); - } - - private static void writeAttributes(Writer writer, Attributes attributes) throws IOException { - if (attributes.isEmpty()) { - return; - } - writer.write('{'); - writeAttributePairs(writer, attributes); - writer.write('}'); - } - - private static void writeAttributes( - Writer writer, Attributes attributes, String additionalAttrKey, double additionalAttrValue) - throws IOException { - writer.write('{'); - if (!attributes.isEmpty()) { - writeAttributePairs(writer, attributes); - writer.write(','); - } - writer.write(additionalAttrKey); - writer.write("=\""); - writeDouble(writer, additionalAttrValue); - writer.write('"'); - writer.write('}'); - } - - private static void writeAttributePairs(Writer writer, Attributes attributes) throws IOException { - try { - attributes.forEach( - new BiConsumer, Object>() { - private boolean wroteOne; - - @Override - public void accept(AttributeKey key, Object value) { - try { - if (wroteOne) { - writer.write(','); - } else { - wroteOne = true; - } - writer.write(NameSanitizer.INSTANCE.apply(key.getKey())); - writer.write("=\""); - writeEscapedLabelValue(writer, value.toString()); - writer.write('"'); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - }); - } catch (UncheckedIOException e) { - throw e.getCause(); - } - } - - private static void writeDouble(Writer writer, double d) throws IOException { - if (d == Double.POSITIVE_INFINITY) { - writer.write("+Inf"); - } else if (d == Double.NEGATIVE_INFINITY) { - writer.write("-Inf"); - } else { - writer.write(Double.toString(d)); - } - } - - static void writeEscapedLabelValue(Writer writer, String s) throws IOException { - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - switch (c) { - case '\\': - writer.write("\\\\"); - break; - case '\"': - writer.write("\\\""); - break; - case '\n': - writer.write("\\n"); - break; - default: - writer.write(c); - } - } - } - - static class Prometheus004Serializer extends Serializer { - - Prometheus004Serializer(Predicate metricNameFilter) { - super(metricNameFilter); - } - - @Override - String contentType() { - return "text/plain; version=0.0.4; charset=utf-8"; - } - - @Override - String headerName(String name, PrometheusType type) { - if (type == PrometheusType.COUNTER) { - return name + "_total"; - } - return name; - } - - @Override - void writeHelp(Writer writer, String help) throws IOException { - for (int i = 0; i < help.length(); i++) { - char c = help.charAt(i); - switch (c) { - case '\\': - writer.write("\\\\"); - break; - case '\n': - writer.write("\\n"); - break; - default: - writer.write(c); - } - } - } - - @Override - void writeTimestamp(Writer writer, long timestampNanos) throws IOException { - writer.write(Long.toString(TimeUnit.NANOSECONDS.toMillis(timestampNanos))); - } - - @Override - void writeExemplar( - Writer writer, - Collection exemplars, - double minExemplar, - double maxExemplar) { - // Don't write exemplars - } - - @Override - void writeEof(Writer writer) { - // Don't write EOF - } - } - - static class OpenMetrics100Serializer extends Serializer { - - OpenMetrics100Serializer(Predicate metricNameFilter) { - super(metricNameFilter); - } - - @Override - String contentType() { - return "application/openmetrics-text; version=1.0.0; charset=utf-8"; - } - - @Override - String headerName(String name, PrometheusType type) { - return name; - } - - @Override - void writeHelp(Writer writer, String description) throws IOException { - writeEscapedLabelValue(writer, description); - } - - @Override - void writeTimestamp(Writer writer, long timestampNanos) throws IOException { - long timestampMillis = TimeUnit.NANOSECONDS.toMillis(timestampNanos); - writer.write(Long.toString(timestampMillis / 1000)); - writer.write("."); - long millis = timestampMillis % 1000; - if (millis < 100) { - writer.write('0'); - } - if (millis < 10) { - writer.write('0'); - } - writer.write(Long.toString(millis)); - } - - @Override - void writeExemplar( - Writer writer, - Collection exemplars, - double minExemplar, - double maxExemplar) - throws IOException { - for (ExemplarData exemplar : exemplars) { - double value = getExemplarValue(exemplar); - if (value > minExemplar && value <= maxExemplar) { - writer.write(" # {"); - SpanContext spanContext = exemplar.getSpanContext(); - if (spanContext.isValid()) { - // NB: Output sorted to match prometheus client library even though it shouldn't matter. - // OTel generally outputs in trace_id span_id order though so we can consider breaking - // from reference implementation if it makes sense. - writer.write("span_id=\""); - writer.write(spanContext.getSpanId()); - writer.write("\",trace_id=\""); - writer.write(spanContext.getTraceId()); - writer.write('"'); - } - writer.write("} "); - writeDouble(writer, value); - writer.write(' '); - writeTimestamp(writer, exemplar.getEpochNanos()); - // Only write one exemplar. - return; - } - } - } - - @Override - void writeEof(Writer writer) throws IOException { - writer.write("# EOF\n"); - } - } - - static Collection getPoints(MetricData metricData) { - switch (metricData.getType()) { - case DOUBLE_GAUGE: - return metricData.getDoubleGaugeData().getPoints(); - case DOUBLE_SUM: - return metricData.getDoubleSumData().getPoints(); - case LONG_GAUGE: - return metricData.getLongGaugeData().getPoints(); - case LONG_SUM: - return metricData.getLongSumData().getPoints(); - case SUMMARY: - return metricData.getSummaryData().getPoints(); - case HISTOGRAM: - return metricData.getHistogramData().getPoints(); - case EXPONENTIAL_HISTOGRAM: - return ExponentialHistogramData.fromMetricData(metricData).getPoints(); - } - return Collections.emptyList(); - } - - private static String metricName(MetricData metric) { - PrometheusType type = PrometheusType.forMetric(metric); - String name = NameSanitizer.INSTANCE.apply(metric.getName()); - if (type == PrometheusType.COUNTER) { - name = name + "_total"; - } - return name; - } - - private static double getExemplarValue(ExemplarData exemplar) { - return exemplar instanceof DoubleExemplarData - ? ((DoubleExemplarData) exemplar).getValue() - : (double) ((LongExemplarData) exemplar).getValue(); - } -} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/TranslationStrategy.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/TranslationStrategy.java new file mode 100644 index 00000000000..d96e9d483e7 --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/TranslationStrategy.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +/** + * Controls how OpenTelemetry metric and label names are translated to Prometheus format. + * + * @see Prometheus + * exporter configuration + */ +public enum TranslationStrategy { + /** + * Default. Non-standard characters are converted to underscores, and type / unit suffixes are + * attached. + */ + UNDERSCORE_ESCAPING_WITH_SUFFIXES, + + /** + * Non-standard characters are converted to underscores, but type / unit suffixes are not attached + * by the exporter. + */ + UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES, + + /** UTF-8 metric and label names are preserved, while type / unit suffixes are still attached. */ + NO_UTF8_ESCAPING_WITH_SUFFIXES, + + /** Metric and label names are passed through without translation. */ + NO_TRANSLATION; +} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/internal/PrometheusComponentProvider.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/internal/PrometheusComponentProvider.java new file mode 100644 index 00000000000..8c1b331bcd4 --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/internal/PrometheusComponentProvider.java @@ -0,0 +1,95 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus.internal; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServerBuilder; +import io.opentelemetry.exporter.prometheus.TranslationStrategy; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import java.util.List; + +/** + * Declarative configuration SPI implementation for {@link PrometheusHttpServer}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class PrometheusComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return MetricReader.class; + } + + @Override + public String getName() { + return "prometheus/development"; + } + + @Override + public MetricReader create(DeclarativeConfigProperties config) { + PrometheusHttpServerBuilder prometheusBuilder = PrometheusHttpServer.builder(); + + Integer port = config.getInt("port"); + if (port != null) { + prometheusBuilder.setPort(port); + } + + String host = config.getString("host"); + if (host != null) { + prometheusBuilder.setHost(host); + } + + Boolean targetInfoEnabled = config.getBoolean("target_info_enabled/development"); + if (targetInfoEnabled != null) { + prometheusBuilder.setTargetInfoMetricEnabled(targetInfoEnabled); + } + Boolean scopeInfoEnabled = config.getBoolean("scope_info_enabled"); + if (scopeInfoEnabled != null) { + prometheusBuilder.setOtelScopeLabelsEnabled(scopeInfoEnabled); + } + String translationStrategy = config.getString("translation_strategy"); + if (translationStrategy != null) { + prometheusBuilder.setTranslationStrategy(parseTranslationStrategy(translationStrategy)); + } + + DeclarativeConfigProperties withResourceConstantLabels = + config.getStructured("resource_constant_labels"); + if (withResourceConstantLabels != null) { + List included = withResourceConstantLabels.getScalarList("included", String.class); + List excluded = withResourceConstantLabels.getScalarList("excluded", String.class); + if (included != null && included.isEmpty()) { + throw new DeclarativeConfigException("included must not be empty"); + } + if (excluded != null && excluded.isEmpty()) { + throw new DeclarativeConfigException("excluded must not be empty"); + } + prometheusBuilder.setAllowedResourceAttributesFilter( + IncludeExcludePredicate.createPatternMatching(included, excluded)); + } + + return prometheusBuilder.build(); + } + + private static TranslationStrategy parseTranslationStrategy(String value) { + switch (value) { + case "underscore_escaping_with_suffixes": + return TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES; + case "underscore_escaping_without_suffixes/development": + return TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES; + case "no_utf8_escaping_with_suffixes/development": + return TranslationStrategy.NO_UTF8_ESCAPING_WITH_SUFFIXES; + case "no_translation/development": + return TranslationStrategy.NO_TRANSLATION; + default: + throw new DeclarativeConfigException("Unsupported translation_strategy: " + value); + } + } +} diff --git a/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProvider.java b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProvider.java new file mode 100644 index 00000000000..4c60d3def19 --- /dev/null +++ b/exporters/prometheus/src/main/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProvider.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus.internal; + +import io.opentelemetry.exporter.internal.ExporterBuilderUtil; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServerBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider; +import io.opentelemetry.sdk.metrics.export.MetricReader; + +/** + * SPI implementation for {@link PrometheusHttpServer}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class PrometheusMetricReaderProvider implements ConfigurableMetricReaderProvider { + + @Override + public MetricReader createMetricReader(ConfigProperties config) { + PrometheusHttpServerBuilder prometheusBuilder = PrometheusHttpServer.builder(); + + Integer port = config.getInt("otel.exporter.prometheus.port"); + if (port != null) { + prometheusBuilder.setPort(port); + } + String host = config.getString("otel.exporter.prometheus.host"); + if (host != null) { + prometheusBuilder.setHost(host); + } + + ExporterBuilderUtil.configureExporterMemoryMode(config, prometheusBuilder::setMemoryMode); + + String defaultHistogramAggregation = + config.getString( + "otel.java.experimental.exporter.prometheus.metrics.default.histogram.aggregation"); + if (defaultHistogramAggregation != null) { + ExporterBuilderUtil.configureHistogramDefaultAggregation( + defaultHistogramAggregation, prometheusBuilder::setDefaultAggregationSelector); + } + + return prometheusBuilder.build(); + } + + @Override + public String getName() { + return "prometheus"; + } +} diff --git a/exporters/prometheus/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/exporters/prometheus/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..aa27fda9217 --- /dev/null +++ b/exporters/prometheus/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,2 @@ +io.opentelemetry.exporter.prometheus.internal.PrometheusComponentProvider + diff --git a/exporters/prometheus/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider b/exporters/prometheus/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider new file mode 100644 index 00000000000..0cb263a5c42 --- /dev/null +++ b/exporters/prometheus/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.prometheus.internal.PrometheusMetricReaderProvider diff --git a/exporters/prometheus/src/module/java/module-info.java b/exporters/prometheus/src/module/java/module-info.java index 89012f016bd..b675c7bf8ec 100644 --- a/exporters/prometheus/src/module/java/module-info.java +++ b/exporters/prometheus/src/module/java/module-info.java @@ -4,4 +4,5 @@ requires transitive io.opentelemetry.sdk.metrics; requires jdk.httpserver; + requires java.logging; } diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/CollectorIntegrationTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/CollectorIntegrationTest.java new file mode 100644 index 00000000000..f4ad8321bc7 --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/CollectorIntegrationTest.java @@ -0,0 +1,227 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static java.util.concurrent.CompletableFuture.completedFuture; +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.testcontainers.Testcontainers.exposeHostPorts; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.linecorp.armeria.server.ServerBuilder; +import com.linecorp.armeria.server.ServiceRequestContext; +import com.linecorp.armeria.server.grpc.protocol.AbstractUnaryGrpcService; +import com.linecorp.armeria.testing.junit5.server.ServerExtension; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.metrics.v1.AggregationTemporality; +import io.opentelemetry.proto.metrics.v1.Metric; +import io.opentelemetry.proto.metrics.v1.NumberDataPoint; +import io.opentelemetry.proto.metrics.v1.ResourceMetrics; +import io.opentelemetry.proto.metrics.v1.ScopeMetrics; +import io.opentelemetry.proto.metrics.v1.Sum; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.resources.Resource; +import java.io.UncheckedIOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.BindMode; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.output.Slf4jLogConsumer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.DockerImageName; + +/** + * Verifies {@link PrometheusHttpServer} end to end using the OpenTelemetry Collector. The Collector + * is configured to scrape the {@link PrometheusHttpServer} and export data over gRPC to a server + * running in process, allowing assertions to be made against the data. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("NonFinalStaticField") +class CollectorIntegrationTest { + + private static final String COLLECTOR_IMAGE = + "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea"; + + private static final Integer COLLECTOR_HEALTH_CHECK_PORT = 13133; + + private static int prometheusPort; + private static Resource resource; + private static SdkMeterProvider meterProvider; + private static OtlpGrpcServer grpcServer; + private static GenericContainer collector; + + @BeforeAll + static void beforeAll() { + PrometheusHttpServer prometheusHttpServer = PrometheusHttpServer.builder().setPort(0).build(); + prometheusPort = prometheusHttpServer.getAddress().getPort(); + resource = Resource.getDefault(); + meterProvider = + SdkMeterProvider.builder() + .setResource(resource) + .registerMetricReader(prometheusHttpServer) + .build(); + exposeHostPorts(prometheusPort); + + grpcServer = new OtlpGrpcServer(); + grpcServer.start(); + exposeHostPorts(grpcServer.httpPort()); + + collector = + new GenericContainer<>(DockerImageName.parse(COLLECTOR_IMAGE)) + .withEnv("APP_ENDPOINT", "host.testcontainers.internal:" + prometheusPort) + .withEnv("LOGGING_EXPORTER_VERBOSITY", "detailed") + .withEnv( + "OTLP_EXPORTER_ENDPOINT", "host.testcontainers.internal:" + grpcServer.httpPort()) + .withClasspathResourceMapping( + "otel-config.yaml", "/otel-config.yaml", BindMode.READ_ONLY) + .withCommand("--config", "/otel-config.yaml") + .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("otel-collector"))) + .withExposedPorts(COLLECTOR_HEALTH_CHECK_PORT) + .waitingFor(Wait.forHttp("/").forPort(COLLECTOR_HEALTH_CHECK_PORT)); + collector.start(); + } + + @AfterAll + static void afterAll() { + meterProvider.shutdown().join(10, TimeUnit.SECONDS); + grpcServer.stop().join(); + collector.stop(); + } + + @AfterEach + void afterEach() { + grpcServer.reset(); + } + + @Test + void endToEnd() { + Meter meter = meterProvider.meterBuilder("test").setInstrumentationVersion("1.0.0").build(); + + meter + .counterBuilder("requests") + .build() + .add(3, Attributes.builder().put("animal", "bear").build()); + + await() + .atMost(Duration.ofSeconds(30)) + .untilAsserted(() -> assertThat(grpcServer.metricRequests.size()).isGreaterThan(0)); + + ExportMetricsServiceRequest request = grpcServer.metricRequests.get(0); + assertThat(request.getResourceMetricsCount()).isEqualTo(1); + + ResourceMetrics resourceMetrics = request.getResourceMetrics(0); + assertThat(resourceMetrics.getResource().getAttributesList()) + .containsExactlyInAnyOrder( + // Resource attributes derived from the prometheus scrape config + stringKeyValue("service.name", "app"), + stringKeyValue("service.instance.id", "host.testcontainers.internal:" + prometheusPort), + stringKeyValue("server.address", "host.testcontainers.internal"), + stringKeyValue("server.port", String.valueOf(prometheusPort)), + stringKeyValue("url.scheme", "http"), + // Resource attributes from the metric SDK resource translated to target_info + stringKeyValue( + "service_name", + Objects.requireNonNull(resource.getAttributes().get(stringKey("service.name")))), + stringKeyValue( + "telemetry_sdk_name", + Objects.requireNonNull( + resource.getAttributes().get(stringKey("telemetry.sdk.name")))), + stringKeyValue( + "telemetry_sdk_language", + Objects.requireNonNull( + resource.getAttributes().get(stringKey("telemetry.sdk.language")))), + stringKeyValue( + "telemetry_sdk_version", + Objects.requireNonNull( + resource.getAttributes().get(stringKey("telemetry.sdk.version"))))); + + assertThat(resourceMetrics.getScopeMetricsCount()).isEqualTo(2); + ScopeMetrics testScopeMetrics = + resourceMetrics.getScopeMetricsList().stream() + .filter(scopeMetrics -> scopeMetrics.getScope().getName().equals("test")) + .findFirst() + .orElseThrow(() -> new IllegalStateException("missing scope with name \"test\"")); + assertThat(testScopeMetrics.getScope().getVersion()).isEqualTo("1.0.0"); + + Optional optRequestTotal = + testScopeMetrics.getMetricsList().stream() + .filter(metric -> metric.getName().equals("requests_total")) + .findFirst(); + assertThat(optRequestTotal).isPresent(); + Metric requestTotal = optRequestTotal.get(); + assertThat(requestTotal.getDataCase()).isEqualTo(Metric.DataCase.SUM); + + Sum requestTotalSum = requestTotal.getSum(); + assertThat(requestTotalSum.getAggregationTemporality()) + .isEqualTo(AggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE); + assertThat(requestTotalSum.getIsMonotonic()).isTrue(); + assertThat(requestTotalSum.getDataPointsCount()).isEqualTo(1); + + NumberDataPoint requestTotalDataPoint = requestTotalSum.getDataPoints(0); + assertThat(requestTotalDataPoint.getAsDouble()).isEqualTo(3.0); + assertThat(requestTotalDataPoint.getAttributesList()) + .containsExactlyInAnyOrder(stringKeyValue("animal", "bear")); + // Scope name and version are serialized as attributes to disambiguate metrics with the + // same name in different scopes + // TODO: potentially add these back or remove entirely, see + // https://github.com/open-telemetry/opentelemetry-java/issues/7544 + // stringKeyValue("otel_scope_name", "test"), + // stringKeyValue("otel_scope_version", "1.0.0")); + } + + private static KeyValue stringKeyValue(String key, String value) { + return KeyValue.newBuilder() + .setKey(key) + .setValue(AnyValue.newBuilder().setStringValue(value).build()) + .build(); + } + + private static class OtlpGrpcServer extends ServerExtension { + + private final List metricRequests = new ArrayList<>(); + + private void reset() { + metricRequests.clear(); + } + + @Override + protected void configure(ServerBuilder sb) { + sb.service( + "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export", + new AbstractUnaryGrpcService() { + @Override + protected CompletionStage handleMessage( + ServiceRequestContext ctx, byte[] message) { + try { + metricRequests.add(ExportMetricsServiceRequest.parseFrom(message)); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + return completedFuture( + ExportMetricsServiceResponse.getDefaultInstance().toByteArray()); + } + }); + sb.http(0); + } + } +} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/NameSanitizerTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/NameSanitizerTest.java deleted file mode 100644 index e1dc0f1926e..00000000000 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/NameSanitizerTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Function; -import org.junit.jupiter.api.Test; - -class NameSanitizerTest { - - @Test - void testSanitizerCaching() { - AtomicInteger count = new AtomicInteger(); - Function delegate = labelName -> labelName + count.incrementAndGet(); - NameSanitizer sanitizer = new NameSanitizer(delegate); - String labelName = "http.name"; - - assertThat(sanitizer.apply(labelName)).isEqualTo("http.name1"); - assertThat(sanitizer.apply(labelName)).isEqualTo("http.name1"); - assertThat(sanitizer.apply(labelName)).isEqualTo("http.name1"); - assertThat(sanitizer.apply(labelName)).isEqualTo("http.name1"); - assertThat(sanitizer.apply(labelName)).isEqualTo("http.name1"); - assertThat(count).hasValue(1); - } -} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java new file mode 100644 index 00000000000..9f8388a24e3 --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Otel2PrometheusConverterTest.java @@ -0,0 +1,1550 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; +import static io.opentelemetry.api.common.AttributeKey.doubleKey; +import static io.opentelemetry.api.common.AttributeKey.longArrayKey; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; +import io.opentelemetry.sdk.resources.Resource; +import io.prometheus.metrics.expositionformats.ExpositionFormats; +import io.prometheus.metrics.model.snapshots.CounterSnapshot; +import io.prometheus.metrics.model.snapshots.GaugeSnapshot; +import io.prometheus.metrics.model.snapshots.GaugeSnapshot.GaugeDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.HistogramSnapshot; +import io.prometheus.metrics.model.snapshots.InfoSnapshot; +import io.prometheus.metrics.model.snapshots.Labels; +import io.prometheus.metrics.model.snapshots.MetricMetadata; +import io.prometheus.metrics.model.snapshots.MetricSnapshot; +import io.prometheus.metrics.model.snapshots.MetricSnapshots; +import io.prometheus.metrics.model.snapshots.NativeHistogramBuckets; +import io.prometheus.metrics.model.snapshots.SummarySnapshot; +import io.prometheus.metrics.model.snapshots.Unit; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiConsumer; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@SuppressLogger(Otel2PrometheusConverter.class) +class Otel2PrometheusConverterTest { + + private static final Pattern PATTERN = + Pattern.compile( + "(.|\\n)*# HELP (?.*)\n# TYPE (?.*)\n(?.*)\\{" + + "otel_scope_foo=\"bar\",otel_scope_name=\"scope\"," + + "otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"}(.|\\n)*"); + + private final Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ true, + /* targetInfoMetricEnabled= */ true, + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + /* allowedResourceAttributesFilter= */ null); + + @ParameterizedTest + @MethodSource("metricMetadataArgs") + void metricMetadata( + MetricData metricData, String expectedType, String expectedHelp, String expectedMetricName) + throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + ExpositionFormats.init().getPrometheusTextFormatWriter().write(out, snapshots); + String expositionFormat = new String(out.toByteArray(), StandardCharsets.UTF_8); + + assertThat(expositionFormat) + .matchesSatisfying( + PATTERN, + matcher -> { + assertThat(matcher.group("help")).isEqualTo(expectedHelp); + assertThat(matcher.group("type")).isEqualTo(expectedType); + // Note: Summaries and histograms produce output which matches METRIC_NAME_PATTERN + // multiple + // times. The pattern ends up matching against the first. + assertThat(matcher.group("metricName")).isEqualTo(expectedMetricName); + }); + } + + private static Stream metricMetadataArgs() { + return Stream.of( + Arguments.argumentSet( + "gauge unitless 1", + createSampleMetricData("sample", "1", MetricDataType.LONG_GAUGE), + "sample gauge", + "sample description", + "sample"), + Arguments.argumentSet( + "gauge with unit", + createSampleMetricData("sample", "unit", MetricDataType.LONG_GAUGE), + "sample_unit gauge", + "sample_unit description", + "sample_unit"), + Arguments.argumentSet( + "gauge curly braces dropped", + createSampleMetricData("sample", "1{dropped}", MetricDataType.LONG_GAUGE), + "sample gauge", + "sample description", + "sample"), + Arguments.argumentSet( + "sum with unit total suffix", + createSampleMetricData("sample", "unit", MetricDataType.LONG_SUM), + "sample_unit_total counter", + "sample_unit_total description", + "sample_unit_total"), + Arguments.argumentSet( + "sum unitless 1 total suffix", + createSampleMetricData("sample", "1", MetricDataType.LONG_SUM), + "sample_total counter", + "sample_total description", + "sample_total"), + Arguments.argumentSet( + "sum numeric unit 2", + createSampleMetricData("sample", "2", MetricDataType.LONG_SUM), + "sample_2_total counter", + "sample_2_total description", + "sample_2_total"), + Arguments.argumentSet( + "summary numeric unit 2", + createSampleMetricData("metric_name", "2", MetricDataType.SUMMARY), + "metric_name_2 summary", + "metric_name_2 description", + "metric_name_2_count"), + // unsupported characters are translated to "_", repeated "_" are dropped + Arguments.argumentSet( + "summary special chars translated", + createSampleMetricData("s%%ple", "%/min", MetricDataType.SUMMARY), + "s_ple_percent_per_minute summary", + "s_ple_percent_per_minute description", + "s_ple_percent_per_minute_count"), + Arguments.argumentSet( + "sum name contains unit", + createSampleMetricData("metric_name_total", "total", MetricDataType.LONG_SUM), + "metric_name_total counter", + "metric_name_total description", + "metric_name_total"), + // total suffix is stripped because total is a reserved suffixed for monotonic sums + Arguments.argumentSet( + "summary total suffix stripped", + createSampleMetricData("metric_name_total", "total", MetricDataType.SUMMARY), + "metric_name summary", + "metric_name description", + "metric_name_count"), + Arguments.argumentSet( + "gauge name ends with ratio unit omitted", + createSampleMetricData("metric_name_ratio", "1", MetricDataType.LONG_GAUGE), + "metric_name_ratio gauge", + "metric_name_ratio description", + "metric_name_ratio"), + Arguments.argumentSet( + "summary name ends with ratio unit omitted", + createSampleMetricData("metric_name_ratio", "1", MetricDataType.SUMMARY), + "metric_name_ratio summary", + "metric_name_ratio description", + "metric_name_ratio_count"), + Arguments.argumentSet( + "gauge name ends with hertz unit omitted", + createSampleMetricData("metric_hertz", "hertz", MetricDataType.LONG_GAUGE), + "metric_hertz gauge", + "metric_hertz description", + "metric_hertz"), + Arguments.argumentSet( + "sum name ends with hertz unit omitted", + createSampleMetricData("metric_hertz", "hertz", MetricDataType.LONG_SUM), + "metric_hertz_total counter", + "metric_hertz_total description", + "metric_hertz_total"), + Arguments.argumentSet( + "sum name total hertz order matters", + createSampleMetricData("metric_total_hertz", "hertz_total", MetricDataType.LONG_SUM), + "metric_total_hertz_total counter", + "metric_total_hertz_total description", + "metric_total_hertz_total"), + Arguments.argumentSet( + "summary name starts with number", + createSampleMetricData("2_metric_name", "By", MetricDataType.SUMMARY), + "_metric_name_bytes summary", + "_metric_name_bytes description", + "_metric_name_bytes_count")); + } + + @ParameterizedTest + @MethodSource("translationStrategyArgs") + void metricMetadata_translationStrategy( + TranslationStrategy translationStrategy, + String expectedName, + String expectedExpositionBaseName, + String expectedOriginalName) { + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ true, + /* targetInfoMetricEnabled= */ true, + translationStrategy, + /* allowedResourceAttributesFilter= */ null); + + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createSampleMetricData("sample.name", "By", MetricDataType.LONG_SUM))); + + MetricMetadata metadata = snapshots.get(0).getMetadata(); + assertThat(metadata.getName()).isEqualTo(expectedName); + assertThat(metadata.getExpositionBaseName()).isEqualTo(expectedExpositionBaseName); + assertThat(metadata.getOriginalName()).isEqualTo(expectedOriginalName); + } + + private static Stream translationStrategyArgs() { + return Stream.of( + Arguments.argumentSet( + "underscore escaping with suffixes", + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + "sample_name_bytes", + "sample_name_bytes", + "sample_name_bytes"), + Arguments.argumentSet( + "underscore escaping without suffixes", + TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES, + "sample_name", + "sample_name", + "sample_name"), + Arguments.argumentSet( + "no utf8 escaping with suffixes", + TranslationStrategy.NO_UTF8_ESCAPING_WITH_SUFFIXES, + "sample.name_bytes", + "sample.name_bytes_total", + "sample.name_bytes"), + Arguments.argumentSet( + "no translation", + TranslationStrategy.NO_TRANSLATION, + "sample.name", + "sample.name", + "sample.name")); + } + + @Test + void metricMetadata_underscoreEscapingCollapsesRepeatedUnderscores() { + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createSampleMetricData("sample__name", "By", MetricDataType.LONG_SUM))); + + MetricMetadata metadata = + snapshots.stream() + .filter(snapshot -> snapshot instanceof CounterSnapshot) + .findFirst() + .orElseThrow(AssertionError::new) + .getMetadata(); + assertThat(metadata.getName()).isEqualTo("sample_name_bytes"); + assertThat(metadata.getExpositionBaseName()).isEqualTo("sample_name_bytes"); + assertThat(metadata.getOriginalName()).isEqualTo("sample_name_bytes"); + } + + @ParameterizedTest + @MethodSource("legacyLabelNameTranslationArgs") + void labelNameTranslation_underscoreEscaping(String labelName, String expectedLabelName) { + Labels labels = + convertAttributeLabels(labelName, TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES); + + assertThat(labels.size()).isEqualTo(1); + assertThat(labels.getName(0)).isEqualTo(expectedLabelName); + assertThat(labels.getValue(0)).isEqualTo("value"); + } + + private static Stream legacyLabelNameTranslationArgs() { + return Stream.of( + Arguments.argumentSet("colons", "label:with:colons", "label_with_colons"), + Arguments.argumentSet( + "capital letters", "LabelWithCapitalLetters", "LabelWithCapitalLetters"), + Arguments.argumentSet( + "special chars", "label!with&special$chars)", "label_with_special_chars_"), + Arguments.argumentSet( + "foreign characters", + "label_with_foreign_characters_字符", + "label_with_foreign_characters_"), + Arguments.argumentSet("dots", "label.with.dots", "label_with_dots"), + Arguments.argumentSet("leading digit", "123label", "key_123label"), + Arguments.argumentSet( + "leading underscore", + "_label_starting_with_underscore", + "_label_starting_with_underscore"), + Arguments.argumentSet( + "leading double underscore", + "__label_starting_with_2underscores", + "_label_starting_with_2underscores"), + Arguments.argumentSet( + "double underscores", + "label__with__double__underscores", + "label_with_double_underscores"), + Arguments.argumentSet( + "mixed special", "label.name__with&&special##chars", "label_name_with_special_chars"), + // Prometheus Java rejects user labels starting with "__". + Arguments.argumentSet( + "reserved name", "__reserved__label__name__", "_reserved_label_name_"), + Arguments.argumentSet( + "trailing underscores", "trailing_underscores___", "trailing_underscores_")); + } + + @Test + void labelNameTranslation_legacyDropsMetricWithInvalidNormalizedName() { + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ false, + /* targetInfoMetricEnabled= */ false, + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + /* allowedResourceAttributesFilter= */ null); + + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createSampleMetricData( + "sample", + "1", + MetricDataType.LONG_SUM, + Attributes.of(stringKey("γ‚ˆγ†γ“γ"), "value"), + Resource.empty()))); + + assertThat(snapshots).isEmpty(); + } + + @Test + void metricNameTranslation_legacyDropsMetricWithInvalidNormalizedName() { + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ false, + /* targetInfoMetricEnabled= */ false, + TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES, + /* allowedResourceAttributesFilter= */ null); + + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createSampleMetricData("γ‚ˆγ†γ“γ", "1", MetricDataType.LONG_SUM))); + + assertThat(snapshots).isEmpty(); + } + + @Test + void metricNameTranslation_legacyDropsMetricWithEmptyName() { + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ false, + /* targetInfoMetricEnabled= */ false, + TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES, + /* allowedResourceAttributesFilter= */ null); + + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList(createSampleMetricData("", "1", MetricDataType.LONG_SUM))); + + assertThat(snapshots).isEmpty(); + } + + @ParameterizedTest + @MethodSource("nonEscapingTranslationStrategyArgs") + void labelNameTranslation_nonEscapingStrategiesPreserveLabels( + TranslationStrategy translationStrategy) { + Labels labels = convertAttributeLabels("label:with:colons", translationStrategy); + + assertThat(labels.size()).isEqualTo(1); + assertThat(labels.getName(0)).isEqualTo("label:with:colons"); + assertThat(labels.getValue(0)).isEqualTo("value"); + } + + private static Stream nonEscapingTranslationStrategyArgs() { + return Stream.of( + Arguments.argumentSet( + "no utf8 escaping with suffixes", TranslationStrategy.NO_UTF8_ESCAPING_WITH_SUFFIXES), + Arguments.argumentSet("no translation", TranslationStrategy.NO_TRANSLATION)); + } + + @Test + void convertReturnsEmptySnapshotsForNullOrEmptyInput() { + assertThat(converter.convert(null)).isEmpty(); + assertThat(converter.convert(Collections.emptyList())).isEmpty(); + } + + @Test + void convertDoesNotAddTargetInfoWhenAllMetricsAreDropped() { + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createSampleMetricData( + "sample", + "1", + MetricDataType.LONG_SUM, + Attributes.of(stringKey("γ‚ˆγ†γ“γ"), "value"), + Resource.empty()))); + + assertThat(snapshots).isEmpty(); + } + + @ParameterizedTest + @MethodSource("deltaMetricDataArgs") + void convertDropsDeltaMetrics(MetricData metricData) { + assertThat(converter.convert(Collections.singletonList(metricData))).isEmpty(); + } + + private static Stream deltaMetricDataArgs() { + return Stream.of( + Arguments.argumentSet( + "delta long sum", createDeltaMetricData("sample", "1", MetricDataType.LONG_SUM)), + Arguments.argumentSet( + "delta double sum", createDeltaMetricData("sample", "1", MetricDataType.DOUBLE_SUM)), + Arguments.argumentSet( + "delta histogram", createDeltaMetricData("sample", "1", MetricDataType.HISTOGRAM)), + Arguments.argumentSet( + "delta exponential histogram", + createDeltaMetricData("sample", "1", MetricDataType.EXPONENTIAL_HISTOGRAM))); + } + + @Test + void nonMonotonicDoubleSumConvertsToGauge() { + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createMetricDataWithTemporality( + "sample", + "1", + MetricDataType.DOUBLE_SUM, + null, + null, + /* cumulative= */ true, + /* monotonic= */ false))); + + assertThat(snapshots).hasSize(2); + assertThat(snapshots.stream().map(snapshot -> snapshot.getMetadata().getName())) + .contains("sample", "target") + .doesNotContain("sample_total"); + } + + @Test + void convertDropsExponentialHistogramWithUnsupportedScale() { + MetricData metricData = createExponentialHistogramMetricData(-5); + + assertThat(converter.convert(Collections.singletonList(metricData))).isEmpty(); + } + + @Test + void summaryExportsConfiguredQuantiles() { + MetricData metricData = createSummaryMetricDataWithQuantiles("summary"); + + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + + SummarySnapshot snapshot = + (SummarySnapshot) + snapshots.stream() + .filter(SummarySnapshot.class::isInstance) + .findFirst() + .orElseThrow(AssertionError::new); + assertThat(snapshot.getDataPoints().get(0).getQuantiles()).hasSize(2); + } + + @Test + void mergeSummaryMetricsWithSameName() { + MetricSnapshots snapshots = + converter.convert( + Arrays.asList( + createSummaryMetricDataWithQuantiles( + "summary", Attributes.of(stringKey("id"), "a")), + createSummaryMetricDataWithQuantiles( + "summary", Attributes.of(stringKey("id"), "b")))); + + SummarySnapshot snapshot = + (SummarySnapshot) + snapshots.stream() + .filter(SummarySnapshot.class::isInstance) + .findFirst() + .orElseThrow(AssertionError::new); + assertThat(snapshot.getDataPoints()).hasSize(2); + } + + @Test + void mergeHistogramMetricsWithSameName() { + MetricSnapshots snapshots = + converter.convert( + Arrays.asList( + createSampleMetricData( + "histogram", + "1", + MetricDataType.HISTOGRAM, + Attributes.of(stringKey("id"), "a"), + null), + createSampleMetricData( + "histogram", + "1", + MetricDataType.HISTOGRAM, + Attributes.of(stringKey("id"), "b"), + null))); + + HistogramSnapshot snapshot = + (HistogramSnapshot) + snapshots.stream() + .filter(HistogramSnapshot.class::isInstance) + .findFirst() + .orElseThrow(AssertionError::new); + assertThat(snapshot.getDataPoints()).hasSize(2); + } + + @Test + void mergeGaugeMetricsWithSameName() { + MetricSnapshots snapshots = + converter.convert( + Arrays.asList( + createSampleMetricData( + "gauge", + "1", + MetricDataType.LONG_GAUGE, + Attributes.of(stringKey("id"), "a"), + null), + createSampleMetricData( + "gauge", + "1", + MetricDataType.LONG_GAUGE, + Attributes.of(stringKey("id"), "b"), + null))); + + GaugeSnapshot snapshot = + (GaugeSnapshot) + snapshots.stream() + .filter(GaugeSnapshot.class::isInstance) + .findFirst() + .orElseThrow(AssertionError::new); + assertThat(snapshot.getDataPoints()).hasSize(2); + } + + private static Labels convertAttributeLabels( + String labelName, TranslationStrategy translationStrategy) { + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ false, + /* targetInfoMetricEnabled= */ false, + translationStrategy, + /* allowedResourceAttributesFilter= */ null); + + MetricSnapshots snapshots = + converter.convert( + Collections.singletonList( + createSampleMetricData( + "sample", + "1", + MetricDataType.LONG_SUM, + Attributes.of(stringKey(labelName), "value"), + Resource.empty()))); + + assertThat(snapshots).hasSize(1); + return snapshots.get(0).getDataPoints().get(0).getLabels(); + } + + @ParameterizedTest + @MethodSource("resourceAttributesAdditionArgs") + void resourceAttributesAddition( + MetricData metricData, + @Nullable Predicate allowedResourceAttributesFilter, + String metricName, + String expectedMetricLabels) + throws IOException { + + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ true, + /* targetInfoMetricEnabled= */ true, + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + allowedResourceAttributesFilter); + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + ExpositionFormats.init().getPrometheusTextFormatWriter().write(out, snapshots); + String expositionFormat = new String(out.toByteArray(), StandardCharsets.UTF_8); + + // extract the only metric line + List metricLines = + Arrays.stream(expositionFormat.split("\n")) + .filter(line -> line.startsWith(metricName)) + .collect(Collectors.toList()); + assertThat(metricLines).hasSize(1); + String metricLine = metricLines.get(0); + + String metricLabels = + metricLine.substring(metricLine.indexOf("{") + 1, metricLine.indexOf("}")); + assertThat(metricLabels).isEqualTo(expectedMetricLabels); + } + + private static Stream resourceAttributesAdditionArgs() { + List arguments = new ArrayList<>(); + + for (MetricDataType metricDataType : MetricDataType.values()) { + // Check that resource attributes are added as labels, according to allowed pattern + arguments.add( + Arguments.argumentSet( + "resource attribute added " + metricDataType, + createSampleMetricData( + "my.metric", + "units", + metricDataType, + Attributes.of(stringKey("foo1"), "bar1", stringKey("foo2"), "bar2"), + Resource.create( + Attributes.of( + stringKey("host"), "localhost", stringKey("cluster"), "mycluster"))), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("clu"), + metricDataType == MetricDataType.SUMMARY + || metricDataType == MetricDataType.HISTOGRAM + || metricDataType == MetricDataType.EXPONENTIAL_HISTOGRAM + ? "my_metric_units_count" + : "my_metric_units", + + // "cluster" attribute is added (due to reg expr specified) and only it + "cluster=\"mycluster\",foo1=\"bar1\",foo2=\"bar2\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + } + + // Resource attributes which also exists in the metric labels are not added twice + arguments.add( + Arguments.argumentSet( + "resource attribute not duplicated", + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + Attributes.of(stringKey("cluster"), "mycluster2", stringKey("foo2"), "bar2"), + Resource.create( + Attributes.of( + stringKey("host"), "localhost", stringKey("cluster"), "mycluster"))), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("clu"), + "my_metric_units", + + // "cluster" attribute is present only once and the value is taken + // from the metric attributes and not the resource attributes + "cluster=\"mycluster2\",foo2=\"bar2\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + + // Empty attributes + arguments.add( + Arguments.argumentSet( + "empty metric attributes", + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + Attributes.empty(), + Resource.create( + Attributes.of( + stringKey("host"), "localhost", stringKey("cluster"), "mycluster"))), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("clu"), + "my_metric_units", + "cluster=\"mycluster\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + + // Array-valued resource attribute is serialized as a JSON string, matching the point attribute + // path. + arguments.add( + Arguments.argumentSet( + "array-valued resource attribute serialized as json", + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + Attributes.empty(), + Resource.create( + Attributes.of(stringArrayKey("clusters"), Arrays.asList("a", "b")))), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("clu"), + "my_metric_units", + "clusters=\"[\\\"a\\\",\\\"b\\\"]\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + + arguments.add( + Arguments.argumentSet( + "resource attribute collisions are merged", + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + Attributes.empty(), + Resource.create( + createMapAttributes("foo_bar", "b", "foo-bar", "c", "foo.bar", "a"))), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("foo"), + "my_metric_units", + "foo_bar=\"c;a;b\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + + arguments.add( + Arguments.argumentSet( + "metric resource collisions preserve metric precedence", + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + createMapAttributes("foo-bar", "metric"), + Resource.create(createMapAttributes("foo.bar", "resource"))), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("foo"), + "my_metric_units", + "foo_bar=\"metric\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + + arguments.add( + Arguments.argumentSet( + "array-valued resource collisions use label rendering", + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + Attributes.empty(), + Resource.create( + Attributes.builder() + .put(stringArrayKey("foo.bar"), Arrays.asList("a", "b")) + .put("foo-bar", "c") + .build())), + /* allowedResourceAttributesFilter= */ Predicates.startsWith("foo"), + "my_metric_units", + "foo_bar=\"c;[\\\"a\\\",\\\"b\\\"]\",otel_scope_foo=\"bar\",otel_scope_name=\"scope\",otel_scope_schema_url=\"schemaUrl\",otel_scope_version=\"version\"")); + + return arguments.stream(); + } + + @Test + void arrayValuedScopeAttributeSerializedAsJson() { + // Array-valued scope attribute is serialized as a JSON string, matching the point attribute + // path + InstrumentationScopeInfo scope = + InstrumentationScopeInfo.builder("scope") + .setAttributes(Attributes.of(stringArrayKey("foo"), Arrays.asList("a", "b"))) + .build(); + MetricData metricData = + ImmutableMetricData.createLongSum( + Resource.getDefault(), + scope, + "sample", + "description", + "1", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create(0, 1, Attributes.empty(), 1L)))); + + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + + Optional metricSnapshot = + snapshots.stream().filter(snapshot -> snapshot instanceof CounterSnapshot).findFirst(); + assertThat(metricSnapshot).isPresent(); + + Labels labels = metricSnapshot.get().getDataPoints().get(0).getLabels(); + assertThat(labels.get("otel_scope_foo")).isEqualTo("[\"a\",\"b\"]"); + } + + @ParameterizedTest + @MethodSource("metricAttributeCollisionArgs") + void metricAttributeCollisionsAreMergedAndSorted( + TranslationStrategy translationStrategy, + Attributes attributes, + String expectedLabelName, + String expectedLabelValue) { + MetricData metricData = + createSampleMetricData("sample", "1", MetricDataType.LONG_SUM, attributes, null); + + Labels labels = extractMetricLabels(metricData, translationStrategy, null); + assertThat(extractLabelNames(labels)) + .containsExactly( + expectedLabelName, + "otel_scope_foo", + "otel_scope_name", + "otel_scope_schema_url", + "otel_scope_version"); + assertThat(labels.get(expectedLabelName)).isEqualTo(expectedLabelValue); + } + + private static Stream metricAttributeCollisionArgs() { + List arguments = new ArrayList<>(); + List escapingStrategies = + Arrays.asList( + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES); + for (TranslationStrategy translationStrategy : escapingStrategies) { + arguments.add( + Arguments.argumentSet( + translationStrategy + " basic collision", + translationStrategy, + createMapAttributes("foo_bar", "b", "foo-bar", "c", "foo.bar", "a"), + "foo_bar", + "c;a;b")); + arguments.add( + Arguments.argumentSet( + translationStrategy + " semicolon value", + translationStrategy, + createMapAttributes("foo.bar", "a;b", "foo-bar", "c"), + "foo_bar", + "c;a;b")); + arguments.add( + Arguments.argumentSet( + translationStrategy + " many symbols", + translationStrategy, + createMapAttributes("a.b", "1", "a-b", "2", "a_b", "3", "a/b", "4", "a@b", "5"), + "a_b", + "2;1;4;5;3")); + } + return arguments.stream(); + } + + @ParameterizedTest + @MethodSource("metricAttributeCollisionNonEscapingArgs") + void metricAttributeCollisionsRemainDistinctWhenEscapingDisabled( + TranslationStrategy translationStrategy) { + MetricData metricData = + createSampleMetricData( + "sample", + "1", + MetricDataType.LONG_SUM, + createMapAttributes("foo:bar", "a", "foo_bar", "c"), + null); + + Labels labels = extractMetricLabels(metricData, translationStrategy, null); + assertThat(extractLabelNames(labels)) + .containsExactly( + "foo:bar", + "foo_bar", + "otel_scope_foo", + "otel_scope_name", + "otel_scope_schema_url", + "otel_scope_version"); + assertThat(labels.get("foo:bar")).isEqualTo("a"); + assertThat(labels.get("foo_bar")).isEqualTo("c"); + } + + private static Stream metricAttributeCollisionNonEscapingArgs() { + return Stream.of( + Arguments.argumentSet( + "no utf8 escaping with suffixes", TranslationStrategy.NO_UTF8_ESCAPING_WITH_SUFFIXES), + Arguments.argumentSet("no translation", TranslationStrategy.NO_TRANSLATION)); + } + + @Test + void metricNameCollisionTest_Issue6277() { + // NOTE: Metrics with the same resolved prometheus name should merge. However, + // Otel2PrometheusConverter is not responsible for merging individual series, so the merge will + // fail if the two different metrics contain overlapping series. Users should deal with this by + // adding a view that renames one of the two metrics such that the conflict does not occur. + MetricData dotName = + createSampleMetricData( + "my.metric", + "units", + MetricDataType.LONG_SUM, + Attributes.builder().put("key", "a").build(), + Resource.create(Attributes.empty())); + MetricData underscoreName = + createSampleMetricData( + "my_metric", + "units", + MetricDataType.LONG_SUM, + Attributes.builder().put("key", "b").build(), + Resource.create(Attributes.empty())); + + List metricData = new ArrayList<>(); + metricData.add(dotName); + metricData.add(underscoreName); + + assertThatCode(() -> converter.convert(metricData)).doesNotThrowAnyException(); + } + + @ParameterizedTest + @MethodSource("labelValueSerializationArgs") + void labelValueSerialization(Attributes attributes, String expectedValue) { + MetricData metricData = + createSampleMetricData("sample", "1", MetricDataType.LONG_SUM, attributes, null); + + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + + Optional metricSnapshot = + snapshots.stream().filter(snapshot -> snapshot instanceof CounterSnapshot).findFirst(); + assertThat(metricSnapshot).isPresent(); + + Labels labels = metricSnapshot.get().getDataPoints().get(0).getLabels(); + String labelValue = labels.get("key"); + assertThat(labelValue).isEqualTo(expectedValue); + } + + private static Stream labelValueSerializationArgs() { + return Stream.of( + Arguments.argumentSet( + "string value", Attributes.of(stringKey("key"), "stringValue"), "stringValue"), + Arguments.argumentSet("boolean value", Attributes.of(booleanKey("key"), true), "true"), + Arguments.argumentSet( + "long value", Attributes.of(longKey("key"), Long.MAX_VALUE), "9223372036854775807"), + Arguments.argumentSet("double value", Attributes.of(doubleKey("key"), 0.12345), "0.12345"), + Arguments.argumentSet( + "string array value", + Attributes.of( + stringArrayKey("key"), + Arrays.asList("stringValue1", "\"+\\\\\\+\b+\f+\n+\r+\t+" + (char) 0)), + "[\"stringValue1\",\"\\\"+\\\\\\\\\\\\+\\b+\\f+\\n+\\r+\\t+\\u0000\"]"), + Arguments.argumentSet( + "boolean array value", + Attributes.of(booleanArrayKey("key"), Arrays.asList(true, false)), + "[true,false]"), + Arguments.argumentSet( + "long array value", + Attributes.of(longArrayKey("key"), Arrays.asList(Long.MIN_VALUE, Long.MAX_VALUE)), + "[-9223372036854775808,9223372036854775807]"), + Arguments.argumentSet( + "double array value", + Attributes.of(doubleArrayKey("key"), Arrays.asList(Double.MIN_VALUE, Double.MAX_VALUE)), + "[4.9E-324,1.7976931348623157E308]"), + Arguments.argumentSet( + "bytes value", Attributes.of(valueKey("key"), Value.of(new byte[] {1, 2, 3})), "AQID"), + Arguments.argumentSet( + "nested key-value value", + Attributes.of(valueKey("key"), Value.of(KeyValue.of("nested", Value.of("value")))), + "{\"nested\":\"value\"}"), + Arguments.argumentSet( + "list value", + Attributes.of(valueKey("key"), Value.of(Value.of("string"), Value.of(123L))), + "[\"string\",123]"), + Arguments.argumentSet("empty value", Attributes.of(valueKey("key"), Value.empty()), "")); + } + + static MetricData createSampleMetricData( + String metricName, Resource resource, Attributes attributes) { + return createSampleMetricData( + metricName, "unit", MetricDataType.LONG_SUM, attributes, resource); + } + + static MetricData createSampleMetricData( + String metricName, String metricUnit, MetricDataType metricDataType) { + return createSampleMetricData(metricName, metricUnit, metricDataType, null, null); + } + + static MetricData createSampleMetricData( + String metricName, + String metricUnit, + MetricDataType metricDataType, + @Nullable Attributes attributes, + @Nullable Resource resource) { + return createMetricDataWithTemporality( + metricName, + metricUnit, + metricDataType, + attributes, + resource, + /* cumulative= */ true, + /* monotonic= */ true); + } + + private static MetricData createDeltaMetricData( + String metricName, String metricUnit, MetricDataType metricDataType) { + return createMetricDataWithTemporality( + metricName, + metricUnit, + metricDataType, + null, + null, + /* cumulative= */ false, + /* monotonic= */ true); + } + + private static MetricData createSummaryMetricDataWithQuantiles(String metricName) { + return createSummaryMetricDataWithQuantiles(metricName, Attributes.empty()); + } + + private static MetricData createSummaryMetricDataWithQuantiles( + String metricName, Attributes attributes) { + InstrumentationScopeInfo scope = + InstrumentationScopeInfo.builder("scope") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .setAttributes(Attributes.of(stringKey("foo"), "bar")) + .build(); + return ImmutableMetricData.createDoubleSummary( + Resource.getDefault(), + scope, + metricName, + "description", + "1", + ImmutableSummaryData.create( + Collections.singletonList( + ImmutableSummaryPointData.create( + 0, + 1, + attributes, + 2, + 3, + Arrays.asList( + ImmutableValueAtQuantile.create(0.5, 1.5), + ImmutableValueAtQuantile.create(0.9, 2.5)))))); + } + + private static MetricData createExponentialHistogramMetricData(int scale) { + InstrumentationScopeInfo scope = + InstrumentationScopeInfo.builder("scope") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .setAttributes(Attributes.of(stringKey("foo"), "bar")) + .build(); + return ImmutableMetricData.createExponentialHistogram( + Resource.getDefault(), + scope, + "histogram", + "description", + "1", + ImmutableExponentialHistogramData.create( + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableExponentialHistogramPointData.create( + 0, + 1, + scale, + false, + 1, + false, + 1, + ImmutableExponentialHistogramBuckets.create(2, 5, Arrays.asList(1L, 2L)), + ImmutableExponentialHistogramBuckets.create(2, 5, Arrays.asList(1L, 2L)), + 0, + 10, + Attributes.empty(), + Collections.emptyList())))); + } + + private static MetricData createMetricDataWithTemporality( + String metricName, + String metricUnit, + MetricDataType metricDataType, + @Nullable Attributes attributes, + @Nullable Resource resource, + boolean cumulative, + boolean monotonic) { + Attributes attributesToUse = attributes == null ? Attributes.empty() : attributes; + Resource resourceToUse = resource == null ? Resource.getDefault() : resource; + AggregationTemporality aggregationTemporality = + cumulative ? AggregationTemporality.CUMULATIVE : AggregationTemporality.DELTA; + + InstrumentationScopeInfo scope = + InstrumentationScopeInfo.builder("scope") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .setAttributes(Attributes.of(stringKey("foo"), "bar")) + .build(); + switch (metricDataType) { + case SUMMARY: + return ImmutableMetricData.createDoubleSummary( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableSummaryData.create( + Collections.singletonList( + ImmutableSummaryPointData.create( + 0, 1, attributesToUse, 1, 1, Collections.emptyList())))); + case LONG_SUM: + return ImmutableMetricData.createLongSum( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableSumData.create( + monotonic, + aggregationTemporality, + Collections.singletonList( + ImmutableLongPointData.create(0, 1, attributesToUse, 1L)))); + case DOUBLE_SUM: + return ImmutableMetricData.createDoubleSum( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableSumData.create( + monotonic, + aggregationTemporality, + Collections.singletonList( + ImmutableDoublePointData.create(0, 1, attributesToUse, 1.0)))); + case LONG_GAUGE: + return ImmutableMetricData.createLongGauge( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableGaugeData.create( + Collections.singletonList( + ImmutableLongPointData.create(0, 1, attributesToUse, 1L)))); + case DOUBLE_GAUGE: + return ImmutableMetricData.createDoubleGauge( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableGaugeData.create( + Collections.singletonList( + ImmutableDoublePointData.create(0, 1, attributesToUse, 1.0f)))); + case HISTOGRAM: + return ImmutableMetricData.createDoubleHistogram( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableHistogramData.create( + aggregationTemporality, + Collections.singletonList( + ImmutableHistogramPointData.create( + 0, + 1, + attributesToUse, + 1, + false, + -1, + false, + -1, + Collections.singletonList(1.0), + Arrays.asList(0L, 1L))))); + case EXPONENTIAL_HISTOGRAM: + return ImmutableMetricData.createExponentialHistogram( + resourceToUse, + scope, + metricName, + "description", + metricUnit, + ImmutableExponentialHistogramData.create( + aggregationTemporality, + Collections.singletonList( + ImmutableExponentialHistogramPointData.create( + 0, + 1, + 5, + false, + 1, + false, + 1, + ImmutableExponentialHistogramBuckets.create( + 2, 5, Arrays.asList(1L, 2L, 3L, 4L, 5L)), + ImmutableExponentialHistogramBuckets.create( + 2, 5, Arrays.asList(1L, 2L, 3L, 4L, 5L)), + 0, + 10, + attributesToUse, + Collections.emptyList())))); + } + + throw new IllegalArgumentException("Unsupported metric data type: " + metricDataType); + } + + @Test + void validateCacheIsBounded() { + AtomicInteger predicateCalledCount = new AtomicInteger(); + Predicate countPredicate = + s -> { + predicateCalledCount.addAndGet(1); + return true; + }; + + Otel2PrometheusConverter otel2PrometheusConverter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ true, + /* targetInfoMetricEnabled= */ true, + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + /* allowedResourceAttributesFilter= */ countPredicate); + + // Create 20 different metric data objects with 2 different resource attributes; + Resource resource1 = Resource.builder().put("cluster", "cluster1").build(); + Resource resource2 = Resource.builder().put("cluster", "cluster2").build(); + + List metricDataList = new ArrayList<>(); + for (int i = 0; i < 10; i++) { + Attributes attributes = Attributes.of(stringKey("foo" + i), "bar" + i); + metricDataList.add(createSampleMetricData("metric1", resource1, attributes)); + metricDataList.add(createSampleMetricData("metric2", resource2, attributes)); + } + + otel2PrometheusConverter.convert(metricDataList); + + // The predicate should be called only once for each resource attribute, and we have + // 2 unique resources, each with 1 attribute, so 2. + assertThat(predicateCalledCount.get()).isEqualTo(2); + + metricDataList.clear(); + + // Create 20 different metric data objects with 20 different resource attributes; + // This should cause the cache to be full, and then subsequently cleared + for (int i = 0; i < Otel2PrometheusConverter.MAX_CACHE_SIZE; i++) { + Attributes attributes = Attributes.of(stringKey("foo" + i), "bar" + i); + Resource resource = Resource.builder().put("cluster", "different-cluster" + i).build(); + metricDataList.add(createSampleMetricData("metric1", resource, attributes)); + metricDataList.add(createSampleMetricData("metric2", resource, attributes)); + } + otel2PrometheusConverter.convert(metricDataList); + + // Now lets put metrics with the same resource attributes as before + metricDataList.clear(); + predicateCalledCount.set(0); + for (int i = 0; i < 10; i++) { + Attributes attributes = Attributes.of(stringKey("foo" + i), "bar" + i); + metricDataList.add(createSampleMetricData("metric1", resource1, attributes)); + metricDataList.add(createSampleMetricData("metric2", resource2, attributes)); + } + otel2PrometheusConverter.convert(metricDataList); + + // If the cache was unbounded, the predicate should be 0, since it's all in the cache, + // but if the cache was cleared, it used the predicate for each resource, since it as if + // it never saw those resources before. + assertThat(predicateCalledCount.get()).isEqualTo(2); + } + + @Test + void mergeInfoSnapshotsWithSameName() throws Exception { + InfoSnapshot merged = + (InfoSnapshot) + invokePrivate( + "merge", + new Class[] {MetricSnapshot.class, MetricSnapshot.class}, + makeInfoSnapshot("a"), + makeInfoSnapshot("b")); + + assertThat(merged.getDataPoints()).hasSize(2); + } + + @Test + void mergeConflictingTypesReturnsNull() throws Exception { + Object merged = + invokePrivate( + "merge", + new Class[] {MetricSnapshot.class, MetricSnapshot.class}, + makeInfoSnapshot("a"), + new GaugeSnapshot( + MetricMetadata.builder().name("target").build(), + Collections.singletonList(new GaugeDataPointSnapshot(1.0, Labels.EMPTY, null)))); + + assertThat(merged).isNull(); + } + + @Test + void mergeMetadataReturnsNullForDifferentUnits() throws Exception { + Object merged = + invokePrivate( + "mergeMetadata", + new Class[] {MetricMetadata.class, MetricMetadata.class}, + MetricMetadata.builder().name("sample").unit(new Unit("seconds")).build(), + MetricMetadata.builder().name("sample").unit(new Unit("milliseconds")).build()); + + assertThat(merged).isNull(); + } + + @Test + void convertLegacyLabelNameRejectsEmptyName() { + assertThatThrownBy( + () -> invokePrivate("convertLegacyLabelName", new Class[] {String.class}, "")) + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("label name is empty"); + } + + @Test + void stripReservedMetricSuffixesHandlesReservedNameOnly() throws Exception { + assertThat( + invokePrivate("stripReservedMetricSuffixes", new Class[] {String.class}, "_total")) + .isEqualTo("total"); + } + + @Test + void validateNormalizedMetricNameRejectsEmptyName() { + assertThatThrownBy(() -> + invokePrivate( + "validateNormalizedMetricName", + new Class[] {String.class, String.class}, + "orig", + "")) + .hasCauseInstanceOf(IllegalArgumentException.class) + .hasRootCauseMessage("normalization for metric \"orig\" resulted in empty name"); + } + + @Test + void convertExponentialHistogramBucketsReturnsEmptyForNoBuckets() throws Exception { + NativeHistogramBuckets buckets = + (NativeHistogramBuckets) + invokePrivate( + "convertExponentialHistogramBuckets", + new Class[] {ExponentialHistogramBuckets.class, int.class}, + ImmutableExponentialHistogramBuckets.create(0, 0, Collections.emptyList()), + 0); + + assertThat(buckets).isSameAs(NativeHistogramBuckets.EMPTY); + } + + @Test + void typeStringUsesLowerCaseClassName() throws Exception { + assertThat( + invokePrivate( + "typeString", new Class[] {MetricSnapshot.class}, makeInfoSnapshot("a"))) + .isEqualTo("info"); + } + + @ParameterizedTest + @MethodSource("exemplarLabelLimitArgs") + void exemplarLabelLimit( + SpanContext spanContext, + Attributes filteredAttributes, + String[] expectedPresentKeys, + String[] expectedAbsentKeys) { + ImmutableDoubleExemplarData exemplar = + (ImmutableDoubleExemplarData) + ImmutableDoubleExemplarData.create(filteredAttributes, 1000L, spanContext, 1.0); + + MetricData metricData = + ImmutableMetricData.createDoubleGauge( + Resource.getDefault(), + InstrumentationScopeInfo.create("test"), + "my.gauge", + "desc", + "unit", + ImmutableGaugeData.create( + Collections.singletonList( + ImmutableDoublePointData.create( + 0, 1000, Attributes.empty(), 1.0, Collections.singletonList(exemplar))))); + + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + assertThat(snapshots).isNotNull(); + GaugeDataPointSnapshot point = (GaugeDataPointSnapshot) snapshots.get(0).getDataPoints().get(0); + Labels exemplarLabels = point.getExemplar().getLabels(); + for (String key : expectedPresentKeys) { + assertThat(exemplarLabels.get(key)).as("expected label '%s' to be present", key).isNotNull(); + } + for (String key : expectedAbsentKeys) { + assertThat(exemplarLabels.get(key)).as("expected label '%s' to be absent", key).isNull(); + } + } + + private static Stream exemplarLabelLimitArgs() { + SpanContext validSpanContext = + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000001", + TraceFlags.getSampled(), + TraceState.getDefault()); + + char[] chars = new char[100]; + Arrays.fill(chars, 'x'); + String longValue100 = new String(chars); + + chars = new char[150]; + Arrays.fill(chars, 'x'); + String longValue150 = new String(chars); + + return Stream.of( + Arguments.argumentSet( + "withSpanContext withinLimit", + validSpanContext, + Attributes.of(stringKey("short_attr"), "val"), + new String[] {"trace_id", "span_id", "short_attr"}, + new String[] {}), + Arguments.argumentSet( + "withSpanContext exceedingLimit", + validSpanContext, + Attributes.of(stringKey("long_attr"), longValue100), + new String[] {"trace_id", "span_id"}, + new String[] {"long_attr"}), + Arguments.argumentSet( + "withoutSpanContext exceedingLimit", + SpanContext.getInvalid(), + Attributes.of(stringKey("long_attr"), longValue150), + new String[] {}, + new String[] {"long_attr"}), + Arguments.argumentSet( + "withoutSpanContext withinLimit", + SpanContext.getInvalid(), + Attributes.of(stringKey("short_attr"), "val"), + new String[] {"short_attr"}, + new String[] {})); + } + + @ParameterizedTest + @MethodSource("exemplarSpanContextLabelsTakePrecedenceArgs") + void exemplarSpanContextLabelsTakePrecedence(Attributes filteredAttributes) { + SpanContext spanContext = + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000001", + TraceFlags.getSampled(), + TraceState.getDefault()); + ImmutableDoubleExemplarData exemplar = + (ImmutableDoubleExemplarData) + ImmutableDoubleExemplarData.create(filteredAttributes, 1000L, spanContext, 1.0); + + MetricData metricData = + ImmutableMetricData.createDoubleGauge( + Resource.getDefault(), + InstrumentationScopeInfo.create("test"), + "my.gauge", + "desc", + "unit", + ImmutableGaugeData.create( + Collections.singletonList( + ImmutableDoublePointData.create( + 0, 1000, Attributes.empty(), 1.0, Collections.singletonList(exemplar))))); + + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + GaugeDataPointSnapshot point = (GaugeDataPointSnapshot) snapshots.get(0).getDataPoints().get(0); + Labels exemplarLabels = point.getExemplar().getLabels(); + assertThat(exemplarLabels.get("trace_id")).isEqualTo("00000000000000000000000000000001"); + assertThat(exemplarLabels.get("span_id")).isEqualTo("0000000000000001"); + } + + private static Stream exemplarSpanContextLabelsTakePrecedenceArgs() { + return Stream.of( + Arguments.argumentSet( + "sameLabelName", + Attributes.of(stringKey("trace_id"), "bogus", stringKey("span_id"), "bogus")), + Arguments.argumentSet( + "sameLabelNameAfterEscaping", + Attributes.of(stringKey("trace.id"), "bogus", stringKey("span.id"), "bogus"))); + } + + private static InfoSnapshot makeInfoSnapshot(String id) { + return new InfoSnapshot( + MetricMetadata.builder().name("target").build(), + Collections.singletonList( + new InfoSnapshot.InfoDataPointSnapshot( + Labels.of(new String[] {"id"}, new String[] {id})))); + } + + private Object invokePrivate(String methodName, Class[] parameterTypes, Object... args) + throws Exception { + Method method = Otel2PrometheusConverter.class.getDeclaredMethod(methodName, parameterTypes); + method.setAccessible(true); + // Support both static and instance methods: static methods receive null, instance methods + // receive the converter instance so that instance fields (e.g. throttlingLogger) are available. + Object instance = Modifier.isStatic(method.getModifiers()) ? null : converter; + try { + return method.invoke(instance, args); + } catch (InvocationTargetException e) { + throw e; + } + } + + private static Labels extractMetricLabels( + MetricData metricData, + TranslationStrategy translationStrategy, + @Nullable Predicate allowedResourceAttributesFilter) { + Otel2PrometheusConverter converter = + new Otel2PrometheusConverter( + /* otelScopeLabelsEnabled= */ true, + /* targetInfoMetricEnabled= */ true, + translationStrategy, + allowedResourceAttributesFilter); + MetricSnapshots snapshots = converter.convert(Collections.singletonList(metricData)); + + Optional metricSnapshot = + snapshots.stream().filter(snapshot -> !(snapshot instanceof InfoSnapshot)).findFirst(); + assertThat(metricSnapshot).isPresent(); + return metricSnapshot.get().getDataPoints().get(0).getLabels(); + } + + private static List extractLabelNames(Labels labels) { + List names = new ArrayList<>(); + for (int i = 0; i < labels.size(); i++) { + names.add(labels.getName(i)); + } + return names; + } + + // Use a non-default Attributes implementation so ordering-sensitive collision tests do not rely + // on the default SDK storage type. + private static Attributes createMapAttributes(String... keyValues) { + Map, Object> map = new LinkedHashMap<>(); + for (int i = 0; i < keyValues.length; i += 2) { + map.put(stringKey(keyValues[i]), keyValues[i + 1]); + } + return new MapAttributes(map); + } + + @SuppressWarnings("unchecked") + private static final class MapAttributes implements Attributes { + + private final LinkedHashMap, Object> map; + + private MapAttributes(Map, Object> map) { + this.map = new LinkedHashMap<>(map); + } + + @Nullable + @Override + public T get(AttributeKey key) { + return (T) map.get(key); + } + + @Override + public void forEach(BiConsumer, ? super Object> consumer) { + map.forEach(consumer); + } + + @Override + public int size() { + return map.size(); + } + + @Override + public boolean isEmpty() { + return map.isEmpty(); + } + + @Override + public Map, Object> asMap() { + return map; + } + + @Override + public AttributesBuilder toBuilder() { + throw new UnsupportedOperationException("not supported"); + } + } +} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Predicates.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Predicates.java new file mode 100644 index 00000000000..8fdcc75c6c4 --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/Predicates.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import java.util.function.Predicate; + +public final class Predicates { + + static final Predicate ALLOW_ALL = attributeKey -> true; + + private Predicates() {} + + @SuppressWarnings("SameParameterValue") + static Predicate startsWith(String prefix) { + return attributeKey -> attributeKey.startsWith(prefix); + } + + public static Predicate is(String value) { + return attributeKey -> attributeKey.equals(value); + } +} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java index 2d487aeda31..40febbb6469 100644 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusHttpServerTest.java @@ -6,47 +6,110 @@ package io.opentelemetry.exporter.prometheus; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.collect.ImmutableList; +import com.google.common.io.ByteStreams; +import com.google.protobuf.TextFormat; import com.linecorp.armeria.client.WebClient; -import com.linecorp.armeria.client.encoding.DecodingClient; +import com.linecorp.armeria.client.retry.RetryRule; +import com.linecorp.armeria.client.retry.RetryingClient; import com.linecorp.armeria.common.AggregatedHttpResponse; +import com.linecorp.armeria.common.HttpData; import com.linecorp.armeria.common.HttpHeaderNames; import com.linecorp.armeria.common.HttpMethod; import com.linecorp.armeria.common.HttpStatus; import com.linecorp.armeria.common.RequestHeaders; +import com.sun.net.httpserver.Authenticator; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpHandler; +import com.sun.net.httpserver.HttpPrincipal; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; import io.opentelemetry.sdk.resources.Resource; +import io.prometheus.metrics.exporter.httpserver.HTTPServer; +import io.prometheus.metrics.exporter.httpserver.MetricsHandler; +import io.prometheus.metrics.expositionformats.generated.Metrics; +import io.prometheus.metrics.model.registry.PrometheusRegistry; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledThreadPoolExecutor; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; +import java.util.stream.Stream; +import java.util.zip.GZIPInputStream; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.ValueSource; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class PrometheusHttpServerTest { - private static final MetricProducer metricProducer = PrometheusHttpServerTest::generateTestData; + private static final AtomicReference> metricData = new AtomicReference<>(); + @SuppressWarnings("NonFinalStaticField") static PrometheusHttpServer prometheusServer; + + @SuppressWarnings("NonFinalStaticField") static WebClient client; + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(Otel2PrometheusConverter.class); + @BeforeAll - static void setUp() { + static void beforeAll() { // Register the SDK metric producer with the prometheus reader. prometheusServer = PrometheusHttpServer.builder().setHost("localhost").setPort(0).build(); - prometheusServer.register(metricProducer); + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + + client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + } - client = WebClient.of("http://localhost:" + prometheusServer.getAddress().getPort()); + @BeforeEach + void beforeEach() { + metricData.set(generateTestData()); } @AfterAll @@ -54,6 +117,7 @@ static void tearDown() { prometheusServer.shutdown(); } + @SuppressWarnings("DataFlowIssue") @Test void invalidConfig() { assertThatThrownBy(() -> PrometheusHttpServer.builder().setPort(-1)) @@ -65,34 +129,98 @@ void invalidConfig() { assertThatThrownBy(() -> PrometheusHttpServer.builder().setHost("")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("host must not be empty"); + assertThatThrownBy(() -> PrometheusHttpServer.builder().setDefaultAggregationSelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("defaultAggregationSelector"); } - @ParameterizedTest - @ValueSource(strings = {"/metrics", "/"}) - void fetchPrometheus(String endpoint) { - AggregatedHttpResponse response = client.get(endpoint).aggregate().join(); + @Test + void fetchPrometheus() { + AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); assertThat(response.status()).isEqualTo(HttpStatus.OK); assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); assertThat(response.contentUtf8()) .isEqualTo( - "# TYPE grpc_name_total counter\n" - + "# HELP grpc_name_total long_description\n" - + "grpc_name_total{kp=\"vp\"} 5.0 0\n" - + "# TYPE http_name_total counter\n" - + "# HELP http_name_total double_description\n" - + "http_name_total{kp=\"vp\"} 3.5 0\n"); + "# HELP grpc_name_unit_total long_description\n" + + "# TYPE grpc_name_unit_total counter\n" + + "grpc_name_unit_total{kp=\"vp\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0\n" + + "# HELP http_name_unit_total double_description\n" + + "# TYPE http_name_unit_total counter\n" + + "http_name_unit_total{kp=\"vp\",otel_scope_name=\"http\",otel_scope_version=\"version\"} 3.5\n" + + "# TYPE target_info gauge\n" + + "target_info{kr=\"vr\"} 1\n"); } - @ParameterizedTest - @ValueSource(strings = {"/metrics", "/"}) - void fetchOpenMetrics(String endpoint) { + @Test + void fetch_ReusableMemoryMode() throws InterruptedException { + try (PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setMemoryMode(MemoryMode.REUSABLE_DATA) + .build()) { + AtomicBoolean collectInProgress = new AtomicBoolean(); + AtomicBoolean concurrentRead = new AtomicBoolean(); + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + if (!collectInProgress.compareAndSet(false, true)) { + concurrentRead.set(true); + } + Collection response = metricData.get(); + try { + Thread.sleep(1); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + if (!collectInProgress.compareAndSet(true, false)) { + concurrentRead.set(true); + } + return response; + } + }); + + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + // Spin up 4 threads calling /metrics simultaneously. If concurrent read happens, + // collectAllMetrics will set concurrentRead to true and the test will fail. + List threads = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + Thread thread = + new Thread(() -> { + for (int j = 0; j < 10; j++) { + AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + } + }); + thread.setDaemon(true); + thread.start(); + threads.add(thread); + } + + // Wait for threads to complete + for (Thread thread : threads) { + thread.join(); + } + + // Confirm no concurrent reads took place + assertThat(concurrentRead.get()).isFalse(); + } + } + + @Test + void fetchOpenMetrics() { AggregatedHttpResponse response = client .execute( RequestHeaders.of( HttpMethod.GET, - endpoint, + "/metrics", HttpHeaderNames.ACCEPT, "application/openmetrics-text")) .aggregate() @@ -102,53 +230,287 @@ void fetchOpenMetrics(String endpoint) { .isEqualTo("application/openmetrics-text; version=1.0.0; charset=utf-8"); assertThat(response.contentUtf8()) .isEqualTo( - "# TYPE grpc_name counter\n" - + "# HELP grpc_name long_description\n" - + "grpc_name_total{kp=\"vp\"} 5.0 0.000\n" - + "# TYPE http_name counter\n" - + "# HELP http_name double_description\n" - + "http_name_total{kp=\"vp\"} 3.5 0.000\n" + "# TYPE grpc_name_unit counter\n" + + "# UNIT grpc_name_unit unit\n" + + "# HELP grpc_name_unit long_description\n" + + "grpc_name_unit_total{kp=\"vp\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0\n" + + "# TYPE http_name_unit counter\n" + + "# UNIT http_name_unit unit\n" + + "# HELP http_name_unit double_description\n" + + "http_name_unit_total{kp=\"vp\",otel_scope_name=\"http\",otel_scope_version=\"version\"} 3.5\n" + + "# TYPE target info\n" + + "target_info{kr=\"vr\"} 1\n" + "# EOF\n"); } + @Test + void fetchOpenMetrics_translationStrategyEnablesOm2() { + try (PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setTranslationStrategy(TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES) + .build()) { + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + AggregatedHttpResponse response = + client + .execute( + RequestHeaders.of( + HttpMethod.GET, + "/metrics", + HttpHeaderNames.ACCEPT, + "application/openmetrics-text")) + .aggregate() + .join(); + + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo("application/openmetrics-text; version=1.0.0; charset=utf-8"); + assertThat(response.contentUtf8()) + .contains( + "grpc_name{kp=\"vp\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0") + .contains( + "http_name{kp=\"vp\",otel_scope_name=\"http\",otel_scope_version=\"version\"} 3.5") + .doesNotContain("grpc_name_unit_total") + .doesNotContain("http_name_unit_total"); + } + } + + @ParameterizedTest + @MethodSource("translationStrategyContentNegotiationArgs") + void fetchOpenMetrics_translationStrategyRespectsAcceptEscaping( + TranslationStrategy translationStrategy, + String acceptHeader, + String expectedLineFragment, + String unexpectedLineFragment) { + metricData.set(generateContentNegotiationTestData()); + try (PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setTranslationStrategy(translationStrategy) + .build()) { + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + AggregatedHttpResponse response = + client + .execute( + RequestHeaders.of( + HttpMethod.GET, "/metrics", HttpHeaderNames.ACCEPT, acceptHeader)) + .aggregate() + .join(); + + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo("application/openmetrics-text; version=1.0.0; charset=utf-8"); + assertThat(response.contentUtf8()) + .contains(expectedLineFragment) + .doesNotContain(unexpectedLineFragment); + } + } + + @Test + void fetchOpenMetrics_noTranslationPreservesRawInputNameWithUnit() { + metricData.set(generateContentNegotiationTestDataWithUnit()); + try (PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setTranslationStrategy(TranslationStrategy.NO_TRANSLATION) + .build()) { + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + AggregatedHttpResponse response = + client + .execute( + RequestHeaders.of( + HttpMethod.GET, + "/metrics", + HttpHeaderNames.ACCEPT, + "application/openmetrics-text; version=1.0.0; escaping=allow-utf-8")) + .aggregate() + .join(); + + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.contentUtf8()) + .contains("{\"metric.name\",otel_scope_name=\"scope\"} 1.0") + .doesNotContain("metric.name_bytes") + .doesNotContain("metric.name_total") + .doesNotContain("metric_name"); + } + } + + private static Stream translationStrategyContentNegotiationArgs() { + return Stream.of( + Arguments.argumentSet( + "no translation + underscores escaping", + TranslationStrategy.NO_TRANSLATION, + "application/openmetrics-text; version=1.0.0; escaping=underscores", + "metric_name{otel_scope_name=\"scope\"} 1.0", + "{\"metric.name\",otel_scope_name=\"scope\"} 1.0"), + Arguments.argumentSet( + "no translation + allow-utf-8 escaping", + TranslationStrategy.NO_TRANSLATION, + "application/openmetrics-text; version=1.0.0; escaping=allow-utf-8", + "{\"metric.name\",otel_scope_name=\"scope\"} 1.0", + "metric_name{otel_scope_name=\"scope\"} 1.0"), + Arguments.argumentSet( + "underscore escaping + allow-utf-8 accept", + TranslationStrategy.UNDERSCORE_ESCAPING_WITH_SUFFIXES, + "application/openmetrics-text; version=1.0.0; escaping=allow-utf-8", + "metric_name_total{otel_scope_name=\"scope\"} 1.0", + "{\"metric.name\",otel_scope_name=\"scope\"} 1.0"), + Arguments.argumentSet( + "underscore escaping without suffixes + allow-utf-8 accept", + TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES, + "application/openmetrics-text; version=1.0.0; escaping=allow-utf-8", + "metric_name{otel_scope_name=\"scope\"} 1.0", + "{\"metric.name\",otel_scope_name=\"scope\"} 1.0")); + } + + @Test + void fetchProtobuf() { + AggregatedHttpResponse response = + client + .execute( + RequestHeaders.of( + HttpMethod.GET, + "/metrics", + HttpHeaderNames.ACCEPT, + "Accept: application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily")) + .aggregate() + .join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo( + "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited"); + // don't decode the protobuf, just verify it doesn't throw an exception + } + + @SuppressWarnings("ConcatenationWithEmptyString") @Test void fetchFiltered() { AggregatedHttpResponse response = - client.get("/?name[]=grpc_name_total&name[]=bears_total").aggregate().join(); + client + .get("/metrics?name[]=grpc_name_unit_total&name[]=bears_total&name[]=target_info") + .aggregate() + .join(); assertThat(response.status()).isEqualTo(HttpStatus.OK); assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); assertThat(response.contentUtf8()) .isEqualTo( - "# TYPE grpc_name_total counter\n" - + "# HELP grpc_name_total long_description\n" - + "grpc_name_total{kp=\"vp\"} 5.0 0\n"); + "" + + "# HELP grpc_name_unit_total long_description\n" + + "# TYPE grpc_name_unit_total counter\n" + + "grpc_name_unit_total{kp=\"vp\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0\n" + + "# TYPE target_info gauge\n" + + "target_info{kr=\"vr\"} 1\n"); } @Test - void fetchPrometheusCompressed() { + void fetchOverrideDefaultHandler() { + PrometheusRegistry registry = new PrometheusRegistry(); + try (PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setPrometheusRegistry(registry) + // Set the default handler to serve metrics on /** + .setDefaultHandler(new MetricsHandler(registry)) + .build()) { + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + // Fetch metrics from / instead of /metrics + AggregatedHttpResponse response = client.get("/").aggregate().join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); + assertThat(response.contentUtf8()) + .isEqualTo( + "# HELP grpc_name_unit_total long_description\n" + + "# TYPE grpc_name_unit_total counter\n" + + "grpc_name_unit_total{kp=\"vp\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0\n" + + "# HELP http_name_unit_total double_description\n" + + "# TYPE http_name_unit_total counter\n" + + "http_name_unit_total{kp=\"vp\",otel_scope_name=\"http\",otel_scope_version=\"version\"} 3.5\n" + + "# TYPE target_info gauge\n" + + "target_info{kr=\"vr\"} 1\n"); + } + } + + @SuppressWarnings("resource") + @Test + void fetchPrometheusCompressed() throws IOException { WebClient client = WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) - .decorator(DecodingClient.newDecorator()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .addHeader(HttpHeaderNames.ACCEPT_ENCODING, "gzip") .build(); - AggregatedHttpResponse response = client.get("/").aggregate().join(); + AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); assertThat(response.status()).isEqualTo(HttpStatus.OK); assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); assertThat(response.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("gzip"); - assertThat(response.contentUtf8()) + GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(response.content().array())); + String content = new String(ByteStreams.toByteArray(gis), StandardCharsets.UTF_8); + assertThat(content) .isEqualTo( - "# TYPE grpc_name_total counter\n" - + "# HELP grpc_name_total long_description\n" - + "grpc_name_total{kp=\"vp\"} 5.0 0\n" - + "# TYPE http_name_total counter\n" - + "# HELP http_name_total double_description\n" - + "http_name_total{kp=\"vp\"} 3.5 0\n"); + "# HELP grpc_name_unit_total long_description\n" + + "# TYPE grpc_name_unit_total counter\n" + + "grpc_name_unit_total{kp=\"vp\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0\n" + + "# HELP http_name_unit_total double_description\n" + + "# TYPE http_name_unit_total counter\n" + + "http_name_unit_total{kp=\"vp\",otel_scope_name=\"http\",otel_scope_version=\"version\"} 3.5\n" + + "# TYPE target_info gauge\n" + + "target_info{kr=\"vr\"} 1\n"); } + @SuppressWarnings("resource") @Test void fetchHead() { - AggregatedHttpResponse response = client.head("/").aggregate().join(); + AggregatedHttpResponse response = client.head("/metrics").aggregate().join(); assertThat(response.status()).isEqualTo(HttpStatus.OK); assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); @@ -160,23 +522,165 @@ void fetchHealth() { AggregatedHttpResponse response = client.get("/-/healthy").aggregate().join(); assertThat(response.status()).isEqualTo(HttpStatus.OK); - assertThat(response.contentUtf8()).isEqualTo("Exporter is Healthy."); + assertThat(response.contentUtf8()).isEqualTo("Exporter is healthy.\n"); + } + + @Test + @SuppressLogger(PrometheusHttpServer.class) + @SuppressLogger(Otel2PrometheusConverter.class) + void fetch_DuplicateMetrics() { + Resource resource = Resource.create(Attributes.of(stringKey("kr"), "vr")); + metricData.set( + ImmutableList.of( + ImmutableMetricData.createLongSum( + resource, + InstrumentationScopeInfo.create("scope1"), + "foo", + "description1", + "unit", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create(123, 456, Attributes.empty(), 1)))), + // A counter with same name as foo but with different scope, description, unit + ImmutableMetricData.createLongSum( + resource, + InstrumentationScopeInfo.create("scope2"), + "foo", + "description2", + "unit", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create(123, 456, Attributes.empty(), 2)))), + // A gauge whose name conflicts with foo counter's name after the "_total" suffix is + // added + ImmutableMetricData.createLongGauge( + resource, + InstrumentationScopeInfo.create("scope3"), + "foo_unit_total", + "unused", + "", + ImmutableGaugeData.create( + Collections.singletonList( + ImmutableLongPointData.create(123, 456, Attributes.empty(), 3)))))); + + AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); + assertThat(response.contentUtf8()) + .isEqualTo( + "# TYPE foo_unit_total counter\n" + + "foo_unit_total{otel_scope_name=\"scope1\"} 1.0\n" + + "foo_unit_total{otel_scope_name=\"scope2\"} 2.0\n" + + "# TYPE target_info gauge\n" + + "target_info{kr=\"vr\"} 1\n"); + + // Validate conflict warning message + assertThat(logs.getEvents()).hasSize(1); + logs.assertContains( + "Conflicting metrics: Multiple metrics with name foo_unit but different units found. Dropping the one with unit null."); } @Test void stringRepresentation() { assertThat(prometheusServer.toString()) - .isEqualTo("PrometheusHttpServer{address=" + prometheusServer.getAddress() + "}"); + .isEqualTo( + "PrometheusHttpServer{" + + "host=localhost," + + "port=0," + + "metricReader=PrometheusMetricReader{otelScopeLabelsEnabled=true,targetInfoMetricEnabled=true,translationStrategy=UNDERSCORE_ESCAPING_WITH_SUFFIXES,allowedResourceAttributesFilter=null}," + + "memoryMode=REUSABLE_DATA," + + "defaultAggregationSelector=DefaultAggregationSelector{COUNTER=default, UP_DOWN_COUNTER=default, HISTOGRAM=default, OBSERVABLE_COUNTER=default, OBSERVABLE_UP_DOWN_COUNTER=default, OBSERVABLE_GAUGE=default, GAUGE=default}" + + "}"); } - private static ImmutableList generateTestData() { + @Test + void defaultExecutor() { + assertThat(prometheusServer) + .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) + .extracting("executorService", as(InstanceOfAssertFactories.type(ThreadPoolExecutor.class))) + .satisfies(executor -> assertThat(executor.getCorePoolSize()).isEqualTo(1)); + } + + @Test + void customExecutor() throws IOException { + ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool(10); + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + try (PrometheusHttpServer server = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(port) + // Memory mode must be IMMUTABLE_DATA to set custom executor + .setMemoryMode(MemoryMode.IMMUTABLE_DATA) + .setExecutor(scheduledExecutor) + .build()) { + assertThat(server) + .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) + .extracting( + "executorService", + as(InstanceOfAssertFactories.type(ScheduledThreadPoolExecutor.class))) + .satisfies(executor -> assertThat(executor).isSameAs(scheduledExecutor)); + } + } + + @Test + void addResourceAttributesWorks() { + WebClient testClient; + try (PrometheusHttpServer testPrometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setAllowedResourceAttributesFilter(Predicates.ALLOW_ALL) + .build()) { + testPrometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + + testClient = + WebClient.builder("http://localhost:" + testPrometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + AggregatedHttpResponse response = testClient.get("/metrics").aggregate().join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo("text/plain; version=0.0.4; charset=utf-8"); + assertThat(response.contentUtf8()) + .isEqualTo( + "# HELP grpc_name_unit_total long_description\n" + + "# TYPE grpc_name_unit_total counter\n" + + // Note the added resource attributes as labels + + "grpc_name_unit_total{kp=\"vp\",kr=\"vr\",otel_scope_name=\"grpc\",otel_scope_version=\"version\"} 5.0\n" + + "# HELP http_name_unit_total double_description\n" + + "# TYPE http_name_unit_total counter\n" + + // Note the added resource attributes as labels + + "http_name_unit_total{kp=\"vp\",kr=\"vr\",otel_scope_name=\"http\",otel_scope_version=\"version\"} 3.5\n" + + "# TYPE target_info gauge\n" + + "target_info{kr=\"vr\"} 1\n"); + } + } + + private static List generateTestData() { return ImmutableList.of( ImmutableMetricData.createLongSum( Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("grpc", "version", null), + InstrumentationScopeInfo.builder("grpc").setVersion("version").build(), "grpc.name", "long_description", - "1", + "unit", ImmutableSumData.create( /* isMonotonic= */ true, AggregationTemporality.CUMULATIVE, @@ -185,10 +689,10 @@ private static ImmutableList generateTestData() { 123, 456, Attributes.of(stringKey("kp"), "vp"), 5)))), ImmutableMetricData.createDoubleSum( Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("http", "version", null), + InstrumentationScopeInfo.builder("http").setVersion("version").build(), "http.name", "double_description", - "1", + "unit", ImmutableSumData.create( /* isMonotonic= */ true, AggregationTemporality.CUMULATIVE, @@ -196,4 +700,192 @@ private static ImmutableList generateTestData() { ImmutableDoublePointData.create( 123, 456, Attributes.of(stringKey("kp"), "vp"), 3.5))))); } + + private static List generateContentNegotiationTestData() { + return Collections.singletonList( + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("scope"), + "metric.name", + "description", + "", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create(123, 456, Attributes.empty(), 1))))); + } + + private static List generateContentNegotiationTestDataWithUnit() { + return Collections.singletonList( + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("scope"), + "metric.name", + "description", + "By", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Collections.singletonList( + ImmutableLongPointData.create(123, 456, Attributes.empty(), 1))))); + } + + @Test + void toBuilder() { + PrometheusHttpServerBuilder builder = PrometheusHttpServer.builder(); + builder.setHost("localhost"); + builder.setPort(1234); + + Predicate resourceAttributesFilter = s -> false; + builder.setAllowedResourceAttributesFilter(resourceAttributesFilter); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + builder.setExecutor(executor).setMemoryMode(MemoryMode.IMMUTABLE_DATA); + + PrometheusRegistry prometheusRegistry = new PrometheusRegistry(); + builder.setPrometheusRegistry(prometheusRegistry); + + Authenticator authenticator = + new Authenticator() { + @Override + public Result authenticate(HttpExchange exchange) { + return new Success(new HttpPrincipal("anonymous", "public")); + } + }; + builder.setAuthenticator(authenticator); + + HttpHandler defaultHandler = exchange -> {}; + builder.setDefaultHandler(defaultHandler); + + PrometheusHttpServer httpServer = builder.build(); + PrometheusHttpServerBuilder fromOriginalBuilder = httpServer.toBuilder(); + httpServer.close(); + assertThat(fromOriginalBuilder) + .isInstanceOf(PrometheusHttpServerBuilder.class) + .hasFieldOrPropertyWithValue("host", "localhost") + .hasFieldOrPropertyWithValue("port", 1234) + .hasFieldOrPropertyWithValue("executor", executor) + .hasFieldOrPropertyWithValue("prometheusRegistry", prometheusRegistry) + .hasFieldOrPropertyWithValue("authenticator", authenticator) + .hasFieldOrPropertyWithValue("defaultHandler", defaultHandler) + .extracting("metricReaderBuilder") + .usingRecursiveComparison() + .isEqualTo( + PrometheusMetricReader.builder() + .setAllowedResourceAttributesFilter(resourceAttributesFilter)); + } + + /** + * Set the default histogram aggregation to be {@link + * Aggregation#base2ExponentialBucketHistogram()}. In order to validate that exponential + * histograms are produced, we request protobuf encoded metrics when scraping since the prometheus + * text format does not support native histograms. We parse the binary content protobuf payload to + * the protobuf java bindings, and assert against the string representation. + */ + @Test + @SuppressWarnings("NonCanonicalType") // stable Metrics class extends versioned protobuf class + void histogramDefaultBase2ExponentialHistogram() throws IOException { + PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.base2ExponentialBucketHistogram())) + .build(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(prometheusServer).build()) { + DoubleHistogram histogram = meterProvider.get("meter").histogramBuilder("histogram").build(); + histogram.record(1.0); + + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + // Request protobuf binary encoding, which is required for the prometheus native + // histogram format + .addHeader( + "Accept", + "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily") + .build(); + AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); + assertThat(response.status()).isEqualTo(HttpStatus.OK); + assertThat(response.headers().get(HttpHeaderNames.CONTENT_TYPE)) + .isEqualTo( + "application/vnd.google.protobuf; proto=io.prometheus.client.MetricFamily; encoding=delimited"); + // Parse the data to Metrics.MetricFamily protobuf java binding and assert against the string + // representation + try (HttpData data = response.content()) { + Metrics.MetricFamily metricFamily = + Metrics.MetricFamily.parseDelimitedFrom(data.toInputStream()); + String s = TextFormat.printer().printToString(metricFamily); + assertThat(s) + .isEqualTo( + "name: \"histogram\"\n" + + "help: \"\"\n" + + "type: HISTOGRAM\n" + + "metric {\n" + + " label {\n" + + " name: \"otel_scope_name\"\n" + + " value: \"meter\"\n" + + " }\n" + + " histogram {\n" + + " sample_count: 1\n" + + " sample_sum: 1.0\n" + + " schema: 8\n" + + " zero_threshold: 0.0\n" + + " zero_count: 0\n" + + " positive_span {\n" + + " offset: 0\n" + + " length: 1\n" + + " }\n" + + " positive_delta: 1\n" + + " }\n" + + "}\n"); + } + } finally { + prometheusServer.shutdown(); + } + } + + @Test + void authenticator() { + // given + try (PrometheusHttpServer prometheusServer = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(0) + .setAuthenticator( + new Authenticator() { + @Override + public Result authenticate(HttpExchange exchange) { + if ("/metrics".equals(exchange.getRequestURI().getPath())) { + return new Failure(401); + } else { + return new Success(new HttpPrincipal("anonymous", "public")); + } + } + }) + .build()) { + prometheusServer.register( + new CollectionRegistration() { + @Override + public Collection collectAllMetrics() { + return metricData.get(); + } + }); + WebClient client = + WebClient.builder("http://localhost:" + prometheusServer.getAddress().getPort()) + .decorator(RetryingClient.newDecorator(RetryRule.failsafe())) + .build(); + + // when + AggregatedHttpResponse metricsResponse = client.get("/metrics").aggregate().join(); + AggregatedHttpResponse defaultResponse = client.get("/").aggregate().join(); + + // then + assertThat(metricsResponse.status()).isEqualTo(HttpStatus.UNAUTHORIZED); + assertThat(defaultResponse.status()).isEqualTo(HttpStatus.OK); + } + } } diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java new file mode 100644 index 00000000000..6e309325890 --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusIntegrationTest.java @@ -0,0 +1,135 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; +import static org.testcontainers.Testcontainers.exposeHostPorts; + +import com.fasterxml.jackson.core.TreeNode; +import com.fasterxml.jackson.jr.ob.JSON; +import com.fasterxml.jackson.jr.stree.JrSimpleTreeExtension; +import com.fasterxml.jackson.jr.stree.JrsString; +import com.google.common.io.Resources; +import com.linecorp.armeria.client.WebClient; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.LoggerFactory; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.output.Slf4jLogConsumer; +import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.junit.jupiter.Testcontainers; +import org.testcontainers.utility.MountableFile; + +@Testcontainers(disabledWithoutDocker = true) +class PrometheusIntegrationTest { + + @SuppressWarnings("NonFinalStaticField") + private static SdkMeterProvider meterProvider; + + @SuppressWarnings("NonFinalStaticField") + private static GenericContainer prometheus; + + @BeforeAll + static void setUp(@TempDir Path tempDir) throws Exception { + PrometheusHttpServer prometheusHttpServer = PrometheusHttpServer.builder().setPort(0).build(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(prometheusHttpServer).build(); + int port = prometheusHttpServer.getAddress().getPort(); + + exposeHostPorts(port); + + String promConfigTemplate = + Resources.toString(Resources.getResource("prom.yml"), StandardCharsets.UTF_8); + Path promConfig = tempDir.resolve("prom.yml"); + Files.write( + promConfig, + promConfigTemplate + .replace("{{APP_PORT}}", String.valueOf(port)) + .getBytes(StandardCharsets.UTF_8)); + + prometheus = + new GenericContainer<>("prom/prometheus:v2.30.3") + .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("prometheus"))) + .withExposedPorts(9090) + .waitingFor(Wait.forHttp("/-/ready")) + .withCopyFileToContainer(MountableFile.forHostPath(promConfig), "/etc/prom.yml") + .withCommand("--config.file", "/etc/prom.yml"); + prometheus.start(); + } + + @AfterAll + static void tearDown() { + prometheus.stop(); + meterProvider.shutdown(); + } + + @Test + void endToEnd() { + Meter meter = meterProvider.meterBuilder("test").build(); + + meter + .counterBuilder("requests") + .build() + .add(3, Attributes.builder().put("animal", "bear").build()); + meter + .gaugeBuilder("lives") + .buildWithCallback( + result -> result.record(9, Attributes.builder().put("animal", "cat").build())); + + WebClient promClient = WebClient.of("http://localhost:" + prometheus.getMappedPort(9090)); + JSON json = JSON.builder().register(new JrSimpleTreeExtension()).build(); + await() + .untilAsserted(() -> { + TreeNode response = + json.treeFrom( + promClient + .get("/api/v1/query?query=requests_total") + .aggregate() + .join() + .contentUtf8()); + assertThat(response.get("status")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); + TreeNode result = response.get("data").get("result").get(0); + assertThat(result).isNotNull(); + assertThat(result.get("metric").get("__name__")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("requests_total")); + assertThat(result.get("metric").get("animal")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("bear")); + assertThat(result.get("value").get(1)) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("3")); + + response = + json.treeFrom( + promClient.get("/api/v1/query?query=lives").aggregate().join().contentUtf8()); + assertThat(response.get("status")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("success")); + result = response.get("data").get("result").get(0); + assertThat(result).isNotNull(); + assertThat(result.get("metric").get("__name__")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("lives")); + assertThat(result.get("metric").get("animal")) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("cat")); + assertThat(result.get("value").get(1)) + .isInstanceOfSatisfying( + JrsString.class, s -> assertThat(s.getValue()).isEqualTo("9")); + }); + } +} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java new file mode 100644 index 00000000000..55c9b943d4b --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusMetricReaderTest.java @@ -0,0 +1,1143 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.prometheus.metrics.expositionformats.OpenMetricsTextFormatWriter; +import io.prometheus.metrics.expositionformats.PrometheusProtobufWriter; +import io.prometheus.metrics.model.snapshots.HistogramSnapshot; +import io.prometheus.metrics.model.snapshots.HistogramSnapshot.HistogramDataPointSnapshot; +import io.prometheus.metrics.model.snapshots.MetricSnapshots; +import io.prometheus.metrics.model.snapshots.NativeHistogramBuckets; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +@SuppressWarnings({"resource", "ConcatenationWithEmptyString"}) +class PrometheusMetricReaderTest { + + private final TestClock testClock = TestClock.create(); + private String createdTimestamp; + private PrometheusMetricReader reader; + private Meter meter; + private Tracer tracer; + + @BeforeEach + void setUp() { + this.testClock.setTime(Instant.ofEpochMilli((System.currentTimeMillis() / 100) * 100)); + this.createdTimestamp = convertTimestamp(testClock.now()); + this.reader = PrometheusMetricReader.create(); + this.meter = + SdkMeterProvider.builder() + .setClock(testClock) + .registerMetricReader(this.reader) + .setResource( + Resource.getDefault().toBuilder().put("telemetry.sdk.version", "1.x.x").build()) + .registerView( + InstrumentSelector.builder().setName("my.exponential.histogram").build(), + View.builder() + .setAggregation(Aggregation.base2ExponentialBucketHistogram()) + .build()) + .build() + .meterBuilder("test") + .build(); + this.tracer = + SdkTracerProvider.builder() + .setClock(testClock) + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build() + .tracerBuilder("test") + .build(); + } + + @Test + void longCounterComplete() throws IOException { + LongCounter counter = + meter + .counterBuilder("requests.size") + .setDescription("some help text") + .setUnit("By") + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + counter.add(3, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + counter.add(2, Attributes.builder().put("animal", "mouse").build()); + } finally { + span2.end(); + } + assertCounterComplete(reader.collect(), span1, span2); + } + + @Test + void doubleCounterComplete() throws IOException { + DoubleCounter counter = + meter + .counterBuilder("requests.size") + .setDescription("some help text") + .setUnit("By") + .ofDoubles() + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + counter.add(3.0, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + counter.add(2.0, Attributes.builder().put("animal", "mouse").build()); + } finally { + span2.end(); + } + assertCounterComplete(reader.collect(), span1, span2); + } + + private void assertCounterComplete(MetricSnapshots snapshots, Span span1, Span span2) + throws IOException { + String expected = + "" + + "# TYPE requests_size_bytes counter\n" + + "# UNIT requests_size_bytes bytes\n" + + "# HELP requests_size_bytes some help text\n" + + "requests_size_bytes_total{animal=\"bear\",otel_scope_name=\"test\"} 3.0 # {span_id=\"" + + span1.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span1.getSpanContext().getTraceId() + + "\"} 3.0 \n" + + "requests_size_bytes_created{animal=\"bear\",otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "requests_size_bytes_total{animal=\"mouse\",otel_scope_name=\"test\"} 2.0 # {span_id=\"" + + span2.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span2.getSpanContext().getTraceId() + + "\"} 2.0 \n" + + "requests_size_bytes_created{animal=\"mouse\",otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertMatches(expected, toOpenMetrics(snapshots)); + } + + @Test + void longCounterMinimal() throws IOException { + LongCounter counter = meter.counterBuilder("requests").build(); + counter.add(2); + assertCounterMinimal(reader.collect()); + } + + @Test + void doubleCounterMinimal() throws IOException { + DoubleCounter counter = meter.counterBuilder("requests").ofDoubles().build(); + counter.add(2.0); + assertCounterMinimal(reader.collect()); + } + + private void assertCounterMinimal(MetricSnapshots snapshots) throws IOException { + String expected = + "" + + "# TYPE requests counter\n" + + "requests_total{otel_scope_name=\"test\"} 2.0\n" + + "requests_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(snapshots)).isEqualTo(expected); + } + + @Test + void longUpDownCounterComplete() throws IOException { + LongUpDownCounter counter = + meter + .upDownCounterBuilder("queue.size") + .setDescription("some help text") + .setUnit("By") + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + counter.add(3, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + counter.add(2, Attributes.builder().put("animal", "mouse").build()); + } finally { + span2.end(); + } + assertUpDownCounterComplete(reader.collect(), span1, span2); + } + + @Test + void doubleUpDownCounterComplete() throws IOException { + DoubleUpDownCounter counter = + meter + .upDownCounterBuilder("queue.size") + .setDescription("some help text") + .setUnit("By") + .ofDoubles() + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + counter.add(3.0, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + counter.add(2.0, Attributes.builder().put("animal", "mouse").build()); + } finally { + span2.end(); + } + assertUpDownCounterComplete(reader.collect(), span1, span2); + } + + private static void assertUpDownCounterComplete(MetricSnapshots snapshots, Span span1, Span span2) + throws IOException { + String expected = + "" + + "# TYPE queue_size_bytes gauge\n" + + "# UNIT queue_size_bytes bytes\n" + + "# HELP queue_size_bytes some help text\n" + + "queue_size_bytes{animal=\"bear\",otel_scope_name=\"test\"} 3.0 # {span_id=\"" + + span1.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span1.getSpanContext().getTraceId() + + "\"} 3.0 \n" + + "queue_size_bytes{animal=\"mouse\",otel_scope_name=\"test\"} 2.0 # {span_id=\"" + + span2.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span2.getSpanContext().getTraceId() + + "\"} 2.0 \n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertMatches(expected, toOpenMetrics(snapshots)); + } + + @Test + void longUpDownCounterMinimal() throws IOException { + LongUpDownCounter counter = meter.upDownCounterBuilder("users.active").build(); + counter.add(27); + assertUpDownCounterMinimal(reader.collect()); + } + + @Test + void doubleUpDownCounterMinimal() throws IOException { + DoubleUpDownCounter counter = meter.upDownCounterBuilder("users.active").ofDoubles().build(); + counter.add(27.0); + assertUpDownCounterMinimal(reader.collect()); + } + + private static void assertUpDownCounterMinimal(MetricSnapshots snapshots) throws IOException { + String expected = + "" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# TYPE users_active gauge\n" + + "users_active{otel_scope_name=\"test\"} 27.0\n" + + "# EOF\n"; + assertThat(toOpenMetrics(snapshots)).isEqualTo(expected); + } + + @Test + void longGaugeComplete() throws IOException { + meter + .gaugeBuilder("temperature") + .setUnit("Cel") + .setDescription("help text") + .ofLongs() + .buildWithCallback(m -> { + m.record(23, Attributes.builder().put("location", "inside").build()); + m.record(17, Attributes.builder().put("location", "outside").build()); + }); + assertGaugeComplete(reader.collect()); + } + + @Test + void doubleGaugeComplete() throws IOException { + meter + .gaugeBuilder("temperature") + .setUnit("Cel") + .setDescription("help text") + .buildWithCallback(m -> { + m.record(23.0, Attributes.builder().put("location", "inside").build()); + m.record(17.0, Attributes.builder().put("location", "outside").build()); + }); + assertGaugeComplete(reader.collect()); + } + + private static void assertGaugeComplete(MetricSnapshots snapshots) throws IOException { + String expected = + "" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# TYPE temperature_celsius gauge\n" + + "# UNIT temperature_celsius celsius\n" + + "# HELP temperature_celsius help text\n" + + "temperature_celsius{location=\"inside\",otel_scope_name=\"test\"} 23.0\n" + + "temperature_celsius{location=\"outside\",otel_scope_name=\"test\"} 17.0\n" + + "# EOF\n"; + assertThat(toOpenMetrics(snapshots)).isEqualTo(expected); + } + + @Test + void longGaugeMinimal() throws IOException { + meter.gaugeBuilder("my_gauge").ofLongs().buildWithCallback(m -> m.record(2)); + assertGaugeMinimal(reader.collect()); + } + + @Test + void doubleGaugeMinimal() throws IOException { + meter.gaugeBuilder("my_gauge").buildWithCallback(m -> m.record(2.0)); + assertGaugeMinimal(reader.collect()); + } + + private static void assertGaugeMinimal(MetricSnapshots snapshots) throws IOException { + String expected = + "" + + "# TYPE my_gauge gauge\n" + + "my_gauge{otel_scope_name=\"test\"} 2.0\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(snapshots)).isEqualTo(expected); + } + + @Test + void longHistogramComplete() throws IOException { + LongHistogram histogram = + meter + .histogramBuilder("request.size") + .setDescription("some help text") + .setUnit("By") + .ofLongs() + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + histogram.record(173, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + histogram.record(400, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span3 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span3.makeCurrent()) { + histogram.record(204, Attributes.builder().put("animal", "mouse").build()); + } finally { + span3.end(); + } + assertHistogramComplete(reader.collect(), span1, span2, span3); + } + + @Test + void doubleHistogramComplete() throws IOException { + DoubleHistogram histogram = + meter + .histogramBuilder("request.size") + .setDescription("some help text") + .setUnit("By") + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + histogram.record(173.0, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + histogram.record(400.0, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + Span span3 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span3.makeCurrent()) { + histogram.record(204.0, Attributes.builder().put("animal", "mouse").build()); + } finally { + span3.end(); + } + assertHistogramComplete(reader.collect(), span1, span2, span3); + } + + private void assertHistogramComplete( + MetricSnapshots snapshots, Span span1, Span span2, Span span3) throws IOException { + String expected = + "" + + "# TYPE request_size_bytes histogram\n" + + "# UNIT request_size_bytes bytes\n" + + "# HELP request_size_bytes some help text\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"0.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"5.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"10.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"25.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"50.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"75.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"100.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"250.0\"} 1 # {span_id=\"" + + span1.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span1.getSpanContext().getTraceId() + + "\"} 173.0 \n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"500.0\"} 2 # {span_id=\"" + + span2.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span2.getSpanContext().getTraceId() + + "\"} 400.0 \n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"750.0\"} 2\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"1000.0\"} 2\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"2500.0\"} 2\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"5000.0\"} 2\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"7500.0\"} 2\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"10000.0\"} 2\n" + + "request_size_bytes_bucket{animal=\"bear\",otel_scope_name=\"test\",le=\"+Inf\"} 2\n" + + "request_size_bytes_count{animal=\"bear\",otel_scope_name=\"test\"} 2 # {span_id=\"" + + "" + + "\",trace_id=\"" + + "" + + "\"} \n" + + "request_size_bytes_sum{animal=\"bear\",otel_scope_name=\"test\"} 573.0\n" + + "request_size_bytes_created{animal=\"bear\",otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"0.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"5.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"10.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"25.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"50.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"75.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"100.0\"} 0\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"250.0\"} 1 # {span_id=\"" + + span3.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span3.getSpanContext().getTraceId() + + "\"} 204.0 \n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"500.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"750.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"1000.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"2500.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"5000.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"7500.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"10000.0\"} 1\n" + + "request_size_bytes_bucket{animal=\"mouse\",otel_scope_name=\"test\",le=\"+Inf\"} 1\n" + + "request_size_bytes_count{animal=\"mouse\",otel_scope_name=\"test\"} 1 # {span_id=\"" + + span3.getSpanContext().getSpanId() + + "\",trace_id=\"" + + span3.getSpanContext().getTraceId() + + "\"} 204.0 \n" + + "request_size_bytes_sum{animal=\"mouse\",otel_scope_name=\"test\"} 204.0\n" + + "request_size_bytes_created{animal=\"mouse\",otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertMatches(expected, toOpenMetrics(snapshots)); + } + + @Test + void longHistogramMinimal() throws IOException { + LongHistogram histogram = meter.histogramBuilder("request.size").ofLongs().build(); + histogram.record(173); + histogram.record(173); + histogram.record(100_000); + assertHistogramMinimal(reader.collect()); + } + + @Test + void doubleHistogramMinimal() throws IOException { + DoubleHistogram histogram = meter.histogramBuilder("request.size").build(); + histogram.record(173.0); + histogram.record(173.0); + histogram.record(100_000.0); + assertHistogramMinimal(reader.collect()); + } + + private void assertHistogramMinimal(MetricSnapshots snapshots) throws IOException { + String expected = + "" + + "# TYPE request_size histogram\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"0.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"5.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"10.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"25.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"50.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"75.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"100.0\"} 0\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"250.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"500.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"750.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"1000.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"2500.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"5000.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"7500.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"10000.0\"} 2\n" + + "request_size_bucket{otel_scope_name=\"test\",le=\"+Inf\"} 3\n" + + "request_size_count{otel_scope_name=\"test\"} 3\n" + + "request_size_sum{otel_scope_name=\"test\"} 100346.0\n" + + "request_size_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(snapshots)).isEqualTo(expected); + } + + @Test + @Disabled("disabled until #6010 is fixed") + void exponentialLongHistogramComplete() { + LongHistogram histogram = + meter + .histogramBuilder("my.exponential.histogram") + .setDescription("some help text") + .setUnit("By") + .ofLongs() + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + histogram.record(7, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + histogram.record(0, Attributes.builder().put("animal", "bear").build()); + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + histogram.record(3, Attributes.builder().put("animal", "mouse").build()); + } finally { + span2.end(); + } + assertExponentialHistogramComplete(reader.collect(), span1, span2); + } + + @Test + void exponentialDoubleHistogramComplete() { + DoubleHistogram histogram = + meter + .histogramBuilder("my.exponential.histogram") + .setDescription("some help text") + .setUnit("By") + .build(); + Span span1 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span1.makeCurrent()) { + histogram.record(7.0, Attributes.builder().put("animal", "bear").build()); + } finally { + span1.end(); + } + histogram.record(0.0, Attributes.builder().put("animal", "bear").build()); + Span span2 = tracer.spanBuilder("test").startSpan(); + try (Scope ignored = span2.makeCurrent()) { + histogram.record(3.0, Attributes.builder().put("animal", "mouse").build()); + } finally { + span2.end(); + } + assertExponentialHistogramComplete(reader.collect(), span1, span2); + } + + private static void assertExponentialHistogramComplete( + MetricSnapshots snapshots, Span span1, Span span2) { + String expected = + "" + + "name: \"my_exponential_histogram_bytes\"\n" + + "help: \"some help text\"\n" + + "type: HISTOGRAM\n" + + "metric {\n" + + " label {\n" + + " name: \"animal\"\n" + + " value: \"bear\"\n" + + " }\n" + + " label {\n" + + " name: \"otel_scope_name\"\n" + + " value: \"test\"\n" + + " }\n" + + " histogram {\n" + + " sample_count: 2\n" + + " sample_sum: 7.0\n" + + " bucket {\n" + + " cumulative_count: 2\n" + + " upper_bound: Infinity\n" + + " exemplar {\n" + + " label {\n" + + " name: \"span_id\"\n" + + " value: \"" + + span1.getSpanContext().getSpanId() + + "\"\n" + + " }\n" + + " label {\n" + + " name: \"trace_id\"\n" + + " value: \"" + + span1.getSpanContext().getTraceId() + + "\"\n" + + " }\n" + + " value: 7.0\n" + + " timestamp {\n" + + " seconds: \n" + + " \n" + + " }\n" + + " }\n" + + " }\n" + + " schema: 8\n" + + " zero_threshold: 0.0\n" + + " zero_count: 1\n" + + " positive_span {\n" + + " offset: 719\n" + + " length: 1\n" + + " }\n" + + " positive_delta: 1\n" + + " }\n" + + "}\n" + + "metric {\n" + + " label {\n" + + " name: \"animal\"\n" + + " value: \"mouse\"\n" + + " }\n" + + " label {\n" + + " name: \"otel_scope_name\"\n" + + " value: \"test\"\n" + + " }\n" + + " histogram {\n" + + " sample_count: 1\n" + + " sample_sum: 3.0\n" + + " bucket {\n" + + " cumulative_count: 1\n" + + " upper_bound: Infinity\n" + + " exemplar {\n" + + " label {\n" + + " name: \"span_id\"\n" + + " value: \"" + + span2.getSpanContext().getSpanId() + + "\"\n" + + " }\n" + + " label {\n" + + " name: \"trace_id\"\n" + + " value: \"" + + span2.getSpanContext().getTraceId() + + "\"\n" + + " }\n" + + " value: 3.0\n" + + " timestamp {\n" + + " seconds: \n" + + " \n" + + " }\n" + + " }\n" + + " }\n" + + " schema: 8\n" + + " zero_threshold: 0.0\n" + + " zero_count: 0\n" + + " positive_span {\n" + + " offset: 406\n" + + " length: 1\n" + + " }\n" + + " positive_delta: 1\n" + + " }\n" + + "}\n" + + "name: \"target_info\"\n" + + "type: GAUGE\n" + + "metric {\n" + + " label {\n" + + " name: \"service_name\"\n" + + " value: \"unknown_service:java\"\n" + + " }\n" + + " label {\n" + + " name: \"telemetry_sdk_language\"\n" + + " value: \"java\"\n" + + " }\n" + + " label {\n" + + " name: \"telemetry_sdk_name\"\n" + + " value: \"opentelemetry\"\n" + + " }\n" + + " label {\n" + + " name: \"telemetry_sdk_version\"\n" + + " value: \"1.x.x\"\n" + + " }\n" + + " gauge {\n" + + " value: 1.0\n" + + " }\n" + + "}\n"; + assertMatches(expected, toPrometheusProtobuf(snapshots)); + } + + @Test + void exponentialLongHistogramMinimal() { + LongHistogram histogram = meter.histogramBuilder("my.exponential.histogram").ofLongs().build(); + histogram.record(1, Attributes.builder().put("animal", "bear").build()); + assertExponentialHistogramMinimal(reader.collect()); + } + + @Test + void exponentialDoubleHistogramMinimal() { + DoubleHistogram histogram = meter.histogramBuilder("my.exponential.histogram").build(); + histogram.record(1.0, Attributes.builder().put("animal", "bear").build()); + assertExponentialHistogramMinimal(reader.collect()); + } + + private static void assertExponentialHistogramMinimal(MetricSnapshots snapshots) { + String expected = + "" + + "name: \"my_exponential_histogram\"\n" + + "help: \"\"\n" + + "type: HISTOGRAM\n" + + "metric {\n" + + " label {\n" + + " name: \"animal\"\n" + + " value: \"bear\"\n" + + " }\n" + + " label {\n" + + " name: \"otel_scope_name\"\n" + + " value: \"test\"\n" + + " }\n" + + " histogram {\n" + + " sample_count: 1\n" + + " sample_sum: 1.0\n" + + " schema: 8\n" + + " zero_threshold: 0.0\n" + + " zero_count: 0\n" + + " positive_span {\n" + + " offset: 0\n" + + " length: 1\n" + + " }\n" + + " positive_delta: 1\n" + + " }\n" + + "}\n" + + "name: \"target_info\"\n" + + "type: GAUGE\n" + + "metric {\n" + + " label {\n" + + " name: \"service_name\"\n" + + " value: \"unknown_service:java\"\n" + + " }\n" + + " label {\n" + + " name: \"telemetry_sdk_language\"\n" + + " value: \"java\"\n" + + " }\n" + + " label {\n" + + " name: \"telemetry_sdk_name\"\n" + + " value: \"opentelemetry\"\n" + + " }\n" + + " label {\n" + + " name: \"telemetry_sdk_version\"\n" + + " value: \"1.x.x\"\n" + + " }\n" + + " gauge {\n" + + " value: 1.0\n" + + " }\n" + + "}\n"; + assertMatches(expected, toPrometheusProtobuf(snapshots)); + } + + @Test + void exponentialHistogramBucketConversion() { + Random random = new Random(); + for (int i = 0; i < 100_000; i++) { + int otelScale = random.nextInt(24) - 4; + int prometheusScale = Math.min(otelScale, 8); + PrometheusMetricReader reader = PrometheusMetricReader.create(); + Meter meter = + SdkMeterProvider.builder() + .registerMetricReader(reader) + .registerView( + InstrumentSelector.builder().setName("my.exponential.histogram").build(), + View.builder() + .setAggregation( + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(160) + .setMaxScale(otelScale) + .build())) + .build()) + .build() + .meterBuilder("test") + .build(); + int orderOfMagnitude = random.nextInt(18) - 9; + double observation = random.nextDouble() * Math.pow(10, orderOfMagnitude); + if (observation == 0) { + continue; + } + DoubleHistogram histogram = meter.histogramBuilder("my.exponential.histogram").build(); + histogram.record(observation); + MetricSnapshots snapshots = reader.collect(); + HistogramSnapshot snapshot = (HistogramSnapshot) snapshots.get(0); + HistogramDataPointSnapshot dataPoint = snapshot.getDataPoints().get(0); + assertThat(dataPoint.getNativeSchema()).isEqualTo(prometheusScale); + NativeHistogramBuckets buckets = dataPoint.getNativeBucketsForPositiveValues(); + assertThat(buckets.size()).isEqualTo(1); + int index = buckets.getBucketIndex(0); + double base = Math.pow(2, Math.pow(2, -prometheusScale)); + double lowerBound = Math.pow(base, index - 1); + double upperBound = Math.pow(base, index); + assertThat(lowerBound).isLessThan(observation); + assertThat(upperBound).isGreaterThanOrEqualTo(observation); + } + } + + @Test + void exponentialLongHistogramScaleDown() { + // The following histogram will have the default scale, which is 20. + DoubleHistogram histogram = meter.histogramBuilder("my.exponential.histogram").build(); + double base = Math.pow(2, Math.pow(2, -20)); + int i; + for (i = 0; i < Math.pow(2, 12); i++) { + histogram.record(Math.pow(base, i)); // one observation per bucket + } + for (int j = 0; j < 10; j++) { + histogram.record(Math.pow(base, i + 2 * j)); // few empty buckets between the observations + } + MetricSnapshots snapshots = reader.collect(); + HistogramSnapshot snapshot = (HistogramSnapshot) snapshots.get(0); + HistogramDataPointSnapshot dataPoint = snapshot.getDataPoints().get(0); + assertThat(dataPoint.getNativeSchema()).isEqualTo(8); // scaled down from 20 to 8. + NativeHistogramBuckets buckets = dataPoint.getNativeBucketsForPositiveValues(); + assertThat(buckets.size()).isEqualTo(3); + // In bucket 0 we have exactly one observation: the value 1.0 + assertThat(buckets.getBucketIndex(0)).isEqualTo(0); + assertThat(buckets.getCount(0)).isEqualTo(1); + // In bucket 1 we have 4095 observations + assertThat(buckets.getBucketIndex(1)).isEqualTo(1); + assertThat(buckets.getCount(1)).isEqualTo(4095); + // In bucket 2 we have 10 observations (despite the empty buckets all observations fall into the + // same bucket at scale 8) + assertThat(buckets.getBucketIndex(2)).isEqualTo(2); + assertThat(buckets.getCount(2)).isEqualTo(10); + } + + @Test + void instrumentationScope() throws IOException { + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .registerMetricReader(this.reader) + .setResource( + Resource.getDefault().toBuilder().put("telemetry.sdk.version", "1.x.x").build()) + .build(); + Meter meter1 = meterProvider.meterBuilder("scopeA").setInstrumentationVersion("1.1").build(); + Meter meter2 = meterProvider.meterBuilder("scopeB").setInstrumentationVersion("1.2").build(); + meter1 + .counterBuilder("processing.time") + .setDescription("processing time in seconds") + .setUnit("s") + .ofDoubles() + .build() + .add(3.3, Attributes.builder().put("a", "b").build()); + meter2 + .counterBuilder("processing.time") + .setDescription("processing time in seconds") + .setUnit("s") + .ofDoubles() + .build() + .add(3.3, Attributes.builder().put("a", "b").build()); + String expected = + "" + + "# TYPE processing_time_seconds counter\n" + + "# UNIT processing_time_seconds seconds\n" + + "# HELP processing_time_seconds processing time in seconds\n" + + "processing_time_seconds_total{a=\"b\",otel_scope_name=\"scopeA\",otel_scope_version=\"1.1\"} 3.3\n" + + "processing_time_seconds_created{a=\"b\",otel_scope_name=\"scopeA\",otel_scope_version=\"1.1\"} " + + createdTimestamp + + "\n" + + "processing_time_seconds_total{a=\"b\",otel_scope_name=\"scopeB\",otel_scope_version=\"1.2\"} 3.3\n" + + "processing_time_seconds_created{a=\"b\",otel_scope_name=\"scopeB\",otel_scope_version=\"1.2\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + @Test + void nameSuffix() throws IOException { + LongCounter unitAndTotal = + meter.counterBuilder("request.duration.seconds.total").setUnit("s").build(); + unitAndTotal.add(1); + LongCounter unitOnly = meter.counterBuilder("response.duration.seconds").setUnit("s").build(); + unitOnly.add(2); + LongCounter totalOnly = meter.counterBuilder("processing.duration.total").setUnit("s").build(); + totalOnly.add(3); + LongCounter noSuffix = meter.counterBuilder("queue.time").setUnit("s").build(); + noSuffix.add(4); + String expected = + "" + + "# TYPE processing_duration_seconds counter\n" + + "# UNIT processing_duration_seconds seconds\n" + + "processing_duration_seconds_total{otel_scope_name=\"test\"} 3.0\n" + + "processing_duration_seconds_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE queue_time_seconds counter\n" + + "# UNIT queue_time_seconds seconds\n" + + "queue_time_seconds_total{otel_scope_name=\"test\"} 4.0\n" + + "queue_time_seconds_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE request_duration_seconds counter\n" + + "# UNIT request_duration_seconds seconds\n" + + "request_duration_seconds_total{otel_scope_name=\"test\"} 1.0\n" + + "request_duration_seconds_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE response_duration_seconds counter\n" + + "# UNIT response_duration_seconds seconds\n" + + "response_duration_seconds_total{otel_scope_name=\"test\"} 2.0\n" + + "response_duration_seconds_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + @Test + void nameSuffixUnit() throws IOException { + LongCounter counter = meter.counterBuilder("request.duration.seconds").setUnit("s").build(); + counter.add(1); + String expected = + "" + + "# TYPE request_duration_seconds counter\n" + + "# UNIT request_duration_seconds seconds\n" + + "request_duration_seconds_total{otel_scope_name=\"test\"} 1.0\n" + + "request_duration_seconds_created{otel_scope_name=\"test\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + @Test + void illegalCharacters() throws IOException { + LongCounter counter = meter.counterBuilder("prod/request.count").build(); + counter.add(1, Attributes.builder().put("user-count", 30).build()); + String expected = + "" + + "# TYPE prod_request_count counter\n" + + "prod_request_count_total{otel_scope_name=\"test\",user_count=\"30\"} 1.0\n" + + "prod_request_count_created{otel_scope_name=\"test\",user_count=\"30\"} " + + createdTimestamp + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + @Test + void createdTimestamp() throws IOException { + + LongCounter counter = meter.counterBuilder("requests").build(); + testClock.advance(Duration.ofMillis(1)); + long bearStartNanos = testClock.now(); + counter.add(3, Attributes.builder().put("animal", "bear").build()); + testClock.advance(Duration.ofMillis(1)); + long mouseStartNanos = testClock.now(); + counter.add(2, Attributes.builder().put("animal", "mouse").build()); + testClock.advance(Duration.ofMillis(1)); + + String expected = + "" + + "# TYPE requests counter\n" + + "requests_total{animal=\"bear\",otel_scope_name=\"test\"} 3.0\n" + + "requests_created{animal=\"bear\",otel_scope_name=\"test\"} " + + convertTimestamp(bearStartNanos) + + "\n" + + "requests_total{animal=\"mouse\",otel_scope_name=\"test\"} 2.0\n" + + "requests_created{animal=\"mouse\",otel_scope_name=\"test\"} " + + convertTimestamp(mouseStartNanos) + + "\n" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + @Test + void withoutScopeLabels() throws IOException { + PrometheusMetricReader reader = + PrometheusMetricReader.builder().setOtelScopeLabelsEnabled(false).build(); + addCounter(reader, Resource.getDefault().toBuilder()); + String expected = + "" + + "# TYPE target info\n" + + "target_info{service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# TYPE test_count counter\n" + + "test_count_total 1.0\n" + + "test_count_created " + + createdTimestamp + + "\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + @Test + void withoutTargetInfoMetric() throws IOException { + PrometheusMetricReader reader = + PrometheusMetricReader.builder().setTargetInfoMetricEnabled(false).build(); + addCounter(reader, Resource.getDefault().toBuilder()); + String expected = + "" + + "# TYPE test_count counter\n" + + "test_count_total{otel_scope_name=\"test-scope\",otel_scope_version=\"a.b.c\"} 1.0\n" + + "test_count_created{otel_scope_name=\"test-scope\",otel_scope_version=\"a.b.c\"} " + + createdTimestamp + + "\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + private void addCounter(PrometheusMetricReader reader, ResourceBuilder builder) { + Meter meter = + SdkMeterProvider.builder() + .setClock(testClock) + .registerMetricReader(reader) + .setResource(builder.put("telemetry.sdk.version", "1.x.x").build()) + .build() + .meterBuilder("test-scope") + .setInstrumentationVersion("a.b.c") + .build(); + LongCounter counter = meter.counterBuilder("test.count").build(); + counter.add(1); + } + + @Test + void addResourceAttributesWorks() throws IOException { + PrometheusMetricReader reader = + PrometheusMetricReader.builder() + .setAllowedResourceAttributesFilter(Predicates.is("cluster")) + .build(); + addCounter(reader, Resource.getDefault().toBuilder().put("cluster", "my.cluster")); + String expected = + "" + + "# TYPE target info\n" + + "target_info{cluster=\"my.cluster\",service_name=\"unknown_service:java\",telemetry_sdk_language=\"java\",telemetry_sdk_name=\"opentelemetry\",telemetry_sdk_version=\"1.x.x\"} 1\n" + + "# TYPE test_count counter\n" + + // In both those metrics we expect the "cluster" label to exist + + "test_count_total{cluster=\"my.cluster\",otel_scope_name=\"test-scope\",otel_scope_version=\"a.b.c\"} 1.0\n" + + "test_count_created{cluster=\"my.cluster\",otel_scope_name=\"test-scope\",otel_scope_version=\"a.b.c\"} " + + createdTimestamp + + "\n" + + "# EOF\n"; + assertThat(toOpenMetrics(reader.collect())).isEqualTo(expected); + } + + /** + * Unfortunately there is no easy way to use {@link TestClock} for Exemplar timestamps. Test if + * {@code expected} equals {@code actual} but {@code } matches arbitrary timestamps. + */ + private static void assertMatches(String expected, String actual) { + String regex = toPattern(expected); + assertThat(actual) + .as("Expected: " + expected + "\nActual: " + actual) + .matches(Pattern.compile(regex)); + } + + /** + * Replace non-deterministic portions of {@code expected} with regex patterns. Other portions are + * quoted such that must match exactly. The following sequences are replaced: + * + *

      + *
    • {@code } + *
    • {@code } + *
    • {@code } + *
    • {@code } + *
    + */ + private static String toPattern(String expected) { + Map replacePatterns = new HashMap<>(); + String timestampPattern = "[0-9]+(\\.[0-9]+)?"; + replacePatterns.put("timestamp", timestampPattern); + replacePatterns.put("maybeNanos", String.format("(nanos: %s)?", timestampPattern)); + replacePatterns.put("spanId", "[a-z0-9]*"); + replacePatterns.put("traceId", "[a-z0-9]*"); + replacePatterns.put("measurement", "[0-9\\.]*"); + + Matcher matcher = Pattern.compile("\\<([a-zA-Z]*)\\>").matcher(expected); + if (!matcher.find()) { + return Pattern.quote(expected); + } + int offset = 0; + StringBuilder regexBuilder = new StringBuilder(); + do { + MatchResult matchResult = matcher.toMatchResult(); + String key = matchResult.group(1); + String pattern = replacePatterns.getOrDefault(key, key); + regexBuilder + .append(Pattern.quote(expected.substring(offset, matchResult.start()))) + .append(pattern); + offset = matchResult.end(); + } while (matcher.find()); + if (offset != expected.length()) { + regexBuilder.append(Pattern.quote(expected.substring(offset))); + } + return regexBuilder.toString(); + } + + @SuppressWarnings("JdkObsolete") // Recommended alternative was introduced in java 10 + private static String toOpenMetrics(MetricSnapshots snapshots) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + OpenMetricsTextFormatWriter writer = new OpenMetricsTextFormatWriter(true, true); + writer.write(out, snapshots); + return out.toString(StandardCharsets.UTF_8.name()); + } + + private static String toPrometheusProtobuf(MetricSnapshots snapshots) { + PrometheusProtobufWriter writer = new PrometheusProtobufWriter(); + return writer.toDebugString(snapshots); + } + + private static String convertTimestamp(long nanoTime) { + String millis = Long.toString(TimeUnit.NANOSECONDS.toMillis(nanoTime)); + return millis.substring(0, millis.length() - 3) + "." + millis.substring(millis.length() - 3); + } +} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusUnitsHelperTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusUnitsHelperTest.java new file mode 100644 index 00000000000..ec62da489fa --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/PrometheusUnitsHelperTest.java @@ -0,0 +1,134 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import com.google.common.base.Strings; +import io.prometheus.metrics.model.snapshots.Unit; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class PrometheusUnitsHelperTest { + + @ParameterizedTest + @MethodSource("providePrometheusOTelUnitEquivalentPairs") + public void testPrometheusUnitEquivalency(String otlpUnit, String expectedPrometheusUnit) { + Unit actualPrometheusUnit = PrometheusUnitsHelper.convertUnit(otlpUnit); + if (expectedPrometheusUnit == null) { + assertNull(actualPrometheusUnit); + } else { + assertEquals(expectedPrometheusUnit, actualPrometheusUnit.toString()); + } + } + + @ParameterizedTest + @MethodSource("reservedSuffixUnitArgs") + void convertUnit_reservedSuffixHandling(String otlpUnit, String expectedPrometheusUnit) { + Unit actualPrometheusUnit = PrometheusUnitsHelper.convertUnit(otlpUnit); + if (expectedPrometheusUnit == null) { + assertNull(actualPrometheusUnit); + } else { + assertEquals(expectedPrometheusUnit, actualPrometheusUnit.toString()); + } + } + + @ParameterizedTest + @MethodSource("annotationUnitArgs") + void convertUnit_annotations(String otlpUnit, String expectedPrometheusUnit) { + Unit actualPrometheusUnit = PrometheusUnitsHelper.convertUnit(otlpUnit); + if (expectedPrometheusUnit == null) { + assertThat(actualPrometheusUnit).isNull(); + } else { + assertThat(actualPrometheusUnit).hasToString(expectedPrometheusUnit); + } + } + + private static Stream annotationUnitArgs() { + String openingBraces = Strings.repeat("{", 8000); + return Stream.of( + Arguments.argumentSet("empty annotation", "s{}", "seconds"), + Arguments.argumentSet("annotation only", "{objects}", null), + Arguments.argumentSet("unitless after annotation removal", "1{objects}", null), + Arguments.argumentSet("multiple annotations", "{first}s{second}", "seconds"), + Arguments.argumentSet("trim after annotation removal", " \ts{objects} \n", "seconds"), + Arguments.argumentSet("annotation containing slash", "s{objects/s}", "seconds"), + Arguments.argumentSet("annotation before denominator", "m{objects}/s", "meters_per_second"), + Arguments.argumentSet("nested opening braces", "s{outer{inner}", "seconds"), + Arguments.argumentSet( + "first closing brace ends annotation", "s{outer{inner}tail}", "stail"), + Arguments.argumentSet("unmatched closing brace retained", "s}m{objects}", "s_m"), + Arguments.argumentSet("unterminated annotation retained", "s{tail", "s_tail"), + Arguments.argumentSet("valid then unterminated annotation", "s{objects}{tail", "s_tail"), + Arguments.argumentSet( + "repeated unterminated opening braces", + "s" + openingBraces + "s", + "s" + Strings.repeat("_", 8000) + "s"), + Arguments.argumentSet( + "repeated opening braces with closing brace", "s" + openingBraces + "}", "seconds"), + Arguments.argumentSet( + "repeated complete annotations", Strings.repeat("{objects}", 1000) + "s", "seconds")); + } + + private static Stream reservedSuffixUnitArgs() { + return Stream.of( + Arguments.argumentSet("reserved suffix only", "total", null), + Arguments.argumentSet("reserved created suffix only", "created", null), + Arguments.argumentSet("reserved bucket suffix only", "bucket", null), + Arguments.argumentSet("reserved info suffix only", "info", null), + Arguments.argumentSet("reserved suffix stripped", "widgets_total", "widgets"), + Arguments.argumentSet( + "repeated reserved suffixes stripped", "widgets_total_info", "widgets"), + Arguments.argumentSet( + "trailing punctuation removed after suffix stripping", "widgets_total_", "widgets"), + Arguments.argumentSet("leading and trailing punctuation trimmed", "._widgets_.", "widgets"), + Arguments.argumentSet("only punctuation becomes null", "._", null)); + } + + private static Stream providePrometheusOTelUnitEquivalentPairs() { + return Stream.of( + Arguments.argumentSet("bytes", "By", "bytes"), + Arguments.argumentSet("upper case KBy not converted", "KBy", "KBy"), + Arguments.argumentSet("kilobytes lowercase k", "kBy", "kilobytes"), + Arguments.argumentSet("megabytes", "MBy", "megabytes"), + Arguments.argumentSet("gigabytes", "GBy", "gigabytes"), + Arguments.argumentSet("terabytes", "TBy", "terabytes"), + Arguments.argumentSet("kibibytes", "KiBy", "kibibytes"), + Arguments.argumentSet("mebibytes", "MiBy", "mebibytes"), + Arguments.argumentSet("gibibytes", "GiBy", "gibibytes"), + Arguments.argumentSet("tebibytes", "TiBy", "tebibytes"), + Arguments.argumentSet("days", "d", "days"), + Arguments.argumentSet("hours", "h", "hours"), + Arguments.argumentSet("seconds", "s", "seconds"), + Arguments.argumentSet("milliseconds", "ms", "milliseconds"), + Arguments.argumentSet("microseconds", "us", "microseconds"), + Arguments.argumentSet("nanoseconds", "ns", "nanoseconds"), + Arguments.argumentSet("minutes", "min", "minutes"), + Arguments.argumentSet("percent", "%", "percent"), + Arguments.argumentSet("hertz", "Hz", "hertz"), + Arguments.argumentSet("celsius", "Cel", "celsius"), + Arguments.argumentSet("unknown unit S (case sensitive)", "S", "S"), + Arguments.argumentSet("unitless 1", "1", null), + Arguments.argumentSet("curly braces dropped", "{packets}", null), + Arguments.argumentSet("curly braces with suffix", "{packets}V", "volts"), + Arguments.argumentSet("both units in curly braces", "{scanned}/{returned}", null), + Arguments.argumentSet("curly braces per second", "{objects}/s", "per_second"), + Arguments.argumentSet("meters per second", "m/s", "meters_per_second"), + Arguments.argumentSet("meters per minute", "m/min", "meters_per_minute"), + Arguments.argumentSet("amperes per day", "A/d", "amperes_per_day"), + Arguments.argumentSet("watts per week", "W/wk", "watts_per_week"), + Arguments.argumentSet("joules per month", "J/mo", "joules_per_month"), + Arguments.argumentSet("terabytes per year", "TBy/a", "terabytes_per_year"), + Arguments.argumentSet("unknown per unknown", "v/v", "v_per_v"), + Arguments.argumentSet("km per hour (first unit unknown)", "km/h", "km_per_hour"), + Arguments.argumentSet("grams per unknown", "g/x", "grams_per_x"), + Arguments.argumentSet("improperly formatted", "watts_W", "watts_W")); + } +} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/SerializerTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/SerializerTest.java deleted file mode 100644 index 8fd29a27d5d..00000000000 --- a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/SerializerTest.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.prometheus; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; -import io.opentelemetry.sdk.resources.Resource; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class SerializerTest { - - private static final AttributeKey TYPE = stringKey("type"); - - private static final MetricData MONOTONIC_CUMULATIVE_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "mcds"), - 5)))); - private static final MetricData NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "description", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "nmcds"), - 5)))); - private static final MetricData MONOTONIC_DELTA_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "mdds"), - 5)))); - private static final MetricData NON_MONOTONIC_DELTA_DOUBLE_SUM = - ImmutableMetricData.createDoubleSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "nmdds"), - 5)))); - private static final MetricData MONOTONIC_CUMULATIVE_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "mcls"), - 5)))); - private static final MetricData NON_MONOTONIC_CUMULATIVE_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "nmcls"), - 5)))); - private static final MetricData MONOTONIC_DELTA_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSumData.create( - /* isMonotonic= */ true, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "mdls"), - 5)))); - private static final MetricData NON_MONOTONIC_DELTA_LONG_SUM = - ImmutableMetricData.createLongSum( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSumData.create( - /* isMonotonic= */ false, - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "nmdls"), - 5)))); - - private static final MetricData DOUBLE_GAUGE = - ImmutableMetricData.createDoubleGauge( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableGaugeData.create( - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, Attributes.of(TYPE, "dg"), 5)))); - private static final MetricData LONG_GAUGE = - ImmutableMetricData.createLongGauge( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableGaugeData.create( - Collections.singletonList( - ImmutableLongPointData.create( - 1633947011000000000L, 1633950672000000000L, Attributes.of(TYPE, "lg"), 5)))); - private static final MetricData SUMMARY = - ImmutableMetricData.createDoubleSummary( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableSummaryData.create( - Collections.singletonList( - ImmutableSummaryPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "s"), - 5, - 7, - Arrays.asList( - ImmutableValueAtQuantile.create(0.9, 0.1), - ImmutableValueAtQuantile.create(0.99, 0.3)))))); - private static final MetricData HISTOGRAM_NO_ATTRIBUTES = - ImmutableMetricData.createDoubleHistogram( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableHistogramData.create( - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableHistogramPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.empty(), - 1.0, - null, - null, - Collections.emptyList(), - Collections.singletonList(2L), - Collections.singletonList( - ImmutableDoubleExemplarData.create( - Attributes.empty(), - TimeUnit.MILLISECONDS.toNanos(1L), - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - /* value= */ 4)))))); - private static final MetricData HISTOGRAM_SINGLE_ATTRIBUTE = - ImmutableMetricData.createDoubleHistogram( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableHistogramData.create( - AggregationTemporality.DELTA, - Collections.singletonList( - ImmutableHistogramPointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "hs"), - 1.0, - null, - null, - Collections.emptyList(), - Collections.singletonList(2L), - Collections.singletonList( - ImmutableDoubleExemplarData.create( - Attributes.empty(), - TimeUnit.MILLISECONDS.toNanos(1L), - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - /* value= */ 4)))))); - private static final MetricData DOUBLE_GAUGE_NO_ATTRIBUTES = - ImmutableMetricData.createDoubleGauge( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableGaugeData.create( - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, 1633950672000000000L, Attributes.empty(), 7)))); - private static final MetricData DOUBLE_GAUGE_MULTIPLE_ATTRIBUTES = - ImmutableMetricData.createDoubleGauge( - Resource.create(Attributes.of(stringKey("kr"), "vr")), - InstrumentationScopeInfo.create("full", "version", null), - "instrument.name", - "unused", - "1", - ImmutableGaugeData.create( - Collections.singletonList( - ImmutableDoublePointData.create( - 1633947011000000000L, - 1633950672000000000L, - Attributes.of(TYPE, "dgma", stringKey("animal"), "bear"), - 8)))); - - @Test - void prometheus004() { - // Same output as prometheus client library except for these changes which are compatible with - // Prometheus - // TYPE / HELP line order reversed - // Attributes do not end in trailing comma - assertThat( - serialize004( - MONOTONIC_CUMULATIVE_DOUBLE_SUM, - NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM, - MONOTONIC_DELTA_DOUBLE_SUM, - NON_MONOTONIC_DELTA_DOUBLE_SUM, - MONOTONIC_CUMULATIVE_LONG_SUM, - NON_MONOTONIC_CUMULATIVE_LONG_SUM, - MONOTONIC_DELTA_LONG_SUM, - NON_MONOTONIC_DELTA_LONG_SUM, - DOUBLE_GAUGE, - LONG_GAUGE, - SUMMARY, - HISTOGRAM_NO_ATTRIBUTES, - HISTOGRAM_SINGLE_ATTRIBUTE, - DOUBLE_GAUGE_NO_ATTRIBUTES, - DOUBLE_GAUGE_MULTIPLE_ATTRIBUTES)) - .isEqualTo( - "# TYPE instrument_name_total counter\n" - + "# HELP instrument_name_total description\n" - + "instrument_name_total{type=\"mcds\"} 5.0 1633950672000\n" - + "instrument_name_total{type=\"mcls\"} 5.0 1633950672000\n" - + "# TYPE instrument_name gauge\n" - + "# HELP instrument_name description\n" - + "instrument_name{type=\"nmcds\"} 5.0 1633950672000\n" - + "instrument_name{type=\"mdds\"} 5.0 1633950672000\n" - + "instrument_name{type=\"nmdds\"} 5.0 1633950672000\n" - + "instrument_name{type=\"nmcls\"} 5.0 1633950672000\n" - + "instrument_name{type=\"mdls\"} 5.0 1633950672000\n" - + "instrument_name{type=\"nmdls\"} 5.0 1633950672000\n" - + "instrument_name{type=\"dg\"} 5.0 1633950672000\n" - + "instrument_name{type=\"lg\"} 5.0 1633950672000\n" - + "instrument_name_count{type=\"s\"} 5.0 1633950672000\n" - + "instrument_name_sum{type=\"s\"} 7.0 1633950672000\n" - + "instrument_name{type=\"s\",quantile=\"0.9\"} 0.1 1633950672000\n" - + "instrument_name{type=\"s\",quantile=\"0.99\"} 0.3 1633950672000\n" - + "instrument_name_count 2.0 1633950672000\n" - + "instrument_name_sum 1.0 1633950672000\n" - + "instrument_name_bucket{le=\"+Inf\"} 2.0 1633950672000\n" - + "instrument_name_count{type=\"hs\"} 2.0 1633950672000\n" - + "instrument_name_sum{type=\"hs\"} 1.0 1633950672000\n" - + "instrument_name_bucket{type=\"hs\",le=\"+Inf\"} 2.0 1633950672000\n" - + "instrument_name 7.0 1633950672000\n" - + "instrument_name{animal=\"bear\",type=\"dgma\"} 8.0 1633950672000\n"); - } - - @Test - void openMetrics() { - assertThat( - serializeOpenMetrics( - MONOTONIC_CUMULATIVE_DOUBLE_SUM, - NON_MONOTONIC_CUMULATIVE_DOUBLE_SUM, - MONOTONIC_DELTA_DOUBLE_SUM, - NON_MONOTONIC_DELTA_DOUBLE_SUM, - MONOTONIC_CUMULATIVE_LONG_SUM, - NON_MONOTONIC_CUMULATIVE_LONG_SUM, - MONOTONIC_DELTA_LONG_SUM, - NON_MONOTONIC_DELTA_LONG_SUM, - DOUBLE_GAUGE, - LONG_GAUGE, - SUMMARY, - HISTOGRAM_SINGLE_ATTRIBUTE, - DOUBLE_GAUGE_NO_ATTRIBUTES, - DOUBLE_GAUGE_MULTIPLE_ATTRIBUTES)) - .isEqualTo( - "# TYPE instrument_name counter\n" - + "# HELP instrument_name description\n" - + "instrument_name_total{type=\"mcds\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"nmcds\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"mdds\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"nmdds\"} 5.0 1633950672.000\n" - + "instrument_name_total{type=\"mcls\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"nmcls\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"mdls\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"nmdls\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"dg\"} 5.0 1633950672.000\n" - + "instrument_name{type=\"lg\"} 5.0 1633950672.000\n" - + "instrument_name_count{type=\"s\"} 5.0 1633950672.000\n" - + "instrument_name_sum{type=\"s\"} 7.0 1633950672.000\n" - + "instrument_name{type=\"s\",quantile=\"0.9\"} 0.1 1633950672.000\n" - + "instrument_name{type=\"s\",quantile=\"0.99\"} 0.3 1633950672.000\n" - + "instrument_name_count{type=\"hs\"} 2.0 1633950672.000\n" - + "instrument_name_sum{type=\"hs\"} 1.0 1633950672.000\n" - + "instrument_name_bucket{type=\"hs\",le=\"+Inf\"} 2.0 1633950672.000 # {span_id=\"0000000000000002\",trace_id=\"00000000000000000000000000000001\"} 4.0 0.001\n" - + "instrument_name 7.0 1633950672.000\n" - + "instrument_name{animal=\"bear\",type=\"dgma\"} 8.0 1633950672.000\n" - + "# EOF\n"); - } - - private static String serialize004(MetricData... metrics) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - new Serializer.Prometheus004Serializer(unused -> true).write(Arrays.asList(metrics), bos); - return bos.toString("UTF-8"); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } - - private static String serializeOpenMetrics(MetricData... metrics) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - try { - new Serializer.OpenMetrics100Serializer(unused -> true).write(Arrays.asList(metrics), bos); - return bos.toString("UTF-8"); - } catch (IOException e) { - throw new UncheckedIOException(e); - } - } -} diff --git a/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java new file mode 100644 index 00000000000..9f19c5edd6f --- /dev/null +++ b/exporters/prometheus/src/test/java/io/opentelemetry/exporter/prometheus/internal/PrometheusMetricReaderProviderTest.java @@ -0,0 +1,119 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.prometheus.internal; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +import com.sun.net.httpserver.HttpServer; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.prometheus.metrics.exporter.httpserver.HTTPServer; +import java.io.IOException; +import java.net.ServerSocket; +import java.util.HashMap; +import java.util.Map; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class PrometheusMetricReaderProviderTest { + + private static final PrometheusMetricReaderProvider provider = + new PrometheusMetricReaderProvider(); + + @Mock private ConfigProperties configProperties; + + @Test + void getName() { + assertThat(provider.getName()).isEqualTo("prometheus"); + } + + @Test + void createMetricReader_Default() throws IOException { + when(configProperties.getInt(any())).thenReturn(null); + when(configProperties.getString(any())).thenReturn(null); + + try (MetricReader metricReader = provider.createMetricReader(configProperties)) { + assertThat(metricReader) + .isInstanceOf(PrometheusHttpServer.class) + .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) + .extracting("server", as(InstanceOfAssertFactories.type(HttpServer.class))) + .satisfies(server -> { + assertThat(server.getAddress().getHostName()) + .isIn("localhost", "127.0.0.1", "kubernetes.docker.internal"); + assertThat(server.getAddress().getPort()).isEqualTo(9464); + }); + assertThat(metricReader.getMemoryMode()).isEqualTo(MemoryMode.REUSABLE_DATA); + assertThat(metricReader.getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.defaultAggregation()); + } + } + + @Test + void createMetricReader_WithConfiguration() throws IOException { + // Find a random unused port. There's a small race if another process takes it before we + // initialize. Consider adding retries to this test if it flakes, presumably it never will on + // CI since there's no prometheus there blocking the well-known port. + int port; + try (ServerSocket socket2 = new ServerSocket(0)) { + port = socket2.getLocalPort(); + } + + Map config = new HashMap<>(); + config.put("otel.exporter.prometheus.host", "localhost"); + config.put("otel.exporter.prometheus.port", String.valueOf(port)); + config.put("otel.java.exporter.memory_mode", "immutable_data"); + config.put( + "otel.java.experimental.exporter.prometheus.metrics.default.histogram.aggregation", + "BASE2_EXPONENTIAL_BUCKET_HISTOGRAM"); + + when(configProperties.getInt(any())).thenReturn(null); + when(configProperties.getString(any())).thenReturn(null); + + try (MetricReader metricReader = + provider.createMetricReader(DefaultConfigProperties.createFromMap(config))) { + assertThat(metricReader) + .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) + .extracting("server", as(InstanceOfAssertFactories.type(HttpServer.class))) + .satisfies(server -> { + assertThat(server.getAddress().getHostName()) + .isIn("localhost", "127.0.0.1", "kubernetes.docker.internal"); + assertThat(server.getAddress().getPort()).isEqualTo(port); + }); + assertThat(metricReader.getMemoryMode()).isEqualTo(MemoryMode.IMMUTABLE_DATA); + assertThat(metricReader.getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); + } + } + + @Test + void createMetricReader_WithWrongConfiguration() { + Map config = new HashMap<>(); + config.put( + "otel.java.experimental.exporter.prometheus.metrics.default.histogram.aggregation", "foo"); + + assertThatThrownBy( + () -> provider.createMetricReader(DefaultConfigProperties.createFromMap(config))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized default histogram aggregation:"); + } +} diff --git a/exporters/prometheus/src/test/resources/otel-config.yaml b/exporters/prometheus/src/test/resources/otel-config.yaml new file mode 100644 index 00000000000..c6cec85cd94 --- /dev/null +++ b/exporters/prometheus/src/test/resources/otel-config.yaml @@ -0,0 +1,25 @@ +extensions: + health_check: + endpoint: 0.0.0.0:13133 +receivers: + prometheus: + config: + scrape_configs: + - job_name: 'app' + scrape_interval: 1s + static_configs: + - targets: ['${APP_ENDPOINT}'] +exporters: + debug: + verbosity: ${LOGGING_EXPORTER_VERBOSITY} + otlp: + endpoint: ${OTLP_EXPORTER_ENDPOINT} + tls: + insecure: true + compression: none +service: + extensions: [health_check] + pipelines: + metrics: + receivers: [prometheus] + exporters: [debug, otlp] diff --git a/exporters/prometheus/src/integrationTest/resources/prom.yml b/exporters/prometheus/src/test/resources/prom.yml similarity index 100% rename from exporters/prometheus/src/integrationTest/resources/prom.yml rename to exporters/prometheus/src/test/resources/prom.yml diff --git a/exporters/sender/build.gradle.kts b/exporters/sender/build.gradle.kts new file mode 100644 index 00000000000..a212101567e --- /dev/null +++ b/exporters/sender/build.gradle.kts @@ -0,0 +1,10 @@ +subprojects { + // Workaround https://github.com/gradle/gradle/issues/847 + group = "io.opentelemetry.exporter.httpsender" + val proj = this + plugins.withId("java") { + configure { + archivesName.set("opentelemetry-exporter-sender-${proj.name}") + } + } +} diff --git a/exporters/sender/grpc-managed-channel/build.gradle.kts b/exporters/sender/grpc-managed-channel/build.gradle.kts new file mode 100644 index 00000000000..ab59aeced42 --- /dev/null +++ b/exporters/sender/grpc-managed-channel/build.gradle.kts @@ -0,0 +1,22 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry gRPC Upstream Sender" +otelJava.moduleName.set("io.opentelemetry.exporter.sender.grpc.managedchannel.internal") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", +)) + +dependencies { + annotationProcessor("com.google.auto.value:auto-value") + + implementation(project(":exporters:common")) + implementation(project(":sdk:common")) + + implementation("io.grpc:grpc-stub") +} diff --git a/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/ImmutableGrpcResponse.java b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/ImmutableGrpcResponse.java new file mode 100644 index 00000000000..6bd7315f87c --- /dev/null +++ b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/ImmutableGrpcResponse.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.grpc.managedchannel.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import javax.annotation.Nullable; + +@AutoValue +abstract class ImmutableGrpcResponse implements GrpcResponse { + + static ImmutableGrpcResponse create( + GrpcStatusCode statusCode, @Nullable String statusDescription, byte[] responseMessage) { + return new AutoValue_ImmutableGrpcResponse(statusCode, statusDescription, responseMessage); + } + + @SuppressWarnings("mutable") + @Override + public abstract byte[] getResponseMessage(); +} diff --git a/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSender.java b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSender.java new file mode 100644 index 00000000000..15d789cbad9 --- /dev/null +++ b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSender.java @@ -0,0 +1,269 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.grpc.managedchannel.internal; + +import com.google.common.util.concurrent.FutureCallback; +import com.google.common.util.concurrent.Futures; +import com.google.common.util.concurrent.MoreExecutors; +import io.grpc.CallOptions; +import io.grpc.Channel; +import io.grpc.ClientInterceptors; +import io.grpc.Compressor; +import io.grpc.CompressorRegistry; +import io.grpc.ManagedChannel; +import io.grpc.Metadata; +import io.grpc.MethodDescriptor; +import io.grpc.Status; +import io.grpc.StatusException; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.ClientCalls; +import io.grpc.stub.MetadataUtils; +import io.opentelemetry.exporter.internal.grpc.MarshalerInputStream; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * A {@link GrpcSender} which uses the upstream grpc-java library. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class UpstreamGrpcSender implements GrpcSender { + + private static final Logger logger = Logger.getLogger(UpstreamGrpcSender.class.getName()); + + private static final MethodDescriptor.Marshaller REQUEST_MARSHALER = + new MethodDescriptor.Marshaller() { + @Override + public InputStream stream(MessageWriter value) { + return new MarshalerInputStream(value); + } + + @Override + public MessageWriter parse(InputStream stream) { + throw new UnsupportedOperationException("Only for serializing"); + } + }; + + private static final MethodDescriptor.Marshaller RESPONSE_MARSHALER = + new MethodDescriptor.Marshaller() { + @Override + public InputStream stream(byte[] value) { + throw new UnsupportedOperationException("Only for parsing"); + } + + @Override + public byte[] parse(InputStream inputStream) { + try { + int bufLen = 4 * 0x400; // 4KB + byte[] buf = new byte[bufLen]; + int readLen; + IOException exception = null; + + try { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + while ((readLen = inputStream.read(buf, 0, bufLen)) != -1) { + outputStream.write(buf, 0, readLen); + } + return outputStream.toByteArray(); + } + } catch (IOException e) { + exception = e; + throw e; + } finally { + if (exception == null) { + inputStream.close(); + } else { + try { + inputStream.close(); + } catch (IOException e) { + exception.addSuppressed(e); + } + } + } + } catch (IOException e) { + throw new IllegalStateException("Failed to read response", e); + } + } + }; + + private final ManagedChannel channel; + private final MethodDescriptor methodDescriptor; + @Nullable private final String compressorName; + private final boolean shutdownChannel; + private final Duration timeout; + private final Supplier>> headersSupplier; + private final Executor executor; + + /** Creates a new {@link UpstreamGrpcSender}. */ + public UpstreamGrpcSender( + ManagedChannel channel, + String fullMethodName, + @Nullable io.opentelemetry.sdk.common.export.Compressor compressor, + boolean shutdownChannel, + Duration timeout, + Supplier>> headersSupplier, + @Nullable ExecutorService executorService) { + this.channel = channel; + this.methodDescriptor = + MethodDescriptor.newBuilder() + .setType(MethodDescriptor.MethodType.UNARY) + .setFullMethodName(fullMethodName) + .setRequestMarshaller(REQUEST_MARSHALER) + .setResponseMarshaller(RESPONSE_MARSHALER) + .build(); + if (compressor != null) { + CompressorRegistry.getDefaultInstance() + .register( + new Compressor() { + @Override + public String getMessageEncoding() { + return compressor.getEncoding(); + } + + @Override + public OutputStream compress(OutputStream os) throws IOException { + return compressor.compress(os); + } + }); + this.compressorName = compressor.getEncoding(); + } else { + this.compressorName = null; + } + this.shutdownChannel = shutdownChannel; + this.timeout = timeout; + this.headersSupplier = headersSupplier; + this.executor = executorService == null ? MoreExecutors.directExecutor() : executorService; + } + + @Override + public void send( + MessageWriter messageWriter, Consumer onResponse, Consumer onError) { + CallOptions requestCallOptions = CallOptions.DEFAULT; + Channel requestChannel = channel; + if (timeout.toNanos() > 0) { + requestCallOptions = requestCallOptions.withDeadlineAfter(timeout); + } + Metadata metadata = new Metadata(); + Map> headers = headersSupplier.get(); + if (headers != null) { + for (Map.Entry> entry : headers.entrySet()) { + metadata.put( + Metadata.Key.of(entry.getKey(), Metadata.ASCII_STRING_MARSHALLER), + String.join(",", entry.getValue())); + // Header names are case-insensitive, so "Host" must override the authority too. + if (entry.getKey().equalsIgnoreCase("host") && !entry.getValue().isEmpty()) { + requestCallOptions = requestCallOptions.withAuthority(entry.getValue().get(0)); + } + } + requestChannel = + ClientInterceptors.intercept( + requestChannel, MetadataUtils.newAttachHeadersInterceptor(metadata)); + } + if (this.compressorName != null) { + requestCallOptions = requestCallOptions.withCompression(compressorName); + } + + Futures.addCallback( + ClientCalls.futureUnaryCall( + requestChannel.newCall(methodDescriptor, requestCallOptions), messageWriter), + new FutureCallback() { + @Override + public void onSuccess(@Nullable byte[] result) { + onResponse.accept( + ImmutableGrpcResponse.create( + GrpcStatusCode.OK, + Status.OK.getDescription(), + result == null ? new byte[0] : result)); + } + + @Override + public void onFailure(Throwable t) { + Status status = fromThrowable(t); + if (status == null) { + onError.accept(t); + } else { + onResponse.accept( + ImmutableGrpcResponse.create( + GrpcStatusCode.fromValue(status.getCode().value()), + status.getDescription(), + new byte[0])); + } + } + }, + executor); + } + + /** + * Copy of {@link Status#fromThrowable(Throwable)} which returns null instead of {@link + * Status#UNKNOWN} when no status can be found. + */ + @Nullable + private static Status fromThrowable(Throwable cause) { + while (cause != null) { + if (cause instanceof StatusException) { + return ((StatusException) cause).getStatus(); + } else if (cause instanceof StatusRuntimeException) { + return ((StatusRuntimeException) cause).getStatus(); + } + cause = cause.getCause(); + } + return null; + } + + @Override + public CompletableResultCode shutdown() { + if (shutdownChannel) { + // Use shutdownNow() to cancel in flight calls immediately + channel.shutdownNow(); + + // Wait for the channel to terminate in a background thread + CompletableResultCode result = new CompletableResultCode(); + Thread terminationThread = + new Thread( + () -> { + try { + // Wait up to 5 seconds for the channel to terminate + // Even if timeout occurs, we succeed since these are daemon threads + boolean terminated = channel.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) { + logger.log( + Level.WARNING, + "Channel did not terminate within 5 seconds, proceeding with shutdown since threads are daemon threads."); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + result.succeed(); + } + }, + "grpc-shutdown"); + terminationThread.setDaemon(true); + terminationThread.start(); + return result; + } + + return CompletableResultCode.ofSuccess(); + } +} diff --git a/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSenderProvider.java b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSenderProvider.java new file mode 100644 index 00000000000..985f93552ef --- /dev/null +++ b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSenderProvider.java @@ -0,0 +1,81 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.grpc.managedchannel.internal; + +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.opentelemetry.exporter.internal.grpc.ExtendedGrpcSenderConfig; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcSenderConfig; +import io.opentelemetry.sdk.common.export.GrpcSenderProvider; +import java.net.URI; + +/** + * {@link GrpcSender} SPI implementation for {@link UpstreamGrpcSender}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class UpstreamGrpcSenderProvider implements GrpcSenderProvider { + + @Override + public GrpcSender createSender(GrpcSenderConfig grpcSenderConfig) { + checkState( + grpcSenderConfig instanceof ExtendedGrpcSenderConfig, + "grpcSenderConfig must be an instance of ExtendedGrpcSenderConfig for UpstreamGrpcSenderProvider"); + ExtendedGrpcSenderConfig extendedSenderConfig = (ExtendedGrpcSenderConfig) grpcSenderConfig; + + boolean shutdownChannel = false; + Object configManagedChannel = extendedSenderConfig.getManagedChannel(); + ManagedChannel managedChannel; + if (configManagedChannel != null) { + checkState( + configManagedChannel instanceof ManagedChannel, + "managedChannel must be an instance of ManagedChannel for UpstreamGrpcSenderProvider"); + managedChannel = (ManagedChannel) configManagedChannel; + } else { + // Shutdown the channel as part of the exporter shutdown sequence if we created it. + shutdownChannel = true; + managedChannel = minimalFallbackManagedChannel(grpcSenderConfig.getEndpoint()); + } + + return new UpstreamGrpcSender( + managedChannel, + extendedSenderConfig.getFullMethodName(), + extendedSenderConfig.getCompressor(), + shutdownChannel, + extendedSenderConfig.getTimeout(), + extendedSenderConfig.getHeadersSupplier(), + extendedSenderConfig.getExecutorService()); + } + + /** + * If {@link ManagedChannel} is not explicitly set, provide a minimally configured fallback + * channel to avoid failing initialization. + * + *

    This is required to accommodate autoconfigure with {@code + * opentelemetry-exporter-sender-grpc-managed-channel} which will always fail to initialize + * without a fallback channel since there isn't an opportunity to explicitly set the channel. + * + *

    This only incorporates the target address, port, and whether to use plain text. All + * additional settings are intentionally ignored and must be configured with an explicitly set + * {@link ManagedChannel}. + */ + private static ManagedChannel minimalFallbackManagedChannel(URI endpoint) { + ManagedChannelBuilder channelBuilder = + ManagedChannelBuilder.forAddress(endpoint.getHost(), endpoint.getPort()); + if (!endpoint.getScheme().equals("https")) { + channelBuilder.usePlaintext(); + } + return channelBuilder.build(); + } + + private static void checkState(boolean isValid, String message) { + if (!isValid) { + throw new IllegalStateException(message); + } + } +} diff --git a/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/package-info.java b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/package-info.java new file mode 100644 index 00000000000..42050312d36 --- /dev/null +++ b/exporters/sender/grpc-managed-channel/src/main/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/package-info.java @@ -0,0 +1,9 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +@ParametersAreNonnullByDefault +package io.opentelemetry.exporter.sender.grpc.managedchannel.internal; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/sender/grpc-managed-channel/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider b/exporters/sender/grpc-managed-channel/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider new file mode 100644 index 00000000000..fabb70d11a9 --- /dev/null +++ b/exporters/sender/grpc-managed-channel/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider diff --git a/exporters/sender/grpc-managed-channel/src/test/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSenderTest.java b/exporters/sender/grpc-managed-channel/src/test/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSenderTest.java new file mode 100644 index 00000000000..8204d3cddec --- /dev/null +++ b/exporters/sender/grpc-managed-channel/src/test/java/io/opentelemetry/exporter/sender/grpc/managedchannel/internal/UpstreamGrpcSenderTest.java @@ -0,0 +1,146 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.grpc.managedchannel.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.grpc.CallOptions; +import io.grpc.ClientCall; +import io.grpc.ManagedChannel; +import io.grpc.MethodDescriptor; +import io.opentelemetry.sdk.common.CompletableResultCode; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +class UpstreamGrpcSenderTest { + + @Test + void shutdown_ManagedChannel_WaitsForChannelTermination() throws Exception { + // The result code must only complete after the channel terminates, not as soon as + // shutdownNow() returns. + FakeManagedChannel channel = new FakeManagedChannel(/* terminates= */ true); + UpstreamGrpcSender sender = newSender(channel, /* shutdownChannel= */ true); + + CompletableResultCode result = sender.shutdown(); + + assertThat(channel.awaitTerminationEntered.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(channel.shutdownNowCalled()).isTrue(); + assertThat(result.isDone()) + .describedAs("result should not complete before the channel terminates") + .isFalse(); + + channel.releaseAwaitTermination.countDown(); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + + @Test + void shutdown_UnmanagedChannel_ReturnsImmediatelyAndLeavesChannelOpen() { + // A caller supplied channel is not ours to close. + FakeManagedChannel channel = new FakeManagedChannel(/* terminates= */ true); + UpstreamGrpcSender sender = newSender(channel, /* shutdownChannel= */ false); + + CompletableResultCode result = sender.shutdown(); + + assertThat(result.isDone()).isTrue(); + assertThat(result.isSuccess()).isTrue(); + assertThat(channel.shutdownNowCalled()).isFalse(); + assertThat(channel.awaitTerminationCalled()).isFalse(); + } + + @Test + void shutdown_ChannelDoesNotTerminateInTime_Succeeds() { + // Termination timing out must not hang or fail the shutdown. + FakeManagedChannel channel = new FakeManagedChannel(/* terminates= */ false); + channel.releaseAwaitTermination.countDown(); + UpstreamGrpcSender sender = newSender(channel, /* shutdownChannel= */ true); + + CompletableResultCode result = sender.shutdown(); + + assertThat(result.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + } + + private static UpstreamGrpcSender newSender(ManagedChannel channel, boolean shutdownChannel) { + return new UpstreamGrpcSender( + channel, + "opentelemetry.proto.collector.trace.v1.TraceService/Export", + /* compressor= */ null, + shutdownChannel, + Duration.ofSeconds(10), + Collections::emptyMap, + /* executorService= */ null); + } + + /** + * A {@link ManagedChannel} which records shutdown interactions and lets the test control when + * {@link #awaitTermination(long, TimeUnit)} returns. + */ + private static class FakeManagedChannel extends ManagedChannel { + + final CountDownLatch awaitTerminationEntered = new CountDownLatch(1); + final CountDownLatch releaseAwaitTermination = new CountDownLatch(1); + + private final boolean terminates; + private final AtomicBoolean shutdownNow = new AtomicBoolean(); + private final AtomicBoolean awaitTermination = new AtomicBoolean(); + + FakeManagedChannel(boolean terminates) { + this.terminates = terminates; + } + + boolean shutdownNowCalled() { + return shutdownNow.get(); + } + + boolean awaitTerminationCalled() { + return awaitTermination.get(); + } + + @Override + public ManagedChannel shutdown() { + return this; + } + + @Override + public ManagedChannel shutdownNow() { + shutdownNow.set(true); + return this; + } + + @Override + public boolean isShutdown() { + return shutdownNow.get(); + } + + @Override + public boolean isTerminated() { + return terminates && shutdownNow.get(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + awaitTermination.set(true); + awaitTerminationEntered.countDown(); + releaseAwaitTermination.await(10, TimeUnit.SECONDS); + return terminates; + } + + @Override + public ClientCall newCall( + MethodDescriptor methodDescriptor, CallOptions callOptions) { + throw new UnsupportedOperationException(); + } + + @Override + public String authority() { + return "fake"; + } + } +} diff --git a/exporters/sender/jdk/build.gradle.kts b/exporters/sender/jdk/build.gradle.kts new file mode 100644 index 00000000000..945fa9d3d6c --- /dev/null +++ b/exporters/sender/jdk/build.gradle.kts @@ -0,0 +1,19 @@ +import org.gradle.api.JavaVersion + +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") +} + +description = "OpenTelemetry JDK HttpSender" +otelJava.moduleName.set("io.opentelemetry.exporter.sender.jdk.internal") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.minJavaVersionSupported.set(JavaVersion.VERSION_11) +otelJava.osgiServiceLoaderProvides.set(listOf("io.opentelemetry.sdk.common.export.HttpSenderProvider")) + +dependencies { + annotationProcessor("com.google.auto.value:auto-value") + + implementation(project(":exporters:common")) + implementation(project(":sdk:common")) +} diff --git a/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/BodyPublisher.java b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/BodyPublisher.java new file mode 100644 index 00000000000..c454bfccdcd --- /dev/null +++ b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/BodyPublisher.java @@ -0,0 +1,109 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.jdk.internal; + +import java.net.http.HttpRequest; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Flow; +import java.util.function.Supplier; + +final class BodyPublisher implements HttpRequest.BodyPublisher { + + private final int length; + private final byte[] content; + private final Supplier bufSupplier; + + BodyPublisher(byte[] content, int length, Supplier bufSupplier) { + this.content = content; + this.length = length; + this.bufSupplier = bufSupplier; + } + + private List copyToBuffers() { + int offset = 0; + int length = this.length; + + List buffers = new ArrayList<>(); + while (length > 0) { + ByteBuffer b = bufSupplier.get(); + b.clear(); + int lengthToCopy = Math.min(b.capacity(), length); + b.put(content, offset, lengthToCopy); + offset += lengthToCopy; + length -= lengthToCopy; + b.flip(); + buffers.add(b); + } + return buffers; + } + + @Override + public long contentLength() { + return length; + } + + @Override + public void subscribe(Flow.Subscriber subscriber) { + Subscription subscription = new Subscription(copyToBuffers(), subscriber); + subscriber.onSubscribe(subscription); + } + + private static class Subscription implements Flow.Subscription { + + private volatile boolean isCompleted; + private final List buffers; + private final Flow.Subscriber subscriber; + + private int offset = 0; + + private Subscription(List buffers, Flow.Subscriber subscriber) { + this.buffers = buffers; + this.subscriber = subscriber; + } + + @Override + public void request(long n) { + if (isCompleted) { + return; + } + if (n <= 0) { + subscriber.onError(new IllegalArgumentException("Subscription request must be >= 0")); + isCompleted = true; + } else { + run(n); + } + } + + @Override + public void cancel() { + isCompleted = true; + } + + private synchronized void run(long requestedItems) { + if (isCompleted) { + return; + } + + long count = 0; + ByteBuffer next; + while (count < requestedItems) { + int nextIndex = offset++; + if (nextIndex >= buffers.size()) { + break; + } + next = buffers.get(nextIndex); + subscriber.onNext(next); + count++; + } + if (offset >= buffers.size()) { + isCompleted = true; + subscriber.onComplete(); + } + } + } +} diff --git a/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/ImmutableHttpResponse.java b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/ImmutableHttpResponse.java new file mode 100644 index 00000000000..4af860c696b --- /dev/null +++ b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/ImmutableHttpResponse.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.jdk.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.common.export.HttpResponse; + +@AutoValue +abstract class ImmutableHttpResponse implements HttpResponse { + + static ImmutableHttpResponse create(int statusCode, String statusMessage, byte[] responseBody) { + return new AutoValue_ImmutableHttpResponse(statusCode, statusMessage, responseBody); + } + + @SuppressWarnings("mutable") + @Override + public abstract byte[] getResponseBody(); +} diff --git a/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java new file mode 100644 index 00000000000..695c69ee074 --- /dev/null +++ b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSender.java @@ -0,0 +1,508 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.jdk.internal; + +import io.opentelemetry.api.impl.InstrumentationUtil; +import io.opentelemetry.exporter.internal.RetryUtil; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.HttpResponse; +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UncheckedIOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse.BodyHandlers; +import java.nio.ByteBuffer; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.OptionalLong; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.zip.GZIPInputStream; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLParameters; + +/** + * {@link HttpSender} which is backed by JDK {@link HttpClient}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class JdkHttpSender implements HttpSender { + + private static final Set retryableStatusCodes = RetryUtil.retryableHttpResponseCodes(); + + private static final ThreadLocal threadLocalBaos = + ThreadLocal.withInitial(NoCopyByteArrayOutputStream::new); + private static final ThreadLocal threadLocalByteBufPool = + ThreadLocal.withInitial(ByteBufferPool::new); + + private static final Logger logger = Logger.getLogger(JdkHttpSender.class.getName()); + + private final boolean managedExecutor; + private final ExecutorService executorService; + private final HttpClient client; + private final URI endpoint; + private final String contentType; + @Nullable private final Compressor compressor; + private final Duration timeout; + private final Supplier>> headerSupplier; + @Nullable private final RetryPolicy retryPolicy; + private final Predicate retryExceptionPredicate; + private final long maxResponseBodySize; + + // Visible for testing + JdkHttpSender( + HttpClient client, + URI endpoint, + String contentType, + @Nullable Compressor compressor, + Duration timeout, + Supplier>> headerSupplier, + @Nullable RetryPolicy retryPolicy, + @Nullable ExecutorService executorService, + long maxResponseBodySize) { + this.client = client; + this.endpoint = endpoint; + this.contentType = contentType; + this.compressor = compressor; + this.timeout = timeout; + this.headerSupplier = headerSupplier; + this.retryPolicy = retryPolicy; + this.retryExceptionPredicate = + Optional.ofNullable(retryPolicy) + .map(RetryPolicy::getRetryExceptionPredicate) + .orElse(JdkHttpSender::isRetryableException); + if (executorService == null) { + this.executorService = newExecutor(); + this.managedExecutor = true; + } else { + this.executorService = executorService; + this.managedExecutor = false; + } + this.maxResponseBodySize = maxResponseBodySize; + } + + JdkHttpSender( + URI endpoint, + String contentType, + @Nullable Compressor compressor, + Duration timeout, + Duration connectTimeout, + Supplier>> headerSupplier, + @Nullable RetryPolicy retryPolicy, + @Nullable ProxyOptions proxyOptions, + @Nullable SSLContext sslContext, + @Nullable ExecutorService executorService, + long maxResponseBodySize, + @Nullable List enabledProtocols) { + this( + configureClient(sslContext, connectTimeout, proxyOptions, enabledProtocols), + endpoint, + contentType, + compressor, + timeout, + headerSupplier, + retryPolicy, + executorService, + maxResponseBodySize); + } + + private static ExecutorService newExecutor() { + return new ThreadPoolExecutor( + 0, + Math.max(Runtime.getRuntime().availableProcessors(), 5), + 60, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + new DaemonThreadFactory("jdkhttp-executor")); + } + + private static HttpClient configureClient( + @Nullable SSLContext sslContext, + Duration connectTimeout, + @Nullable ProxyOptions proxyOptions, + @Nullable List enabledProtocols) { + HttpClient.Builder builder = HttpClient.newBuilder().connectTimeout(connectTimeout); + if (sslContext != null) { + builder.sslContext(sslContext); + } + if (proxyOptions != null) { + builder.proxy(proxyOptions.getProxySelector()); + } + if (enabledProtocols != null && !enabledProtocols.isEmpty()) { + SSLParameters params = new SSLParameters(); + params.setProtocols(enabledProtocols.toArray(new String[0])); + builder.sslParameters(params); + } + return builder.build(); + } + + @Override + public void send( + MessageWriter messageWriter, Consumer onResponse, Consumer onError) { + try { + InstrumentationUtil.suppressInstrumentation(() -> { + CompletableFuture unused = + CompletableFuture.supplyAsync( + () -> { + try { + return sendInternal(messageWriter); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }, + executorService) + .whenComplete((httpResponse, throwable) -> { + if (throwable != null) { + onError.accept(unwrap(throwable)); + return; + } + onResponse.accept(httpResponse); + }); + }); + } catch (RejectedExecutionException e) { + onError.accept(e); + } + } + + // supplyAsync wraps failures in CompletionException, and IOExceptions are additionally wrapped in + // UncheckedIOException above. Pass the original exception to onError, as OkHttpHttpSender does. + private static Throwable unwrap(Throwable throwable) { + Throwable cause = throwable; + if (cause instanceof CompletionException && cause.getCause() != null) { + cause = cause.getCause(); + } + if (cause instanceof UncheckedIOException && cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + // Visible for testing + HttpResponse sendInternal(MessageWriter requestBodyWriter) throws IOException { + long startTimeNanos = System.nanoTime(); + HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().uri(endpoint).timeout(timeout); + Map> headers = headerSupplier.get(); + if (headers != null) { + headers.forEach((key, values) -> values.forEach(value -> requestBuilder.header(key, value))); + } + requestBuilder.header("Content-Type", contentType); + // Advertise gzip and identity response encoding support. + requestBuilder.header("Accept-Encoding", "gzip, identity"); + + NoCopyByteArrayOutputStream os = threadLocalBaos.get(); + os.reset(); + if (compressor != null) { + requestBuilder.header("Content-Encoding", compressor.getEncoding()); + try (OutputStream compressed = compressor.compress(os)) { + requestBodyWriter.writeMessage(compressed); + } catch (IOException e) { + throw new IllegalStateException(e); + } + } else { + requestBodyWriter.writeMessage(os); + } + + ByteBufferPool byteBufferPool = threadLocalByteBufPool.get(); + requestBuilder.POST(new BodyPublisher(os.buf(), os.size(), byteBufferPool::getBuffer)); + + // If no retry policy, short circuit + if (retryPolicy == null) { + return toHttpResponse(sendRequest(requestBuilder, byteBufferPool)); + } + + long attempt = 0; + long nextBackoffNanos = retryPolicy.getInitialBackoff().toNanos(); + HttpResponse httpResponse = null; + IOException exception = null; + OptionalLong retryDelayNanos = OptionalLong.empty(); + do { + if (attempt > 0) { + long remainingNanos = timeout.toNanos() - (System.nanoTime() - startTimeNanos); + if (remainingNanos <= 0) { + break; + } + // Compute and sleep for backoff + long currentBackoffNanos = + Math.min(nextBackoffNanos, retryPolicy.getMaxBackoff().toNanos()); + long requestedBackoffNanos = + retryDelayNanos.isPresent() + ? retryDelayNanos.getAsLong() + : (long) (ThreadLocalRandom.current().nextDouble(0.8d, 1.2d) * currentBackoffNanos); + long backoffNanos = Math.min(requestedBackoffNanos, remainingNanos); + nextBackoffNanos = (long) (currentBackoffNanos * retryPolicy.getBackoffMultiplier()); + retryDelayNanos = OptionalLong.empty(); + try { + TimeUnit.NANOSECONDS.sleep(backoffNanos); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + break; // Break out and return response or throw + } + // If after sleeping we've exceeded timeoutNanos, break out and return + // response or throw + if ((System.nanoTime() - startTimeNanos) >= timeout.toNanos()) { + break; + } + } + httpResponse = null; + exception = null; + requestBuilder.timeout(timeout.minusNanos(System.nanoTime() - startTimeNanos)); + try { + java.net.http.HttpResponse rawResponse = + sendRequest(requestBuilder, byteBufferPool); + httpResponse = toHttpResponse(rawResponse); + boolean retryable = retryableStatusCodes.contains(rawResponse.statusCode()); + if (logger.isLoggable(Level.FINER)) { + logger.log( + Level.FINER, + "Attempt " + + attempt + + " returned " + + (retryable ? "retryable" : "non-retryable") + + " response: " + + responseStringRepresentation(httpResponse)); + } + if (!retryable) { + return httpResponse; + } + retryDelayNanos = retryDelayNanos(rawResponse); + } catch (IOException e) { + exception = e; + boolean retryable = retryExceptionPredicate.test(exception); + if (logger.isLoggable(Level.FINER)) { + logger.log( + Level.FINER, + "Attempt " + + attempt + + " failed with " + + (retryable ? "retryable" : "non-retryable") + + " exception", + exception); + } + if (!retryable) { + throw exception; + } + } + } while (++attempt < retryPolicy.getMaxAttempts()); + + if (httpResponse != null) { + return httpResponse; + } + throw exception; + } + + private static String responseStringRepresentation(HttpResponse response) { + return "HttpResponse{code=" + response.getStatusCode() + "}"; + } + + private java.net.http.HttpResponse sendRequest( + HttpRequest.Builder requestBuilder, ByteBufferPool byteBufferPool) throws IOException { + try { + return client.send(requestBuilder.build(), BodyHandlers.ofInputStream()); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } finally { + byteBufferPool.resetPool(); + } + } + + private static boolean isRetryableException(IOException throwable) { + // Almost all IOExceptions we've encountered are transient retryable, so we + // opt out of specific + // IOExceptions that are unlikely to resolve rather than opting in. + // Known retryable IOException messages: "Connection reset", "/{remote + // ip}:{remote port} GOAWAY + // received" + // Known retryable HttpTimeoutException messages: "request timed out" + // Known retryable HttpConnectTimeoutException messages: "HTTP connect timed + // out" + // ResponseBodyTooLargeException and UnsupportedContentEncodingException are permanent errors: + // a larger body or unsupported encoding will not resolve on retry. + return !(throwable instanceof SSLException) + && !(throwable instanceof ResponseBodyTooLargeException) + && !(throwable instanceof UnsupportedContentEncodingException); + } + + private static final class ResponseBodyTooLargeException extends IOException { + ResponseBodyTooLargeException(String message) { + super(message); + } + } + + private static final class UnsupportedContentEncodingException extends IOException { + UnsupportedContentEncodingException(String message) { + super(message); + } + } + + private static class NoCopyByteArrayOutputStream extends ByteArrayOutputStream { + NoCopyByteArrayOutputStream() { + super(retryableStatusCodes.size()); + } + + private byte[] buf() { + return buf; + } + } + + private HttpResponse toHttpResponse(java.net.http.HttpResponse response) + throws IOException { + int statusCode = response.statusCode(); + // Read up to maxResponseBodySize + 1 bytes. Reading exactly one byte more than the limit + // lets us detect overflow: if we read more than maxResponseBodySize bytes, the body exceeded + // the limit. A body exactly at the limit will read no further (EOF is reached first). + // If maxResponseBodySize is >= Integer.MAX_VALUE, adding 1 would overflow (long) or exceed + // what an int can hold. In that case use Integer.MAX_VALUE β€” the overflow check can never + // trigger for such a large limit. + int readUpTo = + maxResponseBodySize >= Integer.MAX_VALUE + ? Integer.MAX_VALUE + : (int) (maxResponseBodySize + 1); + + String contentEncoding = response.headers().firstValue("Content-Encoding").orElse(null); + if (contentEncoding != null + && !"gzip".equalsIgnoreCase(contentEncoding) + && !"identity".equalsIgnoreCase(contentEncoding)) { + try (InputStream ignored = response.body()) { + throw new UnsupportedContentEncodingException( + "Unsupported Content-Encoding: " + contentEncoding); + } + } + boolean decompress = "gzip".equalsIgnoreCase(contentEncoding); + + byte[] bodyBytes; + try (InputStream rawIs = response.body()) { + // The limit is applied to the decompressed bytes. + InputStream is = decompress ? new GZIPInputStream(rawIs) : rawIs; + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte[] buf = new byte[4 * 0x400]; // 4KB + int n; + while (baos.size() < readUpTo + && (n = is.read(buf, 0, Math.min(buf.length, readUpTo - baos.size()))) != -1) { + baos.write(buf, 0, n); + } + bodyBytes = baos.toByteArray(); + } catch (IOException e) { + bodyBytes = new byte[0]; + logger.log(Level.WARNING, "Failed to read response body", e); + } + if (bodyBytes.length > maxResponseBodySize) { + throw new ResponseBodyTooLargeException( + "HTTP response body exceeded limit of " + maxResponseBodySize + " bytes"); + } + return ImmutableHttpResponse.create(statusCode, String.valueOf(statusCode), bodyBytes); + } + + private static class ByteBufferPool { + + // TODO: make configurable? + private static final int BUF_SIZE = 16 * 1024; + + private final ConcurrentLinkedQueue pool = new ConcurrentLinkedQueue<>(); + private final ConcurrentLinkedQueue out = new ConcurrentLinkedQueue<>(); + + private ByteBuffer getBuffer() { + ByteBuffer buffer = pool.poll(); + if (buffer == null) { + buffer = ByteBuffer.allocate(BUF_SIZE); + } + out.offer(buffer); + return buffer; + } + + private void resetPool() { + ByteBuffer buf = out.poll(); + while (buf != null) { + pool.offer(buf); + buf = out.poll(); + } + } + } + + private static OptionalLong retryDelayNanos(java.net.http.HttpResponse response) { + return RetryUtil.retryAfterNanos(response.headers().firstValue("Retry-After").orElse(null)); + } + + @Override + public CompletableResultCode shutdown() { + if (!managedExecutor) { + return closeClient(); + } + + // Use shutdownNow() to interrupt in-flight requests, including retry backoff sleeps + executorService.shutdownNow(); + + // Wait for threads to terminate in a background thread. Closing the client also blocks until + // in-flight requests complete, so it must not run on the caller's thread either. + CompletableResultCode result = new CompletableResultCode(); + Thread terminationThread = + new Thread( + () -> { + try { + // Wait up to 5 seconds for threads to terminate + // Even if timeout occurs, we proceed since these are daemon threads + boolean terminated = executorService.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) { + logger.log( + Level.WARNING, + "Executor did not terminate within 5 seconds, proceeding with shutdown since threads are daemon threads."); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + CompletableResultCode closeResult = closeClient(); + if (closeResult.isSuccess()) { + result.succeed(); + } else { + result.failExceptionally(closeResult.getFailureThrowable()); + } + } + }, + "jdkhttp-shutdown"); + terminationThread.setDaemon(true); + terminationThread.start(); + return result; + } + + private CompletableResultCode closeClient() { + if (AutoCloseable.class.isInstance(client)) { + try { + AutoCloseable.class.cast(client).close(); + } catch (Exception e) { + return CompletableResultCode.ofExceptionalFailure(e); + } + } + return CompletableResultCode.ofSuccess(); + } +} diff --git a/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderProvider.java b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderProvider.java new file mode 100644 index 00000000000..1a6c0948893 --- /dev/null +++ b/exporters/sender/jdk/src/main/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderProvider.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.jdk.internal; + +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.HttpSenderConfig; +import io.opentelemetry.sdk.common.export.HttpSenderProvider; + +/** + * {@link HttpSender} SPI implementation for {@link JdkHttpSender}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class JdkHttpSenderProvider implements HttpSenderProvider { + + @Override + public HttpSender createSender(HttpSenderConfig httpSenderConfig) { + return new JdkHttpSender( + httpSenderConfig.getEndpoint(), + httpSenderConfig.getContentType(), + httpSenderConfig.getCompressor(), + httpSenderConfig.getTimeout(), + httpSenderConfig.getConnectTimeout(), + httpSenderConfig.getHeadersSupplier(), + httpSenderConfig.getRetryPolicy(), + httpSenderConfig.getProxyOptions(), + httpSenderConfig.getSslContext(), + httpSenderConfig.getExecutorService(), + httpSenderConfig.getMaxResponseBodySize(), + httpSenderConfig.getEnabledProtocols()); + } +} diff --git a/exporters/sender/jdk/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider b/exporters/sender/jdk/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider new file mode 100644 index 00000000000..aad2c64f330 --- /dev/null +++ b/exporters/sender/jdk/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.sender.jdk.internal.JdkHttpSenderProvider diff --git a/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java b/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java new file mode 100644 index 00000000000..3fce0d6d0b8 --- /dev/null +++ b/exporters/sender/jdk/src/test/java/io/opentelemetry/exporter/sender/jdk/internal/JdkHttpSenderTest.java @@ -0,0 +1,493 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.jdk.internal; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.impl.InstrumentationUtil; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.HttpResponse; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.reflect.Method; +import java.net.ConnectException; +import java.net.ServerSocket; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpConnectTimeoutException; +import java.net.http.HttpHeaders; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLException; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledForJreRange; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class JdkHttpSenderTest { + + private final HttpClient realHttpClient = + HttpClient.newBuilder().connectTimeout(Duration.ofMillis(10)).build(); + @Mock private HttpClient mockHttpClient; + private JdkHttpSender sender; + + @BeforeEach + void setup() throws IOException, InterruptedException { + // Can't directly spy on HttpClient for some reason, so create a real instance and a mock that + // delegates to the real thing + when(mockHttpClient.send(any(), any())) + .thenAnswer(invocation -> + realHttpClient.send(invocation.getArgument(0), invocation.getArgument(1))); + sender = + new JdkHttpSender( + mockHttpClient, + // Connecting to a non-routable IP address to trigger connection timeout + URI.create("http://10.255.255.1"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + RetryPolicy.builder().setMaxAttempts(2).setInitialBackoff(Duration.ofMillis(1)).build(), + null, + Long.MAX_VALUE); + } + + @Test + @EnabledForJreRange( + minVersion = 21, + disabledReason = "HttpClient#close has been added in Java 21") + void testShutdown() throws Exception { + CompletableResultCode result = sender.shutdown(); + result.join(1, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isTrue(); + Method close = HttpClient.class.getMethod("close"); + close.invoke(verify(mockHttpClient)); + } + + @Test + @EnabledForJreRange( + minVersion = 21, + disabledReason = "HttpClient#close has been added in Java 21") + void testShutdownException() throws Exception { + Method close = HttpClient.class.getMethod("close"); + close.invoke(doThrow(new RuntimeException("testShutdownException")).when(mockHttpClient)); + + CompletableResultCode result = sender.shutdown(); + result.join(1, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()).isInstanceOf(RuntimeException.class); + assertThat(result.getFailureThrowable().getMessage()).isEqualTo("testShutdownException"); + } + + @Test + void shutdown_managedExecutor_awaitsTermination() { + CompletableResultCode result = sender.shutdown(); + result.join(10, TimeUnit.SECONDS); + + assertThat(result.isSuccess()).isTrue(); + assertThat(sender) + .extracting("executorService", as(InstanceOfAssertFactories.type(ExecutorService.class))) + .satisfies(executor -> assertThat(executor.isTerminated()).isTrue()); + } + + @Test + void shutdown_nonManagedExecutor_doesNotShutDownExecutor() { + ExecutorService customExecutor = Executors.newSingleThreadExecutor(); + try { + JdkHttpSender testSender = + new JdkHttpSender( + mockHttpClient, + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + null, + customExecutor, + Long.MAX_VALUE); + + CompletableResultCode result = testSender.shutdown(); + + assertThat(result.isDone()).isTrue(); + assertThat(result.isSuccess()).isTrue(); + assertThat(customExecutor.isShutdown()).isFalse(); + } finally { + customExecutor.shutdownNow(); + } + } + + @Test + void sendInternal_RetryableConnectTimeoutException() throws IOException, InterruptedException { + assertThatThrownBy(() -> sender.sendInternal(new NoOpRequestBodyWriter())) + .satisfies(e -> + assertThat((e instanceof HttpConnectTimeoutException) || (e instanceof IOException)) + .isTrue()); + + verify(mockHttpClient, times(2)).send(any(), any()); + } + + @Test + void sendInternal_RetryableConnectException() throws IOException, InterruptedException { + sender = + new JdkHttpSender( + mockHttpClient, + // Connecting to localhost on an unused port address to trigger + // java.net.ConnectException (or java.net.http.HttpConnectTimeoutException on linux java + // 11+) + URI.create("http://localhost:" + freePort()), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + RetryPolicy.builder().setMaxAttempts(2).setInitialBackoff(Duration.ofMillis(1)).build(), + null, + Long.MAX_VALUE); + + assertThatThrownBy(() -> sender.sendInternal(new NoOpRequestBodyWriter())) + .satisfies(e -> + assertThat( + (e instanceof ConnectException) || (e instanceof HttpConnectTimeoutException)) + .isTrue()); + + verify(mockHttpClient, times(2)).send(any(), any()); + } + + private static int freePort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + void sendInternal_RetryableIoException() throws IOException, InterruptedException { + doThrow(new IOException("error!")).when(mockHttpClient).send(any(), any()); + + assertThatThrownBy(() -> sender.sendInternal(new NoOpRequestBodyWriter())) + .isInstanceOf(IOException.class) + .hasMessage("error!"); + + verify(mockHttpClient, times(2)).send(any(), any()); + } + + @Test + void sendInternal_NonRetryableException() throws IOException, InterruptedException { + doThrow(new SSLException("unknown error")).when(mockHttpClient).send(any(), any()); + + assertThatThrownBy(() -> sender.sendInternal(new NoOpRequestBodyWriter())) + .isInstanceOf(IOException.class) + .hasMessage("unknown error"); + + verify(mockHttpClient, times(1)).send(any(), any()); + } + + @Test + void defaultExecutor_isBounded() { + JdkHttpSender defaultSender = + new JdkHttpSender( + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofNanos(1), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + Long.MAX_VALUE, + null); + + try { + int expectedMax = Math.max(Runtime.getRuntime().availableProcessors(), 5); + assertThat(defaultSender) + .extracting( + "executorService", as(InstanceOfAssertFactories.type(ThreadPoolExecutor.class))) + .satisfies(executor -> { + assertThat(executor.getMaximumPoolSize()).isEqualTo(expectedMax); + assertThat(executor.getRejectedExecutionHandler()) + .isInstanceOf(ThreadPoolExecutor.AbortPolicy.class); + }); + } finally { + defaultSender.shutdown(); + } + } + + @Test + void connectTimeout() { + sender = + new JdkHttpSender( + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofNanos(1), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + Long.MAX_VALUE, + null); + + assertThat(sender) + .extracting("client", as(InstanceOfAssertFactories.type(HttpClient.class))) + .satisfies(httpClient -> + assertThat(httpClient.connectTimeout().get()).isEqualTo(Duration.ofSeconds(10))); + } + + @SuppressWarnings("unchecked") + @Test + void send_successfulResponse_callsOnResponse() throws Exception { + java.net.http.HttpResponse mockJdkResponse = + mock(java.net.http.HttpResponse.class); + when(mockJdkResponse.statusCode()).thenReturn(200); + when(mockJdkResponse.body()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(mockJdkResponse.headers()) + .thenReturn(HttpHeaders.of(Collections.emptyMap(), (a, b) -> true)); + doReturn(mockJdkResponse).when(mockHttpClient).send(any(), any()); + + JdkHttpSender testSender = + new JdkHttpSender( + mockHttpClient, + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + Long.MAX_VALUE); + + try { + CountDownLatch latch = new CountDownLatch(1); + AtomicReference responseRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + + testSender.send( + new NoOpRequestBodyWriter(), + response -> { + responseRef.set(response); + latch.countDown(); + }, + error -> { + errorRef.set(error); + latch.countDown(); + }); + + assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(responseRef.get()).isNotNull(); + assertThat(responseRef.get().getStatusCode()).isEqualTo(200); + assertThat(errorRef.get()).isNull(); + } finally { + testSender.shutdown(); + } + } + + @SuppressWarnings("unchecked") + @Test + void sendInternal_unsupportedContentEncoding_closesBody() throws Exception { + AtomicBoolean closed = new AtomicBoolean(); + java.net.http.HttpResponse mockJdkResponse = + mock(java.net.http.HttpResponse.class); + when(mockJdkResponse.statusCode()).thenReturn(200); + when(mockJdkResponse.body()) + .thenReturn( + new ByteArrayInputStream(new byte[0]) { + @Override + public void close() throws IOException { + closed.set(true); + super.close(); + } + }); + when(mockJdkResponse.headers()) + .thenReturn( + HttpHeaders.of( + Collections.singletonMap("Content-Encoding", Collections.singletonList("br")), + (a, b) -> true)); + doReturn(mockJdkResponse).when(mockHttpClient).send(any(), any()); + + JdkHttpSender testSender = + new JdkHttpSender( + mockHttpClient, + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + Long.MAX_VALUE); + + try { + assertThatThrownBy(() -> testSender.sendInternal(new NoOpRequestBodyWriter())) + .isInstanceOf(IOException.class) + .hasMessage("Unsupported Content-Encoding: br"); + assertThat(closed.get()).isTrue(); + } finally { + testSender.shutdown(); + } + } + + @Test + void send_ioException_callsOnError() throws Exception { + IOException exception = new IOException("send failed"); + doThrow(exception).when(mockHttpClient).send(any(), any()); + + JdkHttpSender testSender = + new JdkHttpSender( + mockHttpClient, + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + Long.MAX_VALUE); + + try { + CountDownLatch latch = new CountDownLatch(1); + AtomicReference responseRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + + testSender.send( + new NoOpRequestBodyWriter(), + response -> { + responseRef.set(response); + latch.countDown(); + }, + error -> { + errorRef.set(error); + latch.countDown(); + }); + + assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(errorRef.get()).isSameAs(exception); + assertThat(responseRef.get()).isNull(); + } finally { + testSender.shutdown(); + } + } + + @Test + void send_rejectedExecution_callsOnError() { + ThreadPoolExecutor executor = + new ThreadPoolExecutor(0, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<>()); + executor.shutdown(); + + JdkHttpSender testSender = + new JdkHttpSender( + mockHttpClient, + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + null, + executor, + Long.MAX_VALUE); + + AtomicReference responseRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + + testSender.send(new NoOpRequestBodyWriter(), responseRef::set, errorRef::set); + + assertThat(errorRef.get()).isNotNull(); + assertThat(errorRef.get()).isInstanceOf(RejectedExecutionException.class); + assertThat(responseRef.get()).isNull(); + } + + @SuppressWarnings("unchecked") + @Test + void send_suppressesInstrumentation() throws Exception { + java.net.http.HttpResponse mockJdkResponse = + mock(java.net.http.HttpResponse.class); + when(mockJdkResponse.statusCode()).thenReturn(200); + when(mockJdkResponse.body()).thenReturn(new ByteArrayInputStream(new byte[0])); + when(mockJdkResponse.headers()) + .thenReturn(HttpHeaders.of(Collections.emptyMap(), (a, b) -> true)); + + AtomicBoolean suppressed = new AtomicBoolean(false); + doAnswer( + invocation -> { + suppressed.set(InstrumentationUtil.shouldSuppressInstrumentation(Context.current())); + return mockJdkResponse; + }) + .when(mockHttpClient) + .send(any(), any()); + + // Context.taskWrapping stands in for the java agent's executor instrumentation, which + // propagates the calling thread's context to the thread the request is sent on. + ExecutorService executor = Context.taskWrapping(Executors.newSingleThreadExecutor()); + JdkHttpSender testSender = + new JdkHttpSender( + mockHttpClient, + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Collections::emptyMap, + null, + executor, + Long.MAX_VALUE); + + try { + CountDownLatch latch = new CountDownLatch(1); + + testSender.send( + new NoOpRequestBodyWriter(), response -> latch.countDown(), error -> latch.countDown()); + + assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue(); + assertThat(suppressed.get()).isTrue(); + } finally { + testSender.shutdown(); + executor.shutdownNow(); + } + } + + private static class NoOpRequestBodyWriter implements MessageWriter { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + } +} diff --git a/exporters/sender/okhttp/build.gradle.kts b/exporters/sender/okhttp/build.gradle.kts new file mode 100644 index 00000000000..5e09f886ef2 --- /dev/null +++ b/exporters/sender/okhttp/build.gradle.kts @@ -0,0 +1,37 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry OkHttp Senders" +otelJava.moduleName.set("io.opentelemetry.exporter.sender.okhttp.internal") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + "io.opentelemetry.sdk.common.export.HttpSenderProvider" +)) +// okhttp3, okio, and org.jspecify.annotations are not OSGi bundles; imports must be optional. +// (org.jspecify.annotations is pulled in by OkHttp's Kotlin-compiled types, not this bundle's code.) +otelJava.osgiUnversionedOptionalPackages.set(listOf("okhttp3", "okio", "org.jspecify.annotations")) + +tasks.withType().configureEach { + systemProperty( + "java.security.properties", + file("src/test/resources/enable-legacy-tls.security").absolutePath + ) +} + +dependencies { + implementation(project(":exporters:common")) + implementation(project(":sdk:common")) + + annotationProcessor("com.google.auto.value:auto-value") + + implementation("com.squareup.okhttp3:okhttp") + + compileOnly("io.grpc:grpc-stub") + + testImplementation("com.linecorp.armeria:armeria-junit5") +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/GrpcRequestBody.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/GrpcRequestBody.java new file mode 100644 index 00000000000..1dc673cf3af --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/GrpcRequestBody.java @@ -0,0 +1,83 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.IOException; +import javax.annotation.Nullable; +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; + +/** + * A {@link RequestBody} for reading from a {@link Marshaler} and writing in gRPC wire format. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class GrpcRequestBody extends RequestBody { + + private static final int HEADER_LENGTH = 5; + + private static final byte UNCOMPRESSED_FLAG = 0; + private static final byte COMPRESSED_FLAG = 1; + + private static final MediaType GRPC_MEDIA_TYPE = MediaType.parse("application/grpc"); + + private final MessageWriter messageWriter; + private final int messageSize; + private final int contentLength; + @Nullable private final Compressor compressor; + + /** Creates a new {@link GrpcRequestBody}. */ + public GrpcRequestBody(MessageWriter messageWriter, @Nullable Compressor compressor) { + this.messageWriter = messageWriter; + this.compressor = compressor; + + messageSize = messageWriter.getContentLength(); + if (compressor != null) { + // Content length not known since we want to compress on the I/O thread. + contentLength = -1; + } else { + contentLength = HEADER_LENGTH + messageSize; + } + } + + @Nullable + @Override + public MediaType contentType() { + return GRPC_MEDIA_TYPE; + } + + @Override + public long contentLength() { + return contentLength; + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (compressor == null) { + sink.writeByte(UNCOMPRESSED_FLAG); + sink.writeInt(messageSize); + messageWriter.writeMessage(sink.outputStream()); + } else { + try (Buffer compressedBody = new Buffer()) { + try (BufferedSink compressedSink = + Okio.buffer(Okio.sink(compressor.compress(compressedBody.outputStream())))) { + messageWriter.writeMessage(compressedSink.outputStream()); + } + sink.writeByte(COMPRESSED_FLAG); + int compressedBytes = (int) compressedBody.size(); + sink.writeInt(compressedBytes); + sink.write(compressedBody, compressedBytes); + } + } + } +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/ImmutableGrpcResponse.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/ImmutableGrpcResponse.java new file mode 100644 index 00000000000..cb229c2a6a2 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/ImmutableGrpcResponse.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import javax.annotation.Nullable; + +@AutoValue +abstract class ImmutableGrpcResponse implements GrpcResponse { + + static ImmutableGrpcResponse create( + GrpcStatusCode statusCode, @Nullable String statusDescription, byte[] responseMessage) { + return new AutoValue_ImmutableGrpcResponse(statusCode, statusDescription, responseMessage); + } + + @SuppressWarnings("mutable") + @Override + public abstract byte[] getResponseMessage(); +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/ImmutableHttpResponse.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/ImmutableHttpResponse.java new file mode 100644 index 00000000000..80fafddd833 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/ImmutableHttpResponse.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.common.export.HttpResponse; + +@AutoValue +abstract class ImmutableHttpResponse implements HttpResponse { + + static ImmutableHttpResponse create(int statusCode, String statusMessage, byte[] responseBody) { + return new AutoValue_ImmutableHttpResponse(statusCode, statusMessage, responseBody); + } + + @SuppressWarnings("mutable") + @Override + public abstract byte[] getResponseBody(); +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java new file mode 100644 index 00000000000..f17355cea43 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSender.java @@ -0,0 +1,530 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: + +/* + * Copyright 2014 The gRPC Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.api.impl.InstrumentationUtil; +import io.opentelemetry.exporter.internal.RetryUtil; +import io.opentelemetry.exporter.internal.TlsUtil; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.OptionalLong; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.X509TrustManager; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.ConnectionSpec; +import okhttp3.Dispatcher; +import okhttp3.HttpUrl; +import okhttp3.OkHttpClient; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.TlsVersion; +import okio.Buffer; +import okio.GzipSource; + +/** + * A {@link GrpcSender} which uses OkHttp instead of grpc-java. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OkHttpGrpcSender implements GrpcSender { + + private static final Logger logger = Logger.getLogger(OkHttpGrpcSender.class.getName()); + + private static final String GRPC_STATUS = "grpc-status"; + private static final String GRPC_MESSAGE = "grpc-message"; + + private final Object shutdownLock = new Object(); + private boolean isShutdown; + private final boolean managedExecutor; + private final OkHttpClient client; + private final HttpUrl url; + @Nullable private final Compressor compressor; + private final Supplier>> headersSupplier; + private final long maxResponseBodySize; + @Nullable private final RetryPolicy retryPolicy; + private final long timeoutNanos; + + /** Creates a new {@link OkHttpGrpcSender}. */ + @SuppressWarnings("TooManyParameters") + public OkHttpGrpcSender( + String endpoint, + @Nullable Compressor compressor, + Duration timeout, + Duration connectTimeout, + Supplier>> headersSupplier, + @Nullable RetryPolicy retryPolicy, + @Nullable SSLContext sslContext, + @Nullable X509TrustManager trustManager, + @Nullable ExecutorService executorService, + long maxResponseBodySize, + @Nullable List enabledProtocols) { + int callTimeoutMillis = (int) Math.min(timeout.toMillis(), Integer.MAX_VALUE); + int connectTimeoutMillis = (int) Math.min(connectTimeout.toMillis(), Integer.MAX_VALUE); + this.timeoutNanos = TimeUnit.MILLISECONDS.toNanos(callTimeoutMillis); + + Dispatcher dispatcher; + if (executorService == null) { + dispatcher = OkHttpUtil.newDispatcher(); + this.managedExecutor = true; + } else { + dispatcher = new Dispatcher(executorService); + this.managedExecutor = false; + } + + OkHttpClient.Builder clientBuilder = + new OkHttpClient.Builder() + .dispatcher(dispatcher) + .callTimeout(Duration.ofMillis(callTimeoutMillis)) + .connectTimeout(Duration.ofMillis(connectTimeoutMillis)); + boolean isPlainHttp = endpoint.startsWith("http://"); + if (isPlainHttp) { + clientBuilder.connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT)); + clientBuilder.protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE)); + } else { + clientBuilder.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); + if (sslContext != null) { + X509TrustManager effectiveTrustManager = trustManager; + if (effectiveTrustManager == null) { + try { + effectiveTrustManager = TlsUtil.defaultTrustManager(); + } catch (SSLException e) { + throw new IllegalStateException("Unable to initialize default trust manager", e); + } + } + clientBuilder.sslSocketFactory(sslContext.getSocketFactory(), effectiveTrustManager); + } + if (enabledProtocols != null && !enabledProtocols.isEmpty()) { + TlsVersion[] versions = + enabledProtocols.stream().map(TlsVersion::forJavaName).toArray(TlsVersion[]::new); + clientBuilder.connectionSpecs( + Collections.singletonList( + new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) + .tlsVersions(versions) + .build())); + } + } + + this.client = clientBuilder.build(); + this.compressor = compressor; + this.headersSupplier = headersSupplier; + this.url = HttpUrl.get(endpoint); + this.maxResponseBodySize = maxResponseBodySize; + this.retryPolicy = retryPolicy; + } + + @Override + public void send( + MessageWriter messageWriter, Consumer onResponse, Consumer onError) { + RetryState retryState = newRetryState(); + Request.Builder requestBuilder = new Request.Builder().url(url); + + Map> headers = headersSupplier.get(); + if (headers != null) { + headers.forEach( + (key, values) -> values.forEach(value -> requestBuilder.addHeader(key, value))); + } + requestBuilder.addHeader("te", "trailers"); + // Mirror grpc-java's default DecompressorRegistry which advertises identity and gzip. + requestBuilder.addHeader("grpc-accept-encoding", "identity,gzip"); + if (compressor != null) { + requestBuilder.addHeader("grpc-encoding", compressor.getEncoding()); + } + requestBuilder.post(new GrpcRequestBody(messageWriter, compressor)); + + sendAttempt(requestBuilder, messageWriter, onResponse, onError, 0, retryState); + } + + @Nullable + private RetryState newRetryState() { + return retryPolicy == null + ? null + : new RetryState( + retryPolicy, + retryPolicy.getRetryExceptionPredicate() == null + ? RetryState::isRetryableException + : retryPolicy.getRetryExceptionPredicate(), + RetryState::defaultSleeper, + RetryState::defaultRandomJitter, + timeoutNanos, + System::nanoTime); + } + + private void sendAttempt( + Request.Builder requestBuilder, + MessageWriter messageWriter, + Consumer onResponse, + Consumer onError, + int attempt, + @Nullable RetryState retryState) { + + try { + InstrumentationUtil.suppressInstrumentation(() -> { + Call call = client.newCall(requestBuilder.build()); + if (retryState != null && !retryState.configureCallTimeout(call)) { + onError.accept(new SocketTimeoutException("Call timed out")); + return; + } + startCall( + call, + attempt, + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + boolean retryable = retryState != null && retryState.shouldRetryOnException(e); + if (retryState != null && logger.isLoggable(Level.FINER)) { + logger.log( + Level.FINER, + "Attempt " + + attempt + + " failed with " + + (retryable ? "retryable" : "non-retryable") + + " exception", + e); + } + if (!call.isCanceled() + && retryState != null + && retryState.canRetry(attempt) + && retryable + && retryState.backoff(OptionalLong.empty())) { + sendAttempt( + requestBuilder, messageWriter, onResponse, onError, attempt + 1, retryState); + } else { + onError.accept(e); + } + } + + @Override + public void onResponse(Call call, Response response) { + handleResponse( + response, + (resolvedResponse, canRetry) -> { + boolean retryable = canRetry && isRetryable(resolvedResponse); + if (retryState != null && logger.isLoggable(Level.FINER)) { + logger.log( + Level.FINER, + "Attempt " + + attempt + + " returned " + + (retryable ? "retryable" : "non-retryable") + + " response: grpc-status=" + + resolvedResponse.getStatusCode() + + ", grpc-message=" + + resolvedResponse.getStatusDescription()); + } + if (retryState != null + && retryState.canRetry(attempt) + && retryable + && retryState.backoff(OptionalLong.empty())) { + sendAttempt( + requestBuilder, + messageWriter, + onResponse, + onError, + attempt + 1, + retryState); + } else { + onResponse.accept(resolvedResponse); + } + }); + } + }); + }); + } catch (RejectedExecutionException e) { + onError.accept(e); + } + } + + private void startCall(Call call, int attempt, Callback callback) { + if (attempt == 0) { + enqueue(call, callback); + return; + } + // Retries already run on a dispatcher thread, so execute them on this thread instead of + // enqueueing a new call, which a bounded executor would reject. + boolean shutdown; + synchronized (shutdownLock) { + shutdown = isShutdown; + } + if (shutdown) { + call.cancel(); + callback.onFailure(call, new IOException("Canceled")); + return; + } + try { + callback.onResponse(call, call.execute()); + } catch (IOException e) { + callback.onFailure(call, e); + } + } + + private void enqueue(Call call, Callback callback) { + synchronized (shutdownLock) { + if (!isShutdown) { + call.enqueue(callback); + return; + } + } + call.cancel(); + callback.onFailure(call, new IOException("Canceled")); + } + + void handleResponse(Response response, Consumer onResponse) { + handleResponse(response, (resolvedResponse, ignored) -> onResponse.accept(resolvedResponse)); + } + + private void handleResponse(Response response, BiConsumer onResponse) { + try (ResponseBody body = response.body()) { + // A gRPC message frame has a 5-byte header: 1 compression-flag byte + 4 message-length + // bytes. Read the header first so that the size limit applies to the message payload only, + // not the framing overhead. + boolean compressed; + try { + compressed = body.source().readByte() != 0; + body.source().skip(4); // message length β€” we bound reads by EOF instead + } catch (IOException e) { + logger.log(Level.FINE, "Invalid gRPC response frame", e); + GrpcResponse resolvedResponse = + ImmutableGrpcResponse.create(grpcStatus(response), grpcMessage(response), new byte[0]); + onResponse.accept( + resolvedResponse, resolvedResponse.getStatusCode() != GrpcStatusCode.UNKNOWN); + return; + } + + // Read up to maxResponseBodySize + 1 bytes. Reading exactly one byte more than the limit + // lets us detect overflow: if the buffer ends up larger than maxResponseBodySize, the body + // exceeded the limit. A body exactly at the limit will only fill the buffer to + // maxResponseBodySize (EOF is reached before the extra byte is read). + // If maxResponseBodySize is Long.MAX_VALUE, adding 1 would overflow. In that case use + // Long.MAX_VALUE directly β€” the overflow check can never trigger for such a large limit. + long readUpTo = + maxResponseBodySize == Long.MAX_VALUE ? Long.MAX_VALUE : maxResponseBodySize + 1; + Buffer wireBuffer = new Buffer(); + try { + while (wireBuffer.size() <= maxResponseBodySize) { + long n = body.source().read(wireBuffer, readUpTo - wireBuffer.size()); + if (n == -1L) { + break; + } + } + } catch (IOException e) { + logger.log(Level.FINE, "Failed to read response body", e); + } + + if (wireBuffer.size() > maxResponseBodySize) { + onResponse.accept(responseMessageTooLarge(maxResponseBodySize), false); + return; + } + + // Must consume body before accessing trailers + byte[] bodyBytes = new byte[0]; + if (!compressed) { + bodyBytes = wireBuffer.readByteArray(); + } else { + // Compressed: validate the encoding and decompress with a post-decompression size limit + String encoding = response.header("grpc-encoding"); + if (!"gzip".equalsIgnoreCase(encoding)) { + onResponse.accept(responseUnsupportedGrpcEncoding(encoding), false); + return; + } + try { + GzipSource gzipSource = new GzipSource(wireBuffer); + Buffer decompressedBuffer = new Buffer(); + while (decompressedBuffer.size() <= maxResponseBodySize) { + long n = gzipSource.read(decompressedBuffer, readUpTo - decompressedBuffer.size()); + if (n == -1L) { + break; + } + } + if (decompressedBuffer.size() > maxResponseBodySize) { + onResponse.accept(responseMessageTooLarge(maxResponseBodySize), false); + return; + } + bodyBytes = decompressedBuffer.readByteArray(); + } catch (IOException e) { + logger.log(Level.FINE, "Failed to decompress response body", e); + } + } + onResponse.accept( + ImmutableGrpcResponse.create(grpcStatus(response), grpcMessage(response), bodyBytes), + true); + } + } + + private static GrpcResponse responseMessageTooLarge(long maxResponseBodySize) { + return ImmutableGrpcResponse.create( + GrpcStatusCode.RESOURCE_EXHAUSTED, + "gRPC response body exceeded limit of " + maxResponseBodySize + " bytes", + new byte[0]); + } + + private static GrpcResponse responseUnsupportedGrpcEncoding(@Nullable String encoding) { + return ImmutableGrpcResponse.create( + GrpcStatusCode.INTERNAL, "Unsupported gRPC message encoding: " + encoding, new byte[0]); + } + + private static GrpcStatusCode grpcStatus(Response response) { + // Status can either be in the headers or trailers depending on error + String grpcStatus = response.header(GRPC_STATUS); + if (grpcStatus == null) { + try { + grpcStatus = response.trailers().get(GRPC_STATUS); + } catch (IOException e) { + // Could not read a status, this generally means the HTTP status is the error. + return GrpcStatusCode.UNKNOWN; + } + } + if (grpcStatus == null) { + return GrpcStatusCode.UNKNOWN; + } + try { + return GrpcStatusCode.fromValue(Integer.parseInt(grpcStatus)); + } catch (NumberFormatException ex) { + return GrpcStatusCode.UNKNOWN; + } + } + + private static String grpcMessage(Response response) { + String message = response.header(GRPC_MESSAGE); + if (message == null) { + try { + message = response.trailers().get(GRPC_MESSAGE); + } catch (IOException e) { + // Fall through + } + } + if (message != null) { + return unescape(message); + } + // Couldn't get message for some reason, use the HTTP status. + return response.message(); + } + + @Override + public CompletableResultCode shutdown() { + synchronized (shutdownLock) { + isShutdown = true; + } + client.dispatcher().cancelAll(); + client.connectionPool().evictAll(); + + if (managedExecutor) { + ExecutorService executorService = client.dispatcher().executorService(); + // Use shutdownNow() to interrupt idle threads immediately since we've cancelled all work + executorService.shutdownNow(); + + // Wait for threads to terminate in a background thread + CompletableResultCode result = new CompletableResultCode(); + Thread terminationThread = + new Thread( + () -> { + try { + // Wait up to 5 seconds for threads to terminate + // Even if timeout occurs, we succeed since these are daemon threads + boolean terminated = executorService.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) { + logger.log( + Level.WARNING, + "Executor did not terminate within 5 seconds, proceeding with shutdown" + + " since threads are daemon threads."); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + result.succeed(); + } + }, + "okhttp-shutdown"); + terminationThread.setDaemon(true); + terminationThread.start(); + return result; + } + + return CompletableResultCode.ofSuccess(); + } + + /** Whether a resolved response is retriable or not. */ + static boolean isRetryable(GrpcResponse response) { + return RetryUtil.retryableGrpcStatusCodes() + .contains(Integer.toString(response.getStatusCode().getValue())); + } + + // From grpc-java + + /** Unescape the provided ascii to a unicode {@link String}. */ + private static String unescape(String value) { + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c < ' ' || c >= '~' || (c == '%' && i + 2 < value.length())) { + return doUnescape(value.getBytes(StandardCharsets.US_ASCII)); + } + } + return value; + } + + private static String doUnescape(byte[] value) { + ByteBuffer buf = ByteBuffer.allocate(value.length); + for (int i = 0; i < value.length; ) { + if (value[i] == '%' && i + 2 < value.length) { + try { + buf.put((byte) Integer.parseInt(new String(value, i + 1, 2, StandardCharsets.UTF_8), 16)); + i += 3; + continue; + } catch (NumberFormatException e) { + // ignore, fall through, just push the bytes. + } + } + buf.put(value[i]); + i += 1; + } + return new String(buf.array(), 0, buf.position(), StandardCharsets.UTF_8); + } +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderProvider.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderProvider.java new file mode 100644 index 00000000000..a1ead79c0d3 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderProvider.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcSenderConfig; +import io.opentelemetry.sdk.common.export.GrpcSenderProvider; + +/** + * {@link GrpcSender} SPI implementation for {@link OkHttpGrpcSender}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class OkHttpGrpcSenderProvider implements GrpcSenderProvider { + + @Override + public GrpcSender createSender(GrpcSenderConfig grpcSenderConfig) { + return new OkHttpGrpcSender( + grpcSenderConfig + .getEndpoint() + .resolve("/" + grpcSenderConfig.getFullMethodName()) + .toString(), + grpcSenderConfig.getCompressor(), + grpcSenderConfig.getTimeout(), + grpcSenderConfig.getConnectTimeout(), + grpcSenderConfig.getHeadersSupplier(), + grpcSenderConfig.getRetryPolicy(), + grpcSenderConfig.getSslContext(), + grpcSenderConfig.getTrustManager(), + grpcSenderConfig.getExecutorService(), + grpcSenderConfig.getMaxResponseBodySize(), + grpcSenderConfig.getEnabledProtocols()); + } +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java new file mode 100644 index 00000000000..6c5db44535f --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSender.java @@ -0,0 +1,317 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.api.impl.InstrumentationUtil; +import io.opentelemetry.exporter.internal.RetryUtil; +import io.opentelemetry.exporter.internal.TlsUtil; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.HttpResponse; +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.export.ProxyOptions; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.net.URI; +import java.time.Duration; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.OptionalLong; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.X509TrustManager; +import okhttp3.Call; +import okhttp3.Callback; +import okhttp3.ConnectionSpec; +import okhttp3.Dispatcher; +import okhttp3.HttpUrl; +import okhttp3.MediaType; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; +import okhttp3.ResponseBody; +import okhttp3.TlsVersion; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSource; +import okio.Okio; +import okio.Source; + +/** + * {@link HttpSender} which is backed by OkHttp. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OkHttpHttpSender implements HttpSender { + + private static final Logger logger = Logger.getLogger(OkHttpHttpSender.class.getName()); + + private final boolean managedExecutor; + private final OkHttpClient client; + private final HttpUrl url; + private final Supplier>> headerSupplier; + private final MediaType mediaType; + @Nullable private final Compressor compressor; + private final long maxResponseBodySize; + + /** Create a sender. */ + @SuppressWarnings("TooManyParameters") + public OkHttpHttpSender( + URI endpoint, + String contentType, + @Nullable Compressor compressor, + Duration timeout, + Duration connectTimeout, + Supplier>> headerSupplier, + @Nullable ProxyOptions proxyOptions, + @Nullable RetryPolicy retryPolicy, + @Nullable SSLContext sslContext, + @Nullable X509TrustManager trustManager, + @Nullable ExecutorService executorService, + long maxResponseBodySize, + @Nullable List enabledProtocols) { + int callTimeoutMillis = (int) Math.min(timeout.toMillis(), Integer.MAX_VALUE); + int connectTimeoutMillis = (int) Math.min(connectTimeout.toMillis(), Integer.MAX_VALUE); + + Dispatcher dispatcher; + if (executorService == null) { + dispatcher = OkHttpUtil.newDispatcher(); + this.managedExecutor = true; + } else { + dispatcher = new Dispatcher(executorService); + this.managedExecutor = false; + } + + OkHttpClient.Builder builder = + new OkHttpClient.Builder() + .dispatcher(dispatcher) + .connectTimeout(Duration.ofMillis(connectTimeoutMillis)) + .callTimeout(Duration.ofMillis(callTimeoutMillis)); + + if (proxyOptions != null) { + builder.proxySelector(proxyOptions.getProxySelector()); + } + + if (retryPolicy != null) { + builder.addInterceptor( + new RetryInterceptor( + retryPolicy, OkHttpHttpSender::isRetryable, OkHttpHttpSender::retryDelayNanos)); + } + + boolean isPlainHttp = endpoint.getScheme().equals("http"); + if (isPlainHttp) { + builder.connectionSpecs(Collections.singletonList(ConnectionSpec.CLEARTEXT)); + } else { + if (sslContext != null) { + X509TrustManager effectiveTrustManager = trustManager; + if (effectiveTrustManager == null) { + try { + effectiveTrustManager = TlsUtil.defaultTrustManager(); + } catch (SSLException e) { + throw new IllegalStateException("Unable to initialize default trust manager", e); + } + } + builder.sslSocketFactory(sslContext.getSocketFactory(), effectiveTrustManager); + } + if (enabledProtocols != null && !enabledProtocols.isEmpty()) { + TlsVersion[] versions = + enabledProtocols.stream().map(TlsVersion::forJavaName).toArray(TlsVersion[]::new); + builder.connectionSpecs( + Collections.singletonList( + new ConnectionSpec.Builder(ConnectionSpec.COMPATIBLE_TLS) + .tlsVersions(versions) + .build())); + } + } + + this.client = builder.build(); + this.url = HttpUrl.get(endpoint); + this.mediaType = MediaType.parse(contentType); + this.compressor = compressor; + this.headerSupplier = headerSupplier; + this.maxResponseBodySize = maxResponseBodySize; + } + + private static OptionalLong retryDelayNanos(Response response) { + return RetryUtil.retryAfterNanos(response.header("Retry-After")); + } + + @Override + public void send( + MessageWriter messageWriter, Consumer onResponse, Consumer onError) { + Request.Builder requestBuilder = new Request.Builder().url(url); + + Map> headers = headerSupplier.get(); + if (headers != null) { + headers.forEach( + (key, values) -> values.forEach(value -> requestBuilder.addHeader(key, value))); + } + if (compressor != null) { + requestBuilder.addHeader("Content-Encoding", compressor.getEncoding()); + } + // Explicitly advertise gzip and identity encoding support. Because we set Accept-Encoding + // ourselves, OkHttp's BridgeInterceptor will not transparently decompress gzip responses + // (it only does so when it added the header), so we handle decompression ourselves below. + requestBuilder.addHeader("Accept-Encoding", "gzip, identity"); + requestBuilder.post(new RequestBodyImpl(messageWriter, compressor, mediaType)); + + try { + InstrumentationUtil.suppressInstrumentation(() -> + client + .newCall(requestBuilder.build()) + .enqueue( + new Callback() { + @Override + public void onFailure(Call call, IOException e) { + onError.accept(e); + } + + @Override + public void onResponse(Call call, Response response) { + handleResponse(response, onResponse, onError); + } + })); + } catch (RejectedExecutionException e) { + onError.accept(e); + } + } + + private void handleResponse( + Response response, Consumer onResponse, Consumer onError) { + try (ResponseBody body = response.body()) { + String contentEncoding = response.header("Content-Encoding"); + if (contentEncoding != null + && !"gzip".equalsIgnoreCase(contentEncoding) + && !"identity".equalsIgnoreCase(contentEncoding)) { + onError.accept(new IOException("Unsupported Content-Encoding: " + contentEncoding)); + return; + } + boolean decompress = "gzip".equalsIgnoreCase(contentEncoding); + // Read up to maxResponseBodySize + 1 bytes. Reading exactly one byte more than the limit + // lets us detect overflow: if the buffer ends up larger than maxResponseBodySize, the body + // exceeded the limit. A body exactly at the limit will only fill the buffer to + // maxResponseBodySize (EOF is reached before the extra byte is read). + // If maxResponseBodySize is Long.MAX_VALUE, adding 1 would overflow. In that case use + // Long.MAX_VALUE directly β€” the overflow check can never trigger for such a large limit. + long readUpTo = + maxResponseBodySize == Long.MAX_VALUE ? Long.MAX_VALUE : maxResponseBodySize + 1; + Buffer buffer = new Buffer(); + try { + Source source = decompress ? new GzipSource(body.source()) : body.source(); + while (buffer.size() <= maxResponseBodySize) { + long n = source.read(buffer, readUpTo - buffer.size()); + if (n == -1L) { + break; + } + } + } catch (IOException e) { + logger.log(Level.WARNING, "Failed to read response body", e); + } + + if (buffer.size() > maxResponseBodySize) { + onError.accept( + new IOException( + "HTTP response body exceeded limit of " + maxResponseBodySize + " bytes")); + return; + } + + byte[] bodyBytes = buffer.readByteArray(); + onResponse.accept( + ImmutableHttpResponse.create(response.code(), response.message(), bodyBytes)); + } + } + + @Override + public CompletableResultCode shutdown() { + client.dispatcher().cancelAll(); + client.connectionPool().evictAll(); + + if (managedExecutor) { + ExecutorService executorService = client.dispatcher().executorService(); + // Use shutdownNow() to interrupt idle threads immediately since we've cancelled all work + executorService.shutdownNow(); + + // Wait for threads to terminate in a background thread + CompletableResultCode result = new CompletableResultCode(); + Thread terminationThread = + new Thread( + () -> { + try { + // Wait up to 5 seconds for threads to terminate + // Even if timeout occurs, we succeed since these are daemon threads + boolean terminated = executorService.awaitTermination(5, TimeUnit.SECONDS); + if (!terminated) { + logger.log( + Level.WARNING, + "Executor did not terminate within 5 seconds, proceeding with shutdown since threads are daemon threads."); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } finally { + result.succeed(); + } + }, + "okhttp-shutdown"); + terminationThread.setDaemon(true); + terminationThread.start(); + return result; + } + + return CompletableResultCode.ofSuccess(); + } + + static boolean isRetryable(Response response) { + return RetryUtil.retryableHttpResponseCodes().contains(response.code()); + } + + private static class RequestBodyImpl extends RequestBody { + + private final MessageWriter requestBodyWriter; + @Nullable private final Compressor compressor; + private final MediaType mediaType; + + private RequestBodyImpl( + MessageWriter requestBodyWriter, @Nullable Compressor compressor, MediaType mediaType) { + this.requestBodyWriter = requestBodyWriter; + this.compressor = compressor; + this.mediaType = mediaType; + } + + @Override + public long contentLength() { + return compressor == null ? requestBodyWriter.getContentLength() : -1; + } + + @Override + public MediaType contentType() { + return mediaType; + } + + @Override + public void writeTo(BufferedSink bufferedSink) throws IOException { + if (compressor != null) { + BufferedSink compressedSink = + Okio.buffer(Okio.sink(compressor.compress(bufferedSink.outputStream()))); + requestBodyWriter.writeMessage(compressedSink.outputStream()); + compressedSink.close(); + } else { + requestBodyWriter.writeMessage(bufferedSink.outputStream()); + } + } + } +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderProvider.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderProvider.java new file mode 100644 index 00000000000..8f782c5edd4 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderProvider.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.sdk.common.export.HttpSender; +import io.opentelemetry.sdk.common.export.HttpSenderConfig; +import io.opentelemetry.sdk.common.export.HttpSenderProvider; + +/** + * {@link HttpSender} SPI implementation for {@link OkHttpHttpSender}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OkHttpHttpSenderProvider implements HttpSenderProvider { + + @Override + public HttpSender createSender(HttpSenderConfig httpSenderConfig) { + return new OkHttpHttpSender( + httpSenderConfig.getEndpoint(), + httpSenderConfig.getContentType(), + httpSenderConfig.getCompressor(), + httpSenderConfig.getTimeout(), + httpSenderConfig.getConnectTimeout(), + httpSenderConfig.getHeadersSupplier(), + httpSenderConfig.getProxyOptions(), + httpSenderConfig.getRetryPolicy(), + httpSenderConfig.getSslContext(), + httpSenderConfig.getTrustManager(), + httpSenderConfig.getExecutorService(), + httpSenderConfig.getMaxResponseBodySize(), + httpSenderConfig.getEnabledProtocols()); + } +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtil.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtil.java new file mode 100644 index 00000000000..4f763d25478 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtil.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; +import java.util.concurrent.Executors; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import okhttp3.Dispatcher; + +/** + * Utilities for OkHttp. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class OkHttpUtil { + private static final int DEFAULT_MAX_REQUESTS_PER_HOST = 5; + + @SuppressWarnings("NonFinalStaticField") + private static boolean propagateContextForTestingInDispatcher = false; + + public static void setPropagateContextForTestingInDispatcher( + boolean propagateContextForTestingInDispatcher) { + OkHttpUtil.propagateContextForTestingInDispatcher = propagateContextForTestingInDispatcher; + } + + /** + * Returns a {@link Dispatcher} using daemon threads, with both the maximum number of concurrent + * requests and the maximum size of the backing thread pool bounded to {@code + * max(availableProcessors, 5)}, matching the bound used by {@code JdkHttpSender}. + */ + public static Dispatcher newDispatcher() { + int maxRequests = Math.max(Runtime.getRuntime().availableProcessors(), 5); + Dispatcher dispatcher = + new Dispatcher( + new ThreadPoolExecutor( + 0, + maxRequests, + 60, + TimeUnit.SECONDS, + new SynchronousQueue<>(), + createThreadFactory("okhttp-dispatch"))); + dispatcher.setMaxRequests(maxRequests); + dispatcher.setMaxRequestsPerHost(DEFAULT_MAX_REQUESTS_PER_HOST); + return dispatcher; + } + + private static DaemonThreadFactory createThreadFactory(String namePrefix) { + if (propagateContextForTestingInDispatcher) { + return new DaemonThreadFactory( + namePrefix, r -> Executors.defaultThreadFactory().newThread(Context.current().wrap(r))); + } + return new DaemonThreadFactory(namePrefix); + } + + private OkHttpUtil() {} +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptor.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptor.java new file mode 100644 index 00000000000..fbb267a086d --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptor.java @@ -0,0 +1,169 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static java.util.stream.Collectors.joining; + +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.util.OptionalLong; +import java.util.StringJoiner; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import okhttp3.Interceptor; +import okhttp3.Response; + +/** + * Retrier of OkHttp requests. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class RetryInterceptor implements Interceptor { + + private static final Logger logger = Logger.getLogger(RetryInterceptor.class.getName()); + + private final RetryPolicy retryPolicy; + private final Function isRetryable; + private final Function retryDelayNanosExtractor; + private final Predicate retryExceptionPredicate; + private final Sleeper sleeper; + private final Supplier randomJitter; + + /** Constructs a new retrier. */ + public RetryInterceptor( + RetryPolicy retryPolicy, + Function isRetryable, + Function retryDelayNanosExtractor) { + this( + retryPolicy, + isRetryable, + retryDelayNanosExtractor, + retryPolicy.getRetryExceptionPredicate() == null + ? RetryState::isRetryableException + : retryPolicy.getRetryExceptionPredicate(), + RetryState::defaultSleeper, + RetryState::defaultRandomJitter); + } + + // Visible for testing + RetryInterceptor( + RetryPolicy retryPolicy, + Function isRetryable, + Function retryDelayNanosExtractor, + Predicate retryExceptionPredicate, + Sleeper sleeper, + Supplier randomJitter) { + this.retryPolicy = retryPolicy; + this.isRetryable = isRetryable; + this.retryDelayNanosExtractor = retryDelayNanosExtractor; + this.retryExceptionPredicate = retryExceptionPredicate; + this.sleeper = sleeper; + this.randomJitter = randomJitter; + } + + @Override + public Response intercept(Chain chain) throws IOException { + RetryState retryState = + new RetryState( + retryPolicy, + retryExceptionPredicate, + sleeper, + randomJitter, + chain.call().timeout().timeoutNanos(), + System::nanoTime); + Response response = null; + IOException exception = null; + int attempt = 0; + OptionalLong retryDelayNanos = OptionalLong.empty(); + do { + if (attempt > 0) { + // Compute and sleep for backoff + // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff + if (!retryState.backoff(retryDelayNanos)) { + break; // Break out and return response or throw + } + retryDelayNanos = OptionalLong.empty(); + // Close response from previous attempt + if (response != null) { + response.close(); + } + exception = null; + } + try { + response = chain.proceed(chain.request()); + if (response != null) { + boolean retryable = Boolean.TRUE.equals(isRetryable.apply(response)); + if (logger.isLoggable(Level.FINER)) { + logger.log( + Level.FINER, + "Attempt " + + attempt + + " returned " + + (retryable ? "retryable" : "non-retryable") + + " response: " + + responseStringRepresentation(response)); + } + if (!retryable) { + return response; + } + retryDelayNanos = retryDelayNanosExtractor.apply(response); + } else { + throw new NullPointerException("response cannot be null."); + } + } catch (IOException e) { + exception = e; + response = null; + boolean retryable = retryState.shouldRetryOnException(exception); + if (logger.isLoggable(Level.FINER)) { + logger.log( + Level.FINER, + "Attempt " + + attempt + + " failed with " + + (retryable ? "retryable" : "non-retryable") + + " exception", + exception); + } + if (!retryable) { + throw exception; + } + } + } while (++attempt < retryPolicy.getMaxAttempts()); + + if (response != null) { + return response; + } + throw exception; + } + + private static String responseStringRepresentation(Response response) { + StringJoiner joiner = new StringJoiner(",", "Response{", "}"); + joiner.add("code=" + response.code()); + joiner.add( + "headers=" + + response.headers().toMultimap().entrySet().stream() + .map(entry -> entry.getKey() + "=" + String.join(",", entry.getValue())) + .collect(joining(",", "[", "]"))); + return joiner.toString(); + } + + // Visible for testing + static boolean isRetryableException(IOException e) { + return RetryState.isRetryableException(e); + } + + // Visible for testing + boolean shouldRetryOnException(IOException e) { + return retryExceptionPredicate.test(e); + } + + // Visible for testing + interface Sleeper extends RetryState.Sleeper {} +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryState.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryState.java new file mode 100644 index 00000000000..3d49777fe01 --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryState.java @@ -0,0 +1,126 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.net.ConnectException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.OptionalLong; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import java.util.function.LongSupplier; +import java.util.function.Predicate; +import java.util.function.Supplier; +import okhttp3.Call; + +/** Shared retry policy state and mechanics for OkHttp senders. */ +final class RetryState { + + private final RetryPolicy retryPolicy; + private final Predicate retryExceptionPredicate; + private final Sleeper sleeper; + private final Supplier randomJitter; + private final long timeoutNanos; + private final LongSupplier nanoTime; + private final long startTimeNanos; + private long nextBackoffNanos; + + RetryState( + RetryPolicy retryPolicy, + Predicate retryExceptionPredicate, + Sleeper sleeper, + Supplier randomJitter, + long timeoutNanos, + LongSupplier nanoTime) { + this.retryPolicy = retryPolicy; + this.retryExceptionPredicate = retryExceptionPredicate; + this.sleeper = sleeper; + this.randomJitter = randomJitter; + this.timeoutNanos = timeoutNanos; + this.nanoTime = nanoTime; + this.startTimeNanos = nanoTime.getAsLong(); + this.nextBackoffNanos = retryPolicy.getInitialBackoff().toNanos(); + } + + static void defaultSleeper(long delayNanos) throws InterruptedException { + TimeUnit.NANOSECONDS.sleep(delayNanos); + } + + static double defaultRandomJitter() { + return ThreadLocalRandom.current().nextDouble(0.8d, 1.2d); + } + + boolean backoff(OptionalLong retryDelayNanos) { + long remainingNanos = remainingNanos(); + if (remainingNanos <= 0) { + return false; + } + long currentBackoffNanos = Math.min(nextBackoffNanos, retryPolicy.getMaxBackoff().toNanos()); + long requestedBackoffNanos = + retryDelayNanos.isPresent() + ? retryDelayNanos.getAsLong() + : (long) (randomJitter.get() * currentBackoffNanos); + long backoffNanos = Math.min(requestedBackoffNanos, remainingNanos); + nextBackoffNanos = (long) (currentBackoffNanos * retryPolicy.getBackoffMultiplier()); + try { + sleeper.sleep(backoffNanos); + return remainingNanos() > 0; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return false; + } + } + + long remainingNanos() { + if (timeoutNanos <= 0) { + return Long.MAX_VALUE; + } + return Math.max(0, timeoutNanos - (nanoTime.getAsLong() - startTimeNanos)); + } + + boolean configureCallTimeout(Call call) { + long remainingNanos = remainingNanos(); + if (remainingNanos <= 0) { + return false; + } + if (timeoutNanos > 0) { + call.timeout() + .timeout(remainingNanos, TimeUnit.NANOSECONDS) + .deadlineNanoTime(startTimeNanos + timeoutNanos); + } + return true; + } + + boolean canRetry(int attempt) { + return attempt + 1 < retryPolicy.getMaxAttempts(); + } + + boolean shouldRetryOnException(IOException exception) { + return retryExceptionPredicate.test(exception); + } + + // Visible for testing. + static boolean isRetryableException(IOException e) { + if (e instanceof SocketTimeoutException) { + return true; + } else if (e instanceof ConnectException) { + return true; + } else if (e instanceof UnknownHostException) { + return true; + } else if (e instanceof SocketException) { + return true; + } + return false; + } + + @FunctionalInterface + interface Sleeper { + void sleep(long delayNanos) throws InterruptedException; + } +} diff --git a/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/package-info.java b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/package-info.java new file mode 100644 index 00000000000..b623f8855dc --- /dev/null +++ b/exporters/sender/okhttp/src/main/java/io/opentelemetry/exporter/sender/okhttp/internal/package-info.java @@ -0,0 +1,9 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +@ParametersAreNonnullByDefault +package io.opentelemetry.exporter.sender.okhttp.internal; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/sender/okhttp/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider b/exporters/sender/okhttp/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider new file mode 100644 index 00000000000..0d308266d75 --- /dev/null +++ b/exporters/sender/okhttp/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.GrpcSenderProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSenderProvider diff --git a/exporters/sender/okhttp/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider b/exporters/sender/okhttp/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider new file mode 100644 index 00000000000..5f14cc891cf --- /dev/null +++ b/exporters/sender/okhttp/src/main/resources/META-INF/services/io.opentelemetry.sdk.common.export.HttpSenderProvider @@ -0,0 +1 @@ +io.opentelemetry.exporter.sender.okhttp.internal.OkHttpHttpSenderProvider diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/AbstractOkHttpSuppressionTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/AbstractOkHttpSuppressionTest.java new file mode 100644 index 00000000000..f143eb67965 --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/AbstractOkHttpSuppressionTest.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.opentelemetry.api.impl.InstrumentationUtil; +import io.opentelemetry.context.Context; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +abstract class AbstractOkHttpSuppressionTest { + + @BeforeEach + void setUp() { + OkHttpUtil.setPropagateContextForTestingInDispatcher(true); + } + + @AfterEach + void tearDown() { + OkHttpUtil.setPropagateContextForTestingInDispatcher(false); + } + + @Test + void testSuppressInstrumentation() throws InterruptedException { + CountDownLatch latch = new CountDownLatch(1); + AtomicBoolean suppressInstrumentation = new AtomicBoolean(false); + + Runnable onSuccess = Assertions::fail; + Runnable onFailure = + () -> { + suppressInstrumentation.set( + InstrumentationUtil.shouldSuppressInstrumentation(Context.current())); + latch.countDown(); + }; + + send(getSender(), onSuccess, onFailure); + + latch.await(); + + assertTrue(suppressInstrumentation.get()); + } + + abstract void send(T sender, Runnable onSuccess, Runnable onFailure); + + private T getSender() { + return createSender("https://none"); + } + + abstract T createSender(String endpoint); +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java new file mode 100644 index 00000000000..69b82667ead --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSenderTest.java @@ -0,0 +1,504 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.exporter.internal.RetryUtil; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.io.OutputStream; +import java.net.ConnectException; +import java.net.ServerSocket; +import java.security.Security; +import java.time.Duration; +import java.util.Collections; +import java.util.Set; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import okhttp3.Headers; +import okhttp3.MediaType; +import okhttp3.Protocol; +import okhttp3.Request; +import okhttp3.Response; +import okhttp3.ResponseBody; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.event.Level; +import org.slf4j.event.LoggingEvent; + +class OkHttpGrpcSenderTest { + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(OkHttpGrpcSender.class, Level.TRACE); + + private static final MediaType GRPC_MEDIA_TYPE = MediaType.get("application/grpc"); + + static Set provideRetryableGrpcStatusCodes() { + return RetryUtil.retryableGrpcStatusCodes(); + } + + @ParameterizedTest(name = "isRetryable should return true for GRPC status code: {0}") + @MethodSource("provideRetryableGrpcStatusCodes") + void isRetryable_RetryableGrpcStatus(String retryableGrpcStatus) { + GrpcResponse response = + ImmutableGrpcResponse.create( + GrpcStatusCode.fromValue(Integer.parseInt(retryableGrpcStatus)), + "Retryable", + new byte[0]); + boolean isRetryable = OkHttpGrpcSender.isRetryable(response); + assertTrue(isRetryable); + } + + @Test + void isRetryable_NonRetryableGrpcStatus() { + String nonRetryableGrpcStatus = + Integer.valueOf(GrpcStatusCode.UNKNOWN.getValue()).toString(); // INVALID_ARGUMENT + GrpcResponse response = + ImmutableGrpcResponse.create( + GrpcStatusCode.fromValue(Integer.parseInt(nonRetryableGrpcStatus)), + "Non-retryable", + new byte[0]); + boolean isRetryable = OkHttpGrpcSender.isRetryable(response); + assertFalse(isRetryable); + } + + @Test + void handleResponse_resolvesTrailerStatusAndMessageAfterConsumingBody() { + OkHttpGrpcSender sender = createSender(Long.MAX_VALUE); + AtomicReference responseRef = new AtomicReference<>(); + byte[] frame = new byte[] {0, 0, 0, 0, 3, 'o', 'k', '!'}; + Response response = + new Response.Builder() + .request(new Request.Builder().url("http://localhost/").build()) + .protocol(Protocol.HTTP_2) + .code(200) + .body(ResponseBody.create(frame, GRPC_MEDIA_TYPE)) + .message("HTTP message") + .trailers(() -> Headers.of("grpc-status", "14", "grpc-message", "retry%20me")) + .build(); + + sender.handleResponse(response, responseRef::set); + + assertThat(responseRef.get().getStatusCode()).isEqualTo(GrpcStatusCode.UNAVAILABLE); + assertThat(responseRef.get().getStatusDescription()).isEqualTo("retry me"); + assertThat(responseRef.get().getResponseMessage()) + .containsExactly((byte) 'o', (byte) 'k', (byte) '!'); + } + + private static OkHttpGrpcSender createSender(long maxResponseBodySize) { + return new OkHttpGrpcSender( + "http://localhost", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + maxResponseBodySize, + null); + } + + @Test + void send_rejectedExecution_callsOnError() { + ThreadPoolExecutor executor = + new ThreadPoolExecutor(0, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<>()); + executor.shutdown(); + + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + executor, + Long.MAX_VALUE, + null); + + AtomicReference responseRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + + sender.send(new TestMessageWriter(), responseRef::set, errorRef::set); + + assertThat(errorRef.get()).isNotNull(); + assertThat(errorRef.get()).hasMessageContaining("executor rejected"); + assertThat(responseRef.get()).isNull(); + } + + @Test + void send_retryWithSingleThreadExecutor_doesNotRejectRetry() throws Exception { + // Allocate an ephemeral port and immediately close it so that every attempt fails to connect + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + // The only thread is busy running the first attempt when the retry starts + ThreadPoolExecutor executor = + new ThreadPoolExecutor(1, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<>()); + + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost:" + port, + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + RetryPolicy.builder().setMaxAttempts(2).setInitialBackoff(Duration.ofMillis(1)).build(), + null, + null, + executor, + Long.MAX_VALUE, + null); + + CompletableFuture error = new CompletableFuture<>(); + try { + sender.send( + new TestMessageWriter(), + response -> error.completeExceptionally(new AssertionError("Unexpected response")), + error::complete); + + // Without running the retry on the current thread, the retry is rejected by the executor and + // fails with "executor rejected" instead of the connection error + assertThat(error.get(10, TimeUnit.SECONDS)).isInstanceOf(ConnectException.class); + } finally { + sender.shutdown(); + executor.shutdownNow(); + } + } + + @Test + void shutdown_CompletableResultCodeShouldWaitForThreads() throws Exception { + // This test verifies that shutdown() returns a CompletableResultCode that only + // completes AFTER threads terminate, not immediately. + + // Allocate an ephemeral port and immediately close it to get a port with nothing listening + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost:" + port, // Non-existent endpoint to trigger thread creation + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + Long.MAX_VALUE, + null); + + CompletableResultCode sendResult = new CompletableResultCode(); + sender.send( + new TestMessageWriter(), response -> sendResult.succeed(), error -> sendResult.fail()); + + // Give threads time to start + Thread.sleep(500); + + CompletableResultCode shutdownResult = sender.shutdown(); + + // The key test: the CompletableResultCode should NOT be done() immediately + // because we need to wait for threads to terminate. + // Before #7840, this would fail. + assertFalse( + shutdownResult.isDone(), + "CompletableResultCode should not be done immediately - it should wait for thread termination"); + + // Now wait for it to complete + shutdownResult.join(10, TimeUnit.SECONDS); + assertTrue(shutdownResult.isDone(), "CompletableResultCode should be done after waiting"); + assertTrue(shutdownResult.isSuccess(), "Shutdown should complete successfully"); + } + + @Test + void shutdown_NonManagedExecutor_ReturnsImmediately() { + // This test verifies that when using a non-managed executor (custom ExecutorService), + // shutdown() returns an already-completed CompletableResultCode immediately. + + // Create a custom ExecutorService - this makes the executor non-managed + ExecutorService customExecutor = Executors.newSingleThreadExecutor(); + + try { + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost:8080", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + customExecutor, // Pass custom executor -> managedExecutor = false + Long.MAX_VALUE, + null); + + CompletableResultCode shutdownResult = sender.shutdown(); + + // Should complete immediately since executor is not managed + assertTrue( + shutdownResult.isDone(), + "CompletableResultCode should be done immediately for non-managed executor"); + assertTrue(shutdownResult.isSuccess(), "Shutdown should complete successfully"); + } finally { + // Clean up the custom executor + customExecutor.shutdownNow(); + } + } + + @Test + void shutdown_ExecutorDoesNotTerminateInTime_LogsWarningButSucceeds() throws Exception { + // This test verifies that when threads don't terminate within 5 seconds, + // a warning is logged but shutdown still succeeds. + + // Allocate an ephemeral port + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + // Create sender with managed executor (default) + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost:" + port, + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, // null executor = managed + Long.MAX_VALUE, + null); + + // Start multiple requests to ensure threads are busy + CountDownLatch blockCallbacks = new CountDownLatch(1); + for (int i = 0; i < 3; i++) { + sender.send( + new TestMessageWriter(), + response -> { + try { + // Block in callback for longer than the 5-second timeout + blockCallbacks.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }, + error -> { + try { + // Block in callback for longer than the 5-second timeout + blockCallbacks.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } + + // Give threads time to start (same pattern as existing test) + Thread.sleep(500); + + // Shutdown will now try to terminate threads that are blocked + CompletableResultCode shutdownResult = sender.shutdown(); + + // The shutdown should eventually complete successfully + // even though threads didn't terminate in 5 seconds + assertTrue( + shutdownResult.join(10, TimeUnit.SECONDS).isSuccess(), + "Shutdown should succeed even when threads don't terminate quickly"); + + // Release the blocking callbacks + blockCallbacks.countDown(); + } + + @Test + void shutdown_InterruptedWhileWaiting_StillSucceeds() throws Exception { + // This test verifies that if the shutdown thread is interrupted while waiting + // for termination, it still marks the shutdown as successful. + + // Allocate an ephemeral port + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost:" + port, + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + Long.MAX_VALUE, + null); + + // Trigger some activity + sender.send(new TestMessageWriter(), response -> {}, error -> {}); + + // Give threads time to start (same pattern as existing test) + Thread.sleep(500); + + // Start shutdown + CompletableResultCode shutdownResult = sender.shutdown(); + + // Give the shutdown thread a moment to start + Thread.sleep(100); + + // Find and interrupt the okhttp-shutdown thread to trigger the InterruptedException path + Thread[] threads = new Thread[Thread.activeCount() + 10]; + int count = Thread.enumerate(threads); + for (int i = 0; i < count; i++) { + Thread thread = threads[i]; + if (thread != null && thread.getName().equals("okhttp-shutdown")) { + // Interrupt the shutdown thread to test the InterruptedException handling + thread.interrupt(); + break; + } + } + + // Even with interruption, shutdown should still succeed + assertTrue( + shutdownResult.join(10, TimeUnit.SECONDS).isSuccess(), + "Shutdown should succeed even when interrupted"); + } + + @Test + void constructor_usesDefaultTrustManagerWhenTrustManagerIsNull() throws Exception { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + + assertThatCode(() -> + new OkHttpGrpcSender( + "https://localhost", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) + .doesNotThrowAnyException(); + } + + @Test + void constructor_wrapsDefaultTrustManagerFailure() throws Exception { + String originalAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm"); + + try { + Security.setProperty("ssl.TrustManagerFactory.algorithm", "invalid"); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + + assertThatThrownBy(() -> + new OkHttpGrpcSender( + "https://localhost", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Unable to initialize default trust manager") + .hasCauseInstanceOf(SSLException.class); + + } finally { + Security.setProperty("ssl.TrustManagerFactory.algorithm", originalAlgorithm); + } + } + + @Test + void send_retryEnabled_logsEachFailedAttempt() throws Exception { + // Allocate an ephemeral port and immediately close it to get a port with nothing listening + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + OkHttpGrpcSender sender = + new OkHttpGrpcSender( + "http://localhost:" + port, + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + RetryPolicy.builder().setMaxAttempts(2).setInitialBackoff(Duration.ofMillis(1)).build(), + null, + null, + null, + Long.MAX_VALUE, + null); + + CompletableResultCode sendResult = new CompletableResultCode(); + try { + sender.send( + new TestMessageWriter(), response -> sendResult.succeed(), error -> sendResult.fail()); + sendResult.join(10, TimeUnit.SECONDS); + } finally { + sender.shutdown().join(10, TimeUnit.SECONDS); + } + + assertThat(sendResult.isSuccess()).isFalse(); + assertThat(logs.getEvents()) + .extracting(LoggingEvent::getMessage) + .containsExactly( + "Attempt 0 failed with retryable exception", + "Attempt 1 failed with retryable exception"); + } + + /** Simple test marshaler for testing purposes. */ + private static class TestMessageWriter implements MessageWriter { + @Override + public void writeMessage(OutputStream output) throws IOException { + // Empty writer + } + + @Override + public int getContentLength() { + return 0; + } + } +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSuppressionTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSuppressionTest.java new file mode 100644 index 00000000000..5dfdc1980bb --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpGrpcSuppressionTest.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.OutputStream; +import java.time.Duration; +import java.util.Collections; + +class OkHttpGrpcSuppressionTest extends AbstractOkHttpSuppressionTest { + + @Override + void send(OkHttpGrpcSender sender, Runnable onSuccess, Runnable onFailure) { + sender.send( + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + }, + grpcResponse -> {}, + throwable -> onFailure.run()); + } + + @Override + OkHttpGrpcSender createSender(String endpoint) { + return new OkHttpGrpcSender( + "https://localhost", + null, + Duration.ofNanos(10), + Duration.ofNanos(10L), + Collections::emptyMap, + null, + null, + null, + null, + Long.MAX_VALUE, + null); + } +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java new file mode 100644 index 00000000000..9642b889f63 --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSenderTest.java @@ -0,0 +1,399 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.exporter.internal.TlsUtil; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.HttpResponse; +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ServerSocket; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.security.Security; +import java.security.cert.Certificate; +import java.time.Duration; +import java.util.Collections; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.SynchronousQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import javax.annotation.Nullable; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class OkHttpHttpSenderTest { + + @Test + void send_rejectedExecution_callsOnError() { + ThreadPoolExecutor executor = + new ThreadPoolExecutor(0, 1, 0, TimeUnit.SECONDS, new SynchronousQueue<>()); + executor.shutdown(); + + OkHttpHttpSender sender = + new OkHttpHttpSender( + URI.create("http://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + executor, + Long.MAX_VALUE, + null); + + AtomicReference responseRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + + sender.send(new NoOpRequestBodyWriter(), responseRef::set, errorRef::set); + + assertThat(errorRef.get()).isNotNull(); + assertThat(errorRef.get()).hasMessageContaining("executor rejected"); + assertThat(responseRef.get()).isNull(); + } + + @Test + void shutdown_CompletableResultCodeShouldWaitForThreads() throws Exception { + // This test verifies that shutdown() returns a CompletableResultCode that only + // completes AFTER threads terminate, not immediately. + + // Allocate an ephemeral port and immediately close it to get a port with nothing listening + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + OkHttpHttpSender sender = + newSender("http://localhost:" + port, null); // null executor = managed + + CompletableResultCode sendResult = new CompletableResultCode(); + sender.send( + new NoOpRequestBodyWriter(), response -> sendResult.succeed(), error -> sendResult.fail()); + + // Give threads time to start + Thread.sleep(500); + + CompletableResultCode shutdownResult = sender.shutdown(); + + // The CompletableResultCode should NOT be done() immediately because we need to wait for + // threads to terminate. + assertFalse( + shutdownResult.isDone(), + "CompletableResultCode should not be done immediately - it should wait for thread termination"); + + shutdownResult.join(10, TimeUnit.SECONDS); + assertTrue(shutdownResult.isDone(), "CompletableResultCode should be done after waiting"); + assertTrue(shutdownResult.isSuccess(), "Shutdown should complete successfully"); + } + + @Test + void shutdown_NonManagedExecutor_ReturnsImmediately() { + // This test verifies that when using a non-managed executor (custom ExecutorService), + // shutdown() returns an already-completed CompletableResultCode immediately. + + ExecutorService customExecutor = Executors.newSingleThreadExecutor(); + + try { + OkHttpHttpSender sender = newSender("http://localhost:8080", customExecutor); + + CompletableResultCode shutdownResult = sender.shutdown(); + + assertTrue( + shutdownResult.isDone(), + "CompletableResultCode should be done immediately for non-managed executor"); + assertTrue(shutdownResult.isSuccess(), "Shutdown should complete successfully"); + } finally { + customExecutor.shutdownNow(); + } + } + + @Test + void shutdown_ExecutorDoesNotTerminateInTime_LogsWarningButSucceeds() throws Exception { + // This test verifies that when threads don't terminate within 5 seconds, a warning is logged + // but shutdown still succeeds. + + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + OkHttpHttpSender sender = + newSender("http://localhost:" + port, null); // null executor = managed + + // Start multiple requests with callbacks that block longer than the 5-second timeout + CountDownLatch blockCallbacks = new CountDownLatch(1); + for (int i = 0; i < 3; i++) { + sender.send( + new NoOpRequestBodyWriter(), + response -> { + try { + blockCallbacks.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }, + error -> { + try { + blockCallbacks.await(10, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + }); + } + + Thread.sleep(500); + + CompletableResultCode shutdownResult = sender.shutdown(); + + assertTrue( + shutdownResult.join(10, TimeUnit.SECONDS).isSuccess(), + "Shutdown should succeed even when threads don't terminate quickly"); + + blockCallbacks.countDown(); + } + + @Test + void shutdown_InterruptedWhileWaiting_StillSucceeds() throws Exception { + // This test verifies that if the shutdown thread is interrupted while waiting for termination, + // it still marks the shutdown as successful. + + int port; + try (ServerSocket socket = new ServerSocket(0)) { + port = socket.getLocalPort(); + } + + OkHttpHttpSender sender = + newSender("http://localhost:" + port, null); // null executor = managed + + sender.send(new NoOpRequestBodyWriter(), response -> {}, error -> {}); + + Thread.sleep(500); + + CompletableResultCode shutdownResult = sender.shutdown(); + + // Give the shutdown thread a moment to start + Thread.sleep(100); + + // Find and interrupt the okhttp-shutdown thread to trigger the InterruptedException path + Thread[] threads = new Thread[Thread.activeCount() + 10]; + int count = Thread.enumerate(threads); + for (int i = 0; i < count; i++) { + Thread thread = threads[i]; + if (thread != null && thread.getName().equals("okhttp-shutdown")) { + thread.interrupt(); + break; + } + } + + assertTrue( + shutdownResult.join(10, TimeUnit.SECONDS).isSuccess(), + "Shutdown should succeed even when interrupted"); + } + + @RegisterExtension + static final SelfSignedCertificateExtension certificate = new SelfSignedCertificateExtension(); + + @Test + void enabledProtocols_legacyTls() throws Exception { + SSLSocket probe = (SSLSocket) SSLSocketFactory.getDefault().createSocket(); + assertThat(probe.getEnabledProtocols()) + .as("TLSv1.1 must be enabled via enable-legacy-tls.security") + .contains("TLSv1.1"); + probe.close(); + + // Plain JDK SSLServerSocket: no BoringSSL, so TLSv1.1 is honored. + KeyStore ks = KeyStore.getInstance("PKCS12"); + ks.load(null); + ks.setKeyEntry( + "key", + certificate.privateKey(), + new char[0], + new Certificate[] {certificate.certificate()}); + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(ks, new char[0]); + SSLContext serverCtx = SSLContext.getInstance("TLS"); + serverCtx.init(kmf.getKeyManagers(), null, null); + + try (SSLServerSocket serverSocket = + (SSLServerSocket) serverCtx.getServerSocketFactory().createServerSocket(0)) { + serverSocket.setEnabledProtocols(new String[] {"TLSv1.1"}); + int port = serverSocket.getLocalPort(); + + Thread serverThread = + new Thread(() -> { + try (SSLSocket conn = (SSLSocket) serverSocket.accept()) { + InputStream is = conn.getInputStream(); + OutputStream os = conn.getOutputStream(); + // Read until end of HTTP headers. + StringBuilder sb = new StringBuilder(); + while (!sb.toString().endsWith("\r\n\r\n")) { + int b = is.read(); + if (b < 0) { + break; + } + sb.append((char) b); + } + os.write( + "HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n" + .getBytes(StandardCharsets.US_ASCII)); + os.flush(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + serverThread.setDaemon(true); + serverThread.start(); + + X509TrustManager trustManager = TlsUtil.trustManager(certificate.certificate().getEncoded()); + SSLContext clientCtx = SSLContext.getInstance("TLS"); + clientCtx.init(null, new TrustManager[] {trustManager}, null); + + OkHttpHttpSender sender = + new OkHttpHttpSender( + URI.create("https://localhost:" + port + "/"), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + clientCtx, + trustManager, + null, + Long.MAX_VALUE, + Collections.singletonList("TLSv1.1")); + + AtomicReference responseRef = new AtomicReference<>(); + AtomicReference errorRef = new AtomicReference<>(); + CountDownLatch latch = new CountDownLatch(1); + sender.send( + new NoOpRequestBodyWriter(), + response -> { + responseRef.set(response); + latch.countDown(); + }, + error -> { + errorRef.set(error); + latch.countDown(); + }); + + assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); + assertThat(errorRef.get()).isNull(); + assertThat(responseRef.get()).isNotNull(); + assertThat(responseRef.get().getStatusCode()).isEqualTo(200); + } + } + + private static OkHttpHttpSender newSender( + String endpoint, @Nullable ExecutorService executorService) { + return new OkHttpHttpSender( + URI.create(endpoint), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + null, + null, + executorService, + Long.MAX_VALUE, + null); + } + + private static class NoOpRequestBodyWriter implements MessageWriter { + @Override + public void writeMessage(OutputStream output) {} + + @Override + public int getContentLength() { + return 0; + } + } + + @Test + void constructor_usesDefaultTrustManagerWhenTrustManagerIsNull() throws Exception { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + + assertThatCode(() -> + new OkHttpHttpSender( + URI.create("https://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) + .doesNotThrowAnyException(); + } + + @Test + void constructor_wrapsDefaultTrustManagerFailure() throws Exception { + String originalAlgorithm = Security.getProperty("ssl.TrustManagerFactory.algorithm"); + + try { + Security.setProperty("ssl.TrustManagerFactory.algorithm", "invalid"); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, null, null); + + assertThatThrownBy(() -> + new OkHttpHttpSender( + URI.create("https://localhost"), + "text/plain", + null, + Duration.ofSeconds(10), + Duration.ofSeconds(10), + Collections::emptyMap, + null, + null, + sslContext, + null, + null, + Long.MAX_VALUE, + null)) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Unable to initialize default trust manager") + .hasCauseInstanceOf(SSLException.class); + + } finally { + Security.setProperty("ssl.TrustManagerFactory.algorithm", originalAlgorithm); + } + } +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java new file mode 100644 index 00000000000..fa519e9ef5b --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpHttpSuppressionTest.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import io.opentelemetry.sdk.common.export.MessageWriter; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.Collections; + +class OkHttpHttpSuppressionTest extends AbstractOkHttpSuppressionTest { + + @Override + void send(OkHttpHttpSender sender, Runnable onSuccess, Runnable onFailure) { + byte[] content = "A".getBytes(StandardCharsets.UTF_8); + MessageWriter requestBodyWriter = + new MessageWriter() { + @Override + public void writeMessage(OutputStream output) throws IOException { + output.write(content); + } + + @Override + public int getContentLength() { + return content.length; + } + }; + sender.send(requestBodyWriter, response -> onSuccess.run(), error -> onFailure.run()); + } + + @Override + OkHttpHttpSender createSender(String endpoint) { + return new OkHttpHttpSender( + URI.create(endpoint), + "text/plain", + null, + Duration.ofNanos(10), + Duration.ofNanos(10), + Collections::emptyMap, + null, + null, + null, + null, + null, + Long.MAX_VALUE, + null); + } +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java new file mode 100644 index 00000000000..5830d5046f2 --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/OkHttpUtilTest.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.InstanceOfAssertFactories.type; + +import java.util.concurrent.ThreadPoolExecutor; +import okhttp3.Dispatcher; +import org.junit.jupiter.api.Test; + +class OkHttpUtilTest { + private static final int EXPECTED_MAX_REQUESTS = + Math.max(Runtime.getRuntime().availableProcessors(), 5); + + @Test + void newDispatcher_isBounded() { + Dispatcher dispatcher = OkHttpUtil.newDispatcher(); + + try { + assertThat(dispatcher.getMaxRequests()).isEqualTo(EXPECTED_MAX_REQUESTS); + assertThat(dispatcher.getMaxRequestsPerHost()).isEqualTo(5); + assertThat(dispatcher.executorService()) + .asInstanceOf(type(ThreadPoolExecutor.class)) + .satisfies(executor -> { + assertThat(executor.getMaximumPoolSize()).isEqualTo(EXPECTED_MAX_REQUESTS); + assertThat(executor.getRejectedExecutionHandler()) + .isInstanceOf(ThreadPoolExecutor.AbortPolicy.class); + }); + } finally { + dispatcher.executorService().shutdownNow(); + } + } +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java new file mode 100644 index 00000000000..d4074bc950a --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryInterceptorTest.java @@ -0,0 +1,384 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.mockito.internal.verification.VerificationModeFactory.times; + +import com.linecorp.armeria.common.HttpResponse; +import com.linecorp.armeria.common.HttpStatus; +import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.net.ConnectException; +import java.net.HttpRetryException; +import java.net.ServerSocket; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.time.Duration; +import java.util.OptionalLong; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Stream; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mock; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.stubbing.Answer; + +@ExtendWith(MockitoExtension.class) +class RetryInterceptorTest { + + @RegisterExtension static final MockWebServerExtension server = new MockWebServerExtension(); + + @Mock private RetryInterceptor.Sleeper sleeper; + @Mock private Supplier random; + private Predicate retryExceptionPredicate; + + private RetryInterceptor retrier; + private OkHttpClient client; + + @BeforeEach + void setUp() { + Logger logger = Logger.getLogger(RetryInterceptor.class.getName()); + logger.setLevel(Level.FINER); + retryExceptionPredicate = + spy( + new Predicate() { + @Override + public boolean test(IOException e) { + return RetryInterceptor.isRetryableException(e) + || (e instanceof HttpRetryException + && e.getMessage().contains("timeout retry")); + } + }); + + RetryPolicy retryPolicy = + RetryPolicy.builder() + .setBackoffMultiplier(1.6) + .setInitialBackoff(Duration.ofSeconds(1)) + .setMaxBackoff(Duration.ofSeconds(2)) + .setMaxAttempts(5) + .setRetryExceptionPredicate(retryExceptionPredicate) + .build(); + + retrier = + new RetryInterceptor( + retryPolicy, + r -> !r.isSuccessful(), + response -> OptionalLong.empty(), + retryExceptionPredicate, + sleeper, + random); + client = new OkHttpClient.Builder().addInterceptor(retrier).build(); + } + + @Test + void noRetryOnNullResponse() throws IOException { + Interceptor.Chain chain = mock(Interceptor.Chain.class); + Request request = new Request.Builder().url(server.httpUri().toString()).build(); + when(chain.proceed(any())).thenReturn(null); + when(chain.request()).thenReturn(request); + when(chain.call()).thenReturn(client.newCall(request)); + assertThatThrownBy( + () -> { + retrier.intercept(chain); + }) + .isInstanceOf(NullPointerException.class) + .hasMessage("response cannot be null."); + + verifyNoInteractions(retryExceptionPredicate); + verifyNoInteractions(random); + verifyNoInteractions(sleeper); + } + + @Test + void noRetry() throws Exception { + server.enqueue(HttpResponse.of(HttpStatus.OK)); + + try (Response response = sendRequest()) { + assertThat(response.isSuccessful()).isTrue(); + } + + verifyNoInteractions(random); + verifyNoInteractions(sleeper); + } + + @Test + void backoffResetsForEachCall() throws Exception { + server.enqueue(HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR)); + server.enqueue(HttpResponse.of(HttpStatus.OK)); + server.enqueue(HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR)); + server.enqueue(HttpResponse.of(HttpStatus.OK)); + when(random.get()).thenReturn(1.0d); + doNothing().when(sleeper).sleep(anyLong()); + + try (Response first = sendRequest(); + Response second = sendRequest()) { + assertThat(first.isSuccessful()).isTrue(); + assertThat(second.isSuccessful()).isTrue(); + } + + verify(sleeper, times(2)).sleep(TimeUnit.SECONDS.toNanos(1)); + verify(sleeper, never()).sleep(TimeUnit.MILLISECONDS.toNanos(1600)); + } + + @ParameterizedTest + // Test is mostly same for 5 or more attempts since it's the max. We check the backoff timings and + // handling of max attempts by checking both. + @ValueSource(ints = {5, 6}) + void backsOff(int attempts) throws Exception { + succeedOnAttempt(attempts); + when(random.get()).thenReturn(1.0d); + doNothing().when(sleeper).sleep(anyLong()); + + try (Response response = sendRequest()) { + if (attempts <= 5) { + assertThat(response.isSuccessful()).isTrue(); + } else { + assertThat(response.isSuccessful()).isFalse(); + } + } + + for (int i = 0; i < 5; i++) { + server.takeRequest(0, TimeUnit.NANOSECONDS); + } + } + + @Test + void interrupted() throws Exception { + succeedOnAttempt(5); + + // Backs off twice, second is interrupted + when(random.get()).thenReturn(1.0d).thenReturn(1.0d); + doAnswer( + new Answer() { + int counter = 0; + + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + if (counter++ == 1) { + throw new InterruptedException(); + } + return null; + } + }) + .when(sleeper) + .sleep(anyLong()); + + try (Response response = sendRequest()) { + assertThat(response.isSuccessful()).isFalse(); + } + verify(sleeper, times(2)).sleep(anyLong()); + for (int i = 0; i < 2; i++) { + server.takeRequest(0, TimeUnit.NANOSECONDS); + } + } + + @Test + void retryDelayOverride() throws Exception { + succeedOnAttempt(2); + doNothing().when(sleeper).sleep(anyLong()); + + RetryInterceptor retryInterceptor = + new RetryInterceptor( + RetryPolicy.builder() + .setBackoffMultiplier(1.6) + .setInitialBackoff(Duration.ofSeconds(1)) + .setMaxBackoff(Duration.ofSeconds(2)) + .setMaxAttempts(5) + .setRetryExceptionPredicate(retryExceptionPredicate) + .build(), + r -> !r.isSuccessful(), + response -> OptionalLong.of(123L), + retryExceptionPredicate, + sleeper, + random); + client = new OkHttpClient.Builder().addInterceptor(retryInterceptor).build(); + + try (Response response = sendRequest()) { + assertThat(response.isSuccessful()).isTrue(); + } + + verify(sleeper).sleep(123L); + verifyNoInteractions(random); + } + + @Test + void connectTimeout() throws Exception { + client = connectTimeoutClient(); + when(random.get()).thenReturn(1.0d); + doNothing().when(sleeper).sleep(anyLong()); + + // Connecting to a non-routable IP address to trigger connection error + assertThatThrownBy(() -> + client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) + .isInstanceOfAny(SocketTimeoutException.class, SocketException.class); + + verify(retryExceptionPredicate, times(5)).test(any()); + // Should retry maxAttempts, and sleep maxAttempts - 1 times + verify(sleeper, times(4)).sleep(anyLong()); + } + + @Test + void connectException() throws Exception { + client = connectTimeoutClient(); + when(random.get()).thenReturn(1.0d); + doNothing().when(sleeper).sleep(anyLong()); + + // Connecting to localhost on an unused port address to trigger java.net.ConnectException + int openPort = freePort(); + assertThatThrownBy(() -> + client + .newCall(new Request.Builder().url("http://localhost:" + openPort).build()) + .execute()) + .isInstanceOfAny(ConnectException.class, SocketTimeoutException.class); + + verify(retryExceptionPredicate, times(5)).test(any()); + // Should retry maxAttempts, and sleep maxAttempts - 1 times + verify(sleeper, times(4)).sleep(anyLong()); + } + + private static int freePort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Test + void nonRetryableException() throws InterruptedException { + client = connectTimeoutClient(); + // Override retryPredicate so that no exception is retryable + when(retryExceptionPredicate.test(any())).thenReturn(false); + + // Connecting to a non-routable IP address to trigger connection timeout + assertThatThrownBy(() -> + client.newCall(new Request.Builder().url("http://10.255.255.1").build()).execute()) + .isInstanceOfAny(SocketTimeoutException.class, SocketException.class); + + verify(retryExceptionPredicate, times(1)).test(any()); + verify(sleeper, never()).sleep(anyLong()); + } + + private OkHttpClient connectTimeoutClient() { + return new OkHttpClient.Builder() + .connectTimeout(Duration.ofMillis(10)) + .addInterceptor(retrier) + .build(); + } + + @ParameterizedTest + @MethodSource("isRetryableExceptionArgs") + void isRetryableException(IOException exception, boolean expectedRetryResult) { + assertThat(retrier.shouldRetryOnException(exception)).isEqualTo(expectedRetryResult); + } + + private static Stream isRetryableExceptionArgs() { + return Stream.of( + Arguments.argumentSet( + "SocketTimeoutException Connect timed out", + new SocketTimeoutException("Connect timed out"), + true), + Arguments.argumentSet( + "SocketTimeoutException connect timed out", + new SocketTimeoutException("connect timed out"), + true), + Arguments.argumentSet( + "SocketTimeoutException timeout", new SocketTimeoutException("timeout"), true), + Arguments.argumentSet( + "SocketTimeoutException Read timed out", + new SocketTimeoutException("Read timed out"), + true), + Arguments.argumentSet( + "SocketTimeoutException no message", new SocketTimeoutException(), true), + Arguments.argumentSet("UnknownHostException", new UnknownHostException("host"), true), + Arguments.argumentSet("SocketException closed", new SocketException("closed"), true), + Arguments.argumentSet( + "ConnectException localhost", + new ConnectException("Failed to connect to localhost/[0:0:0:0:0:0:0:1]:62611"), + true), + Arguments.argumentSet("IOException not retryable", new IOException("error"), false), + // Testing configured predicate + Arguments.argumentSet( + "HttpRetryException not retryable", new HttpRetryException("error", 400), false), + Arguments.argumentSet( + "HttpRetryException timeout retry", + new HttpRetryException("timeout retry", 400), + true)); + } + + @Test + void isRetryableExceptionDefaultBehaviour() { + RetryInterceptor retryInterceptor = + new RetryInterceptor( + RetryPolicy.getDefault(), + OkHttpHttpSender::isRetryable, + response -> OptionalLong.empty()); + assertThat( + retryInterceptor.shouldRetryOnException( + new SocketTimeoutException("Connect timed out"))) + .isTrue(); + assertThat(retryInterceptor.shouldRetryOnException(new IOException("Connect timed out"))) + .isFalse(); + } + + @Test + void isRetryableExceptionCustomRetryPredicate() { + RetryInterceptor retryInterceptor = + new RetryInterceptor( + RetryPolicy.builder() + .setRetryExceptionPredicate((IOException e) -> e.getMessage().equals("retry")) + .build(), + OkHttpHttpSender::isRetryable, + response -> OptionalLong.empty()); + + assertThat(retryInterceptor.shouldRetryOnException(new IOException("some message"))).isFalse(); + assertThat(retryInterceptor.shouldRetryOnException(new IOException("retry"))).isTrue(); + assertThat( + retryInterceptor.shouldRetryOnException( + new SocketTimeoutException("Connect timed out"))) + .isFalse(); + } + + private Response sendRequest() throws IOException { + return client.newCall(new Request.Builder().url(server.httpUri().toString()).build()).execute(); + } + + private static void succeedOnAttempt(int attempt) { + for (int i = 1; i < attempt; i++) { + server.enqueue(HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR)); + } + server.enqueue(HttpResponse.of(HttpStatus.OK)); + } +} diff --git a/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryStateTest.java b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryStateTest.java new file mode 100644 index 00000000000..84886390a48 --- /dev/null +++ b/exporters/sender/okhttp/src/test/java/io/opentelemetry/exporter/sender/okhttp/internal/RetryStateTest.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.exporter.sender.okhttp.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.io.IOException; +import java.time.Duration; +import java.util.OptionalLong; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import okhttp3.Call; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import org.junit.jupiter.api.Test; + +class RetryStateTest { + + @Test + void backoffIsCappedByRemainingTimeout() { + AtomicLong clock = new AtomicLong(); + AtomicLong sleptNanos = new AtomicLong(); + RetryState retryState = + new RetryState( + retryPolicy(), + (IOException e) -> true, + delay -> { + sleptNanos.set(delay); + clock.addAndGet(delay); + }, + () -> 1.0d, + TimeUnit.MILLISECONDS.toNanos(100), + clock::get); + clock.set(TimeUnit.MILLISECONDS.toNanos(40)); + + assertThat(retryState.backoff(OptionalLong.empty())).isFalse(); + assertThat(sleptNanos.get()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(60)); + assertThat(retryState.remainingNanos()).isZero(); + } + + @Test + void backoffDoesNotSleepAfterTimeoutExpires() { + AtomicLong clock = new AtomicLong(); + AtomicLong sleepCalls = new AtomicLong(); + RetryState retryState = + new RetryState( + retryPolicy(), + (IOException e) -> true, + delay -> sleepCalls.incrementAndGet(), + () -> 1.0d, + TimeUnit.MILLISECONDS.toNanos(100), + clock::get); + clock.set(TimeUnit.MILLISECONDS.toNanos(100)); + + assertThat(retryState.backoff(OptionalLong.empty())).isFalse(); + assertThat(sleepCalls).hasValue(0); + } + + @Test + void callTimeoutUsesRemainingExportBudget() { + AtomicLong clock = new AtomicLong(); + RetryState retryState = + new RetryState( + retryPolicy(), + (IOException e) -> true, + delay -> {}, + () -> 1.0d, + TimeUnit.SECONDS.toNanos(1), + clock::get); + clock.set(TimeUnit.MILLISECONDS.toNanos(400)); + Call call = new OkHttpClient().newCall(new Request.Builder().url("http://localhost/").build()); + + assertThat(retryState.configureCallTimeout(call)).isTrue(); + assertThat(call.timeout().timeoutNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(600)); + assertThat(call.timeout().hasDeadline()).isTrue(); + assertThat(call.timeout().deadlineNanoTime()).isEqualTo(TimeUnit.SECONDS.toNanos(1)); + + clock.set(TimeUnit.MILLISECONDS.toNanos(700)); + Call retry = new OkHttpClient().newCall(new Request.Builder().url("http://localhost/").build()); + + assertThat(retryState.configureCallTimeout(retry)).isTrue(); + assertThat(retry.timeout().timeoutNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(300)); + assertThat(retry.timeout().deadlineNanoTime()).isEqualTo(call.timeout().deadlineNanoTime()); + } + + @Test + void callTimeoutIsUnchangedWithoutExportTimeout() { + RetryState retryState = + new RetryState( + retryPolicy(), (IOException e) -> true, delay -> {}, () -> 1.0d, 0, System::nanoTime); + Call call = new OkHttpClient().newCall(new Request.Builder().url("http://localhost/").build()); + + assertThat(retryState.configureCallTimeout(call)).isTrue(); + assertThat(call.timeout().timeoutNanos()).isZero(); + assertThat(call.timeout().hasDeadline()).isFalse(); + } + + @Test + void callTimeoutIsRejectedAfterExportBudgetExpires() { + AtomicLong clock = new AtomicLong(); + RetryState retryState = + new RetryState( + retryPolicy(), + (IOException e) -> true, + delay -> {}, + () -> 1.0d, + TimeUnit.SECONDS.toNanos(1), + clock::get); + clock.set(TimeUnit.SECONDS.toNanos(1)); + Call call = new OkHttpClient().newCall(new Request.Builder().url("http://localhost/").build()); + + assertThat(retryState.configureCallTimeout(call)).isFalse(); + } + + @Test + void retryPredicateAndAttemptLimitAreRespected() { + RetryState retryState = + new RetryState( + retryPolicy(), + exception -> exception.getMessage().startsWith("retry"), + delay -> {}, + () -> 1.0d, + 0, + System::nanoTime); + + assertThat(retryState.canRetry(0)).isTrue(); + assertThat(retryState.canRetry(1)).isTrue(); + assertThat(retryState.canRetry(2)).isFalse(); + assertThat(retryState.shouldRetryOnException(new IOException("retry this"))).isTrue(); + assertThat(retryState.shouldRetryOnException(new IOException("stop"))).isFalse(); + } + + private static RetryPolicy retryPolicy() { + return RetryPolicy.builder() + .setInitialBackoff(Duration.ofMillis(300)) + .setMaxBackoff(Duration.ofMillis(300)) + .setMaxAttempts(3) + .build(); + } +} diff --git a/exporters/sender/okhttp/src/test/resources/enable-legacy-tls.security b/exporters/sender/okhttp/src/test/resources/enable-legacy-tls.security new file mode 100644 index 00000000000..7d8f6e8db94 --- /dev/null +++ b/exporters/sender/okhttp/src/test/resources/enable-legacy-tls.security @@ -0,0 +1,4 @@ +# Removes TLSv1 and TLSv1.1 from jdk.tls.disabledAlgorithms so that OkHttpHttpSenderTest +# can negotiate TLSv1.1. Applied at JVM bootstrap via -Djava.security.properties. +jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, DH keySize < 1024, \ + EC keySize < 224, 3DES_EDE_CBC, anon, NULL, include jdk.disabled.namedCurves diff --git a/exporters/zipkin/README.md b/exporters/zipkin/README.md deleted file mode 100644 index b398569d435..00000000000 --- a/exporters/zipkin/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# OpenTelemetry - Zipkin Span Exporter - -[![Javadocs][javadoc-image]][javadoc-url] - -This is an OpenTelemetry exporter that sends span data using the [io.zipkin.reporter2:zipkin-reporter](https://github.com/openzipkin/zipkin-reporter-java) library. - -By default, this POSTs json in [Zipkin format](https://zipkin.io/zipkin-api/#/default/post_spans) to -a specified HTTP URL. This could be to a [Zipkin](https://zipkin.io) service, or anything that -consumes the same format. - -You can alternatively use other formats, such as protobuf, or override the `Sender` to use a non-HTTP transport, such as Kafka. - -## Configuration - -The Zipkin span exporter can be configured programmatically. - -An example of simple Zipkin exporter initialization. In this case -spans will be sent to a Zipkin endpoint running on `localhost`: - -```java -ZipkinSpanExporter exporter = - ZipkinSpanExporter.builder() - .setEndpoint("http://localhost/api/v2/spans") - .setServiceName("my-service") - .build(); -``` - -Service name and Endpoint can be also configured via environment variables or system properties. - -```java -// Using environment variables -ZipkinSpanExporter exporter = - ZipkinSpanExporter.builder() - .readEnvironmentVariables() - .build() -``` - -```java -// Using system properties -ZipkinSpanExporter exporter = - ZipkinSpanExporter.builder() - .readSystemProperties() - .build() -``` - -The Zipkin span exporter will look for the following environment variables / system properties: -* `OTEL_ZIPKIN_SERVICE_NAME` / `otel.zipkin.service.name` -* `OTEL_ZIPKIN_ENDPOINT` / `otel.zipkin.endpoint` - - -## Compatibility - -As with the OpenTelemetry SDK itself, this exporter is compatible with Java 8+ and Android API level 24+. - -## Attribution - -The code in this module is based on the [OpenCensus Zipkin exporter][oc-origin] code. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-exporter-zipkin.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-exporter-zipkin -[oc-origin]: https://github.com/census-instrumentation/opencensus-java/ diff --git a/exporters/zipkin/build.gradle.kts b/exporters/zipkin/build.gradle.kts deleted file mode 100644 index c2ac76cde0f..00000000000 --- a/exporters/zipkin/build.gradle.kts +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry - Zipkin Exporter" -otelJava.moduleName.set("io.opentelemetry.exporter.zipkin") - -dependencies { - api(project(":sdk:all")) - - api("io.zipkin.reporter2:zipkin-reporter") - - implementation(project(":semconv")) - - implementation("io.zipkin.reporter2:zipkin-sender-okhttp3") - - testImplementation(project(":sdk:testing")) - - testImplementation("com.linecorp.armeria:armeria") - testImplementation("org.testcontainers:junit-jupiter") -} diff --git a/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporter.java b/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporter.java deleted file mode 100644 index 373ae7cc840..00000000000 --- a/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporter.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.zipkin; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static java.util.concurrent.TimeUnit.NANOSECONDS; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.AttributeType; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.ThrottlingLogger; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.IOException; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Enumeration; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import zipkin2.Callback; -import zipkin2.Endpoint; -import zipkin2.Span; -import zipkin2.codec.BytesEncoder; -import zipkin2.reporter.Sender; - -/** - * This class was based on the OpenCensus zipkin exporter code at - * https://github.com/census-instrumentation/opencensus-java/tree/c960b19889de5e4a7b25f90919d28b066590d4f0/exporters/trace/zipkin - */ -public final class ZipkinSpanExporter implements SpanExporter { - public static final String DEFAULT_ENDPOINT = "http://localhost:9411/api/v2/spans"; - public static final Logger baseLogger = Logger.getLogger(ZipkinSpanExporter.class.getName()); - - private final ThrottlingLogger logger = new ThrottlingLogger(baseLogger); - - static final String OTEL_DROPPED_ATTRIBUTES_COUNT = "otel.dropped_attributes_count"; - static final String OTEL_DROPPED_EVENTS_COUNT = "otel.dropped_events_count"; - static final String OTEL_STATUS_CODE = "otel.status_code"; - static final AttributeKey STATUS_ERROR = stringKey("error"); - - static final String KEY_INSTRUMENTATION_SCOPE_NAME = "otel.scope.name"; - static final String KEY_INSTRUMENTATION_SCOPE_VERSION = "otel.scope.version"; - static final String KEY_INSTRUMENTATION_LIBRARY_NAME = "otel.library.name"; - static final String KEY_INSTRUMENTATION_LIBRARY_VERSION = "otel.library.version"; - - private final BytesEncoder encoder; - private final Sender sender; - @Nullable private final InetAddress localAddress; - - ZipkinSpanExporter(BytesEncoder encoder, Sender sender) { - this.encoder = encoder; - this.sender = sender; - localAddress = produceLocalIp(); - } - - /** Logic borrowed from brave.internal.Platform.produceLocalEndpoint */ - @Nullable - static InetAddress produceLocalIp() { - try { - Enumeration nics = NetworkInterface.getNetworkInterfaces(); - while (nics.hasMoreElements()) { - NetworkInterface nic = nics.nextElement(); - Enumeration addresses = nic.getInetAddresses(); - while (addresses.hasMoreElements()) { - InetAddress address = addresses.nextElement(); - if (address.isSiteLocalAddress()) { - return address; - } - } - } - } catch (Exception e) { - // don't crash the caller if there was a problem reading nics. - baseLogger.log(Level.FINE, "error reading nics", e); - } - return null; - } - - Span generateSpan(SpanData spanData) { - Endpoint endpoint = getEndpoint(spanData); - - long startTimestamp = toEpochMicros(spanData.getStartEpochNanos()); - long endTimestamp = toEpochMicros(spanData.getEndEpochNanos()); - - Span.Builder spanBuilder = - Span.newBuilder() - .traceId(spanData.getTraceId()) - .id(spanData.getSpanId()) - .kind(toSpanKind(spanData)) - .name(spanData.getName()) - .timestamp(toEpochMicros(spanData.getStartEpochNanos())) - .duration(Math.max(1, endTimestamp - startTimestamp)) - .localEndpoint(endpoint); - - if (spanData.getParentSpanContext().isValid()) { - spanBuilder.parentId(spanData.getParentSpanId()); - } - - Attributes spanAttributes = spanData.getAttributes(); - spanAttributes.forEach( - (key, value) -> spanBuilder.putTag(key.getKey(), valueToString(key, value))); - int droppedAttributes = spanData.getTotalAttributeCount() - spanAttributes.size(); - if (droppedAttributes > 0) { - spanBuilder.putTag(OTEL_DROPPED_ATTRIBUTES_COUNT, String.valueOf(droppedAttributes)); - } - - StatusData status = spanData.getStatus(); - - // include status code & error. - if (status.getStatusCode() != StatusCode.UNSET) { - spanBuilder.putTag(OTEL_STATUS_CODE, status.getStatusCode().toString()); - - // add the error tag, if it isn't already in the source span. - if (status.getStatusCode() == StatusCode.ERROR && spanAttributes.get(STATUS_ERROR) == null) { - spanBuilder.putTag(STATUS_ERROR.getKey(), nullToEmpty(status.getDescription())); - } - } - - InstrumentationScopeInfo instrumentationScopeInfo = spanData.getInstrumentationScopeInfo(); - - if (!instrumentationScopeInfo.getName().isEmpty()) { - spanBuilder.putTag(KEY_INSTRUMENTATION_SCOPE_NAME, instrumentationScopeInfo.getName()); - // Include instrumentation library name for backwards compatibility - spanBuilder.putTag(KEY_INSTRUMENTATION_LIBRARY_NAME, instrumentationScopeInfo.getName()); - } - if (instrumentationScopeInfo.getVersion() != null) { - spanBuilder.putTag(KEY_INSTRUMENTATION_SCOPE_VERSION, instrumentationScopeInfo.getVersion()); - // Include instrumentation library name for backwards compatibility - spanBuilder.putTag( - KEY_INSTRUMENTATION_LIBRARY_VERSION, instrumentationScopeInfo.getVersion()); - } - - for (EventData annotation : spanData.getEvents()) { - spanBuilder.addAnnotation(toEpochMicros(annotation.getEpochNanos()), annotation.getName()); - } - int droppedEvents = spanData.getTotalRecordedEvents() - spanData.getEvents().size(); - if (droppedEvents > 0) { - spanBuilder.putTag(OTEL_DROPPED_EVENTS_COUNT, String.valueOf(droppedEvents)); - } - - return spanBuilder.build(); - } - - private static String nullToEmpty(String value) { - return value != null ? value : ""; - } - - private Endpoint getEndpoint(SpanData spanData) { - Attributes resourceAttributes = spanData.getResource().getAttributes(); - - Endpoint.Builder endpoint = Endpoint.newBuilder().ip(localAddress); - - // use the service.name from the Resource, if it's been set. - String serviceNameValue = resourceAttributes.get(ResourceAttributes.SERVICE_NAME); - if (serviceNameValue == null) { - serviceNameValue = Resource.getDefault().getAttribute(ResourceAttributes.SERVICE_NAME); - } - // In practice should never be null unless the default Resource spec is changed. - if (serviceNameValue != null) { - endpoint.serviceName(serviceNameValue); - } - return endpoint.build(); - } - - @Nullable - private static Span.Kind toSpanKind(SpanData spanData) { - switch (spanData.getKind()) { - case SERVER: - return Span.Kind.SERVER; - case CLIENT: - return Span.Kind.CLIENT; - case PRODUCER: - return Span.Kind.PRODUCER; - case CONSUMER: - return Span.Kind.CONSUMER; - case INTERNAL: - return null; - } - return null; - } - - private static long toEpochMicros(long epochNanos) { - return NANOSECONDS.toMicros(epochNanos); - } - - private static String valueToString(AttributeKey key, Object attributeValue) { - AttributeType type = key.getType(); - switch (type) { - case STRING: - case BOOLEAN: - case LONG: - case DOUBLE: - return String.valueOf(attributeValue); - case STRING_ARRAY: - case BOOLEAN_ARRAY: - case LONG_ARRAY: - case DOUBLE_ARRAY: - return commaSeparated((List) attributeValue); - } - throw new IllegalStateException("Unknown attribute type: " + type); - } - - private static String commaSeparated(List values) { - StringBuilder builder = new StringBuilder(); - for (Object value : values) { - if (builder.length() != 0) { - builder.append(','); - } - builder.append(value); - } - return builder.toString(); - } - - @Override - public CompletableResultCode export(Collection spanDataList) { - List encodedSpans = new ArrayList<>(spanDataList.size()); - for (SpanData spanData : spanDataList) { - encodedSpans.add(encoder.encode(generateSpan(spanData))); - } - - CompletableResultCode result = new CompletableResultCode(); - sender - .sendSpans(encodedSpans) - .enqueue( - new Callback() { - @Override - public void onSuccess(Void value) { - result.succeed(); - } - - @Override - public void onError(Throwable t) { - logger.log(Level.WARNING, "Failed to export spans", t); - result.fail(); - } - }); - return result; - } - - @Override - public CompletableResultCode flush() { - // nothing required here - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - try { - sender.close(); - } catch (IOException e) { - logger.log(Level.WARNING, "Exception while closing the Zipkin Sender instance", e); - } - return CompletableResultCode.ofSuccess(); - } - - /** - * Returns a new Builder for {@link ZipkinSpanExporter}. - * - * @return a new {@link ZipkinSpanExporter}. - */ - public static ZipkinSpanExporterBuilder builder() { - return new ZipkinSpanExporterBuilder(); - } - - // VisibleForTesting - @Nullable - InetAddress getLocalAddressForTest() { - return localAddress; - } -} diff --git a/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterBuilder.java b/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterBuilder.java deleted file mode 100644 index 6814596365d..00000000000 --- a/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterBuilder.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.zipkin; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; -import zipkin2.Span; -import zipkin2.codec.BytesEncoder; -import zipkin2.codec.SpanBytesEncoder; -import zipkin2.reporter.Sender; -import zipkin2.reporter.okhttp3.OkHttpSender; - -/** Builder class for {@link ZipkinSpanExporter}. */ -public final class ZipkinSpanExporterBuilder { - private BytesEncoder encoder = SpanBytesEncoder.JSON_V2; - @Nullable private Sender sender; - private String endpoint = ZipkinSpanExporter.DEFAULT_ENDPOINT; - private long readTimeoutMillis = TimeUnit.SECONDS.toMillis(10); - - /** - * Sets the Zipkin sender. Implements the client side of the span transport. A {@link - * OkHttpSender} is a good default. - * - *

    The {@link Sender#close()} method will be called when the exporter is shut down. - * - * @param sender the Zipkin sender implementation. - * @return this. - */ - public ZipkinSpanExporterBuilder setSender(Sender sender) { - requireNonNull(sender, "sender"); - this.sender = sender; - return this; - } - - /** - * Sets the {@link BytesEncoder}, which controls the format used by the {@link Sender}. Defaults - * to the {@link SpanBytesEncoder#JSON_V2}. - * - * @param encoder the {@code BytesEncoder} to use. - * @return this. - * @see SpanBytesEncoder - */ - public ZipkinSpanExporterBuilder setEncoder(BytesEncoder encoder) { - requireNonNull(encoder, "encoder"); - this.encoder = encoder; - return this; - } - - /** - * Sets the zipkin endpoint. This will use the endpoint to assign a {@link OkHttpSender} instance - * to this builder. - * - * @param endpoint The Zipkin endpoint URL, ex. "http://zipkinhost:9411/api/v2/spans". - * @return this. - * @see OkHttpSender - */ - public ZipkinSpanExporterBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - this.endpoint = endpoint; - return this; - } - - /** - * Sets the maximum time to wait for the export of a batch of spans. If unset, defaults to 10s. - * - * @return this. - * @since 1.2.0 - */ - public ZipkinSpanExporterBuilder setReadTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - this.readTimeoutMillis = unit.toMillis(timeout); - return this; - } - - /** - * Sets the maximum time to wait for the export of a batch of spans. If unset, defaults to 10s. - * - * @return this. - * @since 1.2.0 - */ - public ZipkinSpanExporterBuilder setReadTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - setReadTimeout(timeout.toMillis(), TimeUnit.MILLISECONDS); - return this; - } - - /** - * Builds a {@link ZipkinSpanExporter}. - * - * @return a {@code ZipkinSpanExporter}. - */ - public ZipkinSpanExporter build() { - Sender sender = this.sender; - if (sender == null) { - sender = - OkHttpSender.newBuilder().endpoint(endpoint).readTimeout((int) readTimeoutMillis).build(); - } - return new ZipkinSpanExporter(encoder, sender); - } -} diff --git a/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/package-info.java b/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/package-info.java deleted file mode 100644 index 8e03649dd64..00000000000 --- a/exporters/zipkin/src/main/java/io/opentelemetry/exporter/zipkin/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -@ParametersAreNonnullByDefault -package io.opentelemetry.exporter.zipkin; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/exporters/zipkin/src/test/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterEndToEndHttpTest.java b/exporters/zipkin/src/test/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterEndToEndHttpTest.java deleted file mode 100644 index acf455ccda8..00000000000 --- a/exporters/zipkin/src/test/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterEndToEndHttpTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.zipkin; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.linecorp.armeria.client.WebClient; -import com.linecorp.armeria.common.AggregatedHttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.IdGenerator; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.testcontainers.containers.GenericContainer; -import org.testcontainers.containers.wait.strategy.Wait; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; -import zipkin2.Endpoint; -import zipkin2.Span; -import zipkin2.codec.Encoding; -import zipkin2.codec.SpanBytesDecoder; -import zipkin2.codec.SpanBytesEncoder; -import zipkin2.reporter.okhttp3.OkHttpSender; - -@Testcontainers(disabledWithoutDocker = true) -class ZipkinSpanExporterEndToEndHttpTest { - private static final WebClient client = WebClient.of(); - - private static final int ZIPKIN_API_PORT = 9411; - - private static final String SPAN_ID = "9cc1e3049173be09"; - private static final String PARENT_SPAN_ID = "8b03ab423da481c5"; - private static final String SPAN_NAME = "Recv.helloworld.Greeter.SayHello"; - private static final long START_EPOCH_NANOS = 1505855794_194009601L; - private static final long END_EPOCH_NANOS = 1505855799_465726528L; - private static final long RECEIVED_TIMESTAMP_NANOS = 1505855799_433901068L; - private static final long SENT_TIMESTAMP_NANOS = 1505855799_459486280L; - private static final Attributes attributes = Attributes.empty(); - private static final List annotations = - Collections.unmodifiableList( - Arrays.asList( - EventData.create(RECEIVED_TIMESTAMP_NANOS, "RECEIVED", Attributes.empty()), - EventData.create(SENT_TIMESTAMP_NANOS, "SENT", Attributes.empty()))); - - private static final String ENDPOINT_V1_SPANS = "/api/v1/spans"; - private static final String ENDPOINT_V2_SPANS = "/api/v2/spans"; - private static final String SERVICE_NAME = "myService"; - - @Container - public static GenericContainer zipkinContainer = - new GenericContainer<>("ghcr.io/openzipkin/zipkin:2.23") - .withExposedPorts(ZIPKIN_API_PORT) - .waitingFor(Wait.forHttp("/health").forPort(ZIPKIN_API_PORT)); - - @Test - void testExportWithDefaultEncoding() { - ZipkinSpanExporter exporter = - ZipkinSpanExporter.builder().setEndpoint(zipkinUrl(ENDPOINT_V2_SPANS)).build(); - - exportAndVerify(exporter); - } - - @Test - void testExportAsProtobuf() { - ZipkinSpanExporter exporter = - buildZipkinExporter(zipkinUrl(ENDPOINT_V2_SPANS), Encoding.PROTO3, SpanBytesEncoder.PROTO3); - exportAndVerify(exporter); - } - - @Test - void testExportAsThrift() { - @SuppressWarnings("deprecation") // we have to use the deprecated thrift encoding to test it - ZipkinSpanExporter exporter = - buildZipkinExporter(zipkinUrl(ENDPOINT_V1_SPANS), Encoding.THRIFT, SpanBytesEncoder.THRIFT); - exportAndVerify(exporter); - } - - @Test - void testExportAsJsonV1() { - ZipkinSpanExporter exporter = - buildZipkinExporter(zipkinUrl(ENDPOINT_V1_SPANS), Encoding.JSON, SpanBytesEncoder.JSON_V1); - exportAndVerify(exporter); - } - - @Test - void testExportFailedAsWrongEncoderUsed() { - ZipkinSpanExporter zipkinSpanExporter = - buildZipkinExporter(zipkinUrl(ENDPOINT_V2_SPANS), Encoding.JSON, SpanBytesEncoder.PROTO3); - - String traceId = IdGenerator.random().generateTraceId(); - SpanData spanData = buildStandardSpan(traceId).build(); - CompletableResultCode resultCode = zipkinSpanExporter.export(Collections.singleton(spanData)); - - assertThat(resultCode.isSuccess()).isFalse(); - List zipkinSpans = getTrace(traceId); - assertThat(zipkinSpans).isEmpty(); - } - - private static ZipkinSpanExporter buildZipkinExporter( - String endpoint, Encoding encoding, SpanBytesEncoder encoder) { - return ZipkinSpanExporter.builder() - .setSender(OkHttpSender.newBuilder().endpoint(endpoint).encoding(encoding).build()) - .setEncoder(encoder) - .build(); - } - - /** - * Exports a span, verify that it was received by Zipkin, and check that the span stored by Zipkin - * matches what was sent. - */ - private static void exportAndVerify(ZipkinSpanExporter zipkinSpanExporter) { - String traceId = IdGenerator.random().generateTraceId(); - SpanData spanData = buildStandardSpan(traceId).build(); - CompletableResultCode resultCode = zipkinSpanExporter.export(Collections.singleton(spanData)); - resultCode.join(10, TimeUnit.SECONDS); - - assertThat(resultCode.isSuccess()).isTrue(); - List zipkinSpans = getTrace(traceId); - - assertThat(zipkinSpans).isNotNull(); - assertThat(zipkinSpans.size()).isEqualTo(1); - assertThat(zipkinSpans.get(0)) - .isEqualTo(buildZipkinSpan(zipkinSpanExporter.getLocalAddressForTest(), traceId)); - } - - private static TestSpanData.Builder buildStandardSpan(String traceId) { - return TestSpanData.builder() - .setSpanContext( - SpanContext.create(traceId, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())) - .setParentSpanContext( - SpanContext.create( - traceId, PARENT_SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setName(SPAN_NAME) - .setStartEpochNanos(START_EPOCH_NANOS) - .setAttributes(attributes) - .setTotalAttributeCount(attributes.size()) - .setTotalRecordedEvents(annotations.size()) - .setEvents(annotations) - .setLinks(Collections.emptyList()) - .setEndEpochNanos(END_EPOCH_NANOS) - .setHasEnded(true) - .setResource(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, SERVICE_NAME))); - } - - private static Span buildZipkinSpan(InetAddress localAddress, String traceId) { - return Span.newBuilder() - .traceId(traceId) - .parentId(PARENT_SPAN_ID) - .id(SPAN_ID) - .kind(Span.Kind.SERVER) - .name(SPAN_NAME) - .timestamp(START_EPOCH_NANOS / 1000) - .duration((END_EPOCH_NANOS / 1000) - (START_EPOCH_NANOS / 1000)) - .localEndpoint(Endpoint.newBuilder().serviceName(SERVICE_NAME).ip(localAddress).build()) - .addAnnotation(RECEIVED_TIMESTAMP_NANOS / 1000, "RECEIVED") - .addAnnotation(SENT_TIMESTAMP_NANOS / 1000, "SENT") - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build(); - } - - private static List getTrace(String traceId) { - AggregatedHttpResponse response = - client.get(zipkinUrl("/api/v2/trace/" + traceId)).aggregate().join(); - if (response.status().equals(HttpStatus.NOT_FOUND)) { - return Collections.emptyList(); - } - return SpanBytesDecoder.JSON_V2.decodeList(response.content().array()); - } - - private static String zipkinUrl(String endpoint) { - return "http://localhost:" + zipkinContainer.getMappedPort(ZIPKIN_API_PORT) + endpoint; - } -} diff --git a/exporters/zipkin/src/test/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterTest.java b/exporters/zipkin/src/test/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterTest.java deleted file mode 100644 index 382383f68e6..00000000000 --- a/exporters/zipkin/src/test/java/io/opentelemetry/exporter/zipkin/ZipkinSpanExporterTest.java +++ /dev/null @@ -1,473 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.exporter.zipkin; - -import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; -import static io.opentelemetry.api.common.AttributeKey.doubleKey; -import static io.opentelemetry.api.common.AttributeKey.longArrayKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; -import java.io.IOException; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import zipkin2.Call; -import zipkin2.Callback; -import zipkin2.Endpoint; -import zipkin2.Span; -import zipkin2.codec.SpanBytesEncoder; -import zipkin2.reporter.Sender; - -@ExtendWith(MockitoExtension.class) -class ZipkinSpanExporterTest { - - @Mock private Sender mockSender; - @Mock private SpanBytesEncoder mockEncoder; - @Mock private Call mockZipkinCall; - - private static final String TRACE_ID = "d239036e7d5cec116b562147388b35bf"; - private static final String SPAN_ID = "9cc1e3049173be09"; - private static final String PARENT_SPAN_ID = "8b03ab423da481c5"; - private static final Attributes attributes = Attributes.empty(); - private static final List annotations = - Collections.unmodifiableList( - Arrays.asList( - EventData.create(1505855799_433901068L, "RECEIVED", Attributes.empty()), - EventData.create(1505855799_459486280L, "SENT", Attributes.empty()))); - - private final ZipkinSpanExporter exporter = ZipkinSpanExporter.builder().build(); - - @Test - void generateSpan_remoteParent() { - SpanData data = buildStandardSpan().build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - standardZipkinSpanBuilder(Span.Kind.SERVER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_subMicroDurations() { - SpanData data = - buildStandardSpan() - .setStartEpochNanos(1505855794_194009601L) - .setEndEpochNanos(1505855794_194009999L) - .build(); - - Span expected = - standardZipkinSpanBuilder(Span.Kind.SERVER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .duration(1) - .build(); - assertThat(exporter.generateSpan(data)).isEqualTo(expected); - } - - @Test - void generateSpan_ServerKind() { - SpanData data = buildStandardSpan().setKind(SpanKind.SERVER).build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - standardZipkinSpanBuilder(Span.Kind.SERVER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_ClientKind() { - SpanData data = buildStandardSpan().setKind(SpanKind.CLIENT).build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - standardZipkinSpanBuilder(Span.Kind.CLIENT) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_InternalKind() { - SpanData data = buildStandardSpan().setKind(SpanKind.INTERNAL).build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - standardZipkinSpanBuilder(null) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_ConsumeKind() { - SpanData data = buildStandardSpan().setKind(SpanKind.CONSUMER).build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - standardZipkinSpanBuilder(Span.Kind.CONSUMER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_ProducerKind() { - SpanData data = buildStandardSpan().setKind(SpanKind.PRODUCER).build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - standardZipkinSpanBuilder(Span.Kind.PRODUCER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_ResourceServiceNameMapping() { - Resource resource = - Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, "super-zipkin-service")); - SpanData data = buildStandardSpan().setResource(resource).build(); - - Endpoint expectedEndpoint = - Endpoint.newBuilder() - .serviceName("super-zipkin-service") - .ip(exporter.getLocalAddressForTest()) - .build(); - Span expectedZipkinSpan = - buildZipkinSpan(Span.Kind.SERVER).toBuilder() - .localEndpoint(expectedEndpoint) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build(); - assertThat(exporter.generateSpan(data)).isEqualTo(expectedZipkinSpan); - } - - @Test - void generateSpan_defaultResourceServiceName() { - SpanData data = buildStandardSpan().setResource(Resource.empty()).build(); - - Endpoint expectedEndpoint = - Endpoint.newBuilder() - .serviceName(Resource.getDefault().getAttribute(ResourceAttributes.SERVICE_NAME)) - .ip(exporter.getLocalAddressForTest()) - .build(); - Span expectedZipkinSpan = - buildZipkinSpan(Span.Kind.SERVER).toBuilder() - .localEndpoint(expectedEndpoint) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build(); - assertThat(exporter.generateSpan(data)).isEqualTo(expectedZipkinSpan); - } - - @Test - void generateSpan_WithAttributes() { - Attributes attributes = - Attributes.builder() - .put(stringKey("string"), "string value") - .put(booleanKey("boolean"), false) - .put(longKey("long"), 9999L) - .put(doubleKey("double"), 222.333d) - .put(booleanArrayKey("booleanArray"), Arrays.asList(true, false)) - .put(stringArrayKey("stringArray"), Collections.singletonList("Hello")) - .put(doubleArrayKey("doubleArray"), Arrays.asList(32.33d, -98.3d)) - .put(longArrayKey("longArray"), Arrays.asList(33L, 999L)) - .build(); - SpanData data = - buildStandardSpan() - .setAttributes(attributes) - .setTotalAttributeCount(28) - .setTotalRecordedEvents(3) - .setKind(SpanKind.CLIENT) - .build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - buildZipkinSpan(Span.Kind.CLIENT).toBuilder() - .putTag("string", "string value") - .putTag("boolean", "false") - .putTag("long", "9999") - .putTag("double", "222.333") - .putTag("booleanArray", "true,false") - .putTag("stringArray", "Hello") - .putTag("doubleArray", "32.33,-98.3") - .putTag("longArray", "33,999") - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .putTag(ZipkinSpanExporter.OTEL_DROPPED_ATTRIBUTES_COUNT, "20") - .putTag(ZipkinSpanExporter.OTEL_DROPPED_EVENTS_COUNT, "1") - .build()); - } - - @Test - void generateSpan_WithInstrumentationLibraryInfo() { - SpanData data = - buildStandardSpan() - .setInstrumentationScopeInfo( - InstrumentationScopeInfo.create("io.opentelemetry.auto", "1.0.0", null)) - .setKind(SpanKind.CLIENT) - .build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - buildZipkinSpan(Span.Kind.CLIENT).toBuilder() - .putTag("otel.scope.name", "io.opentelemetry.auto") - .putTag("otel.scope.version", "1.0.0") - .putTag("otel.library.name", "io.opentelemetry.auto") - .putTag("otel.library.version", "1.0.0") - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build()); - } - - @Test - void generateSpan_AlreadyHasHttpStatusInfo() { - Attributes attributeMap = - Attributes.of( - SemanticAttributes.HTTP_STATUS_CODE, 404L, stringKey("error"), "A user provided error"); - SpanData data = - buildStandardSpan() - .setAttributes(attributeMap) - .setKind(SpanKind.CLIENT) - .setStatus(StatusData.error()) - .setTotalAttributeCount(2) - .build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - buildZipkinSpan(Span.Kind.CLIENT).toBuilder() - .clearTags() - .putTag(SemanticAttributes.HTTP_STATUS_CODE.getKey(), "404") - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "ERROR") - .putTag("error", "A user provided error") - .build()); - } - - @Test - void generateSpan_WithRpcTimeoutErrorStatus_WithTimeoutErrorDescription() { - Attributes attributeMap = Attributes.of(SemanticAttributes.RPC_SERVICE, "my service name"); - - String errorMessage = "timeout"; - - SpanData data = - buildStandardSpan() - .setStatus(StatusData.create(StatusCode.ERROR, errorMessage)) - .setAttributes(attributeMap) - .setTotalAttributeCount(1) - .build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - buildZipkinSpan(Span.Kind.SERVER).toBuilder() - .putTag(SemanticAttributes.RPC_SERVICE.getKey(), "my service name") - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "ERROR") - .putTag(ZipkinSpanExporter.STATUS_ERROR.getKey(), errorMessage) - .build()); - } - - @Test - void generateSpan_WithRpcErrorStatus_WithEmptyErrorDescription() { - Attributes attributeMap = Attributes.of(SemanticAttributes.RPC_SERVICE, "my service name"); - - SpanData data = - buildStandardSpan() - .setStatus(StatusData.create(StatusCode.ERROR, "")) - .setAttributes(attributeMap) - .setTotalAttributeCount(1) - .build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - buildZipkinSpan(Span.Kind.SERVER).toBuilder() - .putTag(SemanticAttributes.RPC_SERVICE.getKey(), "my service name") - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "ERROR") - .putTag(ZipkinSpanExporter.STATUS_ERROR.getKey(), "") - .build()); - } - - @Test - void generateSpan_WithRpcUnsetStatus() { - Attributes attributeMap = Attributes.of(SemanticAttributes.RPC_SERVICE, "my service name"); - - SpanData data = - buildStandardSpan() - .setStatus(StatusData.create(StatusCode.UNSET, "")) - .setAttributes(attributeMap) - .setTotalAttributeCount(1) - .build(); - - assertThat(exporter.generateSpan(data)) - .isEqualTo( - buildZipkinSpan(Span.Kind.SERVER).toBuilder() - .putTag(SemanticAttributes.RPC_SERVICE.getKey(), "my service name") - .build()); - } - - @Test - void testExport() { - ZipkinSpanExporter zipkinSpanExporter = new ZipkinSpanExporter(mockEncoder, mockSender); - - byte[] someBytes = new byte[0]; - when(mockEncoder.encode( - standardZipkinSpanBuilder(Span.Kind.SERVER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build())) - .thenReturn(someBytes); - when(mockSender.sendSpans(Collections.singletonList(someBytes))).thenReturn(mockZipkinCall); - doAnswer( - invocation -> { - Callback callback = invocation.getArgument(0); - callback.onSuccess(null); - return null; - }) - .when(mockZipkinCall) - .enqueue(any()); - - CompletableResultCode resultCode = - zipkinSpanExporter.export(Collections.singleton(buildStandardSpan().build())); - - assertThat(resultCode.isSuccess()).isTrue(); - } - - @Test - @SuppressLogger(ZipkinSpanExporter.class) - void testExport_failed() { - ZipkinSpanExporter zipkinSpanExporter = new ZipkinSpanExporter(mockEncoder, mockSender); - - byte[] someBytes = new byte[0]; - when(mockEncoder.encode( - standardZipkinSpanBuilder(Span.Kind.SERVER) - .putTag(ZipkinSpanExporter.OTEL_STATUS_CODE, "OK") - .build())) - .thenReturn(someBytes); - when(mockSender.sendSpans(Collections.singletonList(someBytes))).thenReturn(mockZipkinCall); - doAnswer( - invocation -> { - Callback callback = invocation.getArgument(0); - callback.onError(new IOException()); - return null; - }) - .when(mockZipkinCall) - .enqueue(any()); - - CompletableResultCode resultCode = - zipkinSpanExporter.export(Collections.singleton(buildStandardSpan().build())); - - assertThat(resultCode.isSuccess()).isFalse(); - } - - @Test - void testCreate() { - ZipkinSpanExporter exporter = ZipkinSpanExporter.builder().setSender(mockSender).build(); - - assertThat(exporter).isNotNull(); - } - - @Test - void testShutdown() throws IOException { - ZipkinSpanExporter exporter = ZipkinSpanExporter.builder().setSender(mockSender).build(); - - exporter.shutdown(); - verify(mockSender).close(); - } - - private static TestSpanData.Builder buildStandardSpan() { - return TestSpanData.builder() - .setSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())) - .setParentSpanContext( - SpanContext.create( - TRACE_ID, PARENT_SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setResource( - Resource.create( - Attributes.builder().put(ResourceAttributes.SERVICE_NAME, "tweetiebird").build())) - .setStatus(StatusData.ok()) - .setKind(SpanKind.SERVER) - .setName("Recv.helloworld.Greeter.SayHello") - .setStartEpochNanos(1505855794_194009601L) - .setEndEpochNanos(1505855799_465726528L) - .setAttributes(attributes) - .setTotalAttributeCount(attributes.size()) - .setTotalRecordedEvents(annotations.size()) - .setEvents(annotations) - .setLinks(Collections.emptyList()) - .setHasEnded(true); - } - - private Span buildZipkinSpan(Span.Kind kind) { - return standardZipkinSpanBuilder(kind).build(); - } - - private Span.Builder standardZipkinSpanBuilder(Span.Kind kind) { - return Span.newBuilder() - .traceId(TRACE_ID) - .parentId(PARENT_SPAN_ID) - .id(SPAN_ID) - .kind(kind) - .name("Recv.helloworld.Greeter.SayHello") - .timestamp(1505855794000000L + 194009601L / 1000) - .duration((1505855799000000L + 465726528L / 1000) - (1505855794000000L + 194009601L / 1000)) - .localEndpoint( - Endpoint.newBuilder() - .ip(exporter.getLocalAddressForTest()) - .serviceName("tweetiebird") - .build()) - .addAnnotation(1505855799000000L + 433901068L / 1000, "RECEIVED") - .addAnnotation(1505855799000000L + 459486280L / 1000, "SENT"); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void invalidConfig() { - assertThatThrownBy(() -> ZipkinSpanExporter.builder().setReadTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - - assertThatThrownBy(() -> ZipkinSpanExporter.builder().setReadTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - - assertThatThrownBy(() -> ZipkinSpanExporter.builder().setReadTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> ZipkinSpanExporter.builder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - - assertThatThrownBy(() -> ZipkinSpanExporter.builder().setSender(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("sender"); - - assertThatThrownBy(() -> ZipkinSpanExporter.builder().setEncoder(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("encoder"); - } -} diff --git a/extensions/annotations/README.md b/extensions/annotations/README.md deleted file mode 100644 index 4750a1ee2ea..00000000000 --- a/extensions/annotations/README.md +++ /dev/null @@ -1,10 +0,0 @@ -OpenTelemetry Extension Annotations -====================================================== - -[![Javadocs][javadoc-image]][javadoc-url] - -This module contains various annotations that can be used by clients of OpenTelemetry API. -Please see [Javadocs][javadoc-url] for more information. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-annotations.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-annotations diff --git a/extensions/annotations/build.gradle.kts b/extensions/annotations/build.gradle.kts deleted file mode 100644 index b76a10bab79..00000000000 --- a/extensions/annotations/build.gradle.kts +++ /dev/null @@ -1,13 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Extension Annotations" -otelJava.moduleName.set("io.opentelemetry.extension.annotations") - -dependencies { - api(project(":api:all")) -} diff --git a/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/SpanAttribute.java b/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/SpanAttribute.java deleted file mode 100644 index 3934e381518..00000000000 --- a/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/SpanAttribute.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.annotations; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * This annotation marks that a parameter of a method annotated by the {@link WithSpan} annotation - * should be added as an attribute to the newly created {@link io.opentelemetry.api.trace.Span}. - * Using this annotation is equivalent to calling {@code Span.currentSpan().setAttribute(...)} - * within the body of the method. - * - *

    Application developers can use this annotation to signal OpenTelemetry auto-instrumentation - * that a new span attribute should be added to a span created when the parent method is executed. - * - *

    If you are a library developer, then probably you should NOT use this annotation, because it - * is non-functional without the OpenTelemetry auto-instrumentation agent, or some other annotation - * processor. - * - * @see OpenTelemetry - * OpenTelemetry Instrumentation for Java - * @since 1.4.0 - */ -@Target(ElementType.PARAMETER) -@Retention(RetentionPolicy.RUNTIME) -public @interface SpanAttribute { - /** - * Optional name of the attribute. - * - *

    If not specified and the code is compiled using the `{@code -parameters}` argument to - * `javac`, the parameter name will be used instead. If the parameter name is not available, e.g., - * because the code was not compiled with that flag, the attribute will be ignored. - */ - String value() default ""; -} diff --git a/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/WithSpan.java b/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/WithSpan.java deleted file mode 100644 index 2ba6e4e2d72..00000000000 --- a/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/WithSpan.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.annotations; - -import io.opentelemetry.api.trace.SpanKind; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * This annotation marks that an execution of this method or constructor should result in a new - * {@link io.opentelemetry.api.trace.Span}. - * - *

    Application developers can use this annotation to signal OpenTelemetry auto-instrumentation - * that a new span should be created whenever marked method is executed. - * - *

    If you are a library developer, then probably you should NOT use this annotation, because it - * is non-functional without the OpenTelemetry auto-instrumentation agent, or some other annotation - * processor. - * - * @see OpenTelemetry - * OpenTelemetry Instrumentation for Java - */ -@Target({ElementType.METHOD, ElementType.CONSTRUCTOR}) -@Retention(RetentionPolicy.RUNTIME) -public @interface WithSpan { - /** - * Optional name of the created span. - * - *

    If not specified, an appropriate default name should be created by auto-instrumentation. - * E.g. {@code "className"."method"} - */ - String value() default ""; - - /** Specify the {@link SpanKind} of span to be created. Defaults to {@link SpanKind#INTERNAL}. */ - SpanKind kind() default SpanKind.INTERNAL; -} diff --git a/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/package-info.java b/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/package-info.java deleted file mode 100644 index e0bc97a1965..00000000000 --- a/extensions/annotations/src/main/java/io/opentelemetry/extension/annotations/package-info.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * This module contains various annotations that can be used by clients of OpenTelemetry API. They - * don't provide any functionality by themselves, but other modules, e.g. OpenTelemetry - * Auto-Instrumentation can use them to enhance their functionality. - * - *

    Note: If you are a library developer, then you should NOT use this module, because it is - * useless without some kind of annotation processing, such as bytecode manipulation during runtime. - * You cannot guarantee that users of your library will use that in their production system. - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.extension.annotations; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/extensions/annotations/src/test/java/io/opentelemetry/extension/annotations/WithSpanUsageExamples.java b/extensions/annotations/src/test/java/io/opentelemetry/extension/annotations/WithSpanUsageExamples.java deleted file mode 100644 index 617c3133ef8..00000000000 --- a/extensions/annotations/src/test/java/io/opentelemetry/extension/annotations/WithSpanUsageExamples.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.annotations; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanKind; - -/** - * This class is not a classical test. It's just a demonstration of possible usages of {@link - * WithSpan} annotation together with some explanations. The goal of this class is to serve as an - * early detection system for inconvenient API and unintended API breakage. - */ -@SuppressWarnings("unused") -public class WithSpanUsageExamples { - - /** - * A new {@link Span} will be created for this method's execution. The span's name will be - * automatically generated by OpenTelemetry auto-instrumentation, probably as - * "WithSpanUsageExamples.method1". - */ - @WithSpan - public void method1() {} - - /** Name of the generated span will be "shinyName". */ - @WithSpan("shinyName") - public void method2() {} - - /** - * A {@link Span} with the default name, and a {@link SpanKind} of {@link SpanKind#CONSUMER} will - * be created for this method. - */ - @WithSpan(kind = SpanKind.CONSUMER) - public void consume() {} - - /** - * A {@link Span} with the default name and kind and with default span attributes. - * - * @param attribute1 A span attribute with the default name of {@code attribute1}. - * @param value A span attribute with the name "attribute2". - */ - @WithSpan - public void attributes( - @SpanAttribute String attribute1, @SpanAttribute("attribute2") long value) {} -} diff --git a/extensions/aws/README.md b/extensions/aws/README.md deleted file mode 100644 index 00dea946cdf..00000000000 --- a/extensions/aws/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Extension AWS - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-aws.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-aws diff --git a/extensions/aws/build.gradle.kts b/extensions/aws/build.gradle.kts deleted file mode 100644 index 24209c37509..00000000000 --- a/extensions/aws/build.gradle.kts +++ /dev/null @@ -1,14 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry API Extensions for AWS" -otelJava.moduleName.set("io.opentelemetry.extension.aws") - -dependencies { - api(project(":api:all")) - compileOnly(project(":sdk-extensions:autoconfigure")) -} diff --git a/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsConfigurablePropagator.java b/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsConfigurablePropagator.java deleted file mode 100644 index 18d4ef77d9a..00000000000 --- a/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsConfigurablePropagator.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.aws; - -import io.opentelemetry.context.propagation.TextMapPropagator; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider; - -/** - * A {@link ConfigurablePropagatorProvider} which allows enabling the {@link AwsXrayPropagator} with - * the propagator name {@code xray}. - */ -public final class AwsConfigurablePropagator implements ConfigurablePropagatorProvider { - @Override - public TextMapPropagator getPropagator(ConfigProperties config) { - return AwsXrayPropagator.getInstance(); - } - - @Override - public String getName() { - return "xray"; - } -} diff --git a/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsXrayPropagator.java b/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsXrayPropagator.java deleted file mode 100644 index f342d035a15..00000000000 --- a/extensions/aws/src/main/java/io/opentelemetry/extension/aws/AwsXrayPropagator.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.aws; - -import io.opentelemetry.api.baggage.Baggage; -import io.opentelemetry.api.baggage.BaggageBuilder; -import io.opentelemetry.api.baggage.BaggageEntry; -import io.opentelemetry.api.internal.StringUtils; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.propagation.TextMapGetter; -import io.opentelemetry.context.propagation.TextMapPropagator; -import io.opentelemetry.context.propagation.TextMapSetter; -import java.util.Collection; -import java.util.Collections; -import java.util.function.BiConsumer; -import java.util.logging.Logger; -import javax.annotation.Nullable; - -/** - * Implementation of the AWS X-Ray Trace Header propagation protocol. See AWS - * Tracing header spec - * - *

    To register the X-Ray propagator together with default propagator when using the SDK: - * - *

    {@code
    - * OpenTelemetrySdk.builder()
    - *   .setPropagators(
    - *     ContextPropagators.create(
    - *         TextMapPropagator.composite(
    - *             W3CTraceContextPropagator.getInstance(),
    - *             AWSXrayPropagator.getInstance())))
    - *    .build();
    - * }
    - */ -public final class AwsXrayPropagator implements TextMapPropagator { - - // Visible for testing - static final String TRACE_HEADER_KEY = "X-Amzn-Trace-Id"; - - private static final Logger logger = Logger.getLogger(AwsXrayPropagator.class.getName()); - - private static final char TRACE_HEADER_DELIMITER = ';'; - private static final char KV_DELIMITER = '='; - - private static final String TRACE_ID_KEY = "Root"; - private static final int TRACE_ID_LENGTH = 35; - private static final String TRACE_ID_VERSION = "1"; - private static final char TRACE_ID_DELIMITER = '-'; - private static final int TRACE_ID_DELIMITER_INDEX_1 = 1; - private static final int TRACE_ID_DELIMITER_INDEX_2 = 10; - private static final int TRACE_ID_FIRST_PART_LENGTH = 8; - - private static final String PARENT_ID_KEY = "Parent"; - private static final int PARENT_ID_LENGTH = 16; - - private static final String SAMPLED_FLAG_KEY = "Sampled"; - private static final int SAMPLED_FLAG_LENGTH = 1; - private static final char IS_SAMPLED = '1'; - private static final char NOT_SAMPLED = '0'; - - private static final Collection FIELDS = Collections.singletonList(TRACE_HEADER_KEY); - - private static final AwsXrayPropagator INSTANCE = new AwsXrayPropagator(); - - private AwsXrayPropagator() { - // singleton - } - - public static AwsXrayPropagator getInstance() { - return INSTANCE; - } - - @Override - public Collection fields() { - return FIELDS; - } - - @Override - public void inject(Context context, @Nullable C carrier, TextMapSetter setter) { - if (context == null) { - return; - } - if (setter == null) { - return; - } - - Span span = Span.fromContext(context); - if (!span.getSpanContext().isValid()) { - return; - } - - SpanContext spanContext = span.getSpanContext(); - - String otTraceId = spanContext.getTraceId(); - String xrayTraceId = - TRACE_ID_VERSION - + TRACE_ID_DELIMITER - + otTraceId.substring(0, TRACE_ID_FIRST_PART_LENGTH) - + TRACE_ID_DELIMITER - + otTraceId.substring(TRACE_ID_FIRST_PART_LENGTH); - String parentId = spanContext.getSpanId(); - char samplingFlag = spanContext.isSampled() ? IS_SAMPLED : NOT_SAMPLED; - // TODO: Add OT trace state to the X-Ray trace header - - StringBuilder traceHeader = new StringBuilder(); - traceHeader - .append(TRACE_ID_KEY) - .append(KV_DELIMITER) - .append(xrayTraceId) - .append(TRACE_HEADER_DELIMITER) - .append(PARENT_ID_KEY) - .append(KV_DELIMITER) - .append(parentId) - .append(TRACE_HEADER_DELIMITER) - .append(SAMPLED_FLAG_KEY) - .append(KV_DELIMITER) - .append(samplingFlag); - - Baggage baggage = Baggage.fromContext(context); - // Truncate baggage to 256 chars per X-Ray spec. - baggage.forEach( - new BiConsumer() { - - private int baggageWrittenBytes; - - @Override - public void accept(String key, BaggageEntry entry) { - if (key.equals(TRACE_ID_KEY) - || key.equals(PARENT_ID_KEY) - || key.equals(SAMPLED_FLAG_KEY)) { - return; - } - // Size is key/value pair, excludes delimiter. - int size = key.length() + entry.getValue().length() + 1; - if (baggageWrittenBytes + size > 256) { - return; - } - traceHeader - .append(TRACE_HEADER_DELIMITER) - .append(key) - .append(KV_DELIMITER) - .append(entry.getValue()); - baggageWrittenBytes += size; - } - }); - - setter.set(carrier, TRACE_HEADER_KEY, traceHeader.toString()); - } - - @Override - public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { - if (context == null) { - return Context.root(); - } - if (getter == null) { - return context; - } - - return getContextFromHeader(context, carrier, getter); - } - - private static Context getContextFromHeader( - Context context, @Nullable C carrier, TextMapGetter getter) { - String traceHeader = getter.get(carrier, TRACE_HEADER_KEY); - if (traceHeader == null || traceHeader.isEmpty()) { - return context; - } - - String traceId = TraceId.getInvalid(); - String spanId = SpanId.getInvalid(); - Boolean isSampled = false; - - BaggageBuilder baggage = null; - int baggageReadBytes = 0; - - int pos = 0; - while (pos < traceHeader.length()) { - int delimiterIndex = traceHeader.indexOf(TRACE_HEADER_DELIMITER, pos); - String part; - if (delimiterIndex >= 0) { - part = traceHeader.substring(pos, delimiterIndex); - pos = delimiterIndex + 1; - } else { - // Last part. - part = traceHeader.substring(pos); - pos = traceHeader.length(); - } - String trimmedPart = part.trim(); - int equalsIndex = trimmedPart.indexOf(KV_DELIMITER); - if (equalsIndex < 0) { - logger.fine("Error parsing X-Ray trace header. Invalid key value pair: " + part); - return context; - } - - String value = trimmedPart.substring(equalsIndex + 1); - - if (trimmedPart.startsWith(TRACE_ID_KEY)) { - traceId = parseTraceId(value); - } else if (trimmedPart.startsWith(PARENT_ID_KEY)) { - spanId = parseSpanId(value); - } else if (trimmedPart.startsWith(SAMPLED_FLAG_KEY)) { - isSampled = parseTraceFlag(value); - } else if (baggageReadBytes + trimmedPart.length() <= 256) { - if (baggage == null) { - baggage = Baggage.builder(); - } - baggage.put(trimmedPart.substring(0, equalsIndex), value); - baggageReadBytes += trimmedPart.length(); - } - } - if (isSampled == null) { - logger.fine( - "Invalid Sampling flag in X-Ray trace header: '" - + TRACE_HEADER_KEY - + "' with value " - + traceHeader - + "'."); - return context; - } - - if (spanId == null || traceId == null) { - logger.finest("Both traceId and spanId are required to extract a valid span context. "); - } - - SpanContext spanContext = - SpanContext.createFromRemoteParent( - StringUtils.padLeft(traceId, TraceId.getLength()), - spanId, - isSampled ? TraceFlags.getSampled() : TraceFlags.getDefault(), - TraceState.getDefault()); - if (spanContext.isValid()) { - context = context.with(Span.wrap(spanContext)); - } - if (baggage != null) { - context = context.with(baggage.build()); - } - return context; - } - - private static String parseTraceId(String xrayTraceId) { - return (xrayTraceId.length() == TRACE_ID_LENGTH - ? parseSpecTraceId(xrayTraceId) - : parseShortTraceId(xrayTraceId)); - } - - private static String parseSpecTraceId(String xrayTraceId) { - - // Check version trace id version - if (!xrayTraceId.startsWith(TRACE_ID_VERSION)) { - return TraceId.getInvalid(); - } - - // Check delimiters - if (xrayTraceId.charAt(TRACE_ID_DELIMITER_INDEX_1) != TRACE_ID_DELIMITER - || xrayTraceId.charAt(TRACE_ID_DELIMITER_INDEX_2) != TRACE_ID_DELIMITER) { - return TraceId.getInvalid(); - } - - String epochPart = - xrayTraceId.substring(TRACE_ID_DELIMITER_INDEX_1 + 1, TRACE_ID_DELIMITER_INDEX_2); - String uniquePart = xrayTraceId.substring(TRACE_ID_DELIMITER_INDEX_2 + 1, TRACE_ID_LENGTH); - - // X-Ray trace id format is 1-{8 digit hex}-{24 digit hex} - return epochPart + uniquePart; - } - - private static String parseShortTraceId(String xrayTraceId) { - if (xrayTraceId.length() > TRACE_ID_LENGTH) { - return TraceId.getInvalid(); - } - - // Check version trace id version - if (!xrayTraceId.startsWith(TRACE_ID_VERSION)) { - return TraceId.getInvalid(); - } - - // Check delimiters - int firstDelimiter = xrayTraceId.indexOf(TRACE_ID_DELIMITER); - // we don't allow the epoch part to be missing completely - int secondDelimiter = xrayTraceId.indexOf(TRACE_ID_DELIMITER, firstDelimiter + 2); - if (firstDelimiter != TRACE_ID_DELIMITER_INDEX_1 - || secondDelimiter == -1 - || secondDelimiter > TRACE_ID_DELIMITER_INDEX_2) { - return TraceId.getInvalid(); - } - - String epochPart = xrayTraceId.substring(firstDelimiter + 1, secondDelimiter); - String uniquePart = xrayTraceId.substring(secondDelimiter + 1, secondDelimiter + 25); - - // X-Ray trace id format is 1-{at most 8 digit hex}-{24 digit hex} - // epoch part can have leading 0s truncated - return epochPart + uniquePart; - } - - private static String parseSpanId(String xrayParentId) { - if (xrayParentId.length() != PARENT_ID_LENGTH) { - return SpanId.getInvalid(); - } - - return xrayParentId; - } - - @Nullable - private static Boolean parseTraceFlag(String xraySampledFlag) { - if (xraySampledFlag.length() != SAMPLED_FLAG_LENGTH) { - // Returning null as there is no invalid trace flag defined. - return null; - } - - char flag = xraySampledFlag.charAt(0); - if (flag == IS_SAMPLED) { - return true; - } else if (flag == NOT_SAMPLED) { - return false; - } else { - return null; - } - } -} diff --git a/extensions/aws/src/main/java/io/opentelemetry/extension/aws/package-info.java b/extensions/aws/src/main/java/io/opentelemetry/extension/aws/package-info.java deleted file mode 100644 index f70fc7eac53..00000000000 --- a/extensions/aws/src/main/java/io/opentelemetry/extension/aws/package-info.java +++ /dev/null @@ -1,5 +0,0 @@ -/** OpenTelemetry API extensions for use with AWS. */ -@ParametersAreNonnullByDefault -package io.opentelemetry.extension.aws; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider b/extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider deleted file mode 100644 index 838deff6656..00000000000 --- a/extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider +++ /dev/null @@ -1 +0,0 @@ -io.opentelemetry.extension.aws.AwsConfigurablePropagator diff --git a/extensions/aws/src/test/java/io/opentelemetry/extension/aws/AwsXrayPropagatorTest.java b/extensions/aws/src/test/java/io/opentelemetry/extension/aws/AwsXrayPropagatorTest.java deleted file mode 100644 index c1f9637690e..00000000000 --- a/extensions/aws/src/test/java/io/opentelemetry/extension/aws/AwsXrayPropagatorTest.java +++ /dev/null @@ -1,476 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.aws; - -import static io.opentelemetry.extension.aws.AwsXrayPropagator.TRACE_HEADER_KEY; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.baggage.Baggage; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.propagation.TextMapGetter; -import io.opentelemetry.context.propagation.TextMapSetter; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.junit.jupiter.api.Test; - -class AwsXrayPropagatorTest { - - private static final String TRACE_ID = "8a3c60f7d188f8fa79d48a391a778fa6"; - private static final String SPAN_ID = "53995c3f42cd8ad8"; - - private static final TextMapSetter> setter = Map::put; - private static final TextMapGetter> getter = - new TextMapGetter>() { - @Override - public Iterable keys(Map carrier) { - return carrier.keySet(); - } - - @Nullable - @Override - public String get(Map carrier, String key) { - return carrier.get(key); - } - }; - private final AwsXrayPropagator xrayPropagator = AwsXrayPropagator.getInstance(); - - @Test - void inject_SampledContext() { - Map carrier = new LinkedHashMap<>(); - xrayPropagator.inject( - withSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()), - Context.current()), - carrier, - setter); - - assertThat(carrier) - .containsEntry( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1"); - } - - @Test - void inject_NotSampledContext() { - Map carrier = new LinkedHashMap<>(); - xrayPropagator.inject( - withSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()), - Context.current()), - carrier, - setter); - - assertThat(carrier) - .containsEntry( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"); - } - - @Test - void inject_WithBaggage() { - Map carrier = new LinkedHashMap<>(); - xrayPropagator.inject( - withSpanContext( - SpanContext.create( - TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()), - Context.current()) - .with( - Baggage.builder() - .put("cat", "meow") - .put("dog", "bark") - .put("Root", "ignored") - .put("Parent", "ignored") - .put("Sampled", "ignored") - .build()), - carrier, - setter); - - assertThat(carrier) - .containsEntry( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0;" - + "cat=meow;dog=bark"); - } - - @Test - void inject_WithBaggage_LimitTruncates() { - Map carrier = new LinkedHashMap<>(); - // Limit is 256 characters for all baggage. We add a 254-character key/value pair and a - // 3 character key value pair. - String key1 = Stream.generate(() -> "a").limit(252).collect(Collectors.joining()); - String value1 = "a"; // 252 + 1 (=) + 1 = 254 - - String key2 = "b"; - String value2 = "b"; // 1 + 1 (=) + 1 = 3 - - Baggage baggage = Baggage.builder().put(key1, value1).put(key2, value2).build(); - - xrayPropagator.inject( - withSpanContext( - SpanContext.create( - TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()), - Context.current()) - .with(baggage), - carrier, - setter); - - assertThat(carrier) - .containsEntry( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0;" - + key1 - + '=' - + value1); - } - - @Test - void inject_WithTraceState() { - Map carrier = new LinkedHashMap<>(); - xrayPropagator.inject( - withSpanContext( - SpanContext.create( - TRACE_ID, - SPAN_ID, - TraceFlags.getDefault(), - TraceState.builder().put("foo", "bar").build()), - Context.current()), - carrier, - setter); - - // TODO: assert trace state when the propagator supports it, for general key/value pairs we are - // mapping with baggage. - assertThat(carrier) - .containsEntry( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"); - } - - @Test - void inject_nullContext() { - Map carrier = new LinkedHashMap<>(); - xrayPropagator.inject(null, carrier, setter); - assertThat(carrier).isEmpty(); - } - - @Test - void inject_nullSetter() { - Map carrier = new LinkedHashMap<>(); - Context context = - withSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()), - Context.current()); - xrayPropagator.inject(context, carrier, null); - assertThat(carrier).isEmpty(); - } - - @Test - void extract_Nothing() { - // Context remains untouched. - assertThat( - xrayPropagator.extract( - Context.current(), Collections.emptyMap(), getter)) - .isSameAs(Context.current()); - } - - @Test - void extract_SampledContext() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isEqualTo( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - } - - @Test - void extract_NotSampledContext() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isEqualTo( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())); - } - - @Test - void extract_DifferentPartOrder() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Parent=53995c3f42cd8ad8;Sampled=1;Root=1-8a3c60f7-d188f8fa79d48a391a778fa6"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isEqualTo( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - } - - @Test - void extract_AdditionalFields() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1;Foo=Bar"); - - Context context = xrayPropagator.extract(Context.current(), carrier, getter); - assertThat(getSpanContext(context)) - .isEqualTo( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - assertThat(Baggage.fromContext(context).getEntryValue("Foo")).isEqualTo("Bar"); - } - - @Test - void extract_Baggage_LimitTruncates() { - // Limit is 256 characters for all baggage. We add a 254-character key/value pair and a - // 3 character key value pair. - String key1 = Stream.generate(() -> "a").limit(252).collect(Collectors.joining()); - String value1 = "a"; // 252 + 1 (=) + 1 = 254 - - String key2 = "b"; - String value2 = "b"; // 1 + 1 (=) + 1 = 3 - - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1;" - + key1 - + '=' - + value1 - + ';' - + key2 - + '=' - + value2); - - Context context = xrayPropagator.extract(Context.current(), carrier, getter); - assertThat(getSpanContext(context)) - .isEqualTo( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - assertThat(Baggage.fromContext(context).getEntryValue(key1)).isEqualTo(value1); - assertThat(Baggage.fromContext(context).getEntryValue(key2)).isNull(); - } - - @Test - void extract_EmptyHeaderValue() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put(TRACE_HEADER_KEY, ""); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidTraceId() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=abcdefghijklmnopabcdefghijklmnop;Parent=53995c3f42cd8ad8;Sampled=0"); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidTraceId_Size() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa600;Parent=53995c3f42cd8ad8;Sampled=0"); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidSpanId() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=abcdefghijklmnop;Sampled=0"); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidSpanId_Size() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad800;Sampled=0"); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidFlags() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled="); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidFlags_Size() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=10220"); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_InvalidFlags_NonNumeric() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=a"); - - verifyInvalidBehavior(invalidHeaders); - } - - @Test - void extract_Invalid_NoSpanId() { - Map invalidHeaders = new LinkedHashMap<>(1); - invalidHeaders.put(TRACE_HEADER_KEY, "Root=1-622422bf-59625fe25708d4660735d8ef"); - - verifyInvalidBehavior(invalidHeaders); - } - - private void verifyInvalidBehavior(Map invalidHeaders) { - Context input = Context.current(); - Context result = xrayPropagator.extract(input, invalidHeaders, getter); - assertThat(result).isSameAs(input); - assertThat(getSpanContext(result)).isSameAs(SpanContext.getInvalid()); - } - - @Test - void extract_nullContext() { - assertThat(xrayPropagator.extract(null, Collections.emptyMap(), getter)) - .isSameAs(Context.root()); - } - - @Test - void extract_nullGetter() { - Context context = - withSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()), - Context.current()); - assertThat(xrayPropagator.extract(context, Collections.emptyMap(), null)).isSameAs(context); - } - - @Test - void extract_EpochPart_ZeroedSingleDigit() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-0-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1;Foo=Bar"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isEqualTo( - SpanContext.createFromRemoteParent( - "00000000d188f8fa79d48a391a778fa6", - SPAN_ID, - TraceFlags.getSampled(), - TraceState.getDefault())); - } - - @Test - void extract_EpochPart_TwoChars() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-1a-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1;Foo=Bar"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isEqualTo( - SpanContext.createFromRemoteParent( - "0000001ad188f8fa79d48a391a778fa6", - SPAN_ID, - TraceFlags.getSampled(), - TraceState.getDefault())); - } - - @Test - void extract_EpochPart_Zeroed() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=1-00000000-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1;Foo=Bar"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isEqualTo( - SpanContext.createFromRemoteParent( - "00000000d188f8fa79d48a391a778fa6", - SPAN_ID, - TraceFlags.getSampled(), - TraceState.getDefault())); - } - - @Test - void extract_InvalidTraceId_EpochPart_TooLong() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, - "Root=1-8a3c60f711-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), invalidHeaders, getter))) - .isSameAs(SpanContext.getInvalid()); - } - - @Test - void extract_InvalidTraceId_EpochPart_Empty() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, "Root=1--d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), invalidHeaders, getter))) - .isSameAs(SpanContext.getInvalid()); - } - - @Test - void extract_InvalidTraceId_EpochPart_Missing() { - Map invalidHeaders = new LinkedHashMap<>(); - invalidHeaders.put( - TRACE_HEADER_KEY, "Root=1-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), invalidHeaders, getter))) - .isSameAs(SpanContext.getInvalid()); - } - - @Test - void extract_InvalidTraceId_WrongVersion() { - Map carrier = new LinkedHashMap<>(); - carrier.put( - TRACE_HEADER_KEY, - "Root=2-1a2a3a4a-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1;Foo=Bar"); - - assertThat(getSpanContext(xrayPropagator.extract(Context.current(), carrier, getter))) - .isSameAs(SpanContext.getInvalid()); - } - - private static Context withSpanContext(SpanContext spanContext, Context context) { - return context.with(Span.wrap(spanContext)); - } - - private static SpanContext getSpanContext(Context context) { - return Span.fromContext(context).getSpanContext(); - } -} diff --git a/extensions/build.gradle.kts b/extensions/build.gradle.kts index 82930834d2e..f0744dfe9ef 100644 --- a/extensions/build.gradle.kts +++ b/extensions/build.gradle.kts @@ -1,4 +1,6 @@ subprojects { + // Workaround https://github.com/gradle/gradle/issues/847 + group = "io.opentelemetry.extensions" val proj = this plugins.withId("java") { configure { diff --git a/extensions/incubator/README.md b/extensions/incubator/README.md deleted file mode 100644 index aaeec552def..00000000000 --- a/extensions/incubator/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Extension Incubator - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-incubator.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-incubator diff --git a/extensions/incubator/build.gradle.kts b/extensions/incubator/build.gradle.kts deleted file mode 100644 index 6acaf6cddb2..00000000000 --- a/extensions/incubator/build.gradle.kts +++ /dev/null @@ -1,16 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.jmh-conventions") - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry API Incubator" -otelJava.moduleName.set("io.opentelemetry.extension.incubator") - -dependencies { - api(project(":api:all")) - - testImplementation(project(":sdk:testing")) -} diff --git a/extensions/incubator/src/main/java/io/opentelemetry/extension/incubator/trace/ExtendedTracer.java b/extensions/incubator/src/main/java/io/opentelemetry/extension/incubator/trace/ExtendedTracer.java deleted file mode 100644 index 1be6bc899fa..00000000000 --- a/extensions/incubator/src/main/java/io/opentelemetry/extension/incubator/trace/ExtendedTracer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.incubator.trace; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanBuilder; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.context.Scope; -import java.util.concurrent.Callable; - -/** Provides easy mechanisms for wrapping standard Java constructs with an OpenTelemetry Span. */ -public final class ExtendedTracer implements Tracer { - - private final Tracer delegate; - - /** Create a new {@link ExtendedTracer} that wraps the provided Tracer. */ - public static ExtendedTracer create(Tracer delegate) { - return new ExtendedTracer(delegate); - } - - private ExtendedTracer(Tracer delegate) { - this.delegate = delegate; - } - - /** Run the provided {@link Runnable} and wrap with a {@link Span} with the provided name. */ - public void run(String spanName, Runnable runnable) { - Span span = delegate.spanBuilder(spanName).startSpan(); - try (Scope scope = span.makeCurrent()) { - runnable.run(); - } catch (Throwable e) { - span.recordException(e); - throw e; - } finally { - span.end(); - } - } - - /** Call the provided {@link Callable} and wrap with a {@link Span} with the provided name. */ - public T call(String spanName, Callable callable) throws Exception { - Span span = delegate.spanBuilder(spanName).startSpan(); - try (Scope scope = span.makeCurrent()) { - return callable.call(); - } catch (Throwable e) { - span.recordException(e); - throw e; - } finally { - span.end(); - } - } - - @Override - public SpanBuilder spanBuilder(String spanName) { - return delegate.spanBuilder(spanName); - } -} diff --git a/extensions/incubator/src/test/java/io/opentelemetry/extension/incubator/trace/ExtendedTracerTest.java b/extensions/incubator/src/test/java/io/opentelemetry/extension/incubator/trace/ExtendedTracerTest.java deleted file mode 100644 index 537fb8aa447..00000000000 --- a/extensions/incubator/src/test/java/io/opentelemetry/extension/incubator/trace/ExtendedTracerTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.incubator.trace; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class ExtendedTracerTest { - @RegisterExtension - static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); - - private final Tracer tracer = otelTesting.getOpenTelemetry().getTracer("test"); - - @Test - void runRunnable() { - ExtendedTracer.create(tracer).run("testSpan", () -> Span.current().setAttribute("one", 1)); - - otelTesting - .assertTraces() - .hasTracesSatisfyingExactly( - traceAssert -> - traceAssert.hasSpansSatisfyingExactly( - spanDataAssert -> - spanDataAssert - .hasName("testSpan") - .hasAttributes(Attributes.of(AttributeKey.longKey("one"), 1L)))); - } - - @Test - void runRunnable_throws() { - assertThatThrownBy( - () -> - ExtendedTracer.create(tracer) - .run( - "throwingRunnable", - () -> { - Span.current().setAttribute("one", 1); - throw new RuntimeException("failed"); - })) - .isInstanceOf(RuntimeException.class); - - otelTesting - .assertTraces() - .hasTracesSatisfyingExactly( - traceAssert -> - traceAssert.hasSpansSatisfyingExactly( - span -> - span.hasName("throwingRunnable") - .hasAttributes(Attributes.of(AttributeKey.longKey("one"), 1L)) - .hasEventsSatisfying( - (events) -> - assertThat(events) - .singleElement() - .satisfies( - eventData -> - assertThat(eventData.getName()) - .isEqualTo("exception"))))); - } - - @Test - void callCallable() throws Exception { - assertThat( - ExtendedTracer.create(tracer) - .call( - "spanCallable", - () -> { - Span.current().setAttribute("one", 1); - return "hello"; - })) - .isEqualTo("hello"); - - otelTesting - .assertTraces() - .hasTracesSatisfyingExactly( - traceAssert -> - traceAssert.hasSpansSatisfyingExactly( - spanDataAssert -> - spanDataAssert - .hasName("spanCallable") - .hasAttributes(Attributes.of(AttributeKey.longKey("one"), 1L)))); - } - - @Test - void callCallable_throws() { - assertThatThrownBy( - () -> - ExtendedTracer.create(tracer) - .call( - "throwingCallable", - () -> { - Span.current().setAttribute("one", 1); - throw new RuntimeException("failed"); - })) - .isInstanceOf(RuntimeException.class); - - otelTesting - .assertTraces() - .hasTracesSatisfyingExactly( - traceAssert -> - traceAssert.hasSpansSatisfyingExactly( - spanDataAssert -> - spanDataAssert - .hasName("throwingCallable") - .hasAttributes(Attributes.of(AttributeKey.longKey("one"), 1L)))); - } -} diff --git a/extensions/kotlin/README.md b/extensions/kotlin/README.md index cf05ae83ac0..3637e9e6e26 100644 --- a/extensions/kotlin/README.md +++ b/extensions/kotlin/README.md @@ -1,6 +1,12 @@ -# OpenTelemetry Extension Kotlin +# OpenTelemetry Kotlin Extension -[![Javadocs][javadoc-image]][javadoc-url] +Kotlin [Extensions](src/main/kotlin/io/opentelemetry/extension/kotlin/ContextExtensions.kt) to propagate +OpenTelemetry context into coroutines. -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-kotlin.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-kotlin +For example, you could do the following with coroutines + +```kotlin +launch(Context.current().asContextElement()) { +// trace ids propagated here +} +``` diff --git a/extensions/kotlin/build.gradle.kts b/extensions/kotlin/build.gradle.kts index ba7d9a604d3..17df4b47e33 100644 --- a/extensions/kotlin/build.gradle.kts +++ b/extensions/kotlin/build.gradle.kts @@ -1,4 +1,6 @@ -import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion +import org.jetbrains.kotlin.gradle.tasks.KotlinJvmCompile plugins { id("otel.java-conventions") @@ -11,6 +13,7 @@ plugins { description = "OpenTelemetry Kotlin Extensions" otelJava.moduleName.set("io.opentelemetry.extension.kotlin") +otelJava.requireSuppressWarningsExplanation.set(false) dependencies { implementation(platform("org.jetbrains.kotlin:kotlin-bom")) @@ -27,7 +30,7 @@ dependencies { testing { suites { - val testStrictContext by registering(JvmTestSuite::class) { + register("testStrictContext") { dependencies { implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2") @@ -45,9 +48,10 @@ testing { } tasks { - withType(KotlinCompile::class) { - kotlinOptions { - jvmTarget = "1.8" + withType(KotlinJvmCompile::class) { + compilerOptions { + jvmTarget.set(JvmTarget.JVM_1_8) + apiVersion.set(KotlinVersion.KOTLIN_2_2) } } diff --git a/extensions/kotlin/src/main/kotlin/io/opentelemetry/extension/kotlin/ContextExtensions.kt b/extensions/kotlin/src/main/kotlin/io/opentelemetry/extension/kotlin/ContextExtensions.kt index 78f5a43e3f7..21e44222cac 100644 --- a/extensions/kotlin/src/main/kotlin/io/opentelemetry/extension/kotlin/ContextExtensions.kt +++ b/extensions/kotlin/src/main/kotlin/io/opentelemetry/extension/kotlin/ContextExtensions.kt @@ -13,17 +13,13 @@ import kotlin.coroutines.CoroutineContext * Returns a [CoroutineContext] which will make this [Context] current when resuming a coroutine * and restores the previous [Context] on suspension. */ -fun Context.asContextElement(): CoroutineContext { - return KotlinContextElement(this) -} +fun Context.asContextElement(): CoroutineContext = KotlinContextElement(this) /** * Returns a [CoroutineContext] which will make this [ImplicitContextKeyed] current when resuming a * coroutine and restores the previous [Context] on suspension. */ -fun ImplicitContextKeyed.asContextElement(): CoroutineContext { - return KotlinContextElement(Context.current().with(this)) -} +fun ImplicitContextKeyed.asContextElement(): CoroutineContext = KotlinContextElement(Context.current().with(this)) /** * Returns the [Context] in this [CoroutineContext] if present, or the root otherwise. diff --git a/extensions/noop-api/README.md b/extensions/noop-api/README.md deleted file mode 100644 index 23f093ac8ed..00000000000 --- a/extensions/noop-api/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Extension Noop API - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-noop-api.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-noop-api diff --git a/extensions/noop-api/build.gradle.kts b/extensions/noop-api/build.gradle.kts deleted file mode 100644 index 22ac07e6f8d..00000000000 --- a/extensions/noop-api/build.gradle.kts +++ /dev/null @@ -1,13 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Noop API" -otelJava.moduleName.set("io.opentelemetry.extension.noopapi") - -dependencies { - api(project(":api:all")) -} diff --git a/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopContextStorageProvider.java b/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopContextStorageProvider.java deleted file mode 100644 index 536208e1eb3..00000000000 --- a/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopContextStorageProvider.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.noopapi; - -import io.opentelemetry.context.Context; -import io.opentelemetry.context.ContextKey; -import io.opentelemetry.context.ContextStorage; -import io.opentelemetry.context.ContextStorageProvider; -import io.opentelemetry.context.Scope; -import javax.annotation.Nullable; - -/** - * A {@link ContextStorageProvider} that returns a {@link ContextStorage} which is completely no-op. - */ -public class NoopContextStorageProvider implements ContextStorageProvider { - - /** Returns a no-op context storage. */ - @Override - public ContextStorage get() { - return NoopContextStorage.INSTANCE; - } - - enum NoopContextStorage implements ContextStorage { - INSTANCE; - - @Override - public Scope attach(Context toAttach) { - return Scope.noop(); - } - - @Override - public Context current() { - return NoopContext.INSTANCE; - } - } - - enum NoopContext implements Context { - INSTANCE; - - @Nullable - @Override - public V get(ContextKey key) { - return null; - } - - @Override - public Context with(ContextKey k1, V v1) { - return this; - } - } -} diff --git a/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopOpenTelemetry.java b/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopOpenTelemetry.java deleted file mode 100644 index d87c858d0c0..00000000000 --- a/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopOpenTelemetry.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.noopapi; - -import io.opentelemetry.api.OpenTelemetry; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TracerProvider; -import io.opentelemetry.context.propagation.ContextPropagators; - -/** - * An implementation of {@link OpenTelemetry} that is completely no-op. Unlike {@link - * OpenTelemetry#noop()}, this implementation does not support in-process context propagation at - * all. This means that no objects are allocated nor {@link ThreadLocal}s used in an application - * using this implementation. This can be a good option for use in frameworks shared across a large - * number of servers to introduce instrumentation without forcing overhead on any users of the - * framework. If such overhead is not a concern, always use either {@link OpenTelemetry#noop()}, - * {@link OpenTelemetry#propagating(ContextPropagators)}, or the OpenTelemetry SDK. - * - *

    The following code will fail because context is not mounted. - * - *

    {@code
    - * try (Scope ignored = Context.current().with(Span.wrap(VALID_SPAN_CONTEXT).makeCurrent()) {
    - *   assert Span.current().spanContext().equals(VALID_SPAN_CONTEXT);
    - * }
    - * }
    - * - *

    In most cases when instrumenting a library, the above pattern does not happen because {@link - * io.opentelemetry.api.trace.Span#wrap(SpanContext)} is primarily for use in remote propagators. - * The common pattern looks like - * - *

    {@code
    - * Span span = tracer.spanBuilder().setAttribute(...).startSpan();
    - * try (Scope ignored = Context.current().with(span).makeCurrent()) {
    - *   assert Span.current().spanContext().equals(SpanContext.getInvalid());
    - * }
    - * }
    - * - *

    The above will succeed both with the {@linkplain OpenTelemetry#noop() default implementation} - * and this one, but with this implementation there will be no overhead at all. - */ -public class NoopOpenTelemetry implements OpenTelemetry { - - private static final OpenTelemetry INSTANCE = new NoopOpenTelemetry(); - - public static OpenTelemetry getInstance() { - return INSTANCE; - } - - @Override - public TracerProvider getTracerProvider() { - return NoopTracerProvider.INSTANCE; - } - - @Override - public MeterProvider getMeterProvider() { - // Default implementation is already truly no-op. - return MeterProvider.noop(); - } - - @Override - public ContextPropagators getPropagators() { - return ContextPropagators.noop(); - } - - private NoopOpenTelemetry() {} -} diff --git a/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopTracerProvider.java b/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopTracerProvider.java deleted file mode 100644 index f74839b24c5..00000000000 --- a/extensions/noop-api/src/main/java/io/opentelemetry/extension/noopapi/NoopTracerProvider.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.extension.noopapi; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanBuilder; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.api.trace.TracerProvider; -import io.opentelemetry.context.Context; -import java.util.concurrent.TimeUnit; - -enum NoopTracerProvider implements TracerProvider { - INSTANCE; - - @Override - public Tracer get(String instrumentationScopeName) { - return NoopTracer.INSTANCE; - } - - @Override - public Tracer get(String instrumentationScopeName, String instrumentationScopeVersion) { - return NoopTracer.INSTANCE; - } - - enum NoopTracer implements Tracer { - INSTANCE; - - @Override - public SpanBuilder spanBuilder(String spanName) { - return NoopSpanBuilder.INSTANCE; - } - } - - enum NoopSpanBuilder implements SpanBuilder { - INSTANCE; - - @Override - public SpanBuilder setParent(Context context) { - return this; - } - - @Override - public SpanBuilder setNoParent() { - return this; - } - - @Override - public SpanBuilder addLink(SpanContext spanContext) { - return this; - } - - @Override - public SpanBuilder addLink(SpanContext spanContext, Attributes attributes) { - return this; - } - - @Override - public SpanBuilder setAttribute(String key, String value) { - return this; - } - - @Override - public SpanBuilder setAttribute(String key, long value) { - return this; - } - - @Override - public SpanBuilder setAttribute(String key, double value) { - return this; - } - - @Override - public SpanBuilder setAttribute(String key, boolean value) { - return this; - } - - @Override - public SpanBuilder setAttribute(AttributeKey key, T value) { - return this; - } - - @Override - public SpanBuilder setSpanKind(SpanKind spanKind) { - return this; - } - - @Override - public SpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit) { - return this; - } - - @Override - public Span startSpan() { - return Span.getInvalid(); - } - } -} diff --git a/extensions/noop-api/src/main/resources/META-INF/services/io.opentelemetry.context.ContextStorageProvider b/extensions/noop-api/src/main/resources/META-INF/services/io.opentelemetry.context.ContextStorageProvider deleted file mode 100644 index 978ff78ee1c..00000000000 --- a/extensions/noop-api/src/main/resources/META-INF/services/io.opentelemetry.context.ContextStorageProvider +++ /dev/null @@ -1 +0,0 @@ -io.opentelemetry.extension.noopapi.NoopContextStorageProvider diff --git a/extensions/trace-propagators/README.md b/extensions/trace-propagators/README.md deleted file mode 100644 index 57b33cab7ba..00000000000 --- a/extensions/trace-propagators/README.md +++ /dev/null @@ -1,23 +0,0 @@ -OpenTelemetry Extension Trace Propagators -====================================================== - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-extension-trace-propagators.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-extension-trace-propagators - -This repository provides several -[trace propagators](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/context/api-propagators.md), -used to propagate context across a distributed trace. - -OpenTelemetry Java provides first-party support for -[B3 (OpenZipkin)](https://github.com/openzipkin/b3-propagation) and -[Jaeger](https://github.com/jaegertracing/jaeger) propagators. Issues with those propagators -should be filed against this repo. - ---- -#### Running micro-benchmarks -From the root of the repo run `./gradlew clean :opentelemetry-extension-trace-propagators:jmh` -to run all the benchmarks -or run `./gradlew clean :opentelemetry-extension-trace-propagators:jmh -PjmhIncludeSingleClass=` -to run a specific benchmark class. diff --git a/extensions/trace-propagators/build.gradle.kts b/extensions/trace-propagators/build.gradle.kts index 485e8ee35a5..921bd777e5c 100644 --- a/extensions/trace-propagators/build.gradle.kts +++ b/extensions/trace-propagators/build.gradle.kts @@ -8,14 +8,19 @@ plugins { description = "OpenTelemetry Extension : Trace Propagators" otelJava.moduleName.set("io.opentelemetry.extension.trace.propagation") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator", "io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider", + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) dependencies { api(project(":api:all")) - compileOnly(project(":sdk-extensions:autoconfigure")) + compileOnly(project(":api:incubator")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) testImplementation("io.jaegertracing:jaeger-client") testImplementation("com.google.guava:guava") - - jmhImplementation(project(":extensions:aws")) } diff --git a/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextExtractBenchmark.java b/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextExtractBenchmark.java index 295239f99bf..a4cc4cd628f 100644 --- a/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextExtractBenchmark.java +++ b/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextExtractBenchmark.java @@ -8,7 +8,6 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; -import io.opentelemetry.extension.aws.AwsXrayPropagator; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -73,6 +72,7 @@ public void tearDown() { } /** Benchmark for extracting context from Jaeger headers. */ + @SuppressWarnings("deprecation") public static class JaegerContextExtractBenchmark extends AbstractContextExtractBenchmark { private static final List> traceHeaders = @@ -120,6 +120,7 @@ protected List> getHeaders() { } /** Benchmark for extracting context from Jaeger headers which are url encoded. */ + @SuppressWarnings("deprecation") public static class JaegerUrlEncodedContextExtractBenchmark extends AbstractContextExtractBenchmark { @@ -265,51 +266,4 @@ protected List> getHeaders() { return traceHeaders; } } - - /** Benchmark for extracting context from AWS X-Ray trace header. */ - public static class AwsXrayHeaderContextExtractBenchmark extends AbstractContextExtractBenchmark { - - private static final List> traceHeaders = - Arrays.asList( - Collections.singletonMap( - "X-Amzn-Trace-Id", - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=1"), - Collections.singletonMap( - "X-Amzn-Trace-Id", - "Root=1-8a3c60f7-d188f8fa79d48a391a778fa6;Parent=53995c3f42cd8ad8;Sampled=0"), - Collections.singletonMap( - "X-Amzn-Trace-Id", - "Parent=53995c3f42cd8ad8;Sampled=1;Root=1-8a3c60f7-d188f8fa79d48a391a778fa6"), - Collections.singletonMap( - "X-Amzn-Trace-Id", - "Root=1-57ff426a-80c11c39b0c928905eb0828d;Parent=53995c3f42cd8ad8;Sampled=1"), - Collections.singletonMap( - "X-Amzn-Trace-Id", - "Root=1-57ff426a-80c11c39b0c928905eb0828d;Parent=12345c3f42cd8ad8;Sampled=0")); - - private final TextMapGetter> getter = - new TextMapGetter>() { - @Override - public Iterable keys(Map carrier) { - return carrier.keySet(); - } - - @Override - public String get(Map carrier, String key) { - return carrier.get(key); - } - }; - - private final AwsXrayPropagator xrayPropagator = AwsXrayPropagator.getInstance(); - - @Override - protected Context doExtract() { - return xrayPropagator.extract(Context.current(), getCarrier(), getter); - } - - @Override - protected List> getHeaders() { - return traceHeaders; - } - } } diff --git a/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextInjectBenchmark.java b/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextInjectBenchmark.java index e5fa961a120..bf48658b253 100644 --- a/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextInjectBenchmark.java +++ b/extensions/trace-propagators/src/jmh/java/io/opentelemetry/extension/trace/propagation/PropagatorContextInjectBenchmark.java @@ -11,7 +11,6 @@ import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapSetter; -import io.opentelemetry.extension.aws.AwsXrayPropagator; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -82,7 +81,9 @@ private static SpanContext createTestSpanContext(String traceId, String spanId) /** Benchmark for injecting trace context into Jaeger headers. */ public static class JaegerContextInjectBenchmark extends AbstractContextInjectBenchmark { + @SuppressWarnings("deprecation") private final JaegerPropagator jaegerPropagator = JaegerPropagator.getInstance(); + private final TextMapSetter> setter = Map::put; @Override @@ -115,15 +116,4 @@ protected void doInject(Context context, Map carrier) { b3Propagator.inject(context, carrier, setter); } } - - /** Benchmark for injecting trace context into AWS X-Ray headers. */ - public static class AwsXrayPropagatorInjectBenchmark extends AbstractContextInjectBenchmark { - private final AwsXrayPropagator xrayPropagator = AwsXrayPropagator.getInstance(); - private final TextMapSetter> setter = Map::put; - - @Override - protected void doInject(Context context, Map carrier) { - xrayPropagator.inject(context, carrier, setter); - } - } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3ConfigurablePropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3ConfigurablePropagator.java index ba6f9b02448..4481b59c57e 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3ConfigurablePropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3ConfigurablePropagator.java @@ -11,7 +11,7 @@ /** * A {@link ConfigurablePropagatorProvider} which allows enabling the {@linkplain - * B3Propagator#injectingSingleHeader()} B3-single propagator} with the propagator name {@code b3}. + * B3Propagator#injectingSingleHeader() B3-single propagator} with the propagator name {@code b3}. */ public final class B3ConfigurablePropagator implements ConfigurablePropagatorProvider { @Override diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3Propagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3Propagator.java index bdaf849a0b7..8966b9b6b16 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3Propagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3Propagator.java @@ -12,8 +12,6 @@ import io.opentelemetry.context.propagation.TextMapSetter; import java.util.Collection; import java.util.Optional; -import java.util.function.Supplier; -import java.util.stream.Stream; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @@ -22,27 +20,23 @@ * href=https://github.com/openzipkin/b3-propagation>openzipkin/b3-propagation. * *

    Also see B3 + * href="https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/api-propagators.md#b3-requirements">B3 * Requirements * *

    To register the default B3 propagator, which injects a single header, use: * *

    {@code
    - * OpenTelemetry.setPropagators(
    - *   DefaultContextPropagators
    - *     .builder()
    - *     .addTextMapPropagator(B3Propagator.injectingSingleHeader())
    - *     .build());
    + * OpenTelemetrySdk.builder()
    + *     .setPropagators(ContextPropagators.create(B3Propagator.injectingSingleHeader()))
    + *     .build();
      * }
    * *

    To register a B3 propagator that injects multiple headers, use: * *

    {@code
    - * OpenTelemetry.setPropagators(
    - *   DefaultContextPropagators
    - *     .builder()
    - *     .addTextMapPropagator(B3Propagator.injectingMultiHeaders())
    - *     .build());
    + * OpenTelemetrySdk.builder()
    + *     .setPropagators(ContextPropagators.create(B3Propagator.injectingMultiHeaders()))
    + *     .build();
      * }
    */ @Immutable @@ -113,14 +107,15 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se @Override public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { - return Stream.>>of( - () -> singleHeaderExtractor.extract(context, carrier, getter), - () -> multipleHeadersExtractor.extract(context, carrier, getter), - () -> Optional.of(context)) - .map(Supplier::get) - .filter(Optional::isPresent) - .map(Optional::get) - .findFirst() - .get(); + Optional ctx = singleHeaderExtractor.extract(context, carrier, getter); + if (ctx.isPresent()) { + return ctx.get(); + } + return multipleHeadersExtractor.extract(context, carrier, getter).orElse(context); + } + + @Override + public String toString() { + return "B3Propagator{b3PropagatorInjector=" + b3PropagatorInjector + "}"; } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorExtractorSingleHeader.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorExtractorSingleHeader.java index bfd24b9768e..a55fccc747f 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorExtractorSingleHeader.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorExtractorSingleHeader.java @@ -5,7 +5,6 @@ package io.opentelemetry.extension.trace.propagation; -import io.opentelemetry.api.internal.StringUtils; import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; @@ -34,14 +33,16 @@ public Optional extract( private static Optional extractSpanContextFromSingleHeader( Context context, @Nullable C carrier, TextMapGetter getter) { String value = getter.get(carrier, B3Propagator.COMBINED_HEADER); - if (StringUtils.isNullOrEmpty(value)) { + if (value == null || value.isEmpty()) { return Optional.empty(); } // must have between 2 and 4 hyphen delimited parts: // traceId-spanId-sampled-parentSpanId (last two are optional) // NOTE: we do not use parentSpanId - String[] parts = value.split(B3Propagator.COMBINED_HEADER_DELIMITER); + // Bound the split so a header full of delimiters cannot force allocation of an arbitrarily + // large token array before the length check below. + String[] parts = value.split(B3Propagator.COMBINED_HEADER_DELIMITER, 5); if (parts.length < 2 || parts.length > 4) { logger.fine( "Invalid combined header '" diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorMultipleHeaders.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorMultipleHeaders.java index 468bf9be442..f2cda9a7dc2 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorMultipleHeaders.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorMultipleHeaders.java @@ -5,6 +5,7 @@ package io.opentelemetry.extension.trace.propagation; +import static io.opentelemetry.extension.trace.propagation.B3Propagator.DEBUG_HEADER; import static io.opentelemetry.extension.trace.propagation.B3Propagator.SAMPLED_HEADER; import static io.opentelemetry.extension.trace.propagation.B3Propagator.SPAN_ID_HEADER; import static io.opentelemetry.extension.trace.propagation.B3Propagator.TRACE_ID_HEADER; @@ -22,7 +23,8 @@ @Immutable final class B3PropagatorInjectorMultipleHeaders implements B3PropagatorInjector { private static final Collection FIELDS = - Collections.unmodifiableList(Arrays.asList(TRACE_ID_HEADER, SPAN_ID_HEADER, SAMPLED_HEADER)); + Collections.unmodifiableList( + Arrays.asList(TRACE_ID_HEADER, SPAN_ID_HEADER, SAMPLED_HEADER, DEBUG_HEADER)); @Override public void inject(Context context, @Nullable C carrier, TextMapSetter setter) { @@ -54,4 +56,9 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se public Collection fields() { return FIELDS; } + + @Override + public String toString() { + return "B3PropagatorInjectorMultipleHeaders"; + } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorSingleHeader.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorSingleHeader.java index ea7df623157..eae09334300 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorSingleHeader.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/B3PropagatorInjectorSingleHeader.java @@ -7,7 +7,7 @@ import static io.opentelemetry.extension.trace.propagation.B3Propagator.COMBINED_HEADER; -import io.opentelemetry.api.internal.TemporaryBuffers; +import io.opentelemetry.api.impl.TemporaryBuffers; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; @@ -67,4 +67,9 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se public Collection fields() { return FIELDS; } + + @Override + public String toString() { + return "B3PropagatorInjectorSingleHeader"; + } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/Common.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/Common.java index aabbc190e03..a522ba56eea 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/Common.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/Common.java @@ -5,7 +5,6 @@ package io.opentelemetry.extension.trace.propagation; -import io.opentelemetry.api.internal.StringUtils; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceFlags; @@ -29,6 +28,8 @@ final class Common { static final int MAX_TRACE_ID_LENGTH = TraceId.getLength(); static final int MIN_TRACE_ID_LENGTH = MAX_TRACE_ID_LENGTH / 2; + static final int MAX_SPAN_ID_LENGTH = SpanId.getLength(); + private Common() {} static SpanContext buildSpanContext( @@ -44,7 +45,7 @@ static SpanContext buildSpanContext( return SpanContext.createFromRemoteParent( StringUtils.padLeft(traceId, MAX_TRACE_ID_LENGTH), - spanId, + StringUtils.padLeft(spanId, MAX_SPAN_ID_LENGTH), traceFlags, TraceState.getDefault()); } catch (RuntimeException e) { @@ -54,12 +55,13 @@ static SpanContext buildSpanContext( } static boolean isTraceIdValid(@Nullable String value) { - return !(StringUtils.isNullOrEmpty(value) - || (value.length() != MIN_TRACE_ID_LENGTH && value.length() != MAX_TRACE_ID_LENGTH) - || !TraceId.isValid(StringUtils.padLeft(value, TraceId.getLength()))); + return value != null + && !value.isEmpty() + && (value.length() == MIN_TRACE_ID_LENGTH || value.length() == MAX_TRACE_ID_LENGTH) + && TraceId.isValid(StringUtils.padLeft(value, TraceId.getLength())); } static boolean isSpanIdValid(@Nullable String value) { - return !StringUtils.isNullOrEmpty(value) && SpanId.isValid(value); + return value != null && !value.isEmpty() && SpanId.isValid(value); } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerConfigurablePropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerConfigurablePropagator.java index d5a9b01cdae..46999cb81d1 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerConfigurablePropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerConfigurablePropagator.java @@ -13,6 +13,7 @@ * A {@link ConfigurablePropagatorProvider} which allows enabling the {@link JaegerPropagator} with * the propagator name {@code jaeger}. */ +@SuppressWarnings("deprecation") public final class JaegerConfigurablePropagator implements ConfigurablePropagatorProvider { @Override public TextMapPropagator getPropagator(ConfigProperties config) { diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java index 61f207d852b..a6171d0deb6 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/JaegerPropagator.java @@ -7,22 +7,24 @@ import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.baggage.BaggageBuilder; -import io.opentelemetry.api.internal.StringUtils; -import io.opentelemetry.api.internal.TemporaryBuffers; +import io.opentelemetry.api.impl.TemporaryBuffers; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.context.propagation.TextMapSetter; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; +import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Collections; +import java.util.Locale; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; @@ -30,10 +32,15 @@ /** * Implementation of the Jaeger propagation protocol. See Jaeger Propagation + * href="https://www.jaegertracing.io/docs/client-libraries/#propagation-format">Jaeger Propagation * Format. + * + * @deprecated the jaeger propagation format is deprecated in the OpenTelemetry specification (see + * #4827). + * Please use {@link W3CTraceContextPropagator} instead. */ @Immutable +@Deprecated public final class JaegerPropagator implements TextMapPropagator { private static final Logger logger = Logger.getLogger(JaegerPropagator.class.getName()); @@ -65,6 +72,15 @@ public final class JaegerPropagator implements TextMapPropagator { PARENT_SPAN_ID_OFFSET + PARENT_SPAN_ID_SIZE + PROPAGATION_HEADER_DELIMITER_SIZE; private static final int PROPAGATION_HEADER_SIZE = SAMPLED_FLAG_OFFSET + SAMPLED_FLAG_SIZE; + // No limits are defined by the Jaeger format; borrow the W3C Baggage spec limits as a + // defense-in-depth measure (https://www.w3.org/TR/baggage/#limits). + private static final int MAX_BAGGAGE_ENTRIES = 64; + private static final int MAX_BAGGAGE_BYTES = 8192; + + // Bounds the parse work for a single jaeger-baggage header. Counts malformed tokens, which are + // not bounded by MAX_BAGGAGE_ENTRIES because they add no entry. + private static final int MAX_BAGGAGE_HEADER_TOKENS = MAX_BAGGAGE_ENTRIES; + private static final Collection FIELDS = Collections.singletonList(PROPAGATION_HEADER); private static final JaegerPropagator INSTANCE = new JaegerPropagator(); @@ -119,8 +135,20 @@ private static void injectSpan( private static void injectBaggage( Baggage baggage, @Nullable C carrier, TextMapSetter setter) { - baggage.forEach( - (key, baggageEntry) -> setter.set(carrier, BAGGAGE_PREFIX + key, baggageEntry.getValue())); + int[] entriesEmitted = {0}; + int[] bytesEmitted = {0}; + baggage.forEach((key, baggageEntry) -> { + if (entriesEmitted[0] >= MAX_BAGGAGE_ENTRIES) { + return; + } + String value = baggageEntry.getValue(); + if (bytesEmitted[0] + key.length() + value.length() > MAX_BAGGAGE_BYTES) { + return; + } + setter.set(carrier, BAGGAGE_PREFIX + key, value); + entriesEmitted[0]++; + bytesEmitted[0] += key.length() + value.length(); + }); } @Override @@ -145,10 +173,16 @@ public Context extract(Context context, @Nullable C carrier, TextMapGetter SpanContext getSpanContextFromHeader( @Nullable C carrier, TextMapGetter getter) { String value = getter.get(carrier, PROPAGATION_HEADER); - if (StringUtils.isNullOrEmpty(value)) { + if (value == null || value.isEmpty()) { return SpanContext.getInvalid(); } @@ -157,8 +191,8 @@ private static SpanContext getSpanContextFromHeader( if (value.lastIndexOf(PROPAGATION_HEADER_DELIMITER) == -1) { try { // the propagation value - value = URLDecoder.decode(value, "UTF-8"); - } catch (UnsupportedEncodingException e) { + value = URLDecoder.decode(value, StandardCharsets.UTF_8.name()); + } catch (UnsupportedEncodingException | IllegalArgumentException e) { logger.fine( "Error decoding '" + PROPAGATION_HEADER @@ -169,7 +203,9 @@ private static SpanContext getSpanContextFromHeader( } } - String[] parts = value.split(String.valueOf(PROPAGATION_HEADER_DELIMITER)); + // Bound the split so a header full of delimiters cannot force allocation of an arbitrarily + // large token array before the length check below. + String[] parts = value.split(String.valueOf(PROPAGATION_HEADER_DELIMITER), 5); if (parts.length != 4) { logger.fine( "Invalid header '" @@ -213,55 +249,159 @@ private static SpanContext getSpanContextFromHeader( } @Nullable + @SuppressWarnings("deprecation") // Legacy baggage headers require key enumeration. private static Baggage getBaggageFromHeader(@Nullable C carrier, TextMapGetter getter) { BaggageBuilder builder = null; + int entriesAdded = 0; + int bytesAdded = 0; Iterable keys = carrier != null ? getter.keys(carrier) : Collections.emptyList(); for (String key : keys) { - if (key.startsWith(BAGGAGE_PREFIX)) { - if (key.length() == BAGGAGE_PREFIX.length()) { + if (entriesAdded >= MAX_BAGGAGE_ENTRIES || bytesAdded > MAX_BAGGAGE_BYTES) { + break; + } + String lowercaseKey = key.toLowerCase(Locale.ROOT); + if (lowercaseKey.startsWith(BAGGAGE_PREFIX)) { + if (lowercaseKey.length() == BAGGAGE_PREFIX.length()) { continue; } - - if (builder == null) { - builder = Baggage.builder(); - } - String value = getter.get(carrier, key); if (value != null) { - builder.put(key.substring(BAGGAGE_PREFIX.length()), value); + String baggageKey = lowercaseKey.substring(BAGGAGE_PREFIX.length()); + if (bytesAdded + baggageKey.length() + value.length() > MAX_BAGGAGE_BYTES) { + break; + } + if (builder == null) { + builder = Baggage.builder(); + } + builder.put(baggageKey, value); + entriesAdded++; + bytesAdded += baggageKey.length() + value.length(); } - } else if (key.equals(BAGGAGE_HEADER)) { + } else if (lowercaseKey.equals(BAGGAGE_HEADER)) { String value = getter.get(carrier, key); if (value != null) { if (builder == null) { builder = Baggage.builder(); } - builder = parseBaggageHeader(value, builder); + int[] counts = + parseBaggageHeader( + value, + builder, + MAX_BAGGAGE_HEADER_TOKENS, + MAX_BAGGAGE_ENTRIES - entriesAdded, + MAX_BAGGAGE_BYTES - bytesAdded); + entriesAdded += counts[0]; + bytesAdded += counts[1]; } } } - return builder == null ? null : builder.build(); + if (builder == null) { + return null; + } + Baggage baggage = builder.build(); + return baggage.isEmpty() ? null : baggage; } - private static BaggageBuilder parseBaggageHeader(String header, BaggageBuilder builder) { - for (String part : header.split("\\s*,\\s*")) { - String[] kv = part.split("\\s*=\\s*"); - if (kv.length == 2) { - builder.put(kv[0], kv[1]); - } else { - logger.fine("malformed token in " + BAGGAGE_HEADER + " header: " + part); + /** + * Parses a single {@code jaeger-baggage} header, stopping after {@code maxTokens} tokens, after + * {@code maxEntries} entries have been added, or once the next entry would exceed {@code + * maxBytes}. + * + *

    {@code maxTokens} bounds the parse work and counts malformed tokens, so a header of entirely + * malformed tokens cannot keep the loop running to the end of the input. {@code maxEntries} is a + * separate acceptance bound, so malformed tokens do not consume the caller's remaining entry + * budget. + * + *

    Returns a two-element array of {@code [entriesAdded, bytesAdded]}, reflecting what was + * actually added to {@code builder}. + */ + private static int[] parseBaggageHeader( + String header, BaggageBuilder builder, int maxTokens, int maxEntries, int maxBytes) { + int entriesAdded = 0; + int bytesAdded = 0; + int tokensParsed = 0; + int len = header.length(); + int cursor = 0; + while (cursor < len && tokensParsed < maxTokens && entriesAdded < maxEntries) { + int comma = header.indexOf(',', cursor); + int segEnd = (comma == -1) ? len : comma; + int segStart = cursor; + cursor = (comma == -1) ? len : comma + 1; + + // Skip empty segments (e.g., leading/trailing/repeated commas) without consuming budget. + int keyStart = skipLeadingWhitespace(header, segStart, segEnd); + if (keyStart == segEnd) { + continue; + } + tokensParsed++; + + int eq = indexOfSoleEquals(header, keyStart, segEnd); + if (eq < 0) { + logMalformed(header, keyStart, segEnd); + continue; } + int keyEnd = trimTrailingWhitespace(header, keyStart, eq); + int valStart = skipLeadingWhitespace(header, eq + 1, segEnd); + int valEnd = trimTrailingWhitespace(header, valStart, segEnd); + if (keyStart >= keyEnd || valStart >= valEnd) { + logMalformed(header, keyStart, segEnd); + continue; + } + + int entryBytes = (keyEnd - keyStart) + (valEnd - valStart); + if (bytesAdded + entryBytes > maxBytes) { + break; + } + builder.put(header.substring(keyStart, keyEnd), header.substring(valStart, valEnd)); + entriesAdded++; + bytesAdded += entryBytes; + } + return new int[] {entriesAdded, bytesAdded}; + } + + private static int skipLeadingWhitespace(String s, int from, int end) { + int i = from; + while (i < end && Character.isWhitespace(s.charAt(i))) { + i++; + } + return i; + } + + private static int trimTrailingWhitespace(String s, int start, int end) { + int i = end; + while (i > start && Character.isWhitespace(s.charAt(i - 1))) { + i--; + } + return i; + } + + /** Returns the index of the sole {@code '='} in {@code [from, end)}, or -1 if 0 or >1 exist. */ + private static int indexOfSoleEquals(String s, int from, int end) { + int first = s.indexOf('=', from); + if (first < 0 || first >= end) { + return -1; + } + int second = s.indexOf('=', first + 1); + if (second >= 0 && second < end) { + return -1; + } + return first; + } + + private static void logMalformed(String header, int start, int end) { + if (logger.isLoggable(Level.FINE)) { + logger.fine( + "malformed token in " + BAGGAGE_HEADER + " header: " + header.substring(start, end)); } - return builder; } private static SpanContext buildSpanContext(String traceId, String spanId, String flags) { try { String otelTraceId = StringUtils.padLeft(traceId, MAX_TRACE_ID_LENGTH); String otelSpanId = StringUtils.padLeft(spanId, MAX_SPAN_ID_LENGTH); - int flagsInt = Integer.parseInt(flags); + int flagsInt = Integer.parseInt(flags, 16); return SpanContext.createFromRemoteParent( otelTraceId, otelSpanId, @@ -277,14 +417,14 @@ private static SpanContext buildSpanContext(String traceId, String spanId, Strin } private static boolean isTraceIdValid(String value) { - return !(StringUtils.isNullOrEmpty(value) || value.length() > MAX_TRACE_ID_LENGTH); + return !value.isEmpty() && value.length() <= MAX_TRACE_ID_LENGTH; } private static boolean isSpanIdValid(String value) { - return !(StringUtils.isNullOrEmpty(value) || value.length() > MAX_SPAN_ID_LENGTH); + return !value.isEmpty() && value.length() <= MAX_SPAN_ID_LENGTH; } private static boolean isFlagsValid(String value) { - return !(StringUtils.isNullOrEmpty(value) || value.length() > MAX_FLAGS_LENGTH); + return !value.isEmpty() && value.length() <= MAX_FLAGS_LENGTH; } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTraceConfigurablePropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTraceConfigurablePropagator.java index 00568a11444..e80697bd8ff 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTraceConfigurablePropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTraceConfigurablePropagator.java @@ -13,6 +13,7 @@ * A {@link ConfigurablePropagatorProvider} which allows enabling the {@link OtTracePropagator} with * the propagator name {@code ottrace}. */ +@SuppressWarnings("deprecation") public final class OtTraceConfigurablePropagator implements ConfigurablePropagatorProvider { @Override public TextMapPropagator getPropagator(ConfigProperties config) { diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java index fb51ccf4f14..cb63235b6f7 100644 --- a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/OtTracePropagator.java @@ -5,14 +5,16 @@ package io.opentelemetry.extension.trace.propagation; +import static io.opentelemetry.extension.trace.propagation.Common.MAX_SPAN_ID_LENGTH; import static io.opentelemetry.extension.trace.propagation.Common.MAX_TRACE_ID_LENGTH; import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.baggage.BaggageBuilder; -import io.opentelemetry.api.internal.StringUtils; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; @@ -20,6 +22,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Locale; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @@ -30,8 +33,13 @@ * See OT * Python Propagation TextMapPropagator. + * + * @deprecated the OT trace propagation format is deprecated in the OpenTelemetry specification (see + * #4851). + * Please use {@link W3CTraceContextPropagator} instead. */ @Immutable +@Deprecated public final class OtTracePropagator implements TextMapPropagator { static final String TRACE_ID_HEADER = "ot-tracer-traceid"; @@ -41,6 +49,11 @@ public final class OtTracePropagator implements TextMapPropagator { private static final Collection FIELDS = Collections.unmodifiableList(Arrays.asList(TRACE_ID_HEADER, SPAN_ID_HEADER, SAMPLED_HEADER)); + // No limits are defined by the OT trace format; borrow the W3C Baggage spec limits as a + // defense-in-depth measure (https://www.w3.org/TR/baggage/#limits). + private static final int MAX_BAGGAGE_ENTRIES = 64; + private static final int MAX_BAGGAGE_BYTES = 8192; + private static final OtTracePropagator INSTANCE = new OtTracePropagator(); private OtTracePropagator() { @@ -76,13 +89,25 @@ public void inject(Context context, @Nullable C carrier, TextMapSetter se Baggage baggage = Baggage.fromContext(context); if (!baggage.isEmpty()) { // Metadata is not supported by OpenTracing - baggage.forEach( - (key, baggageEntry) -> - setter.set(carrier, PREFIX_BAGGAGE_HEADER + key, baggageEntry.getValue())); + int[] entriesEmitted = {0}; + int[] bytesEmitted = {0}; + baggage.forEach((key, baggageEntry) -> { + if (entriesEmitted[0] >= MAX_BAGGAGE_ENTRIES) { + return; + } + String value = baggageEntry.getValue(); + if (bytesEmitted[0] + key.length() + value.length() > MAX_BAGGAGE_BYTES) { + return; + } + setter.set(carrier, PREFIX_BAGGAGE_HEADER + key, value); + entriesEmitted[0]++; + bytesEmitted[0] += key.length() + value.length(); + }); } } @Override + @SuppressWarnings("deprecation") // Legacy baggage headers require key enumeration. public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { if (context == null) { return Context.root(); @@ -95,7 +120,13 @@ public Context extract(Context context, @Nullable C carrier, TextMapGetter Context extract(Context context, @Nullable C carrier, TextMapGetter= MAX_BAGGAGE_ENTRIES || bytesAdded > MAX_BAGGAGE_BYTES) { + break; + } + String lowercaseKey = key.toLowerCase(Locale.ROOT); + if (!lowercaseKey.startsWith(PREFIX_BAGGAGE_HEADER) + || lowercaseKey.length() == PREFIX_BAGGAGE_HEADER.length()) { continue; } String value = getter.get(carrier, key); if (value == null) { continue; } - baggageBuilder.put(key.replace(OtTracePropagator.PREFIX_BAGGAGE_HEADER, ""), value); + String baggageKey = + lowercaseKey.substring(OtTracePropagator.PREFIX_BAGGAGE_HEADER.length()); + if (bytesAdded + baggageKey.length() + value.length() > MAX_BAGGAGE_BYTES) { + break; + } + baggageBuilder.put(baggageKey, value); + entriesAdded++; + bytesAdded += baggageKey.length() + value.length(); } Baggage baggage = baggageBuilder.build(); if (!baggage.isEmpty()) { @@ -133,4 +178,9 @@ private static SpanContext buildSpanContext( } return Common.buildSpanContext(traceId, spanId, sampled); } + + @Override + public String toString() { + return "OtTracePropagator"; + } } diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/StringUtils.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/StringUtils.java new file mode 100644 index 00000000000..0ba914cb877 --- /dev/null +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/StringUtils.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.extension.trace.propagation; + +import java.util.Objects; +import javax.annotation.concurrent.Immutable; + +/** + * Utilities for working with strings. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +final class StringUtils { + + /** + * Returns {@code value} left-padded with zeroes to at least {@code minLength} characters. + * + *

    If {@code value} is already at least {@code minLength} characters long, it is returned + * unchanged. + * + * @param value the string to pad + * @param minLength the minimum length of the returned string + * @return the padded string, or {@code value} if it already meets the minimum length + */ + static String padLeft(String value, int minLength) { + return padStart(value, minLength, '0'); + } + + /** + * Returns a string, of length at least {@code minLength}, consisting of {@code string} prepended + * with as many copies of {@code padChar} as are necessary to reach that length. For example, + * + *

      + *
    • {@code padStart("7", 3, '0')} returns {@code "007"} + *
    • {@code padStart("2010", 3, '0')} returns {@code "2010"} + *
    + * + *

    See {@link java.util.Formatter} for a richer set of formatting capabilities. + * + *

    This method was copied almost verbatim from Guava library method + * com.google.common.base.Strings#padStart(java.lang.String, int, char). + * + * @param string the string which should appear at the end of the result + * @param minLength the minimum length the resulting string must have. Can be zero or negative, in + * which case the input string is always returned. + * @param padChar the character to insert at the beginning of the result until the minimum length + * is reached + * @return the padded string + */ + private static String padStart(String string, int minLength, char padChar) { + Objects.requireNonNull(string); + if (string.length() >= minLength) { + return string; + } + StringBuilder sb = new StringBuilder(minLength); + for (int i = string.length(); i < minLength; i++) { + sb.append(padChar); + } + sb.append(string); + return sb.toString(); + } + + private StringUtils() {} +} diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/internal/B3ComponentProvider.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/internal/B3ComponentProvider.java new file mode 100644 index 00000000000..21c7d1300e2 --- /dev/null +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/internal/B3ComponentProvider.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.extension.trace.propagation.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.extension.trace.propagation.B3Propagator; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; + +/** + * Declarative configuration SPI implementation for {@link B3Propagator} which allows enabling + * {@link B3Propagator#injectingSingleHeader()}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class B3ComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return TextMapPropagator.class; + } + + @Override + public String getName() { + return "b3"; + } + + @Override + public TextMapPropagator create(DeclarativeConfigProperties config) { + return B3Propagator.injectingSingleHeader(); + } +} diff --git a/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/internal/B3MultiComponentProvider.java b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/internal/B3MultiComponentProvider.java new file mode 100644 index 00000000000..92271dda1a0 --- /dev/null +++ b/extensions/trace-propagators/src/main/java/io/opentelemetry/extension/trace/propagation/internal/B3MultiComponentProvider.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.extension.trace.propagation.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.extension.trace.propagation.B3Propagator; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; + +/** + * Declarative configuration SPI implementation for {@link B3Propagator} which allows enabling + * {@link B3Propagator#injectingMultiHeaders()}. + * + *

    This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class B3MultiComponentProvider implements ComponentProvider { + + @Override + public Class getType() { + return TextMapPropagator.class; + } + + @Override + public String getName() { + return "b3multi"; + } + + @Override + public TextMapPropagator create(DeclarativeConfigProperties config) { + return B3Propagator.injectingMultiHeaders(); + } +} diff --git a/extensions/trace-propagators/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/extensions/trace-propagators/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..ecc77430ed3 --- /dev/null +++ b/extensions/trace-propagators/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,3 @@ +io.opentelemetry.extension.trace.propagation.internal.B3ComponentProvider +io.opentelemetry.extension.trace.propagation.internal.B3MultiComponentProvider + diff --git a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/B3PropagatorTest.java b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/B3PropagatorTest.java index 90437c72844..b98c745250b 100644 --- a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/B3PropagatorTest.java +++ b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/B3PropagatorTest.java @@ -7,9 +7,7 @@ import static io.opentelemetry.extension.trace.propagation.B3Propagator.DEBUG_CONTEXT_KEY; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.jupiter.api.Assertions.assertTrue; -import io.opentelemetry.api.internal.StringUtils; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; @@ -237,6 +235,15 @@ void extract_InvalidTraceId_NotHex() { verifyInvalidBehavior(invalidHeaders); } + @Test + void extract_EmptyTraceId() { + Map invalidHeaders = new LinkedHashMap<>(); + invalidHeaders.put(B3Propagator.TRACE_ID_HEADER, ""); + invalidHeaders.put(B3Propagator.SPAN_ID_HEADER, SPAN_ID); + invalidHeaders.put(B3Propagator.SAMPLED_HEADER, Common.TRUE_INT); + verifyInvalidBehavior(invalidHeaders); + } + @Test void extract_InvalidTraceId_TooShort() { Map invalidHeaders = new LinkedHashMap<>(); @@ -273,6 +280,15 @@ void extract_InvalidSpanId_NotHex() { verifyInvalidBehavior(invalidHeaders); } + @Test + void extract_EmptySpanId() { + Map invalidHeaders = new LinkedHashMap<>(); + invalidHeaders.put(B3Propagator.TRACE_ID_HEADER, TRACE_ID); + invalidHeaders.put(B3Propagator.SPAN_ID_HEADER, ""); + invalidHeaders.put(B3Propagator.SAMPLED_HEADER, Common.TRUE_INT); + verifyInvalidBehavior(invalidHeaders); + } + @Test void extract_InvalidSpanId_TooShort() { Map invalidHeaders = new LinkedHashMap<>(); @@ -611,7 +627,10 @@ void extract_nullGetter() { void fieldsList_multiInject() { assertThat(b3Propagator.fields()) .containsExactly( - B3Propagator.TRACE_ID_HEADER, B3Propagator.SPAN_ID_HEADER, B3Propagator.SAMPLED_HEADER); + B3Propagator.TRACE_ID_HEADER, + B3Propagator.SPAN_ID_HEADER, + B3Propagator.SAMPLED_HEADER, + B3Propagator.DEBUG_HEADER); } @Test @@ -644,7 +663,7 @@ void extract_DebugContext_SingleHeader() { .isEqualTo( SpanContext.createFromRemoteParent( TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - assertTrue(context.get(DEBUG_CONTEXT_KEY)); + assertThat(context.get(DEBUG_CONTEXT_KEY)).isTrue(); } @Test @@ -659,7 +678,7 @@ void extract_DebugContext_MultipleHeaders() { .isEqualTo( SpanContext.createFromRemoteParent( TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - assertTrue(context.get(DEBUG_CONTEXT_KEY)); + assertThat(context.get(DEBUG_CONTEXT_KEY)).isTrue(); } @Test @@ -675,7 +694,7 @@ void extract_DebugContext_SampledFalseDebugTrue_MultipleHeaders() { .isEqualTo( SpanContext.createFromRemoteParent( TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - assertTrue(context.get(DEBUG_CONTEXT_KEY)); + assertThat(context.get(DEBUG_CONTEXT_KEY)).isTrue(); } @Test @@ -691,7 +710,39 @@ void extract_DebugContext_SampledTrueDebugTrue_MultipleHeaders() { .isEqualTo( SpanContext.createFromRemoteParent( TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); - assertTrue(context.get(DEBUG_CONTEXT_KEY)); + assertThat(context.get(DEBUG_CONTEXT_KEY)).isTrue(); + } + + @Test + void inject_ReusedCarrier_DoesNotRetainDebugFlag() { + Map carrier = new LinkedHashMap<>(); + + Context debugContext = + withSpanContext( + SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()), + Context.root().with(DEBUG_CONTEXT_KEY, true)); + + b3Propagator.inject(debugContext, carrier, setter); + assertThat(carrier).containsEntry(B3Propagator.DEBUG_HEADER, Common.TRUE_INT); + + for (String header : b3Propagator.fields()) { + carrier.remove(header); + } + + Context normalContext = + withSpanContext( + SpanContext.create( + EXTRA_TRACE_ID, EXTRA_SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()), + Context.root()); + + b3Propagator.inject(normalContext, carrier, setter); + + assertThat(carrier).doesNotContainKey(B3Propagator.DEBUG_HEADER); + assertThat(carrier).containsEntry(B3Propagator.SAMPLED_HEADER, Common.FALSE_INT); + + // The receiver must also see this request as unsampled. + Context extractedContext = b3Propagator.extract(Context.root(), carrier, getter); + assertThat(getSpanContext(extractedContext).isSampled()).isFalse(); } @Test @@ -725,4 +776,12 @@ void inject_DebugContext_SingleHeader() { B3Propagator.COMBINED_HEADER, TRACE_ID + "-" + SPAN_ID + "-" + B3Propagator.SINGLE_HEADER_DEBUG); } + + @Test + void toString_Valid() { + assertThat(b3Propagator.toString()) + .isEqualTo("B3Propagator{b3PropagatorInjector=B3PropagatorInjectorMultipleHeaders}"); + assertThat(b3PropagatorSingleHeader.toString()) + .isEqualTo("B3Propagator{b3PropagatorInjector=B3PropagatorInjectorSingleHeader}"); + } } diff --git a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/CommonTest.java b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/CommonTest.java new file mode 100644 index 00000000000..37db5ae223a --- /dev/null +++ b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/CommonTest.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.extension.trace.propagation; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class CommonTest { + + @Test + void isTraceIdValid() { + assertThat(Common.isTraceIdValid(null)).isFalse(); + assertThat(Common.isTraceIdValid("")).isFalse(); + assertThat(Common.isTraceIdValid("0000000000000001")).isTrue(); + assertThat(Common.isTraceIdValid("00000000000000000000000000000001")).isTrue(); + assertThat(Common.isTraceIdValid("000000000000000")).isFalse(); + assertThat(Common.isTraceIdValid("0000000000000000")).isFalse(); + } + + @Test + void isSpanIdValid() { + assertThat(Common.isSpanIdValid(null)).isFalse(); + assertThat(Common.isSpanIdValid("")).isFalse(); + assertThat(Common.isSpanIdValid("0000000000000001")).isTrue(); + assertThat(Common.isSpanIdValid("0000000000000000")).isFalse(); + } +} diff --git a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/JaegerPropagatorTest.java b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/JaegerPropagatorTest.java index 73a2552a66a..6becceb597a 100644 --- a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/JaegerPropagatorTest.java +++ b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/JaegerPropagatorTest.java @@ -6,17 +6,13 @@ package io.opentelemetry.extension.trace.propagation; import static io.opentelemetry.api.baggage.Baggage.fromContext; -import static io.opentelemetry.extension.trace.propagation.JaegerPropagator.BAGGAGE_HEADER; -import static io.opentelemetry.extension.trace.propagation.JaegerPropagator.BAGGAGE_PREFIX; -import static io.opentelemetry.extension.trace.propagation.JaegerPropagator.DEPRECATED_PARENT_SPAN; -import static io.opentelemetry.extension.trace.propagation.JaegerPropagator.PROPAGATION_HEADER; -import static io.opentelemetry.extension.trace.propagation.JaegerPropagator.PROPAGATION_HEADER_DELIMITER; import static org.assertj.core.api.Assertions.assertThat; import com.google.common.collect.ImmutableMap; import io.jaegertracing.internal.JaegerSpanContext; import io.jaegertracing.internal.propagation.TextMapCodec; import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.baggage.BaggageBuilder; import io.opentelemetry.api.baggage.BaggageEntryMetadata; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; @@ -29,15 +25,32 @@ import io.opentelemetry.context.propagation.TextMapSetter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -/** Unit tests for {@link io.opentelemetry.extension.trace.propagation.JaegerPropagator}. */ +/** Unit tests for {@link JaegerPropagator}. */ +@SuppressWarnings("deprecation") class JaegerPropagatorTest { + private static final String BAGGAGE_HEADER = JaegerPropagator.BAGGAGE_HEADER; + private static final String BAGGAGE_PREFIX = JaegerPropagator.BAGGAGE_PREFIX; + private static final char DEPRECATED_PARENT_SPAN = JaegerPropagator.DEPRECATED_PARENT_SPAN; + private static final String PROPAGATION_HEADER = JaegerPropagator.PROPAGATION_HEADER; + private static final char PROPAGATION_HEADER_DELIMITER = + JaegerPropagator.PROPAGATION_HEADER_DELIMITER; + private static final long TRACE_ID_HI = 77L; private static final long TRACE_ID_LOW = 22L; private static final String TRACE_ID = "000000000000004d0000000000000016"; @@ -72,6 +85,25 @@ private static Context withSpanContext(SpanContext spanContext, Context context) return context.with(Span.wrap(spanContext)); } + @Test + void extractWithLambdaGetter() { + Map carrier = new LinkedHashMap<>(); + carrier.put(PROPAGATION_HEADER, TRACE_ID + ":" + SPAN_ID + ":0:1"); + carrier.put(BAGGAGE_PREFIX + "key", "value"); + TextMapGetter> lambdaGetter = + (map, key) -> map == null ? null : map.get(key); + + Context extracted = jaegerPropagator.extract(Context.root(), carrier, lambdaGetter); + + assertThat(getSpanContext(extracted)) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); + assertThat(Baggage.fromContext(extracted).isEmpty()).isTrue(); + assertThat(jaegerPropagator.extract(Context.root(), Collections.emptyMap(), lambdaGetter)) + .isSameAs(Context.root()); + } + @Test void inject_invalidContext() { Map carrier = new LinkedHashMap<>(); @@ -242,6 +274,15 @@ void extract_InvalidTraceId() { verifyInvalidBehavior(invalidHeaders); } + @Test + void extract_EmptyTraceId() { + Map invalidHeaders = new LinkedHashMap<>(); + invalidHeaders.put( + PROPAGATION_HEADER, generateTraceIdHeaderValue("", SPAN_ID, DEPRECATED_PARENT_SPAN, "0")); + + verifyInvalidBehavior(invalidHeaders); + } + @Test void extract_InvalidTraceId_Size() { Map invalidHeaders = new LinkedHashMap<>(); @@ -262,6 +303,15 @@ void extract_InvalidSpanId() { verifyInvalidBehavior(invalidHeaders); } + @Test + void extract_EmptySpanId() { + Map invalidHeaders = new LinkedHashMap<>(); + invalidHeaders.put( + PROPAGATION_HEADER, generateTraceIdHeaderValue(TRACE_ID, "", DEPRECATED_PARENT_SPAN, "0")); + + verifyInvalidBehavior(invalidHeaders); + } + @Test void extract_InvalidSpanId_Size() { Map invalidHeaders = new LinkedHashMap<>(); @@ -316,6 +366,29 @@ void extract_SampledContext() { TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); } + @ParameterizedTest + @MethodSource + void extract_HexadecimalFlags(byte flags, String encodedFlags, TraceFlags expectedTraceFlags) { + Map carrier = new LinkedHashMap<>(); + JaegerSpanContext context = + new JaegerSpanContext( + TRACE_ID_HI, TRACE_ID_LOW, SPAN_ID_LONG, DEPRECATED_PARENT_SPAN_LONG, flags); + carrier.put(PROPAGATION_HEADER, TextMapCodec.contextAsString(context)); + + assertThat(carrier.get(PROPAGATION_HEADER)).endsWith(":" + encodedFlags); + assertThat(getSpanContext(jaegerPropagator.extract(Context.root(), carrier, getter))) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID, SPAN_ID, expectedTraceFlags, TraceState.getDefault())); + } + + static Stream extract_HexadecimalFlags() { + return Stream.of( + Arguments.argumentSet("sampled debug firehose", (byte) 0x0b, "b", TraceFlags.getSampled()), + Arguments.argumentSet("unsampled hex", (byte) 0x0a, "a", TraceFlags.getDefault()), + Arguments.argumentSet("two-digit hex", (byte) 0xff, "ff", TraceFlags.getSampled())); + } + @Test void extract_NotSampledContext() { Map carrier = new LinkedHashMap<>(); @@ -349,13 +422,15 @@ void extract_SampledContext_Short_TraceId() { } @Test + @SuppressWarnings("JdkObsolete") // Recommended alternative was introduced in java 10 void extract_UrlEncodedContext() throws UnsupportedEncodingException { Map carrier = new LinkedHashMap<>(); JaegerSpanContext context = new JaegerSpanContext( TRACE_ID_HI, TRACE_ID_LOW, SPAN_ID_LONG, DEPRECATED_PARENT_SPAN_LONG, (byte) 5); carrier.put( - PROPAGATION_HEADER, URLEncoder.encode(TextMapCodec.contextAsString(context), "UTF-8")); + PROPAGATION_HEADER, + URLEncoder.encode(TextMapCodec.contextAsString(context), StandardCharsets.UTF_8.name())); assertThat(getSpanContext(jaegerPropagator.extract(Context.current(), carrier, getter))) .isEqualTo( @@ -363,6 +438,18 @@ void extract_UrlEncodedContext() throws UnsupportedEncodingException { TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); } + @Test + void extract_MalformedUrlEncodedContext() { + Map carrier = new LinkedHashMap<>(); + carrier.put(PROPAGATION_HEADER, "%GG"); + + Context inputContext = Context.root(); + + Context extractedContext = jaegerPropagator.extract(inputContext, carrier, getter); + + assertThat(extractedContext).isSameAs(inputContext); + } + @Test void extract_SampledContext_withBaggage() { Map carrier = new LinkedHashMap<>(); @@ -430,6 +517,26 @@ void extract_baggageOnly_withHeader_invalid() { .isEqualTo(Baggage.empty()); } + @ParameterizedTest + @MethodSource + void extract_baggageOnly_withHeader_invalid_keepsExistingBaggage(String headerValue) { + Baggage existingBaggage = Baggage.builder().put("user", "alice").build(); + Map carrier = new LinkedHashMap<>(); + carrier.put(BAGGAGE_HEADER, headerValue); + + Context context = Context.root().with(existingBaggage); + assertThat(fromContext(jaegerPropagator.extract(context, carrier, getter))) + .isEqualTo(existingBaggage); + } + + static Stream extract_baggageOnly_withHeader_invalid_keepsExistingBaggage() { + return Stream.of( + Arguments.argumentSet("no separator", "nometa+novalue"), + Arguments.argumentSet("empty value", "user="), + Arguments.argumentSet("empty header", ""), + Arguments.argumentSet("too many separators", "a=b=c")); + } + @Test void extract_baggageOnly_withHeader_andPrefix() { Map carrier = new LinkedHashMap<>(); @@ -445,6 +552,42 @@ void extract_baggageOnly_withHeader_andPrefix() { .build()); } + @Test + void extract_baggageOnly_capitalizedHeaders() { + Map carrier = new LinkedHashMap<>(); + // Some TextMapGetters return header keys in their original case (e.g. undertow 1.7), so baggage + // matching must be case insensitive. + carrier.put(BAGGAGE_PREFIX.toUpperCase(Locale.ROOT) + "some-key", "value"); + carrier.put(BAGGAGE_HEADER.toUpperCase(Locale.ROOT), "nometa=nometa-value,meta=meta-value"); + + assertThat(fromContext(jaegerPropagator.extract(Context.current(), carrier, getter))) + .isEqualTo( + Baggage.builder() + .put("some-key", "value") + .put("nometa", "nometa-value") + .put("meta", "meta-value") + .build()); + } + + @Test + @Timeout(value = 1, unit = TimeUnit.SECONDS) + void extract_baggageHeader_largeInputIsBounded() { + // Parsing an oversized jaeger-baggage header must not allocate proportionally + // to the input. + StringBuilder header = new StringBuilder(4_000_000); + for (int i = 0; i < 1_000_000; i++) { + header.append("a=b,"); + } + Map carrier = new LinkedHashMap<>(); + carrier.put(BAGGAGE_HEADER, header.toString()); + + // Only the first accepted entry is retained (all keys are "a"); the parse must stop well + // before the end of the header. + Baggage extracted = fromContext(jaegerPropagator.extract(Context.root(), carrier, getter)); + assertThat(extracted.size()).isEqualTo(1); + assertThat(extracted.getEntryValue("a")).isEqualTo("b"); + } + @Test void extract_nullContext() { assertThat(jaegerPropagator.extract(null, Collections.emptyMap(), getter)) @@ -460,6 +603,109 @@ void extract_nullGetter() { assertThat(jaegerPropagator.extract(context, Collections.emptyMap(), null)).isSameAs(context); } + @Test + void inject_baggageLimit_maxEntries() { + Map carrier = new LinkedHashMap<>(); + jaegerPropagator.inject(Context.root().with(baggageWithEntries(0, 65)), carrier, Map::put); + long count = carrier.keySet().stream().filter(k -> k.startsWith(BAGGAGE_PREFIX)).count(); + assertThat(count).isEqualTo(64); + } + + @Test + void inject_baggageLimit_maxBytes() { + Baggage baggage = Baggage.builder().put("k", fillChars('v', 8192)).build(); + Map carrier = new LinkedHashMap<>(); + jaegerPropagator.inject(Context.root().with(baggage), carrier, Map::put); + assertThat(carrier).doesNotContainKey(BAGGAGE_PREFIX + "k"); + } + + @ParameterizedTest + @MethodSource + void extract_baggageLimit(Map carrier, Baggage expectedBaggage) { + assertThat(fromContext(jaegerPropagator.extract(Context.root(), carrier, getter))) + .isEqualTo(expectedBaggage); + } + + static Stream extract_baggageLimit() { + Map prefixCarrier = new LinkedHashMap<>(); + for (int i = 0; i < 65; i++) { + prefixCarrier.put(BAGGAGE_PREFIX + "k" + i, "v" + i); + } + StringBuilder jaegerHeader = new StringBuilder(); + for (int i = 0; i < 65; i++) { + if (i > 0) { + jaegerHeader.append(","); + } + jaegerHeader.append("k").append(i).append("=v").append(i); + } + Map headerCarrier = new LinkedHashMap<>(); + headerCarrier.put(BAGGAGE_HEADER, jaegerHeader.toString()); + Map bigValueCarrier = new LinkedHashMap<>(); + bigValueCarrier.put(BAGGAGE_PREFIX + "k", fillChars('v', 8192)); + // 64 malformed tokens exhaust the per-header parse budget, so the trailing valid entry is not + // extracted. With 63, the budget still has room for it. + Map malformedCarrier = new LinkedHashMap<>(); + malformedCarrier.put(BAGGAGE_HEADER, malformedTokens(64) + "k0=v0"); + Map malformedUnderLimitCarrier = new LinkedHashMap<>(); + malformedUnderLimitCarrier.put(BAGGAGE_HEADER, malformedTokens(63) + "k0=v0"); + // Malformed tokens consume the per-header token budget, not the remaining entry budget, so the + // trailing valid entry still fills the last of the 64 entry slots. + Map prefixThenMalformedCarrier = new LinkedHashMap<>(); + for (int i = 0; i < 63; i++) { + prefixThenMalformedCarrier.put(BAGGAGE_PREFIX + "k" + i, "v" + i); + } + prefixThenMalformedCarrier.put(BAGGAGE_HEADER, malformedTokens(1) + "k63=v63"); + return Stream.of( + Arguments.argumentSet( + "65 prefix keys truncated to 64", prefixCarrier, baggageWithEntries(0, 64)), + Arguments.argumentSet( + "65 header entries truncated to 64", headerCarrier, baggageWithEntries(0, 64)), + Arguments.argumentSet("large value exceeds byte limit", bigValueCarrier, Baggage.empty()), + Arguments.argumentSet( + "64 malformed tokens exhaust the token budget", malformedCarrier, Baggage.empty()), + Arguments.argumentSet( + "63 malformed tokens leave room for one entry", + malformedUnderLimitCarrier, + baggageWithEntries(0, 1)), + Arguments.argumentSet( + "malformed token does not consume the remaining entry budget", + prefixThenMalformedCarrier, + baggageWithEntries(0, 64))); + } + + /** Returns {@code count} malformed (no {@code =}) comma-terminated baggage tokens. */ + private static String malformedTokens(int count) { + StringBuilder header = new StringBuilder(); + for (int i = 0; i < count; i++) { + header.append("malformed").append(i).append(","); + } + return header.toString(); + } + + /** + * Builds a {@link Baggage} with entries {@code k{start}=v{start}} through {@code + * k{start+count-1}=v{start+count-1}}. + */ + private static Baggage baggageWithEntries(int start, int count) { + BaggageBuilder builder = Baggage.builder(); + for (int i = start; i < start + count; i++) { + builder.put("k" + i, "v" + i); + } + return builder.build(); + } + + /** Returns a string of {@code count} repetitions of {@code c}. */ + private static String fillChars(char c, int count) { + char[] chars = new char[count]; + Arrays.fill(chars, c); + return new String(chars); + } + + @Test + void toString_Valid() { + assertThat(jaegerPropagator.toString()).isEqualTo("JaegerPropagator"); + } + private static String generateTraceIdHeaderValue( String traceId, String spanId, char parentSpan, String sampled) { return traceId diff --git a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/OtTracePropagatorTest.java b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/OtTracePropagatorTest.java index 5c2fa5a9d4e..a230db0ea98 100644 --- a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/OtTracePropagatorTest.java +++ b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/OtTracePropagatorTest.java @@ -8,6 +8,7 @@ import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.baggage.BaggageBuilder; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; @@ -17,13 +18,20 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapSetter; +import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Locale; import java.util.Map; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +@SuppressWarnings("deprecation") class OtTracePropagatorTest { private static final String TRACE_ID = "ff000000000000000000000000000041"; @@ -31,6 +39,8 @@ class OtTracePropagatorTest { private static final String SHORT_TRACE_ID = "ff00000000000000"; private static final String SHORT_TRACE_ID_FULL = "0000000000000000ff00000000000000"; private static final String SPAN_ID = "ff00000000000041"; + private static final String SHORT_SPAN_ID = "f00000000000041"; + private static final String SHORT_SPAN_ID_FULL = "0f00000000000041"; private static final TextMapSetter> setter = Map::put; private static final TextMapGetter> getter = new TextMapGetter>() { @@ -55,6 +65,39 @@ private static Context withSpanContext(SpanContext spanContext, Context context) return context.with(Span.wrap(spanContext)); } + private static String capitalizeFirstLetter(String input, String delimiter) { + String[] words = input.split(delimiter); + + for (int i = 0; i < words.length; i++) { + String firstLetter = words[i].substring(0, 1).toUpperCase(Locale.ROOT); + String restOfWord = words[i].substring(1).toLowerCase(Locale.ROOT); + words[i] = firstLetter + restOfWord; + } + + return String.join(delimiter, words); + } + + @Test + void extractWithLambdaGetter() { + Map carrier = new LinkedHashMap<>(); + carrier.put("ot-tracer-traceid", SHORT_TRACE_ID); + carrier.put("ot-tracer-spanid", SPAN_ID); + carrier.put("ot-tracer-sampled", "true"); + carrier.put("ot-baggage-key", "value"); + TextMapGetter> lambdaGetter = + (map, key) -> map == null ? null : map.get(key); + + Context extracted = propagator.extract(Context.root(), carrier, lambdaGetter); + + assertThat(getSpanContext(extracted)) + .isEqualTo( + SpanContext.createFromRemoteParent( + SHORT_TRACE_ID_FULL, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault())); + assertThat(Baggage.fromContext(extracted).isEmpty()).isTrue(); + assertThat(propagator.extract(Context.root(), Collections.emptyMap(), lambdaGetter)) + .isSameAs(Context.root()); + } + @Test void inject_invalidContext() { Map carrier = new LinkedHashMap<>(); @@ -248,6 +291,45 @@ void extract_NotSampledContext_Short_TraceId() { SHORT_TRACE_ID_FULL, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())); } + @Test + void extract_SampledContext_Int_Short_SPanId() { + Map carrier = new LinkedHashMap<>(); + carrier.put(OtTracePropagator.TRACE_ID_HEADER, TRACE_ID); + carrier.put(OtTracePropagator.SPAN_ID_HEADER, SHORT_SPAN_ID); + carrier.put(OtTracePropagator.SAMPLED_HEADER, Common.TRUE_INT); + + assertThat(getSpanContext(propagator.extract(Context.current(), carrier, getter))) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID, SHORT_SPAN_ID_FULL, TraceFlags.getSampled(), TraceState.getDefault())); + } + + @Test + void extract_SampledContext_Bool_Short_SpanId() { + Map carrier = new LinkedHashMap<>(); + carrier.put(OtTracePropagator.TRACE_ID_HEADER, TRACE_ID); + carrier.put(OtTracePropagator.SPAN_ID_HEADER, SHORT_SPAN_ID); + carrier.put(OtTracePropagator.SAMPLED_HEADER, "true"); + + assertThat(getSpanContext(propagator.extract(Context.current(), carrier, getter))) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID, SHORT_SPAN_ID_FULL, TraceFlags.getSampled(), TraceState.getDefault())); + } + + @Test + void extract_NotSampledContext_Short_SpanId() { + Map carrier = new LinkedHashMap<>(); + carrier.put(OtTracePropagator.TRACE_ID_HEADER, TRACE_ID); + carrier.put(OtTracePropagator.SPAN_ID_HEADER, SHORT_SPAN_ID); + carrier.put(OtTracePropagator.SAMPLED_HEADER, Common.FALSE_INT); + + assertThat(getSpanContext(propagator.extract(Context.current(), carrier, getter))) + .isEqualTo( + SpanContext.createFromRemoteParent( + TRACE_ID, SHORT_SPAN_ID_FULL, TraceFlags.getDefault(), TraceState.getDefault())); + } + @Test void extract_InvalidTraceId() { Map invalidHeaders = new LinkedHashMap<>(); @@ -313,6 +395,35 @@ void extract_Baggage() { assertThat(Baggage.fromContext(context)).isEqualTo(expectedBaggage); } + @Test + void extract_Baggage_CapitalizedHeaders() { + String capitalizedBaggageHeader = + capitalizeFirstLetter(OtTracePropagator.PREFIX_BAGGAGE_HEADER + "some-key", "-"); + Map carrier = new LinkedHashMap<>(); + carrier.put(OtTracePropagator.TRACE_ID_HEADER, TRACE_ID); + carrier.put(OtTracePropagator.SPAN_ID_HEADER, SPAN_ID); + carrier.put(OtTracePropagator.SAMPLED_HEADER, Common.TRUE_INT); + carrier.put(capitalizedBaggageHeader, "value"); + + Context context = propagator.extract(Context.current(), carrier, getter); + + Baggage expectedBaggage = Baggage.builder().put("some-key", "value").build(); + assertThat(Baggage.fromContext(context)).isEqualTo(expectedBaggage); + } + + @Test + void extract_Baggage_EmptyKey() { + Map carrier = new LinkedHashMap<>(); + carrier.put(OtTracePropagator.TRACE_ID_HEADER, TRACE_ID); + carrier.put(OtTracePropagator.SPAN_ID_HEADER, SPAN_ID); + carrier.put(OtTracePropagator.SAMPLED_HEADER, Common.TRUE_INT); + carrier.put(OtTracePropagator.PREFIX_BAGGAGE_HEADER, "value"); // Not really a valid key. + + Context context = propagator.extract(Context.current(), carrier, getter); + + assertThat(Baggage.fromContext(context)).isEqualTo(Baggage.empty()); + } + @Test void extract_Baggage_InvalidContext() { Map carrier = new LinkedHashMap<>(); @@ -340,4 +451,89 @@ void extract_nullGetter() { Context.current()); assertThat(propagator.extract(context, Collections.emptyMap(), null)).isSameAs(context); } + + @Test + void inject_baggageLimit_maxEntries() { + Map carrier = new LinkedHashMap<>(); + propagator.inject( + withSpanContext( + SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()), + Context.current().with(baggageWithEntries(0, 65))), + carrier, + setter); + long count = + carrier.keySet().stream() + .filter(k -> k.startsWith(OtTracePropagator.PREFIX_BAGGAGE_HEADER)) + .count(); + assertThat(count).isEqualTo(64); + } + + @Test + void inject_baggageLimit_maxBytes() { + Baggage baggage = Baggage.builder().put("k", fillChars('v', 8192)).build(); + Map carrier = new LinkedHashMap<>(); + propagator.inject( + withSpanContext( + SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()), + Context.current().with(baggage)), + carrier, + setter); + assertThat(carrier).doesNotContainKey(OtTracePropagator.PREFIX_BAGGAGE_HEADER + "k"); + } + + @ParameterizedTest + @MethodSource + void extract_baggageLimit(Map carrier, Baggage expectedBaggage) { + assertThat(Baggage.fromContext(propagator.extract(Context.root(), carrier, getter))) + .isEqualTo(expectedBaggage); + } + + static Stream extract_baggageLimit() { + // Valid span context is required for baggage to be extracted + Map manyEntriesCarrier = carrierWithSpanContext(); + for (int i = 0; i < 65; i++) { + manyEntriesCarrier.put(OtTracePropagator.PREFIX_BAGGAGE_HEADER + "k" + i, "v" + i); + } + Map bigValueCarrier = carrierWithSpanContext(); + bigValueCarrier.put(OtTracePropagator.PREFIX_BAGGAGE_HEADER + "k", fillChars('v', 8192)); + return Stream.of( + Arguments.argumentSet( + "65 baggage keys truncated to 64", manyEntriesCarrier, baggageWithEntries(0, 64)), + Arguments.argumentSet("large value exceeds byte limit", bigValueCarrier, Baggage.empty())); + } + + /** + * Returns a carrier pre-populated with a valid span context (required for baggage extraction). + */ + private static Map carrierWithSpanContext() { + Map carrier = new LinkedHashMap<>(); + carrier.put(OtTracePropagator.TRACE_ID_HEADER, TRACE_ID_RIGHT_PART); + carrier.put(OtTracePropagator.SPAN_ID_HEADER, SPAN_ID); + carrier.put(OtTracePropagator.SAMPLED_HEADER, "true"); + return carrier; + } + + /** + * Builds a {@link Baggage} with entries {@code k{start}=v{start}} through {@code + * k{start+count-1}=v{start+count-1}}. + */ + private static Baggage baggageWithEntries(int start, int count) { + BaggageBuilder builder = Baggage.builder(); + for (int i = start; i < start + count; i++) { + builder.put("k" + i, "v" + i); + } + return builder.build(); + } + + /** Returns a string of {@code count} repetitions of {@code c}. */ + private static String fillChars(char c, int count) { + char[] chars = new char[count]; + Arrays.fill(chars, c); + return new String(chars); + } + + @Test + void toString_Valid() { + assertThat(propagator.toString()).isEqualTo("OtTracePropagator"); + } } diff --git a/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/StringUtilsTest.java b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/StringUtilsTest.java new file mode 100644 index 00000000000..902a3561f6c --- /dev/null +++ b/extensions/trace-propagators/src/test/java/io/opentelemetry/extension/trace/propagation/StringUtilsTest.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.extension.trace.propagation; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class StringUtilsTest { + + @Test + void padLeft() { + assertThat(StringUtils.padLeft("value", 10)).isEqualTo("00000value"); + } + + @Test + void padLeft_length_does_not_exceed_minimum() { + assertThat(StringUtils.padLeft("value", 3)).isEqualTo("value"); + assertThat(StringUtils.padLeft("value", -10)).isEqualTo("value"); + assertThat(StringUtils.padLeft("value", 0)).isEqualTo("value"); + } + + @Test + void padLeft_throws_for_null_value() { + assertThatThrownBy(() -> StringUtils.padLeft(null, 10)) + .isInstanceOf(NullPointerException.class); + } +} diff --git a/gradle.properties b/gradle.properties index 140d672d3b9..0d9cc9c5012 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,18 +1,17 @@ org.gradle.parallel=true org.gradle.caching=true +org.gradle.configuration-cache=true +org.gradle.configuration-cache.parallel=true org.gradle.priority=low # Gradle default is 256m which causes issues with our build - https://docs.gradle.org/current/userguide/build_environment.html#sec:configuring_jvm_memory -# Also workaround https://github.com/diffplug/spotless/issues/834 -org.gradle.jvmargs=-XX:MaxMetaspaceSize=512m \ - --add-exports jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED \ - --add-exports jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED \ - --add-exports=jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED \ - --add-exports=jdk.compiler/com.sun.tools.javac.model=ALL-UNNAMED \ - --add-exports jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED \ - --add-exports=jdk.compiler/com.sun.tools.javac.processing=ALL-UNNAMED \ - --add-exports jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED \ - --add-exports jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED \ - --add-opens=jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED \ - --add-opens=jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED +org.gradle.jvmargs=-XX:MaxMetaspaceSize=512m + +# Try to reduce CI failures due to maven central flakiness +# in particular this has been a problem for maven-metadata.xml files, which are TTL'd quickly out of +# the gradle cache since they contain the latest versions available in maven central +systemProp.org.gradle.internal.http.connectionTimeout=120000 +systemProp.org.gradle.internal.http.socketTimeout=120000 +systemProp.org.gradle.internal.repository.max.retries=10 +systemProp.org.gradle.internal.repository.initial.backoff=500 diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar index 7454180f2ae..51cbd2a6f81 100644 Binary files a/gradle/wrapper/gradle-wrapper.jar and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 5c51a4acc9d..0bb71f34684 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,10 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionSha256Sum=29e49b10984e585d8118b7d0bc452f944e386458df27371b49b4ac1dec4b7fda -distributionUrl=https\://services.gradle.org/distributions/gradle-7.4.2-bin.zip +distributionSha256Sum=0b00b0ffe07c4d4789c12d4935a44a7057d55774b7540bd4a3f76f336deb177a +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip +networkTimeout=10000 +retries=0 +retryBackOffMs=500 +validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew index 1b6c787337f..249efbb032c 100755 --- a/gradlew +++ b/gradlew @@ -1,7 +1,7 @@ #!/bin/sh # -# Copyright Β© 2015-2021 the original authors. +# Copyright Β© 2015 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -15,10 +15,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # +# SPDX-License-Identifier: Apache-2.0 +# ############################################################################## # -# Gradle start up script for POSIX generated by Gradle. +# gradlew start up script for POSIX generated by Gradle. # # Important for running: # @@ -27,7 +29,7 @@ # bash, then to run this script, type that shell name before the whole # command line, like: # -# ksh Gradle +# ksh gradlew # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: @@ -55,7 +57,7 @@ # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template -# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# https://github.com/gradle/gradle/blob/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. @@ -80,13 +82,11 @@ do esac done -APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit - -APP_NAME="Gradle" +# This is normally unused +# shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} - -# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. -DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum @@ -114,7 +114,6 @@ case "$( uname )" in #( NONSTOP* ) nonstop=true ;; esac -CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. @@ -133,22 +132,29 @@ location of your Java installation." fi else JAVACMD=java - which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." + fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac @@ -165,7 +171,6 @@ fi # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) - CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) @@ -193,18 +198,27 @@ if "$cygwin" || "$msys" ; then done fi -# Collect all arguments for the java command; -# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of -# shell script including quotes and variable substitutions, so put them in -# double quotes to make sure that they get re-expanded; and -# * put everything else in single quotes, so that it's not re-expanded. + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ - -classpath "$CLASSPATH" \ - org.gradle.wrapper.GradleWrapperMain \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ "$@" +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. diff --git a/gradlew.bat b/gradlew.bat index 107acd32c4e..3185a43f78f 100644 --- a/gradlew.bat +++ b/gradlew.bat @@ -13,19 +13,49 @@ @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem -@rem Gradle startup script for Windows +@rem gradlew startup script for Windows @rem @rem ########################################################################## -@rem Set local scope for the variables with windows NT shell -if "%OS%"=="Windows_NT" setlocal +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +@rem Catch executions from older scripts and ensure they exit cleanly. +@rem This can be removed once we can be reasonably confident that few people +@rem will be migrating directly to this new wrapper. +goto afterSafetyNet +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +goto exitWithErrorLevel +:afterSafetyNet set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,15 +70,16 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute -echo. -echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% @@ -56,34 +87,26 @@ set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute -echo. -echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% -echo. -echo Please set the JAVA_HOME variable in your environment to match the -echo location of your Java installation. +1>&2 echo. +1>&2 echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +1>&2 echo. +1>&2 echo Please set the JAVA_HOME variable in your environment to match the +1>&2 echo location of your Java installation. -goto fail +"%COMSPEC%" /c exit 1 +goto exitWithErrorLevel :execute @rem Setup the command line -set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar - - -@rem Execute Gradle -"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* - -:end -@rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd -:fail -rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of -rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 -:mainEnd -if "%OS%"=="Windows_NT" endlocal +@rem Execute gradlew +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel & goto exitWithErrorLevel -:omega +@rem This label must not be changed. We rely on old scripts being able to jump to this point. +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/integration-tests/README.md b/integration-tests/README.md deleted file mode 100644 index 0632073ccd5..00000000000 --- a/integration-tests/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# OpenTelemetry Integration Tests - - -* Integration Test code lives here diff --git a/integration-tests/build.gradle.kts b/integration-tests/build.gradle.kts index 90dae0aaf1a..4f6916740e3 100644 --- a/integration-tests/build.gradle.kts +++ b/integration-tests/build.gradle.kts @@ -4,6 +4,8 @@ plugins { description = "OpenTelemetry Integration Tests" otelJava.moduleName.set("io.opentelemetry.integration.tests") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) dependencies { testImplementation(project(":sdk:all")) @@ -11,6 +13,12 @@ dependencies { testImplementation(project(":extensions:trace-propagators")) testImplementation("com.linecorp.armeria:armeria-junit5") + testImplementation("io.github.crac:org-crac") testImplementation("org.junit.jupiter:junit-jupiter-params") - testImplementation("org.testcontainers:junit-jupiter") + testImplementation("org.testcontainers:testcontainers-junit-jupiter") +} + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false } diff --git a/integration-tests/graal-incubating/build.gradle.kts b/integration-tests/graal-incubating/build.gradle.kts new file mode 100644 index 00000000000..d669cb3b773 --- /dev/null +++ b/integration-tests/graal-incubating/build.gradle.kts @@ -0,0 +1,48 @@ +import org.gradle.api.JavaVersion +plugins { + id("otel.java-conventions") + id("org.graalvm.buildtools.native") +} + +description = "OpenTelemetry Graal Integration Tests (Incubating)" +otelJava.moduleName.set("io.opentelemetry.graal.integration.tests.incubating") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) +otelJava.minJavaVersionSupported.set(JavaVersion.VERSION_17) + +sourceSets { + main { + // We need to ensure that we have the shadowed classes on the classpath, without this + // we will get the <:sdk:trace-shaded-deps> classes only, without the shadowed ones + val traceShadedDeps = project(":sdk:trace-shaded-deps") + output.dir(traceShadedDeps.file("build/extracted/shadow"), "builtBy" to ":sdk:trace-shaded-deps:extractShadowJar") + } +} + +dependencies { + implementation(project(":sdk:all")) + implementation(project(":sdk:trace-shaded-deps")) + implementation(project(":sdk:testing")) + implementation(project(":exporters:otlp:all")) + implementation(project(":api:incubator")) + implementation(project(":sdk-extensions:declarative-config")) +} + +// org.graalvm.buildtools.native plugin requires java 17+ as of version 0.11.0 +// https://github.com/graalvm/native-build-tools/blob/master/docs/src/docs/asciidoc/index.adoc + +graalvmNative { + binaries { + named("test") { + // JUnit initialization is (mostly) handled automatically by the GraalVM plugin 0.11+ + // Required as of junit 5.14.1 + buildArgs.add("--initialize-at-build-time=org.junit.jupiter.engine.discovery.MethodSegmentResolver") + } + } + toolchainDetection.set(false) + // Disable metadata repository to work around configuration cache incompatibility + // https://github.com/graalvm/native-build-tools/issues/477 + metadataRepository { + enabled.set(false) + } +} diff --git a/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java b/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java new file mode 100644 index 00000000000..40c278d8646 --- /dev/null +++ b/integration-tests/graal-incubating/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingApiTests.java @@ -0,0 +1,130 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtests.graal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.incubator.logs.ExtendedLogger; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounterBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounter; +import io.opentelemetry.api.incubator.trace.ExtendedTracer; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class IncubatingApiTests { + @Test + void incubatingApiIsLoadedViaReflection() { + assertThat(LoggerProvider.noop().get("test")).isInstanceOf(ExtendedLogger.class); + assertThat(TracerProvider.noop().get("test")).isInstanceOf(ExtendedTracer.class); + assertThat(MeterProvider.noop().get("test").counterBuilder("test")) + .isInstanceOf(ExtendedLongCounterBuilder.class); + } + + @Test + void incubatingLogSdk() { + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + + ExtendedLogger logger = (ExtendedLogger) loggerProvider.get("logger"); + logger.isEnabled(Severity.INFO); + logger.logRecordBuilder().setSeverity(Severity.INFO).setBody("message").emit(); + } + + @Test + void incubatingTraceSdk() { + InMemorySpanExporter exporter = InMemorySpanExporter.create(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)).build(); + + ExtendedTracer tracer = (ExtendedTracer) tracerProvider.get("tracer"); + tracer.isEnabled(); + tracer.spanBuilder("span").startAndRun(() -> {}); + } + + @Test + void incubatingMetricSdk() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Meter meter = meterProvider.get("meter"); + + ExtendedLongCounter longCounter = + (ExtendedLongCounter) meter.counterBuilder("longCounter").build(); + longCounter.isEnabled(); + ExtendedDoubleCounter doubleCounter = + (ExtendedDoubleCounter) meter.counterBuilder("doubleCounter").ofDoubles().build(); + doubleCounter.isEnabled(); + ExtendedLongUpDownCounter longUpDownCounter = + (ExtendedLongUpDownCounter) meter.upDownCounterBuilder("longUpDownCounter").build(); + longUpDownCounter.isEnabled(); + ExtendedDoubleUpDownCounter doubleUpDownCounter = + (ExtendedDoubleUpDownCounter) + meter.upDownCounterBuilder("doubleUpDownCounter").ofDoubles().build(); + doubleUpDownCounter.isEnabled(); + ExtendedDoubleHistogram doubleHistogram = + (ExtendedDoubleHistogram) meter.histogramBuilder("doubleHistogram").build(); + doubleHistogram.isEnabled(); + ExtendedLongHistogram longHistogram = + (ExtendedLongHistogram) meter.histogramBuilder("longHistogram").ofLongs().build(); + longHistogram.isEnabled(); + ExtendedDoubleGauge doubleGauge = + (ExtendedDoubleGauge) meter.gaugeBuilder("doubleGauge").build(); + doubleGauge.isEnabled(); + ExtendedLongGauge longGauge = + (ExtendedLongGauge) meter.gaugeBuilder("longGauge").ofLongs().build(); + longGauge.isEnabled(); + } + + @Test + void parseDeclarativeConfiguration() { + // make sure to test enums too: "instrument_type: histogram" + String string = + """ + file_format: "1.2" + tracer_provider: + processors: + - batch: + exporter: + console: {} + meter_provider: + views: + - selector: + instrument_type: histogram + stream: + aggregation: + drop: {} + """; + // should not throw + DeclarativeConfiguration.parse( + new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/integration-tests/graal/build.gradle.kts b/integration-tests/graal/build.gradle.kts new file mode 100644 index 00000000000..5d8bde940bd --- /dev/null +++ b/integration-tests/graal/build.gradle.kts @@ -0,0 +1,46 @@ +import org.gradle.api.JavaVersion + +plugins { + id("otel.java-conventions") + id("org.graalvm.buildtools.native") +} + +description = "OpenTelemetry Graal Integration Tests" +otelJava.moduleName.set("io.opentelemetry.graal.integration.tests") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) +otelJava.minJavaVersionSupported.set(JavaVersion.VERSION_17) + +sourceSets { + main { + // We need to ensure that we have the shadowed classes on the classpath, without this + // we will get the <:sdk:trace-shaded-deps> classes only, without the shadowed ones + val traceShadedDeps = project(":sdk:trace-shaded-deps") + output.dir(traceShadedDeps.file("build/extracted/shadow"), "builtBy" to ":sdk:trace-shaded-deps:extractShadowJar") + } +} + +dependencies { + implementation(project(":sdk:all")) + implementation(project(":sdk:trace-shaded-deps")) + implementation(project(":exporters:otlp:all")) +} + +// org.graalvm.buildtools.native plugin requires java 17+ as of version 0.11.0 +// https://github.com/graalvm/native-build-tools/blob/master/docs/src/docs/asciidoc/index.adoc + +graalvmNative { + binaries { + named("test") { + // JUnit initialization is (mostly) handled automatically by the GraalVM plugin 0.11+ + // Required as of junit 5.14.1 + buildArgs.add("--initialize-at-build-time=org.junit.jupiter.engine.discovery.MethodSegmentResolver") + } + } + toolchainDetection.set(false) + // Disable metadata repository to work around configuration cache incompatibility + // https://github.com/graalvm/native-build-tools/issues/477 + metadataRepository { + enabled.set(false) + } +} diff --git a/integration-tests/graal/src/main/resources/simplelogger.properties b/integration-tests/graal/src/main/resources/simplelogger.properties new file mode 100644 index 00000000000..a6233fa3461 --- /dev/null +++ b/integration-tests/graal/src/main/resources/simplelogger.properties @@ -0,0 +1,2 @@ +org.slf4j.simpleLogger.defaultLogLevel=info +org.slf4j.simpleLogger.log.org.eclipse.jetty=warn diff --git a/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingNotFoundApiTests.java b/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingNotFoundApiTests.java new file mode 100644 index 00000000000..0a840a68d3b --- /dev/null +++ b/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/IncubatingNotFoundApiTests.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtests.graal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.TracerProvider; +import org.junit.jupiter.api.Test; + +class IncubatingNotFoundApiTests { + @Test + void incubatingApiIsNotFoundViaReflection() { + // The graal module deliberately excludes :api:incubator, so the noop instances must come from + // the stable api packages, not io.opentelemetry.api.incubator.*. An isInstanceOf check against + // the stable types cannot detect a regression here because the incubator Extended* types + // subtype the stable types; assert on the runtime class package instead, since the Extended* + // types are not on this module's classpath to reference directly. + assertThat(LoggerProvider.noop().get("test").getClass().getName()) + .doesNotStartWith("io.opentelemetry.api.incubator."); + assertThat(TracerProvider.noop().get("test").getClass().getName()) + .doesNotStartWith("io.opentelemetry.api.incubator."); + assertThat(MeterProvider.noop().get("test").counterBuilder("test").getClass().getName()) + .doesNotStartWith("io.opentelemetry.api.incubator."); + } +} diff --git a/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/InitializeSdkTest.java b/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/InitializeSdkTest.java new file mode 100644 index 00000000000..8826db405de --- /dev/null +++ b/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/InitializeSdkTest.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtests.graal; + +import static org.assertj.core.api.Assertions.assertThatCode; + +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import org.junit.jupiter.api.Test; + +class InitializeSdkTest { + + @Test + void initializeSdk() { + assertThatCode( + () -> { + OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor( + BatchSpanProcessor.builder(OtlpGrpcSpanExporter.getDefault()) + .build()) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.create(OtlpGrpcMetricExporter.getDefault())) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + OtlpGrpcLogRecordExporter.getDefault()) + .build()) + .build()) + .build(); + sdk.close(); + }) + .doesNotThrowAnyException(); + } +} diff --git a/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/JcToolsTest.java b/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/JcToolsTest.java new file mode 100644 index 00000000000..55363a0487f --- /dev/null +++ b/integration-tests/graal/src/test/java/io/opentelemetry/integrationtests/graal/JcToolsTest.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtests.graal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.trace.internal.JcTools; +import java.util.Queue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledInNativeImage; + +class JcToolsTest { + + @Test + @EnabledInNativeImage + void insert_oneElementToTheQueue() { + Queue objects = JcTools.newFixedSizeQueue(10); + + objects.add(new Object()); + + assertThat(objects).hasSize(1); + } +} diff --git a/integration-tests/osgi/build.gradle.kts b/integration-tests/osgi/build.gradle.kts new file mode 100644 index 00000000000..3db229d7b2c --- /dev/null +++ b/integration-tests/osgi/build.gradle.kts @@ -0,0 +1,334 @@ +import aQute.bnd.gradle.Bundle +import aQute.bnd.gradle.Resolve +import aQute.bnd.gradle.TestOSGi + +plugins { + id("otel.java-conventions") +} + +description = "OpenTelemetry OSGi Integration Tests" +otelJava.moduleName.set("io.opentelemetry.integration.tests.osgi") +otelJava.requireSuppressWarningsExplanation.set(false) + +// For similar test examples see: +// https://github.com/micrometer-metrics/micrometer/tree/main/micrometer-osgi-test +// https://github.com/eclipse-osgi-technology/osgi-test/tree/main/examples/osgi-test-example-gradle + +// OSGi test infrastructure shared across all suites. +// Each suite's source set automatically inherits these via registerOsgiSuite(). +val osgiInfraImplementation: Configuration = configurations.create("osgiInfraImplementation") { + isCanBeResolved = false + isCanBeConsumed = false +} +val osgiInfraRuntimeOnly: Configuration = configurations.create("osgiInfraRuntimeOnly") { + isCanBeResolved = false + isCanBeConsumed = false +} + +dependencies { + osgiInfraImplementation("org.assertj:assertj-core") + osgiInfraImplementation("org.junit.jupiter:junit-jupiter") + osgiInfraImplementation("org.osgi:org.osgi.test.junit5") + osgiInfraImplementation("org.osgi:org.osgi.test.assertj.framework") + osgiInfraRuntimeOnly("org.junit.platform:junit-platform-launcher") + osgiInfraRuntimeOnly("org.apache.felix:org.apache.felix.framework") + osgiInfraRuntimeOnly("org.apache.aries.spifly:org.apache.aries.spifly.dynamic.bundle") +} + +/** Typed dependency scope for an OSGi test suite, avoiding stringly-typed invoke() calls. */ +class OsgiSuiteDependencies(private val sourceSet: SourceSet, private val handler: DependencyHandler) { + fun implementation(notation: Any) = handler.add(sourceSet.implementationConfigurationName, notation) + fun runtimeOnly(notation: Any) = handler.add(sourceSet.runtimeOnlyConfigurationName, notation) +} + +/** + * Registers tasks for an OSGi test suite (TestingBundle, GenerateBndrun, Resolve, testOSGi) + * with a corresponding source set under src/test/java. + * + * @param extraRunrequires `bnd.identity` entries added to `-runrequires` to force bundles into the + * Felix runtime that the BND resolver won't pull in automatically. + * @param extraRunsystempackages Package prefixes of non-OSGi classpath libraries to expose via + * `-runsystempackages`. Versions are resolved dynamically from the runtime classpath. + * @param minJavaVersion If set, skips the suite when `testJavaVersion` is below this value and + * targets this version on the runtime classpath for dependency variant selection. + */ +fun registerOsgiSuite( + suiteName: String, + extraRunrequires: List = emptyList(), + extraRunsystempackages: List = emptyList(), + // SPI types that the testing bundle provides via META-INF/services (noop test implementations). + // Generates Provide-Capability + Require-Capability registrar so SPI Fly picks them up. + serviceLoaderProvides: List = emptyList(), + minJavaVersion: Int? = null, + configureDependencies: OsgiSuiteDependencies.() -> Unit = {} +): TaskProvider { + val sourceSet = sourceSets.create("test${suiteName.replaceFirstChar { it.uppercase() }}") + OsgiSuiteDependencies(sourceSet, dependencies).configureDependencies() + + // Inherit shared OSGi test infrastructure + configurations[sourceSet.implementationConfigurationName].extendsFrom(osgiInfraImplementation) + configurations[sourceSet.runtimeOnlyConfigurationName].extendsFrom(osgiInfraRuntimeOnly) + // osgi.core is compile-only (provided by the OSGi container at runtime). extendsFrom does not + // propagate to custom source set compile classpaths, so we add it directly. + dependencies.add(sourceSet.compileOnlyConfigurationName, "org.osgi:osgi.core") + + if (minJavaVersion != null) { + configurations[sourceSet.runtimeClasspathConfigurationName].attributes { + attribute(TargetJvmVersion.TARGET_JVM_VERSION_ATTRIBUTE, minJavaVersion) + } + } + + val bsn = "opentelemetry-osgi-testing-$suiteName" + + val bundleTask = tasks.register("${suiteName}TestingBundle") { + archiveClassifier.set("testing-$suiteName") + from(sourceSet.output) + bundle { + // The Bundle task uses compileClasspath by default for BND analysis (e.g. resolving the + // @Testable annotation to populate Test-Cases). Without this, testImplementation dependencies + // like junit-jupiter are invisible to BND, causing Test-Cases to be empty and 0 tests to run. + classpath(sourceSet.runtimeClasspath) + val bndArgs = mutableListOf( + "Bundle-SymbolicName: $bsn", + "Test-Cases: \${classes;HIERARCHY_INDIRECTLY_ANNOTATED;org.junit.platform.commons.annotation.Testable;CONCRETE}" + ) + if (serviceLoaderProvides.isNotEmpty()) { + bndArgs.add("Provide-Capability: ${serviceLoaderProvides.joinToString(",") { "osgi.serviceloader;osgi.serviceloader=\"$it\"" }}") + bndArgs.add("Require-Capability: osgi.extender;filter:=\"(osgi.extender=osgi.serviceloader.registrar)\"") + } + bnd(*bndArgs.toTypedArray()) + } + } + + val runee = "JavaSE-${java.toolchain.languageVersion.get()}" + val inputBndrun = layout.buildDirectory.file("bndrun/$suiteName.bndrun") + // Suppresses noisy INFO logs from Apache Aries SPI Fly's BaseActivator (one line per SPI + // provider registration per bundle). Passed to the forked test JVM via bndrun's -runvm. + val loggingConfig = layout.projectDirectory.file("logging.properties").asFile + val generateBndrunTask = tasks.register("${suiteName}GenerateBndrun") { + inputs.property("bsn", bsn) + inputs.property("runee", runee) + inputs.property("extraRunrequires", extraRunrequires) + inputs.file(loggingConfig) + outputs.file(inputBndrun) + doLast { + val extraEntries = extraRunrequires.joinToString("") { ",\\\n| bnd.identity;id='$it'" } + inputBndrun.get().asFile.apply { parentFile.mkdirs() }.writeText( + """ + |-tester: biz.aQute.tester.junit-platform + |-runfw: org.apache.felix.framework + |-runee: $runee + |-runvm: --sun-misc-unsafe-memory-access=allow, -Djava.util.logging.config.file="${loggingConfig.absolutePath}" + | + |-runrequires: \ + | bnd.identity;id='$bsn',\ + | bnd.identity;id='junit-jupiter-engine',\ + | bnd.identity;id='junit-platform-launcher'$extraEntries + """.trimMargin() + ) + } + } + + val resolvedBndrun = layout.buildDirectory.file("$suiteName.bndrun") + + val resolveTask = tasks.register("${suiteName}Resolve") { + dependsOn(bundleTask, generateBndrunTask) + description = "Resolve $suiteName OSGi suite" + group = JavaBasePlugin.VERIFICATION_GROUP + bndrun = inputBndrun.get().asFile + outputBndrun = resolvedBndrun + bundles = files(sourceSet.runtimeClasspath, bundleTask.get().archiveFile) + // The generated output embeds an absolute path to the source bndrun, making it unsafe to share + // across machines or worktrees via the build cache. + outputs.cacheIf { false } + if (extraRunsystempackages.isNotEmpty()) { + // Compute runpath/runsystempackages content here (at task registration / configuration time) + // so the doLast closure only captures serializable types (String, RegularFileProperty). + // Capturing SourceSet or the build script's `configurations` property in a doLast is not + // supported by Gradle's configuration cache. + // + // BND identifies non-OSGi JARs by Maven group ID (e.g. OkHttp β†’ "com.squareup.okhttp3"). + // Exception: JARs with no manifest (e.g. Kotlin stdlib) are indexed by artifact name + // normalized to dot notation ("kotlin-stdlib" β†’ "kotlin.stdlib") at version 0.0.0. + // Heuristic: JetBrains artifacts lack OSGi manifests; broaden if other deps behave the same. + fun bndCoordinate(a: org.gradle.api.artifacts.ResolvedArtifact) = if (a.moduleVersion.id.group.startsWith("org.jetbrains")) { + "${a.name.replace('-', '.')};version=0.0.0" + } else { + "${a.moduleVersion.id.group};version=${a.moduleVersion.id.version}" + } + + val resolvedArtifacts = project.configurations[sourceSet.runtimeClasspathConfigurationName] + .resolvedConfiguration.resolvedArtifacts + + val runpathCoords = mutableListOf() + val systemPackageSpecs = mutableListOf() + + for (prefix in extraRunsystempackages) { + val normalizedPrefix = prefix.trimEnd { it.isDigit() }.lowercase() + val matches = resolvedArtifacts.filter { it.name.lowercase().startsWith(normalizedPrefix) } + for (artifact in matches) { + // Export the package at the artifact's actual version; the sender bundle's optional + // Import-Package range must include this version (managed in dependencyManagement). + systemPackageSpecs += "$prefix;version=${artifact.moduleVersion.id.version}" + runpathCoords += bndCoordinate(artifact) + // Kotlin-based libraries (e.g. OkHttp) also need Kotlin stdlib on the framework classpath + if (!artifact.moduleVersion.id.group.startsWith("org.jetbrains")) { + resolvedArtifacts.filter { it.name.startsWith("kotlin-stdlib") } + .forEach { runpathCoords += bndCoordinate(it) } + } + } + } + + // Pre-compute the complete string to append; doLast only captures this String value. + val appendContent = buildString { + val distinctRunpath = runpathCoords.distinct() + if (distinctRunpath.isNotEmpty()) append("\n-runpath: ${distinctRunpath.joinToString(", ")}") + append("\n-runsystempackages: ${systemPackageSpecs.distinct().joinToString(", ")}\n") + } + inputs.property("extraRunsystempackages", extraRunsystempackages) + inputs.property("appendContent", appendContent) + + doLast { + resolvedBndrun.get().asFile.appendText(appendContent) + } + } + } + + return tasks.register("testOSGi${suiteName.replaceFirstChar { it.uppercase() }}") { + description = "OSGi Test $suiteName.bndrun" + group = JavaBasePlugin.VERIFICATION_GROUP + bndrun = resolveTask.flatMap { it.outputBndrun } + bundles = files(sourceSet.runtimeClasspath, bundleTask.get().archiveFile) + if (minJavaVersion != null) { + val testJavaVersion = project.findProperty("testJavaVersion") as String? + enabled = testJavaVersion == null || testJavaVersion!!.toInt() >= minJavaVersion + } + // BND reports success when zero tests ran (e.g. if bundles failed to start). Fail explicitly. + val testResultsDir = layout.buildDirectory.dir("test-results/$name") + doLast { + check(testResultsDir.get().asFile.listFiles()?.isNotEmpty() == true) { + "No OSGi test results found for suite '$suiteName' β€” bundles may have failed to start. Check the output above." + } + } + } +} + +// Testing the "kitchen sink" hides OSGi configuration issues. For example, opentelemetry-api has +// optional dependencies on :sdk-extensions:autoconfigure and :api:incubator. If we only test a +// bundle which includes those, then mask the fact that OSGi fails when using a bundle without those +// until opentelemetry-api OSGi configuration is updated to indicate that they are optional. + +// Suite: sdk β€” exercises core SDK OSGi metadata in isolation +val sdkSuiteTask = registerOsgiSuite("sdk") { + implementation(project(":sdk:all")) +} + +// OTLP exporter suites. Each suite uses a specific sender implementation and documents exactly +// which system packages (if any) must be exposed for the sender to function in OSGi. + +// Suite: OTLP HTTP via JDK sender β€” Java 11+, no non-OSGi system packages required. +// The JDK sender uses java.net.http.HttpClient which is part of the OSGi system bundle. +val otlpHttpJdkSuiteTask = registerOsgiSuite( + "otlpHttpJdk", + extraRunrequires = listOf("opentelemetry-exporter-sender-jdk"), + minJavaVersion = 11, +) { + implementation(project(":sdk:all")) + implementation(project(":exporters:otlp:all")) + runtimeOnly(project(":exporters:sender:jdk")) +} + +// okhttp3 and okio are not OSGi bundles; they must be exposed via -runsystempackages. +val otlpHttpOkHttpSuiteTask = registerOsgiSuite( + "otlpHttpOkHttp", + extraRunrequires = listOf("opentelemetry-exporter-sender-okhttp"), + extraRunsystempackages = listOf("okhttp3", "okio"), +) { + implementation(project(":sdk:all")) + implementation(project(":exporters:otlp:all")) +} + +// okhttp3 and okio are not OSGi bundles; they must be exposed via -runsystempackages. +val otlpGrpcOkHttpSuiteTask = registerOsgiSuite( + "otlpGrpcOkHttp", + extraRunrequires = listOf("opentelemetry-exporter-sender-okhttp"), + extraRunsystempackages = listOf("okhttp3", "okio"), +) { + implementation(project(":sdk:all")) + implementation(project(":exporters:otlp:all")) +} + +// Autoconfigure suites. + +// Suite: autoconfigure with OTLP + JDK sender. Exercises the full SPI loading chain across all +// SPI types. +val autoconfigureSuiteTask = registerOsgiSuite( + "autoconfigure", + extraRunrequires = listOf( + "opentelemetry-exporter-sender-jdk", + "opentelemetry-exporter-otlp", + "opentelemetry-extension-trace-propagators", + ), + // Some SPIs have implementations in project modules. Others do not. To verify the ones without implementation, we provide noop implementations here. + serviceLoaderProvides = listOf( + "io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider", + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider", + "io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider", + ), + minJavaVersion = 11, +) { + implementation(project(":sdk:all")) + implementation(project(":sdk-extensions:autoconfigure")) + implementation(project(":exporters:otlp:all")) + implementation(project(":extensions:trace-propagators")) + runtimeOnly(project(":exporters:sender:jdk")) +} + +// Suite: autoconfigure + declarative-config. Same as above but with declarative-config on the +// classpath, additionally exercising its SnakeYAML parser and Jackson mapper OSGi metadata. +val autoconfigureDeclarativeConfigSuiteTask = registerOsgiSuite( + "autoconfigureDeclarativeConfig", + extraRunrequires = listOf( + "opentelemetry-exporter-sender-jdk", + "opentelemetry-exporter-otlp", + "opentelemetry-extension-trace-propagators", + "opentelemetry-sdk-extension-declarative-config", + "opentelemetry-sdk-extension-declarative-config-jackson2", + "opentelemetry-sdk-extension-declarative-config-snakeyaml-engine2", + ), + serviceLoaderProvides = listOf( + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider", + ), + minJavaVersion = 11, +) { + implementation(project(":sdk:all")) + implementation(project(":sdk-extensions:autoconfigure")) + implementation(project(":sdk-extensions:declarative-config")) + implementation(project(":exporters:otlp:all")) + implementation(project(":extensions:trace-propagators")) + runtimeOnly(project(":exporters:sender:jdk")) +} + +tasks { + jar { + enabled = false + } + test { + // We need to replace junit testing with the testOSGi tasks, so we clear test actions and add + // dependencies on all suite tasks. As a result, running :test runs all OSGi suites. + actions.clear() + dependsOn( + sdkSuiteTask, + otlpHttpJdkSuiteTask, + otlpHttpOkHttpSuiteTask, + otlpGrpcOkHttpSuiteTask, + autoconfigureSuiteTask, + autoconfigureDeclarativeConfigSuiteTask + ) + } +} + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false +} diff --git a/integration-tests/osgi/logging.properties b/integration-tests/osgi/logging.properties new file mode 100644 index 00000000000..e10e58db7ec --- /dev/null +++ b/integration-tests/osgi/logging.properties @@ -0,0 +1,3 @@ +# Suppress noisy INFO logs from Apache Aries SPI Fly which logs a line for every SPI provider it +# registers per bundle. These are emitted via java.util.logging. +org.apache.aries.spifly.level = WARNING diff --git a/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/AutoconfigureTest.java b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/AutoconfigureTest.java new file mode 100644 index 00000000000..c63f5af3ffc --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/AutoconfigureTest.java @@ -0,0 +1,115 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.extension.trace.propagation.B3Propagator; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.ServiceInstanceIdResourceProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.osgi.test.junit5.context.BundleContextExtension; + +/** Verifies autoconfigure works in OSGi. */ +@ExtendWith(BundleContextExtension.class) +public class AutoconfigureTest { + + @Test + void autoConfiguredSdkInitializes() { + AutoConfiguredOpenTelemetrySdk autoConfigured = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(AutoconfigureTest::config) + .build(); + + // The component loader autoconfigure uses: autoconfigure bundle's classloader. + ComponentLoader autoConfigureLoader = + ComponentLoader.forClassLoader(AutoConfiguredOpenTelemetrySdk.class.getClassLoader()); + + // ServiceInstanceIdResourceProvider's UUID is static, so expected and actual match. + Resource resource = + Resource.getDefault() + .merge( + new ServiceInstanceIdResourceProvider() + .createResource(DefaultConfigProperties.createFromMap(Collections.emptyMap()))) + .merge( + Resource.create( + Attributes.of( + AttributeKey.stringKey("test.customizer"), "test-osgi-customizer"))); + OpenTelemetrySdk expected = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .setResource(resource) + .setSampler(new TestSamplerProvider.NoopSampler()) + .addSpanProcessor( + BatchSpanProcessor.builder( + OtlpHttpSpanExporter.builder() + .setComponentLoader(autoConfigureLoader) + .build()) + .build()) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .setResource(resource) + .registerMetricReader(new TestMetricReaderProvider.NoopMetricReader()) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .setResource(resource) + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + OtlpHttpLogRecordExporter.builder() + .setComponentLoader(autoConfigureLoader) + .build()) + .build()) + .build()) + .setPropagators( + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + W3CBaggagePropagator.getInstance(), + B3Propagator.injectingSingleHeader()))) + .build(); + try { + assertThat(autoConfigured.getOpenTelemetrySdk().toString()).isEqualTo(expected.toString()); + } finally { + autoConfigured.getOpenTelemetrySdk().close(); + expected.close(); + } + } + + private static Map config() { + Map props = new HashMap<>(); + props.put("otel.traces.exporter", "otlp"); + props.put("otel.metrics.exporter", "test-noop-reader"); + props.put("otel.logs.exporter", "otlp"); + props.put("otel.exporter.otlp.protocol", "http/protobuf"); + props.put("otel.propagators", "tracecontext,baggage,b3"); + props.put("otel.traces.sampler", "test-noop"); + return props; + } +} diff --git a/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java new file mode 100644 index 00000000000..b742aceeda9 --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestAutoConfigurationCustomizerProvider.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class TestAutoConfigurationCustomizerProvider + implements AutoConfigurationCustomizerProvider { + + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + autoConfiguration.addResourceCustomizer((resource, config) -> + resource.merge( + Resource.create( + Attributes.of(AttributeKey.stringKey("test.customizer"), "test-osgi-customizer")))); + } +} diff --git a/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestMetricReaderProvider.java b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestMetricReaderProvider.java new file mode 100644 index 00000000000..f54bbd93e71 --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestMetricReaderProvider.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.MetricReader; + +public class TestMetricReaderProvider implements ConfigurableMetricReaderProvider { + + @Override + public String getName() { + return "test-noop-reader"; + } + + @Override + public MetricReader createMetricReader(ConfigProperties config) { + return new NoopMetricReader(); + } + + static final class NoopMetricReader implements MetricReader { + + @Override + public void register(CollectionRegistration registration) {} + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + + @Override + public CompletableResultCode forceFlush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + return "TestNoopMetricReader"; + } + } +} diff --git a/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestSamplerProvider.java b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestSamplerProvider.java new file mode 100644 index 00000000000..2f50e8dc69a --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/java/io/opentelemetry/integrationtest/osgi/TestSamplerProvider.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.List; + +public class TestSamplerProvider implements ConfigurableSamplerProvider { + + @Override + public String getName() { + return "test-noop"; + } + + @Override + public Sampler createSampler(ConfigProperties config) { + return new NoopSampler(); + } + + static final class NoopSampler implements Sampler { + + @Override + public SamplingResult shouldSample( + Context parentContext, + String traceId, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return SamplingResult.recordAndSample(); + } + + @Override + public String getDescription() { + return "TestNoopSampler"; + } + + @Override + public String toString() { + return "TestNoopSampler"; + } + } +} diff --git a/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider b/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider new file mode 100644 index 00000000000..fd2a3e7b34e --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider @@ -0,0 +1 @@ +io.opentelemetry.integrationtest.osgi.TestAutoConfigurationCustomizerProvider diff --git a/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider b/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider new file mode 100644 index 00000000000..49f70c84af6 --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider @@ -0,0 +1 @@ +io.opentelemetry.integrationtest.osgi.TestMetricReaderProvider diff --git a/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider b/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider new file mode 100644 index 00000000000..14663a9a1ab --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigure/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider @@ -0,0 +1 @@ +io.opentelemetry.integrationtest.osgi.TestSamplerProvider diff --git a/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/java/io/opentelemetry/integrationtest/osgi/AutoconfigureDeclarativeConfigTest.java b/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/java/io/opentelemetry/integrationtest/osgi/AutoconfigureDeclarativeConfigTest.java new file mode 100644 index 00000000000..9ceacc41f69 --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/java/io/opentelemetry/integrationtest/osgi/AutoconfigureDeclarativeConfigTest.java @@ -0,0 +1,169 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.extension.trace.propagation.B3Propagator; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.ServiceResourceDetector; +import io.opentelemetry.sdk.internal.OpenTelemetrySdkBuilderUtil; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.io.TempDir; +import org.osgi.test.junit5.context.BundleContextExtension; + +/** Verifies autoconfigure with declarative config works in OSGi. */ +@ExtendWith(BundleContextExtension.class) +public class AutoconfigureDeclarativeConfigTest { + + @Test + void declarativeConfigSdkInitializes(@TempDir Path tempDir) throws IOException { + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: test-osgi-declarative\n" + + " detection/development:\n" + + " detectors:\n" + + " - service:\n" + + "propagator:\n" + + " composite:\n" + + " - tracecontext:\n" + + " - b3:\n" + + "tracer_provider:\n" + + " processors:\n" + + " - simple:\n" + + " exporter:\n" + + " otlp_http:\n" + + "meter_provider:\n" + + " readers:\n" + + " - periodic:\n" + + " exporter:\n" + + " otlp_http:\n" + + "logger_provider:\n" + + " processors:\n" + + " - simple:\n" + + " exporter:\n" + + " otlp_http:\n"; + Path configFile = tempDir.resolve("otel-config.yaml"); + Files.write(configFile, yaml.getBytes(StandardCharsets.UTF_8)); + + // System.setProperty (not addPropertiesSupplier) is required because property suppliers are + // not resolved until after the otel.config.file check. + System.setProperty("otel.config.file", configFile.toString()); + AutoConfiguredOpenTelemetrySdk autoConfigured; + try { + autoConfigured = AutoConfiguredOpenTelemetrySdk.builder().build(); + } catch (RuntimeException e) { + System.clearProperty("otel.config.file"); + throw e; + } + + ComponentLoader delegateLoader = + ComponentLoader.forClassLoader(AutoConfiguredOpenTelemetrySdk.class.getClassLoader()); + ComponentLoader autoConfigureLoader = + componentLoaderWithToString( + delegateLoader, "DeclarativeConfigContext{componentLoader=" + delegateLoader + "}"); + + // ServiceResourceDetector.RANDOM_SERVICE_INSTANCE_ID is a static field β€” same value within + // a JVM run, so the expected and actual resources match deterministically. + Resource detectedResource = + new ServiceResourceDetector().create(DeclarativeConfigProperties.empty()); + Resource resource = + Resource.getDefault().toBuilder() + .putAll(detectedResource) + .put(AttributeKey.stringKey("service.name"), "test-osgi-declarative") + .build(); + + OpenTelemetrySdk expected = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .setResource(resource) + .addSpanProcessor( + SimpleSpanProcessor.create( + // TestDeclarativeConfigurationCustomizerProvider wraps + // OtlpHttpSpanExporter β€” proves the SPI was invoked. + new TestDeclarativeConfigurationCustomizerProvider + .TestCustomizedSpanExporter( + OtlpHttpSpanExporter.builder() + .setComponentLoader(autoConfigureLoader) + .build()))) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .setResource(resource) + .registerMetricReader( + PeriodicMetricReader.create( + OtlpHttpMetricExporter.builder() + .setComponentLoader(autoConfigureLoader) + .build())) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .setResource(resource) + .addLogRecordProcessor( + SimpleLogRecordProcessor.create( + OtlpHttpLogRecordExporter.builder() + .setComponentLoader(autoConfigureLoader) + .build())) + .build()) + .setPropagators( + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + B3Propagator.injectingSingleHeader()))), + SdkConfigProvider.create(DeclarativeConfigProperties.empty())) + .build(); + try { + assertThat(autoConfigured.getOpenTelemetrySdk().toString()).isEqualTo(expected.toString()); + } finally { + autoConfigured.getOpenTelemetrySdk().close(); + expected.close(); + System.clearProperty("otel.config.file"); + } + } + + private static ComponentLoader componentLoaderWithToString( + ComponentLoader componentLoader, String toString) { + return new ComponentLoader() { + @Override + public Iterable load(Class spiClass) { + return componentLoader.load(spiClass); + } + + @Override + public String toString() { + return toString; + } + }; + } +} diff --git a/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/java/io/opentelemetry/integrationtest/osgi/TestDeclarativeConfigurationCustomizerProvider.java b/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/java/io/opentelemetry/integrationtest/osgi/TestDeclarativeConfigurationCustomizerProvider.java new file mode 100644 index 00000000000..9554c0b7f33 --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/java/io/opentelemetry/integrationtest/osgi/TestDeclarativeConfigurationCustomizerProvider.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; + +/** + * Noop customizer provider that wraps the OTLP HTTP span exporter with a distinctive toString, + * making the customizer's invocation verifiable in the SDK toString comparison. + */ +public class TestDeclarativeConfigurationCustomizerProvider + implements DeclarativeConfigurationCustomizerProvider { + + @Override + public void customize(DeclarativeConfigurationCustomizer customizer) { + // SpanExporter.class matches all span exporters (OtlpHttpSpanExporter in this test). + // OtlpHttpSpanExporter is final so we can't use it as type bound for the wrapper return type. + customizer.addSpanExporterCustomizer( + SpanExporter.class, (exporter, props) -> new TestCustomizedSpanExporter(exporter)); + } + + /** Wraps a SpanExporter with a distinctive toString to prove the customizer was invoked. */ + public static final class TestCustomizedSpanExporter implements SpanExporter { + + private final SpanExporter delegate; + + public TestCustomizedSpanExporter(SpanExporter delegate) { + this.delegate = delegate; + } + + @Override + public CompletableResultCode export(Collection spans) { + return delegate.export(spans); + } + + @Override + public CompletableResultCode flush() { + return delegate.flush(); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public String toString() { + return "TestDeclarativeCustomized{" + delegate + '}'; + } + } +} diff --git a/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider b/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider new file mode 100644 index 00000000000..1135822d04a --- /dev/null +++ b/integration-tests/osgi/src/testAutoconfigureDeclarativeConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider @@ -0,0 +1 @@ +io.opentelemetry.integrationtest.osgi.TestDeclarativeConfigurationCustomizerProvider diff --git a/integration-tests/osgi/src/testOtlpGrpcOkHttp/java/io/opentelemetry/integrationtest/osgi/OtlpGrpcOkHttpTest.java b/integration-tests/osgi/src/testOtlpGrpcOkHttp/java/io/opentelemetry/integrationtest/osgi/OtlpGrpcOkHttpTest.java new file mode 100644 index 00000000000..fe5168e3fd6 --- /dev/null +++ b/integration-tests/osgi/src/testOtlpGrpcOkHttp/java/io/opentelemetry/integrationtest/osgi/OtlpGrpcOkHttpTest.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.osgi.test.junit5.context.BundleContextExtension; + +/** + * Verifies OTLP gRPC exporters with OkHttp sender work in OSGi. + * + *

    See {@code extraRunsystempackages} in {@code build.gradle.kts} for the system packages that + * must be exposed in the OSGi container for this sender to function. + */ +@ExtendWith(BundleContextExtension.class) +public class OtlpGrpcOkHttpTest { + + @Test + void sdkWithOtlpGrpcExportersInitializes() { + try (OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor( + SimpleSpanProcessor.create(OtlpGrpcSpanExporter.builder().build())) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.create(OtlpGrpcMetricExporter.builder().build())) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .addLogRecordProcessor( + SimpleLogRecordProcessor.create( + OtlpGrpcLogRecordExporter.builder().build())) + .build()) + .build()) { + assertThat(sdk).isNotNull(); + } + } +} diff --git a/integration-tests/osgi/src/testOtlpHttpJdk/java/io/opentelemetry/integrationtest/osgi/OtlpHttpJdkTest.java b/integration-tests/osgi/src/testOtlpHttpJdk/java/io/opentelemetry/integrationtest/osgi/OtlpHttpJdkTest.java new file mode 100644 index 00000000000..d9c5519aa4a --- /dev/null +++ b/integration-tests/osgi/src/testOtlpHttpJdk/java/io/opentelemetry/integrationtest/osgi/OtlpHttpJdkTest.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.osgi.test.junit5.context.BundleContextExtension; + +/** Verifies OTLP HTTP exporters with Jdk 11+ HttpClient sender work in OSGi. */ +@ExtendWith(BundleContextExtension.class) +public class OtlpHttpJdkTest { + + @Test + void sdkWithOtlpHttpExportersInitializes() { + OtlpHttpSpanExporter spanExporter = OtlpHttpSpanExporter.builder().build(); + OtlpHttpMetricExporter metricExporter = OtlpHttpMetricExporter.builder().build(); + OtlpHttpLogRecordExporter logExporter = OtlpHttpLogRecordExporter.builder().build(); + try (OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(spanExporter)) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(logExporter)) + .build()) + .build()) { + assertThat(sdk).isNotNull(); + } + } +} diff --git a/integration-tests/osgi/src/testOtlpHttpOkHttp/java/io/opentelemetry/integrationtest/osgi/OtlpHttpOkHttpTest.java b/integration-tests/osgi/src/testOtlpHttpOkHttp/java/io/opentelemetry/integrationtest/osgi/OtlpHttpOkHttpTest.java new file mode 100644 index 00000000000..4e3d4256045 --- /dev/null +++ b/integration-tests/osgi/src/testOtlpHttpOkHttp/java/io/opentelemetry/integrationtest/osgi/OtlpHttpOkHttpTest.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.osgi.test.junit5.context.BundleContextExtension; + +/** + * Verifies OTLP HTTP exporters with OkHttp sender work in OSGi. + * + *

    See {@code extraRunsystempackages} in {@code build.gradle.kts} for the system packages that + * must be exposed in the OSGi container for this sender to function. + */ +@ExtendWith(BundleContextExtension.class) +public class OtlpHttpOkHttpTest { + + @Test + void sdkWithOtlpHttpExportersInitializes() { + try (OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor( + SimpleSpanProcessor.create(OtlpHttpSpanExporter.builder().build())) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.create(OtlpHttpMetricExporter.builder().build())) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .addLogRecordProcessor( + SimpleLogRecordProcessor.create( + OtlpHttpLogRecordExporter.builder().build())) + .build()) + .build()) { + assertThat(sdk).isNotNull(); + } + } +} diff --git a/integration-tests/osgi/src/testSdk/java/io/opentelemetry/integrationtest/osgi/OpenTelemetryOsgiTest.java b/integration-tests/osgi/src/testSdk/java/io/opentelemetry/integrationtest/osgi/OpenTelemetryOsgiTest.java new file mode 100644 index 00000000000..13f3dd0c557 --- /dev/null +++ b/integration-tests/osgi/src/testSdk/java/io/opentelemetry/integrationtest/osgi/OpenTelemetryOsgiTest.java @@ -0,0 +1,127 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.integrationtest.osgi; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.osgi.test.junit5.context.BundleContextExtension; + +/** Verifies the SDK (traces, metrics, logs) and Context API work in OSGi. */ +@ExtendWith(BundleContextExtension.class) +public class OpenTelemetryOsgiTest { + + @Test + public void verifyContextStorage() { + ContextKey testContextKey = ContextKey.named("test"); + try (Scope scope = Context.current().with(testContextKey, "testValue").makeCurrent()) { + assertThat(Context.current().get(testContextKey)).isEqualTo("testValue"); + } + } + + @Test + public void vanillaSdkInitializes() { + try (OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.create( + new MetricExporter() { + @Override + public CompletableResultCode export(Collection metrics) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public AggregationTemporality getAggregationTemporality( + InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + })) + .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .addLogRecordProcessor( + SimpleLogRecordProcessor.create( + new LogRecordExporter() { + @Override + public CompletableResultCode export(Collection logs) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + })) + .build()) + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor( + SimpleSpanProcessor.create( + new SpanExporter() { + @Override + public CompletableResultCode export(Collection spans) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + })) + .build()) + .build()) { + assertThat(sdk).isNotNull(); + + // Verify Context API is available + Context current = Context.current(); + assertThat(current).isNotNull(); + } + } +} diff --git a/integration-tests/otlp/build.gradle.kts b/integration-tests/otlp/build.gradle.kts index e834817ec3f..caf42067f2f 100644 --- a/integration-tests/otlp/build.gradle.kts +++ b/integration-tests/otlp/build.gradle.kts @@ -4,17 +4,16 @@ plugins { description = "OTLP Exporter Integration Tests" otelJava.moduleName.set("io.opentelemetry.integration.tests.otlp") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) dependencies { - api("org.testcontainers:junit-jupiter") + api("org.testcontainers:testcontainers-junit-jupiter") - implementation(project(":exporters:otlp:trace")) - implementation(project(":exporters:otlp:metrics")) - implementation(project(":exporters:otlp:logs")) - implementation(project(":exporters:otlp-http:logs")) - implementation(project(":exporters:otlp-http:metrics")) - implementation(project(":exporters:otlp-http:trace")) - implementation(project(":semconv")) + implementation(project(":exporters:otlp:all")) + implementation(project(":api:incubator")) + + compileOnly("com.google.errorprone:error_prone_annotations") implementation("com.linecorp.armeria:armeria-grpc-protocol") implementation("com.linecorp.armeria:armeria-junit5") @@ -26,7 +25,7 @@ dependencies { testing { suites { - val testGrpcJava by registering(JvmTestSuite::class) { + register("testGrpcJava") { dependencies { runtimeOnly("io.grpc:grpc-netty-shaded") runtimeOnly("io.grpc:grpc-stub") @@ -45,3 +44,8 @@ tasks { dependsOn(testing.suites) } } + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false +} diff --git a/integration-tests/otlp/src/main/java/io/opentelemetry/integrationtest/OtlpExporterIntegrationTest.java b/integration-tests/otlp/src/main/java/io/opentelemetry/integrationtest/OtlpExporterIntegrationTest.java index c6a428ad582..8a4ae79bb9c 100644 --- a/integration-tests/otlp/src/main/java/io/opentelemetry/integrationtest/OtlpExporterIntegrationTest.java +++ b/integration-tests/otlp/src/main/java/io/opentelemetry/integrationtest/OtlpExporterIntegrationTest.java @@ -5,11 +5,13 @@ package io.opentelemetry.integrationtest; +import static io.opentelemetry.api.common.Value.of; import static java.util.concurrent.CompletableFuture.completedFuture; import static org.assertj.core.api.Assertions.assertThat; import static org.awaitility.Awaitility.await; import static org.testcontainers.Testcontainers.exposeHostPorts; +import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import com.linecorp.armeria.server.ServerBuilder; import com.linecorp.armeria.server.ServiceRequestContext; @@ -17,7 +19,12 @@ import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; import com.linecorp.armeria.testing.junit5.server.ServerExtension; import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.incubator.logs.ExtendedLogRecordBuilder; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.trace.Span; @@ -26,10 +33,12 @@ import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogExporter; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; -import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; @@ -39,7 +48,9 @@ import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; import io.opentelemetry.proto.common.v1.AnyValue; -import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.common.v1.ArrayValue; +import io.opentelemetry.proto.common.v1.KeyValueList; +import io.opentelemetry.proto.logs.v1.LogRecord; import io.opentelemetry.proto.logs.v1.ResourceLogs; import io.opentelemetry.proto.logs.v1.ScopeLogs; import io.opentelemetry.proto.metrics.v1.AggregationTemporality; @@ -51,11 +62,11 @@ import io.opentelemetry.proto.trace.v1.ResourceSpans; import io.opentelemetry.proto.trace.v1.ScopeSpans; import io.opentelemetry.proto.trace.v1.Span.Link; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.logs.export.LogExporter; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.ExemplarFilter; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.export.MetricExporter; import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; @@ -64,14 +75,14 @@ import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.time.Instant; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletionStage; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -79,12 +90,14 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.ValueSource; import org.slf4j.LoggerFactory; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.containers.wait.strategy.Wait; +import org.testcontainers.images.PullPolicy; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; import org.testcontainers.utility.MountableFile; @@ -98,17 +111,18 @@ @Testcontainers(disabledWithoutDocker = true) abstract class OtlpExporterIntegrationTest { + private static final AttributeKey SERVICE_NAME = AttributeKey.stringKey("service.name"); + private static final String COLLECTOR_IMAGE = - "ghcr.io/open-telemetry/opentelemetry-java/otel-collector"; + "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea"; + private static final Integer COLLECTOR_OTLP_GRPC_PORT = 4317; private static final Integer COLLECTOR_OTLP_HTTP_PORT = 4318; private static final Integer COLLECTOR_OTLP_GRPC_MTLS_PORT = 5317; private static final Integer COLLECTOR_OTLP_HTTP_MTLS_PORT = 5318; private static final Integer COLLECTOR_HEALTH_CHECK_PORT = 13133; private static final Resource RESOURCE = - Resource.getDefault().toBuilder() - .put(ResourceAttributes.SERVICE_NAME, "integration test") - .build(); + Resource.getDefault().toBuilder().put(SERVICE_NAME, "integration test").build(); @RegisterExtension static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); @@ -116,7 +130,10 @@ abstract class OtlpExporterIntegrationTest { @RegisterExtension static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + @SuppressWarnings("NonFinalStaticField") private static OtlpGrpcServer grpcServer; + + @SuppressWarnings("NonFinalStaticField") private static GenericContainer collector; @BeforeAll @@ -130,7 +147,8 @@ static void beforeAll() { collector = new GenericContainer<>(DockerImageName.parse(COLLECTOR_IMAGE)) - .withEnv("LOGGING_EXPORTER_LOG_LEVEL", "INFO") + .withImagePullPolicy(PullPolicy.alwaysPull()) + .withEnv("LOGGING_EXPORTER_VERBOSITY_LEVEL", "normal") .withCopyFileToContainer( MountableFile.forHostPath(serverTls.certificateFile().toPath(), 0555), "/server.cert") @@ -176,7 +194,7 @@ void afterEach() {} @ParameterizedTest @ValueSource(strings = {"gzip", "none"}) void testOtlpGrpcTraceExport(String compression) { - SpanExporter otlpGrpcTraceExporter = + SpanExporter exporter = OtlpGrpcSpanExporter.builder() .setEndpoint( "http://" @@ -186,7 +204,23 @@ void testOtlpGrpcTraceExport(String compression) { .setCompression(compression) .build(); - testTraceExport(otlpGrpcTraceExporter); + testTraceExport(exporter); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testOtlpGrpcTraceExport_memoryMode(MemoryMode memoryMode) { + SpanExporter exporter = + OtlpGrpcSpanExporter.builder() + .setEndpoint( + "http://" + + collector.getHost() + + ":" + + collector.getMappedPort(COLLECTOR_OTLP_GRPC_PORT)) + .setMemoryMode(memoryMode) + .build(); + + testTraceExport(exporter); } @Test @@ -208,7 +242,7 @@ void testOtlpGrpcTraceExport_mtls() throws Exception { @ParameterizedTest @ValueSource(strings = {"gzip", "none"}) void testOtlpHttpTraceExport(String compression) { - SpanExporter otlpGrpcTraceExporter = + SpanExporter exporter = OtlpHttpSpanExporter.builder() .setEndpoint( "http://" @@ -219,7 +253,24 @@ void testOtlpHttpTraceExport(String compression) { .setCompression(compression) .build(); - testTraceExport(otlpGrpcTraceExporter); + testTraceExport(exporter); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testOtlpHttpTraceExport_memoryMode(MemoryMode memoryMode) { + SpanExporter exporter = + OtlpHttpSpanExporter.builder() + .setEndpoint( + "http://" + + collector.getHost() + + ":" + + collector.getMappedPort(COLLECTOR_OTLP_HTTP_PORT) + + "/v1/traces") + .setMemoryMode(memoryMode) + .build(); + + testTraceExport(exporter); } @Test @@ -262,20 +313,21 @@ private static void testTraceExport(SpanExporter spanExporter) { span.addEvent("event"); span.end(); + // Closing triggers flush of processor + tracerProvider.close(); + await() .atMost(Duration.ofSeconds(30)) .untilAsserted(() -> assertThat(grpcServer.traceRequests).hasSize(1)); - tracerProvider.close(); - ExportTraceServiceRequest request = grpcServer.traceRequests.get(0); assertThat(request.getResourceSpansCount()).isEqualTo(1); ResourceSpans resourceSpans = request.getResourceSpans(0); assertThat(resourceSpans.getResource().getAttributesList()) .contains( - KeyValue.newBuilder() - .setKey(ResourceAttributes.SERVICE_NAME.getKey()) + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey(SERVICE_NAME.getKey()) .setValue(AnyValue.newBuilder().setStringValue("integration test").build()) .build()); assertThat(resourceSpans.getScopeSpansCount()).isEqualTo(1); @@ -293,7 +345,7 @@ private static void testTraceExport(SpanExporter spanExporter) { assertThat(protoSpan.getAttributesList()) .isEqualTo( Collections.singletonList( - KeyValue.newBuilder() + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() .setKey("key") .setValue(AnyValue.newBuilder().setStringValue("value").build()) .build())); @@ -308,7 +360,7 @@ private static void testTraceExport(SpanExporter spanExporter) { @ParameterizedTest @ValueSource(strings = {"gzip", "none"}) void testOtlpGrpcMetricExport(String compression) { - MetricExporter otlpGrpcMetricExporter = + MetricExporter exporter = OtlpGrpcMetricExporter.builder() .setEndpoint( "http://" @@ -318,7 +370,24 @@ void testOtlpGrpcMetricExport(String compression) { .setCompression(compression) .build(); - testMetricExport(otlpGrpcMetricExporter); + testMetricExport(exporter); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testOtlpGrpcMetricExport_memoryMode(MemoryMode memoryMode) { + MetricExporter exporter = + OtlpGrpcMetricExporter.builder() + .setEndpoint( + "http://" + + collector.getHost() + + ":" + + collector.getMappedPort(COLLECTOR_OTLP_GRPC_PORT)) + .setMemoryMode(memoryMode) + .build(); + assertThat(exporter.getMemoryMode()).isEqualTo(memoryMode); + + testMetricExport(exporter); } @Test @@ -340,7 +409,8 @@ void testOtlpGrpcMetricExport_mtls() throws Exception { @ParameterizedTest @ValueSource(strings = {"gzip", "none"}) void testOtlpHttpMetricExport(String compression) { - MetricExporter otlpGrpcMetricExporter = + + MetricExporter exporter = OtlpHttpMetricExporter.builder() .setEndpoint( "http://" @@ -351,7 +421,25 @@ void testOtlpHttpMetricExport(String compression) { .setCompression(compression) .build(); - testMetricExport(otlpGrpcMetricExporter); + testMetricExport(exporter); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testOtlpHttpMetricExport_memoryMode(MemoryMode memoryMode) { + MetricExporter exporter = + OtlpHttpMetricExporter.builder() + .setEndpoint( + "http://" + + collector.getHost() + + ":" + + collector.getMappedPort(COLLECTOR_OTLP_HTTP_PORT) + + "/v1/metrics") + .setMemoryMode(memoryMode) + .build(); + assertThat(exporter.getMemoryMode()).isEqualTo(memoryMode); + + testMetricExport(exporter); } @Test @@ -377,8 +465,10 @@ private static void testMetricExport(MetricExporter metricExporter) { .setResource(RESOURCE) .registerMetricReader( PeriodicMetricReader.builder(metricExporter) - .setInterval(Duration.ofSeconds(5)) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) .build()) + // Enable alwaysOn exemplar filter, instead of default traceBased filter + .setExemplarFilter(ExemplarFilter.alwaysOn()) .build(); Meter meter = meterProvider.meterBuilder(OtlpExporterIntegrationTest.class.getName()).build(); @@ -386,13 +476,12 @@ private static void testMetricExport(MetricExporter metricExporter) { LongCounter longCounter = meter.counterBuilder("my-counter").build(); longCounter.add(100, Attributes.builder().put("key", "value").build()); - try { - await() - .atMost(Duration.ofSeconds(30)) - .untilAsserted(() -> assertThat(grpcServer.metricRequests).hasSize(1)); - } finally { - meterProvider.close(); - } + // Closing triggers flush of reader + meterProvider.close(); + + await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> assertThat(grpcServer.metricRequests).hasSize(1)); ExportMetricsServiceRequest request = grpcServer.metricRequests.get(0); assertThat(request.getResourceMetricsCount()).isEqualTo(1); @@ -400,8 +489,8 @@ private static void testMetricExport(MetricExporter metricExporter) { ResourceMetrics resourceMetrics = request.getResourceMetrics(0); assertThat(resourceMetrics.getResource().getAttributesList()) .contains( - KeyValue.newBuilder() - .setKey(ResourceAttributes.SERVICE_NAME.getKey()) + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey(SERVICE_NAME.getKey()) .setValue(AnyValue.newBuilder().setStringValue("integration test").build()) .build()); assertThat(resourceMetrics.getScopeMetricsCount()).isEqualTo(1); @@ -425,17 +514,18 @@ private static void testMetricExport(MetricExporter metricExporter) { assertThat(dataPoint.getAttributesList()) .isEqualTo( Collections.singletonList( - KeyValue.newBuilder() + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() .setKey("key") .setValue(AnyValue.newBuilder().setStringValue("value").build()) .build())); + assertThat(dataPoint.getExemplarsCount()).isEqualTo(1); } @ParameterizedTest @ValueSource(strings = {"gzip", "none"}) void testOtlpGrpcLogExport(String compression) { - LogExporter otlpGrpcLogExporter = - OtlpGrpcLogExporter.builder() + LogRecordExporter otlpGrpcLogRecordExporter = + OtlpGrpcLogRecordExporter.builder() .setEndpoint( "http://" + collector.getHost() @@ -444,13 +534,29 @@ void testOtlpGrpcLogExport(String compression) { .setCompression(compression) .build(); - testLogExporter(otlpGrpcLogExporter); + testLogRecordExporter(otlpGrpcLogRecordExporter); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testOtlpGrpcLogExport_memoryMode(MemoryMode memoryMode) { + LogRecordExporter otlpGrpcLogRecordExporter = + OtlpGrpcLogRecordExporter.builder() + .setEndpoint( + "http://" + + collector.getHost() + + ":" + + collector.getMappedPort(COLLECTOR_OTLP_GRPC_PORT)) + .setMemoryMode(memoryMode) + .build(); + + testLogRecordExporter(otlpGrpcLogRecordExporter); } @Test void testOtlpGrpcLogExport_mtls() throws Exception { - LogExporter exporter = - OtlpGrpcLogExporter.builder() + LogRecordExporter exporter = + OtlpGrpcLogRecordExporter.builder() .setEndpoint( "https://" + collector.getHost() @@ -460,14 +566,14 @@ void testOtlpGrpcLogExport_mtls() throws Exception { .setTrustedCertificates(serverTls.certificate().getEncoded()) .build(); - testLogExporter(exporter); + testLogRecordExporter(exporter); } @ParameterizedTest @ValueSource(strings = {"gzip", "none"}) void testOtlpHttpLogExport(String compression) { - LogExporter otlpHttpLogExporter = - OtlpHttpLogExporter.builder() + LogRecordExporter otlpHttpLogRecordExporter = + OtlpHttpLogRecordExporter.builder() .setEndpoint( "http://" + collector.getHost() @@ -477,13 +583,30 @@ void testOtlpHttpLogExport(String compression) { .setCompression(compression) .build(); - testLogExporter(otlpHttpLogExporter); + testLogRecordExporter(otlpHttpLogRecordExporter); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testOtlpHttpLogExport_memoryMode(MemoryMode memoryMode) { + LogRecordExporter otlpHttpLogRecordExporter = + OtlpHttpLogRecordExporter.builder() + .setEndpoint( + "http://" + + collector.getHost() + + ":" + + collector.getMappedPort(COLLECTOR_OTLP_HTTP_PORT) + + "/v1/logs") + .setMemoryMode(memoryMode) + .build(); + + testLogRecordExporter(otlpHttpLogRecordExporter); } @Test void testOtlpHttpLogExport_mtls() throws Exception { - LogExporter exporter = - OtlpHttpLogExporter.builder() + LogRecordExporter exporter = + OtlpHttpLogRecordExporter.builder() .setEndpoint( "https://" + collector.getHost() @@ -494,43 +617,70 @@ void testOtlpHttpLogExport_mtls() throws Exception { .setTrustedCertificates(serverTls.certificate().getEncoded()) .build(); - testLogExporter(exporter); + testLogRecordExporter(exporter); } - private static void testLogExporter(LogExporter logExporter) { - LogData logData = - LogDataBuilder.create( - RESOURCE, - InstrumentationScopeInfo.create(OtlpExporterIntegrationTest.class.getName())) - .setBody("log body") - .setAttributes(Attributes.builder().put("key", "value").build()) - .setSeverity(Severity.DEBUG) - .setSeverityText("DEBUG") - .setEpoch(Instant.now()) - .setSpanContext( - SpanContext.create( - IdGenerator.random().generateTraceId(), - IdGenerator.random().generateSpanId(), - TraceFlags.getDefault(), - TraceState.getDefault())) + @SuppressWarnings("BadImport") + private static void testLogRecordExporter(LogRecordExporter logRecordExporter) { + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .setResource(RESOURCE) + .addLogRecordProcessor( + BatchLogRecordProcessor.builder(logRecordExporter) + .setExporterTimeout(Duration.ofSeconds(1000)) + .build()) .build(); - logExporter.export(Collections.singletonList(logData)); + Logger logger = loggerProvider.get(OtlpExporterIntegrationTest.class.getName()); + + SpanContext spanContext = + SpanContext.create( + IdGenerator.random().generateTraceId(), + IdGenerator.random().generateSpanId(), + TraceFlags.getDefault(), + TraceState.getDefault()); + + try (Scope ignored = Span.wrap(spanContext).makeCurrent()) { + ((ExtendedLogRecordBuilder) logger.logRecordBuilder()) + .setEventName("event name") + .setBody( + of( + KeyValue.of("str_key", of("value")), + KeyValue.of("bool_key", of(true)), + KeyValue.of("int_key", of(1L)), + KeyValue.of("double_key", of(1.1)), + KeyValue.of("bytes_key", of("value".getBytes(StandardCharsets.UTF_8))), + KeyValue.of("arr_key", of(of("value"), of(1L))), + KeyValue.of( + "kv_list", + of( + KeyValue.of("child_str_key", of("value")), + KeyValue.of( + "child_kv_list", + of(KeyValue.of("grandchild_str_key", of("value")))))))) + .setTimestamp(100, TimeUnit.NANOSECONDS) + .setAllAttributes(Attributes.builder().put("key", "value").build()) + .setSeverity(Severity.DEBUG) + .setSeverityText("DEBUG") + .setContext(Context.current()) + .emit(); + } + + // Closing triggers flush of processor + loggerProvider.close(); await() .atMost(Duration.ofSeconds(30)) .untilAsserted(() -> assertThat(grpcServer.logRequests).hasSize(1)); - logExporter.close(); - ExportLogsServiceRequest request = grpcServer.logRequests.get(0); assertThat(request.getResourceLogsCount()).isEqualTo(1); ResourceLogs resourceLogs = request.getResourceLogs(0); assertThat(resourceLogs.getResource().getAttributesList()) .contains( - KeyValue.newBuilder() - .setKey(ResourceAttributes.SERVICE_NAME.getKey()) + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey(SERVICE_NAME.getKey()) .setValue(AnyValue.newBuilder().setStringValue("integration test").build()) .build()); assertThat(resourceLogs.getScopeLogsCount()).isEqualTo(1); @@ -539,25 +689,122 @@ private static void testLogExporter(LogExporter logExporter) { assertThat(ilLogs.getScope().getName()).isEqualTo(OtlpExporterIntegrationTest.class.getName()); assertThat(ilLogs.getLogRecordsCount()).isEqualTo(1); - io.opentelemetry.proto.logs.v1.LogRecord protoLog = ilLogs.getLogRecords(0); - assertThat(protoLog.getBody().getStringValue()).isEqualTo("log body"); - assertThat(protoLog.getAttributesList()) + // LogRecord via Logger.logRecordBuilder()...emit() + LogRecord protoLog1 = ilLogs.getLogRecords(0); + assertThat(protoLog1.getEventName()).isEqualTo("event name"); + assertThat(protoLog1.getBody()) + .isEqualTo( + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("str_key") + .setValue(AnyValue.newBuilder().setStringValue("value").build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("bool_key") + .setValue(AnyValue.newBuilder().setBoolValue(true).build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("int_key") + .setValue(AnyValue.newBuilder().setIntValue(1).build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("double_key") + .setValue(AnyValue.newBuilder().setDoubleValue(1.1).build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("bytes_key") + .setValue( + AnyValue.newBuilder() + .setBytesValue( + ByteString.copyFrom( + "value".getBytes(StandardCharsets.UTF_8))) + .build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("arr_key") + .setValue( + AnyValue.newBuilder() + .setArrayValue( + ArrayValue.newBuilder() + .addValues( + AnyValue.newBuilder() + .setStringValue("value") + .build()) + .addValues( + AnyValue.newBuilder().setIntValue(1).build()) + .build()) + .build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() + .setKey("kv_list") + .setValue( + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + io.opentelemetry.proto.common.v1.KeyValue + .newBuilder() + .setKey("child_str_key") + .setValue( + AnyValue.newBuilder() + .setStringValue("value") + .build()) + .build()) + .addValues( + io.opentelemetry.proto.common.v1.KeyValue + .newBuilder() + .setKey("child_kv_list") + .setValue( + AnyValue.newBuilder() + .setKvlistValue( + KeyValueList.newBuilder() + .addValues( + io.opentelemetry.proto + .common.v1.KeyValue + .newBuilder() + .setKey( + "grandchild_str_key") + .setValue( + AnyValue + .newBuilder() + .setStringValue( + "value") + .build()) + .build()) + .build()) + .build()) + .build()) + .build()) + .build()) + .build()) + .build()) + .build()); + assertThat(protoLog1.getAttributesList()) .isEqualTo( Collections.singletonList( - KeyValue.newBuilder() + io.opentelemetry.proto.common.v1.KeyValue.newBuilder() .setKey("key") .setValue(AnyValue.newBuilder().setStringValue("value").build()) .build())); - assertThat(protoLog.getSeverityNumber().getNumber()) - .isEqualTo(logData.getSeverity().getSeverityNumber()); - assertThat(protoLog.getSeverityText()).isEqualTo("DEBUG"); - assertThat(TraceId.fromBytes(protoLog.getTraceId().toByteArray())) - .isEqualTo(logData.getSpanContext().getTraceId()); - assertThat(SpanId.fromBytes(protoLog.getSpanId().toByteArray())) - .isEqualTo(logData.getSpanContext().getSpanId()); - assertThat(TraceFlags.fromByte((byte) protoLog.getFlags())) - .isEqualTo(logData.getSpanContext().getTraceFlags()); - assertThat(protoLog.getTimeUnixNano()).isEqualTo(logData.getEpochNanos()); + assertThat(protoLog1.getSeverityNumber().getNumber()) + .isEqualTo(Severity.DEBUG.getSeverityNumber()); + assertThat(protoLog1.getSeverityText()).isEqualTo("DEBUG"); + assertThat(TraceId.fromBytes(protoLog1.getTraceId().toByteArray())) + .isEqualTo(spanContext.getTraceId()); + assertThat(SpanId.fromBytes(protoLog1.getSpanId().toByteArray())) + .isEqualTo(spanContext.getSpanId()); + assertThat(TraceFlags.fromByte((byte) protoLog1.getFlags())) + .isEqualTo(spanContext.getTraceFlags()); + assertThat(protoLog1.getTimeUnixNano()).isEqualTo(100); } private static class OtlpGrpcServer extends ServerExtension { diff --git a/integration-tests/otlp/src/main/resources/otel-config.yaml b/integration-tests/otlp/src/main/resources/otel-config.yaml index 16abb90b90f..614cb5443bd 100644 --- a/integration-tests/otlp/src/main/resources/otel-config.yaml +++ b/integration-tests/otlp/src/main/resources/otel-config.yaml @@ -1,5 +1,6 @@ extensions: - health_check: {} + health_check: + endpoint: 0.0.0.0:13133 receivers: otlp: protocols: @@ -12,31 +13,32 @@ receivers: grpc: endpoint: 0.0.0.0:5317 tls: - client_ca_file: $MTLS_CLIENT_CERTIFICATE - cert_file: $MTLS_SERVER_CERTIFICATE - key_file: $MTLS_SERVER_KEY + client_ca_file: ${MTLS_CLIENT_CERTIFICATE} + cert_file: ${MTLS_SERVER_CERTIFICATE} + key_file: ${MTLS_SERVER_KEY} http: endpoint: 0.0.0.0:5318 tls: - client_ca_file: $MTLS_CLIENT_CERTIFICATE - cert_file: $MTLS_SERVER_CERTIFICATE - key_file: $MTLS_SERVER_KEY + client_ca_file: ${MTLS_CLIENT_CERTIFICATE} + cert_file: ${MTLS_SERVER_CERTIFICATE} + key_file: ${MTLS_SERVER_KEY} exporters: - logging: - logLevel: $LOGGING_EXPORTER_LOG_lEVEL + debug: + verbosity: ${LOGGING_EXPORTER_VERBOSITY_LEVEL} otlp: - endpoint: $OTLP_EXPORTER_ENDPOINT + endpoint: ${OTLP_EXPORTER_ENDPOINT} tls: insecure: true + compression: none service: extensions: [health_check] pipelines: metrics: receivers: [otlp, otlp/mtls] - exporters: [logging, otlp] + exporters: [debug, otlp] traces: receivers: [otlp, otlp/mtls] - exporters: [logging, otlp] + exporters: [debug, otlp] logs: receivers: [otlp, otlp/mtls] - exporters: [logging, otlp] + exporters: [debug, otlp] diff --git a/integration-tests/otlp/src/testGrpcJava/java/io/opentelemetry/integrationtest/GrpcJavaOtlpIntegrationTest.java b/integration-tests/otlp/src/testGrpcJava/java/io/opentelemetry/integrationtest/GrpcJavaOtlpIntegrationTest.java index 250c85700ec..a3d4da0a45b 100644 --- a/integration-tests/otlp/src/testGrpcJava/java/io/opentelemetry/integrationtest/GrpcJavaOtlpIntegrationTest.java +++ b/integration-tests/otlp/src/testGrpcJava/java/io/opentelemetry/integrationtest/GrpcJavaOtlpIntegrationTest.java @@ -12,7 +12,7 @@ class GrpcJavaOtlpIntegrationTest extends OtlpExporterIntegrationTest { @Test - void noGrpcFound() { + void grpcFound() { assertThatCode(() -> Class.forName("io.grpc.ManagedChannel")).doesNotThrowAnyException(); } } diff --git a/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java b/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java index 8dae9adb8ff..e3477eb83aa 100644 --- a/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java +++ b/integration-tests/src/test/java/io/opentelemetry/B3PropagationIntegrationTest.java @@ -30,7 +30,6 @@ import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; -import java.io.IOException; import java.net.URI; import java.util.List; import java.util.function.Supplier; @@ -44,13 +43,17 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsProvider; import org.junit.jupiter.params.provider.ArgumentsSource; +import org.junit.jupiter.params.support.ParameterDeclarations; /** Integration tests for the B3 propagators, in various configurations. */ class B3PropagationIntegrationTest { private static final InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); + @SuppressWarnings("NonFinalStaticField") static WebClient b3MultiClient; + + @SuppressWarnings("NonFinalStaticField") static WebClient b3SingleClient; private static class FrontendService implements HttpService { @@ -72,16 +75,15 @@ public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) { .setParent(incomingContext) .startSpan(); try (Scope ignored = span.makeCurrent()) { - return HttpResponse.from( + return HttpResponse.of( client .get() .get("/backend") .aggregate() - .thenApply( - unused -> { - span.end(); - return HttpResponse.of("OK"); - })); + .thenApply(unused -> { + span.end(); + return HttpResponse.of("OK"); + })); } } } @@ -158,7 +160,7 @@ void shutdown() { @ParameterizedTest @ArgumentsSource(WebClientArgumentSupplier.class) - void propagation(String testType, WebClient client) throws IOException { + void propagation(WebClient client) { OpenTelemetrySdk clientSdk = setupClient(); Span span = clientSdk.getTracer("testTracer").spanBuilder("clientSpan").startSpan(); @@ -179,7 +181,7 @@ void propagation(String testType, WebClient client) throws IOException { @ParameterizedTest @ArgumentsSource(WebClientArgumentSupplier.class) - void noClientTracing(String testType, WebClient client) throws IOException { + void noClientTracing(WebClient client) { assertThat(client.get("/frontend").aggregate().join().contentUtf8()).isEqualTo("OK"); List finishedSpanItems = spanExporter.getFinishedSpanItems(); @@ -193,12 +195,11 @@ void noClientTracing(String testType, WebClient client) throws IOException { private static WebClient createPropagatingClient(URI uri, TextMapPropagator propagator) { return WebClient.builder(uri) - .decorator( - (delegate, ctx, req) -> { - propagator.inject( - Context.current(), ctx, ClientRequestContext::addAdditionalRequestHeader); - return delegate.execute(ctx, req); - }) + .decorator((delegate, ctx, req) -> { + propagator.inject( + Context.current(), ctx, ClientRequestContext::addAdditionalRequestHeader); + return delegate.execute(ctx, req); + }) .build(); } @@ -234,9 +235,11 @@ public String get(@Nullable HttpRequest carrier, String key) { public static class WebClientArgumentSupplier implements ArgumentsProvider { @Override - public Stream provideArguments(ExtensionContext context) { + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) { return Stream.of( - Arguments.of("b3multi", b3MultiClient), Arguments.of("b3single", b3SingleClient)); + Arguments.argumentSet("b3multi", b3MultiClient), + Arguments.argumentSet("b3single", b3SingleClient)); } } } diff --git a/integration-tests/src/test/java/io/opentelemetry/CracLifecycleIntegrationTest.java b/integration-tests/src/test/java/io/opentelemetry/CracLifecycleIntegrationTest.java new file mode 100644 index 00000000000..a15ec015043 --- /dev/null +++ b/integration-tests/src/test/java/io/opentelemetry/CracLifecycleIntegrationTest.java @@ -0,0 +1,165 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.crac.Context; +import org.crac.Resource; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Integration-style lifecycle tests for CRaC (Coordinated Restore at Checkpoint) support. + * + *

    These tests use {@link MockCracContext} to simulate the CRaC checkpoint/restore lifecycle + * without a CRaC-enabled JDK. Resources register with the mock context; the test then drives {@code + * beforeCheckpoint} and {@code afterRestore} callbacks directly. + * + *

    See: #6756 + */ +class CracLifecycleIntegrationTest { + + /** + * Demonstrates the failure mode when the SDK is naively shut down at checkpoint with no + * corresponding restore logic. This is what happens today without proper CRaC support: the SDK is + * a one-shot object, so spans emitted after a restore are silently dropped. + */ + @Test + void spansDroppedAfterRestore_naiveCracIntegration() throws Exception { + MockCracContext cracContext = new MockCracContext(); + InMemorySpanExporter exporter = new InMemorySpanExporter(); + OpenTelemetrySdk sdk = buildSdk(exporter); + Tracer tracer = sdk.getTracer("crac-lifecycle-test"); + + // Naive CRaC resource: shuts the SDK down at checkpoint, does nothing on restore. + cracContext.register( + new Resource() { + @Override + public void beforeCheckpoint(Context context) { + sdk.getSdkTracerProvider().shutdown().join(10, TimeUnit.SECONDS); + } + + @Override + public void afterRestore(Context context) { + // No restore logic β€” this is the gap that #6756 addresses. + } + }); + + emitSpan(tracer, "before-checkpoint"); + sdk.getSdkTracerProvider().forceFlush().join(10, TimeUnit.SECONDS); + assertThat(exporter.exportedCount()).isEqualTo(1); + + cracContext.simulateCheckpoint(); + cracContext.simulateRestore(); + + // Post-restore span is silently dropped: the SDK is shut down and has no way to reinitialize. + emitSpan(tracer, "after-restore"); + sdk.getSdkTracerProvider().forceFlush().join(10, TimeUnit.SECONDS); + assertThat(exporter.exportedCount()).isEqualTo(1); + } + + /** + * Describes the desired behavior once the SDK properly implements {@link Resource}: spans emitted + * after a CRaC restore should be exported normally. + * + *

    This test is disabled until #6756 is addressed. + * When that work lands, the SDK (or an adapter it exposes) should register with the CRaC context + * so that {@code beforeCheckpoint} flushes and quiesces, and {@code afterRestore} reinitializes + * exporters and processors. Replace the TODO below with the real SDK API. + */ + @Test + @Disabled("Expected to fail until #6756 adds checkpoint/restore-safe SDK lifecycle") + void spansExportedAfterRestore_properCracIntegration() throws Exception { + MockCracContext cracContext = new MockCracContext(); + InMemorySpanExporter exporter = new InMemorySpanExporter(); + OpenTelemetrySdk sdk = buildSdk(exporter); + Tracer tracer = sdk.getTracer("crac-lifecycle-test"); + + // TODO(#6756): replace this placeholder with the real SDK CRaC API, e.g.: + // cracContext.register(sdk.asCracResource()); + cracContext.register( + new Resource() { + @Override + public void beforeCheckpoint(Context context) throws Exception { + sdk.getSdkTracerProvider().shutdown().join(10, TimeUnit.SECONDS); + } + + @Override + public void afterRestore(Context context) throws Exception { + // Reinitialize: reopen connections, restart background threads. + // No SDK API exists for this yet β€” this is the body of #6756. + } + }); + + emitSpan(tracer, "before-checkpoint"); + sdk.getSdkTracerProvider().forceFlush().join(10, TimeUnit.SECONDS); + assertThat(exporter.exportedCount()).isEqualTo(1); + + cracContext.simulateCheckpoint(); + cracContext.simulateRestore(); + + emitSpan(tracer, "after-restore"); + sdk.getSdkTracerProvider().forceFlush().join(10, TimeUnit.SECONDS); + assertThat(exporter.exportedCount()).isEqualTo(2); + } + + private static OpenTelemetrySdk buildSdk(SpanExporter exporter) { + return OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(exporter)) + .build()) + .build(); + } + + private static void emitSpan(Tracer tracer, String name) { + Span span = tracer.spanBuilder(name).startSpan(); + span.end(); + } + + private static final class InMemorySpanExporter implements SpanExporter { + private final List spans = new ArrayList<>(); + private boolean shutdown; + + @Override + public CompletableResultCode export(Collection spans) { + if (shutdown) { + return CompletableResultCode.ofFailure(); + } + this.spans.addAll(spans); + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + shutdown = true; + return CompletableResultCode.ofSuccess(); + } + + int exportedCount() { + return spans.size(); + } + } +} diff --git a/integration-tests/src/test/java/io/opentelemetry/MockCracContext.java b/integration-tests/src/test/java/io/opentelemetry/MockCracContext.java new file mode 100644 index 00000000000..c351892401f --- /dev/null +++ b/integration-tests/src/test/java/io/opentelemetry/MockCracContext.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry; + +import java.util.ArrayList; +import java.util.List; +import org.crac.Context; +import org.crac.Resource; + +/** + * A test-only {@link Context} that allows simulating CRaC checkpoint and restore lifecycle events + * without requiring a CRaC-enabled JDK. Register resources with {@link #register(Resource)}, then + * call {@link #simulateCheckpoint()} and {@link #simulateRestore()} to drive the lifecycle. + * + *

    Notification order follows the CRaC specification: checkpoint callbacks fire in reverse + * registration order; restore callbacks fire in forward registration order. + */ +final class MockCracContext extends Context { + + private final List resources = new ArrayList<>(); + + @Override + public void register(Resource resource) { + resources.add(resource); + } + + /** + * Simulates a CRaC checkpoint by invoking {@link Resource#beforeCheckpoint} on all registered + * resources in reverse registration order, as the CRaC spec requires. + */ + void simulateCheckpoint() throws Exception { + for (int i = resources.size() - 1; i >= 0; i--) { + resources.get(i).beforeCheckpoint(this); + } + } + + /** + * Simulates a CRaC restore by invoking {@link Resource#afterRestore} on all registered resources + * in forward registration order, as the CRaC spec requires. + */ + void simulateRestore() throws Exception { + for (Resource resource : resources) { + resource.afterRestore(this); + } + } + + // Not used: this context is not itself registered with a parent context. + @Override + public void beforeCheckpoint(Context context) {} + + @Override + public void afterRestore(Context context) {} +} diff --git a/integration-tests/tracecontext/build.gradle.kts b/integration-tests/tracecontext/build.gradle.kts index b9aced24889..ae32f7743bb 100644 --- a/integration-tests/tracecontext/build.gradle.kts +++ b/integration-tests/tracecontext/build.gradle.kts @@ -1,24 +1,28 @@ plugins { id("otel.java-conventions") - id("com.github.johnrengelman.shadow") + id("com.gradleup.shadow") } description = "OpenTelemetry W3C Context Propagation Integration Tests" otelJava.moduleName.set("io.opentelemetry.tracecontext.integration.tests") +otelJava.requireSuppressWarningsExplanation.set(false) dependencies { implementation(project(":sdk:all")) implementation(project(":extensions:trace-propagators")) + compileOnly("com.google.errorprone:error_prone_annotations") + implementation("com.linecorp.armeria:armeria") - testImplementation("org.testcontainers:junit-jupiter") + testImplementation("org.testcontainers:testcontainers-junit-jupiter") } tasks { - val shadowJar by existing(Jar::class) { + val shadowJar = named("shadowJar") { archiveFileName.set("tracecontext-tests.jar") + exclude("META-INF/*.kotlin_module") // not needed at runtime. avoids KotlinModuleMetadataTransformer warning manifest { attributes("Main-Class" to "io.opentelemetry.Application") @@ -31,3 +35,8 @@ tasks { jvmArgs("-Dio.opentelemetry.testArchive=${shadowJar.get().archiveFile.get().asFile.absolutePath}") } } + +// Skip ossIndexAudit on test module +tasks.named("ossIndexAudit") { + enabled = false +} diff --git a/integration-tests/tracecontext/docker/Dockerfile b/integration-tests/tracecontext/docker/Dockerfile index fc6dd4e7cea..f64694f36e0 100644 --- a/integration-tests/tracecontext/docker/Dockerfile +++ b/integration-tests/tracecontext/docker/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3 AS build +FROM python:3.15.2@sha256:d650864079477d7468a0f384777be3b534f2bbdf5beb6155dbd73a4723b89300 AS build # Main branch SHA as of April-1-2021 ARG TRACECONTEXT_GIT_TAG="dcd3ad9b7d6ac36f70ff3739874b73c11b0302a1" @@ -11,7 +11,7 @@ RUN unzip trace-context.zip RUN rm trace-context.zip RUN mv trace-context-${TRACECONTEXT_GIT_TAG}/test /tracecontext-testsuite -FROM python:3-slim +FROM python:3.15.2-slim@sha256:65a65fc7b30b06cb6df4930fd4650697cb23f4c2698ab81fc87e4b031bc36928 RUN pip install aiohttp diff --git a/integration-tests/tracecontext/src/main/java/io/opentelemetry/Application.java b/integration-tests/tracecontext/src/main/java/io/opentelemetry/Application.java index 35c7e846520..d5ec50eb1a0 100644 --- a/integration-tests/tracecontext/src/main/java/io/opentelemetry/Application.java +++ b/integration-tests/tracecontext/src/main/java/io/opentelemetry/Application.java @@ -32,6 +32,7 @@ import java.util.stream.Collectors; import javax.annotation.Nullable; +/** HTTP server for the W3C trace context conformance tests. */ public final class Application { private static final Logger logger = Logger.getLogger(Application.class.getName()); @@ -87,7 +88,7 @@ public String serve(RequestHeaders headers, List requests) { .getTextMapPropagator() .extract(Context.current(), headers, ArmeriaGetter.INSTANCE); - for (io.opentelemetry.Request req : requests) { + for (Request req : requests) { Span span = openTelemetry .getTracer("validation-server") diff --git a/integration-tests/tracecontext/src/main/java/io/opentelemetry/Request.java b/integration-tests/tracecontext/src/main/java/io/opentelemetry/Request.java index 3feb8ee18a4..bce27218dda 100644 --- a/integration-tests/tracecontext/src/main/java/io/opentelemetry/Request.java +++ b/integration-tests/tracecontext/src/main/java/io/opentelemetry/Request.java @@ -5,12 +5,13 @@ package io.opentelemetry; -import java.util.Arrays; +import java.util.List; import javax.annotation.Nullable; +/** An outbound request in a trace context conformance test, including any nested requests. */ public final class Request { @Nullable private String url; - @Nullable private Request[] arguments; + @Nullable private List arguments; @Nullable public String getUrl() { @@ -22,16 +23,16 @@ public void setUrl(String url) { } @Nullable - public Request[] getArguments() { + public List getArguments() { return arguments; } - public void setArguments(Request[] arguments) { + public void setArguments(List arguments) { this.arguments = arguments; } @Override public String toString() { - return "Request{" + "url='" + url + '\'' + ", arguments=" + Arrays.toString(arguments) + '}'; + return "Request{" + "url='" + url + '\'' + ", arguments=" + arguments + '}'; } } diff --git a/integration-tests/tracecontext/src/test/java/io/opentelemetry/integrationtests/tracecontext/TraceContextIntegrationTest.java b/integration-tests/tracecontext/src/test/java/io/opentelemetry/integrationtests/tracecontext/TraceContextIntegrationTest.java index bef89e32bce..4b8921b67f7 100644 --- a/integration-tests/tracecontext/src/test/java/io/opentelemetry/integrationtests/tracecontext/TraceContextIntegrationTest.java +++ b/integration-tests/tracecontext/src/test/java/io/opentelemetry/integrationtests/tracecontext/TraceContextIntegrationTest.java @@ -24,7 +24,7 @@ class TraceContextIntegrationTest { @Container private static final GenericContainer appContainer = - new GenericContainer<>(DockerImageName.parse("ghcr.io/open-telemetry/openjdk17")) + new GenericContainer<>(DockerImageName.parse("eclipse-temurin:17-jre-focal")) .withExposedPorts(5000) .withNetwork(Network.SHARED) .withNetworkAliases("app") @@ -35,6 +35,7 @@ class TraceContextIntegrationTest { MountableFile.forHostPath(System.getProperty("io.opentelemetry.testArchive")), "/opt/app.jar"); + @SuppressWarnings("UnusedVariable") @Container private static final GenericContainer testSuiteContainer = new GenericContainer<>( diff --git a/javadoc-crawler/README.md b/javadoc-crawler/README.md new file mode 100644 index 00000000000..4d44d0887bb --- /dev/null +++ b/javadoc-crawler/README.md @@ -0,0 +1,20 @@ +# Javadoc Crawler + +## Context + +The javadocs.io website lazy loads content only when the artifacts have been accessed, which can +lead to inaccuracies and confusion when someone loads the +https://www.javadoc.io/doc/io.opentelemetry page, since the published `Latest version` will only be +accurate if someone has accessed the page for the actual latest version. + +This module provides a simple scraper that pulls the list of all `io.opentelemetry` artifacts from +maven central and then visits each corresponding page on the javadoc.io website in order to trigger +loading them into the site's system. + +See https://github.com/open-telemetry/opentelemetry-java/issues/7294 for more information. + +## How to run + +```bash +./gradlew :javadoc-crawler:crawl +``` diff --git a/javadoc-crawler/build.gradle.kts b/javadoc-crawler/build.gradle.kts new file mode 100644 index 00000000000..a2b2b77a98a --- /dev/null +++ b/javadoc-crawler/build.gradle.kts @@ -0,0 +1,25 @@ +import org.gradle.api.JavaVersion + +plugins { + id("otel.java-conventions") +} + +dependencies { + implementation("com.fasterxml.jackson.core:jackson-databind") + testImplementation("org.assertj:assertj-core:3.27.7") +} + +description = "OpenTelemetry Javadoc Crawler" +otelJava.moduleName.set("io.opentelemetry.javadocs") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) +otelJava.minJavaVersionSupported.set(JavaVersion.VERSION_17) + +tasks { + val crawl = register("crawl") { + dependsOn(classes) + + mainClass.set("io.opentelemetry.javadocs.JavaDocsCrawler") + classpath(sourceSets["main"].runtimeClasspath) + } +} diff --git a/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/Artifact.java b/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/Artifact.java new file mode 100644 index 00000000000..3bcfdc80587 --- /dev/null +++ b/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/Artifact.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.javadocs; + +/** Maven coordinates of an artifact whose Javadoc is crawled. */ +public class Artifact { + private final String group; + private final String name; + private final String version; + + public Artifact(String group, String name, String version) { + this.group = group; + this.name = name; + this.version = version; + } + + public String getGroup() { + return group; + } + + public String getName() { + return name; + } + + public String getVersion() { + return version; + } + + @Override + public String toString() { + return group + ":" + name + ":" + version; + } +} diff --git a/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java b/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java new file mode 100644 index 00000000000..89c941ffbd3 --- /dev/null +++ b/javadoc-crawler/src/main/java/io/opentelemetry/javadocs/JavaDocsCrawler.java @@ -0,0 +1,311 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.javadocs; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Collectors; + +/** + * The javadoc.io site relies on someone accessing the page for an artifact version in order to + * update the contents of the site. This will query Maven Central for all artifacts under + * io.opentelemetry in order to identify the latest versions. Then it will crawl the associated + * pages on the javadoc.io site to trigger updates. + */ +public final class JavaDocsCrawler { + // Track list of groups and the minimum artifact versions that should be crawled. Update to the + // latest periodically to avoid crawling artifacts that stopped being published. + private static final Map GROUPS_AND_MIN_VERSION = + Map.of( + "io.opentelemetry", "1.60.1", + "io.opentelemetry.instrumentation", "2.25.0", + "io.opentelemetry.contrib", "1.54.0", + "io.opentelemetry.semconv", "1.40.0", + "io.opentelemetry.proto", "1.10.0"); + + private static final String MAVEN_CENTRAL_BASE_URL = + "https://central.sonatype.com/solrsearch/select?q=g:"; + private static final String JAVA_DOCS_BASE_URL = "https://javadoc.io/doc/"; + // Every group is fetched in a single request, so no paging parameter is sent. The largest group + // currently holds fewer than 200 artifacts and getArtifacts fails if the response is incomplete. + private static final int MAX_ROWS = 500; + private static final int THROTTLE_MS = 500; + + // visible for testing + static final String JAVA_DOC_DOWNLOADED_TEXT = "Javadoc is being downloaded"; + + private static final Logger logger = Logger.getLogger(JavaDocsCrawler.class.getName()); + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public static void main(String[] args) throws Exception { + HttpClient client = HttpClient.newHttpClient(); + + for (Map.Entry groupAndMinVersion : GROUPS_AND_MIN_VERSION.entrySet()) { + String group = groupAndMinVersion.getKey(); + + List artifacts = getArtifacts(client, group); + if (artifacts.isEmpty()) { + logger.log(Level.SEVERE, "No artifacts found for group " + group); + continue; + } + logger.info( + String.format(Locale.ROOT, "Found %d artifacts for group " + group, artifacts.size())); + + List updated = crawlJavaDocs(client, groupAndMinVersion.getValue(), artifacts); + if (updated.isEmpty()) { + logger.info("No updates were needed for group " + group); + continue; + } + + logger.info( + "Artifacts that triggered updates for group " + + group + + ":\n" + + updated.stream().map(Artifact::toString).collect(Collectors.joining("\n"))); + } + } + + static List getArtifacts(HttpClient client, String group) + throws IOException, InterruptedException { + Map map = queryMavenCentral(client, group, MAX_ROWS); + + // a 200 response without numFound means the endpoint changed shape; failing here keeps that + // from silently disabling the completeness check below + int numFound = + Optional.ofNullable(map) + .map(mavenResult -> (Map) mavenResult.get("response")) + .map(response -> (Integer) response.get("numFound")) + .orElseThrow(() -> + new IOException( + "Maven Central response for group " + + group + + " did not contain response.numFound")); + + List artifacts = convertToArtifacts(map); + if (artifacts.size() < numFound) { + throw new IOException( + String.format( + Locale.ROOT, + "Received %d of %d artifacts for group %s, raise MAX_ROWS", + artifacts.size(), + numFound, + group)); + } + + return artifacts; + } + + private static List convertToArtifacts(Map map) { + return Optional.ofNullable(map) + .map(mavenResults -> (Map) mavenResults.get("response")) + .map(response -> (List) response.get("docs")) + .map(docs -> { + List artifacts = new ArrayList<>(); + for (Object doc : docs) { + Map docMap = (Map) doc; + String group = Objects.requireNonNull((String) docMap.get("g"), "g"); + String artifact = Objects.requireNonNull((String) docMap.get("a"), "a"); + String version = + Objects.requireNonNull((String) docMap.get("latestVersion"), "latestVersion"); + artifacts.add(new Artifact(Objects.requireNonNull(group), artifact, version)); + } + return artifacts; + }) + .orElseGet(ArrayList::new); + } + + private static Map queryMavenCentral(HttpClient client, String group, int rows) + throws IOException, InterruptedException { + URI uri = + URI.create( + String.format( + Locale.ROOT, "%s%s&rows=%d&wt=json", MAVEN_CENTRAL_BASE_URL, group, rows)); + + HttpRequest request = HttpRequest.newBuilder(uri).GET().build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() != 200) { + logger.log( + Level.SEVERE, + "Unexpected response code " + + response.statusCode() + + " for uri: " + + uri.toASCIIString() + + "\n" + + response.body()); + throw new IOException("Unable to pull Maven central artifacts list"); + } + return objectMapper.readValue(response.body(), Map.class); + } + + static List crawlJavaDocs( + HttpClient client, String minVersion, List artifacts) + throws IOException, InterruptedException { + List updatedArtifacts = new ArrayList<>(); + SemanticVersion minSemanticVersion = SemanticVersion.parse(minVersion); + + for (Artifact artifact : artifacts) { + if (SemanticVersion.parse(artifact.getVersion()).compareTo(minSemanticVersion) < 0) { + logger.info( + String.format( + "Skipping crawling %s due to version %s being less than minVersion %s", + artifact, artifact.getVersion(), minVersion)); + continue; + } + + String[] parts = artifact.getName().split("-"); + StringBuilder path = new StringBuilder(); + path.append(JAVA_DOCS_BASE_URL) + .append(artifact.getGroup()) + .append("/") + .append(artifact.getName()) + .append("/") + .append(artifact.getVersion()) + .append("/") + .append(String.join("/", parts)) + .append("/package-summary.html"); + + HttpRequest crawlRequest = HttpRequest.newBuilder(URI.create(path.toString())).GET().build(); + logger.info(String.format("Crawling %s at: %s", artifact, path)); + HttpResponse crawlResponse = + client.send(crawlRequest, HttpResponse.BodyHandlers.ofString()); + + // gets a status code 303 when version exists and the site redirects it to use /latest/ + if (crawlResponse.statusCode() != 200 && crawlResponse.statusCode() != 303) { + logger.log( + Level.WARNING, + String.format( + Locale.ROOT, + "Crawl failed for %s with status code %d at URL %s\nResponse: %s", + artifact, + crawlResponse.statusCode(), + path, + crawlResponse.body())); + continue; + } + + if (crawlResponse.body().contains(JAVA_DOC_DOWNLOADED_TEXT)) { + updatedArtifacts.add(artifact); + } + + Thread.sleep(THROTTLE_MS); // some light throttling + } + return updatedArtifacts; + } + + static final class SemanticVersion implements Comparable { + private static final Comparator> CORE_VERSION_COMPARATOR = + (left, right) -> { + for (int i = 0; i < Math.max(left.size(), right.size()); i++) { + int leftPart = i < left.size() ? left.get(i) : 0; + int rightPart = i < right.size() ? right.get(i) : 0; + int result = Integer.compare(leftPart, rightPart); + if (result != 0) { + return result; + } + } + return 0; + }; + + private final List coreVersionParts; + private final String qualifier; + + private SemanticVersion(List coreVersionParts, String qualifier) { + this.coreVersionParts = coreVersionParts; + this.qualifier = qualifier; + } + + static SemanticVersion parse(String version) { + String[] versionParts = version.split("-", 2); + List coreVersionParts = new ArrayList<>(); + for (String part : versionParts[0].split("\\.")) { + coreVersionParts.add(Integer.parseInt(part)); + } + String qualifier = versionParts.length == 2 ? versionParts[1] : ""; + return new SemanticVersion(coreVersionParts, qualifier); + } + + @Override + public int compareTo(SemanticVersion other) { + int coreVersionResult = + CORE_VERSION_COMPARATOR.compare(coreVersionParts, other.coreVersionParts); + if (coreVersionResult != 0) { + return coreVersionResult; + } + if (qualifier.isEmpty() && other.qualifier.isEmpty()) { + return 0; + } + if (qualifier.isEmpty()) { + return 1; + } + if (other.qualifier.isEmpty()) { + return -1; + } + return compareQualifier(qualifier, other.qualifier); + } + + private static int compareQualifier(String leftQualifier, String rightQualifier) { + String[] leftParts = leftQualifier.split("\\."); + String[] rightParts = rightQualifier.split("\\."); + + for (int i = 0; i < Math.max(leftParts.length, rightParts.length); i++) { + if (i >= leftParts.length) { + return -1; + } + if (i >= rightParts.length) { + return 1; + } + + String leftIdentifier = leftParts[i]; + String rightIdentifier = rightParts[i]; + if (leftIdentifier.equals(rightIdentifier)) { + continue; + } + + boolean leftNumeric = isNumericIdentifier(leftIdentifier); + boolean rightNumeric = isNumericIdentifier(rightIdentifier); + if (leftNumeric && rightNumeric) { + if (leftIdentifier.length() != rightIdentifier.length()) { + return Integer.compare(leftIdentifier.length(), rightIdentifier.length()); + } + return leftIdentifier.compareTo(rightIdentifier); + } + if (leftNumeric != rightNumeric) { + return leftNumeric ? -1 : 1; + } + return leftIdentifier.compareTo(rightIdentifier); + } + return 0; + } + + private static boolean isNumericIdentifier(String identifier) { + if (identifier.isEmpty()) { + return false; + } + for (int i = 0; i < identifier.length(); i++) { + if (!Character.isDigit(identifier.charAt(i))) { + return false; + } + } + return true; + } + } + + private JavaDocsCrawler() {} +} diff --git a/javadoc-crawler/src/test/java/io/opentelemetry/javadocs/JavaDocsCrawlerTest.java b/javadoc-crawler/src/test/java/io/opentelemetry/javadocs/JavaDocsCrawlerTest.java new file mode 100644 index 00000000000..5b12d3b1439 --- /dev/null +++ b/javadoc-crawler/src/test/java/io/opentelemetry/javadocs/JavaDocsCrawlerTest.java @@ -0,0 +1,166 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.javadocs; + +import static io.opentelemetry.javadocs.JavaDocsCrawler.JAVA_DOC_DOWNLOADED_TEXT; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.tuple; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class JavaDocsCrawlerTest { + @Mock HttpClient mockClient; + @Mock HttpResponse mockMavenCentralRequest1; + @Mock HttpResponse mockMavenCentralRequest2; + @Mock HttpResponse mockJavaDocResponse; + + @Test + void testGetArtifactsUsesASingleRequest() throws IOException, InterruptedException { + String response = + """ + { + "response": { + "numFound": 2, + "docs": [ + {"g": "group", "a": "artifact1", "latestVersion": "1.0"}, + {"g": "group", "a": "artifact2", "latestVersion": "1.1"} + ] + } + } + """; + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); + + when(mockMavenCentralRequest1.body()).thenReturn(response); + when(mockMavenCentralRequest1.statusCode()).thenReturn(200); + + when(mockClient.send(any(), any())).thenReturn(mockMavenCentralRequest1); + + List artifacts = JavaDocsCrawler.getArtifacts(mockClient, "io.opentelemetry"); + + verify(mockClient, times(1)).send(requestCaptor.capture(), any()); + + String uri = requestCaptor.getValue().uri().toString(); + assertThat(uri) + .startsWith("https://central.sonatype.com/solrsearch/select?q=g:io.opentelemetry"); + assertThat(uri).contains("rows=500"); + assertThat(uri).doesNotContain("start="); + assertThat(artifacts) + .extracting(Artifact::getGroup, Artifact::getName, Artifact::getVersion) + .containsExactly(tuple("group", "artifact1", "1.0"), tuple("group", "artifact2", "1.1")); + } + + @Test + void testGetArtifactsFailsOnIncompleteResponse() throws IOException, InterruptedException { + String response = + """ + { + "response": { + "numFound": 40, + "docs": [ + {"g": "group", "a": "artifact1", "latestVersion": "1.0"}, + {"g": "group", "a": "artifact2", "latestVersion": "1.1"} + ] + } + } + """; + + when(mockMavenCentralRequest2.body()).thenReturn(response); + when(mockMavenCentralRequest2.statusCode()).thenReturn(200); + + when(mockClient.send(any(), any())).thenReturn(mockMavenCentralRequest2); + + assertThatThrownBy(() -> JavaDocsCrawler.getArtifacts(mockClient, "io.opentelemetry")) + .isInstanceOf(IOException.class) + .hasMessageContaining("io.opentelemetry"); + } + + @Test + void testGetArtifactsFailsWithoutNumFound() throws IOException, InterruptedException { + String response = + """ + { + "response": { + "docs": [ + {"g": "group", "a": "artifact1", "latestVersion": "1.0"} + ] + } + } + """; + + when(mockMavenCentralRequest1.body()).thenReturn(response); + when(mockMavenCentralRequest1.statusCode()).thenReturn(200); + + when(mockClient.send(any(), any())).thenReturn(mockMavenCentralRequest1); + + assertThatThrownBy(() -> JavaDocsCrawler.getArtifacts(mockClient, "io.opentelemetry")) + .isInstanceOf(IOException.class) + .hasMessageContaining("numFound") + .hasMessageContaining("io.opentelemetry"); + } + + @Test + void testCrawler() throws IOException, InterruptedException { + Artifact artifact = new Artifact("io.opentelemetry", "opentelemetry-context", "1.49.0"); + ArgumentCaptor requestCaptor = ArgumentCaptor.forClass(HttpRequest.class); + + when(mockJavaDocResponse.body()).thenReturn(JAVA_DOC_DOWNLOADED_TEXT); + when(mockJavaDocResponse.statusCode()).thenReturn(200); + + when(mockClient.send(any(), any())).thenReturn(mockJavaDocResponse); + + List updated = JavaDocsCrawler.crawlJavaDocs(mockClient, "1.49.0", List.of(artifact)); + + verify(mockClient, times(1)).send(requestCaptor.capture(), any()); + + assertThat(requestCaptor.getValue().uri().toString()) + .isEqualTo( + "https://javadoc.io/doc/io.opentelemetry/opentelemetry-context/1.49.0/opentelemetry/context/package-summary.html"); + assertThat(updated).containsExactly(artifact); + } + + @Test + void compareVersionsUsesSemanticOrdering() { + assertThat(compareVersions("1.9.0", "1.49.0")).isLessThan(0); + assertThat(compareVersions("1.49.0", "1.49.0")).isZero(); + assertThat(compareVersions("1.60.0", "1.49.0")).isGreaterThan(0); + assertThat(compareVersions("1.60.0-alpha", "1.60.0")).isLessThan(0); + assertThat(compareVersions("1.0.0-rc.2", "1.0.0-rc.10")).isLessThan(0); + assertThat(compareVersions("1.0.0-rc.10", "1.0.0")).isLessThan(0); + } + + @Test + void crawlSkipsArtifactsBelowMinVersionUsingSemanticComparison() + throws IOException, InterruptedException { + Artifact oldArtifact = new Artifact("io.opentelemetry", "opentelemetry-context", "1.9.0"); + + List updated = + JavaDocsCrawler.crawlJavaDocs(mockClient, "1.49.0", List.of(oldArtifact)); + + verify(mockClient, never()).send(any(HttpRequest.class), any()); + assertThat(updated).isEmpty(); + } + + private static int compareVersions(String left, String right) { + return JavaDocsCrawler.SemanticVersion.parse(left) + .compareTo(JavaDocsCrawler.SemanticVersion.parse(right)); + } +} diff --git a/micrometer1-shim/build.gradle.kts b/micrometer1-shim/build.gradle.kts deleted file mode 100644 index b7dd688bb06..00000000000 --- a/micrometer1-shim/build.gradle.kts +++ /dev/null @@ -1,51 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") -} - -description = "OpenTelemetry Micrometer Bridge" -otelJava.moduleName.set("io.opentelemetry.micrometer1shim") - -dependencies { - api(project(":api:all")) - - api("io.micrometer:micrometer-core") - - testImplementation(project(":sdk:testing")) -} - -testing { - suites { - // Test older LTS versions - val testMicrometer15 by registering(JvmTestSuite::class) { - sources { - java { - setSrcDirs(listOf("src/test/java")) - } - } - dependencies { - implementation(project(":sdk:testing")) - - implementation(project.dependencies.enforcedPlatform("io.micrometer:micrometer-bom:1.5.17")) - } - } - val testMicrometer16 by registering(JvmTestSuite::class) { - sources { - java { - setSrcDirs(listOf("src/test/java")) - } - } - dependencies { - implementation(project(":sdk:testing")) - - implementation(project.dependencies.enforcedPlatform("io.micrometer:micrometer-bom:1.6.13")) - } - } - } -} - -tasks { - check { - dependsOn(testing.suites) - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/Bridging.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/Bridging.java deleted file mode 100644 index 1c632457ef8..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/Bridging.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.Statistic; -import io.micrometer.core.instrument.Tag; -import io.micrometer.core.instrument.config.NamingConvention; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -final class Bridging { - - private static final ConcurrentMap descriptionsCache = new ConcurrentHashMap<>(); - - static Attributes tagsAsAttributes(Meter.Id id, NamingConvention namingConvention) { - Iterable tags = id.getTagsAsIterable(); - if (!tags.iterator().hasNext()) { - return Attributes.empty(); - } - AttributesBuilder builder = Attributes.builder(); - for (Tag tag : tags) { - String tagKey = namingConvention.tagKey(tag.getKey()); - String tagValue = namingConvention.tagValue(tag.getValue()); - builder.put(tagKey, tagValue); - } - return builder.build(); - } - - static String name(Meter.Id id, NamingConvention namingConvention) { - return namingConvention.name(id.getName(), id.getType(), id.getBaseUnit()); - } - - static String description(Meter.Id id) { - return descriptionsCache.computeIfAbsent( - id.getName(), - n -> { - String description = id.getDescription(); - return description != null ? description : ""; - }); - } - - static String baseUnit(Meter.Id id) { - String baseUnit = id.getBaseUnit(); - return baseUnit == null ? "1" : baseUnit; - } - - static String statisticInstrumentName( - Meter.Id id, Statistic statistic, NamingConvention namingConvention) { - String prefix = id.getName() + "."; - // use "total_time" instead of "total" to avoid clashing with Statistic.TOTAL - String statisticStr = - statistic == Statistic.TOTAL_TIME ? "total_time" : statistic.getTagValueRepresentation(); - return namingConvention.name(prefix + statisticStr, id.getType(), id.getBaseUnit()); - } - - private Bridging() {} -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/DoubleMeasurementRecorder.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/DoubleMeasurementRecorder.java deleted file mode 100644 index f57352fdbb2..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/DoubleMeasurementRecorder.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; -import java.lang.ref.WeakReference; -import java.util.function.Consumer; -import java.util.function.ToDoubleFunction; -import javax.annotation.Nullable; - -final class DoubleMeasurementRecorder implements Consumer { - - // using a weak reference here so that the existence of the micrometer Meter does not block the - // measured object from being GC'd; e.g. a Gauge (or any other async instrument) must not block - // garbage collection of the object that it measures - private final WeakReference objWeakRef; - private final ToDoubleFunction metricFunction; - private final Attributes attributes; - - DoubleMeasurementRecorder( - @Nullable T obj, ToDoubleFunction metricFunction, Attributes attributes) { - this.objWeakRef = new WeakReference<>(obj); - this.metricFunction = metricFunction; - this.attributes = attributes; - } - - @Override - public void accept(ObservableDoubleMeasurement measurement) { - T obj = objWeakRef.get(); - if (obj != null) { - measurement.record(metricFunction.applyAsDouble(obj), attributes); - } - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/LongMeasurementRecorder.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/LongMeasurementRecorder.java deleted file mode 100644 index fcf75a4f17c..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/LongMeasurementRecorder.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.ObservableLongMeasurement; -import java.lang.ref.WeakReference; -import java.util.function.Consumer; -import java.util.function.ToLongFunction; -import javax.annotation.Nullable; - -final class LongMeasurementRecorder implements Consumer { - - // using a weak reference here so that the existence of the micrometer Meter does not block the - // measured object from being GC'd; e.g. a Gauge (or any other async instrument) must not block - // garbage collection of the object that it measures - private final WeakReference objWeakRef; - private final ToLongFunction metricFunction; - private final Attributes attributes; - - LongMeasurementRecorder( - @Nullable T obj, ToLongFunction metricFunction, Attributes attributes) { - this.objWeakRef = new WeakReference<>(obj); - this.metricFunction = metricFunction; - this.attributes = attributes; - } - - @Override - public void accept(ObservableLongMeasurement measurement) { - T obj = objWeakRef.get(); - if (obj != null) { - measurement.record(metricFunction.applyAsLong(obj), attributes); - } - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryCounter.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryCounter.java deleted file mode 100644 index 79e8c0a091c..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryCounter.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.baseUnit; -import static io.opentelemetry.micrometer1shim.Bridging.name; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.util.MeterEquivalence; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.DoubleCounter; -import io.opentelemetry.api.metrics.Meter; -import java.util.Collections; -import javax.annotation.Nullable; - -@SuppressWarnings("HashCodeToString") -final class OpenTelemetryCounter implements Counter, RemovableMeter { - - private final Id id; - // TODO: use bound instruments when they're available - private final DoubleCounter otelCounter; - private final Attributes attributes; - - private volatile boolean removed = false; - - OpenTelemetryCounter(Id id, NamingConvention namingConvention, Meter otelMeter) { - this.id = id; - - this.attributes = tagsAsAttributes(id, namingConvention); - String conventionName = name(id, namingConvention); - this.otelCounter = - otelMeter - .counterBuilder(conventionName) - .setDescription(Bridging.description(id)) - .setUnit(baseUnit(id)) - .ofDoubles() - .build(); - } - - @Override - public void increment(double v) { - if (removed) { - return; - } - otelCounter.add(v, attributes); - } - - @Override - public double count() { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public Id getId() { - return id; - } - - @Override - public void onRemove() { - removed = true; - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - public boolean equals(@Nullable Object o) { - return MeterEquivalence.equals(this, o); - } - - @Override - public int hashCode() { - return MeterEquivalence.hashCode(this); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryDistributionSummary.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryDistributionSummary.java deleted file mode 100644 index 2414139a6f1..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryDistributionSummary.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.baseUnit; -import static io.opentelemetry.micrometer1shim.Bridging.name; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.AbstractDistributionSummary; -import io.micrometer.core.instrument.Clock; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; -import io.micrometer.core.instrument.distribution.NoopHistogram; -import io.micrometer.core.instrument.distribution.TimeWindowMax; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.DoubleHistogram; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleGauge; -import java.util.Collections; -import java.util.concurrent.atomic.DoubleAdder; -import java.util.concurrent.atomic.LongAdder; - -final class OpenTelemetryDistributionSummary extends AbstractDistributionSummary - implements RemovableMeter { - - private final Measurements measurements; - private final TimeWindowMax max; - // TODO: use bound instruments when they're available - private final DoubleHistogram otelHistogram; - private final Attributes attributes; - private final ObservableDoubleGauge observableMax; - - private volatile boolean removed = false; - - OpenTelemetryDistributionSummary( - Id id, - NamingConvention namingConvention, - Clock clock, - DistributionStatisticConfig distributionStatisticConfig, - double scale, - Meter otelMeter) { - super(id, clock, distributionStatisticConfig, scale, false); - - if (isUsingMicrometerHistograms()) { - measurements = new MicrometerHistogramMeasurements(); - } else { - measurements = NoopMeasurements.INSTANCE; - } - max = new TimeWindowMax(clock, distributionStatisticConfig); - - this.attributes = tagsAsAttributes(id, namingConvention); - - String name = name(id, namingConvention); - this.otelHistogram = - otelMeter - .histogramBuilder(name) - .setDescription(Bridging.description(id)) - .setUnit(baseUnit(id)) - .build(); - this.observableMax = - otelMeter - .gaugeBuilder(name + ".max") - .setDescription(Bridging.description(id)) - .setUnit(baseUnit(id)) - .buildWithCallback( - new DoubleMeasurementRecorder<>(max, TimeWindowMax::poll, attributes)); - } - - boolean isUsingMicrometerHistograms() { - return histogram != NoopHistogram.INSTANCE; - } - - @Override - protected void recordNonNegative(double amount) { - if (!removed) { - otelHistogram.record(amount, attributes); - measurements.record(amount); - max.record(amount); - } - } - - @Override - public long count() { - return measurements.count(); - } - - @Override - public double totalAmount() { - return measurements.totalAmount(); - } - - @Override - public double max() { - return max.poll(); - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public void onRemove() { - removed = true; - observableMax.close(); - } - - private interface Measurements { - void record(double amount); - - long count(); - - double totalAmount(); - } - - // if micrometer histograms are not being used then there's no need to keep any local state - // OpenTelemetry metrics bridge does not support reading measurements - enum NoopMeasurements implements Measurements { - INSTANCE; - - @Override - public void record(double amount) {} - - @Override - public long count() { - UnsupportedReadLogger.logWarning(); - return 0; - } - - @Override - public double totalAmount() { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - } - - // calculate count and totalAmount value for the use of micrometer histograms - // kinda similar to how DropwizardDistributionSummary does that - private static final class MicrometerHistogramMeasurements implements Measurements { - - private final LongAdder count = new LongAdder(); - private final DoubleAdder totalAmount = new DoubleAdder(); - - @Override - public void record(double amount) { - count.increment(); - totalAmount.add(amount); - } - - @Override - public long count() { - return count.sum(); - } - - @Override - public double totalAmount() { - return totalAmount.sum(); - } - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryFunctionCounter.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryFunctionCounter.java deleted file mode 100644 index 3199fe83fb5..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryFunctionCounter.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.baseUnit; -import static io.opentelemetry.micrometer1shim.Bridging.name; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.FunctionCounter; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.util.MeterEquivalence; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleCounter; -import java.util.Collections; -import java.util.function.ToDoubleFunction; -import javax.annotation.Nullable; - -@SuppressWarnings("HashCodeToString") -final class OpenTelemetryFunctionCounter implements FunctionCounter, RemovableMeter { - - private final Id id; - private final ObservableDoubleCounter observableCount; - - OpenTelemetryFunctionCounter( - Id id, - NamingConvention namingConvention, - T obj, - ToDoubleFunction countFunction, - Meter otelMeter) { - this.id = id; - - String name = name(id, namingConvention); - observableCount = - otelMeter - .counterBuilder(name) - .ofDoubles() - .setDescription(Bridging.description(id)) - .setUnit(baseUnit(id)) - .buildWithCallback( - new DoubleMeasurementRecorder<>( - obj, countFunction, tagsAsAttributes(id, namingConvention))); - } - - @Override - public double count() { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public Id getId() { - return id; - } - - @Override - public void onRemove() { - observableCount.close(); - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - public boolean equals(@Nullable Object o) { - return MeterEquivalence.equals(this, o); - } - - @Override - public int hashCode() { - return MeterEquivalence.hashCode(this); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryFunctionTimer.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryFunctionTimer.java deleted file mode 100644 index 9df1c7f4192..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryFunctionTimer.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.micrometer.core.instrument.FunctionTimer; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.util.MeterEquivalence; -import io.micrometer.core.instrument.util.TimeUtils; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleCounter; -import io.opentelemetry.api.metrics.ObservableLongCounter; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import java.util.function.ToDoubleFunction; -import java.util.function.ToLongFunction; -import javax.annotation.Nullable; - -@SuppressWarnings("HashCodeToString") -final class OpenTelemetryFunctionTimer implements FunctionTimer, RemovableMeter { - - private final Id id; - private final TimeUnit baseTimeUnit; - private final ObservableLongCounter observableCount; - private final ObservableDoubleCounter observableTotalTime; - - OpenTelemetryFunctionTimer( - Id id, - NamingConvention namingConvention, - T obj, - ToLongFunction countFunction, - ToDoubleFunction totalTimeFunction, - TimeUnit totalTimeFunctionUnit, - TimeUnit baseTimeUnit, - Meter otelMeter) { - - this.id = id; - this.baseTimeUnit = baseTimeUnit; - - String name = Bridging.name(id, namingConvention); - Attributes attributes = Bridging.tagsAsAttributes(id, namingConvention); - - this.observableCount = - otelMeter - .counterBuilder(name + ".count") - .setDescription(Bridging.description(id)) - .setUnit("1") - .buildWithCallback(new LongMeasurementRecorder<>(obj, countFunction, attributes)); - - this.observableTotalTime = - otelMeter - .counterBuilder(name + ".sum") - .ofDoubles() - .setDescription(Bridging.description(id)) - .setUnit(TimeUnitHelper.getUnitString(baseTimeUnit)) - .buildWithCallback( - new DoubleMeasurementRecorder<>( - obj, - val -> - TimeUtils.convert( - totalTimeFunction.applyAsDouble(val), - totalTimeFunctionUnit, - baseTimeUnit), - attributes)); - } - - @Override - public double count() { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - - @Override - public double totalTime(TimeUnit unit) { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - - @Override - public double mean(TimeUnit unit) { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - - @Override - public TimeUnit baseTimeUnit() { - return baseTimeUnit; - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public Id getId() { - return id; - } - - @Override - public void onRemove() { - observableCount.close(); - observableTotalTime.close(); - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - public boolean equals(@Nullable Object o) { - return MeterEquivalence.equals(this, o); - } - - @Override - public int hashCode() { - return MeterEquivalence.hashCode(this); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryGauge.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryGauge.java deleted file mode 100644 index 33d9b3fa5a1..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryGauge.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.baseUnit; -import static io.opentelemetry.micrometer1shim.Bridging.name; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.util.MeterEquivalence; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleGauge; -import java.util.Collections; -import java.util.function.ToDoubleFunction; -import javax.annotation.Nullable; - -@SuppressWarnings("HashCodeToString") -final class OpenTelemetryGauge implements Gauge, RemovableMeter { - - private final Id id; - private final ObservableDoubleGauge observableGauge; - - OpenTelemetryGauge( - Id id, - NamingConvention namingConvention, - @Nullable T obj, - ToDoubleFunction objMetric, - Meter otelMeter) { - - this.id = id; - - String name = name(id, namingConvention); - observableGauge = - otelMeter - .gaugeBuilder(name) - .setDescription(Bridging.description(id)) - .setUnit(baseUnit(id)) - .buildWithCallback( - new DoubleMeasurementRecorder<>( - obj, objMetric, tagsAsAttributes(id, namingConvention))); - } - - @Override - public double value() { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public Id getId() { - return id; - } - - @Override - public void onRemove() { - observableGauge.close(); - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - public boolean equals(@Nullable Object o) { - return MeterEquivalence.equals(this, o); - } - - @Override - public int hashCode() { - return MeterEquivalence.hashCode(this); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryLongTaskTimer.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryLongTaskTimer.java deleted file mode 100644 index 5b60761373f..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryLongTaskTimer.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.name; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.Clock; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; -import io.micrometer.core.instrument.internal.DefaultLongTaskTimer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleUpDownCounter; -import io.opentelemetry.api.metrics.ObservableLongUpDownCounter; -import java.util.Collections; -import java.util.concurrent.TimeUnit; - -final class OpenTelemetryLongTaskTimer extends DefaultLongTaskTimer implements RemovableMeter { - - private final DistributionStatisticConfig distributionStatisticConfig; - private final ObservableLongUpDownCounter observableActiveTasks; - private final ObservableDoubleUpDownCounter observableDuration; - - OpenTelemetryLongTaskTimer( - Id id, - NamingConvention namingConvention, - Clock clock, - TimeUnit baseTimeUnit, - DistributionStatisticConfig distributionStatisticConfig, - Meter otelMeter) { - super(id, clock, baseTimeUnit, distributionStatisticConfig, false); - - this.distributionStatisticConfig = distributionStatisticConfig; - - String name = name(id, namingConvention); - Attributes attributes = tagsAsAttributes(id, namingConvention); - - this.observableActiveTasks = - otelMeter - .upDownCounterBuilder(name + ".active") - .setDescription(Bridging.description(id)) - .setUnit("tasks") - .buildWithCallback( - new LongMeasurementRecorder<>(this, DefaultLongTaskTimer::activeTasks, attributes)); - this.observableDuration = - otelMeter - .upDownCounterBuilder(name + ".duration") - .ofDoubles() - .setDescription(Bridging.description(id)) - .setUnit(TimeUnitHelper.getUnitString(baseTimeUnit)) - .buildWithCallback( - new DoubleMeasurementRecorder<>( - this, t -> t.duration(t.baseTimeUnit()), attributes)); - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public void onRemove() { - observableActiveTasks.close(); - observableDuration.close(); - } - - boolean isUsingMicrometerHistograms() { - return distributionStatisticConfig.isPublishingPercentiles() - || distributionStatisticConfig.isPublishingHistogram(); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeter.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeter.java deleted file mode 100644 index c108f7d1905..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeter.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.baseUnit; -import static io.opentelemetry.micrometer1shim.Bridging.statisticInstrumentName; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.util.MeterEquivalence; -import io.opentelemetry.api.common.Attributes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import javax.annotation.Nullable; - -@SuppressWarnings("HashCodeToString") -final class OpenTelemetryMeter implements Meter, RemovableMeter { - - private final Id id; - private final List observableInstruments; - - OpenTelemetryMeter( - Id id, - NamingConvention namingConvention, - Iterable measurements, - io.opentelemetry.api.metrics.Meter otelMeter) { - this.id = id; - Attributes attributes = tagsAsAttributes(id, namingConvention); - - List observableInstruments = new ArrayList<>(); - for (Measurement measurement : measurements) { - String name = statisticInstrumentName(id, measurement.getStatistic(), namingConvention); - String description = Bridging.description(id); - String baseUnit = baseUnit(id); - DoubleMeasurementRecorder callback = - new DoubleMeasurementRecorder<>(measurement, Measurement::getValue, attributes); - - switch (measurement.getStatistic()) { - case TOTAL: - // fall through - case TOTAL_TIME: - case COUNT: - observableInstruments.add( - otelMeter - .counterBuilder(name) - .ofDoubles() - .setDescription(description) - .setUnit(baseUnit) - .buildWithCallback(callback)); - break; - - case ACTIVE_TASKS: - observableInstruments.add( - otelMeter - .upDownCounterBuilder(name) - .ofDoubles() - .setDescription(description) - .setUnit(baseUnit) - .buildWithCallback(callback)); - break; - - case DURATION: - // fall through - case MAX: - case VALUE: - case UNKNOWN: - observableInstruments.add( - otelMeter - .gaugeBuilder(name) - .setDescription(description) - .setUnit(baseUnit) - .buildWithCallback(callback)); - break; - } - } - this.observableInstruments = observableInstruments; - } - - @Override - public Id getId() { - return id; - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public void onRemove() { - try { - for (AutoCloseable observableInstrument : observableInstruments) { - observableInstrument.close(); - } - } catch (Exception e) { - throw new IllegalStateException("SDK instruments should never throw on close()", e); - } - } - - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - public boolean equals(@Nullable Object o) { - return MeterEquivalence.equals(this, o); - } - - @Override - public int hashCode() { - return MeterEquivalence.hashCode(this); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeterRegistry.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeterRegistry.java deleted file mode 100644 index c1dcc1f50d8..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeterRegistry.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.micrometer.core.instrument.Clock; -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.FunctionCounter; -import io.micrometer.core.instrument.FunctionTimer; -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Timer; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; -import io.micrometer.core.instrument.distribution.HistogramGauges; -import io.micrometer.core.instrument.distribution.pause.PauseDetector; -import io.opentelemetry.api.OpenTelemetry; -import java.util.concurrent.TimeUnit; -import java.util.function.ToDoubleFunction; -import java.util.function.ToLongFunction; -import javax.annotation.Nullable; - -/** - * A {@link MeterRegistry} implementation that forwards all the captured metrics to the {@linkplain - * io.opentelemetry.api.metrics.Meter OpenTelemetry Meter} obtained from the passed {@link - * OpenTelemetry} instance. - */ -public final class OpenTelemetryMeterRegistry extends MeterRegistry { - - /** - * Returns a new {@link OpenTelemetryMeterRegistry} configured with the given {@link - * OpenTelemetry}. - */ - public static MeterRegistry create(OpenTelemetry openTelemetry) { - return builder(openTelemetry).build(); - } - - /** - * Returns a new {@link OpenTelemetryMeterRegistryBuilder} configured with the given {@link - * OpenTelemetry}. - */ - public static OpenTelemetryMeterRegistryBuilder builder(OpenTelemetry openTelemetry) { - return new OpenTelemetryMeterRegistryBuilder(openTelemetry); - } - - private final TimeUnit baseTimeUnit; - private final io.opentelemetry.api.metrics.Meter otelMeter; - - OpenTelemetryMeterRegistry( - Clock clock, - TimeUnit baseTimeUnit, - NamingConvention namingConvention, - io.opentelemetry.api.metrics.Meter otelMeter) { - super(clock); - this.baseTimeUnit = baseTimeUnit; - this.otelMeter = otelMeter; - - this.config() - .namingConvention(namingConvention) - .onMeterRemoved(OpenTelemetryMeterRegistry::onMeterRemoved); - } - - @Override - protected Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction valueFunction) { - return new OpenTelemetryGauge<>(id, config().namingConvention(), obj, valueFunction, otelMeter); - } - - @Override - protected Counter newCounter(Meter.Id id) { - return new OpenTelemetryCounter(id, config().namingConvention(), otelMeter); - } - - @Override - protected LongTaskTimer newLongTaskTimer( - Meter.Id id, DistributionStatisticConfig distributionStatisticConfig) { - OpenTelemetryLongTaskTimer timer = - new OpenTelemetryLongTaskTimer( - id, - config().namingConvention(), - clock, - getBaseTimeUnit(), - distributionStatisticConfig, - otelMeter); - if (timer.isUsingMicrometerHistograms()) { - HistogramGauges.registerWithCommonFormat(timer, this); - } - return timer; - } - - @Override - protected Timer newTimer( - Meter.Id id, - DistributionStatisticConfig distributionStatisticConfig, - PauseDetector pauseDetector) { - OpenTelemetryTimer timer = - new OpenTelemetryTimer( - id, - config().namingConvention(), - clock, - distributionStatisticConfig, - pauseDetector, - getBaseTimeUnit(), - otelMeter); - if (timer.isUsingMicrometerHistograms()) { - HistogramGauges.registerWithCommonFormat(timer, this); - } - return timer; - } - - @Override - protected DistributionSummary newDistributionSummary( - Meter.Id id, DistributionStatisticConfig distributionStatisticConfig, double scale) { - OpenTelemetryDistributionSummary distributionSummary = - new OpenTelemetryDistributionSummary( - id, config().namingConvention(), clock, distributionStatisticConfig, scale, otelMeter); - if (distributionSummary.isUsingMicrometerHistograms()) { - HistogramGauges.registerWithCommonFormat(distributionSummary, this); - } - return distributionSummary; - } - - @Override - protected Meter newMeter(Meter.Id id, Meter.Type type, Iterable measurements) { - return new OpenTelemetryMeter(id, config().namingConvention(), measurements, otelMeter); - } - - @Override - protected FunctionTimer newFunctionTimer( - Meter.Id id, - T obj, - ToLongFunction countFunction, - ToDoubleFunction totalTimeFunction, - TimeUnit totalTimeFunctionUnit) { - return new OpenTelemetryFunctionTimer<>( - id, - config().namingConvention(), - obj, - countFunction, - totalTimeFunction, - totalTimeFunctionUnit, - getBaseTimeUnit(), - otelMeter); - } - - @Override - protected FunctionCounter newFunctionCounter( - Meter.Id id, T obj, ToDoubleFunction countFunction) { - return new OpenTelemetryFunctionCounter<>( - id, config().namingConvention(), obj, countFunction, otelMeter); - } - - @Override - protected TimeUnit getBaseTimeUnit() { - return baseTimeUnit; - } - - @Override - protected DistributionStatisticConfig defaultHistogramConfig() { - return DistributionStatisticConfig.DEFAULT; - } - - private static void onMeterRemoved(Meter meter) { - if (meter instanceof RemovableMeter) { - ((RemovableMeter) meter).onRemove(); - } - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeterRegistryBuilder.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeterRegistryBuilder.java deleted file mode 100644 index c49290341ef..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryMeterRegistryBuilder.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.micrometer.core.instrument.Clock; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.config.NamingConvention; -import io.opentelemetry.api.OpenTelemetry; -import java.util.concurrent.TimeUnit; - -/** A builder of {@link OpenTelemetryMeterRegistry}. */ -public final class OpenTelemetryMeterRegistryBuilder { - - // Visible for testing - static final String INSTRUMENTATION_NAME = "io.opentelemetry.micrometer1shim"; - - private final OpenTelemetry openTelemetry; - private Clock clock = Clock.SYSTEM; - private TimeUnit baseTimeUnit = TimeUnit.MILLISECONDS; - private boolean prometheusMode = false; - - OpenTelemetryMeterRegistryBuilder(OpenTelemetry openTelemetry) { - this.openTelemetry = openTelemetry; - } - - /** Sets a custom {@link Clock}. Useful for testing. */ - public OpenTelemetryMeterRegistryBuilder setClock(Clock clock) { - this.clock = clock; - return this; - } - - /** Sets the base time unit. */ - public OpenTelemetryMeterRegistryBuilder setBaseTimeUnit(TimeUnit baseTimeUnit) { - this.baseTimeUnit = baseTimeUnit; - return this; - } - - /** - * Enables the "Prometheus mode" - this will simulate the behavior of Micrometer's {@code - * PrometheusMeterRegistry}. The instruments will be renamed to match Micrometer instrument - * naming, and the base time unit will be set to seconds. - * - *

    Set this to {@code true} if you are using the Prometheus metrics exporter. - */ - public OpenTelemetryMeterRegistryBuilder setPrometheusMode(boolean prometheusMode) { - this.prometheusMode = prometheusMode; - return this; - } - - /** - * Returns a new {@link OpenTelemetryMeterRegistry} with the settings of this {@link - * OpenTelemetryMeterRegistryBuilder}. - */ - public MeterRegistry build() { - // prometheus mode overrides any unit settings with SECONDS - TimeUnit baseTimeUnit = prometheusMode ? TimeUnit.SECONDS : this.baseTimeUnit; - NamingConvention namingConvention = - prometheusMode ? PrometheusModeNamingConvention.INSTANCE : NamingConvention.identity; - - return new OpenTelemetryMeterRegistry( - clock, - baseTimeUnit, - namingConvention, - openTelemetry.getMeterProvider().get(INSTRUMENTATION_NAME)); - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryTimer.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryTimer.java deleted file mode 100644 index 2c4b31b5258..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/OpenTelemetryTimer.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.Bridging.name; -import static io.opentelemetry.micrometer1shim.Bridging.tagsAsAttributes; - -import io.micrometer.core.instrument.AbstractTimer; -import io.micrometer.core.instrument.Clock; -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.config.NamingConvention; -import io.micrometer.core.instrument.distribution.DistributionStatisticConfig; -import io.micrometer.core.instrument.distribution.NoopHistogram; -import io.micrometer.core.instrument.distribution.TimeWindowMax; -import io.micrometer.core.instrument.distribution.pause.PauseDetector; -import io.micrometer.core.instrument.util.TimeUtils; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.DoubleHistogram; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleGauge; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.DoubleAdder; -import java.util.concurrent.atomic.LongAdder; - -final class OpenTelemetryTimer extends AbstractTimer implements RemovableMeter { - - private final Measurements measurements; - private final TimeWindowMax max; - private final TimeUnit baseTimeUnit; - // TODO: use bound instruments when they're available - private final DoubleHistogram otelHistogram; - private final Attributes attributes; - private final ObservableDoubleGauge observableMax; - - private volatile boolean removed = false; - - OpenTelemetryTimer( - Id id, - NamingConvention namingConvention, - Clock clock, - DistributionStatisticConfig distributionStatisticConfig, - PauseDetector pauseDetector, - TimeUnit baseTimeUnit, - Meter otelMeter) { - super(id, clock, distributionStatisticConfig, pauseDetector, TimeUnit.MILLISECONDS, false); - - if (isUsingMicrometerHistograms()) { - measurements = new MicrometerHistogramMeasurements(); - } else { - measurements = NoopMeasurements.INSTANCE; - } - max = new TimeWindowMax(clock, distributionStatisticConfig); - - this.baseTimeUnit = baseTimeUnit; - this.attributes = tagsAsAttributes(id, namingConvention); - - String name = name(id, namingConvention); - this.otelHistogram = - otelMeter - .histogramBuilder(name) - .setDescription(Bridging.description(id)) - .setUnit(TimeUnitHelper.getUnitString(baseTimeUnit)) - .build(); - this.observableMax = - otelMeter - .gaugeBuilder(name + ".max") - .setDescription(Bridging.description(id)) - .setUnit(TimeUnitHelper.getUnitString(baseTimeUnit)) - .buildWithCallback( - new DoubleMeasurementRecorder<>(max, m -> m.poll(baseTimeUnit), attributes)); - } - - boolean isUsingMicrometerHistograms() { - return histogram != NoopHistogram.INSTANCE; - } - - @Override - protected void recordNonNegative(long amount, TimeUnit unit) { - if (!removed) { - double nanos = (double) unit.toNanos(amount); - double time = TimeUtils.nanosToUnit(nanos, baseTimeUnit); - otelHistogram.record(time, attributes); - measurements.record(nanos); - max.record(nanos, TimeUnit.NANOSECONDS); - } - } - - @Override - public long count() { - return measurements.count(); - } - - @Override - public double totalTime(TimeUnit unit) { - return measurements.totalTime(unit); - } - - @Override - public double max(TimeUnit unit) { - return max.poll(unit); - } - - @Override - public Iterable measure() { - UnsupportedReadLogger.logWarning(); - return Collections.emptyList(); - } - - @Override - public void onRemove() { - removed = true; - observableMax.close(); - } - - private interface Measurements { - void record(double nanos); - - long count(); - - double totalTime(TimeUnit unit); - } - - // if micrometer histograms are not being used then there's no need to keep any local state - // OpenTelemetry metrics bridge does not support reading measurements - enum NoopMeasurements implements Measurements { - INSTANCE; - - @Override - public void record(double nanos) {} - - @Override - public long count() { - UnsupportedReadLogger.logWarning(); - return 0; - } - - @Override - public double totalTime(TimeUnit unit) { - UnsupportedReadLogger.logWarning(); - return Double.NaN; - } - } - - // calculate count and totalTime value for the use of micrometer histograms - // kinda similar to how DropwizardTimer does that - private static final class MicrometerHistogramMeasurements implements Measurements { - - private final LongAdder count = new LongAdder(); - private final DoubleAdder totalTime = new DoubleAdder(); - - @Override - public void record(double nanos) { - count.increment(); - totalTime.add(nanos); - } - - @Override - public long count() { - return count.sum(); - } - - @Override - public double totalTime(TimeUnit unit) { - return TimeUtils.nanosToUnit(totalTime.sum(), unit); - } - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/PrometheusModeNamingConvention.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/PrometheusModeNamingConvention.java deleted file mode 100644 index e156b6fa455..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/PrometheusModeNamingConvention.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.config.NamingConvention; -import javax.annotation.Nullable; - -// This naming strategy does not replace '.' with '_', and it does not append '_total' to counter -// names - the reason behind it is that this is already done by the Prometheus exporter; see the -// io.opentelemetry.exporter.prometheus.MetricAdapter class -enum PrometheusModeNamingConvention implements NamingConvention { - INSTANCE; - - @Override - public String name(String name, Meter.Type type, @Nullable String baseUnit) { - if (type == Meter.Type.COUNTER - || type == Meter.Type.DISTRIBUTION_SUMMARY - || type == Meter.Type.GAUGE) { - if (baseUnit != null && !name.endsWith("." + baseUnit)) { - name = name + "." + baseUnit; - } - } - - if (type == Meter.Type.LONG_TASK_TIMER || type == Meter.Type.TIMER) { - if (!name.endsWith(".seconds")) { - name = name + ".seconds"; - } - } - - return name; - } -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/RemovableMeter.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/RemovableMeter.java deleted file mode 100644 index e8e274f146b..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/RemovableMeter.java +++ /dev/null @@ -1,11 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -interface RemovableMeter { - - void onRemove(); -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/TimeUnitHelper.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/TimeUnitHelper.java deleted file mode 100644 index 516432c0af1..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/TimeUnitHelper.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import java.util.concurrent.TimeUnit; - -final class TimeUnitHelper { - - static String getUnitString(TimeUnit unit) { - switch (unit) { - case NANOSECONDS: - return "ns"; - case MICROSECONDS: - return "us"; - case MILLISECONDS: - return "ms"; - case SECONDS: - return "s"; - case MINUTES: - return "min"; - case HOURS: - return "h"; - case DAYS: - return "d"; - } - throw new IllegalStateException("Should not ever happen"); - } - - private TimeUnitHelper() {} -} diff --git a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/UnsupportedReadLogger.java b/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/UnsupportedReadLogger.java deleted file mode 100644 index 3a4674f4d98..00000000000 --- a/micrometer1-shim/src/main/java/io/opentelemetry/micrometer1shim/UnsupportedReadLogger.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import java.util.logging.Level; -import java.util.logging.Logger; - -final class UnsupportedReadLogger { - - static { - Logger logger = Logger.getLogger(OpenTelemetryMeterRegistry.class.getName()); - logger.log(Level.WARNING, "OpenTelemetry metrics bridge does not support reading measurements"); - } - - static void logWarning() { - // do nothing; the warning will be logged exactly once when this class is loaded - } - - private UnsupportedReadLogger() {} -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/CounterTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/CounterTest.java deleted file mode 100644 index 839b85d2aed..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/CounterTest.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class CounterTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - @Test - void testCounter() { - Counter counter = - Counter.builder("testCounter") - .description("This is a test counter") - .tags("tag", "value") - .baseUnit("items") - .register(Metrics.globalRegistry); - - counter.increment(); - counter.increment(2); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test counter") - .hasUnit("items") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(3) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(counter); - counter.increment(); - - // Synchronous instruments will continue to report previous value after removal - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasDoubleSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(3)))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/DistributionSummaryTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/DistributionSummaryTest.java deleted file mode 100644 index a7c68e5504e..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/DistributionSummaryTest.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class DistributionSummaryTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - @Test - void testMicrometerDistributionSummary() { - DistributionSummary summary = - DistributionSummary.builder("testSummary") - .description("This is a test distribution summary") - .baseUnit("things") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - summary.record(1); - summary.record(2); - summary.record(4); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testSummary") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test distribution summary") - .hasUnit("things") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(7) - .hasCount(3) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testSummary.max") - .hasDescription("This is a test distribution summary") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(4) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(summary); - - // Histogram is synchronous and returns previous value after removal, max is asynchronous and is - // removed completely. - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testSummary") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(7) - .hasCount(3) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testMicrometerHistogram() { - DistributionSummary summary = - DistributionSummary.builder("testSummary") - .description("This is a test distribution summary") - .baseUnit("things") - .tags("tag", "value") - .serviceLevelObjectives(1, 10, 100, 1000) - .distributionStatisticBufferLength(10) - .register(Metrics.globalRegistry); - - summary.record(0.5); - summary.record(5); - summary.record(50); - summary.record(500); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testSummary") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test distribution summary") - .hasUnit("things") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - points -> - points - .hasSum(555.5) - .hasCount(4) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testSummary.max") - .hasDescription("This is a test distribution summary") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(500) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testSummary.histogram") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes( - attributeEntry("le", "1"), - attributeEntry("tag", "value")), - point -> - point - .hasValue(2) - .hasAttributes( - attributeEntry("le", "10"), - attributeEntry("tag", "value")), - point -> - point - .hasValue(3) - .hasAttributes( - attributeEntry("le", "100"), - attributeEntry("tag", "value")), - point -> - point - .hasValue(4) - .hasAttributes( - attributeEntry("le", "1000"), - attributeEntry("tag", "value"))))); - } - - @Test - void testMicrometerPercentiles() { - DistributionSummary summary = - DistributionSummary.builder("testSummary") - .description("This is a test distribution summary") - .baseUnit("things") - .tags("tag", "value") - .publishPercentiles(0.5, 0.95, 0.99) - .register(Metrics.globalRegistry); - - summary.record(50); - summary.record(100); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testSummary") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test distribution summary") - .hasUnit("things") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(150) - .hasCount(2) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testSummary.max") - .hasDescription("This is a test distribution summary") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(100) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testSummary.percentile") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("phi", "0.5"), - attributeEntry("tag", "value")), - point -> - point.hasAttributes( - attributeEntry("phi", "0.95"), - attributeEntry("tag", "value")), - point -> - point.hasAttributes( - attributeEntry("phi", "0.99"), - attributeEntry("tag", "value"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionCounterTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionCounterTest.java deleted file mode 100644 index ec213a030c7..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionCounterTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.FunctionCounter; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.internal.state.MetricStorageRegistry; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class FunctionCounterTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - final AtomicLong num = new AtomicLong(12); - final AtomicLong anotherNum = new AtomicLong(13); - - @Test - void testFunctionCounter() { - FunctionCounter counter = - FunctionCounter.builder("testFunctionCounter", num, AtomicLong::get) - .description("This is a test function counter") - .tags("tag", "value") - .baseUnit("items") - .register(Metrics.globalRegistry); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testFunctionCounter") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function counter") - .hasUnit("items") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(12) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(counter); - assertThat(testing.collectAllMetrics()).isEmpty(); - } - - @Test - @SuppressLogger(MetricStorageRegistry.class) - void functionCountersWithSameNameAndDifferentTags() { - FunctionCounter.builder("testFunctionCounterWithTags", num, AtomicLong::get) - .description("First description") - .tags("tag", "1") - .baseUnit("items") - .register(Metrics.globalRegistry); - FunctionCounter.builder("testFunctionCounterWithTags", anotherNum, AtomicLong::get) - .description("ignored") - .tags("tag", "2") - .baseUnit("items") - .register(Metrics.globalRegistry); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testFunctionCounterWithTags") - .hasDescription("First description") - .hasUnit("items") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(12) - .hasAttributes(attributeEntry("tag", "1")), - point -> - point - .hasValue(13) - .hasAttributes(attributeEntry("tag", "2"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionTimerSecondsTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionTimerSecondsTest.java deleted file mode 100644 index 2e42f8d4621..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionTimerSecondsTest.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.FunctionTimer; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class FunctionTimerSecondsTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = - new MicrometerTestingExtension() { - - @Override - OpenTelemetryMeterRegistryBuilder configureOtelRegistry( - OpenTelemetryMeterRegistryBuilder registry) { - return registry.setBaseTimeUnit(TimeUnit.SECONDS); - } - }; - - final TestTimer timerObj = new TestTimer(); - - @BeforeEach - void cleanupTimer() { - timerObj.reset(); - } - - @Test - void testFunctionTimerWithBaseUnitSeconds() { - FunctionTimer functionTimer = - FunctionTimer.builder( - "testFunctionTimerSeconds", - timerObj, - TestTimer::getCount, - TestTimer::getTotalTimeNanos, - TimeUnit.NANOSECONDS) - .description("This is a test function timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - timerObj.add(42, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testFunctionTimerSeconds.count") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function timer") - .hasUnit("1") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testFunctionTimerSeconds.sum") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function timer") - .hasUnit("s") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(42) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(functionTimer); - assertThat(testing.collectAllMetrics()).isEmpty(); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionTimerTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionTimerTest.java deleted file mode 100644 index 9446f5feb84..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/FunctionTimerTest.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.FunctionTimer; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class FunctionTimerTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - final TestTimer timerObj = new TestTimer(); - final TestTimer anotherTimerObj = new TestTimer(); - - @BeforeEach - void cleanupTimers() { - timerObj.reset(); - anotherTimerObj.reset(); - } - - @Test - void testFunctionTimer() throws InterruptedException { - FunctionTimer functionTimer = - FunctionTimer.builder( - "testFunctionTimer", - timerObj, - TestTimer::getCount, - TestTimer::getTotalTimeNanos, - TimeUnit.NANOSECONDS) - .description("This is a test function timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - timerObj.add(42, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testFunctionTimer.count") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function timer") - .hasUnit("1") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testFunctionTimer.sum") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function timer") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(42_000) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(functionTimer); - assertThat(testing.collectAllMetrics()).isEmpty(); - } - - @Test - void testNanoPrecision() { - FunctionTimer.builder( - "testNanoFunctionTimer", - timerObj, - TestTimer::getCount, - TestTimer::getTotalTimeNanos, - TimeUnit.NANOSECONDS) - .register(Metrics.globalRegistry); - - timerObj.add(1_234_000, TimeUnit.NANOSECONDS); - - assertThat(testing.collectAllMetrics()) - .anySatisfy( - metric -> - assertThat(metric) - .hasName("testNanoFunctionTimer.sum") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasValue(1.234).hasAttributes(Attributes.empty())))); - } - - @Test - void functionTimersWithSameNameAndDifferentTags() { - FunctionTimer.builder( - "testFunctionTimerWithTags", - timerObj, - TestTimer::getCount, - TestTimer::getTotalTimeNanos, - TimeUnit.NANOSECONDS) - .tags("tag", "1") - .register(Metrics.globalRegistry); - - FunctionTimer.builder( - "testFunctionTimerWithTags", - anotherTimerObj, - TestTimer::getCount, - TestTimer::getTotalTimeNanos, - TimeUnit.NANOSECONDS) - .tags("tag", "2") - .register(Metrics.globalRegistry); - - timerObj.add(12, TimeUnit.SECONDS); - anotherTimerObj.add(42, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .anySatisfy( - metric -> - assertThat(metric) - .hasName("testFunctionTimerWithTags.sum") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(12_000) - .hasAttributes(attributeEntry("tag", "1")), - point -> - point - .hasValue(42_000) - .hasAttributes(attributeEntry("tag", "2"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/GaugeTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/GaugeTest.java deleted file mode 100644 index b0fd7717d19..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/GaugeTest.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.lang.ref.WeakReference; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class GaugeTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - @Test - void testGauge() { - // when - Gauge gauge = - Gauge.builder("testGauge", () -> 42) - .description("This is a test gauge") - .tags("tag", "value") - .baseUnit("items") - .register(Metrics.globalRegistry); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test gauge") - .hasUnit("items") - .hasDoubleGaugeSatisfying( - doubleGauge -> - doubleGauge.hasPointsSatisfying( - point -> - point - .hasValue(42) - .hasAttributes(attributeEntry("tag", "value"))))); - - // when - Metrics.globalRegistry.remove(gauge); - assertThat(testing.collectAllMetrics()).isEmpty(); - } - - @Test - void gaugesWithSameNameAndDifferentTags() { - Gauge.builder("testGaugeWithTags", () -> 12) - .description("First description wins") - .baseUnit("items") - .tags("tag", "1") - .register(Metrics.globalRegistry); - Gauge.builder("testGaugeWithTags", () -> 42) - .description("ignored") - .baseUnit("items") - .tags("tag", "2") - .register(Metrics.globalRegistry); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGaugeWithTags") - .hasDescription("First description wins") - .hasUnit("items") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasValue(12).hasAttributes(attributeEntry("tag", "1")), - point -> - point.hasValue(42).hasAttributes(attributeEntry("tag", "2"))))); - } - - @Test - void testWeakRefGauge() throws InterruptedException { - AtomicLong num = new AtomicLong(42); - Gauge.builder("testWeakRefGauge", num, AtomicLong::get) - .strongReference(false) - .register(Metrics.globalRegistry); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testWeakRefGauge") - .hasDoubleGaugeSatisfying( - gauge -> gauge.hasPointsSatisfying(point -> point.hasValue(42)))); - - WeakReference numWeakRef = new WeakReference<>(num); - num = null; - awaitGc(numWeakRef); - - assertThat(testing.collectAllMetrics()).isEmpty(); - } - - private static void awaitGc(WeakReference ref) throws InterruptedException { - while (ref.get() != null) { - if (Thread.interrupted()) { - throw new InterruptedException(); - } - System.gc(); - System.runFinalization(); - } - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerHistogramTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerHistogramTest.java deleted file mode 100644 index 1bf52e31ded..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerHistogramTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.MockClock; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.time.Duration; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class LongTaskTimerHistogramTest { - - static MockClock clock = new MockClock(); - - @RegisterExtension - static final MicrometerTestingExtension testing = - new MicrometerTestingExtension() { - @Override - OpenTelemetryMeterRegistryBuilder configureOtelRegistry( - OpenTelemetryMeterRegistryBuilder registry) { - return registry.setClock(clock); - } - }; - - @Test - void testMicrometerHistogram() { - LongTaskTimer timer = - LongTaskTimer.builder("testLongTaskTimerHistogram") - .description("This is a test timer") - .serviceLevelObjectives(Duration.ofMillis(100), Duration.ofMillis(1000)) - .distributionStatisticBufferLength(10) - .register(Metrics.globalRegistry); - - LongTaskTimer.Sample sample1 = timer.start(); - // only active tasks count - timer.start().stop(); - clock.add(Duration.ofMillis(100)); - LongTaskTimer.Sample sample2 = timer.start(); - LongTaskTimer.Sample sample3 = timer.start(); - clock.add(Duration.ofMillis(10)); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testLongTaskTimerHistogram.active") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("tasks") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> point.hasValue(3).hasAttributes(Attributes.empty()))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimerHistogram.duration") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasAttributes(Attributes.empty()) - .satisfies( - pointData -> - assertThat(pointData.getValue()) - .isPositive()))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimerHistogram.histogram") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasAttributes(attributeEntry("le", "100")).hasValue(2), - point -> - point - .hasAttributes(attributeEntry("le", "1000")) - .hasValue(3)))); - - sample1.stop(); - sample2.stop(); - sample3.stop(); - - // Continues to report 0 after stopped. - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testLongTaskTimerHistogram.active") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("tasks") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> point.hasValue(0).hasAttributes(Attributes.empty()))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimerHistogram.duration") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> point.hasValue(0).hasAttributes(Attributes.empty()))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimerHistogram.histogram") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasValue(0).hasAttributes(attributeEntry("le", "100")), - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("le", "1000"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerSecondsTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerSecondsTest.java deleted file mode 100644 index 714bfa03e43..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerSecondsTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class LongTaskTimerSecondsTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = - new MicrometerTestingExtension() { - - @Override - OpenTelemetryMeterRegistryBuilder configureOtelRegistry( - OpenTelemetryMeterRegistryBuilder registry) { - return registry.setBaseTimeUnit(TimeUnit.SECONDS); - } - }; - - @Test - void testLongTaskTimerWithBaseUnitSeconds() throws InterruptedException { - // given - LongTaskTimer timer = - LongTaskTimer.builder("testLongTaskTimerSeconds") - .description("This is a test long task timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - // when - LongTaskTimer.Sample sample = timer.start(); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testLongTaskTimerSeconds.active") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test long task timer") - .hasUnit("tasks") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimerSeconds.duration") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test long task timer") - .hasUnit("s") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributeEntry("tag", "value")) - .satisfies( - pointData -> - assertThat(pointData.getValue()) - .isPositive())))); - - // when - TimeUnit.MILLISECONDS.sleep(100); - sample.stop(); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testLongTaskTimerSeconds.active") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimerSeconds.duration") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("tag", "value"))))); - - // when timer is removed from the registry - Metrics.globalRegistry.remove(timer); - timer.start(); - - // then no tasks are active after starting a new sample - assertThat(testing.collectAllMetrics()).isEmpty(); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerTest.java deleted file mode 100644 index 3ee22ed80da..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/LongTaskTimerTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class LongTaskTimerTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - @Test - void testLongTaskTimer() throws InterruptedException { - LongTaskTimer timer = - LongTaskTimer.builder("testLongTaskTimer") - .description("This is a test long task timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - LongTaskTimer.Sample sample = timer.start(); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testLongTaskTimer.active") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test long task timer") - .hasUnit("tasks") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimer.duration") - .hasDescription("This is a test long task timer") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributeEntry("tag", "value")) - .satisfies( - pointData -> - assertThat(pointData.getValue()) - .isPositive())))); - - // when - TimeUnit.MILLISECONDS.sleep(100); - sample.stop(); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testLongTaskTimer.active") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testLongTaskTimer.duration") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("tag", "value"))))); - - // when timer is removed from the registry - Metrics.globalRegistry.remove(timer); - timer.start(); - - // then no tasks are active after starting a new sample - assertThat(testing.collectAllMetrics()).isEmpty(); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/MeterTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/MeterTest.java deleted file mode 100644 index 00432c9682b..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/MeterTest.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Measurement; -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Statistic; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class MeterTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - @Test - void testMeter() { - AtomicReference number = new AtomicReference<>(12345.0); - - List measurements = - Arrays.asList( - new Measurement(number::get, Statistic.TOTAL), - new Measurement(number::get, Statistic.TOTAL_TIME), - new Measurement(number::get, Statistic.COUNT), - new Measurement(number::get, Statistic.ACTIVE_TASKS), - new Measurement(number::get, Statistic.DURATION), - new Measurement(number::get, Statistic.MAX), - new Measurement(number::get, Statistic.VALUE), - new Measurement(number::get, Statistic.UNKNOWN)); - - Meter meter = - Meter.builder("testMeter", Meter.Type.OTHER, measurements) - .description("This is a test meter") - .baseUnit("things") - .tag("tag", "value") - .register(Metrics.globalRegistry); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testMeter.total") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.total_time") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.count") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.active") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.duration") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.max") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.value") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testMeter.unknown") - .hasDescription("This is a test meter") - .hasUnit("things") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12345) - .hasAttributes(attributeEntry("tag", "value"))))); - - // when - Metrics.globalRegistry.remove(meter); - assertThat(testing.collectAllMetrics()).isEmpty(); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/MicrometerTestingExtension.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/MicrometerTestingExtension.java deleted file mode 100644 index 7e12972ffb3..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/MicrometerTestingExtension.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Metrics; -import io.opentelemetry.sdk.OpenTelemetrySdk; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import java.util.Collection; -import org.junit.jupiter.api.extension.AfterEachCallback; -import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.ExtensionContext; - -class MicrometerTestingExtension implements AfterEachCallback, BeforeEachCallback { - - private static final ExtensionContext.Namespace NAMESPACE = - ExtensionContext.Namespace.create(MicrometerTestingExtension.class); - - private InMemoryMetricReader metricReader; - - Collection collectAllMetrics() { - return metricReader.collectAllMetrics(); - } - - @Override - public void beforeEach(ExtensionContext context) { - ExtensionContext.Store store = context.getStore(NAMESPACE); - - metricReader = InMemoryMetricReader.create(); - SdkMeterProvider meterProvider = - SdkMeterProvider.builder().registerMetricReader(metricReader).build(); - MeterRegistry otelMeterRegistry = - configureOtelRegistry( - OpenTelemetryMeterRegistry.builder( - OpenTelemetrySdk.builder().setMeterProvider(meterProvider).build())) - .build(); - configureMeterRegistry(otelMeterRegistry); - - store.put(SdkMeterProvider.class, meterProvider); - store.put(MeterRegistry.class, otelMeterRegistry); - - Metrics.addRegistry(otelMeterRegistry); - } - - @Override - public void afterEach(ExtensionContext context) { - ExtensionContext.Store store = context.getStore(NAMESPACE); - MeterRegistry otelMeterRegistry = store.get(MeterRegistry.class, MeterRegistry.class); - SdkMeterProvider meterProvider = store.get(SdkMeterProvider.class, SdkMeterProvider.class); - - Metrics.removeRegistry(otelMeterRegistry); - meterProvider.close(); - - Metrics.globalRegistry.forEachMeter(Metrics.globalRegistry::remove); - } - - OpenTelemetryMeterRegistryBuilder configureOtelRegistry( - OpenTelemetryMeterRegistryBuilder registry) { - return registry; - } - - MeterRegistry configureMeterRegistry(MeterRegistry registry) { - return registry; - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/NamingConventionTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/NamingConventionTest.java deleted file mode 100644 index 5a48139fa0f..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/NamingConventionTest.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Meter; -import io.micrometer.core.instrument.MeterRegistry; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Tags; -import io.micrometer.core.instrument.Timer; -import io.micrometer.core.instrument.config.NamingConvention; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressWarnings("PreferJavaTimeOverload") -class NamingConventionTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = - new MicrometerTestingExtension() { - @Override - MeterRegistry configureMeterRegistry(MeterRegistry registry) { - registry - .config() - .namingConvention( - new NamingConvention() { - @Override - public String name(String name, Meter.Type type, String baseUnit) { - return "test." + name; - } - - @Override - public String tagKey(String key) { - return "test." + key; - } - - @Override - public String tagValue(String value) { - return "test." + value; - } - }); - return registry; - } - }; - - final AtomicLong num = new AtomicLong(42); - - @Test - void renameCounter() { - Counter counter = Metrics.counter("renamedCounter", "tag", "value"); - counter.increment(); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedCounter") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } - - @Test - void renameDistributionSummary() { - DistributionSummary summary = Metrics.summary("renamedSummary", "tag", "value"); - summary.record(42); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedSummary") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point.hasAttributes(attributeEntry("test.tag", "test.value")))), - metric -> - assertThat(metric) - .hasName("test.renamedSummary.max") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } - - @Test - void renameFunctionCounter() { - Metrics.more().counter("renamedFunctionCounter", Tags.of("tag", "value"), num); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedFunctionCounter") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } - - @Test - void renameFunctionTimer() { - Metrics.more() - .timer( - "renamedFunctionTimer", - Tags.of("tag", "value"), - num, - AtomicLong::longValue, - AtomicLong::doubleValue, - TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedFunctionTimer.count") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasAttributes(attributeEntry("test.tag", "test.value")))), - metric -> - assertThat(metric) - .hasName("test.renamedFunctionTimer.sum") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } - - @Test - void renameGauge() { - Metrics.gauge("renamedGauge", Tags.of("tag", "value"), num); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedGauge") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } - - @Test - void renameLongTaskTimer() { - LongTaskTimer timer = Metrics.more().longTaskTimer("renamedLongTaskTimer", "tag", "value"); - timer.start().stop(); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedLongTaskTimer.active") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasAttributes(attributeEntry("test.tag", "test.value")))), - metric -> - assertThat(metric) - .hasName("test.renamedLongTaskTimer.duration") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } - - @Test - void renameTimer() { - Timer timer = Metrics.timer("renamedTimer", "tag", "value"); - timer.record(10, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("test.renamedTimer") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point.hasAttributes(attributeEntry("test.tag", "test.value")))), - metric -> - assertThat(metric) - .hasName("test.renamedTimer.max") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("test.tag", "test.value"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/PrometheusModeTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/PrometheusModeTest.java deleted file mode 100644 index b2765a87832..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/PrometheusModeTest.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Counter; -import io.micrometer.core.instrument.DistributionSummary; -import io.micrometer.core.instrument.FunctionTimer; -import io.micrometer.core.instrument.Gauge; -import io.micrometer.core.instrument.LongTaskTimer; -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Timer; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressWarnings("PreferJavaTimeOverload") -class PrometheusModeTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = - new MicrometerTestingExtension() { - - @Override - OpenTelemetryMeterRegistryBuilder configureOtelRegistry( - OpenTelemetryMeterRegistryBuilder registry) { - return registry.setPrometheusMode(true); - } - }; - - final TestTimer timerObj = new TestTimer(); - - @BeforeEach - void cleanupMeters() { - Metrics.globalRegistry.forEachMeter(Metrics.globalRegistry::remove); - } - - @Test - void testCounter() { - // given - Counter counter = - Counter.builder("testPrometheusCounter") - .description("This is a test counter") - .tags("tag", "value") - .baseUnit("items") - .register(Metrics.globalRegistry); - - // when - counter.increment(12); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusCounter.items") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test counter") - .hasUnit("items") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(12) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testDistributionSummary() { - // given - DistributionSummary summary = - DistributionSummary.builder("testPrometheusSummary") - .description("This is a test summary") - .baseUnit("items") - .tag("tag", "value") - .register(Metrics.globalRegistry); - - // when - summary.record(12); - summary.record(42); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusSummary.items") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test summary") - .hasUnit("items") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(54) - .hasCount(2) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testPrometheusSummary.items.max") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test summary") - .hasUnit("items") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(42) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testFunctionTimer() { - // given - FunctionTimer.builder( - "testPrometheusFunctionTimer", - timerObj, - TestTimer::getCount, - TestTimer::getTotalTimeNanos, - TimeUnit.NANOSECONDS) - .description("This is a test function timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - // when - timerObj.add(42, TimeUnit.SECONDS); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusFunctionTimer.seconds.count") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function timer") - .hasUnit("1") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testPrometheusFunctionTimer.seconds.sum") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test function timer") - .hasUnit("s") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(42) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testGauge() { - // when - Gauge.builder("testPrometheusGauge", () -> 42) - .description("This is a test gauge") - .tags("tag", "value") - .baseUnit("items") - .register(Metrics.globalRegistry); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusGauge.items") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test gauge") - .hasUnit("items") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(42) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testLongTaskTimer() throws InterruptedException { - // given - LongTaskTimer timer = - LongTaskTimer.builder("testPrometheusLongTaskTimer") - .description("This is a test long task timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - // when - LongTaskTimer.Sample sample = timer.start(); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusLongTaskTimer.seconds.active") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test long task timer") - .hasUnit("tasks") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testPrometheusLongTaskTimer.seconds.duration") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test long task timer") - .hasUnit("s") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasAttributes(attributeEntry("tag", "value")) - .satisfies( - pointData -> - assertThat(pointData.getValue()) - .isPositive())))); - - // when - TimeUnit.MILLISECONDS.sleep(100); - sample.stop(); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusLongTaskTimer.seconds.active") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testPrometheusLongTaskTimer.seconds.duration") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(0) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testTimer() { - // given - Timer timer = - Timer.builder("testPrometheusTimer") - .description("This is a test timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - // when - timer.record(1, TimeUnit.SECONDS); - timer.record(5, TimeUnit.SECONDS); - timer.record(10_789, TimeUnit.MILLISECONDS); - - // then - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testPrometheusTimer.seconds") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("s") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(16.789) - .hasCount(3) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testPrometheusTimer.seconds.max") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("s") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(10.789) - .hasAttributes(attributeEntry("tag", "value"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TestTimer.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TestTimer.java deleted file mode 100644 index 723afbf3ca2..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TestTimer.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import java.util.concurrent.TimeUnit; - -class TestTimer { - int count = 0; - long totalTimeNanos = 0; - - void add(long time, TimeUnit unit) { - count++; - totalTimeNanos += unit.toNanos(time); - } - - int getCount() { - return count; - } - - double getTotalTimeNanos() { - return totalTimeNanos; - } - - void reset() { - count = 0; - totalTimeNanos = 0; - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TimerSecondsTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TimerSecondsTest.java deleted file mode 100644 index d8bd0a49dd4..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TimerSecondsTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Timer; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressWarnings("PreferJavaTimeOverload") -class TimerSecondsTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = - new MicrometerTestingExtension() { - - @Override - OpenTelemetryMeterRegistryBuilder configureOtelRegistry( - OpenTelemetryMeterRegistryBuilder registry) { - return registry.setBaseTimeUnit(TimeUnit.SECONDS); - } - }; - - @Test - void testTimerWithBaseUnitSeconds() { - Timer timer = - Timer.builder("testTimerSeconds") - .description("This is a test timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - timer.record(1, TimeUnit.SECONDS); - timer.record(10, TimeUnit.SECONDS); - timer.record(12_345, TimeUnit.MILLISECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testTimerSeconds") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("s") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(23.345) - .hasCount(3) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testTimerSeconds.max") - .hasDescription("This is a test timer") - .hasUnit("s") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(12.345) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(timer); - timer.record(12, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testTimerSeconds") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("s") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(23.345) - .hasCount(3) - .hasAttributes(attributeEntry("tag", "value"))))); - } -} diff --git a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TimerTest.java b/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TimerTest.java deleted file mode 100644 index 0b49c22ff57..00000000000 --- a/micrometer1-shim/src/test/java/io/opentelemetry/micrometer1shim/TimerTest.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.micrometer1shim; - -import static io.opentelemetry.micrometer1shim.OpenTelemetryMeterRegistryBuilder.INSTRUMENTATION_NAME; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.micrometer.core.instrument.Metrics; -import io.micrometer.core.instrument.Timer; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressWarnings("PreferJavaTimeOverload") -class TimerTest { - - @RegisterExtension - static final MicrometerTestingExtension testing = new MicrometerTestingExtension(); - - @Test - void testTimer() { - Timer timer = - Timer.builder("testTimer") - .description("This is a test timer") - .tags("tag", "value") - .register(Metrics.globalRegistry); - - timer.record(42, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testTimer") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(42_000) - .hasCount(1) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testTimer.max") - .hasDescription("This is a test timer") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(42_000) - .hasAttributes(attributeEntry("tag", "value"))))); - - Metrics.globalRegistry.remove(timer); - timer.record(12, TimeUnit.SECONDS); - - // Histogram is synchronous and returns previous value after removal, max is asynchronous and is - // removed completely. - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testTimer") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(42_000) - .hasCount(1) - .hasAttributes(attributeEntry("tag", "value"))))); - } - - @Test - void testNanoPrecision() { - Timer timer = Timer.builder("testNanoTimer").register(Metrics.globalRegistry); - - timer.record(1_234_000, TimeUnit.NANOSECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testNanoTimer") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(1.234) - .hasCount(1) - .hasAttributes(Attributes.empty()))), - metric -> - assertThat(metric) - .hasName("testNanoTimer.max") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasValue(1.234).hasAttributes(Attributes.empty())))); - } - - @Test - void testMicrometerHistogram() { - // given - Timer timer = - Timer.builder("testTimer") - .description("This is a test timer") - .tags("tag", "value") - .serviceLevelObjectives( - Duration.ofSeconds(1), - Duration.ofSeconds(10), - Duration.ofSeconds(100), - Duration.ofSeconds(1000)) - .distributionStatisticBufferLength(10) - .register(Metrics.globalRegistry); - - timer.record(500, TimeUnit.MILLISECONDS); - timer.record(5, TimeUnit.SECONDS); - timer.record(50, TimeUnit.SECONDS); - timer.record(500, TimeUnit.SECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testTimer") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(555500) - .hasCount(4) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testTimer.max") - .hasDescription("This is a test timer") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(500000) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testTimer.histogram") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes( - attributeEntry("le", "1000"), - attributeEntry("tag", "value")), - point -> - point - .hasValue(2) - .hasAttributes( - attributeEntry("le", "10000"), - attributeEntry("tag", "value")), - point -> - point - .hasValue(3) - .hasAttributes( - attributeEntry("le", "100000"), - attributeEntry("tag", "value")), - point -> - point - .hasValue(4) - .hasAttributes( - attributeEntry("le", "1000000"), - attributeEntry("tag", "value"))))); - } - - @Test - void testMicrometerPercentiles() { - // given - Timer timer = - Timer.builder("testTimer") - .description("This is a test timer") - .tags("tag", "value") - .publishPercentiles(0.5, 0.95, 0.99) - .register(Metrics.globalRegistry); - - timer.record(50, TimeUnit.MILLISECONDS); - timer.record(100, TimeUnit.MILLISECONDS); - - assertThat(testing.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metric -> - assertThat(metric) - .hasName("testTimer") - .hasInstrumentationScope( - InstrumentationScopeInfo.create(INSTRUMENTATION_NAME, null, null)) - .hasDescription("This is a test timer") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(150) - .hasCount(2) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testTimer.max") - .hasDescription("This is a test timer") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(100) - .hasAttributes(attributeEntry("tag", "value")))), - metric -> - assertThat(metric) - .hasName("testTimer.percentile") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasAttributes( - attributeEntry("phi", "0.5"), - attributeEntry("tag", "value")), - point -> - point.hasAttributes( - attributeEntry("phi", "0.95"), - attributeEntry("tag", "value")), - point -> - point.hasAttributes( - attributeEntry("phi", "0.99"), - attributeEntry("tag", "value"))))); - } -} diff --git a/mise.toml b/mise.toml new file mode 100644 index 00000000000..1e59aff83e5 --- /dev/null +++ b/mise.toml @@ -0,0 +1,23 @@ +[tools] + +# Linters +"aqua:grafana/flint" = "0.22.15" +lychee = "0.24.2" + +[env] +FLINT_CONFIG_DIR = ".github/config" + +[settings] +# Only install tools explicitly defined in the [tools] section above +idiomatic_version_file_enable_tools = [] + +# Windows configuration for file-based tasks +# Based on: https://github.com/jdx/mise/discussions/4461 +windows_executable_extensions = ["sh"] +windows_default_file_shell_args = "bash" +use_file_shell_for_executable_tasks = true + +[tasks."lint:links"] +description = "Check for broken links in changed files + all local links" +raw_args = true +run = "flint run" diff --git a/opencensus-shim/README.md b/opencensus-shim/README.md index 9e54ba4adac..22389827e34 100644 --- a/opencensus-shim/README.md +++ b/opencensus-shim/README.md @@ -1,6 +1,10 @@ # OpenTelemetry OpenCensus Shim -[![Javadocs][javadoc-image]][javadoc-url] +> [!WARNING] +> OpenCensus compatibility is deprecated in the OpenTelemetry specification, and this shim is +> deprecated accordingly. It remains available for legacy compatibility, but users should migrate +> OpenCensus instrumentation to the OpenTelemetry APIs. See the +> [OpenTelemetry specification guidance on OpenCensus compatibility](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/opencensus.md). The OpenCensus shim allows applications and libraries that are instrumented with OpenTelemetry, but depend on other libraries instrumented with OpenCensus, @@ -22,35 +26,23 @@ Applications only need to set up OpenTelemetry exporters, not OpenCensus. To allow the shim to work for metrics, add the shim as a dependency. -Applications also need to attach OpenCensus metrics to their metric readers on registration. +Applications also need to register the OpenCensus metric producer with the meter provider. -``` +```java +PeriodicMetricReader reader = ... SdkMeterProvider.builder() - .registerMetricReader( - OpenCensusMetrics.attachTo(readerFactory) - ) - .buildAndRegisterGlobal(); + .registerMetricReader(reader) + .registerMetricProducer(OpenCensusMetricProducer.create()) + .build(); ``` For example, if a logging exporter were configured, the following would be added: -``` -LoggingMetricExporter metricExporter = new LoggingMetricExporter(); +```java +LoggingMetricExporter metricExporter = LoggingMetricExporter.create(); SdkMeterProvider.builder() - .registerMetricReader( - OpenCensusMetrics.attachTo( - PeriodicMetricReader.builder(metricExporter) - .newMetricReaderFactory() - ) - ) - .buildAndRegisterGlobal(); + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) + .registerMetricProducer(OpenCensusMetricProducer.create()) + .build(); ``` - -## Known Problems - -* OpenCensus links added after an OpenCensus span is created will not be -exported, as OpenTelemetry only supports links added when a span is created. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-opencensus-shim.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-opencensus-shim diff --git a/opencensus-shim/build.gradle.kts b/opencensus-shim/build.gradle.kts index 7d3b7e908ce..fa1d0986247 100644 --- a/opencensus-shim/build.gradle.kts +++ b/opencensus-shim/build.gradle.kts @@ -1,16 +1,19 @@ +import io.opentelemetry.gradle.OtelVersionClassPlugin + plugins { id("otel.java-conventions") id("otel.publish-conventions") } +apply() description = "OpenTelemetry OpenCensus Shim" otelJava.moduleName.set("io.opentelemetry.opencensusshim") +otelJava.requireSuppressWarningsExplanation.set(false) dependencies { api(project(":api:all")) api(project(":extensions:trace-propagators")) api(project(":sdk:all")) - api(project(":sdk:metrics")) api("io.opencensus:opencensus-api") api("io.opencensus:opencensus-impl-core") diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/DelegatingSpan.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/DelegatingSpan.java new file mode 100644 index 00000000000..254fca4830b --- /dev/null +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/DelegatingSpan.java @@ -0,0 +1,171 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import com.google.errorprone.annotations.MustBeClosed; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + +/** + * Delegates all {@link Span} methods to some underlying Span via {@link + * DelegatingSpan#getDelegate()}. + * + *

    If not all calls are proxied, some, such as and in particular {@link + * Span#storeInContext(Context)} and {@link Span#makeCurrent()}, will use {@code this} instead of + * the proxied {@link Span} which betrays the expectation of instance fidelity imposed by the + * underlying otel mechanisms which minted the original {@link Span}, such as the otel javaagent. + * + *

    This proxy class simplification allows the shim to perform its duties as minimally invasively + * as possible and itself never expose its own classes and objects to callers or recipients of calls + * from the shim. + * + *

    This addresses the inconsistency where not all methods are appropriately delegated by exposing + * a single method, {@link DelegatingSpan#getDelegate()}, to simplify and better ensure delegation + * and meeting expectations. + */ +interface DelegatingSpan extends Span { + Span getDelegate(); + + @Override + default Span updateName(String name) { + return getDelegate().updateName(name); + } + + @Override + default SpanContext getSpanContext() { + return getDelegate().getSpanContext(); + } + + @Override + default boolean isRecording() { + return getDelegate().isRecording(); + } + + @Override + default Span setAttribute(AttributeKey key, @Nullable T value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAttribute(String key, @Nullable String value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAttribute(String key, long value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAttribute(String key, double value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAttribute(String key, boolean value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAttribute(String key, Value value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAttribute(AttributeKey key, int value) { + return getDelegate().setAttribute(key, value); + } + + @Override + default Span setAllAttributes(Attributes attributes) { + return getDelegate().setAllAttributes(attributes); + } + + @Override + default Span addEvent(String name, Attributes attributes) { + return getDelegate().addEvent(name, attributes); + } + + @Override + default Span addEvent(String name, Attributes attributes, long timestamp, TimeUnit unit) { + return getDelegate().addEvent(name, attributes, timestamp, unit); + } + + @Override + default Span addEvent(String name) { + return getDelegate().addEvent(name); + } + + @Override + default Span addEvent(String name, long timestamp, TimeUnit unit) { + return getDelegate().addEvent(name, timestamp, unit); + } + + @Override + default Span addEvent(String name, Instant timestamp) { + return getDelegate().addEvent(name, timestamp); + } + + @Override + default Span addEvent(String name, Attributes attributes, Instant timestamp) { + return getDelegate().addEvent(name, attributes, timestamp); + } + + @Override + default Span setStatus(StatusCode statusCode, String description) { + return getDelegate().setStatus(statusCode, description); + } + + @Override + default Span setStatus(StatusCode statusCode) { + return getDelegate().setStatus(statusCode); + } + + @Override + default Span recordException(Throwable exception, Attributes additionalAttributes) { + return getDelegate().recordException(exception, additionalAttributes); + } + + @Override + default Span recordException(Throwable exception) { + return getDelegate().recordException(exception); + } + + @Override + default void end(Instant timestamp) { + getDelegate().end(timestamp); + } + + @Override + default void end() { + getDelegate().end(); + } + + @Override + default void end(long timestamp, TimeUnit unit) { + getDelegate().end(timestamp, unit); + } + + @Override + default Context storeInContext(Context context) { + return getDelegate().storeInContext(context); + } + + @MustBeClosed + @Override + default Scope makeCurrent() { + return getDelegate().makeCurrent(); + } +} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/MetricAdapter.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/MetricAdapter.java new file mode 100644 index 00000000000..366f6786a4d --- /dev/null +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/MetricAdapter.java @@ -0,0 +1,385 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import io.opencensus.common.Timestamp; +import io.opencensus.metrics.LabelKey; +import io.opencensus.metrics.LabelValue; +import io.opencensus.metrics.data.Exemplar; +import io.opencensus.metrics.export.Distribution; +import io.opencensus.metrics.export.Metric; +import io.opencensus.metrics.export.MetricDescriptor; +import io.opencensus.metrics.export.Point; +import io.opencensus.metrics.export.Summary; +import io.opencensus.metrics.export.TimeSeries; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.GaugeData; +import io.opentelemetry.sdk.metrics.data.HistogramData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.SumData; +import io.opentelemetry.sdk.metrics.data.SummaryData; +import io.opentelemetry.sdk.metrics.data.SummaryPointData; +import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.annotation.Nullable; + +/** Adapts an OpenCensus metric into the OpenTelemetry metric data API. */ +final class MetricAdapter { + private MetricAdapter() {} + + // All OpenCensus metrics come from this shim. + // VisibleForTesting. + static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.create("io.opentelemetry.opencensusshim"); + + // Parser for string value of `io.opencensus.contrib.exemplar.util.AttachmentValueSpanContext` + // // SpanContext{traceId=TraceId{traceId=(id))}, spanId=SpanId{spanId=(id), ...} + private static final Pattern OPENCENSUS_TRACE_ATTACHMENT_PATTERN = + Pattern.compile( + "SpanContext\\{traceId=TraceId\\{traceId=([0-9A-Ga-g]+)\\}, spanId=SpanId\\{spanId=([0-9A-Ga-g]+)\\},.*\\}"); + + /** + * Converts an open-census metric into the OTLP format. + * + * @param otelResource The resource associated with the opentelemetry SDK. + * @param censusMetric The OpenCensus metric to convert. + */ + static MetricData convert(Resource otelResource, Metric censusMetric) { + // Note: we can't just adapt interfaces, we need to do full copy because OTel data API uses + // auto-value vs. pure interfaces. + switch (censusMetric.getMetricDescriptor().getType()) { + case GAUGE_INT64: + return ImmutableMetricData.createLongGauge( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertLongGauge(censusMetric)); + case GAUGE_DOUBLE: + return ImmutableMetricData.createDoubleGauge( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertDoubleGauge(censusMetric)); + case CUMULATIVE_INT64: + return ImmutableMetricData.createLongSum( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertLongSum(censusMetric)); + case CUMULATIVE_DOUBLE: + return ImmutableMetricData.createDoubleSum( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertDoubleSum(censusMetric)); + case CUMULATIVE_DISTRIBUTION: + return ImmutableMetricData.createDoubleHistogram( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertHistogram(censusMetric)); + case SUMMARY: + return ImmutableMetricData.createDoubleSummary( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertSummary(censusMetric)); + case GAUGE_DISTRIBUTION: + return ImmutableMetricData.createDoubleHistogram( + otelResource, + INSTRUMENTATION_SCOPE_INFO, + censusMetric.getMetricDescriptor().getName(), + censusMetric.getMetricDescriptor().getDescription(), + censusMetric.getMetricDescriptor().getUnit(), + convertGaugeHistogram(censusMetric)); + } + // Should be unreachable.... + throw new IllegalArgumentException( + "Unknown OpenCensus metric type: " + censusMetric.getMetricDescriptor().getType()); + } + + static GaugeData convertLongGauge(Metric censusMetric) { + return ImmutableGaugeData.create(convertLongPoints(censusMetric)); + } + + static GaugeData convertDoubleGauge(Metric censusMetric) { + return ImmutableGaugeData.create(convertDoublePoints(censusMetric)); + } + + static SumData convertLongSum(Metric censusMetric) { + return ImmutableSumData.create( + true, AggregationTemporality.CUMULATIVE, convertLongPoints(censusMetric)); + } + + static SumData convertDoubleSum(Metric censusMetric) { + return ImmutableSumData.create( + true, AggregationTemporality.CUMULATIVE, convertDoublePoints(censusMetric)); + } + + static HistogramData convertHistogram(Metric censusMetric) { + return ImmutableHistogramData.create( + AggregationTemporality.CUMULATIVE, convertHistogramPoints(censusMetric)); + } + + static HistogramData convertGaugeHistogram(Metric censusMetric) { + return ImmutableHistogramData.create( + AggregationTemporality.DELTA, convertHistogramPoints(censusMetric)); + } + + static SummaryData convertSummary(Metric censusMetric) { + return ImmutableSummaryData.create(convertSummaryPoints(censusMetric)); + } + + static Collection convertLongPoints(Metric censusMetric) { + // TODO - preallocate array to correct size. + List result = new ArrayList<>(); + for (TimeSeries ts : censusMetric.getTimeSeriesList()) { + long startTimestamp = mapTimestamp(ts.getStartTimestamp()); + Attributes attributes = + mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); + for (Point point : ts.getPoints()) { + result.add( + ImmutableLongPointData.create( + startTimestamp, mapTimestamp(point.getTimestamp()), attributes, longValue(point))); + } + } + return result; + } + + static Collection convertDoublePoints(Metric censusMetric) { + // TODO - preallocate array to correct size. + List result = new ArrayList<>(); + for (TimeSeries ts : censusMetric.getTimeSeriesList()) { + long startTimestamp = mapTimestamp(ts.getStartTimestamp()); + Attributes attributes = + mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); + for (Point point : ts.getPoints()) { + result.add( + ImmutableDoublePointData.create( + startTimestamp, + mapTimestamp(point.getTimestamp()), + attributes, + doubleValue(point))); + } + } + return result; + } + + static Collection convertHistogramPoints(Metric censusMetric) { + boolean isGauge = + censusMetric.getMetricDescriptor().getType() == MetricDescriptor.Type.GAUGE_DISTRIBUTION; + // TODO - preallocate array to correct size. + List result = new ArrayList<>(); + for (TimeSeries ts : censusMetric.getTimeSeriesList()) { + long startTimestamp = mapTimestamp(ts.getStartTimestamp()); + Attributes attributes = + mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); + for (Point point : ts.getPoints()) { + long endTimestamp = mapTimestamp(point.getTimestamp()); + HistogramPointData otelPoint = + point + .getValue() + .match( + doubleValue -> null, + longValue -> null, + distribution -> + ImmutableHistogramPointData.create( + // Report Gauge histograms as DELTA with "instantaneous" time window. + isGauge ? endTimestamp : startTimestamp, + endTimestamp, + attributes, + distribution.getSum(), + /* hasMin= */ false, + 0, + /* hasMax= */ false, + 0, + mapBoundaries(distribution.getBucketOptions()), + mapCounts(distribution.getBuckets()), + mapExemplars(distribution.getBuckets())), + summary -> null, + defaultValue -> null); + if (otelPoint != null) { + result.add(otelPoint); + } + } + } + return result; + } + + static Collection convertSummaryPoints(Metric censusMetric) { + List result = new ArrayList<>(); + for (TimeSeries ts : censusMetric.getTimeSeriesList()) { + long startTimestamp = mapTimestamp(ts.getStartTimestamp()); + Attributes attributes = + mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); + for (Point point : ts.getPoints()) { + SummaryPointData otelPoint = + point + .getValue() + .match( + dv -> null, + lv -> null, + distribution -> null, + summary -> + ImmutableSummaryPointData.create( + startTimestamp, + mapTimestamp(point.getTimestamp()), + attributes, + summary.getCount(), + summary.getSum(), + mapValueAtPercentiles(summary.getSnapshot().getValueAtPercentiles())), + defaultValue -> null); + if (otelPoint != null) { + result.add(otelPoint); + } + } + } + return result; + } + + static Attributes mapAttributes(List labels, List values) { + AttributesBuilder result = Attributes.builder(); + for (int i = 0; i < labels.size(); i++) { + result.put(labels.get(i).getKey(), values.get(i).getValue()); + } + return result.build(); + } + + static long longValue(Point point) { + return point + .getValue() + .match( + Double::longValue, + lv -> lv, + // Ignore these cases (logic error) + distribution -> 0, + summary -> 0, + defaultValue -> 0) + .longValue(); + } + + static double doubleValue(Point point) { + return point + .getValue() + .match( + d -> d, + Long::doubleValue, + // Ignore these cases (logic error) + distribution -> 0, + summary -> 0, + defaultValue -> 0) + .doubleValue(); + } + + static List mapBoundaries(Distribution.BucketOptions censusBuckets) { + return censusBuckets.match( + explicit -> explicit.getBucketBoundaries(), defaultOption -> Collections.emptyList()); + } + + static List mapCounts(List buckets) { + List result = new ArrayList<>(buckets.size()); + for (Distribution.Bucket bucket : buckets) { + result.add(bucket.getCount()); + } + return result; + } + + static List mapExemplars(List buckets) { + List result = new ArrayList<>(); + for (Distribution.Bucket bucket : buckets) { + Exemplar exemplar = bucket.getExemplar(); + if (exemplar != null) { + result.add(mapExemplar(exemplar)); + } + } + return result; + } + + private static DoubleExemplarData mapExemplar(Exemplar exemplar) { + // Look for trace/span id. + SpanContext spanContext = SpanContext.getInvalid(); + if (exemplar.getAttachments().containsKey("SpanContext")) { + // We need to use `io.opencensus.contrib.exemplar.util.AttachmentValueSpanContext` + // The `toString` will be the following: + // SpanContext{traceId=TraceId{traceId=(id))}, spanId=SpanId{spanId=(id), ...} + // We *attempt* parse it rather than pull in yet another dependency. + String spanContextToString = exemplar.getAttachments().get("SpanContext").getValue(); + Matcher m = OPENCENSUS_TRACE_ATTACHMENT_PATTERN.matcher(spanContextToString); + if (m.matches()) { + MatchResult mr = m.toMatchResult(); + String traceId = mr.group(1); + String spanId = mr.group(2); + spanContext = + SpanContext.create(traceId, spanId, TraceFlags.getDefault(), TraceState.getDefault()); + } + } + return ImmutableDoubleExemplarData.create( + Attributes.empty(), + mapTimestamp(exemplar.getTimestamp()), + spanContext, + exemplar.getValue()); + } + + static long mapTimestamp(@Nullable Timestamp time) { + // Treat all empty timestamps as "0" (proto3) + if (time == null) { + return 0; + } + return TimeUnit.SECONDS.toNanos(time.getSeconds()) + time.getNanos(); + } + + private static List mapValueAtPercentiles( + List valueAtPercentiles) { + List result = new ArrayList<>(valueAtPercentiles.size()); + for (Summary.Snapshot.ValueAtPercentile censusValue : valueAtPercentiles) { + result.add( + ImmutableValueAtQuantile.create( + censusValue.getPercentile() / 100.0, censusValue.getValue())); + } + return result; + } +} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java new file mode 100644 index 00000000000..20f301833c9 --- /dev/null +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducer.java @@ -0,0 +1,61 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import io.opencensus.metrics.Metrics; +import io.opencensus.metrics.export.MetricProducerManager; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricProducer; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * {@link MetricProducer} for OpenCensus metrics, which allows {@link MetricReader}s to read from + * both OpenTelemetry and OpenCensus metrics. + * + *

    To use, register with {@link SdkMeterProviderBuilder#registerMetricProducer(MetricProducer)}. + * + * @deprecated OpenCensus compatibility is deprecated in the OpenTelemetry specification (see #5138). + * Expect this artifact to no longer be published after June 2027. + */ +@Deprecated +public final class OpenCensusMetricProducer implements MetricProducer { + private final MetricProducerManager openCensusMetricStorage; + + private OpenCensusMetricProducer(MetricProducerManager openCensusMetricStorage) { + this.openCensusMetricStorage = openCensusMetricStorage; + } + + /** + * Constructs a new {@link OpenCensusMetricProducer} that reads from the global OpenCensus {@link + * MetricProducerManager}. + * + * @deprecated OpenCensus compatibility is deprecated in the OpenTelemetry specification (see #5138). + * Expect this artifact to no longer be published after June 2027. + */ + @Deprecated + public static MetricProducer create() { + return new OpenCensusMetricProducer(Metrics.getExportComponent().getMetricProducerManager()); + } + + @Override + public Collection produce(Resource resource) { + List result = new ArrayList<>(); + openCensusMetricStorage + .getAllMetricProducer() + .forEach(producer -> + producer + .getMetrics() + .forEach(metric -> result.add(MetricAdapter.convert(resource, metric)))); + return result; + } +} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryContextManager.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryContextManager.java index d73e41ab5dd..65c7a9174b4 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryContextManager.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryContextManager.java @@ -16,12 +16,26 @@ * {@link io.opencensus.trace.unsafe.ContextManagerImpl}. It is loaded by OpenCensus via reflection * automatically in {@link io.opencensus.trace.unsafe.ContextHandleUtils} when the OpenCensus shim * library exists as a dependency. + * + * @deprecated OpenCensus compatibility is deprecated in the OpenTelemetry specification (see #5138). + * Expect this artifact to no longer be published after June 2027. */ +@Deprecated public final class OpenTelemetryContextManager implements ContextManager { private static final Logger LOGGER = Logger.getLogger(OpenTelemetryContextManager.class.getName()); + /** + * Creates the context manager loaded by OpenCensus through reflection. + * + * @deprecated OpenCensus compatibility is deprecated in the OpenTelemetry specification (see #5138). + * Expect this artifact to no longer be published after June 2027. + */ + @Deprecated + @SuppressWarnings("unused") // Loaded via reflection public OpenTelemetryContextManager() {} @Override diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryCtx.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryCtx.java index ae94f630713..a551597186f 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryCtx.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryCtx.java @@ -10,7 +10,7 @@ import io.opentelemetry.context.Scope; import javax.annotation.Nullable; -class OpenTelemetryCtx implements ContextHandle { +final class OpenTelemetryCtx implements ContextHandle { private final Context context; diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryMetricsExporter.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryMetricsExporter.java deleted file mode 100644 index 32783892204..00000000000 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryMetricsExporter.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim; - -import com.google.common.base.Joiner; -import io.opencensus.common.Duration; -import io.opencensus.exporter.metrics.util.IntervalMetricReader; -import io.opencensus.exporter.metrics.util.MetricExporter; -import io.opencensus.exporter.metrics.util.MetricReader; -import io.opencensus.metrics.Metrics; -import io.opencensus.metrics.export.Metric; -import io.opencensus.metrics.export.MetricDescriptor; -import io.opentelemetry.opencensusshim.internal.metrics.MetricAdapter; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.logging.Logger; - -@Deprecated -public final class OpenTelemetryMetricsExporter extends MetricExporter { - private static final Logger LOGGER = - Logger.getLogger(OpenTelemetryMetricsExporter.class.getName()); - - private static final String EXPORTER_NAME = "OpenTelemetryMetricExporter"; - - private final IntervalMetricReader intervalMetricReader; - private final io.opentelemetry.sdk.metrics.export.MetricExporter otelExporter; - // TODO - find this from OTel SDK. - private final Resource resource = Resource.getDefault(); - - public static OpenTelemetryMetricsExporter createAndRegister( - io.opentelemetry.sdk.metrics.export.MetricExporter otelExporter) { - return new OpenTelemetryMetricsExporter(otelExporter, Duration.create(60, 0)); - } - - public static OpenTelemetryMetricsExporter createAndRegister( - io.opentelemetry.sdk.metrics.export.MetricExporter otelExporter, Duration exportInterval) { - return new OpenTelemetryMetricsExporter(otelExporter, exportInterval); - } - - private OpenTelemetryMetricsExporter( - io.opentelemetry.sdk.metrics.export.MetricExporter otelExporter, Duration exportInterval) { - this.otelExporter = otelExporter; - IntervalMetricReader.Options.Builder options = IntervalMetricReader.Options.builder(); - MetricReader reader = - MetricReader.create( - MetricReader.Options.builder() - .setMetricProducerManager(Metrics.getExportComponent().getMetricProducerManager()) - .setSpanName(EXPORTER_NAME) - .build()); - intervalMetricReader = - IntervalMetricReader.create( - this, reader, options.setExportInterval(exportInterval).build()); - } - - @Override - public void export(Collection metrics) { - List metricData = new ArrayList<>(); - Set unsupportedTypes = new HashSet<>(); - for (Metric metric : metrics) { - metricData.add(MetricAdapter.convert(resource, metric)); - } - if (!unsupportedTypes.isEmpty()) { - LOGGER.warning( - Joiner.on(",").join(unsupportedTypes) - + " not supported by OpenCensus to OpenTelemetry migrator."); - } - if (!metricData.isEmpty()) { - otelExporter.export(metricData); - } - } - - public void stop() { - intervalMetricReader.stop(); - } -} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImpl.java index b6f3e8eec11..5c075c212b2 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImpl.java @@ -22,7 +22,6 @@ package io.opentelemetry.opencensusshim; -import com.google.common.base.Preconditions; import io.opencensus.trace.Annotation; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.EndSpanOptions; @@ -33,13 +32,16 @@ import io.opencensus.trace.Status; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.trace.StatusCode; import java.util.EnumSet; import java.util.Map; +import java.util.Objects; import java.util.concurrent.TimeUnit; -import javax.annotation.Nonnull; +import javax.annotation.Nullable; -class OpenTelemetryNoRecordEventsSpanImpl extends Span implements io.opentelemetry.api.trace.Span { +final class OpenTelemetryNoRecordEventsSpanImpl extends Span + implements io.opentelemetry.api.trace.Span { private static final EnumSet NOT_RECORD_EVENTS_SPAN_OPTIONS = EnumSet.noneOf(Options.class); @@ -53,39 +55,39 @@ static OpenTelemetryNoRecordEventsSpanImpl create(SpanContext context) { @Override public void addAnnotation(String description, Map attributes) { - Preconditions.checkNotNull(description, "description"); - Preconditions.checkNotNull(attributes, "attribute"); + Objects.requireNonNull(description, "description"); + Objects.requireNonNull(attributes, "attribute"); } @Override public void addAnnotation(Annotation annotation) { - Preconditions.checkNotNull(annotation, "annotation"); + Objects.requireNonNull(annotation, "annotation"); } @Override public void putAttribute(String key, AttributeValue value) { - Preconditions.checkNotNull(key, "key"); - Preconditions.checkNotNull(value, "value"); + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(value, "value"); } @Override public void putAttributes(Map attributes) { - Preconditions.checkNotNull(attributes, "attributes"); + Objects.requireNonNull(attributes, "attributes"); } @Override public void addMessageEvent(MessageEvent messageEvent) { - Preconditions.checkNotNull(messageEvent, "messageEvent"); + Objects.requireNonNull(messageEvent, "messageEvent"); } @Override public void addLink(Link link) { - Preconditions.checkNotNull(link, "link"); + Objects.requireNonNull(link, "link"); } @Override public void setStatus(Status status) { - Preconditions.checkNotNull(status, "status"); + Objects.requireNonNull(status, "status"); } @Override @@ -100,7 +102,7 @@ public io.opentelemetry.api.trace.Span setStatus(StatusCode canonicalCode, Strin @Override public void end(EndSpanOptions options) { - Preconditions.checkNotNull(options, "options"); + Objects.requireNonNull(options, "options"); } @Override @@ -109,7 +111,7 @@ public void end(long timestamp, TimeUnit unit) { } @Override - public io.opentelemetry.api.trace.Span setAttribute(String key, @Nonnull String value) { + public io.opentelemetry.api.trace.Span setAttribute(String key, @Nullable String value) { return this; } @@ -129,7 +131,12 @@ public io.opentelemetry.api.trace.Span setAttribute(String key, boolean value) { } @Override - public io.opentelemetry.api.trace.Span setAttribute(AttributeKey key, @Nonnull T value) { + public io.opentelemetry.api.trace.Span setAttribute(String key, Value value) { + return this; + } + + @Override + public io.opentelemetry.api.trace.Span setAttribute(AttributeKey key, @Nullable T value) { return this; } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryPropagationComponentImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryPropagationComponentImpl.java index 6898345ebd0..a4d77541675 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryPropagationComponentImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryPropagationComponentImpl.java @@ -10,7 +10,7 @@ import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.extension.trace.propagation.B3Propagator; -class OpenTelemetryPropagationComponentImpl extends PropagationComponentImpl { +final class OpenTelemetryPropagationComponentImpl extends PropagationComponentImpl { private final TextFormat b3Format = new OpenTelemetryTextFormatImpl(B3Propagator.injectingMultiHeaders()); diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanBuilderImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanBuilderImpl.java index fbf4b423e66..cae916eca8b 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanBuilderImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanBuilderImpl.java @@ -22,8 +22,8 @@ package io.opentelemetry.opencensusshim; -import static com.google.common.base.Preconditions.checkNotNull; import static io.opentelemetry.opencensusshim.SpanConverter.mapKind; +import static java.util.Objects.requireNonNull; import io.opencensus.implcore.trace.internal.RandomHandler; import io.opencensus.trace.Sampler; @@ -41,15 +41,17 @@ import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.internal.OtelVersion; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import javax.annotation.Nullable; -class OpenTelemetrySpanBuilderImpl extends SpanBuilder { +final class OpenTelemetrySpanBuilderImpl extends SpanBuilder { + private static final Tracer OTEL_TRACER = - GlobalOpenTelemetry.getTracer("io.opentelemetry.opencensusshim"); + GlobalOpenTelemetry.getTracer("io.opentelemetry.opencensusshim", OtelVersion.VERSION); private static final Tracestate OC_TRACESTATE_DEFAULT = Tracestate.builder().build(); private static final TraceOptions OC_SAMPLED_TRACE_OPTIONS = TraceOptions.builder().setIsSampled(true).build(); @@ -66,15 +68,38 @@ class OpenTelemetrySpanBuilderImpl extends SpanBuilder { @Nullable private Sampler ocSampler; @Nullable private SpanKind otelKind; + private OpenTelemetrySpanBuilderImpl( + String name, + @Nullable SpanContext ocRemoteParentSpanContext, + @Nullable Span ocParent, + OpenTelemetrySpanBuilderImpl.Options options) { + this.name = requireNonNull(name, "name"); + this.ocParent = ocParent; + this.ocRemoteParentSpanContext = ocRemoteParentSpanContext; + this.options = options; + } + + static OpenTelemetrySpanBuilderImpl createWithParent( + String spanName, @Nullable Span parent, OpenTelemetrySpanBuilderImpl.Options options) { + return new OpenTelemetrySpanBuilderImpl(spanName, null, parent, options); + } + + static OpenTelemetrySpanBuilderImpl createWithRemoteParent( + String spanName, + @Nullable SpanContext remoteParentSpanContext, + OpenTelemetrySpanBuilderImpl.Options options) { + return new OpenTelemetrySpanBuilderImpl(spanName, remoteParentSpanContext, null, options); + } + @Override public SpanBuilder setSampler(Sampler sampler) { - this.ocSampler = checkNotNull(sampler, "sampler"); + this.ocSampler = requireNonNull(sampler, "sampler"); return this; } @Override public SpanBuilder setParentLinks(List parentLinks) { - this.ocParentLinks = checkNotNull(parentLinks, "parentLinks"); + this.ocParentLinks = requireNonNull(parentLinks, "parentLinks"); for (Span parent : parentLinks) { this.otelParentLinks.add(SpanConverter.mapSpanContext(parent.getContext())); } @@ -104,12 +129,12 @@ public Span startSpan() { Boolean hasRemoteParent = null; if (ocRemoteParentSpanContext != null && ocRemoteParentSpanContext.isValid()) { ocParentContext = ocRemoteParentSpanContext; - hasRemoteParent = Boolean.TRUE; + hasRemoteParent = true; ocTraceId = ocParentContext.getTraceId(); ocTracestate = ocParentContext.getTracestate(); } else if (ocParent != null && ocParent.getContext().isValid()) { ocParentContext = ocParent.getContext(); - hasRemoteParent = Boolean.FALSE; + hasRemoteParent = false; ocTraceId = ocParentContext.getTraceId(); ocTracestate = ocParentContext.getTracestate(); } else { @@ -139,7 +164,11 @@ public Span startSpan() { otelSpanBuilder.setParent(Context.current().with((OpenTelemetrySpanImpl) ocParent)); } if (ocRemoteParentSpanContext != null) { - otelSpanBuilder.addLink(SpanConverter.mapSpanContext(ocRemoteParentSpanContext)); + io.opentelemetry.api.trace.SpanContext spanContext = + SpanConverter.mapSpanContext(ocRemoteParentSpanContext, /* isRemoteParent= */ true); + otelSpanBuilder.setParent( + Context.current().with(io.opentelemetry.api.trace.Span.wrap(spanContext))); + otelSpanBuilder.addLink(spanContext); } if (otelKind != null) { otelSpanBuilder.setSpanKind(otelKind); @@ -153,29 +182,6 @@ public Span startSpan() { return new OpenTelemetrySpanImpl(otSpan); } - private OpenTelemetrySpanBuilderImpl( - String name, - @Nullable SpanContext ocRemoteParentSpanContext, - @Nullable Span ocParent, - OpenTelemetrySpanBuilderImpl.Options options) { - this.name = checkNotNull(name, "name"); - this.ocParent = ocParent; - this.ocRemoteParentSpanContext = ocRemoteParentSpanContext; - this.options = options; - } - - static OpenTelemetrySpanBuilderImpl createWithParent( - String spanName, @Nullable Span parent, OpenTelemetrySpanBuilderImpl.Options options) { - return new OpenTelemetrySpanBuilderImpl(spanName, null, parent, options); - } - - static OpenTelemetrySpanBuilderImpl createWithRemoteParent( - String spanName, - @Nullable SpanContext remoteParentSpanContext, - OpenTelemetrySpanBuilderImpl.Options options) { - return new OpenTelemetrySpanBuilderImpl(spanName, remoteParentSpanContext, null, options); - } - private static boolean makeSamplingDecision( @Nullable SpanContext parent, @Nullable Boolean hasRemoteParent, @@ -214,8 +220,8 @@ static final class Options { private final TraceConfig traceConfig; Options(RandomHandler randomHandler, TraceConfig traceConfig) { - this.randomHandler = checkNotNull(randomHandler, "randomHandler"); - this.traceConfig = checkNotNull(traceConfig, "traceConfig"); + this.randomHandler = requireNonNull(randomHandler, "randomHandler"); + this.traceConfig = requireNonNull(traceConfig, "traceConfig"); } } } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java index 6d0e39501f4..4e68d9c144c 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImpl.java @@ -31,7 +31,6 @@ import static io.opentelemetry.opencensusshim.SpanConverter.setLongAttribute; import static io.opentelemetry.opencensusshim.SpanConverter.setStringAttribute; -import com.google.common.base.Preconditions; import io.opencensus.trace.Annotation; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.EndSpanOptions; @@ -39,6 +38,8 @@ import io.opencensus.trace.MessageEvent; import io.opencensus.trace.Span; import io.opencensus.trace.Status; +import io.opencensus.trace.TraceOptions; +import io.opencensus.trace.Tracestate; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; @@ -46,14 +47,13 @@ import io.opentelemetry.api.trace.StatusCode; import java.util.EnumSet; import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.logging.Logger; -import javax.annotation.Nonnull; +import java.util.Objects; -class OpenTelemetrySpanImpl extends Span implements io.opentelemetry.api.trace.Span { - private static final Logger LOGGER = Logger.getLogger(OpenTelemetrySpanImpl.class.getName()); +class OpenTelemetrySpanImpl extends Span + implements io.opentelemetry.api.trace.Span, DelegatingSpan { private static final EnumSet RECORD_EVENTS_SPAN_OPTIONS = EnumSet.of(Span.Options.RECORD_EVENTS); + private static final Tracestate OC_TRACESTATE_DEFAULT = Tracestate.builder().build(); private final io.opentelemetry.api.trace.Span otelSpan; @@ -62,21 +62,30 @@ class OpenTelemetrySpanImpl extends Span implements io.opentelemetry.api.trace.S this.otelSpan = otelSpan; } + // otel + + @Override + public io.opentelemetry.api.trace.Span getDelegate() { + return otelSpan; + } + + // opencensus + @Override public void putAttribute(String key, AttributeValue value) { - Preconditions.checkNotNull(key, "key"); - Preconditions.checkNotNull(value, "value"); + Objects.requireNonNull(key, "key"); + Objects.requireNonNull(value, "value"); value.match( - arg -> otelSpan.setAttribute(key, arg), - arg -> otelSpan.setAttribute(key, arg), - arg -> otelSpan.setAttribute(key, arg), - arg -> otelSpan.setAttribute(key, arg), + arg -> DelegatingSpan.super.setAttribute(key, arg), + arg -> DelegatingSpan.super.setAttribute(key, arg), + arg -> DelegatingSpan.super.setAttribute(key, arg), + arg -> DelegatingSpan.super.setAttribute(key, arg), arg -> null); } @Override public void putAttributes(Map attributes) { - Preconditions.checkNotNull(attributes, "attributes"); + Objects.requireNonNull(attributes, "attributes"); attributes.forEach(this::putAttribute); } @@ -84,24 +93,37 @@ public void putAttributes(Map attributes) { public void addAnnotation(String description, Map attributes) { AttributesBuilder attributesBuilder = Attributes.builder(); mapAttributes(attributes, attributesBuilder); - otelSpan.addEvent(description, attributesBuilder.build()); + DelegatingSpan.super.addEvent(description, attributesBuilder.build()); } @Override public void addAnnotation(Annotation annotation) { AttributesBuilder attributesBuilder = Attributes.builder(); mapAttributes(annotation.getAttributes(), attributesBuilder); - otelSpan.addEvent(annotation.getDescription(), attributesBuilder.build()); + DelegatingSpan.super.addEvent(annotation.getDescription(), attributesBuilder.build()); } @Override public void addLink(Link link) { - LOGGER.warning("OpenTelemetry does not support links added after a span is created."); + Objects.requireNonNull(link, "link"); + AttributesBuilder attributesBuilder = Attributes.builder(); + mapAttributes(link.getAttributes(), attributesBuilder); + // DelegatingSpan does not override addLink, so DelegatingSpan.super.addLink(..) would call the + // no-op default method of Span and drop the link. Call the delegate directly instead. + getDelegate() + .addLink( + mapSpanContext( + io.opencensus.trace.SpanContext.create( + link.getTraceId(), + link.getSpanId(), + TraceOptions.DEFAULT, + OC_TRACESTATE_DEFAULT)), + attributesBuilder.build()); } @Override public void addMessageEvent(MessageEvent messageEvent) { - otelSpan.addEvent( + DelegatingSpan.super.addEvent( String.valueOf(messageEvent.getMessageId()), Attributes.of( AttributeKey.stringKey(MESSAGE_EVENT_ATTRIBUTE_KEY_TYPE), @@ -114,71 +136,29 @@ public void addMessageEvent(MessageEvent messageEvent) { @Override public void setStatus(Status status) { - Preconditions.checkNotNull(status, "status"); - otelSpan.setStatus(status.isOk() ? StatusCode.OK : StatusCode.ERROR); + Objects.requireNonNull(status, "status"); + StatusCode code = status.isOk() ? StatusCode.OK : StatusCode.ERROR; + String description = status.getDescription(); + if (description == null) { + DelegatingSpan.super.setStatus(code); + } else { + DelegatingSpan.super.setStatus(code, description); + } } @Override public io.opentelemetry.api.trace.Span setStatus(StatusCode canonicalCode, String description) { - return otelSpan.setStatus(canonicalCode, description); + return DelegatingSpan.super.setStatus(canonicalCode, description); } @Override public void end(EndSpanOptions options) { - otelSpan.end(); - } - - @Override - @SuppressWarnings("ParameterPackage") - public void end(long timestamp, TimeUnit unit) { - otelSpan.end(timestamp, unit); - } - - @Override - public io.opentelemetry.api.trace.Span setAttribute(AttributeKey key, @Nonnull T value) { - return otelSpan.setAttribute(key, value); - } - - @Override - public io.opentelemetry.api.trace.Span addEvent(String name) { - return otelSpan.addEvent(name); - } - - @Override - public io.opentelemetry.api.trace.Span addEvent(String name, long timestamp, TimeUnit unit) { - return otelSpan.addEvent(name, timestamp, unit); - } - - @Override - public io.opentelemetry.api.trace.Span addEvent(String name, Attributes attributes) { - return otelSpan.addEvent(name, attributes); - } - - @Override - public io.opentelemetry.api.trace.Span addEvent( - String name, Attributes attributes, long timestamp, TimeUnit unit) { - return otelSpan.addEvent(name, attributes, timestamp, unit); - } - - @Override - public io.opentelemetry.api.trace.Span recordException(Throwable exception) { - return otelSpan.recordException(exception); - } - - @Override - public io.opentelemetry.api.trace.Span recordException( - Throwable exception, Attributes additionalAttributes) { - return otelSpan.recordException(exception, additionalAttributes); - } - - @Override - public io.opentelemetry.api.trace.Span updateName(String name) { - return otelSpan.updateName(name); + DelegatingSpan.super.end(); } @Override public SpanContext getSpanContext() { - return otelSpan.getSpanContext(); + return DelegatingSpan.super.getSpanContext(); } @Override @@ -188,13 +168,12 @@ public boolean isRecording() { private static void mapAttributes( Map attributes, AttributesBuilder attributesBuilder) { - attributes.forEach( - (s, attributeValue) -> - attributeValue.match( - setStringAttribute(attributesBuilder, s), - setBooleanAttribute(attributesBuilder, s), - setLongAttribute(attributesBuilder, s), - setDoubleAttribute(attributesBuilder, s), - arg -> null)); + attributes.forEach((s, attributeValue) -> + attributeValue.match( + setStringAttribute(attributesBuilder, s), + setBooleanAttribute(attributesBuilder, s), + setLongAttribute(attributesBuilder, s), + setDoubleAttribute(attributesBuilder, s), + arg -> null)); } } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImpl.java index c8c2c3d4009..ac4d76f429d 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImpl.java @@ -18,7 +18,7 @@ import java.util.List; import javax.annotation.Nullable; -class OpenTelemetryTextFormatImpl extends TextFormat { +final class OpenTelemetryTextFormatImpl extends TextFormat { private final TextMapPropagator propagator; diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTraceComponentImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTraceComponentImpl.java index b35e0092c3f..4a306aa5627 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTraceComponentImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTraceComponentImpl.java @@ -12,23 +12,38 @@ import io.opencensus.trace.TraceComponent; import io.opencensus.trace.Tracer; import io.opencensus.trace.config.TraceConfig; +import io.opencensus.trace.config.TraceParams; import io.opencensus.trace.export.ExportComponent; import io.opencensus.trace.propagation.PropagationComponent; +import io.opencensus.trace.samplers.Samplers; /** * Implementation of the {@link TraceComponent} for OpenTelemetry migration, which uses the * OpenTelemetry migration StartEndHandler. This class is loaded by reflection in {@link * io.opencensus.trace.Tracing} and overrides the OpenCensus default implementation when present. + * + * @deprecated OpenCensus compatibility is deprecated in the OpenTelemetry specification (see #5138). + * Expect this artifact to no longer be published after June 2027. */ +@Deprecated public final class OpenTelemetryTraceComponentImpl extends TraceComponent { private final PropagationComponent propagationComponent = new OpenTelemetryPropagationComponentImpl(); private final ExportComponent noopExportComponent = ExportComponent.newNoopExportComponent(); private final Clock clock; - private final TraceConfig traceConfig = new TraceConfigImpl(); + private final TraceConfig traceConfig = makeTraceConfig(); private final Tracer tracer; - /** Public constructor to be used with reflection loading. */ + /** + * Creates the trace component loaded by OpenCensus through reflection. + * + * @deprecated OpenCensus compatibility is deprecated in the OpenTelemetry specification (see #5138). + * Expect this artifact to no longer be published after June 2027. + */ + @Deprecated + @SuppressWarnings("unused") // Loaded via reflection public OpenTelemetryTraceComponentImpl() { clock = MillisClock.getInstance(); RandomHandler randomHandler = new ThreadLocalRandomHandler(); @@ -46,7 +61,7 @@ public PropagationComponent getPropagationComponent() { } @Override - public final Clock getClock() { + public Clock getClock() { return clock; } @@ -60,4 +75,13 @@ public ExportComponent getExportComponent() { public TraceConfig getTraceConfig() { return traceConfig; } + + private static TraceConfig makeTraceConfig() { + // Use the default TraceParams except use an always-on sampler. This defers the + // sampling decision to OpenTelemetry + TraceConfig traceConfig = new TraceConfigImpl(); + traceConfig.updateActiveTraceParams( + TraceParams.DEFAULT.toBuilder().setSampler(Samplers.alwaysSample()).build()); + return traceConfig; + } } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTracerImpl.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTracerImpl.java index c3ba98b67fd..4bffa46fc26 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTracerImpl.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/OpenTelemetryTracerImpl.java @@ -30,10 +30,10 @@ import io.opencensus.trace.config.TraceConfig; import javax.annotation.Nullable; -class OpenTelemetryTracerImpl extends Tracer { +final class OpenTelemetryTracerImpl extends Tracer { private final OpenTelemetrySpanBuilderImpl.Options spanBuilderOptions; - public OpenTelemetryTracerImpl(RandomHandler randomHandler, TraceConfig traceConfig) { + OpenTelemetryTracerImpl(RandomHandler randomHandler, TraceConfig traceConfig) { spanBuilderOptions = new OpenTelemetrySpanBuilderImpl.Options(randomHandler, traceConfig); } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java index fc559d2d063..b60d38d835c 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/SpanConverter.java @@ -8,6 +8,7 @@ import io.opencensus.common.Function; import io.opencensus.trace.BlankSpan; import io.opencensus.trace.Span; +import io.opencensus.trace.Span.Kind; import io.opencensus.trace.SpanContext; import io.opencensus.trace.SpanId; import io.opencensus.trace.TraceId; @@ -28,7 +29,7 @@ final class SpanConverter { private SpanConverter() {} - static SpanKind mapKind(@Nullable io.opencensus.trace.Span.Kind ocKind) { + static SpanKind mapKind(@Nullable Kind ocKind) { if (ocKind == null) { return SpanKind.INTERNAL; } @@ -57,13 +58,22 @@ static SpanContext mapSpanContext(io.opentelemetry.api.trace.SpanContext otelSpa } static io.opentelemetry.api.trace.SpanContext mapSpanContext(SpanContext ocSpanContext) { - return io.opentelemetry.api.trace.SpanContext.create( - ocSpanContext.getTraceId().toLowerBase16(), - ocSpanContext.getSpanId().toLowerBase16(), + return mapSpanContext(ocSpanContext, /* isRemoteParent= */ false); + } + + static io.opentelemetry.api.trace.SpanContext mapSpanContext( + SpanContext ocSpanContext, boolean isRemoteParent) { + String traceId = ocSpanContext.getTraceId().toLowerBase16(); + String spanId = ocSpanContext.getSpanId().toLowerBase16(); + TraceFlags traceFlags = ocSpanContext.getTraceOptions().isSampled() ? TraceFlags.getSampled() - : TraceFlags.getDefault(), - mapTracestate(ocSpanContext.getTracestate())); + : TraceFlags.getDefault(); + TraceState traceState = mapTracestate(ocSpanContext.getTracestate()); + return isRemoteParent + ? io.opentelemetry.api.trace.SpanContext.createFromRemoteParent( + traceId, spanId, traceFlags, traceState) + : io.opentelemetry.api.trace.SpanContext.create(traceId, spanId, traceFlags, traceState); } private static TraceState mapTracestate(Tracestate tracestate) { @@ -74,7 +84,13 @@ private static TraceState mapTracestate(Tracestate tracestate) { static Tracestate mapTracestate(TraceState traceState) { Tracestate.Builder tracestateBuilder = Tracestate.builder(); - traceState.forEach(tracestateBuilder::set); + traceState.forEach((key, value) -> { + // OpenCensus does not accept the W3C multi-tenant key format (tenant-id@system-id) that + // OpenTelemetry allows. Drop such entries instead of failing the whole conversion. + if (key.indexOf('@') < 0) { + tracestateBuilder.set(key, value); + } + }); return tracestateBuilder.build(); } diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/ThreadLocalRandomHandler.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/ThreadLocalRandomHandler.java index 76b1567d2bf..942a06c8856 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/ThreadLocalRandomHandler.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/ThreadLocalRandomHandler.java @@ -15,10 +15,10 @@ * implementation in opencensus-impl, however we do not want to depend on opencensus-impl here. */ @ThreadSafe -public final class ThreadLocalRandomHandler extends RandomHandler { +final class ThreadLocalRandomHandler extends RandomHandler { /** Constructs a new {@code ThreadLocalRandomHandler}. */ - public ThreadLocalRandomHandler() {} + ThreadLocalRandomHandler() {} @Override public Random current() { diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/internal/metrics/MetricAdapter.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/internal/metrics/MetricAdapter.java deleted file mode 100644 index f8b7c9f1d3f..00000000000 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/internal/metrics/MetricAdapter.java +++ /dev/null @@ -1,386 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.internal.metrics; - -import io.opencensus.common.Timestamp; -import io.opencensus.metrics.LabelKey; -import io.opencensus.metrics.LabelValue; -import io.opencensus.metrics.data.Exemplar; -import io.opencensus.metrics.export.Distribution; -import io.opencensus.metrics.export.Metric; -import io.opencensus.metrics.export.MetricDescriptor; -import io.opencensus.metrics.export.Point; -import io.opencensus.metrics.export.Summary; -import io.opencensus.metrics.export.TimeSeries; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.DoublePointData; -import io.opentelemetry.sdk.metrics.data.GaugeData; -import io.opentelemetry.sdk.metrics.data.HistogramData; -import io.opentelemetry.sdk.metrics.data.HistogramPointData; -import io.opentelemetry.sdk.metrics.data.LongPointData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.SumData; -import io.opentelemetry.sdk.metrics.data.SummaryData; -import io.opentelemetry.sdk.metrics.data.SummaryPointData; -import io.opentelemetry.sdk.metrics.data.ValueAtQuantile; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; -import io.opentelemetry.sdk.resources.Resource; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import javax.annotation.Nullable; - -/** - * Adapts an OpenCensus metric into the OpenTelemetry metric data API. - * - *

    This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class MetricAdapter { - private MetricAdapter() {} - // All OpenCensus metrics come from this shim. - // VisibleForTesting. - static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("io.opentelemetry.opencensusshim"); - - // Parser for string value of `io.opencensus.contrib.exemplar.util.AttachmentValueSpanContext` - // // SpanContext{traceId=TraceId{traceId=(id))}, spanId=SpanId{spanId=(id), ...} - private static final Pattern OPENCENSUS_TRACE_ATTACHMENT_PATTERN = - Pattern.compile( - "SpanContext\\{traceId=TraceId\\{traceId=([0-9A-Ga-g]+)\\}, spanId=SpanId\\{spanId=([0-9A-Ga-g]+)\\},.*\\}"); - /** - * Converts an open-census metric into the OTLP format. - * - * @param otelResource The resource associated with the opentelemetry SDK. - * @param censusMetric The OpenCensus metric to convert. - */ - public static MetricData convert(Resource otelResource, Metric censusMetric) { - // Note: we can't just adapt interfaces, we need to do full copy because OTel data API uses - // auto-value vs. pure interfaces. - switch (censusMetric.getMetricDescriptor().getType()) { - case GAUGE_INT64: - return ImmutableMetricData.createLongGauge( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertLongGauge(censusMetric)); - case GAUGE_DOUBLE: - return ImmutableMetricData.createDoubleGauge( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertDoubleGauge(censusMetric)); - case CUMULATIVE_INT64: - return ImmutableMetricData.createLongSum( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertLongSum(censusMetric)); - case CUMULATIVE_DOUBLE: - return ImmutableMetricData.createDoubleSum( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertDoubleSum(censusMetric)); - case CUMULATIVE_DISTRIBUTION: - return ImmutableMetricData.createDoubleHistogram( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertHistogram(censusMetric)); - case SUMMARY: - return ImmutableMetricData.createDoubleSummary( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertSummary(censusMetric)); - case GAUGE_DISTRIBUTION: - return ImmutableMetricData.createDoubleHistogram( - otelResource, - INSTRUMENTATION_SCOPE_INFO, - censusMetric.getMetricDescriptor().getName(), - censusMetric.getMetricDescriptor().getDescription(), - censusMetric.getMetricDescriptor().getUnit(), - convertGaugeHistogram(censusMetric)); - } - // Should be unreachable.... - throw new IllegalArgumentException( - "Unknown OpenCensus metric type: " + censusMetric.getMetricDescriptor().getType()); - } - - static GaugeData convertLongGauge(Metric censusMetric) { - return ImmutableGaugeData.create(convertLongPoints(censusMetric)); - } - - static GaugeData convertDoubleGauge(Metric censusMetric) { - return ImmutableGaugeData.create(convertDoublePoints(censusMetric)); - } - - static SumData convertLongSum(Metric censusMetric) { - return ImmutableSumData.create( - true, AggregationTemporality.CUMULATIVE, convertLongPoints(censusMetric)); - } - - static SumData convertDoubleSum(Metric censusMetric) { - return ImmutableSumData.create( - true, AggregationTemporality.CUMULATIVE, convertDoublePoints(censusMetric)); - } - - static HistogramData convertHistogram(Metric censusMetric) { - return ImmutableHistogramData.create( - AggregationTemporality.CUMULATIVE, convertHistogramPoints(censusMetric)); - } - - static HistogramData convertGaugeHistogram(Metric censusMetric) { - return ImmutableHistogramData.create( - AggregationTemporality.DELTA, convertHistogramPoints(censusMetric)); - } - - static SummaryData convertSummary(Metric censusMetric) { - return ImmutableSummaryData.create(convertSummaryPoints(censusMetric)); - } - - static Collection convertLongPoints(Metric censusMetric) { - // TODO - preallocate array to correct size. - List result = new ArrayList<>(); - for (TimeSeries ts : censusMetric.getTimeSeriesList()) { - long startTimestamp = mapTimestamp(ts.getStartTimestamp()); - Attributes attributes = - mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); - for (Point point : ts.getPoints()) { - result.add( - ImmutableLongPointData.create( - startTimestamp, mapTimestamp(point.getTimestamp()), attributes, longValue(point))); - } - } - return result; - } - - static Collection convertDoublePoints(Metric censusMetric) { - // TODO - preallocate array to correct size. - List result = new ArrayList<>(); - for (TimeSeries ts : censusMetric.getTimeSeriesList()) { - long startTimestamp = mapTimestamp(ts.getStartTimestamp()); - Attributes attributes = - mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); - for (Point point : ts.getPoints()) { - result.add( - ImmutableDoublePointData.create( - startTimestamp, - mapTimestamp(point.getTimestamp()), - attributes, - doubleValue(point))); - } - } - return result; - } - - static Collection convertHistogramPoints(Metric censusMetric) { - boolean isGauge = - censusMetric.getMetricDescriptor().getType() == MetricDescriptor.Type.GAUGE_DISTRIBUTION; - // TODO - preallocate array to correct size. - List result = new ArrayList<>(); - for (TimeSeries ts : censusMetric.getTimeSeriesList()) { - long startTimestamp = mapTimestamp(ts.getStartTimestamp()); - Attributes attributes = - mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); - for (Point point : ts.getPoints()) { - long endTimestamp = mapTimestamp(point.getTimestamp()); - HistogramPointData otelPoint = - point - .getValue() - .match( - doubleValue -> null, - longValue -> null, - distribution -> - ImmutableHistogramPointData.create( - // Report Gauge histograms as DELTA with "instantaneous" time window. - isGauge ? endTimestamp : startTimestamp, - endTimestamp, - attributes, - distribution.getSum(), - null, - null, - mapBoundaries(distribution.getBucketOptions()), - mapCounts(distribution.getBuckets()), - mapExemplars(distribution.getBuckets())), - summary -> null, - defaultValue -> null); - if (otelPoint != null) { - result.add(otelPoint); - } - } - } - return result; - } - - static Collection convertSummaryPoints(Metric censusMetric) { - List result = new ArrayList<>(); - for (TimeSeries ts : censusMetric.getTimeSeriesList()) { - long startTimestamp = mapTimestamp(ts.getStartTimestamp()); - Attributes attributes = - mapAttributes(censusMetric.getMetricDescriptor().getLabelKeys(), ts.getLabelValues()); - for (Point point : ts.getPoints()) { - SummaryPointData otelPoint = - point - .getValue() - .match( - dv -> null, - lv -> null, - distribution -> null, - summary -> - ImmutableSummaryPointData.create( - startTimestamp, - mapTimestamp(point.getTimestamp()), - attributes, - summary.getCount(), - summary.getSum(), - mapValueAtPercentiles(summary.getSnapshot().getValueAtPercentiles())), - defaultValue -> null); - if (otelPoint != null) { - result.add(otelPoint); - } - } - } - return result; - } - - static Attributes mapAttributes(List labels, List values) { - AttributesBuilder result = Attributes.builder(); - for (int i = 0; i < labels.size(); i++) { - result.put(labels.get(i).getKey(), values.get(i).getValue()); - } - return result.build(); - } - - static long longValue(Point point) { - return point - .getValue() - .match( - Double::longValue, - lv -> lv, - // Ignore these cases (logic error) - distribution -> 0, - summary -> 0, - defaultValue -> 0) - .longValue(); - } - - static double doubleValue(Point point) { - return point - .getValue() - .match( - d -> d, - Long::doubleValue, - // Ignore these cases (logic error) - distribution -> 0, - summary -> 0, - defaultValue -> 0) - .doubleValue(); - } - - static List mapBoundaries(Distribution.BucketOptions censusBuckets) { - return censusBuckets.match( - explicit -> explicit.getBucketBoundaries(), defaultOption -> Collections.emptyList()); - } - - static List mapCounts(List buckets) { - List result = new ArrayList<>(buckets.size()); - for (Distribution.Bucket bucket : buckets) { - result.add(bucket.getCount()); - } - return result; - } - - static List mapExemplars(List buckets) { - List result = new ArrayList<>(); - for (Distribution.Bucket bucket : buckets) { - Exemplar exemplar = bucket.getExemplar(); - if (exemplar != null) { - result.add(mapExemplar(exemplar)); - } - } - return result; - } - - private static DoubleExemplarData mapExemplar(Exemplar exemplar) { - // Look for trace/span id. - SpanContext spanContext = SpanContext.getInvalid(); - if (exemplar.getAttachments().containsKey("SpanContext")) { - // We need to use `io.opencensus.contrib.exemplar.util.AttachmentValueSpanContext` - // The `toString` will be the following: - // SpanContext{traceId=TraceId{traceId=(id))}, spanId=SpanId{spanId=(id), ...} - // We *attempt* parse it rather than pull in yet another dependency. - String spanContextToString = exemplar.getAttachments().get("SpanContext").getValue(); - Matcher m = OPENCENSUS_TRACE_ATTACHMENT_PATTERN.matcher(spanContextToString); - if (m.matches()) { - MatchResult mr = m.toMatchResult(); - String traceId = mr.group(1); - String spanId = mr.group(2); - spanContext = - SpanContext.create(traceId, spanId, TraceFlags.getDefault(), TraceState.getDefault()); - } - } - return ImmutableDoubleExemplarData.create( - Attributes.empty(), - mapTimestamp(exemplar.getTimestamp()), - spanContext, - exemplar.getValue()); - } - - static long mapTimestamp(@Nullable Timestamp time) { - // Treat all empty timestamps as "0" (proto3) - if (time == null) { - return 0; - } - return TimeUnit.SECONDS.toNanos(time.getSeconds()) + time.getNanos(); - } - - private static List mapValueAtPercentiles( - List valueAtPercentiles) { - List result = new ArrayList<>(valueAtPercentiles.size()); - for (Summary.Snapshot.ValueAtPercentile censusValue : valueAtPercentiles) { - result.add( - ImmutableValueAtQuantile.create( - censusValue.getPercentile() / 100.0, censusValue.getValue())); - } - return result; - } -} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/MultiMetricProducer.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/MultiMetricProducer.java deleted file mode 100644 index a2494faf783..00000000000 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/MultiMetricProducer.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.metrics; - -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** Class that wraps multiple metric producers into one. */ -final class MultiMetricProducer implements MetricProducer { - private final Collection producers; - - public MultiMetricProducer(Collection producers) { - this.producers = producers; - } - - @Override - public Collection collectAllMetrics() { - List result = new ArrayList<>(); - for (MetricProducer p : producers) { - result.addAll(p.collectAllMetrics()); - } - return result; - } -} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusAttachingMetricReader.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusAttachingMetricReader.java deleted file mode 100644 index 46e0f9534c2..00000000000 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusAttachingMetricReader.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.metrics; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.export.CollectionRegistration; -import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Arrays; - -/** {@link MetricReader} that appends OpenCensus metrics to anything read. */ -final class OpenCensusAttachingMetricReader implements MetricReader { - private final MetricReader adapted; - - OpenCensusAttachingMetricReader(MetricReader adapted) { - this.adapted = adapted; - } - - @Override - public void register(CollectionRegistration registration) { - // TODO: Find a way to pull the resource off of the SDK. - adapted.register( - new MultiMetricProducer( - Arrays.asList( - MetricProducer.asMetricProducer(registration), - OpenCensusMetricProducer.create(Resource.getDefault())))); - } - - @Override - public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return adapted.getAggregationTemporality(instrumentType); - } - - @Override - public CompletableResultCode forceFlush() { - return adapted.forceFlush(); - } - - @Override - public CompletableResultCode shutdown() { - return adapted.shutdown(); - } -} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricProducer.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricProducer.java deleted file mode 100644 index 77af7ecf5ee..00000000000 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricProducer.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.metrics; - -import io.opencensus.metrics.Metrics; -import io.opencensus.metrics.export.MetricProducerManager; -import io.opentelemetry.opencensusshim.internal.metrics.MetricAdapter; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import io.opentelemetry.sdk.resources.Resource; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -/** - * A producer instance of OpenCensus metrics. - * - *

    The idea here is we can register a merged {@link MetricProducer} combining this with the - * {@link SdkMeterProvider} producer with a {@link MetricReader}, allowing the reader to pull - * metrics from both OpenTelemetry and OpenCensus backends. - */ -final class OpenCensusMetricProducer implements MetricProducer { - private final Resource resource; - private final MetricProducerManager openCensusMetricStorage; - - OpenCensusMetricProducer(Resource resource, MetricProducerManager openCensusMetricStorage) { - this.resource = resource; - this.openCensusMetricStorage = openCensusMetricStorage; - } - - /** - * Constructs a new {@link OpenCensusMetricProducer} that reports against the given {@link - * Resource}. - */ - static MetricProducer create(Resource resource) { - return new OpenCensusMetricProducer( - resource, Metrics.getExportComponent().getMetricProducerManager()); - } - - @Override - public Collection collectAllMetrics() { - List result = new ArrayList<>(); - openCensusMetricStorage - .getAllMetricProducer() - .forEach( - producer -> { - producer - .getMetrics() - .forEach(metric -> result.add(MetricAdapter.convert(resource, metric))); - }); - return result; - } -} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetrics.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetrics.java deleted file mode 100644 index fc4d5a2b22c..00000000000 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetrics.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.metrics; - -import io.opentelemetry.sdk.metrics.export.MetricReader; - -/** Convenience methods for adapting OpenCensus metrics into OpenTelemetry. */ -public final class OpenCensusMetrics { - private OpenCensusMetrics() {} - - /** - * Attaches OpenCensus metrics to metrics read by the given input. - * - * @param input A {@link MetricReader} that will receive OpenCensus metrics. - * @return The adapted MetricReaderFactory. - */ - public static MetricReader attachTo(MetricReader input) { - return new OpenCensusAttachingMetricReader(input); - } -} diff --git a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/package-info.java b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/package-info.java index 36b5be41e94..9428c9c7dab 100644 --- a/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/package-info.java +++ b/opencensus-shim/src/main/java/io/opentelemetry/opencensusshim/package-info.java @@ -3,7 +3,13 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** The OpenCensus to OpenTelemetry shim. */ +/** + * Legacy OpenCensus compatibility built on top of OpenTelemetry. + * + *

    OpenCensus compatibility is deprecated in the OpenTelemetry specification, and this shim is + * deprecated accordingly. Use this package only for legacy compatibility while migrating OpenCensus + * instrumentation to the OpenTelemetry APIs. + */ @ParametersAreNonnullByDefault package io.opentelemetry.opencensusshim; diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java new file mode 100644 index 00000000000..e86a12c05a6 --- /dev/null +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/DelegatingSpanTest.java @@ -0,0 +1,243 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.times; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.context.Context; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.time.Instant; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mockito; +import org.mockito.verification.VerificationMode; + +/** + * Ensures all methods for {@link Span} are appropriately proxied by {@link OpenTelemetrySpanImpl}, + * further ensuring the shim behaves as expected when under otel javaagent instrumentation. + * + *

    This addresses a regression between the shim as used with the Otel SDK on the app classloader + * and as instrumented via the javaagent. Details here. + */ +class DelegatingSpanTest { + + /* + Verifies all methods on the otel Span interface are under test. + Each case is enumerated in proxyMethodsProvider() to avoid false-positives (bad reflection) and maximize + flexibility for special cases (e.g. getSpanContext() and isRecording()) + */ + @Test + void verifyAllMethodsAreUnderTest() { + List methods = + delegateMethodsProvider() + .map(pm -> { + try { + return getInterfaceMethod( + Span.class, (String) pm.get()[0], (Class[]) pm.get()[1]); + } catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + }) + .collect(Collectors.toList()); + + assertThat(methods) + .describedAs("all interface methods are being tested") + .containsAll(allInterfaceMethods(Span.class)); + assertThat(allInterfaceMethods(Span.class)) + .describedAs("all tested methods are on the Span interface") + .containsAll(methods); + } + + @ParameterizedTest + @MethodSource("delegateMethodsProvider") + void testit(String name, Class[] params, VerificationMode timesCalled) + throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { + Method method = getInterfaceMethod(Span.class, name, params); + Span mockedSpan = Mockito.spy(Span.current()); + OpenTelemetrySpanImpl span = new OpenTelemetrySpanImpl(mockedSpan); + assertDelegated(span, mockedSpan, method, timesCalled); + } + + static List allInterfaceMethods(Class clazz) { + return Arrays.stream(clazz.getDeclaredMethods()) + .filter(m -> Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers())) + .collect(Collectors.toList()); + } + + static Stream delegateMethodsProvider() { + return Stream.of( + Arguments.argumentSet("end no-args", "end", new Class[] {}, times(1)), + Arguments.argumentSet( + "end long TimeUnit", "end", new Class[] {long.class, TimeUnit.class}, times(1)), + Arguments.argumentSet("end Instant", "end", new Class[] {Instant.class}, times(1)), + Arguments.argumentSet( + "setAttribute String String", + "setAttribute", + new Class[] {String.class, String.class}, + times(1)), + Arguments.argumentSet( + "setAttribute AttributeKey int", + "setAttribute", + new Class[] {AttributeKey.class, int.class}, + times(1)), + Arguments.argumentSet( + "setAttribute AttributeKey Object", + "setAttribute", + new Class[] {AttributeKey.class, Object.class}, + times(1)), + Arguments.argumentSet( + "setAttribute String long", + "setAttribute", + new Class[] {String.class, long.class}, + times(1)), + Arguments.argumentSet( + "setAttribute String double", + "setAttribute", + new Class[] {String.class, double.class}, + times(1)), + Arguments.argumentSet( + "setAttribute String boolean", + "setAttribute", + new Class[] {String.class, boolean.class}, + times(1)), + Arguments.argumentSet( + "setAttribute String Value", + "setAttribute", + new Class[] {String.class, Value.class}, + times(1)), + Arguments.argumentSet( + "recordException with Attributes", + "recordException", + new Class[] {Throwable.class, Attributes.class}, + times(1)), + Arguments.argumentSet( + "recordException no Attributes", + "recordException", + new Class[] {Throwable.class}, + times(1)), + Arguments.argumentSet( + "setAllAttributes", "setAllAttributes", new Class[] {Attributes.class}, times(1)), + Arguments.argumentSet("updateName", "updateName", new Class[] {String.class}, times(1)), + Arguments.argumentSet( + "storeInContext", "storeInContext", new Class[] {Context.class}, times(1)), + Arguments.argumentSet( + "addEvent String Instant", + "addEvent", + new Class[] {String.class, Instant.class}, + times(1)), + Arguments.argumentSet( + "addEvent String long TimeUnit", + "addEvent", + new Class[] {String.class, long.class, TimeUnit.class}, + times(1)), + Arguments.argumentSet( + "addEvent String Attributes Instant", + "addEvent", + new Class[] {String.class, Attributes.class, Instant.class}, + times(1)), + Arguments.argumentSet( + "addEvent String", "addEvent", new Class[] {String.class}, times(1)), + Arguments.argumentSet( + "addEvent String Attributes long TimeUnit", + "addEvent", + new Class[] {String.class, Attributes.class, long.class, TimeUnit.class}, + times(1)), + Arguments.argumentSet( + "addEvent String Attributes", + "addEvent", + new Class[] {String.class, Attributes.class}, + times(1)), + Arguments.argumentSet( + "setStatus StatusCode String", + "setStatus", + new Class[] {StatusCode.class, String.class}, + times(1)), + Arguments.argumentSet( + "setStatus StatusCode", "setStatus", new Class[] {StatusCode.class}, times(1)), + // + // special cases + // + // called never -- it's shared between OC and Otel Span types and is always true, so returns + // `true` + Arguments.argumentSet("isRecording", "isRecording", new Class[] {}, times(0)), + // called twice: once in constructor, then once during delegation + Arguments.argumentSet("getSpanContext", "getSpanContext", new Class[] {}, times(2)), + // addLink is never called + Arguments.argumentSet( + "addLink SpanContext", "addLink", new Class[] {SpanContext.class}, times(0)), + Arguments.argumentSet( + "addLink SpanContext Attributes", + "addLink", + new Class[] {SpanContext.class, Attributes.class}, + times(0))); + } + + // gets default values for all cases, as mockito can't mock wrappers or primitives, including + // String + static Object valueLookup(Class clazz) { + if (clazz == int.class || clazz == Integer.class) { + return Integer.valueOf(0).intValue(); + } else if (clazz == long.class || clazz == Long.class) { + return Long.valueOf(0L).longValue(); + } else if (clazz == double.class || clazz == Double.class) { + return Double.valueOf(0d).doubleValue(); + } else if (clazz == char.class || clazz == Character.class) { + return Character.valueOf('\0').charValue(); + } else if (clazz == boolean.class || clazz == Boolean.class) { + return Boolean.valueOf(false).booleanValue(); + } else if (clazz == float.class || clazz == Float.class) { + return Float.valueOf(0f).floatValue(); + } else if (clazz == String.class) { + return ""; + } else if (clazz == byte.class || clazz == Byte.class) { + return Byte.valueOf((byte) 0).byteValue(); + } else if (clazz == short.class || clazz == Short.class) { + return Short.valueOf((short) 0).shortValue(); + } else { + return Mockito.mock(clazz); + } + } + + static Method getInterfaceMethod(Class clazz, String name, Class[] params) + throws NoSuchMethodException { + Method method = clazz.getMethod(name, params); + assertThat(method).isNotNull(); + return method; + } + + static void assertDelegated(T proxy, T delegate, Method method, VerificationMode mode) + throws InvocationTargetException, IllegalAccessException { + // Get parameters for method + Class[] parameterTypes = method.getParameterTypes(); + Object[] arguments = new Object[parameterTypes.length]; + for (int j = 0; j < arguments.length; j++) { + arguments[j] = valueLookup(parameterTypes[j]); + } + + // Invoke wrapper method + method.invoke(proxy, arguments); + + // Ensure method was called on delegate exactly once with the correct arguments + method.invoke(Mockito.verify(delegate, mode), arguments); + } +} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/InteroperabilityTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/InteroperabilityTest.java index 1672f071cdf..4d2fefc7242 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/InteroperabilityTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/InteroperabilityTest.java @@ -35,6 +35,7 @@ import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.SdkTracerProvider; @@ -43,6 +44,7 @@ import io.opentelemetry.sdk.trace.data.StatusData; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; import java.util.Collection; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; @@ -70,7 +72,11 @@ class InteroperabilityTest { SpanProcessor spanProcessor = SimpleSpanProcessor.create(spanExporter); openTelemetry = OpenTelemetrySdk.builder() - .setTracerProvider(SdkTracerProvider.builder().addSpanProcessor(spanProcessor).build()) + .setTracerProvider( + SdkTracerProvider.builder() + .setSampler(Sampler.alwaysOn()) + .addSpanProcessor(spanProcessor) + .build()) .buildAndRegisterGlobal(); } @@ -83,7 +89,7 @@ void resetMocks() { } @Test - void testParentChildRelationshipsAreExportedCorrectly() { + void parentChildRelationshipsAreExportedCorrectly() { Tracer tracer = openTelemetry.getTracer("io.opentelemetry.test.scoped.span.1"); Span span = tracer.spanBuilder("OpenTelemetrySpan").startSpan(); try (Scope scope = Context.current().with(span).makeCurrent()) { @@ -127,7 +133,7 @@ void testParentChildRelationshipsAreExportedCorrectly() { } @Test - void testRemoteParent() { + void remoteParent() { io.opencensus.trace.Tracer tracer = Tracing.getTracer(); io.opencensus.trace.Span remoteParentSpan = tracer.spanBuilder("remote parent span").startSpan(); @@ -147,13 +153,23 @@ void testRemoteParent() { assertThat(export1.size()).isEqualTo(1); SpanData spanData1 = export1.iterator().next(); + + // Remote parent should be set to parent span context + assertThat(spanData1.getParentSpanContext().isRemote()).isTrue(); + assertThat(spanData1.getParentSpanContext().getTraceId()) + .isEqualTo(remoteParentSpan.getContext().getTraceId().toLowerBase16()); + assertThat(spanData1.getParentSpanContext().getSpanId()) + .isEqualTo(remoteParentSpan.getContext().getSpanId().toLowerBase16()); + + // Remote parent should be added as link assertThat(spanData1.getName()).isEqualTo("OpenCensusSpan"); assertThat(spanData1.getLinks().get(0).getSpanContext().getSpanId()) .isEqualTo(remoteParentSpan.getContext().getSpanId().toLowerBase16()); } @Test - void testParentChildRelationshipsAreExportedCorrectlyForOpenCensusOnly() { + @SuppressLogger(OpenTelemetrySpanImpl.class) + void parentChildRelationshipsAreExportedCorrectlyForOpenCensusOnly() { io.opencensus.trace.Tracer tracer = Tracing.getTracer(); io.opencensus.trace.Span parentLinkSpan = tracer.spanBuilder("parent link span").startSpan(); try (io.opencensus.common.Scope scope = @@ -259,7 +275,7 @@ void testParentChildRelationshipsAreExportedCorrectlyForOpenCensusOnly() { } @Test - void testOpenTelemetryMethodsOnOpenCensusSpans() { + void openTelemetryMethodsOnOpenCensusSpans() { io.opencensus.trace.Tracer tracer = Tracing.getTracer(); try (io.opencensus.common.Scope scope = tracer @@ -306,7 +322,7 @@ void testOpenTelemetryMethodsOnOpenCensusSpans() { } @Test - public void testNoSampleDoesNotExport() { + public void noSampleDoesNotExport() { io.opencensus.trace.Tracer tracer = Tracing.getTracer(); try (io.opencensus.common.Scope scope = tracer.spanBuilder("OpenCensusSpan").setSampler(Samplers.neverSample()).startScopedSpan()) { @@ -322,7 +338,14 @@ public void testNoSampleDoesNotExport() { } @Test - public void testNoRecordDoesNotExport() { + public void openCensusSamplerIsAlwaysOn() { + // OpenTelemetryTraceComponentImpl provides this behavior + assertThat(Tracing.getTraceConfig().getActiveTraceParams().getSampler()) + .isEqualTo(Samplers.alwaysSample()); + } + + @Test + public void byDefaultDoesExport() { io.opencensus.trace.Tracer tracer = Tracing.getTracer(); try (io.opencensus.common.Scope scope = tracer.spanBuilder("OpenCensusSpan").setRecordEvents(false).startScopedSpan()) { @@ -333,7 +356,7 @@ public void testNoRecordDoesNotExport() { span.putAttribute("testKey", AttributeValue.stringAttributeValue("testValue")); } Tracing.getExportComponent().shutdown(); - verify(spanExporter, never()).export(anyCollection()); + verify(spanExporter, times(1)).export(anyCollection()); } private static void createOpenCensusScopedSpanWithChildSpan( diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java new file mode 100644 index 00000000000..8ec647286f5 --- /dev/null +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/MetricAdapterTest.java @@ -0,0 +1,368 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; + +import io.opencensus.common.Timestamp; +import io.opencensus.metrics.LabelKey; +import io.opencensus.metrics.LabelValue; +import io.opencensus.metrics.data.AttachmentValue; +import io.opencensus.metrics.data.Exemplar; +import io.opencensus.metrics.export.Distribution; +import io.opencensus.metrics.export.Metric; +import io.opencensus.metrics.export.MetricDescriptor; +import io.opencensus.metrics.export.Point; +import io.opencensus.metrics.export.Summary; +import io.opencensus.metrics.export.TimeSeries; +import io.opencensus.metrics.export.Value; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class MetricAdapterTest { + + private static final Resource RESOURCE = + Resource.create(Attributes.of(AttributeKey.stringKey("test"), "resource")); + + @Test + void convertsTimeStamps() { + assertThat(MetricAdapter.mapTimestamp(Timestamp.create(1, 2))).isEqualTo(1000000002L); + } + + @Test + void convertsLongValue() { + assertThat(MetricAdapter.longValue(Point.create(Value.longValue(5), Timestamp.fromMillis(2)))) + .isEqualTo(5); + } + + @Test + void convertsDoubleValue() { + assertThat( + MetricAdapter.doubleValue(Point.create(Value.doubleValue(5), Timestamp.fromMillis(2)))) + .isEqualTo(5); + } + + @Test + void convertsLongGauge() { + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.GAUGE_INT64, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create(Value.longValue(4), Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(4) + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")))); + } + + @Test + void convertsDoubleGauge() { + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.GAUGE_DOUBLE, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create(Value.doubleValue(4), Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasValue(4))); + } + + @Test + void convertsLongSum() { + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.CUMULATIVE_INT64, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create(Value.longValue(4), Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasValue(4))); + } + + @Test + void convertsDoubleSum() { + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.CUMULATIVE_DOUBLE, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create(Value.doubleValue(4), Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasValue(4))); + } + + @Test + void convertHistogram() { + Map exemplarAttachments = new HashMap<>(); + // TODO - Import opencensus util for a code-dependent test on common exemplar-trace usage. + exemplarAttachments.put( + "SpanContext", + AttachmentValue.AttachmentValueString.create( + "SpanContext{traceId=TraceId{traceId=00000000000000000000000000000001}, spanId=SpanId{spanId=0000000000000002}, others=stuff}")); + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.CUMULATIVE_DISTRIBUTION, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create( + Value.distributionValue( + Distribution.create( + 10, + 5, + 2, // Sum of squared deviations, ignored + Distribution.BucketOptions.explicitOptions(Arrays.asList(2.0, 5.0)), + Arrays.asList( + Distribution.Bucket.create( + 2, + Exemplar.create( + 1.0, Timestamp.fromMillis(2), Collections.emptyMap())), + Distribution.Bucket.create( + 6, + Exemplar.create( + 4.0, Timestamp.fromMillis(1), exemplarAttachments)), + Distribution.Bucket.create(2)))), + Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasSum(5) + .hasCount(10) + .hasBucketBoundaries(2.0, 5.0) + .hasBucketCounts(2, 6, 2) + .hasExemplars( + ImmutableDoubleExemplarData.create( + Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), + ImmutableDoubleExemplarData.create( + Attributes.empty(), + 1000000, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 4.0)))); + } + + @Test + void convertSummary() { + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.SUMMARY, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create( + Value.summaryValue( + Summary.create( + 10L, + 5d, + Summary.Snapshot.create( + 10L, + 5d, + Collections.singletonList( + Summary.Snapshot.ValueAtPercentile.create(100.0, 200))))), + Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(1000000000) + .hasEpochNanos(2000000000) + .hasAttributes(attributeEntry("key1", "value1")) + .hasCount(10) + .hasSum(5) + .hasValuesSatisfying(value -> value.hasValue(200.0).hasQuantile(1.0)))); + } + + @Test + void convertGaugeHistogram() { + Map exemplarAttachments = new HashMap<>(); + // TODO - Import opencensus util for a code-dependent test on common exemplar-trace usage. + exemplarAttachments.put( + "SpanContext", + AttachmentValue.AttachmentValueString.create( + "SpanContext{traceId=TraceId{traceId=00000000000000000000000000000001}, spanId=SpanId{spanId=0000000000000002}, others=stuff}")); + Metric censusMetric = + Metric.createWithOneTimeSeries( + MetricDescriptor.create( + "name", + "description", + "unit", + MetricDescriptor.Type.GAUGE_DISTRIBUTION, + Collections.singletonList(LabelKey.create("key1", "desc1"))), + TimeSeries.create( + Collections.singletonList(LabelValue.create("value1")), + Collections.singletonList( + Point.create( + Value.distributionValue( + Distribution.create( + 10, + 5, + 2, // Sum of squared deviations, ignored + Distribution.BucketOptions.explicitOptions(Arrays.asList(2.0, 5.0)), + Arrays.asList( + Distribution.Bucket.create( + 2, + Exemplar.create( + 1.0, Timestamp.fromMillis(2), Collections.emptyMap())), + Distribution.Bucket.create( + 6, + Exemplar.create( + 4.0, Timestamp.fromMillis(1), exemplarAttachments)), + Distribution.Bucket.create(2)))), + Timestamp.fromMillis(2000))), + Timestamp.fromMillis(1000))); + assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) + .hasResource(RESOURCE) + .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) + .hasName("name") + .hasDescription("description") + .hasUnit("unit") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(2000000000) + .hasEpochNanos(2000000000) + .hasSum(5) + .hasCount(10) + .hasBucketBoundaries(2.0, 5.0) + .hasBucketCounts(2, 6, 2) + .hasExemplars( + ImmutableDoubleExemplarData.create( + Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), + ImmutableDoubleExemplarData.create( + Attributes.empty(), + 1000000, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 4.0)))); + } +} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java new file mode 100644 index 00000000000..cb2748bd2f2 --- /dev/null +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricProducerTest.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opencensus.contrib.exemplar.util.ExemplarUtils; +import io.opencensus.stats.Aggregation; +import io.opencensus.stats.BucketBoundaries; +import io.opencensus.stats.Measure; +import io.opencensus.stats.MeasureMap; +import io.opencensus.stats.Stats; +import io.opencensus.stats.StatsRecorder; +import io.opencensus.stats.View; +import io.opencensus.trace.SpanContext; +import io.opencensus.trace.SpanId; +import io.opencensus.trace.TraceId; +import io.opencensus.trace.TraceOptions; +import io.opencensus.trace.Tracestate; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.export.MetricProducer; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Random; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") // testing deprecated shim API +class OpenCensusMetricProducerTest { + private final MetricProducer openCensusMetrics = OpenCensusMetricProducer.create(); + + private static final Measure.MeasureLong LATENCY_MS = + Measure.MeasureLong.create("task_latency", "The task latency in milliseconds", "ms"); + // Latency in buckets: + // [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s] + private static final BucketBoundaries LATENCY_BOUNDARIES = + BucketBoundaries.create(Arrays.asList(0d, 100d, 200d, 400d, 1000d, 2000d, 4000d)); + private static final StatsRecorder STATS_RECORDER = Stats.getStatsRecorder(); + + // For Exemplar + private static final Random RANDOM = new Random(1234); + private static final TraceId TRACE_ID = TraceId.generateRandomId(RANDOM); + private static final SpanId SPAN_ID = SpanId.generateRandomId(RANDOM); + private static final SpanContext SPAN_CONTEXT = + SpanContext.create(TRACE_ID, SPAN_ID, TraceOptions.DEFAULT, Tracestate.builder().build()); + + @Test + void extractHistogram() throws InterruptedException { + View view = + View.create( + View.Name.create("task_latency_distribution"), + "The distribution of the task latencies.", + LATENCY_MS, + Aggregation.Distribution.create(LATENCY_BOUNDARIES), + Collections.emptyList()); + Stats.getViewManager().registerView(view); + + MeasureMap recorder = STATS_RECORDER.newMeasureMap(); + ExemplarUtils.putSpanContextAttachments(recorder, SPAN_CONTEXT); + recorder.put(LATENCY_MS, 50).record(); + // Wait for measurement to hit the aggregator. + + Awaitility.await() + .atMost(Duration.ofSeconds(10)) + .untilAsserted(() -> + assertThat(openCensusMetrics.produce(Resource.empty())) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("task_latency_distribution") + .hasDescription("The distribution of the task latencies.") + .hasUnit("ms") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasSum(50) + .hasCount(1) + .hasBucketCounts(1, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries(100d, 200d, 400d, 1000d, 2000d, 4000d) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasFilteredAttributes(Attributes.empty()) + .hasValue(50) + .hasTraceId(TRACE_ID.toLowerBase16()) + .hasSpanId(SPAN_ID.toLowerBase16())))))); + } +} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java new file mode 100644 index 00000000000..a41b4b92f6b --- /dev/null +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenCensusMetricsTest.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opencensus.stats.Aggregation; +import io.opencensus.stats.Measure; +import io.opencensus.stats.Stats; +import io.opencensus.stats.StatsRecorder; +import io.opencensus.stats.View; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.time.Duration; +import java.util.Collections; +import org.awaitility.Awaitility; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") // testing deprecated shim API +class OpenCensusMetricsTest { + private static final StatsRecorder STATS_RECORDER = Stats.getStatsRecorder(); + + @Test + void capturesOpenCensusAndOtelMetrics() throws InterruptedException { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider otelMetrics = + SdkMeterProvider.builder() + .registerMetricReader(reader) + .registerMetricProducer(OpenCensusMetricProducer.create()) + .build(); + // Record an otel metric. + otelMetrics.meterBuilder("otel").build().counterBuilder("otel.sum").build().add(1); + // Record an OpenCensus metric. + Measure.MeasureLong measure = Measure.MeasureLong.create("oc.measure", "oc.desc", "oc.unit"); + Stats.getViewManager() + .registerView( + View.create( + View.Name.create("oc.sum"), + "oc.desc", + measure, + Aggregation.Count.create(), + Collections.emptyList())); + STATS_RECORDER.newMeasureMap().put(measure, 1).record(); + + // Wait for OpenCensus propagation. + Awaitility.await() + .atMost(Duration.ofSeconds(5)) + .untilAsserted(() -> + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metric -> + assertThat(metric).hasName("otel.sum").hasLongSumSatisfying(sum -> {}), + metric -> + assertThat(metric).hasName("oc.sum").hasLongSumSatisfying(sum -> {}))); + } +} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryMetricExporterTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryMetricExporterTest.java deleted file mode 100644 index 19673e9e312..00000000000 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryMetricExporterTest.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableList; -import io.opencensus.common.Duration; -import io.opencensus.stats.Aggregation; -import io.opencensus.stats.Measure; -import io.opencensus.stats.Stats; -import io.opencensus.stats.StatsRecorder; -import io.opencensus.stats.View; -import io.opencensus.stats.ViewManager; -import io.opencensus.tags.TagContext; -import io.opencensus.tags.TagKey; -import io.opencensus.tags.TagMetadata; -import io.opencensus.tags.TagValue; -import io.opencensus.tags.Tagger; -import io.opencensus.tags.Tags; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporter; -import java.util.Comparator; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.Collectors; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; - -class OpenTelemetryMetricExporterTest { - - @Test - @SuppressWarnings({"deprecation", "unchecked"}) // Summary is deprecated in census - void testSupportedMetricsExportedCorrectly() throws Exception { - Tagger tagger = Tags.getTagger(); - Measure.MeasureLong latency = - Measure.MeasureLong.create("task_latency", "The task latency in milliseconds", "ms"); - Measure.MeasureDouble latency2 = - Measure.MeasureDouble.create("task_latency_2", "The task latency in milliseconds 2", "ms"); - StatsRecorder statsRecorder = Stats.getStatsRecorder(); - TagKey tagKey = TagKey.create("tagKey"); - TagValue tagValue = TagValue.create("tagValue"); - View longSumView = - View.create( - View.Name.create("long_sum"), - "long sum", - latency, - Aggregation.Sum.create(), - ImmutableList.of(tagKey)); - View longGaugeView = - View.create( - View.Name.create("long_gauge"), - "long gauge", - latency, - Aggregation.LastValue.create(), - ImmutableList.of(tagKey)); - View doubleSumView = - View.create( - View.Name.create("double_sum"), - "double sum", - latency2, - Aggregation.Sum.create(), - ImmutableList.of()); - View doubleGaugeView = - View.create( - View.Name.create("double_gauge"), - "double gauge", - latency2, - Aggregation.LastValue.create(), - ImmutableList.of()); - ViewManager viewManager = Stats.getViewManager(); - viewManager.registerView(longSumView); - viewManager.registerView(longGaugeView); - viewManager.registerView(doubleSumView); - viewManager.registerView(doubleGaugeView); - // Create OpenCensus -> OpenTelemetry Exporter bridge - InMemoryMetricExporter exporter = InMemoryMetricExporter.create(); - OpenTelemetryMetricsExporter otelExporter = - OpenTelemetryMetricsExporter.createAndRegister(exporter, Duration.create(1, 0)); - try { - TagContext tagContext = - tagger - .emptyBuilder() - .put(tagKey, tagValue, TagMetadata.create(TagMetadata.TagTtl.UNLIMITED_PROPAGATION)) - .build(); - try (io.opencensus.common.Scope ss = tagger.withTagContext(tagContext)) { - statsRecorder.newMeasureMap().put(latency, 50).record(); - statsRecorder.newMeasureMap().put(latency2, 60).record(); - } - Set allowedMetrics = new HashSet<>(); - allowedMetrics.add("double_gauge"); - allowedMetrics.add("double_sum"); - allowedMetrics.add("long_gauge"); - allowedMetrics.add("long_sum"); - // Slow down for OpenCensus to catch up. - Awaitility.await() - .atMost(java.time.Duration.ofSeconds(10)) - .untilAsserted( - () -> - assertThat( - exporter.getFinishedMetricItems().stream() - .filter(metric -> allowedMetrics.contains(metric.getName())) - .sorted(Comparator.comparing(MetricData::getName)) - .collect(Collectors.toList())) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("double_gauge") - .hasDescription("double gauge") - .hasUnit("ms") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(60) - .hasAttributes(Attributes.empty()))), - metric -> - assertThat(metric) - .hasName("double_sum") - .hasDescription("double sum") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(60) - .hasAttributes(Attributes.empty()))), - metric -> - assertThat(metric) - .hasName("long_gauge") - .hasDescription("long gauge") - .hasUnit("ms") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(50) - .hasAttributes( - attributeEntry( - tagKey.getName(), - tagValue.asString())))), - metric -> - assertThat(metric) - .hasName("long_sum") - .hasDescription("long sum") - .hasUnit("ms") - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(50) - .hasAttributes( - attributeEntry( - tagKey.getName(), - tagValue.asString())))))); - } finally { - otelExporter.stop(); - } - } -} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImplTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImplTest.java index 8f6d67e5e36..9a14ad5fc15 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImplTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryNoRecordEventsSpanImplTest.java @@ -38,6 +38,7 @@ import io.opencensus.trace.Tracestate; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import java.util.HashMap; import java.util.Map; import java.util.Random; @@ -93,6 +94,7 @@ public void doNotCrash() { noRecordEventsSpan.setAttribute("OTelAttributeKeyLong", 123); noRecordEventsSpan.setAttribute("OTelAttributeKeyDouble", 123.45); noRecordEventsSpan.setAttribute("OTelAttributeKeyBoolean", true); + noRecordEventsSpan.setAttribute("OTelAttributeKeyValue", Value.empty()); noRecordEventsSpan.addEvent("OTel event 1"); noRecordEventsSpan.addEvent("OTel event 2", 29922310, TimeUnit.HOURS); noRecordEventsSpan.addEvent( diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImplTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImplTest.java new file mode 100644 index 00000000000..e700d5b30f6 --- /dev/null +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetrySpanImplTest.java @@ -0,0 +1,95 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opencensusshim; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opencensus.trace.AttributeValue; +import io.opencensus.trace.Link; +import io.opencensus.trace.SpanId; +import io.opencensus.trace.Status; +import io.opencensus.trace.TraceId; +import io.opencensus.trace.TraceOptions; +import io.opencensus.trace.Tracestate; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import java.util.Collections; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class OpenTelemetrySpanImplTest { + + private static final String TRACE_ID = "0123456789abcdef0123456789abcdef"; + private static final String SPAN_ID = "fedcba9876543210"; + + @Mock private Span otelSpan; + + private OpenTelemetrySpanImpl shimSpan() { + when(otelSpan.getSpanContext()).thenReturn(SpanContext.getInvalid()); + return new OpenTelemetrySpanImpl(otelSpan); + } + + @Test + void setStatus_preservesDescription() { + shimSpan().setStatus(Status.UNKNOWN.withDescription("connection refused")); + + verify(otelSpan).setStatus(StatusCode.ERROR, "connection refused"); + } + + @Test + void setStatus_withoutDescription_setsCodeOnly() { + shimSpan().setStatus(Status.OK); + + verify(otelSpan).setStatus(StatusCode.OK); + verify(otelSpan, never()).setStatus(any(StatusCode.class), anyString()); + } + + @Test + void addLink_delegatesToOtelSpan() { + shimSpan().addLink(Link.fromSpanContext(ocSpanContext(), Link.Type.CHILD_LINKED_SPAN)); + + verify(otelSpan).addLink(expectedOtelSpanContext(), Attributes.empty()); + } + + @Test + void addLink_mapsAttributes() { + shimSpan() + .addLink( + Link.fromSpanContext( + ocSpanContext(), + Link.Type.PARENT_LINKED_SPAN, + Collections.singletonMap("key", AttributeValue.stringAttributeValue("value")))); + + verify(otelSpan).addLink(expectedOtelSpanContext(), Attributes.of(stringKey("key"), "value")); + } + + private static io.opencensus.trace.SpanContext ocSpanContext() { + return io.opencensus.trace.SpanContext.create( + TraceId.fromLowerBase16(TRACE_ID), + SpanId.fromLowerBase16(SPAN_ID), + TraceOptions.DEFAULT, + Tracestate.builder().build()); + } + + private static SpanContext expectedOtelSpanContext() { + return SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()); + } +} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImplTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImplTest.java index 4416d23d1a2..0cfd0f4ef21 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImplTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/OpenTelemetryTextFormatImplTest.java @@ -132,4 +132,22 @@ void testInjectAndExtractWithW3c() { SpanContext extractedSpanContext = textFormatImpl.extract(carrier, GETTER); assertThat(extractedSpanContext).isEqualTo(SPAN_CONTEXT); } + + @Test + void testExtractWithW3cDropsMultiTenantTracestateKeys() { + OpenTelemetryTextFormatImpl textFormatImpl = + new OpenTelemetryTextFormatImpl(W3CTraceContextPropagator.getInstance()); + Map carrier = new LinkedHashMap<>(); + carrier.put("traceparent", "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"); + carrier.put("tracestate", "fw529a3039@dt=fw4,congo=t61rcWkgMzE"); + + SpanContext extractedSpanContext = textFormatImpl.extract(carrier, GETTER); + + assertThat(extractedSpanContext.getTraceId().toLowerBase16()) + .isEqualTo("0af7651916cd43dd8448eb211c80319c"); + assertThat(extractedSpanContext.getSpanId().toLowerBase16()).isEqualTo("b7ad6b7169203331"); + assertThat(extractedSpanContext.getTraceOptions().isSampled()).isTrue(); + assertThat(extractedSpanContext.getTracestate().getEntries()).hasSize(1); + assertThat(extractedSpanContext.getTracestate().get("congo")).isEqualTo("t61rcWkgMzE"); + } } diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/SpanConverterTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/SpanConverterTest.java index d49cab98270..1682e3cabd3 100644 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/SpanConverterTest.java +++ b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/SpanConverterTest.java @@ -9,6 +9,7 @@ import static org.mockito.Mockito.when; import io.opencensus.trace.SpanContext; +import io.opencensus.trace.Tracestate; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; @@ -44,4 +45,30 @@ void testFromOtelSpan() { assertThat(context.getTracestate().getEntries().size()).isEqualTo(1); assertThat(context.getTracestate().get(traceStateKey)).isEqualTo(traceStateValue); } + + @Test + void testFromOtelSpanDropsMultiTenantTracestateKeys() { + String traceIdHex = RANDOM_IDS_GENERATOR.generateTraceId(); + String spanIdHex = RANDOM_IDS_GENERATOR.generateSpanId(); + + Span otelSpan = Mockito.mock(Span.class); + when(otelSpan.getSpanContext()) + .thenReturn( + io.opentelemetry.api.trace.SpanContext.create( + traceIdHex, + spanIdHex, + TraceFlags.getSampled(), + TraceState.builder() + .put("congo", "t61rcWkgMzE") + // W3C multi-tenant key, valid in OpenTelemetry but rejected by OpenCensus + .put("fw529a3039@dt", "fw4") + .build())); + + io.opencensus.trace.Span ocSpan = SpanConverter.fromOtelSpan(otelSpan); + + Tracestate tracestate = ocSpan.getContext().getTracestate(); + assertThat(tracestate.getEntries()).hasSize(1); + assertThat(tracestate.get("congo")).isEqualTo("t61rcWkgMzE"); + assertThat(tracestate.get("fw529a3039@dt")).isNull(); + } } diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/internal/metrics/MetricAdapterTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/internal/metrics/MetricAdapterTest.java deleted file mode 100644 index 07d7c3b462f..00000000000 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/internal/metrics/MetricAdapterTest.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.internal.metrics; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.opencensus.common.Timestamp; -import io.opencensus.metrics.LabelKey; -import io.opencensus.metrics.LabelValue; -import io.opencensus.metrics.data.AttachmentValue; -import io.opencensus.metrics.data.Exemplar; -import io.opencensus.metrics.export.Distribution; -import io.opencensus.metrics.export.Metric; -import io.opencensus.metrics.export.MetricDescriptor; -import io.opencensus.metrics.export.Point; -import io.opencensus.metrics.export.Summary; -import io.opencensus.metrics.export.TimeSeries; -import io.opencensus.metrics.export.Value; -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Test; - -class MetricAdapterTest { - - private static final Resource RESOURCE = - Resource.create(Attributes.of(AttributeKey.stringKey("test"), "resource")); - - @Test - void convertsTimeStamps() { - assertThat(MetricAdapter.mapTimestamp(Timestamp.create(1, 2))).isEqualTo(1000000002L); - } - - @Test - void convertsLongValue() { - assertThat(MetricAdapter.longValue(Point.create(Value.longValue(5), Timestamp.fromMillis(2)))) - .isEqualTo(5); - } - - @Test - void convertsDoubleValue() { - assertThat( - MetricAdapter.doubleValue(Point.create(Value.doubleValue(5), Timestamp.fromMillis(2)))) - .isEqualTo(5); - } - - @Test - void convertsLongGauge() { - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.GAUGE_INT64, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create(Value.longValue(4), Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(4) - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")))); - } - - @Test - void convertsDoubleGauge() { - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.GAUGE_DOUBLE, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create(Value.doubleValue(4), Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasValue(4))); - } - - @Test - void convertsLongSum() { - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.CUMULATIVE_INT64, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create(Value.longValue(4), Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasValue(4))); - } - - @Test - void convertsDoubleSum() { - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.CUMULATIVE_DOUBLE, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create(Value.doubleValue(4), Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasValue(4))); - } - - @Test - void convertHistogram() { - Map exemplarAttachements = new HashMap<>(); - // TODO - Import opencensus util for a code-dependent test on common exemplar-trace usage. - exemplarAttachements.put( - "SpanContext", - AttachmentValue.AttachmentValueString.create( - "SpanContext{traceId=TraceId{traceId=00000000000000000000000000000001}, spanId=SpanId{spanId=0000000000000002}, others=stuff}")); - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.CUMULATIVE_DISTRIBUTION, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create( - Value.distributionValue( - Distribution.create( - 10, - 5, - 2, // Sum of squared deviations, ignored - Distribution.BucketOptions.explicitOptions(Arrays.asList(2.0, 5.0)), - Arrays.asList( - Distribution.Bucket.create( - 2, - Exemplar.create( - 1.0, Timestamp.fromMillis(2), Collections.emptyMap())), - Distribution.Bucket.create( - 6, - Exemplar.create( - 4.0, Timestamp.fromMillis(1), exemplarAttachements)), - Distribution.Bucket.create(2)))), - Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasSum(5) - .hasCount(10) - .hasBucketBoundaries(2.0, 5.0) - .hasBucketCounts(2, 6, 2) - .hasExemplars( - ImmutableDoubleExemplarData.create( - Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), - ImmutableDoubleExemplarData.create( - Attributes.empty(), - 1000000, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 4.0)))); - } - - @Test - void convertSummary() { - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.SUMMARY, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create( - Value.summaryValue( - Summary.create( - 10L, - 5d, - Summary.Snapshot.create( - 10L, - 5d, - Collections.singletonList( - Summary.Snapshot.ValueAtPercentile.create(100.0, 200))))), - Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(1000000000) - .hasEpochNanos(2000000000) - .hasAttributes(attributeEntry("key1", "value1")) - .hasCount(10) - .hasSum(5) - .hasValuesSatisfying(value -> value.hasValue(200.0).hasQuantile(1.0)))); - } - - @Test - void convertGaugeHistogram() { - Map exemplarAttachements = new HashMap<>(); - // TODO - Import opencensus util for a code-dependent test on common exemplar-trace usage. - exemplarAttachements.put( - "SpanContext", - AttachmentValue.AttachmentValueString.create( - "SpanContext{traceId=TraceId{traceId=00000000000000000000000000000001}, spanId=SpanId{spanId=0000000000000002}, others=stuff}")); - Metric censusMetric = - Metric.createWithOneTimeSeries( - MetricDescriptor.create( - "name", - "description", - "unit", - MetricDescriptor.Type.GAUGE_DISTRIBUTION, - Collections.singletonList(LabelKey.create("key1", "desc1"))), - TimeSeries.create( - Collections.singletonList(LabelValue.create("value1")), - Collections.singletonList( - Point.create( - Value.distributionValue( - Distribution.create( - 10, - 5, - 2, // Sum of squared deviations, ignored - Distribution.BucketOptions.explicitOptions(Arrays.asList(2.0, 5.0)), - Arrays.asList( - Distribution.Bucket.create( - 2, - Exemplar.create( - 1.0, Timestamp.fromMillis(2), Collections.emptyMap())), - Distribution.Bucket.create( - 6, - Exemplar.create( - 4.0, Timestamp.fromMillis(1), exemplarAttachements)), - Distribution.Bucket.create(2)))), - Timestamp.fromMillis(2000))), - Timestamp.fromMillis(1000))); - assertThat(MetricAdapter.convert(RESOURCE, censusMetric)) - .hasResource(RESOURCE) - .hasInstrumentationScope(MetricAdapter.INSTRUMENTATION_SCOPE_INFO) - .hasName("name") - .hasDescription("description") - .hasUnit("unit") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(2000000000) - .hasEpochNanos(2000000000) - .hasSum(5) - .hasCount(10) - .hasBucketBoundaries(2.0, 5.0) - .hasBucketCounts(2, 6, 2) - .hasExemplars( - ImmutableDoubleExemplarData.create( - Attributes.empty(), 2000000, SpanContext.getInvalid(), 1.0), - ImmutableDoubleExemplarData.create( - Attributes.empty(), - 1000000, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 4.0)))); - } -} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricProducerTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricProducerTest.java deleted file mode 100644 index 1e9f756ca47..00000000000 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricProducerTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.metrics; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opencensus.contrib.exemplar.util.ExemplarUtils; -import io.opencensus.stats.Aggregation; -import io.opencensus.stats.BucketBoundaries; -import io.opencensus.stats.Measure; -import io.opencensus.stats.MeasureMap; -import io.opencensus.stats.Stats; -import io.opencensus.stats.StatsRecorder; -import io.opencensus.stats.View; -import io.opencensus.trace.SpanContext; -import io.opencensus.trace.SpanId; -import io.opencensus.trace.TraceId; -import io.opencensus.trace.TraceOptions; -import io.opencensus.trace.Tracestate; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.Random; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; - -class OpenCensusMetricProducerTest { - private final MetricProducer openCensusMetrics = - OpenCensusMetricProducer.create(Resource.empty()); - - private static final Measure.MeasureLong LATENCY_MS = - Measure.MeasureLong.create("task_latency", "The task latency in milliseconds", "ms"); - // Latency in buckets: - // [>=0ms, >=100ms, >=200ms, >=400ms, >=1s, >=2s, >=4s] - private static final BucketBoundaries LATENCY_BOUNDARIES = - BucketBoundaries.create(Arrays.asList(0d, 100d, 200d, 400d, 1000d, 2000d, 4000d)); - private static final StatsRecorder STATS_RECORDER = Stats.getStatsRecorder(); - - // For Exemplar - private static final Random RANDOM = new Random(1234); - private static final TraceId TRACE_ID = TraceId.generateRandomId(RANDOM); - private static final SpanId SPAN_ID = SpanId.generateRandomId(RANDOM); - private static final SpanContext SPAN_CONTEXT = - SpanContext.create(TRACE_ID, SPAN_ID, TraceOptions.DEFAULT, Tracestate.builder().build()); - - @Test - void extractHistogram() throws InterruptedException { - View view = - View.create( - View.Name.create("task_latency_distribution"), - "The distribution of the task latencies.", - LATENCY_MS, - Aggregation.Distribution.create(LATENCY_BOUNDARIES), - Collections.emptyList()); - Stats.getViewManager().registerView(view); - - MeasureMap recorder = STATS_RECORDER.newMeasureMap(); - ExemplarUtils.putSpanContextAttachments(recorder, SPAN_CONTEXT); - recorder.put(LATENCY_MS, 50).record(); - // Wait for measurement to hit the aggregator. - - Awaitility.await() - .atMost(Duration.ofSeconds(10)) - .untilAsserted( - () -> - assertThat(openCensusMetrics.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("task_latency_distribution") - .hasDescription("The distribution of the task latencies.") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasSum(50) - .hasCount(1) - .hasBucketCounts(1, 0, 0, 0, 0, 0, 0) - .hasBucketBoundaries( - 100d, 200d, 400d, 1000d, 2000d, 4000d) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasFilteredAttributes( - Attributes.empty()) - .hasValue(50) - .hasTraceId( - TRACE_ID.toLowerBase16()) - .hasSpanId( - SPAN_ID - .toLowerBase16())))))); - } -} diff --git a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricsTest.java b/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricsTest.java deleted file mode 100644 index 661054ecc1b..00000000000 --- a/opencensus-shim/src/test/java/io/opentelemetry/opencensusshim/metrics/OpenCensusMetricsTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opencensusshim.metrics; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opencensus.stats.Aggregation; -import io.opencensus.stats.Measure; -import io.opencensus.stats.Stats; -import io.opencensus.stats.StatsRecorder; -import io.opencensus.stats.View; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import java.time.Duration; -import java.util.Collections; -import org.awaitility.Awaitility; -import org.junit.jupiter.api.Test; - -class OpenCensusMetricsTest { - private static final StatsRecorder STATS_RECORDER = Stats.getStatsRecorder(); - - @Test - void capturesOpenCensusAndOtelMetrics() throws InterruptedException { - InMemoryMetricReader reader = InMemoryMetricReader.create(); - SdkMeterProvider otelMetrics = - SdkMeterProvider.builder().registerMetricReader(OpenCensusMetrics.attachTo(reader)).build(); - // Record an otel metric. - otelMetrics.meterBuilder("otel").build().counterBuilder("otel.sum").build().add(1); - // Record an OpenCensus metric. - Measure.MeasureLong measure = Measure.MeasureLong.create("oc.measure", "oc.desc", "oc.unit"); - Stats.getViewManager() - .registerView( - View.create( - View.Name.create("oc.sum"), - "oc.desc", - measure, - Aggregation.Count.create(), - Collections.emptyList())); - STATS_RECORDER.newMeasureMap().put(measure, 1).record(); - - // Wait for OpenCensus propagation. - Awaitility.await() - .atMost(Duration.ofSeconds(5)) - .untilAsserted( - () -> - assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric).hasName("otel.sum").hasLongSumSatisfying(sum -> {}), - metric -> - assertThat(metric).hasName("oc.sum").hasLongSumSatisfying(sum -> {}))); - } -} diff --git a/opentelemetry-jfr-profiles-shim/build.gradle.kts b/opentelemetry-jfr-profiles-shim/build.gradle.kts new file mode 100644 index 00000000000..34967f14171 --- /dev/null +++ b/opentelemetry-jfr-profiles-shim/build.gradle.kts @@ -0,0 +1,30 @@ +plugins { + id("otel.java-conventions") + // TODO decide what to do about JfrExportExample before publishing. + // unlike the other classes here it's an example, not a reusable utility. + // id("otel.publish-conventions") +} + +description = "OpenTelemetry - JFR to Profiles data conversion example" +otelJava.moduleName.set("io.opentelemetry.jfr.profiles.shim") +otelJava.requireSuppressWarningsExplanation.set(false) + +tasks { + // this module uses the jdk.jfr.consumer API, which was backported into 1.8 but is '@since 9' + // and therefore a bit of a pain to get gradle to compile against... + compileJava { + sourceCompatibility = "1.8" + targetCompatibility = "1.8" + options.release.set(null as Int?) + } + compileTestJava { + sourceCompatibility = "1.8" + targetCompatibility = "1.8" + options.release.set(null as Int?) + } +} + +dependencies { + api(project(":exporters:otlp:profiles")) + api(project(":sdk:profiles")) +} diff --git a/extensions/incubator/gradle.properties b/opentelemetry-jfr-profiles-shim/gradle.properties similarity index 100% rename from extensions/incubator/gradle.properties rename to opentelemetry-jfr-profiles-shim/gradle.properties diff --git a/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrExecutionSampleEventConverter.java b/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrExecutionSampleEventConverter.java new file mode 100644 index 00000000000..3d14c76399d --- /dev/null +++ b/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrExecutionSampleEventConverter.java @@ -0,0 +1,109 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.jfr; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.sdk.profiles.ProfilesDictionaryCompositor; +import io.opentelemetry.sdk.profiles.SampleCompositionBuilder; +import io.opentelemetry.sdk.profiles.SampleCompositionKey; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import io.opentelemetry.sdk.profiles.data.SampleData; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.TimeUnit; +import jdk.jfr.consumer.RecordedEvent; +import jdk.jfr.consumer.RecordedThread; + +/** + * Converter for batching a stream of recorded jfr.ExecutionSample events into a format suitable for + * consumption in a ProfileData i.e. for OTLP export. Similar converters, or a more generalized + * converter, are needed for each JFR event type. + */ +public class JfrExecutionSampleEventConverter { + + private JfrExecutionSampleEventConverter() {} + + /** + * Returns a new converter, initialized with an empty dictionary. + * + * @return a new JfrExecutionSampleEventConverter. + */ + public static JfrExecutionSampleEventConverter create() { + return new JfrExecutionSampleEventConverter(); + } + + /* + * The profiles signal encoding uses dictionary lookup tables to save space by deduplicating + * repeated object occurrences. The dictionary compositor is used to assemble these tables. + */ + private final ProfilesDictionaryCompositor profilesDictionaryCompositor = + new ProfilesDictionaryCompositor(); + + /* + * stack frames are dictionary encoded in multiple steps. + * first, frames are converted to Locations, each of which is placed in the dictionary. + * Then the stack as a whole is represented as an array of those Locations, + * and the Stack message itself is also placed in the dictionary. + * This assembly is handled by a JfrLocationDataCompositor wrapping the dictionary + */ + private final JfrLocationDataCompositor locationCompositor = + JfrLocationDataCompositor.create(profilesDictionaryCompositor); + + /* + * Samples are occurrences of the same observation, with an optional value and timestamp. + * In JFR, for each given event type, a SampleCompositionBuilder is used to split the + * events (observations) by key (stack+metadata) and record the timestamps. + * If processing multiple event types, a Map would be used. + */ + private final SampleCompositionBuilder sampleCompositionBuilder = new SampleCompositionBuilder(); + + /** + * Convert and add a JFR event, if of appropriate type. + * + * @param recordedEvent the event to process. + */ + public void accept(RecordedEvent recordedEvent) { + if (!"jdk.ExecutionSample".equals(recordedEvent.getEventType().getName())) { + return; + } + + RecordedThread recordedThread = recordedEvent.getValue("sampledThread"); + if (recordedThread == null) { + // just skip these - it would be spec valid, but practically without Thread metadata + // the receiving backend likely won't group and render properly them anyhow. + return; + } + + String threadName = recordedThread.getJavaName(); + int threadNameIndex = profilesDictionaryCompositor.putIfAbsent("thread.name"); + KeyValueAndUnitData threadNameData = + KeyValueAndUnitData.create(threadNameIndex, Value.of(threadName), 0); + int attribIndex = profilesDictionaryCompositor.putIfAbsent(threadNameData); + int stackIndex = locationCompositor.putIfAbsent(recordedEvent.getStackTrace().getFrames()); + SampleCompositionKey key = new SampleCompositionKey(stackIndex, List.of(attribIndex), 0); + Instant instant = recordedEvent.getStartTime(); + long epochNanos = TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano(); + sampleCompositionBuilder.add(key, null, epochNanos); + } + + /** + * Gets the underlying dictionary storage. + * + * @return the ProfilesDictionaryCompositor used by this converter. + */ + public ProfilesDictionaryCompositor getProfilesDictionaryCompositor() { + return profilesDictionaryCompositor; + } + + /** + * Gets the samples assembled from the accepted events. + * + * @return the data samples. + */ + public List getSamples() { + return sampleCompositionBuilder.build(); + } +} diff --git a/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrExportExample.java b/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrExportExample.java new file mode 100644 index 00000000000..9407749424d --- /dev/null +++ b/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrExportExample.java @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.jfr; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.exporter.otlp.profiles.OtlpGrpcProfileExporter; +import io.opentelemetry.exporter.otlp.profiles.OtlpGrpcProfilesExporterBuilder; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.profiles.ProfileExporter; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import io.opentelemetry.sdk.profiles.data.ValueTypeData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import jdk.jfr.consumer.RecordingFile; + +/** + * Simple example of how to wire up the profiles signal OTLP exporter to convert and send the + * content of a JFR recording file. This is not a supported CLI and is not intended to be + * configurable by e.g. command line flags. + */ +public class JfrExportExample { + + private JfrExportExample() {} + + @SuppressWarnings("SystemOut") + public static void main(String[] args) throws IOException { + + Path jfrFilePath = Path.of("/tmp/demo.jfr"); // TODO set the JFR file location here + ProfileData profileData = convertJfrFile(jfrFilePath); + + // for test purposes https://github.com/elastic/devfiler/ provides a handy standalone backend. + // by default devfiler listens on port 11000 + String destination = "127.0.0.1:11000"; // TODO set the location of the backend receiver here + + OtlpGrpcProfilesExporterBuilder exporterBuilder = OtlpGrpcProfileExporter.builder(); + exporterBuilder.setEndpoint("http://" + destination); + ProfileExporter exporter = exporterBuilder.build(); + + CompletableResultCode completableResultCode = exporter.export(List.of(profileData)); + completableResultCode.join(1, TimeUnit.MINUTES); + System.out.println(completableResultCode.isSuccess() ? "success" : "failure"); + } + + /** + * Read the content of the JFR recording file and convert it to a ProfileData object in + * preparation for OTLP export. + * + * @param jfrFilePath the data source. + * @return a ProfileData object constructed from the JFR recording. + * @throws IOException if the conversion fails. + */ + public static ProfileData convertJfrFile(Path jfrFilePath) throws IOException { + + JfrExecutionSampleEventConverter converter = JfrExecutionSampleEventConverter.create(); + + RecordingFile recordingFile = new RecordingFile(jfrFilePath); + while (recordingFile.hasMoreEvents()) { + converter.accept(recordingFile.readEvent()); + } + recordingFile.close(); + + String profileId = "0123456789abcdef0123456789abcdef"; + InstrumentationScopeInfo scopeInfo = + InstrumentationScopeInfo.builder("testLib") + .setVersion("1.0") + .setSchemaUrl("http://url") + .build(); + + int sampleStringIndex = converter.getProfilesDictionaryCompositor().putIfAbsent("samples"); + int countStringIndex = converter.getProfilesDictionaryCompositor().putIfAbsent("count"); + + return ProfileData.create( + Resource.create(Attributes.empty()), + scopeInfo, + converter.getProfilesDictionaryCompositor().getProfileDictionaryData(), + ValueTypeData.create(sampleStringIndex, countStringIndex), + converter.getSamples(), + 0, + 0, + ValueTypeData.create(0, 0), + 0, + profileId, + 0, + "jfr", + ByteBuffer.wrap(Files.readAllBytes(jfrFilePath)), + Collections.emptyList()); + } +} diff --git a/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrLocationDataCompositor.java b/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrLocationDataCompositor.java new file mode 100644 index 00000000000..9c4a0840d93 --- /dev/null +++ b/opentelemetry-jfr-profiles-shim/src/main/java/io/opentelemetry/sdk/profiles/jfr/JfrLocationDataCompositor.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.jfr; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.sdk.profiles.ProfilesDictionaryCompositor; +import io.opentelemetry.sdk.profiles.data.FunctionData; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import io.opentelemetry.sdk.profiles.data.LineData; +import io.opentelemetry.sdk.profiles.data.LocationData; +import io.opentelemetry.sdk.profiles.data.StackData; +import java.util.List; +import jdk.jfr.consumer.RecordedFrame; + +/** + * Allows for the conversion and storage of JFR thread stacks in the dictionary encoding structure + * used by OTLP profile signal exporters. + * + *

    The compositor resembles a builder, though without the fluent API. Instead, mutation methods + * return the index of the offered element, this information being required to construct any element + * that references into the tables. + * + *

    This class is not threadsafe and must be externally synchronized. + */ +public class JfrLocationDataCompositor { + + private final ProfilesDictionaryCompositor profilesDictionaryCompositor; + + /** + * Returns a new JFR Compositor, using the offered Dictionary for storage. + * + * @param profilesDictionaryCompositor the underlying dictionary state store. + * @return a new JfrLocationDataCompositor. + */ + public static JfrLocationDataCompositor create( + ProfilesDictionaryCompositor profilesDictionaryCompositor) { + return new JfrLocationDataCompositor(profilesDictionaryCompositor); + } + + /** + * Wrap the given dictionary with additional JFR-specific stack data handling functionality. + * + * @param profilesDictionaryCompositor the underlying storage. + */ + private JfrLocationDataCompositor(ProfilesDictionaryCompositor profilesDictionaryCompositor) { + this.profilesDictionaryCompositor = profilesDictionaryCompositor; + } + + /** + * Stores the provided list of frames as a StackData element in the dictionary if an equivalent is + * not already present, and returns its index. + * + * @param frameList the JFR stack data. + * @return the index of the added or existing StackData element. + */ + public int putIfAbsent(List frameList) { + + List locationIndices = frameList.stream().map(this::frameToLocation).toList(); + + StackData stackData = StackData.create(locationIndices); + int stackIndex = profilesDictionaryCompositor.putIfAbsent(stackData); + return stackIndex; + } + + /** + * Convert a single frame of a stack to a LocationData, store it and its components in the + * dictionary and return its index. + * + * @param frame the source data + * @return the LocationData storage index in the dictionary + */ + protected int frameToLocation(RecordedFrame frame) { + + // the LocationData references several components which need creating and placing in their + // respective dictionary tables + + String name = nameFrom(frame); + int nameStringIndex = profilesDictionaryCompositor.putIfAbsent(name); + + FunctionData functionData = FunctionData.create(nameStringIndex, 0, 0, 0); + int functionIndex = profilesDictionaryCompositor.putIfAbsent(functionData); + + int lineNumber = frame.getLineNumber() != -1 ? frame.getLineNumber() : 0; + LineData lineData = LineData.create(functionIndex, lineNumber, 0); + + // https://opentelemetry.io/docs/specs/semconv/general/profiles/#frame-types + int typeKeyIndex = profilesDictionaryCompositor.putIfAbsent("profile.frame.type"); + KeyValueAndUnitData frameType = KeyValueAndUnitData.create(typeKeyIndex, Value.of("jvm"), 0); + int typeAttributeIndex = profilesDictionaryCompositor.putIfAbsent(frameType); + + LocationData locationData = + LocationData.create(0, 0, List.of(lineData), List.of(typeAttributeIndex)); + + int locationIndex = profilesDictionaryCompositor.putIfAbsent(locationData); + return locationIndex; + } + + /** + * Construct a name String from the frame. Note that the wire spec and semantic conventions don't + * define a specific string format. Override this method to customize the conversion. + * + * @param frame the JFR frame data. + * @return the name as a String. + */ + protected String nameFrom(RecordedFrame frame) { + String name = frame.getMethod().getType() != null ? frame.getMethod().getType().getName() : ""; + name += "."; + name += frame.getMethod().getName() != null ? frame.getMethod().getName() : ""; + return name; + } +} diff --git a/opentracing-shim/README.md b/opentracing-shim/README.md index 5afab793674..7404e305f2e 100644 --- a/opentracing-shim/README.md +++ b/opentracing-shim/README.md @@ -1,6 +1,9 @@ # OpenTelemetry - OpenTracing Shim -[![Javadocs][javadoc-image]][javadoc-url] +> [!WARNING] +> OpenTracing is deprecated, and this shim is deprecated accordingly. It remains available for +> legacy compatibility, but users should migrate to the OpenTelemetry API directly. See the +> [OpenTelemetry specification guidance on OpenTracing compatibility](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/opentracing.md#opentracing-compatibility). The OpenTracing shim is a bridge layer from OpenTelemetry to the OpenTracing API. It takes OpenTelemetry Tracer and exposes it as an implementation of an OpenTracing Tracer. @@ -8,19 +11,16 @@ It takes OpenTelemetry Tracer and exposes it as an implementation of an OpenTrac ## Usage There are 2 ways to expose an OpenTracing tracer: -1. From the global OpenTelemetry configuration: - ```java - Tracer tracer = OpenTracingShim.createTracerShim(); - ``` 1. From a provided `OpenTelemetry` instance: ```java Tracer tracer = OpenTracingShim.createTracerShim(openTelemetry); ``` +2. From a specific `TracerProvider`, text map propagator (`TextMapPropagator`), and http propagator (`TextMapPropagator`): + ```java + Tracer tracer = OpenTracingShim.createTracerShim(tracerProvider, textMapPropagator, httpPropagator); + ``` Optionally register the tracer as the OpenTracing GlobalTracer: ```java GlobalTracer.registerIfAbsent(tracer); ``` - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-opentracing-shim.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-opentracing-shim diff --git a/opentracing-shim/build.gradle.kts b/opentracing-shim/build.gradle.kts index 9947bc7f5c5..fba755833c2 100644 --- a/opentracing-shim/build.gradle.kts +++ b/opentracing-shim/build.gradle.kts @@ -1,16 +1,22 @@ +import io.opentelemetry.gradle.OtelVersionClassPlugin + plugins { id("otel.java-conventions") id("otel.publish-conventions") } +apply() description = "OpenTelemetry OpenTracing Bridge" otelJava.moduleName.set("io.opentelemetry.opentracingshim") +otelJava.requireSuppressWarningsExplanation.set(false) dependencies { api(project(":api:all")) api("io.opentracing:opentracing-api") - implementation(project(":semconv")) + implementation("io.opentracing:opentracing-noop:0.33.0") + + annotationProcessor("com.google.auto.value:auto-value") testImplementation(project(":sdk:testing")) } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/BaseShimObject.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/BaseShimObject.java deleted file mode 100644 index 3a5f3cce49e..00000000000 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/BaseShimObject.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opentracingshim; - -import io.opentelemetry.api.trace.Tracer; - -abstract class BaseShimObject { - - final TelemetryInfo telemetryInfo; - - BaseShimObject(TelemetryInfo telemetryInfo) { - this.telemetryInfo = telemetryInfo; - } - - TelemetryInfo telemetryInfo() { - return telemetryInfo; - } - - Tracer tracer() { - return telemetryInfo.tracer(); - } - - SpanContextShimTable spanContextTable() { - return telemetryInfo.spanContextTable(); - } - - OpenTracingPropagators propagators() { - return telemetryInfo.propagators(); - } -} diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/NoopSpanBuilderShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/NoopSpanBuilderShim.java index 07d8d3fdc01..c06458ce427 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/NoopSpanBuilderShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/NoopSpanBuilderShim.java @@ -12,15 +12,14 @@ import io.opentracing.Tracer.SpanBuilder; import io.opentracing.tag.Tag; -final class NoopSpanBuilderShim extends BaseShimObject implements SpanBuilder { +final class NoopSpanBuilderShim implements SpanBuilder { private static final Tracer TRACER = TracerProvider.noop().get("io.opentelemetry.opentracingshim"); private final String spanName; - public NoopSpanBuilderShim(TelemetryInfo telemetryInfo, String spanName) { - super(telemetryInfo); + NoopSpanBuilderShim(String spanName) { this.spanName = spanName == null ? "" : spanName; // OT is more permissive than OTel. } @@ -71,6 +70,6 @@ public SpanBuilder withStartTimestamp(long microseconds) { @Override public Span start() { - return new SpanShim(telemetryInfo, TRACER.spanBuilder(spanName).startSpan()); + return new SpanShim(TRACER.spanBuilder(spanName).startSpan()); } } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingPropagators.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingPropagators.java deleted file mode 100644 index 1c2fc3ec5c8..00000000000 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingPropagators.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opentracingshim; - -import io.opentelemetry.context.propagation.TextMapPropagator; - -/** - * Container for {@link io.opentracing.propagation.Format.Builtin#TEXT_MAP} and {@link - * io.opentracing.propagation.Format.Builtin#HTTP_HEADERS} format propagators. - * - * @since 1.1.0 - */ -public class OpenTracingPropagators { - private final TextMapPropagator textMapPropagator; - private final TextMapPropagator httpHeadersPropagator; - - OpenTracingPropagators( - TextMapPropagator textMapPropagator, TextMapPropagator httpHeadersPropagator) { - this.textMapPropagator = textMapPropagator; - this.httpHeadersPropagator = httpHeadersPropagator; - } - - /** - * Returns a new builder instance for {@link OpenTracingPropagators}. - * - * @return a new builder instance for {@link OpenTracingPropagators}. - */ - public static OpenTracingPropagatorsBuilder builder() { - return new OpenTracingPropagatorsBuilder(); - } - - /** - * Returns the propagator for {@link io.opentracing.propagation.Format.Builtin#TEXT_MAP} format. - * - * @return the propagator for {@link io.opentracing.propagation.Format.Builtin#TEXT_MAP} format. - */ - public TextMapPropagator textMapPropagator() { - return textMapPropagator; - } - - /** - * Returns the propagator for {@link io.opentracing.propagation.Format.Builtin#HTTP_HEADERS} - * format. - * - * @return the propagator for {@link io.opentracing.propagation.Format.Builtin#HTTP_HEADERS} - * format. - */ - public TextMapPropagator httpHeadersPropagator() { - return httpHeadersPropagator; - } -} diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingPropagatorsBuilder.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingPropagatorsBuilder.java deleted file mode 100644 index 06ceabe3715..00000000000 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingPropagatorsBuilder.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opentracingshim; - -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.context.propagation.TextMapPropagator; -import java.util.Objects; - -/** Builder for {@link OpenTracingPropagators}. */ -public class OpenTracingPropagatorsBuilder { - - private TextMapPropagator textMapPropagator = - GlobalOpenTelemetry.getPropagators().getTextMapPropagator(); - private TextMapPropagator httpHeadersPropagator = - GlobalOpenTelemetry.getPropagators().getTextMapPropagator(); - - /** Set propagator for {@link io.opentracing.propagation.Format.Builtin#TEXT_MAP} format. */ - public OpenTracingPropagatorsBuilder setTextMap(TextMapPropagator textMapPropagator) { - Objects.requireNonNull(textMapPropagator, "textMapPropagator"); - this.textMapPropagator = textMapPropagator; - return this; - } - - /** Set propagator for {@link io.opentracing.propagation.Format.Builtin#HTTP_HEADERS} format. */ - public OpenTracingPropagatorsBuilder setHttpHeaders(TextMapPropagator httpHeadersPropagator) { - Objects.requireNonNull(httpHeadersPropagator, "httpHeadersPropagator"); - this.httpHeadersPropagator = httpHeadersPropagator; - return this; - } - - /** - * Constructs a new instance of the {@link OpenTracingPropagators} based on the builder's values. - * If propagators are not set then {@code GlobalOpenTelemetry.getPropagators()} is used. - * - * @return a new Propagators instance. - */ - public OpenTracingPropagators build() { - return new OpenTracingPropagators(textMapPropagator, httpHeadersPropagator); - } -} diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingShim.java index db8152aa1d3..df7b846f62c 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/OpenTracingShim.java @@ -5,66 +5,56 @@ package io.opentelemetry.opentracingshim; -import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; -import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentracing.Tracer; /** * Factory for creating an OpenTracing {@link io.opentracing.Tracer} that is implemented using the * OpenTelemetry APIs. + * + * @since 1.26.0 + * @deprecated OpenTracing is deprecated in the OpenTelemetry specification. This shim is deprecated + * accordingly and is expected to stop being published sometime in 2027 per spec guidance. + * Prefer migrating to the OpenTelemetry API directly. */ +@Deprecated public final class OpenTracingShim { private OpenTracingShim() {} /** - * Creates a {@code io.opentracing.Tracer} shim out of {@code - * GlobalOpenTelemetry.getTracerProvider()} and {@code GlobalOpenTelemetry.getPropagators()}. - * - * @return a {@code io.opentracing.Tracer}. - */ - public static io.opentracing.Tracer createTracerShim() { - return createTracerShim(getTracer(GlobalOpenTelemetry.getTracerProvider())); - } - - /** - * Creates a {@code io.opentracing.Tracer} shim using provided Tracer instance and {@code - * GlobalOpenTelemetry.getPropagators()}. - * - * @return a {@code io.opentracing.Tracer}. - */ - public static io.opentracing.Tracer createTracerShim(Tracer tracer) { - return createTracerShim(tracer, OpenTracingPropagators.builder().build()); - } - - /** - * Creates a {@code io.opentracing.Tracer} shim using provided Tracer instance and {@code - * OpenTracingPropagators} instance. + * Creates a {@code io.opentracing.Tracer} shim using the provided {@link OpenTelemetry} instance. + * Uses the {@link TracerProvider} and {@link TextMapPropagator} associated with the {@link + * OpenTelemetry} instance. * + * @param openTelemetry the {@code OpenTelemetry} instance used to create this shim. * @return a {@code io.opentracing.Tracer}. - * @since 1.1.0 + * @deprecated OpenTracing is deprecated. Prefer migrating to the OpenTelemetry API directly. */ - public static io.opentracing.Tracer createTracerShim( - Tracer tracer, OpenTracingPropagators propagators) { - return new TracerShim(new TelemetryInfo(tracer, propagators)); + @Deprecated + public static Tracer createTracerShim(OpenTelemetry openTelemetry) { + TextMapPropagator propagator = openTelemetry.getPropagators().getTextMapPropagator(); + return createTracerShim(openTelemetry.getTracerProvider(), propagator, propagator); } /** - * Creates a {@code io.opentracing.Tracer} shim using the provided OpenTelemetry instance. + * Creates a {@code io.opentracing.Tracer} shim using the provided {@code TracerProvider} and + * {@code TextMapPropagator} instance. * - * @param openTelemetry the {@code OpenTelemetry} instance used to create this shim. + * @param provider the {@code TracerProvider} instance used to create this shim. + * @param textMapPropagator the propagator used for {@link + * io.opentracing.propagation.Format.Builtin#TEXT_MAP} format. + * @param httpPropagator the propagator used for {@link + * io.opentracing.propagation.Format.Builtin#HTTP_HEADERS} format. * @return a {@code io.opentracing.Tracer}. + * @deprecated OpenTracing is deprecated. Prefer migrating to the OpenTelemetry API directly. */ - public static io.opentracing.Tracer createTracerShim(OpenTelemetry openTelemetry) { - return createTracerShim( - getTracer(openTelemetry.getTracerProvider()), - OpenTracingPropagators.builder() - .setTextMap(openTelemetry.getPropagators().getTextMapPropagator()) - .setHttpHeaders(openTelemetry.getPropagators().getTextMapPropagator()) - .build()); - } - - private static Tracer getTracer(TracerProvider tracerProvider) { - return tracerProvider.get("opentracingshim"); + @Deprecated + public static Tracer createTracerShim( + TracerProvider provider, + TextMapPropagator textMapPropagator, + TextMapPropagator httpPropagator) { + return new TracerShim(provider, textMapPropagator, httpPropagator); } } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/Propagation.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/Propagation.java index 3f27bbeb171..e67bf4fa73d 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/Propagation.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/Propagation.java @@ -16,12 +16,16 @@ import java.util.Map; import javax.annotation.Nullable; -final class Propagation extends BaseShimObject { +final class Propagation { private static final TextMapSetter SETTER_INSTANCE = new TextMapSetter(); private static final TextMapGetter GETTER_INSTANCE = new TextMapGetter(); - Propagation(TelemetryInfo telemetryInfo) { - super(telemetryInfo); + private final TextMapPropagator textMapPropagator; + private final TextMapPropagator httpPropagator; + + Propagation(TextMapPropagator textMapPropagator, TextMapPropagator httpPropagator) { + this.textMapPropagator = textMapPropagator; + this.httpPropagator = httpPropagator; } void injectTextMap(SpanContextShim contextShim, Format format, TextMapInject carrier) { @@ -38,21 +42,26 @@ SpanContextShim extractTextMap(Format format, TextMapExtract carrier) { carrierMap.put(entry.getKey(), entry.getValue()); } - Context context = getPropagator(format).extract(Context.current(), carrierMap, GETTER_INSTANCE); + Context context = getPropagator(format).extract(Context.root(), carrierMap, GETTER_INSTANCE); Span span = Span.fromContext(context); - if (!span.getSpanContext().isValid()) { + Baggage baggage = Baggage.fromContext(context); + if (!span.getSpanContext().isValid() + && !span.getSpanContext().isSampled() + && baggage.isEmpty()) { return null; } - return new SpanContextShim(telemetryInfo, span.getSpanContext(), Baggage.fromContext(context)); + return new SpanContextShim(span.getSpanContext(), baggage); } - private TextMapPropagator getPropagator(Format format) { + // Visible for testing + @SuppressWarnings("ReferenceEquality") + TextMapPropagator getPropagator(Format format) { if (format == Format.Builtin.HTTP_HEADERS) { - return propagators().httpHeadersPropagator(); + return httpPropagator; } - return propagators().textMapPropagator(); + return textMapPropagator; } static final class TextMapSetter diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeManagerShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeManagerShim.java index 1e9e73d25a8..4b69eccc5fb 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeManagerShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeManagerShim.java @@ -5,61 +5,51 @@ package io.opentelemetry.opentracingshim; -import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.context.Context; import io.opentracing.Scope; import io.opentracing.ScopeManager; import io.opentracing.Span; import javax.annotation.Nullable; -final class ScopeManagerShim extends BaseShimObject implements ScopeManager { +final class ScopeManagerShim implements ScopeManager { private static final SpanShim NOOP_SPANSHIM = - new SpanShim( - new TelemetryInfo( - OpenTelemetry.noop().getTracer("noop"), OpenTracingPropagators.builder().build()), - io.opentelemetry.api.trace.Span.getInvalid()); + new SpanShim(io.opentelemetry.api.trace.Span.getInvalid()); - public ScopeManagerShim(TelemetryInfo telemetryInfo) { - super(telemetryInfo); - } + ScopeManagerShim() {} @Override @Nullable + @SuppressWarnings("ReferenceEquality") public Span activeSpan() { SpanShim spanShim = SpanShim.current(); - io.opentelemetry.api.trace.Span span = null; - if (spanShim == null) { - span = io.opentelemetry.api.trace.Span.current(); - } else { - span = spanShim.getSpan(); - } + io.opentelemetry.api.trace.Span span = io.opentelemetry.api.trace.Span.current(); + Baggage baggage = Baggage.current(); - // As OpenTracing simply returns null when no active instance is available, - // we need to do map an invalid OpenTelemetry span to null here. if (!span.getSpanContext().isValid()) { - return null; + if (baggage.isEmpty()) { + return null; + } + + return new SpanShim(io.opentelemetry.api.trace.Span.getInvalid(), baggage); } // If there's a SpanShim for the *actual* active Span, simply return it. - if (spanShim != null && span == io.opentelemetry.api.trace.Span.current()) { + if (spanShim != null && spanShim.getSpan() == span) { return spanShim; } // Span was activated from outside the Shim layer unfortunately. - return new SpanShim(telemetryInfo(), span); + return new SpanShim(span, baggage); } @Override @SuppressWarnings("MustBeClosedChecker") public Scope activate(@Nullable Span span) { - if (span == null) { + SpanShim spanShim = ShimUtil.getSpanShim(span); + if (spanShim == null) { return new ScopeShim(Context.current().with(NOOP_SPANSHIM).makeCurrent()); } - if (!(span instanceof SpanShim)) { - throw new IllegalArgumentException("span is not a valid SpanShim object"); - } - - SpanShim spanShim = (SpanShim) span; return new ScopeShim(Context.current().with(spanShim).makeCurrent()); } } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeShim.java index e51d77bae73..7af751881d7 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ScopeShim.java @@ -10,7 +10,7 @@ final class ScopeShim implements Scope { final io.opentelemetry.context.Scope scope; - public ScopeShim(io.opentelemetry.context.Scope scope) { + ScopeShim(io.opentelemetry.context.Scope scope) { this.scope = scope; } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ShimUtil.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ShimUtil.java new file mode 100644 index 00000000000..475490eb717 --- /dev/null +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/ShimUtil.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opentracingshim; + +import io.opentracing.Span; +import io.opentracing.SpanContext; +import io.opentracing.noop.NoopSpan; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +class ShimUtil { + private static final Logger logger = Logger.getLogger(ShimUtil.class.getName()); + + private ShimUtil() {} + + @Nullable + static SpanContextShim getContextShim(@Nullable SpanContext context) { + if (context == null) { + return null; + } + + if (!(context instanceof SpanContextShim)) { + logger.log( + Level.INFO, + "Expected to have an OpenTelemetry SpanContext but got {0}", + className(context)); + return null; + } + + return (SpanContextShim) context; + } + + @Nullable + static SpanShim getSpanShim(@Nullable Span span) { + if (span == null || span instanceof NoopSpan) { + return null; + } + + if (!(span instanceof SpanShim)) { + if (span instanceof Supplier) { + // allow libraries to implement a delegate span, + // such as https://github.com/zalando/opentracing-toolbox/tree/main/opentracing-proxy + Object wrapped = ((Supplier) span).get(); + if (wrapped instanceof Span) { + return getSpanShim((Span) wrapped); + } else { + logger.log(Level.INFO, "Span wrapper didn't return a span: {0}", className(wrapped)); + return null; + } + } + + logger.log(Level.INFO, "Expected to have an OpenTelemetry Span but got {0}", className(span)); + return null; + } + + return (SpanShim) span; + } + + private static String className(@Nullable Object o) { + return o == null ? "null" : o.getClass().getName(); + } +} diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanBuilderShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanBuilderShim.java index 82b0c5d801c..0d3be078c1f 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanBuilderShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanBuilderShim.java @@ -10,58 +10,62 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import com.google.auto.value.AutoValue; import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.baggage.BaggageBuilder; import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; +import io.opentracing.References; import io.opentracing.Span; import io.opentracing.SpanContext; import io.opentracing.Tracer.SpanBuilder; import io.opentracing.tag.Tag; import io.opentracing.tag.Tags; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; -final class SpanBuilderShim extends BaseShimObject implements SpanBuilder { - private final String spanName; +final class SpanBuilderShim implements SpanBuilder { - // The parent will be either a Span or a SpanContext. - // Inherited baggage is supported only for the main parent. - @Nullable private SpanShim parentSpan; - @Nullable private SpanContextShim parentSpanContext; - private boolean ignoreActiveSpan; + private static final AttributeKey OPENTRACING_REF_TYPE = + stringKey("opentracing.ref_type"); + private static final String OPEN_TRACING_REF_TYPE_CHILD_OF = "child_of"; + private static final String OPEN_TRACING_REF_TYPE_FOLLOWS_FROM = "follows_from"; - private final List parentLinks = new ArrayList<>(); + private static final Attributes CHILD_OF_ATTR = + Attributes.of(OPENTRACING_REF_TYPE, OPEN_TRACING_REF_TYPE_CHILD_OF); + private static final Attributes FOLLOWS_FROM_ATTR = + Attributes.of(OPENTRACING_REF_TYPE, OPEN_TRACING_REF_TYPE_FOLLOWS_FROM); - @SuppressWarnings("rawtypes") - private final List spanBuilderAttributeKeys = new ArrayList<>(); + private final Tracer tracer; + private final String spanName; + + // *All* parents are saved in this list. + private List allParents = Collections.emptyList(); + private boolean ignoreActiveSpan; + private final List> spanBuilderAttributeKeys = new ArrayList<>(); private final List spanBuilderAttributeValues = new ArrayList<>(); - @Nullable private SpanKind spanKind; - private boolean error; + + @Nullable private Boolean error; private long startTimestampMicros; - public SpanBuilderShim(TelemetryInfo telemetryInfo, String spanName) { - super(telemetryInfo); + SpanBuilderShim(Tracer tracer, String spanName) { + this.tracer = tracer; this.spanName = spanName; } @Override public SpanBuilder asChildOf(Span parent) { - if (parent == null) { - return this; - } - - // TODO - Verify we handle a no-op Span - SpanShim spanShim = getSpanShim(parent); - - if (parentSpan == null && parentSpanContext == null) { - parentSpan = spanShim; - } else { - parentLinks.add(spanShim.getSpan().getSpanContext()); + SpanShim spanShim = ShimUtil.getSpanShim(parent); + if (spanShim != null) { + addReference(References.CHILD_OF, spanShim.context()); } return this; @@ -69,22 +73,38 @@ public SpanBuilder asChildOf(Span parent) { @Override public SpanBuilder asChildOf(SpanContext parent) { - return addReference(null, parent); + return addReference(References.CHILD_OF, parent); } @Override public SpanBuilder addReference(@Nullable String referenceType, SpanContext referencedContext) { - if (referencedContext == null) { + SpanContextShim contextShim = ShimUtil.getContextShim(referencedContext); + if (contextShim == null) { return this; } - // TODO - Use referenceType - SpanContextShim contextShim = getContextShim(referencedContext); + ReferenceType refType; + if (References.CHILD_OF.equals(referenceType)) { + refType = ReferenceType.CHILD_OF; + } else if (References.FOLLOWS_FROM.equals(referenceType)) { + refType = ReferenceType.FOLLOWS_FROM; + } else { + // Discard references with unrecognized type. + return this; + } - if (parentSpan == null && parentSpanContext == null) { - parentSpanContext = contextShim; + // Optimization for 99% situations, when there is only one parent. + if (allParents.size() == 0) { + allParents = + Collections.singletonList( + SpanParentInfo.create( + contextShim.getSpanContext(), contextShim.getBaggage(), refType)); } else { - parentLinks.add(contextShim.getSpanContext()); + if (allParents.size() == 1) { + allParents = new ArrayList<>(allParents); + } + allParents.add( + SpanParentInfo.create(contextShim.getSpanContext(), contextShim.getBaggage(), refType)); } return this; @@ -98,25 +118,7 @@ public SpanBuilder ignoreActiveSpan() { @Override public SpanBuilder withTag(String key, String value) { - if (Tags.SPAN_KIND.getKey().equals(key)) { - switch (value) { - case Tags.SPAN_KIND_CLIENT: - spanKind = SpanKind.CLIENT; - break; - case Tags.SPAN_KIND_SERVER: - spanKind = SpanKind.SERVER; - break; - case Tags.SPAN_KIND_PRODUCER: - spanKind = SpanKind.PRODUCER; - break; - case Tags.SPAN_KIND_CONSUMER: - spanKind = SpanKind.CONSUMER; - break; - default: - spanKind = SpanKind.INTERNAL; - break; - } - } else if (Tags.ERROR.getKey().equals(key)) { + if (Tags.ERROR.getKey().equals(key)) { error = Boolean.parseBoolean(value); } else { this.spanBuilderAttributeKeys.add(stringKey(key)); @@ -142,7 +144,7 @@ public SpanBuilder withTag(String key, Number value) { if (value == null) { return this; } - // TODO - Verify only the 'basic' types are supported/used. + if (value instanceof Integer || value instanceof Long || value instanceof Short @@ -153,7 +155,8 @@ public SpanBuilder withTag(String key, Number value) { this.spanBuilderAttributeKeys.add(doubleKey(key)); this.spanBuilderAttributeValues.add(value.doubleValue()); } else { - throw new IllegalArgumentException("Number type not supported"); + this.spanBuilderAttributeKeys.add(stringKey(key)); + this.spanBuilderAttributeValues.add(value.toString()); } return this; @@ -186,28 +189,27 @@ public SpanBuilder withStartTimestamp(long microseconds) { @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Span start() { - Baggage baggage = null; - io.opentelemetry.api.trace.SpanBuilder builder = tracer().spanBuilder(spanName); + Baggage baggage; + io.opentelemetry.api.trace.SpanBuilder builder = tracer.spanBuilder(spanName); + io.opentelemetry.api.trace.SpanContext mainParent = getMainParent(allParents); - if (ignoreActiveSpan && parentSpan == null && parentSpanContext == null) { + if (ignoreActiveSpan && mainParent == null) { builder.setNoParent(); - } else if (parentSpan != null) { - builder.setParent(Context.root().with(parentSpan.getSpan())); - SpanContextShim contextShim = spanContextTable().get(parentSpan); - baggage = contextShim == null ? null : contextShim.getBaggage(); - } else if (parentSpanContext != null) { + baggage = Baggage.empty(); + } else if (mainParent != null) { + baggage = getAllBaggage(allParents); builder.setParent( - Context.root() - .with(io.opentelemetry.api.trace.Span.wrap(parentSpanContext.getSpanContext()))); - baggage = parentSpanContext.getBaggage(); - } - - for (io.opentelemetry.api.trace.SpanContext link : parentLinks) { - builder.addLink(link); + Context.root().with(io.opentelemetry.api.trace.Span.wrap(mainParent)).with(baggage)); + } else { + // No explicit parent Span, but extracted baggage may be available. + baggage = Baggage.current(); } - if (spanKind != null) { - builder.setSpanKind(spanKind); + // *All* parents are processed as Links, in order to keep the reference type value. + for (SpanParentInfo parentInfo : allParents) { + builder.addLink( + parentInfo.getSpanContext(), + parentInfo.getRefType() == ReferenceType.CHILD_OF ? CHILD_OF_ATTR : FOLLOWS_FROM_ATTR); } if (startTimestampMicros > 0) { @@ -224,32 +226,69 @@ public Span start() { } io.opentelemetry.api.trace.Span span = builder.startSpan(); - if (error) { - span.setStatus(StatusCode.ERROR); + if (error != null) { + span.setStatus(error ? StatusCode.ERROR : StatusCode.OK); } - SpanShim spanShim = new SpanShim(telemetryInfo(), span); + return new SpanShim(span, baggage); + } + + // The first SpanContext with Child Of type in the entire list is used as parent, + // else the first SpanContext is used as parent. + @Nullable + private static io.opentelemetry.api.trace.SpanContext getMainParent( + List parents) { + if (parents.size() == 0) { + return null; + } - if (baggage != null && baggage != telemetryInfo().emptyBaggage()) { - spanContextTable().create(spanShim, baggage); + SpanParentInfo mainParent = parents.get(0); + for (SpanParentInfo parentInfo : parents) { + if (parentInfo.getRefType() == ReferenceType.CHILD_OF) { + mainParent = parentInfo; + break; + } } - return spanShim; + return mainParent.getSpanContext(); } - private static SpanShim getSpanShim(Span span) { - if (!(span instanceof SpanShim)) { - throw new IllegalArgumentException("span is not a valid SpanShim object"); + private static Baggage getAllBaggage(List parents) { + if (parents.size() == 0) { + return Baggage.empty(); } - return (SpanShim) span; + if (parents.size() == 1) { + return parents.get(0).getBaggage(); + } + + BaggageBuilder builder = Baggage.builder(); + for (SpanParentInfo parent : parents) { + parent.getBaggage().forEach((key, entry) -> builder.put(key, entry.getValue())); + } + + return builder.build(); } - private static SpanContextShim getContextShim(SpanContext context) { - if (!(context instanceof SpanContextShim)) { - throw new IllegalArgumentException("context is not a valid SpanContextShim object"); + @AutoValue + @Immutable + abstract static class SpanParentInfo { + private static SpanParentInfo create( + io.opentelemetry.api.trace.SpanContext spanContext, + Baggage baggage, + ReferenceType refType) { + return new AutoValue_SpanBuilderShim_SpanParentInfo(spanContext, baggage, refType); } - return (SpanContextShim) context; + abstract io.opentelemetry.api.trace.SpanContext getSpanContext(); + + abstract Baggage getBaggage(); + + abstract ReferenceType getRefType(); + } + + enum ReferenceType { + CHILD_OF, + FOLLOWS_FROM } } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java index c0d9000f514..5eff8ca7f80 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShim.java @@ -15,28 +15,12 @@ import java.util.Map; import javax.annotation.Nullable; -final class SpanContextShim extends BaseShimObject implements SpanContext { +final class SpanContextShim implements SpanContext { private final io.opentelemetry.api.trace.SpanContext context; private final Baggage baggage; - public SpanContextShim(SpanShim spanShim) { - this( - spanShim.telemetryInfo(), - spanShim.getSpan().getSpanContext(), - spanShim.telemetryInfo().emptyBaggage()); - } - - public SpanContextShim( - TelemetryInfo telemetryInfo, io.opentelemetry.api.trace.SpanContext context) { - this(telemetryInfo, context, telemetryInfo.emptyBaggage()); - } - - public SpanContextShim( - TelemetryInfo telemetryInfo, - io.opentelemetry.api.trace.SpanContext context, - Baggage baggage) { - super(telemetryInfo); + SpanContextShim(io.opentelemetry.api.trace.SpanContext context, Baggage baggage) { this.context = context; this.baggage = baggage; } @@ -45,7 +29,7 @@ SpanContextShim newWithKeyValue(String key, String value) { BaggageBuilder builder = baggage.toBuilder(); builder.put(key, value, BaggageEntryMetadata.empty()); - return new SpanContextShim(telemetryInfo(), context, builder.build()); + return new SpanContextShim(context, builder.build()); } io.opentelemetry.api.trace.SpanContext getSpanContext() { @@ -69,9 +53,8 @@ public String toSpanId() { @Override public Iterable> baggageItems() { List> items = new ArrayList<>(baggage.size()); - baggage.forEach( - (key, baggageEntry) -> - items.add(new AbstractMap.SimpleImmutableEntry<>(key, baggageEntry.getValue()))); + baggage.forEach((key, baggageEntry) -> + items.add(new AbstractMap.SimpleImmutableEntry<>(key, baggageEntry.getValue()))); return items; } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShimTable.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShimTable.java deleted file mode 100644 index ded13f90923..00000000000 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanContextShimTable.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opentracingshim; - -import io.opentelemetry.api.baggage.Baggage; -import io.opentelemetry.api.trace.Span; -import java.util.Map; -import java.util.WeakHashMap; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.annotation.Nullable; - -/* - * SpanContextShimTable stores and manages OpenTracing SpanContext instances, - * which are expected to a unmodfiable union of SpanContext and Baggage - * (Baggage/TagMap under OpenTelemetry). - * - * This requires that changes on a given Span and its (new) SpanContext - * are visible in all threads at *any* moment. The current approach uses - * a weak map synchronized through a read-write lock to get and set both - * SpanContext and any Baggage content related to its owner Span. - * - * Observe that, because of this design, a global read or write lock - * will be taken for ALL operations involving OT SpanContext/Baggage. - * When/if performance becomes an issue in the OT Shim layer, consider - * adding an extra slot in io.opentelemetry.trace.Span, so: - * 1) The current SpanContextShim is directly stored in Span. - * 2) The lock for this operation can be on a per-Span basis. - * - * For more information, see: - * https://github.com/opentracing/specification/blob/master/specification.md#set-a-baggage-item - */ -final class SpanContextShimTable { - private final Map shimsMap = new WeakHashMap<>(); - private final ReadWriteLock lock = new ReentrantReadWriteLock(); - - public void setBaggageItem(SpanShim spanShim, String key, String value) { - lock.writeLock().lock(); - try { - SpanContextShim contextShim = shimsMap.get(spanShim.getSpan()); - if (contextShim == null) { - contextShim = new SpanContextShim(spanShim); - } - - contextShim = contextShim.newWithKeyValue(key, value); - shimsMap.put(spanShim.getSpan(), contextShim); - } finally { - lock.writeLock().unlock(); - } - } - - @Nullable - public String getBaggageItem(SpanShim spanShim, String key) { - lock.readLock().lock(); - try { - SpanContextShim contextShim = shimsMap.get(spanShim.getSpan()); - return contextShim == null ? null : contextShim.getBaggageItem(key); - } finally { - lock.readLock().unlock(); - } - } - - @Nullable - public SpanContextShim get(SpanShim spanShim) { - lock.readLock().lock(); - try { - return shimsMap.get(spanShim.getSpan()); - } finally { - lock.readLock().unlock(); - } - } - - public SpanContextShim create(SpanShim spanShim) { - return create(spanShim, spanShim.telemetryInfo().emptyBaggage()); - } - - public SpanContextShim create(SpanShim spanShim, Baggage baggage) { - lock.writeLock().lock(); - try { - SpanContextShim contextShim = shimsMap.get(spanShim.getSpan()); - if (contextShim != null) { - return contextShim; - } - - contextShim = - new SpanContextShim( - spanShim.telemetryInfo(), spanShim.getSpan().getSpanContext(), baggage); - shimsMap.put(spanShim.getSpan(), contextShim); - return contextShim; - - } finally { - lock.writeLock().unlock(); - } - } -} diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanShim.java index 8853737b0bf..a5524cd1645 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/SpanShim.java @@ -10,6 +10,7 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; @@ -17,7 +18,6 @@ import io.opentelemetry.context.Context; import io.opentelemetry.context.ContextKey; import io.opentelemetry.context.ImplicitContextKeyed; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import io.opentracing.Span; import io.opentracing.SpanContext; import io.opentracing.log.Fields; @@ -28,32 +28,47 @@ import javax.annotation.Nullable; /* - * SpanContextShim is not directly stored in the SpanShim, - * as its changes need to be visible in all threads at *any* moment. - * By default, the related SpanContextShim will not be created - * in order to avoid overhead (which would require taking a write lock - * at creation time). - * - * Calling context() or setBaggageItem() will effectively force the creation - * of SpanContextShim object if none existed yet. + * SpanContextShim is directly stored in the SpanShim for simplicity + * and performance reasons, as opposed to keeping a global map + * link OTel's Span and OT Span/SpanContext. */ -final class SpanShim extends BaseShimObject implements Span, ImplicitContextKeyed { +final class SpanShim implements Span, ImplicitContextKeyed { + + private static final AttributeKey EXCEPTION_TYPE = + AttributeKey.stringKey("exception.type"); + private static final AttributeKey EXCEPTION_MESSAGE = + AttributeKey.stringKey("exception.message"); + private static final AttributeKey EXCEPTION_STACKTRACE = + AttributeKey.stringKey("exception.stacktrace"); + private static final String EXCEPTION_EVENT_NAME = "exception"; + private static final String DEFAULT_EVENT_NAME = "log"; private static final String ERROR = "error"; private static final ContextKey SPAN_SHIM_KEY = ContextKey.named("opentracing-shim-key"); private final io.opentelemetry.api.trace.Span span; + private final Object spanContextShimLock; + private volatile SpanContextShim spanContextShim; + + SpanShim(io.opentelemetry.api.trace.Span span) { + this(span, Baggage.empty()); + } - public SpanShim(TelemetryInfo telemetryInfo, io.opentelemetry.api.trace.Span span) { - super(telemetryInfo); + SpanShim(io.opentelemetry.api.trace.Span span, Baggage baggage) { this.span = span; + this.spanContextShimLock = new Object(); + this.spanContextShim = new SpanContextShim(span.getSpanContext(), baggage); } io.opentelemetry.api.trace.Span getSpan() { return span; } + Baggage getBaggage() { + return spanContextShim.getBaggage(); + } + @Nullable public static SpanShim current() { return Context.current().get(SPAN_SHIM_KEY); @@ -61,38 +76,20 @@ public static SpanShim current() { @Override public Context storeInContext(Context context) { - context = context.with(SPAN_SHIM_KEY, this).with(span); - - SpanContextShim spanContextShim = spanContextTable().get(this); - if (spanContextShim != null) { - context = context.with(spanContextShim.getBaggage()); - } + context = context.with(SPAN_SHIM_KEY, this).with(span).with(spanContextShim.getBaggage()); return context; } @Override public SpanContext context() { - /* Read the value using the read lock first. */ - SpanContextShim contextShim = spanContextTable().get(this); - - /* Switch to the write lock *only* for the relatively exceptional case - * of no context being created. - * (as we cannot upgrade read->write lock sadly).*/ - if (contextShim == null) { - contextShim = spanContextTable().create(this); - } - - return contextShim; + return spanContextShim; } @Override public Span setTag(String key, String value) { - if (Tags.SPAN_KIND.getKey().equals(key)) { - // TODO: confirm we can safely ignore span.kind after Span was created - // https://github.com/bogdandrutu/opentelemetry/issues/42 - } else if (Tags.ERROR.getKey().equals(key)) { - StatusCode canonicalCode = Boolean.parseBoolean(value) ? StatusCode.ERROR : StatusCode.UNSET; + if (Tags.ERROR.getKey().equals(key)) { + StatusCode canonicalCode = Boolean.parseBoolean(value) ? StatusCode.ERROR : StatusCode.OK; span.setStatus(canonicalCode); } else { span.setAttribute(key, value); @@ -104,7 +101,7 @@ public Span setTag(String key, String value) { @Override public Span setTag(String key, boolean value) { if (Tags.ERROR.getKey().equals(key)) { - StatusCode canonicalCode = value ? StatusCode.ERROR : StatusCode.UNSET; + StatusCode canonicalCode = value ? StatusCode.ERROR : StatusCode.OK; span.setStatus(canonicalCode); } else { span.setAttribute(key, value); @@ -118,7 +115,7 @@ public Span setTag(String key, Number value) { if (value == null) { return this; } - // TODO - Verify only the 'basic' types are supported/used. + if (value instanceof Integer || value instanceof Long || value instanceof Short @@ -127,7 +124,7 @@ public Span setTag(String key, Number value) { } else if (value instanceof Float || value instanceof Double) { span.setAttribute(key, value.doubleValue()); } else { - throw new IllegalArgumentException("Number type not supported"); + span.setAttribute(key, value.toString()); } return this; @@ -173,7 +170,9 @@ public Span setBaggageItem(String key, String value) { return this; } - spanContextTable().setBaggageItem(this, key, value); + synchronized (spanContextShimLock) { + spanContextShim = spanContextShim.newWithKeyValue(key, value); + } return this; } @@ -185,7 +184,7 @@ public String getBaggageItem(String key) { return null; } - return spanContextTable().getBaggageItem(this, key); + return spanContextShim.getBaggageItem(key); } @Override @@ -212,7 +211,7 @@ private void logInternal(long timestampMicroseconds, Map fields) { throwable = findThrowable(fields); isError = true; if (throwable == null) { - name = SemanticAttributes.EXCEPTION_EVENT_NAME; + name = EXCEPTION_EVENT_NAME; } } Attributes attributes = convertToAttributes(fields, isError, throwable != null); @@ -262,11 +261,11 @@ private static Attributes convertToAttributes( AttributeKey attributeKey = null; if (isError && !isRecordingException) { if (key.equals(Fields.ERROR_KIND)) { - attributeKey = SemanticAttributes.EXCEPTION_TYPE; + attributeKey = EXCEPTION_TYPE; } else if (key.equals(Fields.MESSAGE)) { - attributeKey = SemanticAttributes.EXCEPTION_MESSAGE; + attributeKey = EXCEPTION_MESSAGE; } else if (key.equals(Fields.STACK)) { - attributeKey = SemanticAttributes.EXCEPTION_STACKTRACE; + attributeKey = EXCEPTION_STACKTRACE; } } if (isRecordingException && key.equals(Fields.ERROR_OBJECT)) { diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TelemetryInfo.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TelemetryInfo.java deleted file mode 100644 index 9617f1b32d9..00000000000 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TelemetryInfo.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opentracingshim; - -import io.opentelemetry.api.baggage.Baggage; -import io.opentelemetry.api.trace.Tracer; - -/** - * Utility class that holds a Tracer, a BaggageManager, and related objects that are core part of - * the OT Shim layer. - */ -final class TelemetryInfo { - - private final Tracer tracer; - private final Baggage emptyBaggage; - private final OpenTracingPropagators openTracingPropagators; - private final SpanContextShimTable spanContextTable; - - TelemetryInfo(Tracer tracer, OpenTracingPropagators openTracingPropagators) { - this.tracer = tracer; - this.openTracingPropagators = openTracingPropagators; - this.emptyBaggage = Baggage.empty(); - this.spanContextTable = new SpanContextShimTable(); - } - - Tracer tracer() { - return tracer; - } - - SpanContextShimTable spanContextTable() { - return spanContextTable; - } - - Baggage emptyBaggage() { - return emptyBaggage; - } - - OpenTracingPropagators propagators() { - return openTracingPropagators; - } -} diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TracerShim.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TracerShim.java index 27d61129976..f275e841855 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TracerShim.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/TracerShim.java @@ -5,6 +5,9 @@ package io.opentelemetry.opentracingshim; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.opentracing.shim.internal.OtelVersion; import io.opentracing.Scope; import io.opentracing.ScopeManager; import io.opentracing.Span; @@ -13,21 +16,41 @@ import io.opentracing.propagation.Format; import io.opentracing.propagation.TextMapExtract; import io.opentracing.propagation.TextMapInject; +import java.io.Closeable; +import java.io.IOException; +import java.lang.reflect.Field; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; -final class TracerShim extends BaseShimObject implements Tracer { +final class TracerShim implements Tracer { private static final Logger logger = Logger.getLogger(TracerShim.class.getName()); + private final TracerProvider provider; + private final io.opentelemetry.api.trace.Tracer tracer; private final ScopeManager scopeManagerShim; private final Propagation propagation; - private volatile boolean isClosed; + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + TracerShim( + TracerProvider provider, + TextMapPropagator textMapPropagator, + TextMapPropagator httpPropagator) { + this.provider = provider; + this.tracer = provider.get("opentracing-shim", OtelVersion.VERSION); + this.propagation = new Propagation(textMapPropagator, httpPropagator); + this.scopeManagerShim = new ScopeManagerShim(); + } + + // Visible for testing + io.opentelemetry.api.trace.Tracer tracer() { + return tracer; + } - TracerShim(TelemetryInfo telemetryInfo) { - super(telemetryInfo); - this.scopeManagerShim = new ScopeManagerShim(telemetryInfo); - this.propagation = new Propagation(telemetryInfo); + // Visible for testing + Propagation propagation() { + return propagation; } @Override @@ -47,21 +70,26 @@ public Scope activateSpan(Span span) { @Override public SpanBuilder buildSpan(String operationName) { - if (isClosed) { - return new NoopSpanBuilderShim(telemetryInfo(), operationName); + if (isShutdown.get()) { + return new NoopSpanBuilderShim(operationName); } - return new SpanBuilderShim(telemetryInfo, operationName); + return new SpanBuilderShim(tracer, operationName); } @Override + @SuppressWarnings("ReferenceEquality") public void inject(SpanContext context, Format format, C carrier) { if (context == null) { - logger.log(Level.INFO, "Cannot inject a null span context."); + logger.log(Level.WARNING, "Cannot inject a null span context."); return; } - SpanContextShim contextShim = getContextShim(context); + SpanContextShim contextShim = ShimUtil.getContextShim(context); + if (contextShim == null) { + logger.log(Level.WARNING, "Cannot inject a null span context shim."); + return; + } if (format == Format.Builtin.TEXT_MAP || format == Format.Builtin.TEXT_MAP_INJECT @@ -72,6 +100,7 @@ public void inject(SpanContext context, Format format, C carrier) { @Override @Nullable + @SuppressWarnings("ReferenceEquality") public SpanContext extract(Format format, C carrier) { try { if (format == Format.Builtin.TEXT_MAP @@ -81,10 +110,7 @@ public SpanContext extract(Format format, C carrier) { } } catch (RuntimeException e) { logger.log( - Level.INFO, - "Exception caught while extracting span context; returning null. " - + "Exception: [{0}] Message: [{1}]", - new String[] {e.getClass().getName(), e.getMessage()}); + Level.WARNING, "Exception caught while extracting span context; returning null.", e); } return null; @@ -92,14 +118,34 @@ public SpanContext extract(Format format, C carrier) { @Override public void close() { - isClosed = true; - } + if (!isShutdown.compareAndSet(false, true)) { + return; + } - static SpanContextShim getContextShim(SpanContext context) { - if (!(context instanceof SpanContextShim)) { - throw new IllegalArgumentException("context is not a valid SpanContextShim object"); + TracerProvider provider = maybeUnobfuscate(this.provider); + if (provider instanceof Closeable) { + try { + ((Closeable) provider).close(); + } catch (RuntimeException | IOException e) { + logger.log(Level.WARNING, "Exception caught while closing TracerProvider.", e); + } } + } - return (SpanContextShim) context; + private static TracerProvider maybeUnobfuscate(TracerProvider tracerProvider) { + if (!tracerProvider.getClass().getSimpleName().equals("ObfuscatedTracerProvider")) { + return tracerProvider; + } + try { + Field delegateField = tracerProvider.getClass().getDeclaredField("delegate"); + delegateField.setAccessible(true); + Object delegate = delegateField.get(tracerProvider); + if (delegate instanceof TracerProvider) { + return (TracerProvider) delegate; + } + } catch (NoSuchFieldException | IllegalAccessException e) { + logger.log(Level.INFO, "Error trying to unobfuscate SdkTracerProvider", e); + } + return tracerProvider; } } diff --git a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/package-info.java b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/package-info.java index 53177c39a6b..d935461444f 100644 --- a/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/package-info.java +++ b/opentracing-shim/src/main/java/io/opentelemetry/opentracingshim/package-info.java @@ -4,8 +4,11 @@ */ /** - * An OpenTracing implementation that delegates to the OpenTelemetry SDK. Use {@link - * io.opentelemetry.opentracingshim.OpenTracingShim} to create tracers using this implementation. + * Legacy OpenTracing compatibility built on top of OpenTelemetry. + * + *

    OpenTracing is deprecated in the OpenTelemetry specification, and this shim is deprecated + * accordingly. Use {@link io.opentelemetry.opentracingshim.OpenTracingShim} only for legacy + * compatibility while migrating to the OpenTelemetry API. */ @ParametersAreNonnullByDefault package io.opentelemetry.opentracingshim; diff --git a/opentracing-shim/src/main/resources/simplelogger.properties b/opentracing-shim/src/main/resources/simplelogger.properties deleted file mode 100644 index cd90c2acb8f..00000000000 --- a/opentracing-shim/src/main/resources/simplelogger.properties +++ /dev/null @@ -1 +0,0 @@ -org.slf4j.simpleLogger.defaultLogLevel=warn diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/OpenTracingShimTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/OpenTracingShimTest.java index 901977fb40e..895867aeb2f 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/OpenTracingShimTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/OpenTracingShimTest.java @@ -11,13 +11,16 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; -import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.common.internal.OtelVersion; import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentracing.propagation.Format; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") // testing deprecated shim API class OpenTracingShimTest { @AfterEach @@ -25,28 +28,27 @@ void tearDown() { GlobalOpenTelemetry.resetForTest(); } - @Test - void createTracerShim_default() { - TracerShim tracerShim = (TracerShim) OpenTracingShim.createTracerShim(); - assertThat(tracerShim.tracer()).isEqualTo(GlobalOpenTelemetry.getTracer("opentracingshim")); - } - @Test void createTracerShim_fromOpenTelemetryInstance() { OpenTelemetry openTelemetry = mock(OpenTelemetry.class); SdkTracerProvider sdk = SdkTracerProvider.builder().build(); when(openTelemetry.getTracerProvider()).thenReturn(sdk); + TextMapPropagator textMapPropagator = mock(TextMapPropagator.class); ContextPropagators contextPropagators = mock(ContextPropagators.class); - when(contextPropagators.getTextMapPropagator()).thenReturn(mock(TextMapPropagator.class)); + when(contextPropagators.getTextMapPropagator()).thenReturn(textMapPropagator); when(openTelemetry.getPropagators()).thenReturn(contextPropagators); TracerShim tracerShim = (TracerShim) OpenTracingShim.createTracerShim(openTelemetry); - assertThat(tracerShim.tracer()).isEqualTo(sdk.get("opentracingshim")); + assertThat(tracerShim.propagation().getPropagator(Format.Builtin.TEXT_MAP)) + .isSameAs(textMapPropagator); + assertThat(tracerShim.propagation().getPropagator(Format.Builtin.HTTP_HEADERS)) + .isSameAs(textMapPropagator); + assertThat(tracerShim.tracer()).isEqualTo(sdk.get("opentracing-shim", OtelVersion.VERSION)); } @Test void createTracerShim_withPropagators() { - Tracer tracer = mock(Tracer.class); + TracerProvider tracerProvider = mock(TracerProvider.class); TextMapPropagator textMapPropagator = new CustomTextMapPropagator(); TextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); @@ -54,13 +56,27 @@ void createTracerShim_withPropagators() { TracerShim tracerShim = (TracerShim) OpenTracingShim.createTracerShim( - tracer, - OpenTracingPropagators.builder() - .setTextMap(textMapPropagator) - .setHttpHeaders(httpHeadersPropagator) - .build()); + tracerProvider, textMapPropagator, httpHeadersPropagator); + + assertThat(tracerShim.propagation().getPropagator(Format.Builtin.TEXT_MAP)) + .isSameAs(textMapPropagator); + assertThat(tracerShim.propagation().getPropagator(Format.Builtin.HTTP_HEADERS)) + .isSameAs(httpHeadersPropagator); + } + + @Test + void createTracerShim_withTraceProviderAndPropagator() { + TextMapPropagator textMapPropagator = new CustomTextMapPropagator(); + TextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); + SdkTracerProvider sdk = SdkTracerProvider.builder().build(); + TracerShim tracerShim = + (TracerShim) + OpenTracingShim.createTracerShim(sdk, textMapPropagator, httpHeadersPropagator); - assertThat(tracerShim.propagators().textMapPropagator()).isSameAs(textMapPropagator); - assertThat(tracerShim.propagators().httpHeadersPropagator()).isSameAs(httpHeadersPropagator); + assertThat(tracerShim.propagation().getPropagator(Format.Builtin.TEXT_MAP)) + .isSameAs(textMapPropagator); + assertThat(tracerShim.propagation().getPropagator(Format.Builtin.HTTP_HEADERS)) + .isSameAs(httpHeadersPropagator); + assertThat(tracerShim.tracer()).isSameAs(sdk.get("opentracing-shim", OtelVersion.VERSION)); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/PropagationTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/PropagationTest.java deleted file mode 100644 index e0ac8448037..00000000000 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/PropagationTest.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.opentracingshim; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.context.propagation.TextMapPropagator; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class PropagationTest { - private final Tracer tracer = SdkTracerProvider.builder().build().get("PropagationTest"); - - @BeforeEach - @AfterEach - void setUp() { - GlobalOpenTelemetry.resetForTest(); - } - - @Test - public void defaultPropagators() { - Propagation propagation = - new Propagation(new TelemetryInfo(tracer, OpenTracingPropagators.builder().build())); - assertThat(propagation.propagators().textMapPropagator()) - .isSameAs(propagation.propagators().httpHeadersPropagator()); - } - - @Test - public void textMapPropagator() { - TextMapPropagator textMapPropagator = new CustomTextMapPropagator(); - - Propagation propagation = - new Propagation( - new TelemetryInfo( - tracer, OpenTracingPropagators.builder().setTextMap(textMapPropagator).build())); - - assertThat(propagation.propagators().textMapPropagator()) - .isNotSameAs(propagation.propagators().httpHeadersPropagator()); - - assertThat(propagation.propagators().textMapPropagator()).isSameAs(textMapPropagator); - } - - @Test - public void httpHeadersPropagator() { - TextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); - - Propagation propagation = - new Propagation( - new TelemetryInfo( - tracer, - OpenTracingPropagators.builder().setHttpHeaders(httpHeadersPropagator).build())); - - assertThat(propagation.propagators().textMapPropagator()) - .isNotSameAs(propagation.propagators().httpHeadersPropagator()); - - assertThat(propagation.propagators().httpHeadersPropagator()).isSameAs(httpHeadersPropagator); - } - - @Test - public void bothCustomPropagator() { - TextMapPropagator textMapPropagator = new CustomTextMapPropagator(); - TextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); - - Propagation propagation = - new Propagation( - new TelemetryInfo( - tracer, - OpenTracingPropagators.builder() - .setTextMap(textMapPropagator) - .setHttpHeaders(httpHeadersPropagator) - .build())); - - assertThat(propagation.propagators().textMapPropagator()) - .isNotSameAs(propagation.propagators().httpHeadersPropagator()); - - assertThat(propagation.propagators().textMapPropagator()).isSameAs(textMapPropagator); - assertThat(propagation.propagators().httpHeadersPropagator()).isSameAs(httpHeadersPropagator); - } -} diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/ShimUtilTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/ShimUtilTest.java new file mode 100644 index 00000000000..c0960d3c6fd --- /dev/null +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/ShimUtilTest.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opentracingshim; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ShimUtilTest { + + private final SdkTracerProvider tracerSdkFactory = SdkTracerProvider.builder().build(); + private final Tracer tracer = tracerSdkFactory.get("SpanShimTest"); + private Span span; + + private static final String SPAN_NAME = "Span"; + + @BeforeEach + void setUp() { + span = tracer.spanBuilder(SPAN_NAME).startSpan(); + } + + @AfterEach + void tearDown() { + span.end(); + } + + @Test + void spanWrapper() { + SpanShim shim = new SpanShim(span); + assertThat(ShimUtil.getSpanShim(shim)).isEqualTo(shim); + assertThat(ShimUtil.getSpanShim(new SpanWrapper(shim))).isEqualTo(shim); + assertThat(ShimUtil.getSpanShim(new SpanWrapper("not a span"))).isNull(); + assertThat(ShimUtil.getSpanShim(null)).isNull(); + } + + @Test + void getContextShim() { + SpanContextShim contextShim = new SpanContextShim(span.getSpanContext(), Baggage.empty()); + assertThat(ShimUtil.getContextShim(contextShim)).isEqualTo(contextShim); + assertThat(ShimUtil.getContextShim(null)).isNull(); + } +} diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanBuilderShimTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanBuilderShimTest.java index cd780cbabf7..2c05435fa82 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanBuilderShimTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanBuilderShimTest.java @@ -5,31 +5,47 @@ package io.opentelemetry.opentracingshim; +import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.opentracingshim.TestUtils.getBaggageMap; import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.ReadWriteSpan; import io.opentelemetry.sdk.trace.ReadableSpan; import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.data.StatusData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.samplers.Sampler; import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import io.opentracing.References; +import io.opentracing.noop.NoopSpan; +import io.opentracing.tag.Tags; +import java.math.BigInteger; import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SpanBuilderShimTest { - private final SdkTracerProvider tracerSdkFactory = SdkTracerProvider.builder().build(); + private final SdkTracerProvider tracerSdkFactory = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); private final Tracer tracer = tracerSdkFactory.get("SpanShimTest"); - private final TelemetryInfo telemetryInfo = - new TelemetryInfo(tracer, OpenTracingPropagators.builder().build()); private static final String SPAN_NAME = "Span"; @@ -38,14 +54,179 @@ void setUp() { GlobalOpenTelemetry.resetForTest(); } + @Test + void default_values() { + SpanShim span = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + try { + SpanData spanData = ((ReadableSpan) span.getSpan()).toSpanData(); + assertThat(spanData.getName()).isEqualTo(SPAN_NAME); + assertThat(spanData.getStatus()).isEqualTo(StatusData.unset()); + assertThat(spanData.getSpanContext()).isNotEqualTo(SpanContext.getInvalid()); + assertThat(spanData.getKind()).isEqualTo(SpanKind.INTERNAL); + assertThat(spanData.getAttributes().size()).isEqualTo(0); + assertThat(spanData.getEvents()).hasSize(0); + assertThat(spanData.getLinks()).hasSize(0); + } finally { + span.finish(); + } + } + + @Test + void parent_single() { + SpanShim parentSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + try { + SpanShim childSpan = + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(parentSpan).start(); + + try { + SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData(); + assertThat(parentSpan.context().toSpanId()).isEqualTo(spanData.getParentSpanId()); + } finally { + childSpan.finish(); + } + } finally { + parentSpan.finish(); + } + } + + @Test + void noop_parent_span() { + SpanShim childSpan = + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(NoopSpan.INSTANCE).start(); + try { + SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData(); + assertThat(SpanId.isValid(spanData.getParentSpanId())).isFalse(); + } finally { + childSpan.finish(); + } + } + + @Test + void parent_multipleFollowsFrom() { + SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + + try { + SpanShim childSpan = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME) + .addReference(References.FOLLOWS_FROM, parentSpan1.context()) + .addReference(References.FOLLOWS_FROM, parentSpan2.context()) + .start(); + + try { + // If no parent of CHILD_OF type exists, use the first value as main parent. + SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData(); + assertThat(parentSpan1.context().toSpanId()).isEqualTo(spanData.getParentSpanId()); + } finally { + childSpan.finish(); + } + } finally { + parentSpan1.finish(); + parentSpan2.finish(); + } + } + + @Test + void parent_multipleDifferentRefType() { + SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + SpanShim parentSpan3 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + + try { + SpanShim childSpan = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME) + .addReference(References.FOLLOWS_FROM, parentSpan1.context()) + .addReference(References.CHILD_OF, parentSpan2.context()) + .addReference(References.CHILD_OF, parentSpan3.context()) + .start(); + + try { + // The first parent with CHILD_OF becomes the direct parent (if any). + SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData(); + assertThat(parentSpan2.context().toSpanId()).isEqualTo(spanData.getParentSpanId()); + } finally { + childSpan.finish(); + } + } finally { + parentSpan1.finish(); + parentSpan2.finish(); + parentSpan3.finish(); + } + } + + @Test + void parent_multipleLinks() { + SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + SpanShim parentSpan3 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + + try { + SpanShim childSpan = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME) + .addReference(References.FOLLOWS_FROM, parentSpan1.context()) + .addReference(References.CHILD_OF, parentSpan2.context()) + .addReference(References.FOLLOWS_FROM, parentSpan3.context()) + .start(); + + try { + SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData(); + List links = spanData.getLinks(); + assertThat(links).hasSize(3); + + assertThat(links.get(0).getSpanContext()).isEqualTo(parentSpan1.getSpan().getSpanContext()); + assertThat(links.get(1).getSpanContext()).isEqualTo(parentSpan2.getSpan().getSpanContext()); + assertThat(links.get(2).getSpanContext()).isEqualTo(parentSpan3.getSpan().getSpanContext()); + assertThat(links.get(0).getAttributes().get(stringKey("opentracing.ref_type"))) + .isEqualTo("follows_from"); + assertThat(links.get(1).getAttributes().get(stringKey("opentracing.ref_type"))) + .isEqualTo("child_of"); + assertThat(links.get(2).getAttributes().get(stringKey("opentracing.ref_type"))) + .isEqualTo("follows_from"); + + } finally { + childSpan.finish(); + } + } finally { + parentSpan1.finish(); + parentSpan2.finish(); + parentSpan3.finish(); + } + } + + @Test + void parent_wrongRefType() { + SpanShim parentSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + try { + SpanShim childSpan = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME) + .addReference("wrongreftype-value", parentSpan.context()) + .start(); + + try { + // Incorrect typeref values get discarded. + SpanData spanData = ((ReadableSpan) childSpan.getSpan()).toSpanData(); + assertThat(spanData.getParentSpanContext()).isEqualTo(SpanContext.getInvalid()); + assertThat(spanData.getLinks()).isEmpty(); + } finally { + childSpan.finish(); + } + } finally { + parentSpan.finish(); + } + } + @Test void baggage_parent() { - SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start(); + SpanShim parentSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); try { parentSpan.setBaggageItem("key1", "value1"); SpanShim childSpan = - (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan).start(); + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(parentSpan).start(); try { assertThat("value1").isEqualTo(childSpan.getBaggageItem("key1")); assertThat(getBaggageMap(parentSpan.context().baggageItems())) @@ -58,15 +239,58 @@ void baggage_parent() { } } + @Test + void baggage_explicitParent_inParentContext() { + AtomicReference parentContextBaggage = new AtomicReference<>(); + SdkTracerProvider tracerSdkFactory = + SdkTracerProvider.builder() + .addSpanProcessor( + new SpanProcessor() { + @Override + public void onStart(Context parentContext, ReadWriteSpan span) { + parentContextBaggage.set(Baggage.fromContext(parentContext)); + } + + @Override + public boolean isStartRequired() { + return true; + } + + @Override + public void onEnd(ReadableSpan span) {} + + @Override + public boolean isEndRequired() { + return false; + } + }) + .build(); + Tracer tracer = tracerSdkFactory.get("SpanShimTest"); + + SpanShim parentSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + try { + parentSpan.setBaggageItem("key1", "value1"); + + SpanShim childSpan = + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(parentSpan).start(); + try { + assertThat(parentContextBaggage.get().getEntryValue("key1")).isEqualTo("value1"); + } finally { + childSpan.finish(); + } + } finally { + parentSpan.finish(); + } + } + @Test void baggage_parentContext() { - SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start(); + SpanShim parentSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); try { parentSpan.setBaggageItem("key1", "value1"); SpanShim childSpan = - (SpanShim) - new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan.context()).start(); + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(parentSpan.context()).start(); try { assertThat("value1").isEqualTo(childSpan.getBaggageItem("key1")); assertThat(getBaggageMap(parentSpan.context().baggageItems())) @@ -79,14 +303,59 @@ void baggage_parentContext() { } } + @Test + void baggage_multipleParents() { + SpanShim parentSpan1 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + SpanShim parentSpan2 = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); + try { + parentSpan1.setBaggageItem("key1", "value1"); + parentSpan2.setBaggageItem("key2", "value2"); + + SpanShim childSpan = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME) + .addReference(References.FOLLOWS_FROM, parentSpan1.context()) + .addReference(References.CHILD_OF, parentSpan2.context()) + .start(); + try { + assertThat(childSpan.getBaggageItem("key1")).isEqualTo("value1"); + assertThat(childSpan.getBaggageItem("key2")).isEqualTo("value2"); + } finally { + childSpan.finish(); + } + } finally { + parentSpan1.finish(); + parentSpan2.finish(); + } + } + + @Test + void baggage_spanWithInvalidSpan() { + Baggage baggage = Baggage.builder().put("foo", "bar").build(); + SpanShim span = new SpanShim(Span.getInvalid(), baggage); + + SpanShim childSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(span).start(); + assertThat(childSpan.getBaggage()).isEqualTo(baggage); + } + + @Test + void baggage_spanContextWithInvalidSpan() { + Baggage baggage = Baggage.builder().put("foo", "bar").build(); + SpanContextShim spanContext = new SpanContextShim(Span.getInvalid().getSpanContext(), baggage); + + SpanShim childSpan = + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(spanContext).start(); + assertThat(childSpan.getBaggage()).isEqualTo(baggage); + } + @Test void parent_NullContextShim() { /* SpanContextShim is null until Span.context() or Span.getBaggageItem() are called. * Verify a null SpanContextShim in the parent is handled properly. */ - SpanShim parentSpan = (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).start(); + SpanShim parentSpan = (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).start(); try { SpanShim childSpan = - (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).asChildOf(parentSpan).start(); + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).asChildOf(parentSpan).start(); try { assertThat(childSpan.context().baggageItems().iterator().hasNext()).isFalse(); } finally { @@ -101,21 +370,75 @@ void parent_NullContextShim() { void withStartTimestamp() { long micros = 123447307984L; SpanShim spanShim = - (SpanShim) new SpanBuilderShim(telemetryInfo, SPAN_NAME).withStartTimestamp(micros).start(); + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).withStartTimestamp(micros).start(); SpanData spanData = ((ReadableSpan) spanShim.getSpan()).toSpanData(); assertThat(spanData.getStartEpochNanos()).isEqualTo(micros * 1000L); } + @Test + void setAttribute_errorAsBoolean() { + SpanShim span1 = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME).withTag(Tags.ERROR.getKey(), true).start(); + SpanShim span2 = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME).withTag(Tags.ERROR.getKey(), false).start(); + try { + SpanData spanData1 = ((ReadableSpan) span1.getSpan()).toSpanData(); + assertThat(spanData1.getStatus()).isEqualTo(StatusData.error()); + + SpanData spanData2 = ((ReadableSpan) span2.getSpan()).toSpanData(); + assertThat(spanData2.getStatus()).isEqualTo(StatusData.ok()); + } finally { + span1.finish(); + span2.finish(); + } + } + + @Test + void setAttribute_errorAsString() { + SpanShim span1 = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME).withTag(Tags.ERROR.getKey(), "tRuE").start(); + SpanShim span2 = + (SpanShim) + new SpanBuilderShim(tracer, SPAN_NAME).withTag(Tags.ERROR.getKey(), "FaLsE").start(); + try { + SpanData spanData1 = ((ReadableSpan) span1.getSpan()).toSpanData(); + assertThat(spanData1.getStatus()).isEqualTo(StatusData.error()); + + SpanData spanData2 = ((ReadableSpan) span2.getSpan()).toSpanData(); + assertThat(spanData2.getStatus()).isEqualTo(StatusData.ok()); + } finally { + span1.finish(); + span2.finish(); + } + } + + @Test + void setAttribute_unrecognizedType() { + SpanShim span = + (SpanShim) new SpanBuilderShim(tracer, SPAN_NAME).withTag("foo", BigInteger.TEN).start(); + try { + SpanData spanData = ((ReadableSpan) span.getSpan()).toSpanData(); + assertThat(spanData.getAttributes().size()).isEqualTo(1); + assertThat(spanData.getAttributes().get(stringKey("foo"))).isEqualTo("10"); + } finally { + span.finish(); + } + } + @Test void setAttributes_beforeSpanStart() { SdkTracerProvider tracerSdkFactory = - SdkTracerProvider.builder().setSampler(SamplingPrioritySampler.INSTANCE).build(); + SdkTracerProvider.builder() + .setSampler(SamplingPrioritySampler.INSTANCE) + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); Tracer tracer = tracerSdkFactory.get("SpanShimTest"); - TelemetryInfo telemetryInfo = - new TelemetryInfo(tracer, OpenTracingPropagators.builder().build()); - SpanBuilderShim spanBuilder1 = new SpanBuilderShim(telemetryInfo, SPAN_NAME); - SpanBuilderShim spanBuilder2 = new SpanBuilderShim(telemetryInfo, SPAN_NAME); + SpanBuilderShim spanBuilder1 = new SpanBuilderShim(tracer, SPAN_NAME); + SpanBuilderShim spanBuilder2 = new SpanBuilderShim(tracer, SPAN_NAME); SpanShim span1 = (SpanShim) spanBuilder1 diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanShimTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanShimTest.java index 5ecb3d9d87d..fb38c9688b3 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanShimTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanShimTest.java @@ -5,6 +5,7 @@ package io.opentelemetry.opentracingshim; +import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.opentracingshim.TestUtils.getBaggageMap; import static org.assertj.core.api.Assertions.assertThat; @@ -15,27 +16,36 @@ import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; +import io.opentelemetry.sdk.trace.data.StatusData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentracing.log.Fields; +import io.opentracing.tag.Tags; +import java.math.BigInteger; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class SpanShimTest { - private final SdkTracerProvider tracerSdkFactory = SdkTracerProvider.builder().build(); + private final SdkTracerProvider tracerSdkFactory = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); private final Tracer tracer = tracerSdkFactory.get("SpanShimTest"); - private final TelemetryInfo telemetryInfo = - new TelemetryInfo(tracer, OpenTracingPropagators.builder().build()); private Span span; private static final String SPAN_NAME = "Span"; @BeforeEach void setUp() { - span = telemetryInfo.tracer().spanBuilder(SPAN_NAME).startSpan(); + span = tracer.spanBuilder(SPAN_NAME).startSpan(); } @AfterEach @@ -45,19 +55,55 @@ void tearDown() { @Test void context_simple() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); SpanContextShim contextShim = (SpanContextShim) spanShim.context(); assertThat(contextShim).isNotNull(); assertThat(span.getSpanContext()).isEqualTo(contextShim.getSpanContext()); - assertThat(span.getSpanContext().getTraceId().toString()).isEqualTo(contextShim.toTraceId()); - assertThat(span.getSpanContext().getSpanId().toString()).isEqualTo(contextShim.toSpanId()); + assertThat(span.getSpanContext().getTraceId()).isEqualTo(contextShim.toTraceId()); + assertThat(span.getSpanContext().getSpanId()).isEqualTo(contextShim.toSpanId()); assertThat(contextShim.baggageItems().iterator().hasNext()).isFalse(); } + @Test + void setAttribute_errorAsBoolean() { + SpanShim spanShim = new SpanShim(span); + spanShim.setTag(Tags.ERROR.getKey(), true); + + SpanData spanData = ((ReadableSpan) span).toSpanData(); + assertThat(spanData.getStatus()).isEqualTo(StatusData.error()); + + spanShim.setTag(Tags.ERROR.getKey(), false); + spanData = ((ReadableSpan) span).toSpanData(); + assertThat(spanData.getStatus()).isEqualTo(StatusData.ok()); + } + + @Test + void setAttribute_errorAsString() { + SpanShim spanShim = new SpanShim(span); + spanShim.setTag(Tags.ERROR.getKey(), "tRuE"); + + SpanData spanData = ((ReadableSpan) span).toSpanData(); + assertThat(spanData.getStatus()).isEqualTo(StatusData.error()); + + spanShim.setTag(Tags.ERROR.getKey(), "FaLsE"); + spanData = ((ReadableSpan) span).toSpanData(); + assertThat(spanData.getStatus()).isEqualTo(StatusData.ok()); + } + + @Test + void setAttribute_unrecognizedType() { + SpanShim spanShim = new SpanShim(span); + spanShim.setTag("foo", BigInteger.ONE); + + SpanData spanData = ((ReadableSpan) span).toSpanData(); + assertThat(spanData.getAttributes().size()).isEqualTo(1); + assertThat(spanData.getAttributes().get(stringKey("foo"))).isEqualTo("1"); + } + @Test void baggage() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); spanShim.setBaggageItem("key1", "value1"); spanShim.setBaggageItem("key2", "value2"); @@ -74,7 +120,7 @@ void baggage() { @Test void baggage_replacement() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); SpanContextShim contextShim1 = (SpanContextShim) spanShim.context(); spanShim.setBaggageItem("key1", "value1"); @@ -84,24 +130,26 @@ void baggage_replacement() { assertThat(contextShim2.baggageItems().iterator()).hasNext(); /* updated, with values */ } + @SuppressWarnings("FutureReturnValueIgnored") @Test - void baggage_differentShimObjs() { - SpanShim spanShim1 = new SpanShim(telemetryInfo, span); - spanShim1.setBaggageItem("key1", "value1"); - - /* Baggage should be synchronized among different SpanShim objects - * referring to the same Span.*/ - SpanShim spanShim2 = new SpanShim(telemetryInfo, span); - spanShim2.setBaggageItem("key1", "value2"); - assertThat(spanShim1.getBaggageItem("key1")).isEqualTo("value2"); - assertThat(spanShim2.getBaggageItem("key1")).isEqualTo("value2"); - assertThat(getBaggageMap(spanShim2.context().baggageItems())) - .isEqualTo(getBaggageMap(spanShim1.context().baggageItems())); + void baggage_multipleThreads() throws Exception { + ExecutorService executor = Executors.newCachedThreadPool(); + SpanShim spanShim = new SpanShim(span); + int baggageItemsCount = 100; + + IntStream.range(0, baggageItemsCount) + .forEach(i -> executor.execute(() -> spanShim.setBaggageItem("key-" + i, "value-" + i))); + executor.shutdown(); + executor.awaitTermination(10, TimeUnit.SECONDS); + + for (int i = 0; i < baggageItemsCount; i++) { + assertThat(spanShim.getBaggageItem("key-" + i)).isEqualTo("value-" + i); + } } @Test void finish_micros() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); long micros = 123447307984L; spanShim.finish(micros); SpanData spanData = ((ReadableSpan) span).toSpanData(); @@ -110,7 +158,7 @@ void finish_micros() { @Test public void log_error() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); Map fields = createErrorFields(); spanShim.log(fields); SpanData spanData = ((ReadableSpan) span).toSpanData(); @@ -119,7 +167,7 @@ public void log_error() { @Test public void log_error_with_timestamp() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); Map fields = createErrorFields(); long micros = 123447307984L; spanShim.log(micros, fields); @@ -129,7 +177,7 @@ public void log_error_with_timestamp() { @Test public void log_exception() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); Map fields = createExceptionFields(); spanShim.log(fields); SpanData spanData = ((ReadableSpan) span).toSpanData(); @@ -140,7 +188,7 @@ public void log_exception() { @Test public void log_error_with_exception() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); Map fields = createExceptionFields(); fields.putAll(createErrorFields()); @@ -152,7 +200,7 @@ public void log_error_with_exception() { @Test public void log_exception_with_timestamp() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); Map fields = createExceptionFields(); long micros = 123447307984L; spanShim.log(micros, fields); @@ -164,7 +212,7 @@ public void log_exception_with_timestamp() { @Test public void log_fields() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); spanShim.log(putKeyValuePairsToMap(new HashMap<>())); SpanData spanData = ((ReadableSpan) span).toSpanData(); verifyAttributes(spanData.getEvents().get(0)); @@ -172,7 +220,7 @@ public void log_fields() { @Test void log_micros() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); long micros = 123447307984L; spanShim.log(micros, "event"); SpanData spanData = ((ReadableSpan) span).toSpanData(); @@ -181,7 +229,7 @@ void log_micros() { @Test void log_fields_micros() { - SpanShim spanShim = new SpanShim(telemetryInfo, span); + SpanShim spanShim = new SpanShim(span); long micros = 123447307984L; spanShim.log(micros, putKeyValuePairsToMap(new HashMap<>())); SpanData spanData = ((ReadableSpan) span).toSpanData(); @@ -232,28 +280,15 @@ private static void verifyExceptionEvent(SpanData spanData) { EventData eventData = spanData.getEvents().get(0); assertThat(eventData.getName()).isEqualTo("exception"); - assertThat( - eventData - .getAttributes() - .get(AttributeKey.stringKey(SemanticAttributes.EXCEPTION_TYPE.getKey()))) - .isEqualTo("kind"); - assertThat( - eventData - .getAttributes() - .get(AttributeKey.stringKey(SemanticAttributes.EXCEPTION_MESSAGE.getKey()))) - .isEqualTo("message"); - assertThat( - eventData - .getAttributes() - .get(AttributeKey.stringKey(SemanticAttributes.EXCEPTION_STACKTRACE.getKey()))) - .isEqualTo("stack"); + assertThat(eventData.getAttributes().get(stringKey("exception.type"))).isEqualTo("kind"); + assertThat(eventData.getAttributes().get(stringKey("exception.message"))).isEqualTo("message"); + assertThat(eventData.getAttributes().get(stringKey("exception.stacktrace"))).isEqualTo("stack"); verifyAttributes(eventData); } private static void verifyAttributes(EventData eventData) { - assertThat(eventData.getAttributes().get(AttributeKey.stringKey("keyForString"))) - .isEqualTo("value"); + assertThat(eventData.getAttributes().get(stringKey("keyForString"))).isEqualTo("value"); assertThat(eventData.getAttributes().get(AttributeKey.longKey("keyForInt"))).isEqualTo(1); assertThat(eventData.getAttributes().get(AttributeKey.doubleKey("keyForDouble"))) .isEqualTo(1.0); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanWrapper.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanWrapper.java new file mode 100644 index 00000000000..4cfa03fd4a7 --- /dev/null +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/SpanWrapper.java @@ -0,0 +1,92 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.opentracingshim; + +import io.opentracing.Span; +import io.opentracing.SpanContext; +import io.opentracing.tag.Tag; +import java.util.Map; +import java.util.function.Supplier; + +class SpanWrapper implements Span, Supplier { + // it's Object to simulate errors + private final Object span; + + public SpanWrapper(Object span) { + this.span = span; + } + + @Override + public Object get() { + return span; + } + + @Override + public SpanContext context() { + return null; + } + + @Override + public Span setTag(String key, String value) { + return null; + } + + @Override + public Span setTag(String key, boolean value) { + return null; + } + + @Override + public Span setTag(String key, Number value) { + return null; + } + + @Override + public Span setTag(Tag tag, T value) { + return null; + } + + @Override + public Span log(Map fields) { + return null; + } + + @Override + public Span log(long timestampMicroseconds, Map fields) { + return null; + } + + @Override + public Span log(String event) { + return null; + } + + @Override + public Span log(long timestampMicroseconds, String event) { + return null; + } + + @Override + public Span setBaggageItem(String key, String value) { + return null; + } + + @Override + public String getBaggageItem(String key) { + return null; + } + + @Override + public Span setOperationName(String operationName) { + return null; + } + + @Override + public void finish() {} + + @Override + public void finish(long finishMicros) {} +} diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/TracerShimTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/TracerShimTest.java index c760671d5af..199b6209e26 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/TracerShimTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/TracerShimTest.java @@ -6,12 +6,31 @@ package io.opentelemetry.opentracingshim; import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.trace.Tracer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; + +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.propagation.TextMapGetter; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.context.propagation.TextMapSetter; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; +import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentracing.Scope; import io.opentracing.Span; import io.opentracing.SpanContext; +import io.opentracing.Tracer; import io.opentracing.propagation.Format; import io.opentracing.propagation.TextMapAdapter; import io.opentracing.tag.BooleanTag; @@ -19,30 +38,43 @@ import io.opentracing.tag.StringTag; import io.opentracing.tag.Tag; import io.opentracing.tag.Tags; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import javax.annotation.Nullable; +import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +@SuppressWarnings("deprecation") // testing deprecated shim API class TracerShimTest { static final io.opentelemetry.api.trace.Span INVALID_SPAN = io.opentelemetry.api.trace.Span.getInvalid(); - static final io.opentelemetry.api.baggage.Baggage EMPTY_BAGGAGE = - io.opentelemetry.api.baggage.Baggage.empty(); + static final Baggage EMPTY_BAGGAGE = Baggage.empty(); - @RegisterExtension public OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); + @RegisterExtension + static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); TracerShim tracerShim; - Tracer tracer; + TracerProvider provider; @BeforeEach void setUp() { - tracer = otelTesting.getOpenTelemetry().getTracer("opentracingshim"); - tracerShim = - new TracerShim(new TelemetryInfo(tracer, OpenTracingPropagators.builder().build())); + GlobalOpenTelemetry.resetForTest(); + GlobalOpenTelemetry.set(otelTesting.getOpenTelemetry()); + + provider = otelTesting.getOpenTelemetry().getTracerProvider(); + TextMapPropagator propagator = + otelTesting.getOpenTelemetry().getPropagators().getTextMapPropagator(); + tracerShim = new TracerShim(provider, propagator, propagator); + } + + @AfterEach + void cleanup() { + GlobalOpenTelemetry.resetForTest(); } @Test @@ -61,7 +93,7 @@ void activateSpan() { assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); try (Scope scope = tracerShim.activateSpan(otSpan)) { assertThat(tracerShim.activeSpan()).isNotNull(); @@ -71,13 +103,13 @@ void activateSpan() { .isSameAs(actualSpan); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(actualSpan); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } @Test @@ -85,7 +117,7 @@ void activateNullSpan() { assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); Span otSpan = tracerShim.buildSpan("one").start(); io.opentelemetry.api.trace.Span actualSpan = ((SpanShim) otSpan).getSpan(); @@ -102,7 +134,7 @@ void activateNullSpan() { assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } @Test @@ -112,19 +144,14 @@ void activateSpan_withBaggage() { otSpan.setBaggageItem("hello", "world"); io.opentelemetry.api.trace.Span actualSpan = ((SpanShim) otSpan).getSpan(); - io.opentelemetry.api.baggage.Baggage actualBaggage = - ((SpanContextShim) otSpan.context()).getBaggage(); - assertThat( - io.opentelemetry.api.baggage.Baggage.builder() - .put("foo", "bar") - .put("hello", "world") - .build()) + Baggage actualBaggage = ((SpanContextShim) otSpan.context()).getBaggage(); + assertThat(Baggage.builder().put("foo", "bar").put("hello", "world").build()) .isEqualTo(actualBaggage); assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); try (Scope scope = tracerShim.activateSpan(otSpan)) { assertThat(tracerShim.activeSpan()).isNotNull(); @@ -134,31 +161,32 @@ void activateSpan_withBaggage() { .isSameAs(actualSpan); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(actualSpan); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(actualBaggage); + assertThat(Baggage.current()).isSameAs(actualBaggage); + + Span child = tracerShim.buildSpan("child").start(); + assertThat(child.getBaggageItem("foo")).isEqualTo("bar"); } assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } - /* If the Span has no baggage, allow any previously active Baggage go through */ + /* A Span should activate its related Baggage, which may mean implicitly + * overriding any previous current Baggage value */ @Test public void activateSpan_withExistingBaggage() { + /* Span has empty Baggage as there's no parent nor previously set Baggage */ Span otSpan = tracerShim.buildSpan("one").start(); io.opentelemetry.api.trace.Span actualSpan = ((SpanShim) otSpan).getSpan(); - io.opentelemetry.api.baggage.Baggage otherBaggage = - io.opentelemetry.api.baggage.Baggage.builder() - .put("foo", "bar") - .put("hello", "world") - .build(); + Baggage otherBaggage = Baggage.builder().put("foo", "bar").put("hello", "world").build(); assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); try (io.opentelemetry.context.Scope scope1 = otherBaggage.makeCurrent()) { try (Scope scope2 = tracerShim.activateSpan(otSpan)) { @@ -169,14 +197,14 @@ public void activateSpan_withExistingBaggage() { .isSameAs(actualSpan); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(actualSpan); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(otherBaggage); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } } assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } /* @@ -192,7 +220,7 @@ void activateSpan_cacheSpanShim() { assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); try (Scope scope = tracerShim.activateSpan(otSpan)) { assertThat(tracerShim.activeSpan()).isSameAs(tracerShim.activeSpan()); @@ -204,7 +232,7 @@ void activateSpan_cacheSpanShim() { assertThat(tracerShim.activeSpan()).isNull(); assertThat(tracerShim.scopeManager().activeSpan()).isNull(); assertThat(io.opentelemetry.api.trace.Span.current()).isSameAs(INVALID_SPAN); - assertThat(io.opentelemetry.api.baggage.Baggage.current()).isSameAs(EMPTY_BAGGAGE); + assertThat(Baggage.current()).isSameAs(EMPTY_BAGGAGE); } /* @@ -226,6 +254,20 @@ void activateSpan_withoutShim() { assertThat(tracerShim.scopeManager().activeSpan()).isNull(); } + @Test + void activeSpan_onlyBaggage() { + Baggage baggage = Baggage.builder().put("foo", "bar").build(); + + try (io.opentelemetry.context.Scope scope = Context.root().with(baggage).makeCurrent()) { + Span span = tracerShim.activeSpan(); + assertThat(span).isNotNull(); + + SpanShim spanShim = (SpanShim) span; + assertThat(spanShim.getSpan()).isSameAs(INVALID_SPAN); + assertThat(spanShim.getBaggage()).isSameAs(baggage); + } + } + @Test void extract_nullContext() { SpanContext result = @@ -234,27 +276,29 @@ void extract_nullContext() { } @Test + @SuppressLogger(TracerShim.class) void inject_nullContext() { Map map = new HashMap<>(); tracerShim.inject(null, Format.Builtin.TEXT_MAP, new TextMapAdapter(map)); assertThat(map).isEmpty(); } + @Test + @SuppressLogger(TracerShim.class) + void inject_invalid() { + Map map = new HashMap<>(); + tracerShim.inject(mock(SpanContext.class), Format.Builtin.TEXT_MAP, new TextMapAdapter(map)); + assertThat(map).isEmpty(); + } + @Test void inject_textMap() { Map map = new HashMap<>(); CustomTextMapPropagator textMapPropagator = new CustomTextMapPropagator(); CustomTextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); - TelemetryInfo telemetryInfo = - new TelemetryInfo( - tracer, - OpenTracingPropagators.builder() - .setTextMap(textMapPropagator) - .setHttpHeaders(httpHeadersPropagator) - .build()); - tracerShim = new TracerShim(telemetryInfo); - io.opentelemetry.api.trace.Span span = telemetryInfo.tracer().spanBuilder("span").startSpan(); - SpanContext context = new SpanShim(telemetryInfo, span).context(); + tracerShim = new TracerShim(provider, textMapPropagator, httpHeadersPropagator); + io.opentelemetry.api.trace.Span span = tracerShim.tracer().spanBuilder("span").startSpan(); + SpanContext context = new SpanShim(span).context(); tracerShim.inject(context, Format.Builtin.TEXT_MAP, new TextMapAdapter(map)); assertThat(textMapPropagator.isInjected()).isTrue(); @@ -266,16 +310,9 @@ void inject_httpHeaders() { Map map = new HashMap<>(); CustomTextMapPropagator textMapPropagator = new CustomTextMapPropagator(); CustomTextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); - TelemetryInfo telemetryInfo = - new TelemetryInfo( - tracer, - OpenTracingPropagators.builder() - .setTextMap(textMapPropagator) - .setHttpHeaders(httpHeadersPropagator) - .build()); - tracerShim = new TracerShim(telemetryInfo); - io.opentelemetry.api.trace.Span span = telemetryInfo.tracer().spanBuilder("span").startSpan(); - SpanContext context = new SpanShim(telemetryInfo, span).context(); + tracerShim = new TracerShim(provider, textMapPropagator, httpHeadersPropagator); + io.opentelemetry.api.trace.Span span = tracerShim.tracer().spanBuilder("span").startSpan(); + SpanContext context = new SpanShim(span).context(); tracerShim.inject(context, Format.Builtin.HTTP_HEADERS, new TextMapAdapter(map)); assertThat(textMapPropagator.isInjected()).isFalse(); @@ -287,14 +324,7 @@ void extract_textMap() { Map map = new HashMap<>(); CustomTextMapPropagator textMapPropagator = new CustomTextMapPropagator(); CustomTextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); - tracerShim = - new TracerShim( - new TelemetryInfo( - tracer, - OpenTracingPropagators.builder() - .setTextMap(textMapPropagator) - .setHttpHeaders(httpHeadersPropagator) - .build())); + tracerShim = new TracerShim(provider, textMapPropagator, httpHeadersPropagator); tracerShim.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(map)); assertThat(textMapPropagator.isExtracted()).isTrue(); @@ -306,14 +336,7 @@ void extract_httpHeaders() { Map map = new HashMap<>(); CustomTextMapPropagator textMapPropagator = new CustomTextMapPropagator(); CustomTextMapPropagator httpHeadersPropagator = new CustomTextMapPropagator(); - tracerShim = - new TracerShim( - new TelemetryInfo( - tracer, - OpenTracingPropagators.builder() - .setTextMap(textMapPropagator) - .setHttpHeaders(httpHeadersPropagator) - .build())); + tracerShim = new TracerShim(provider, textMapPropagator, httpHeadersPropagator); tracerShim.extract(Format.Builtin.HTTP_HEADERS, new TextMapAdapter(map)); assertThat(textMapPropagator.isExtracted()).isFalse(); @@ -321,8 +344,88 @@ void extract_httpHeaders() { } @Test - void close() { + void extract_onlyBaggage() { + W3CBaggagePropagator propagator = W3CBaggagePropagator.getInstance(); + tracerShim = new TracerShim(provider, propagator, TextMapPropagator.noop()); + + Baggage baggage = Baggage.builder().put("foo", "bar").build(); + Map map = new HashMap<>(); + propagator.inject(Context.root().with(baggage), map, Map::put); + + SpanContext spanContext = tracerShim.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(map)); + SpanContextShim spanContextShim = (SpanContextShim) spanContext; + assertThat(spanContextShim.getSpanContext().isValid()).isFalse(); + assertThat(spanContextShim.getBaggage()).isEqualTo(baggage); + } + + @Test + void extract_invalidButSampledSpanContext() { + tracerShim = + new TracerShim(provider, new InvalidButSampledPropagator(), TextMapPropagator.noop()); + + SpanContext spanContext = + tracerShim.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(new HashMap<>())); + + assertThat(spanContext).isNotNull(); + SpanContextShim spanContextShim = (SpanContextShim) spanContext; + assertThat(spanContextShim.getSpanContext().isValid()).isFalse(); + assertThat(spanContextShim.getSpanContext().isSampled()).isTrue(); + assertThat(spanContextShim.getBaggage().isEmpty()).isTrue(); + } + + @Test + void extract_emptyCarrier_withActiveSpan_returnsNull() { + Span span = tracerShim.buildSpan("one").start(); + try (Scope scope = tracerShim.activateSpan(span)) { + SpanContext result = + tracerShim.extract(Format.Builtin.TEXT_MAP, new TextMapAdapter(Collections.emptyMap())); + assertThat(result).isNull(); + } finally { + span.finish(); + } + } + + @Test + @SuppressLogger(TracerShim.class) + void close_OpenTelemetrySdk() { + SdkTracerProvider sdkProvider = mock(SdkTracerProvider.class); + doThrow(new RuntimeException("testing error")).when(sdkProvider).close(); + + Tracer tracerShim = + OpenTracingShim.createTracerShim( + OpenTelemetrySdk.builder().setTracerProvider(sdkProvider).build()); + tracerShim.close(); + + verify(sdkProvider).close(); + + Span otSpan = tracerShim.buildSpan(null).start(); + io.opentelemetry.api.trace.Span span = ((SpanShim) otSpan).getSpan(); + assertThat(span.getSpanContext().isValid()).isFalse(); + } + + @Test + @SuppressLogger(TracerShim.class) + void close_GlobalOpenTelemetry() { + GlobalOpenTelemetry.resetForTest(); + SdkTracerProvider sdkProvider = mock(SdkTracerProvider.class); + doThrow(new RuntimeException("testing error")).when(sdkProvider).close(); + GlobalOpenTelemetry.set(OpenTelemetrySdk.builder().setTracerProvider(sdkProvider).build()); + + Tracer tracerShim = OpenTracingShim.createTracerShim(GlobalOpenTelemetry.get()); + tracerShim.close(); + + verify(sdkProvider).close(); + + Span otSpan = tracerShim.buildSpan(null).start(); + io.opentelemetry.api.trace.Span span = ((SpanShim) otSpan).getSpan(); + assertThat(span.getSpanContext().isValid()).isFalse(); + } + + @Test + void close_NoopOpenTelemetry() { + Tracer tracerShim = OpenTracingShim.createTracerShim(OpenTelemetry.noop()); tracerShim.close(); + Span otSpan = tracerShim.buildSpan(null).start(); io.opentelemetry.api.trace.Span span = ((SpanShim) otSpan).getSpan(); assertThat(span.getSpanContext().isValid()).isFalse(); @@ -369,7 +472,8 @@ void doesNotCrash() { @Test void noopDoesNotCrash() { - tracerShim.close(); + Tracer tracerShim = OpenTracingShim.createTracerShim(OpenTelemetry.noop()); + Span span = tracerShim .buildSpan("test") @@ -386,4 +490,26 @@ void noopDoesNotCrash() { assertThat(((SpanShim) span).getSpan().isRecording()).isFalse(); } + + /** Extracts an invalid but sampled {@code SpanContext}, as {@code jaeger-debug-id} headers do. */ + private static class InvalidButSampledPropagator implements TextMapPropagator { + @Override + public Collection fields() { + return Collections.emptyList(); + } + + @Override + public void inject(Context context, @Nullable C carrier, TextMapSetter setter) {} + + @Override + public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { + return context.with( + io.opentelemetry.api.trace.Span.wrap( + io.opentelemetry.api.trace.SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.getSampled(), + TraceState.getDefault()))); + } + } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/OpenTelemetryInteroperabilityTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/OpenTelemetryInteroperabilityTest.java index 9b233349a0a..47fdb93046b 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/OpenTelemetryInteroperabilityTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/OpenTelemetryInteroperabilityTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +@SuppressWarnings("deprecation") // testing deprecated shim API class OpenTelemetryInteroperabilityTest { @RegisterExtension diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/TestUtils.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/TestUtils.java index c5ae9b180df..a8ccfde0a44 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/TestUtils.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/TestUtils.java @@ -130,7 +130,6 @@ public static List sortByStartTime(List spans) { /** Asserts the specified {@code List} of {@code Span} belongs to the same trace. */ public static void assertSameTrace(List spans) { for (int i = 0; i < spans.size() - 1; i++) { - // TODO - Include nanos in this comparison. assertThat(spans.get(i).getEndEpochNanos()) .isLessThanOrEqualTo(spans.get(spans.size() - 1).getEndEpochNanos()); assertThat(spans.get(i).getTraceId()).isEqualTo(spans.get(spans.size() - 1).getTraceId()); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java index bbc6a9d0601..a6dd57e5969 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/activespanreplacement/ActiveSpanReplacementTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -@SuppressWarnings("FutureReturnValueIgnored") +@SuppressWarnings({"FutureReturnValueIgnored", "deprecation"}) class ActiveSpanReplacementTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -63,30 +63,29 @@ void test() throws Exception { private void submitAnotherTask(Span initialSpan) { - executor.submit( - () -> { - // Create a new Span for this task - Span taskSpan = tracer.buildSpan("task").start(); - try (Scope scope = tracer.scopeManager().activate(taskSpan)) { + executor.submit(() -> { + // Create a new Span for this task + Span taskSpan = tracer.buildSpan("task").start(); + try (Scope scope = tracer.scopeManager().activate(taskSpan)) { - // Simulate work strictly related to the initial Span - // and finish it. - try (Scope initialScope = tracer.scopeManager().activate(initialSpan)) { - sleep(50); - } finally { - initialSpan.finish(); - } + // Simulate work strictly related to the initial Span + // and finish it. + try (Scope initialScope = tracer.scopeManager().activate(initialSpan)) { + sleep(50); + } finally { + initialSpan.finish(); + } - // Restore the span for this task and create a subspan - Span subTaskSpan = tracer.buildSpan("subtask").start(); - try (Scope subTaskScope = tracer.scopeManager().activate(subTaskSpan)) { - sleep(50); - } finally { - subTaskSpan.finish(); - } - } finally { - taskSpan.finish(); - } - }); + // Restore the span for this task and create a subspan + Span subTaskSpan = tracer.buildSpan("subtask").start(); + try (Scope subTaskScope = tracer.scopeManager().activate(subTaskSpan)) { + sleep(50); + } finally { + subTaskSpan.finish(); + } + } finally { + taskSpan.finish(); + } + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java index 8cb9c38648f..2a07c13b32b 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/Actor.java @@ -36,50 +36,48 @@ public void close() { public Future tell(String message) { Span parent = tracer.scopeManager().activeSpan(); phaser.register(); - return executor.submit( - () -> { - Span child = + return executor.submit(() -> { + Span child = + tracer + .buildSpan("received") + .addReference(References.FOLLOWS_FROM, parent.context()) + .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER) + .start(); + try (Scope scope = tracer.activateSpan(child)) { + phaser.arriveAndAwaitAdvance(); // child tracer started + child.log("received " + message); + phaser.arriveAndAwaitAdvance(); // assert size + } finally { + child.finish(); + } + + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + }); + } + + public Future ask(String message) { + Span parent = tracer.scopeManager().activeSpan(); + phaser.register(); + Future future = + executor.submit(() -> { + Span span = tracer .buildSpan("received") .addReference(References.FOLLOWS_FROM, parent.context()) .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER) .start(); - try (Scope scope = tracer.activateSpan(child)) { + try { phaser.arriveAndAwaitAdvance(); // child tracer started - child.log("received " + message); phaser.arriveAndAwaitAdvance(); // assert size + return "received " + message; } finally { - child.finish(); - } + span.finish(); - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + } }); - } - - public Future ask(String message) { - Span parent = tracer.scopeManager().activeSpan(); - phaser.register(); - Future future = - executor.submit( - () -> { - Span span = - tracer - .buildSpan("received") - .addReference(References.FOLLOWS_FROM, parent.context()) - .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CONSUMER) - .start(); - try { - phaser.arriveAndAwaitAdvance(); // child tracer started - phaser.arriveAndAwaitAdvance(); // assert size - return "received " + message; - } finally { - span.finish(); - - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size - } - }); return future; } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/ActorPropagationTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/ActorPropagationTest.java index 64f0595f2f3..d865f705352 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/ActorPropagationTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/actorpropagation/ActorPropagationTest.java @@ -5,11 +5,8 @@ package io.opentelemetry.opentracingshim.testbed.actorpropagation; -import static io.opentelemetry.opentracingshim.testbed.TestUtils.getByKind; -import static io.opentelemetry.opentracingshim.testbed.TestUtils.getOneByKind; import static org.assertj.core.api.Assertions.assertThat; -import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.opentracingshim.OpenTracingShim; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; import io.opentelemetry.sdk.trace.data.SpanData; @@ -32,7 +29,7 @@ *

    For improved readability, ignore the phaser lines as those are there to ensure deterministic * execution for the tests without sleeps. */ -@SuppressWarnings("FutureReturnValueIgnored") +@SuppressWarnings({"FutureReturnValueIgnored", "deprecation"}) class ActorPropagationTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -67,14 +64,11 @@ void testActorTell() { phaser.arriveAndAwaitAdvance(); // continue... phaser.arriveAndAwaitAdvance(); // child tracer finished assertThat(otelTesting.getSpans().size()).isEqualTo(3); - assertThat(getByKind(otelTesting.getSpans(), SpanKind.CONSUMER)).hasSize(2); phaser.arriveAndDeregister(); // continue... List finished = otelTesting.getSpans(); assertThat(finished.size()).isEqualTo(3); assertThat(finished.get(0).getTraceId()).isEqualTo(finished.get(1).getTraceId()); - assertThat(getByKind(finished, SpanKind.CONSUMER)).hasSize(2); - assertThat(getOneByKind(finished, SpanKind.PRODUCER)).isNotNull(); assertThat(tracer.scopeManager().activeSpan()).isNull(); } @@ -103,7 +97,6 @@ void testActorAsk() throws ExecutionException, InterruptedException { phaser.arriveAndAwaitAdvance(); // continue... phaser.arriveAndAwaitAdvance(); // child tracer finished assertThat(otelTesting.getSpans().size()).isEqualTo(3); - assertThat(getByKind(otelTesting.getSpans(), SpanKind.CONSUMER)).hasSize(2); phaser.arriveAndDeregister(); // continue... List finished = otelTesting.getSpans(); @@ -114,8 +107,6 @@ void testActorAsk() throws ExecutionException, InterruptedException { assertThat(finished.size()).isEqualTo(3); assertThat(finished.get(0).getTraceId()).isEqualTo(finished.get(1).getTraceId()); - assertThat(getByKind(finished, SpanKind.CONSUMER)).hasSize(2); - assertThat(getOneByKind(finished, SpanKind.PRODUCER)).isNotNull(); assertThat(tracer.scopeManager().activeSpan()).isNull(); } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java index 66c024e19fe..b270fe3dbe3 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/baggagehandling/BaggageHandlingTest.java @@ -18,6 +18,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +@SuppressWarnings("deprecation") // testing deprecated shim API public final class BaggageHandlingTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -31,26 +32,25 @@ void test_multithreaded() throws Exception { span.setBaggageItem("key1", "value1"); Future f = - executor.submit( - () -> { - /* Override the previous value... */ - span.setBaggageItem("key1", "value2"); - - /* add a new baggage item... */ - span.setBaggageItem("newkey", "newvalue"); - - /* have a child that updates its own baggage - * (should not be reflected in the original Span). */ - Span childSpan = tracer.buildSpan("child").start(); - try { - childSpan.setBaggageItem("key1", "childvalue"); - } finally { - childSpan.finish(); - } - - /* and finish the Span. */ - span.finish(); - }); + executor.submit(() -> { + /* Override the previous value... */ + span.setBaggageItem("key1", "value2"); + + /* add a new baggage item... */ + span.setBaggageItem("newkey", "newvalue"); + + /* have a child that updates its own baggage + * (should not be reflected in the original Span). */ + Span childSpan = tracer.buildSpan("child").start(); + try { + childSpan.setBaggageItem("key1", "childvalue"); + } finally { + childSpan.finish(); + } + + /* and finish the Span. */ + span.finish(); + }); /* Single call, no need to use await() */ f.get(5, TimeUnit.SECONDS); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/Client.java index 4da5ca1552d..51d6d3ab216 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/Client.java @@ -11,6 +11,7 @@ import io.opentracing.propagation.Format.Builtin; import io.opentracing.propagation.TextMapInjectAdapter; import io.opentracing.tag.Tags; +import java.util.Locale; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; @@ -38,7 +39,7 @@ public void send(boolean convertKeysToUpperCase) throws InterruptedException { if (convertKeysToUpperCase) { Message newMessage = new Message(); for (Map.Entry entry : message.entrySet()) { - newMessage.put(entry.getKey().toUpperCase(), entry.getValue()); + newMessage.put(entry.getKey().toUpperCase(Locale.getDefault()), entry.getValue()); } message = newMessage; } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/TestClientServerTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/TestClientServerTest.java index b88d780bb81..07565c31479 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/TestClientServerTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/clientserver/TestClientServerTest.java @@ -7,7 +7,6 @@ import static io.opentelemetry.opentracingshim.testbed.TestUtils.finishedSpansSize; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; import static org.awaitility.Awaitility.await; import static org.hamcrest.core.IsEqual.equalTo; @@ -24,6 +23,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; +@SuppressWarnings("deprecation") // testing deprecated shim API class TestClientServerTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -65,17 +65,8 @@ private void verify() { assertThat(finished).hasSize(2); assertThat(finished.get(1).getTraceId()).isEqualTo(finished.get(0).getTraceId()); - SpanKind firstSpanKind = finished.get(0).getKind(); - switch (firstSpanKind) { - case CLIENT: - assertThat(finished.get(1).getKind()).isEqualTo(SpanKind.SERVER); - break; - case SERVER: - assertThat(finished.get(1).getKind()).isEqualTo(SpanKind.CLIENT); - break; - default: - fail("Unexpected first span kind: " + firstSpanKind); - } + assertThat(finished.get(0).getKind()).isEqualTo(SpanKind.INTERNAL); // No semconv mapping. + assertThat(finished.get(1).getKind()).isEqualTo(SpanKind.INTERNAL); assertThat(tracer.scopeManager().activeSpan()).isNull(); } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java index 6a633b3ce37..be126002433 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/Client.java @@ -26,27 +26,24 @@ public Client(RequestHandler requestHandler) { public Future send(Object message) { Context context = new Context(); - return executor.submit( - () -> { - logger.info("send {}", message); - TestUtils.sleep(); - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.beforeRequest(message, context); - }) - .get(); - - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.afterResponse(message, context); - }) - .get(); - - return message + ":response"; - }); + return executor.submit(() -> { + logger.info("send {}", message); + TestUtils.sleep(); + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.beforeRequest(message, context); + }) + .get(); + + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.afterResponse(message, context); + }) + .get(); + + return message + ":response"; + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/HandlerTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/HandlerTest.java index 8dd7aa180e2..444e094422a 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/HandlerTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/concurrentcommonrequesthandler/HandlerTest.java @@ -10,7 +10,6 @@ import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.opentracingshim.OpenTracingShim; import io.opentelemetry.sdk.testing.junit5.OpenTelemetryExtension; import io.opentelemetry.sdk.trace.data.SpanData; @@ -28,6 +27,7 @@ * executed concurrently in different threads which are reused (common pool). Therefore we cannot * use current active span and activate span. So one issue here is setting correct parent span. */ +@SuppressWarnings("deprecation") // testing deprecated shim API class HandlerTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -46,10 +46,6 @@ void two_requests() throws Exception { List finished = otelTesting.getSpans(); assertThat(finished).hasSize(2); - for (SpanData spanData : finished) { - assertThat(spanData.getKind()).isEqualTo(SpanKind.CLIENT); - } - assertThat(finished.get(1).getTraceId()).isNotEqualTo(finished.get(0).getTraceId()); assertThat(SpanId.isValid(finished.get(0).getParentSpanId())).isFalse(); assertThat(SpanId.isValid(finished.get(1).getParentSpanId())).isFalse(); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java index 93ba48e0790..f81c0204e7a 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/errorreporting/ErrorReportingTest.java @@ -29,7 +29,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -@SuppressWarnings("FutureReturnValueIgnored") +@SuppressWarnings({"FutureReturnValueIgnored", "deprecation"}) public final class ErrorReportingTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -60,16 +60,15 @@ void testSimpleError() { @Test void testCallbackError() { Span span = tracer.buildSpan("one").start(); - executor.submit( - () -> { - try (Scope scope = tracer.activateSpan(span)) { - throw new RuntimeException("Invalid state"); - } catch (RuntimeException exc) { - Tags.ERROR.set(span, true); - } finally { - span.finish(); - } - }); + executor.submit(() -> { + try (Scope scope = tracer.activateSpan(span)) { + throw new RuntimeException("Invalid state"); + } catch (RuntimeException exc) { + Tags.ERROR.set(span, true); + } finally { + span.finish(); + } + }); await().atMost(Duration.ofSeconds(5)).until(finishedSpansSize(otelTesting), equalTo(1)); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java index c4966d99252..afe0b14e3f2 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/latespanfinish/LateSpanFinishTest.java @@ -22,7 +22,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -@SuppressWarnings("FutureReturnValueIgnored") +@SuppressWarnings({"FutureReturnValueIgnored", "deprecation"}) public final class LateSpanFinishTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -62,30 +62,28 @@ void test() throws Exception { */ private void submitTasks(Span parentSpan) { - executor.submit( - () -> { - /* Alternative to calling activate() is to pass it manually to asChildOf() for each - * created Span. */ - try (Scope scope = tracer.scopeManager().activate(parentSpan)) { - Span childSpan = tracer.buildSpan("task1").start(); - try (Scope childScope = tracer.scopeManager().activate(childSpan)) { - sleep(55); - } finally { - childSpan.finish(); - } - } - }); + executor.submit(() -> { + /* Alternative to calling activate() is to pass it manually to asChildOf() for each + * created Span. */ + try (Scope scope = tracer.scopeManager().activate(parentSpan)) { + Span childSpan = tracer.buildSpan("task1").start(); + try (Scope childScope = tracer.scopeManager().activate(childSpan)) { + sleep(55); + } finally { + childSpan.finish(); + } + } + }); - executor.submit( - () -> { - try (Scope scope = tracer.scopeManager().activate(parentSpan)) { - Span childSpan = tracer.buildSpan("task2").start(); - try (Scope childScope = tracer.scopeManager().activate(childSpan)) { - sleep(85); - } finally { - childSpan.finish(); - } - } - }); + executor.submit(() -> { + try (Scope scope = tracer.scopeManager().activate(parentSpan)) { + Span childSpan = tracer.buildSpan("task2").start(); + try (Scope childScope = tracer.scopeManager().activate(childSpan)) { + sleep(85); + } finally { + childSpan.finish(); + } + } + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java index d8f8f964ebe..61d1b341194 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/Client.java @@ -22,13 +22,12 @@ public Client(Tracer tracer) { /** Async execution. */ private Future execute(Object message, ResponseListener responseListener) { - return executor.submit( - () -> { - // send via wire and get response - Object response = message + ":response"; - responseListener.onResponse(response); - return response; - }); + return executor.submit(() -> { + // send via wire and get response + Object response = message + ":response"; + responseListener.onResponse(response); + return response; + }); } public Future send(Object message) { diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/ListenerTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/ListenerTest.java index 77378bbdc59..bb2c6e1c030 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/ListenerTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/listenerperrequest/ListenerTest.java @@ -5,7 +5,6 @@ package io.opentelemetry.opentracingshim.testbed.listenerperrequest; -import static io.opentelemetry.api.trace.SpanKind.CLIENT; import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.opentracingshim.OpenTracingShim; @@ -17,6 +16,7 @@ import org.junit.jupiter.api.extension.RegisterExtension; /** Each request has own instance of ResponseListener. */ +@SuppressWarnings("deprecation") // testing deprecated shim API class ListenerTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -31,7 +31,6 @@ void test() throws Exception { List finished = otelTesting.getSpans(); assertThat(finished).hasSize(1); - assertThat(CLIENT).isEqualTo(finished.get(0).getKind()); assertThat(tracer.scopeManager().activeSpan()).isNull(); } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java index d45692966d4..ce1ffccdea6 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/Client.java @@ -32,24 +32,23 @@ public Client(Tracer tracer, CountDownLatch parentDoneLatch) { public Future send(Object message) { SpanContext parentSpanContext = tracer.activeSpan().context(); - return executor.submit( - () -> { - logger.info("Child thread with message '{}' started", message); - - Span span = - tracer - .buildSpan("subtask") - .addReference(References.FOLLOWS_FROM, parentSpanContext) - .start(); - try (Scope subtaskScope = tracer.activateSpan(span)) { - // Simulate work - make sure we finish *after* the parent Span. - parentDoneLatch.await(); - } finally { - span.finish(); - } - - logger.info("Child thread with message '{}' finished", message); - return message + "::response"; - }); + return executor.submit(() -> { + logger.info("Child thread with message '{}' started", message); + + Span span = + tracer + .buildSpan("subtask") + .addReference(References.FOLLOWS_FROM, parentSpanContext) + .start(); + try (Scope subtaskScope = tracer.activateSpan(span)) { + // Simulate work - make sure we finish *after* the parent Span. + parentDoneLatch.await(); + } finally { + span.finish(); + } + + logger.info("Child thread with message '{}' finished", message); + return message + "::response"; + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/MultipleCallbacksTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/MultipleCallbacksTest.java index 08e43060dd6..2a0e52aff3f 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/MultipleCallbacksTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/multiplecallbacks/MultipleCallbacksTest.java @@ -28,7 +28,7 @@ *

    For improved readability, ignore the CountDownLatch lines as those are there to ensure * deterministic execution for the tests without sleeps. */ -@SuppressWarnings("FutureReturnValueIgnored") +@SuppressWarnings({"FutureReturnValueIgnored", "deprecation"}) class MultipleCallbacksTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java index af43003b954..a50cd4ccdcb 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/nestedcallbacks/NestedCallbacksTest.java @@ -25,7 +25,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -@SuppressWarnings("FutureReturnValueIgnored") +@SuppressWarnings({"FutureReturnValueIgnored", "deprecation"}) public final class NestedCallbacksTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -57,27 +57,24 @@ void test() { private void submitCallbacks(Span span) { - executor.submit( - () -> { - try (Scope scope = tracer.scopeManager().activate(span)) { - span.setTag("key1", "1"); + executor.submit(() -> { + try (Scope scope = tracer.scopeManager().activate(span)) { + span.setTag("key1", "1"); - executor.submit( - () -> { - try (Scope scope12 = tracer.scopeManager().activate(span)) { - span.setTag("key2", "2"); + executor.submit(() -> { + try (Scope scope12 = tracer.scopeManager().activate(span)) { + span.setTag("key2", "2"); - executor.submit( - () -> { - try (Scope scope1 = tracer.scopeManager().activate(span)) { - span.setTag("key3", "3"); - } finally { - span.finish(); - } - }); - } - }); + executor.submit(() -> { + try (Scope scope1 = tracer.scopeManager().activate(span)) { + span.setTag("key3", "3"); + } finally { + span.finish(); + } + }); } }); + } + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java index 244e3d0451e..fa441086958 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/Promise.java @@ -40,42 +40,40 @@ public void onError(ErrorCallback errorCallback) { @SuppressWarnings("FutureReturnValueIgnored") public void success(T result) { for (SuccessCallback callback : successCallbacks) { - context.submit( - () -> { - Span childSpan = - tracer - .buildSpan("success") - .addReference(References.FOLLOWS_FROM, parentSpan.context()) - .withTag(Tags.COMPONENT.getKey(), "success") - .start(); - try (Scope childScope = tracer.activateSpan(childSpan)) { - callback.accept(result); - } finally { - childSpan.finish(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = + tracer + .buildSpan("success") + .addReference(References.FOLLOWS_FROM, parentSpan.context()) + .withTag(Tags.COMPONENT.getKey(), "success") + .start(); + try (Scope childScope = tracer.activateSpan(childSpan)) { + callback.accept(result); + } finally { + childSpan.finish(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } @SuppressWarnings("FutureReturnValueIgnored") public void error(Throwable error) { for (ErrorCallback callback : errorCallbacks) { - context.submit( - () -> { - Span childSpan = - tracer - .buildSpan("error") - .addReference(References.FOLLOWS_FROM, parentSpan.context()) - .withTag(Tags.COMPONENT.getKey(), "error") - .start(); - try (Scope childScope = tracer.activateSpan(childSpan)) { - callback.accept(error); - } finally { - childSpan.finish(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = + tracer + .buildSpan("error") + .addReference(References.FOLLOWS_FROM, parentSpan.context()) + .withTag(Tags.COMPONENT.getKey(), "error") + .start(); + try (Scope childScope = tracer.activateSpan(childSpan)) { + callback.accept(error); + } finally { + childSpan.finish(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java index 5a8687a785d..ea357060381 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/promisepropagation/PromisePropagationTest.java @@ -32,6 +32,7 @@ *

    For improved readability, ignore the phaser lines as those are there to ensure deterministic * execution for the tests without sleeps. */ +@SuppressWarnings("deprecation") // testing deprecated shim API class PromisePropagationTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); @@ -58,26 +59,23 @@ void testPromiseCallback() { try (Scope parentScope = tracer.activateSpan(parentSpan)) { Promise successPromise = new Promise<>(context, tracer); - successPromise.onSuccess( - s -> { - tracer.activeSpan().log("Promised 1 " + s); - successResult1.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); - successPromise.onSuccess( - s -> { - tracer.activeSpan().log("Promised 2 " + s); - successResult2.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); + successPromise.onSuccess(s -> { + tracer.activeSpan().log("Promised 1 " + s); + successResult1.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); + successPromise.onSuccess(s -> { + tracer.activeSpan().log("Promised 2 " + s); + successResult2.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); Promise errorPromise = new Promise<>(context, tracer); - errorPromise.onError( - t -> { - errorResult.set(t); - phaser.arriveAndAwaitAdvance(); // result set - }); + errorPromise.onError(t -> { + errorResult.set(t); + phaser.arriveAndAwaitAdvance(); // result set + }); assertThat(otelTesting.getSpans().size()).isEqualTo(0); successPromise.success("success!"); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java index af24b8dd8a3..02510c7c4ea 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/Client.java @@ -26,16 +26,15 @@ public Client(RequestHandler requestHandler) { /** Send a request....... */ public Future send(Object message) { - return executor.submit( - () -> { - logger.info("send {}", message); - TestUtils.sleep(); - requestHandler.beforeRequest(message); + return executor.submit(() -> { + logger.info("send {}", message); + TestUtils.sleep(); + requestHandler.beforeRequest(message); - TestUtils.sleep(); - requestHandler.afterResponse(message); + TestUtils.sleep(); + requestHandler.afterResponse(message); - return message + ":response"; - }); + return message + ":response"; + }); } } diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/HandlerTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/HandlerTest.java index 785a6d6285d..b32700b8705 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/HandlerTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/statelesscommonrequesthandler/HandlerTest.java @@ -21,6 +21,7 @@ * There is only one instance of 'RequestHandler' per 'Client'. Methods of 'RequestHandler' are * executed in the same thread (beforeRequest() and its resulting afterRequest(), that is). */ +@SuppressWarnings("deprecation") // testing deprecated shim API public final class HandlerTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); diff --git a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/suspendresumepropagation/SuspendResumePropagationTest.java b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/suspendresumepropagation/SuspendResumePropagationTest.java index 16221ea7bf9..d024e5cc332 100644 --- a/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/suspendresumepropagation/SuspendResumePropagationTest.java +++ b/opentracing-shim/src/test/java/io/opentelemetry/opentracingshim/testbed/suspendresumepropagation/SuspendResumePropagationTest.java @@ -21,6 +21,7 @@ * These tests are intended to simulate the kind of async models that are common in java async * frameworks. */ +@SuppressWarnings("deprecation") // testing deprecated shim API class SuspendResumePropagationTest { @RegisterExtension static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); diff --git a/perf-harness/build.gradle.kts b/perf-harness/build.gradle.kts index ea6520c5f4e..90065e964bf 100644 --- a/perf-harness/build.gradle.kts +++ b/perf-harness/build.gradle.kts @@ -4,17 +4,18 @@ plugins { description = "Performance Testing Harness" otelJava.moduleName.set("io.opentelemetry.perf-harness") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) dependencies { implementation(project(":api:all")) implementation(project(":sdk:all")) implementation(project(":sdk:testing")) - implementation(project(":exporters:otlp:trace")) + implementation(project(":exporters:otlp:all")) implementation(project(":exporters:logging")) - implementation(project(":semconv")) implementation("eu.rekawek.toxiproxy:toxiproxy-java") - implementation("org.testcontainers:junit-jupiter") + implementation("org.testcontainers:testcontainers-junit-jupiter") runtimeOnly("io.grpc:grpc-netty-shaded") } diff --git a/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java b/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java index bba93e740d0..ee3a2634129 100644 --- a/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java +++ b/perf-harness/src/test/java/io/opentelemetry/perf/OtlpPipelineStressTest.java @@ -5,12 +5,13 @@ package io.opentelemetry.perf; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + import eu.rekawek.toxiproxy.Proxy; import eu.rekawek.toxiproxy.ToxiproxyClient; import eu.rekawek.toxiproxy.model.ToxicDirection; import eu.rekawek.toxiproxy.model.ToxicList; import eu.rekawek.toxiproxy.model.toxic.Timeout; -import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; @@ -26,7 +27,6 @@ import io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporter; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; import java.io.IOException; import java.time.Duration; import java.util.List; @@ -48,6 +48,7 @@ import org.testcontainers.containers.Network; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.containers.wait.strategy.LogMessageWaitStrategy; +import org.testcontainers.images.PullPolicy; import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.DockerImageName; @@ -60,15 +61,17 @@ public class OtlpPipelineStressTest { public static final int OTLP_RECEIVER_PORT = 4317; public static final int COLLECTOR_PROXY_PORT = 44444; public static final int TOXIPROXY_CONTROL_PORT = 8474; - public static Network network = Network.newNetwork(); - public static AtomicLong totalSpansReceivedByCollector = new AtomicLong(); + public static final Network network = Network.newNetwork(); + public static final AtomicLong totalSpansReceivedByCollector = new AtomicLong(); private static final Logger logger = LoggerFactory.getLogger(OtlpPipelineStressTest.class); @Container - public static GenericContainer collectorContainer = + public static final GenericContainer collectorContainer = new GenericContainer<>( - DockerImageName.parse("ghcr.io/open-telemetry/opentelemetry-java/otel-collector")) + DockerImageName.parse( + "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea")) + .withImagePullPolicy(PullPolicy.alwaysPull()) .withNetwork(network) .withNetworkAliases("otel-collector") .withExposedPorts(OTLP_RECEIVER_PORT) @@ -77,23 +80,22 @@ public class OtlpPipelineStressTest { MountableFile.forClasspathResource("otel-collector-config-perf.yaml"), "/etc/otel-collector-config-perf.yaml") .withLogConsumer(new Slf4jLogConsumer(LoggerFactory.getLogger("otel-collector"))) - .withLogConsumer( - outputFrame -> { - String logline = outputFrame.getUtf8String(); - String spanExportPrefix = "TracesExporter\t{\"#spans\": "; - int start = logline.indexOf(spanExportPrefix); - int end = logline.indexOf("}"); - if (start > 0) { - String substring = logline.substring(start + spanExportPrefix.length(), end); - totalSpansReceivedByCollector.addAndGet(Long.parseLong(substring)); - } - }) + .withLogConsumer(outputFrame -> { + String logline = outputFrame.getUtf8String(); + String spanExportPrefix = "TracesExporter\t{\"#spans\": "; + int start = logline.indexOf(spanExportPrefix); + int end = logline.indexOf("}"); + if (start > 0) { + String substring = logline.substring(start + spanExportPrefix.length(), end); + totalSpansReceivedByCollector.addAndGet(Long.parseLong(substring)); + } + }) .waitingFor(new LogMessageWaitStrategy().withRegEx(".*Everything is ready.*")); @Container - public static GenericContainer toxiproxyContainer = - new GenericContainer<>( - DockerImageName.parse("ghcr.io/open-telemetry/opentelemetry-java/toxiproxy")) + public static final GenericContainer toxiproxyContainer = + new GenericContainer<>(DockerImageName.parse("shopify/toxiproxy:latest")) + .withImagePullPolicy(PullPolicy.alwaysPull()) .withNetwork(network) .withNetworkAliases("toxiproxy") .withExposedPorts(TOXIPROXY_CONTROL_PORT, COLLECTOR_PROXY_PORT) @@ -103,9 +105,7 @@ public class OtlpPipelineStressTest { private final InMemoryMetricExporter metricExporter = InMemoryMetricExporter.create(); - private SdkTracerProvider sdkTracerProvider; - private OpenTelemetry openTelemetry; - private SdkMeterProvider meterProvider; + private OpenTelemetrySdk openTelemetry; private Proxy collectorProxy; private ToxiproxyClient toxiproxyClient; @@ -131,8 +131,7 @@ void setUp() throws IOException { @AfterEach void tearDown() throws IOException { - meterProvider.close(); - sdkTracerProvider.shutdown(); + openTelemetry.close(); toxiproxyClient.reset(); collectorProxy.delete(); @@ -141,7 +140,7 @@ void tearDown() throws IOException { @Test @Disabled("we don't want to run this with every build.") - void oltpExportWithFlakyCollector() throws IOException, InterruptedException { + void otlpExportWithFlakyCollector() throws IOException, InterruptedException { ToxicList toxics = collectorProxy.toxics(); // Latency latency = toxics.latency("jittery_latency", ToxicDirection.UPSTREAM, 500); // latency.setJitter(1000); @@ -160,16 +159,15 @@ void oltpExportWithFlakyCollector() throws IOException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads); CountDownLatch latch = new CountDownLatch(1); for (int i = 0; i < numberOfThreads; i++) { - executorService.submit( - () -> { - try { - latch.await(); - runOnce(null, 30_000); - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - throw new IllegalStateException("Interrupted", e); - } - }); + executorService.submit(() -> { + try { + latch.await(); + runOnce(null, 30_000); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException("Interrupted", e); + } + }); } latch.countDown(); @@ -185,7 +183,7 @@ void oltpExportWithFlakyCollector() throws IOException, InterruptedException { Thread.sleep(10000); List finishedMetricItems = metricExporter.getFinishedMetricItems(); - meterProvider.close(); + openTelemetry.getSdkMeterProvider().close(); Thread.sleep(1000); reportMetrics(finishedMetricItems); Thread.sleep(10000); @@ -194,18 +192,16 @@ void oltpExportWithFlakyCollector() throws IOException, InterruptedException { private static void reportMetrics(List finishedMetricItems) { Map> metricsByName = finishedMetricItems.stream().collect(Collectors.groupingBy(MetricData::getName)); - metricsByName.forEach( - (name, metricData) -> { - Stream longPointStream = - metricData.stream().flatMap(md -> md.getLongSumData().getPoints().stream()); - Map> pointsByAttributes = - longPointStream.collect(Collectors.groupingBy(PointData::getAttributes)); - pointsByAttributes.forEach( - (attributes, longPoints) -> { - long total = longPoints.get(longPoints.size() - 1).getValue(); - logger.info("{} : {} : {}", name, attributes, total); - }); - }); + metricsByName.forEach((name, metricData) -> { + Stream longPointStream = + metricData.stream().flatMap(md -> md.getLongSumData().getPoints().stream()); + Map> pointsByAttributes = + longPointStream.collect(Collectors.groupingBy(PointData::getAttributes)); + pointsByAttributes.forEach((attributes, longPoints) -> { + long total = longPoints.get(longPoints.size() - 1).getValue(); + logger.info("{} : {} : {}", name, attributes, total); + }); + }); } private void runOnce(Integer numberOfSpans, int numberOfMillisToRunFor) @@ -242,12 +238,12 @@ private void setupSdk() { Resource resource = Resource.create( Attributes.builder() - .put(ResourceAttributes.SERVICE_NAME, "PerfTester") - .put(ResourceAttributes.SERVICE_VERSION, "1.0.1-RC-1") + .put(stringKey("service.name"), "PerfTester") + .put(stringKey("service.version"), "1.0.1-RC-1") .build()); // set up the metric exporter and wire it into the SDK and a timed reader. - meterProvider = + SdkMeterProvider meterProvider = SdkMeterProvider.builder() .setResource(resource) .registerMetricReader( @@ -259,7 +255,7 @@ private void setupSdk() { // set up the span exporter and wire it into the SDK OtlpGrpcSpanExporter spanExporter = OtlpGrpcSpanExporter.builder() - .setMeterProvider(meterProvider) + .setMeterProvider(() -> meterProvider) .setEndpoint( "http://" + toxiproxyContainer.getHost() @@ -278,7 +274,9 @@ private void setupSdk() { SdkTracerProvider tracerProvider = SdkTracerProvider.builder().addSpanProcessor(spanProcessor).build(); openTelemetry = - OpenTelemetrySdk.builder().setTracerProvider(tracerProvider).buildAndRegisterGlobal(); - sdkTracerProvider = tracerProvider; + OpenTelemetrySdk.builder() + .setTracerProvider(tracerProvider) + .setMeterProvider(meterProvider) + .buildAndRegisterGlobal(); } } diff --git a/perf-harness/src/test/resources/otel-collector-config-perf.yaml b/perf-harness/src/test/resources/otel-collector-config-perf.yaml index 0aa39a4d998..8df61145341 100644 --- a/perf-harness/src/test/resources/otel-collector-config-perf.yaml +++ b/perf-harness/src/test/resources/otel-collector-config-perf.yaml @@ -4,8 +4,8 @@ receivers: grpc: exporters: - logging: - loglevel: info + debug: + verbosity: normal sampling_initial: 1 sampling_thereafter: 1 @@ -25,8 +25,8 @@ service: traces: receivers: [otlp] processors: [batch] - exporters: [logging] + exporters: [debug] metrics: receivers: [otlp] processors: [batch] - exporters: [logging] + exporters: [debug] diff --git a/sdk-extensions/autoconfigure-spi/README.md b/sdk-extensions/autoconfigure-spi/README.md deleted file mode 100644 index 475f7efed35..00000000000 --- a/sdk-extensions/autoconfigure-spi/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# OpenTelemetry SDK Autoconfigure SPI - -[![Javadocs][javadoc-image]][javadoc-url] - -This artifact provides Java Service Provider Interfaces (SPI) for controlling [SDK autoconfiguration](../autoconfigure). -Visit the autoconfigure module for more information on how to use autoconfiguration. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure-spi.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure-spi diff --git a/sdk-extensions/autoconfigure-spi/build.gradle.kts b/sdk-extensions/autoconfigure-spi/build.gradle.kts index 66dd7b32f04..ef68447a751 100644 --- a/sdk-extensions/autoconfigure-spi/build.gradle.kts +++ b/sdk-extensions/autoconfigure-spi/build.gradle.kts @@ -5,14 +5,16 @@ plugins { description = "OpenTelemetry SDK Auto-configuration SPI" otelJava.moduleName.set("io.opentelemetry.sdk.autoconfigure.spi") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) dependencies { api(project(":sdk:all")) + compileOnly(project(":api:incubator")) + testImplementation(project(":api:incubator")) +} - // implementation dependency to require users to add the artifact directly to their build to use - // SdkMeterProviderBuilder. - implementation(project(":sdk:metrics")) - // implementation dependency to require users to add the artifact directly to their build to use - // SdkLogEmitterProviderBuilder. - implementation(project(":sdk:logs")) +tasks.test { + // Configure environment variable for ConfigPropertiesTest + environment("OTEL_JAVA_EXPORTER_MEMORY_MODE", "immutable_data") } diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizer.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizer.java index c45a391e108..68955813dd7 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizer.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizer.java @@ -6,16 +6,20 @@ package io.opentelemetry.sdk.autoconfigure.spi; import io.opentelemetry.context.propagation.TextMapPropagator; -import io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder; -import io.opentelemetry.sdk.logs.export.LogExporter; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.util.Map; import java.util.function.BiFunction; +import java.util.function.Function; import java.util.function.Supplier; /** A builder for customizing OpenTelemetry auto-configuration. */ @@ -61,6 +65,24 @@ AutoConfigurationCustomizer addSpanExporterCustomizer( BiFunction exporterCustomizer); + /** + * Adds a {@link BiFunction} to invoke for all autoconfigured {@link + * io.opentelemetry.sdk.trace.SpanProcessor}. The return value of the {@link BiFunction} will + * replace the passed-in argument. In contrast to {@link #addSpanExporterCustomizer(BiFunction)} + * this allows modifications to happen before batching occurs. As a result, it is possible to + * efficiently filter spans, add artificial spans or delay spans for enhancing them with external, + * delayed data. + * + *

    Multiple calls will execute the customizers in order. + * + * @since 1.33.0 + */ + default AutoConfigurationCustomizer addSpanProcessorCustomizer( + BiFunction + spanProcessorCustomizer) { + return this; + } + /** * Adds a {@link Supplier} of a map of property names and values to use as defaults for the {@link * ConfigProperties} used during auto-configuration. The order of precedence of properties is @@ -73,10 +95,36 @@ AutoConfigurationCustomizer addPropertiesSupplier( Supplier> propertiesSupplier); /** - * Adds a {@link BiFunction} to invoke the with the {@link SdkTracerProviderBuilder} to allow + * Adds a {@link Function} to invoke with the {@link ConfigProperties} to allow customization. The + * return value of the {@link Function} will be merged into the {@link ConfigProperties} before it + * is used for auto-configuration, overwriting the properties that are already there. + * + *

    Multiple calls will cause properties to be merged in order, with later ones overwriting + * duplicate keys in earlier ones. + * + * @since 1.17.0 + */ + default AutoConfigurationCustomizer addPropertiesCustomizer( + Function> propertiesCustomizer) { + return this; + } + + /** + * Adds a {@link BiFunction} to invoke with the {@link SdkTracerProviderBuilder} to allow * customization. The return value of the {@link BiFunction} will replace the passed-in argument. * *

    Multiple calls will execute the customizers in order. + * + *

    Note: calling {@link SdkTracerProviderBuilder#setSampler(Sampler)} inside of your + * configuration function will cause any sampler customizers to be ignored that were configured + * via {@link #addSamplerCustomizer(BiFunction)}. If you want to replace the default sampler, + * check out {@link io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider} and + * use {@link #addPropertiesSupplier(Supplier)} to set `otel.traces.sampler` to your named + * sampler. + * + *

    Similarly, calling {@link SdkTracerProviderBuilder#setResource(Resource)} inside of your + * configuration function will cause any resource customizers to be ignored that were configured + * via {@link #addResourceCustomizer(BiFunction)}. */ default AutoConfigurationCustomizer addTracerProviderCustomizer( BiFunction @@ -85,7 +133,7 @@ default AutoConfigurationCustomizer addTracerProviderCustomizer( } /** - * Adds a {@link BiFunction} to invoke the with the {@link SdkMeterProviderBuilder} to allow + * Adds a {@link BiFunction} to invoke with the {@link SdkMeterProviderBuilder} to allow * customization. The return value of the {@link BiFunction} will replace the passed-in argument. * *

    Multiple calls will execute the customizers in order. @@ -103,6 +151,7 @@ default AutoConfigurationCustomizer addMeterProviderCustomizer( * *

    Multiple calls will execute the customizers in order. */ + @SuppressWarnings("UnusedReturnValue") default AutoConfigurationCustomizer addMetricExporterCustomizer( BiFunction exporterCustomizer) { @@ -110,26 +159,63 @@ default AutoConfigurationCustomizer addMetricExporterCustomizer( } /** - * Adds a {@link BiFunction} to invoke the with the {@link SdkLogEmitterProviderBuilder} to allow + * Adds a {@link BiFunction} to invoke with the autoconfigured {@link MetricReader} to allow * customization. The return value of the {@link BiFunction} will replace the passed-in argument. * *

    Multiple calls will execute the customizers in order. + * + * @since 1.36.0 */ - default AutoConfigurationCustomizer addLogEmitterProviderCustomizer( - BiFunction - meterProviderCustomizer) { + @SuppressWarnings("UnusedReturnValue") + default AutoConfigurationCustomizer addMetricReaderCustomizer( + BiFunction readerCustomizer) { return this; } /** - * Adds a {@link BiFunction} to invoke with the default autoconfigured {@link LogExporter} to - * allow customization. The return value of the {@link BiFunction} will replace the passed-in + * Adds a {@link BiFunction} to invoke with the {@link SdkLoggerProviderBuilder} to allow + * customization. The return value of the {@link BiFunction} will replace the passed-in argument. + * + *

    Multiple calls will execute the customizers in order. + * + * @since 1.19.0 + */ + default AutoConfigurationCustomizer addLoggerProviderCustomizer( + BiFunction + loggerProviderCustomizer) { + return this; + } + + /** + * Adds a {@link BiFunction} to invoke with the default autoconfigured {@link LogRecordExporter} + * to allow customization. The return value of the {@link BiFunction} will replace the passed-in * argument. * *

    Multiple calls will execute the customizers in order. + * + * @since 1.19.0 + */ + default AutoConfigurationCustomizer addLogRecordExporterCustomizer( + BiFunction + exporterCustomizer) { + return this; + } + + /** + * Adds a {@link BiFunction} to invoke for all autoconfigured {@link + * io.opentelemetry.sdk.logs.LogRecordProcessor}s. The return value of the {@link BiFunction} will + * replace the passed-in argument. In contrast to {@link + * #addLogRecordExporterCustomizer(BiFunction)} this allows modifications to happen before + * batching occurs. As a result, it is possible to efficiently filter logs, add artificial logs or + * delay logs for enhancing them with external, delayed data. + * + *

    Multiple calls will execute the customizers in order. + * + * @since 1.33.0 */ - default AutoConfigurationCustomizer addLogExporterCustomizer( - BiFunction exporterCustomizer) { + default AutoConfigurationCustomizer addLogRecordProcessorCustomizer( + BiFunction + logRecordProcessorCustomizer) { return this; } } diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizerProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizerProvider.java index 200fa2b6113..d1dc17edb00 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizerProvider.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/AutoConfigurationCustomizerProvider.java @@ -6,7 +6,7 @@ package io.opentelemetry.sdk.autoconfigure.spi; /** A service provider interface (SPI) for customizing auto-configuration. */ -public interface AutoConfigurationCustomizerProvider { +public interface AutoConfigurationCustomizerProvider extends Ordered { /** * Method invoked when auto-configuring the SDK to allow further customization of diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ConfigProperties.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ConfigProperties.java index e34746c6543..48c98145a33 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ConfigProperties.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ConfigProperties.java @@ -5,6 +5,7 @@ package io.opentelemetry.sdk.autoconfigure.spi; +import io.opentelemetry.common.ComponentLoader; import java.time.Duration; import java.util.List; import java.util.Map; @@ -22,6 +23,19 @@ public interface ConfigProperties { @Nullable String getString(String name); + /** + * Returns a string-valued configuration property. + * + * @return a string-valued configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default String getString(String name, String defaultValue) { + String value = getString(name); + return value == null ? defaultValue : value; + } + /** * Returns a boolean-valued configuration property. Implementations should use the same rules as * {@link Boolean#parseBoolean(String)} for handling the values. @@ -33,7 +47,20 @@ public interface ConfigProperties { Boolean getBoolean(String name); /** - * Returns a integer-valued configuration property. + * Returns a boolean-valued configuration property. + * + * @return a Boolean-valued configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default boolean getBoolean(String name, boolean defaultValue) { + Boolean value = getBoolean(name); + return value == null ? defaultValue : value; + } + + /** + * Returns an Integer-valued configuration property. * * @return null if the property has not been configured. * @throws ConfigurationException if the property is not a valid integer. @@ -42,7 +69,20 @@ public interface ConfigProperties { Integer getInt(String name); /** - * Returns a long-valued configuration property. + * Returns an Integer-valued configuration property. + * + * @return an Integer-valued configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default int getInt(String name, int defaultValue) { + Integer value = getInt(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a Long-valued configuration property. * * @return null if the property has not been configured. * @throws ConfigurationException if the property is not a valid long. @@ -50,6 +90,19 @@ public interface ConfigProperties { @Nullable Long getLong(String name); + /** + * Returns a Long-valued configuration property. + * + * @return a Long-valued configuration property or {@code defaultValue} if a property with {@code + * name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default long getLong(String name, long defaultValue) { + Long value = getLong(name); + return value == null ? defaultValue : value; + } + /** * Returns a double-valued configuration property. * @@ -60,12 +113,26 @@ public interface ConfigProperties { Double getDouble(String name); /** - * Returns a duration property from the map, or {@code null} if it cannot be found or it has a - * wrong type. + * Returns a double-valued configuration property. + * + * @return a Double-valued configuration property or {@code defaultValue} if a property with + * {@code name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default double getDouble(String name, double defaultValue) { + Double value = getDouble(name); + return value == null ? defaultValue : value; + } + + /** + * Returns a duration property from the map, or {@code null} if it cannot be found. * *

    Durations can be of the form "{number}{unit}", where unit is one of: * *

      + *
    • ns + *
    • us *
    • ms *
    • s *
    • m @@ -83,6 +150,20 @@ public interface ConfigProperties { @Nullable Duration getDuration(String name); + /** + * Returns a Duration value configuration property. + * + * @see ConfigProperties#getDuration(String name) + * @return a Duration-valued configuration property or {@code defaultValue} if a property with + * name {@code name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default Duration getDuration(String name, Duration defaultValue) { + Duration value = getDuration(name); + return value == null ? defaultValue : value; + } + /** * Returns a list-valued configuration property. The format of the original value must be * comma-separated. Empty values will be removed. @@ -93,12 +174,45 @@ public interface ConfigProperties { List getList(String name); /** - * Returns a map-valued configuration property. The format of the original value must be - * comma-separated for each key, with an '=' separating the key and value. For instance, - * service.name=Greatest Service,host.name=localhost Empty values will be removed. + * Returns a List value configuration property. + * + * @see ConfigProperties#getList(String name) + * @return a List configuration property or {@code defaultValue} if a property with {@code name} + * has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default List getList(String name, List defaultValue) { + List value = getList(name); + return value.isEmpty() ? defaultValue : value; + } + + /** + * Returns a Map configuration property. The format of the original value must be comma-separated + * for each key, with an '=' separating the key and value. For instance, + * service.name=Greatest Service,host.name=localhost. Empty values will be removed. * * @return an empty map if the property has not been configured. * @throws ConfigurationException for malformed map strings. */ Map getMap(String name); + + /** + * Returns a Map value configuration property. + * + * @see ConfigProperties#getMap(String name) + * @return a Map-valued configuration property or {@code defaultValue} if a property with {@code + * name} has not been configured. + * @throws ConfigurationException if the property is not a valid string. + * @since 1.15.0 + */ + default Map getMap(String name, Map defaultValue) { + Map value = getMap(name); + return value.isEmpty() ? defaultValue : value; + } + + /** Return a {@link ComponentLoader} that should be used to load SPIs. */ + default ComponentLoader getComponentLoader() { + return ComponentLoader.forClassLoader(ConfigProperties.class.getClassLoader()); + } } diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/Ordered.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/Ordered.java new file mode 100644 index 00000000000..e2182b08a40 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/Ordered.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi; + +import io.opentelemetry.common.ComponentLoader; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +/** + * Interface to be extended by SPIs that need to guarantee ordering during loading. + * + * @since 1.17.0 + */ +public interface Ordered { + + /** + * Returns the order of applying the SPI implementing this interface. Higher values are applied + * later, for example: an SPI with order=1 will run after an SPI with order=0. SPI implementations + * with equal values will be run in a non-deterministic order. + */ + default int order() { + return 0; + } + + /** + * Convenience method to load an ordered list of SPIs implementing {@link Ordered}. + * + * @since 1.61.0 + */ + static List loadOrderedList( + ComponentLoader componentLoader, Class spiClass) { + List result = new ArrayList<>(ComponentLoader.loadList(componentLoader, spiClass)); + result.sort(Comparator.comparingInt(Ordered::order)); + return Collections.unmodifiableList(result); + } +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ResourceProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ResourceProvider.java index d0726e1c796..0957929e5a9 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ResourceProvider.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/ResourceProvider.java @@ -11,7 +11,7 @@ * A service provider interface (SPI) for providing a {@link Resource} that is merged into the * {@linkplain Resource#getDefault() default resource}. */ -public interface ResourceProvider { +public interface ResourceProvider extends Ordered { Resource createResource(ConfigProperties config); } diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/ComponentProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/ComponentProvider.java new file mode 100644 index 00000000000..b7874803d06 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/ComponentProvider.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; + +/** + * Provides configured instances of SDK extension components. {@link ComponentProvider} allows SDK + * extension components which are not part of the core SDK to be referenced in declarative based + * configuration. + * + *

      NOTE: when {@link #getType()} is {@link Resource}, the {@link #getName()} is not (currently) + * used, and {@link #create(DeclarativeConfigProperties)} is (currently) called with an empty {@link + * DeclarativeConfigProperties}. + * + *

      Supported component types include: {@link SpanExporter}, {@link MetricExporter}, {@link + * LogRecordExporter}, {@link SpanProcessor}, {@link LogRecordProcessor}, {@link TextMapPropagator}, + * {@link Sampler}, {@link Resource}. + */ +public interface ComponentProvider { + + /** + * The type of SDK extension component. For example, if providing instances of a custom span + * exporter, the type would be {@link SpanExporter}. + */ + Class getType(); + + /** + * The name of the exporter, to be referenced in configuration files. For example, if providing + * instances of a custom span exporter for the "acme" protocol, the name might be "acme". + * + *

      This name MUST not be the same as any other component provider name which returns components + * of the same {@link #getType() type}. In other words, {@link #getType()} and name form a + * composite key uniquely identifying the provider. + */ + String getName(); + + /** + * Configure an instance of the SDK extension component according to the {@code config}. + * + * @param config the configuration provided where the component is referenced in a configuration + * file. + * @return an instance the SDK extension component + */ + Object create(DeclarativeConfigProperties config); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/package-info.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/package-info.java new file mode 100644 index 00000000000..bb65d1147b9 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/package-info.java @@ -0,0 +1,13 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Java SPI (Service Provider Interface) for providing custom components to declarative + * configuration. + */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/AutoConfigureListener.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/AutoConfigureListener.java new file mode 100644 index 00000000000..e181447adb5 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/AutoConfigureListener.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.sdk.OpenTelemetrySdk; + +/** + * Interface to be extended by SPIs that require access to the autoconfigured {@link + * OpenTelemetrySdk} instance. + * + *

      This is not a standalone SPI. Instead, implementations of other SPIs can also implement this + * interface to receive a callback with the configured SDK. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface AutoConfigureListener { + + void afterAutoConfigure(OpenTelemetrySdk sdk); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ComponentProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ComponentProvider.java new file mode 100644 index 00000000000..1bdbe1291b7 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ComponentProvider.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.api.incubator.config.DeclarativeConfigProperties; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; + +/** + * Provides configured instances of SDK extension components. {@link ComponentProvider} allows SDK + * extension components which are not part of the core SDK to be referenced in declarative based + * configuration. + * + *

      NOTE: when {@link #getType()} is {@link Resource}, the {@link #getName()} is not (currently) + * used, and {@link #create(DeclarativeConfigProperties)} is (currently) called with an empty {@link + * DeclarativeConfigProperties}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      Supported component types include: {@link SpanExporter}, {@link MetricExporter}, {@link + * LogRecordExporter}, {@link SpanProcessor}, {@link LogRecordProcessor}, {@link TextMapPropagator}, + * {@link Sampler}, {@link Resource}. + * + * @deprecated Use {@link + * io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider} instead. + * Scheduled for removal after 1.68.0. + */ +@Deprecated +public interface ComponentProvider { + + /** + * The type of SDK extension component. For example, if providing instances of a custom span + * exporter, the type would be {@link SpanExporter}. + */ + Class getType(); + + /** + * The name of the exporter, to be referenced in configuration files. For example, if providing + * instances of a custom span exporter for the "acme" protocol, the name might be "acme". + * + *

      This name MUST not be the same as any other component provider name which returns components + * of the same {@link #getType() type}. In other words, {@link #getType()} and name form a + * composite key uniquely identifying the provider. + */ + String getName(); + + /** + * Configure an instance of the SDK extension component according to the {@code config}. + * + * @param config the configuration provided where the component is referenced in a configuration + * file. + * @return an instance the SDK extension component + */ + Object create(DeclarativeConfigProperties config); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConditionalResourceProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConditionalResourceProvider.java new file mode 100644 index 00000000000..12aede7ce4d --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConditionalResourceProvider.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +/** + * A resource provider that is only applied if the {@link #shouldApply(ConfigProperties, Resource)} + * method returns {@code true}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ConditionalResourceProvider extends ResourceProvider { + + /** + * If an implementation needs to apply only under certain conditions related to the config or the + * existing state of the Resource being built, they can choose to override this default. + * + * @param config The auto configuration properties + * @param existing The current state of the Resource being created + * @return false to skip over this ResourceProvider, or true to use it + */ + boolean shouldApply(ConfigProperties config, Resource existing); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigurableMetricReaderProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigurableMetricReaderProvider.java new file mode 100644 index 00000000000..8283d304027 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigurableMetricReaderProvider.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; + +/** + * A service provider interface (SPI) for providing additional metric readers that can be used with + * the autoconfigured SDK. If the {@code otel.metrics.exporter} property contains a value equal to + * what is returned by {@link #getName()}, the reader returned by {@link + * #createMetricReader(ConfigProperties)} will be enabled and added to the SDK. + * + *

      Where as {@link ConfigurableMetricExporterProvider} provides push-based {@link + * MetricExporter}s to be paired with {@link PeriodicMetricReader}, this SPI facilitates pull-based + * {@link MetricReader}s. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ConfigurableMetricReaderProvider { + + /** + * Returns a {@link MetricReader} that can be registered to OpenTelemetry by providing the + * property value specified by {@link #getName()}. + */ + MetricReader createMetricReader(ConfigProperties config); + + /** + * Returns the name of this reader, which can be specified with the {@code otel.metrics.exporter} + * property to enable it. The name returned should NOT be the same as any other reader / exporter + * name, either from other implementations of this SPI or {@link + * ConfigurableMetricExporterProvider}. If the name does conflict with another reader / exporter + * name, the resulting behavior is undefined and it is explicitly unspecified which reader / + * exporter will actually be used. + */ + String getName(); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DeclarativeConfigurationMapper.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DeclarativeConfigurationMapper.java new file mode 100644 index 00000000000..2803c9c940d --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DeclarativeConfigurationMapper.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Converts parsed configuration values to declarative configuration models and generic maps. + * + *

      Implementations must preserve the models' mapping semantics, including extension properties + * and null values. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface DeclarativeConfigurationMapper { + + /** + * Convert a value to an instance of {@code targetType}. + * + * @param value the value to convert + * @param targetType the target type + * @param the target type + * @return the converted value + * @throws DeclarativeConfigException if the value cannot be converted to {@code targetType} + */ + T convert(Object value, Class targetType); + + /** + * Convert a model or parsed configuration value to a map with string keys. + * + * @param value the value to convert + * @return the converted map, or null if the input value is null + * @throws DeclarativeConfigException if the value cannot be converted to a map + */ + @Nullable + Map toMap(Object value); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DeclarativeConfigurationYamlParser.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DeclarativeConfigurationYamlParser.java new file mode 100644 index 00000000000..9b975cde82b --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DeclarativeConfigurationYamlParser.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import java.io.InputStream; +import java.util.Map; + +/** + * Parses a declarative configuration YAML stream into generic Java objects. + * + *

      Implementations must apply environment variable and system property substitution according to + * the OpenTelemetry Configuration Data Model specification. Substitution is performed on scalar + * values, not mapping keys. For unquoted scalar values, substituted text must be parsed using the + * same YAML scalar rules as the original text. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface DeclarativeConfigurationYamlParser { + + /** + * Parse a YAML stream. + * + * @param configuration the YAML input stream + * @param environmentVariables environment variables used for substitution + * @param systemProperties system properties used for substitution + * @return the parsed configuration + * @throws DeclarativeConfigException if the YAML cannot be parsed + */ + Object parse( + InputStream configuration, + Map environmentVariables, + Map systemProperties); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java new file mode 100644 index 00000000000..b29d664a460 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/DefaultConfigProperties.java @@ -0,0 +1,314 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import static java.util.stream.Collectors.groupingBy; +import static java.util.stream.Collectors.joining; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.common.impl.ConfigUtil; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import java.time.Duration; +import java.util.AbstractMap; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.function.Function; +import java.util.stream.Collectors; +import javax.annotation.Nullable; + +/** + * Property keys from all sources are normalized to be all lower case, with dashes and underscores + * replaced with periods. For example, {@code otel.java.exporter.memory_mode} matches the + * environment variable {@code OTEL_JAVA_EXPORTER_MEMORY_MODE}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class DefaultConfigProperties implements ConfigProperties { + + private final Map config; + private final ComponentLoader componentLoader; + + /** + * Creates a {@link DefaultConfigProperties} by merging system properties, environment variables, + * and the {@code defaultProperties}. + * + *

      Environment variables take priority over {@code defaultProperties}. System properties take + * priority over environment variables. + */ + public static DefaultConfigProperties create( + Map defaultProperties, ComponentLoader componentLoader) { + return new DefaultConfigProperties( + ConfigUtil.safeSystemProperties(), System.getenv(), defaultProperties, componentLoader); + } + + /** + * Create a {@link DefaultConfigProperties} from the {@code properties}, ignoring system + * properties and environment variables. + */ + public static DefaultConfigProperties createFromMap(Map properties) { + return new DefaultConfigProperties( + properties, + Collections.emptyMap(), + Collections.emptyMap(), + ComponentLoader.forClassLoader(DefaultConfigProperties.class.getClassLoader())); + } + + private DefaultConfigProperties( + Map systemProperties, + Map environmentVariables, + Map defaultProperties, + ComponentLoader componentLoader) { + Map config = new HashMap<>(); + defaultProperties.forEach((name, value) -> config.put(normalizeKey(name), value)); + environmentVariables.forEach( + (name, value) -> config.put(ConfigUtil.normalizeEnvironmentVariableKey(name), value)); + systemProperties.forEach( + (key, value) -> config.put(normalizeKey(key.toString()), value.toString())); + + this.config = config; + this.componentLoader = componentLoader; + } + + private DefaultConfigProperties( + DefaultConfigProperties previousProperties, Map overrides) { + // previousProperties are already normalized, they can be copied as they are + Map config = new HashMap<>(previousProperties.config); + overrides.forEach((name, value) -> config.put(normalizeKey(name), value)); + + this.config = config; + this.componentLoader = previousProperties.componentLoader; + } + + @Override + @Nullable + public String getString(String name) { + return config.get(normalizeKey(name)); + } + + @Override + @Nullable + public Boolean getBoolean(String name) { + String value = config.get(normalizeKey(name)); + if (value == null || value.isEmpty()) { + return null; + } + return Boolean.parseBoolean(value); + } + + @Override + @Nullable + @SuppressWarnings("UnusedException") + public Integer getInt(String name) { + String value = config.get(normalizeKey(name)); + if (value == null || value.isEmpty()) { + return null; + } + try { + return Integer.parseInt(value); + } catch (NumberFormatException ex) { + throw newInvalidPropertyException(name, value, "integer"); + } + } + + @Override + @Nullable + @SuppressWarnings("UnusedException") + public Long getLong(String name) { + String value = config.get(normalizeKey(name)); + if (value == null || value.isEmpty()) { + return null; + } + try { + return Long.parseLong(value); + } catch (NumberFormatException ex) { + throw newInvalidPropertyException(name, value, "long"); + } + } + + @Override + @Nullable + @SuppressWarnings("UnusedException") + public Double getDouble(String name) { + String value = config.get(normalizeKey(name)); + if (value == null || value.isEmpty()) { + return null; + } + try { + return Double.parseDouble(value); + } catch (NumberFormatException ex) { + throw newInvalidPropertyException(name, value, "double"); + } + } + + @Override + @Nullable + @SuppressWarnings("UnusedException") + public Duration getDuration(String name) { + String value = config.get(normalizeKey(name)); + if (value == null || value.isEmpty()) { + return null; + } + String unitString = getUnitString(value); + // TODO: Environment variables have unknown encoding. `trim()` may cut codepoints oddly + // but likely we'll fail for malformed unit string either way. + String numberString = value.substring(0, value.length() - unitString.length()); + try { + long rawNumber = Long.parseLong(numberString.trim()); + TimeUnit unit = getDurationUnit(unitString.trim()); + return Duration.ofNanos(TimeUnit.NANOSECONDS.convert(rawNumber, unit)); + } catch (NumberFormatException ex) { + throw new ConfigurationException( + "Invalid duration property " + + name + + "=" + + value + + ". Expected number, found: " + + numberString, + ex); + } catch (ConfigurationException ex) { + throw new ConfigurationException( + "Invalid duration property " + name + "=" + value + ". " + ex.getMessage()); + } + } + + @Override + public List getList(String name) { + String value = config.get(normalizeKey(name)); + if (value == null) { + return Collections.emptyList(); + } + return filterBlanksAndNulls(value.split(",")); + } + + /** + * Returns {@link ConfigProperties#getList(String)} as a {@link Set} after validating there are no + * duplicate entries. + * + * @throws ConfigurationException if {@code name} contains duplicate entries + */ + public static Set getSet(ConfigProperties config, String name) { + List list = config.getList(ConfigUtil.normalizePropertyKey(name)); + Set set = new HashSet<>(list); + if (set.size() != list.size()) { + String duplicates = + list.stream() + .collect(groupingBy(Function.identity(), Collectors.counting())) + .entrySet() + .stream() + .filter(entry -> entry.getValue() > 1) + .map(Map.Entry::getKey) + .collect(joining(",", "[", "]")); + throw new ConfigurationException(name + " contains duplicates: " + duplicates); + } + return set; + } + + @Override + public Map getMap(String name) { + return getList(ConfigUtil.normalizePropertyKey(name)).stream() + .map(entry -> { + String[] split = entry.split("=", 2); + if (split.length != 2 || split[0].isEmpty()) { + throw new ConfigurationException("Invalid map property: " + name); + } + return filterBlanksAndNulls(split); + }) + // Filter entries with an empty value, i.e. "foo=" + .filter(splitKeyValuePairs -> splitKeyValuePairs.size() == 2) + .map(splitKeyValuePairs -> + new AbstractMap.SimpleImmutableEntry<>( + splitKeyValuePairs.get(0), splitKeyValuePairs.get(1))) + // If duplicate keys, prioritize later ones similar to duplicate system properties on a + // Java command line. + .collect( + Collectors.toMap( + Map.Entry::getKey, Map.Entry::getValue, (first, next) -> next, LinkedHashMap::new)); + } + + @Override + public ComponentLoader getComponentLoader() { + return componentLoader; + } + + /** + * Return a new {@link DefaultConfigProperties} by overriding the {@code previousProperties} with + * the {@code overrides}. + */ + public DefaultConfigProperties withOverrides(Map overrides) { + return new DefaultConfigProperties(this, overrides); + } + + private static ConfigurationException newInvalidPropertyException( + String name, String value, String type) { + throw new ConfigurationException( + "Invalid value for property " + name + "=" + value + ". Must be a " + type + "."); + } + + /** + * Normalize a property key the same way environment variable keys are normalized, so that keys + * containing "_" match their environment variable. + */ + private static String normalizeKey(String key) { + return ConfigUtil.normalizeEnvironmentVariableKey(ConfigUtil.normalizePropertyKey(key)); + } + + private static List filterBlanksAndNulls(String[] values) { + return Arrays.stream(values) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .collect(Collectors.toList()); + } + + /** Returns the TimeUnit associated with a unit string. Defaults to milliseconds. */ + private static TimeUnit getDurationUnit(String unitString) { + switch (unitString) { + case "us": + return TimeUnit.MICROSECONDS; + case "ns": + return TimeUnit.NANOSECONDS; + case "": // Fallthrough expected + case "ms": + return TimeUnit.MILLISECONDS; + case "s": + return TimeUnit.SECONDS; + case "m": + return TimeUnit.MINUTES; + case "h": + return TimeUnit.HOURS; + case "d": + return TimeUnit.DAYS; + default: + throw new ConfigurationException("Invalid duration string, found: " + unitString); + } + } + + /** + * Fragments the 'units' portion of a config value from the 'value' portion. + * + *

      E.g. "1ms" would return the string "ms". + */ + private static String getUnitString(String rawValue) { + int lastDigitIndex = rawValue.length() - 1; + while (lastDigitIndex >= 0) { + char c = rawValue.charAt(lastDigitIndex); + if (Character.isDigit(c)) { + break; + } + lastDigitIndex -= 1; + } + // Pull everything after the last digit. + return rawValue.substring(lastDigitIndex + 1); + } +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ExtendedDeclarativeConfigProperties.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ExtendedDeclarativeConfigProperties.java new file mode 100644 index 00000000000..b48e4a0d416 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ExtendedDeclarativeConfigProperties.java @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; + +/** + * Extended version of {@link DeclarativeConfigProperties} with access to {@link ConfigProvider}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ExtendedDeclarativeConfigProperties extends DeclarativeConfigProperties { + + ConfigProvider getConfigProvider(); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/logs/ConfigurableLogRecordExporterProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/logs/ConfigurableLogRecordExporterProvider.java new file mode 100644 index 00000000000..d4e3d2bc949 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/logs/ConfigurableLogRecordExporterProvider.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.logs; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +/** + * A service provider interface (SPI) for providing additional exporters that can be used with the + * autoconfigured SDK. If the {@code otel.logs.exporter} property contains a value equal to what is + * returned by {@link #getName()}, the exporter returned by {@link + * #createExporter(ConfigProperties)} will be enabled and added to the SDK. + * + * @since 1.19.0 + */ +public interface ConfigurableLogRecordExporterProvider { + + /** + * Returns a {@link LogRecordExporter} that can be registered to OpenTelemetry by providing the + * property value specified by {@link #getName()}. + */ + LogRecordExporter createExporter(ConfigProperties config); + + /** + * Returns the name of this exporter, which can be specified with the {@code otel.logs.exporter} + * property to enable it. The name returned should NOT be the same as any other exporter name. If + * the name does conflict with another exporter name, the resulting behavior is undefined and it + * is explicitly unspecified which exporter will actually be used. + */ + String getName(); +} diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/logs/package-info.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/logs/package-info.java new file mode 100644 index 00000000000..7e35824451e --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/logs/package-info.java @@ -0,0 +1,13 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Java SPI (Service Provider Interface) for implementing extensions to SDK autoconfiguration of + * logs. + */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.autoconfigure.spi.logs; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/metrics/ConfigurableMetricExporterProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/metrics/ConfigurableMetricExporterProvider.java index 707ff856ec6..465366c4e29 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/metrics/ConfigurableMetricExporterProvider.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/metrics/ConfigurableMetricExporterProvider.java @@ -6,13 +6,21 @@ package io.opentelemetry.sdk.autoconfigure.spi.metrics; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider; import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; /** * A service provider interface (SPI) for providing additional exporters that can be used with the * autoconfigured SDK. If the {@code otel.metrics.exporter} property contains a value equal to what * is returned by {@link #getName()}, the exporter returned by {@link * #createExporter(ConfigProperties)} will be enabled and added to the SDK. + * + *

      The push-based {@link MetricExporter}s supplied by this SPI are paired with a {@link + * io.opentelemetry.sdk.metrics.export.PeriodicMetricReader}. See {@link + * ConfigurableMetricReaderProvider} for providing pull-based {@link MetricReader}s. + * + * @since 1.15.0 */ public interface ConfigurableMetricExporterProvider { @@ -25,8 +33,10 @@ public interface ConfigurableMetricExporterProvider { /** * Returns the name of this exporter, which can be specified with the {@code * otel.metrics.exporter} property to enable it. The name returned should NOT be the same as any - * other exporter name. If the name does conflict with another exporter name, the resulting - * behavior is undefined and it is explicitly unspecified which exporter will actually be used. + * other exporter / reader name, either from other implementations of this SPI or {@link + * ConfigurableMetricReaderProvider}. If the name does conflict with another exporter / reader + * name, the resulting behavior is undefined and it is explicitly unspecified which exporter / + * reader will actually be used. */ String getName(); } diff --git a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/traces/ConfigurableSamplerProvider.java b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/traces/ConfigurableSamplerProvider.java index b97d9eb4a43..a0dd91b1315 100644 --- a/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/traces/ConfigurableSamplerProvider.java +++ b/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/traces/ConfigurableSamplerProvider.java @@ -24,9 +24,9 @@ public interface ConfigurableSamplerProvider { /** * Returns the name of this sampler, which can be specified with the {@code otel.traces.sampler} - * property to enable it. The name returned should NOT be the same as any other exporter name. If - * the name does conflict with another exporter name, the resulting behavior is undefined and it - * is explicitly unspecified which exporter will actually be used. + * property to enable it. The name returned should NOT be the same as any other sampler name. If + * the name does conflict with another sampler name, the resulting behavior is undefined and it is + * explicitly unspecified which sampler will actually be used. */ String getName(); } diff --git a/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java b/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java new file mode 100644 index 00000000000..8e1f0470a57 --- /dev/null +++ b/sdk-extensions/autoconfigure-spi/src/test/java/io/opentelemetry/sdk/autoconfigure/spi/internal/ConfigPropertiesTest.java @@ -0,0 +1,320 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.spi.internal; + +import static java.util.Collections.emptyList; +import static java.util.Collections.emptyMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.entry; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.SetSystemProperty; + +/** + * Relies on environment configuration in {@code + * ./sdk-extensions/autoconfigure-spi/build.gradle.kts}. + */ +class ConfigPropertiesTest { + + private static final ComponentLoader COMPONENT_LOADER = + ComponentLoader.forClassLoader(ConfigPropertiesTest.class.getClassLoader()); + + @Test + void allValid() { + Map properties = makeTestProps(); + + ConfigProperties config = DefaultConfigProperties.createFromMap(properties); + assertThat(config.getString("test.string")).isEqualTo("str"); + assertThat(config.getInt("test.int")).isEqualTo(10); + assertThat(config.getLong("test.long")).isEqualTo(20); + assertThat(config.getDouble("test.double")).isEqualTo(5.4); + assertThat(config.getList("test.list")).containsExactly("cat", "dog", "bear"); + assertThat(config.getMap("test.map")) + .containsExactly(entry("cat", "meow"), entry("dog", "bark"), entry("bear", "growl")); + assertThat(config.getDuration("test.duration")).isEqualTo(Duration.ofSeconds(1)); + } + + @Test + void allValidUsingHyphens() { + Map properties = makeTestProps(); + + ConfigProperties config = DefaultConfigProperties.createFromMap(properties); + assertThat(config.getString("test-string")).isEqualTo("str"); + assertThat(config.getInt("test-int")).isEqualTo(10); + assertThat(config.getLong("test-long")).isEqualTo(20); + assertThat(config.getDouble("test-double")).isEqualTo(5.4); + assertThat(config.getList("test-list")).containsExactly("cat", "dog", "bear"); + assertThat(config.getMap("test-map")) + .containsExactly(entry("cat", "meow"), entry("dog", "bark"), entry("bear", "growl")); + assertThat(config.getDuration("test-duration")).isEqualTo(Duration.ofSeconds(1)); + } + + @Test + void allMissing() { + ConfigProperties config = DefaultConfigProperties.createFromMap(emptyMap()); + assertThat(config.getString("test.string")).isNull(); + assertThat(config.getInt("test.int")).isNull(); + assertThat(config.getLong("test.long")).isNull(); + assertThat(config.getDouble("test.double")).isNull(); + assertThat(config.getList("test.list")).isEmpty(); + assertThat(config.getMap("test.map")).isEmpty(); + assertThat(config.getDuration("test.duration")).isNull(); + } + + @Test + void allEmpty() { + Map properties = new HashMap<>(); + properties.put("test.string", ""); + properties.put("test.int", ""); + properties.put("test.long", ""); + properties.put("test.double", ""); + properties.put("test.list", ""); + properties.put("test.map", ""); + properties.put("test.duration", ""); + + ConfigProperties config = DefaultConfigProperties.createFromMap(properties); + assertThat(config.getString("test.string")).isEmpty(); + assertThat(config.getInt("test.int")).isNull(); + assertThat(config.getLong("test.long")).isNull(); + assertThat(config.getDouble("test.double")).isNull(); + assertThat(config.getList("test.list")).isEmpty(); + assertThat(config.getMap("test.map")).isEmpty(); + assertThat(config.getDuration("test.duration")).isNull(); + } + + @Test + void invalidInt() { + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("int", "bar")) + .getInt("int")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid value for property int=bar. Must be a integer."); + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap( + Collections.singletonMap("int", "999999999999999")) + .getInt("int")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid value for property int=999999999999999. Must be a integer."); + } + + @Test + void invalidLong() { + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("long", "bar")) + .getLong("long")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid value for property long=bar. Must be a long."); + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap( + Collections.singletonMap("long", "99223372036854775807")) + .getLong("long")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid value for property long=99223372036854775807. Must be a long."); + } + + @Test + void invalidDouble() { + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("double", "bar")) + .getDouble("double")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid value for property double=bar. Must be a double."); + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("double", "1.0.1")) + .getDouble("double")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid value for property double=1.0.1. Must be a double."); + } + + @Test + void uncleanList() { + assertThat( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("list", " a ,b,c , d,, ,")) + .getList("list")) + .containsExactly("a", "b", "c", "d"); + } + + @Test + void uncleanMap() { + assertThat( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("map", " a=1 ,b=2,c = 3 , d= 4,, ,")) + .getMap("map")) + .containsExactly(entry("a", "1"), entry("b", "2"), entry("c", "3"), entry("d", "4")); + } + + @Test + void invalidMap() { + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap( + Collections.singletonMap("map", "authorization=Bearer s3cr3t,malformed")) + .getMap("map")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid map property: map"); + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("map", "a=1,=b")) + .getMap("map")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid map property: map"); + } + + @Test + void invalidDuration() { + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "1a1ms")) + .getDuration("duration")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid duration property duration=1a1ms. Expected number, found: 1a1"); + assertThatThrownBy(() -> + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "9mm")) + .getDuration("duration")) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Invalid duration property duration=9mm. Invalid duration string, found: mm"); + } + + @Test + void durationNegativeParsing() { + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "-41")) + .getDuration("duration")) + .isEqualTo(Duration.ofMillis(-41)); + } + + @Test + void durationUnitParsing() { + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "3ns")) + .getDuration("duration")) + .isEqualTo(Duration.ofNanos(3)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "2us")) + .getDuration("duration")) + .isEqualTo(Duration.ofNanos(2000)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "1")) + .getDuration("duration")) + .isEqualTo(Duration.ofMillis(1)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "2ms")) + .getDuration("duration")) + .isEqualTo(Duration.ofMillis(2)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "3s")) + .getDuration("duration")) + .isEqualTo(Duration.ofSeconds(3)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "4m")) + .getDuration("duration")) + .isEqualTo(Duration.ofMinutes(4)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "5h")) + .getDuration("duration")) + .isEqualTo(Duration.ofHours(5)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "6d")) + .getDuration("duration")) + .isEqualTo(Duration.ofDays(6)); + // Check Space handling + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "7 ms")) + .getDuration("duration")) + .isEqualTo(Duration.ofMillis(7)); + assertThat( + DefaultConfigProperties.createFromMap(Collections.singletonMap("duration", "8 ms")) + .getDuration("duration")) + .isEqualTo(Duration.ofMillis(8)); + } + + @Test + void defaultMethodsDelegate() { + Map expectedMap = new HashMap<>(); + expectedMap.put("dog", "bark"); + expectedMap.put("cat", "meow"); + expectedMap.put("bear", "growl"); + + Map map = makeTestProps(); + ConfigProperties properties = DefaultConfigProperties.create(map, COMPONENT_LOADER); + assertThat(properties.getBoolean("test.boolean", false)).isTrue(); + assertThat(properties.getString("test.string", "nah")).isEqualTo("str"); + assertThat(properties.getDouble("test.double", 65.535)).isEqualTo(5.4); + assertThat(properties.getInt("test.int", 21)).isEqualTo(10); + assertThat(properties.getLong("test.long", 123L)).isEqualTo(20L); + assertThat(properties.getDuration("test.duration", Duration.ofDays(13))) + .isEqualTo(Duration.ofSeconds(1)); + assertThat(properties.getList("test.list", emptyList())).containsExactly("cat", "dog", "bear"); + assertThat(properties.getMap("test.map", emptyMap())).containsAllEntriesOf(expectedMap); + } + + @Test + void defaultMethodsFallBack() { + ConfigProperties properties = DefaultConfigProperties.create(emptyMap(), COMPONENT_LOADER); + assertThat(properties.getBoolean("foo", true)).isTrue(); + assertThat(properties.getString("foo", "bar")).isEqualTo("bar"); + assertThat(properties.getDouble("foo", 65.535)).isEqualTo(65.535); + assertThat(properties.getInt("foo", 21)).isEqualTo(21); + assertThat(properties.getLong("foo", 123L)).isEqualTo(123L); + assertThat(properties.getDuration("foo", Duration.ofDays(13))).isEqualTo(Duration.ofDays(13)); + } + + @Test + void defaultCollectionTypes() { + ConfigProperties properties = DefaultConfigProperties.create(emptyMap(), COMPONENT_LOADER); + assertThat(properties.getList("foo", Arrays.asList("1", "2", "3"))) + .containsExactly("1", "2", "3"); + assertThat(properties.getList("foo")).isEmpty(); + Map defaultMap = new HashMap<>(); + defaultMap.put("one", "1"); + defaultMap.put("two", "2"); + assertThat(properties.getMap("foo", defaultMap)) + .containsExactly(entry("one", "1"), entry("two", "2")); + assertThat(properties.getMap("foo")).isEmpty(); + } + + @Test + void environmentVariableForKeyWithUnderscore() { + ConfigProperties properties = DefaultConfigProperties.create(emptyMap(), COMPONENT_LOADER); + assertThat(properties.getString("otel.java.exporter.memory_mode")).isEqualTo("immutable_data"); + } + + @Test + void environmentVariableTakesPriorityOverDefaultForKeyWithUnderscore() { + ConfigProperties properties = + DefaultConfigProperties.create( + Collections.singletonMap("otel.java.exporter.memory_mode", "reusable_data"), + COMPONENT_LOADER); + assertThat(properties.getString("otel.java.exporter.memory_mode")).isEqualTo("immutable_data"); + } + + @Test + @SetSystemProperty(key = "otel.java.exporter.memory_mode", value = "reusable_data") + void systemPropertyTakesPriorityOverEnvironmentVariableForKeyWithUnderscore() { + ConfigProperties properties = DefaultConfigProperties.create(emptyMap(), COMPONENT_LOADER); + assertThat(properties.getString("otel.java.exporter.memory_mode")).isEqualTo("reusable_data"); + } + + private static Map makeTestProps() { + Map properties = new HashMap<>(); + properties.put("test.string", "str"); + properties.put("test.int", "10"); + properties.put("test.long", "20"); + properties.put("test.double", "5.4"); + properties.put("test.boolean", "true"); + properties.put("test.list", "cat,dog,bear"); + properties.put("test.map", "cat=meow,dog=bark,bear=growl,bird="); + properties.put("test.duration", "1s"); + return properties; + } +} diff --git a/sdk-extensions/autoconfigure/README.md b/sdk-extensions/autoconfigure/README.md index 21b9fcee0d7..8662e8b2c7f 100644 --- a/sdk-extensions/autoconfigure/README.md +++ b/sdk-extensions/autoconfigure/README.md @@ -1,277 +1,8 @@ # OpenTelemetry SDK Autoconfigure -[![Javadocs][javadoc-image]][javadoc-url] - This artifact implements environment-based autoconfiguration of the OpenTelemetry SDK. This can be an alternative to programmatic configuration using the normal SDK builders. -All options support being passed as Java system properties, e.g., `-Dotel.traces.exporter=zipkin` or -environment variables, e.g., `OTEL_TRACES_EXPORTER=zipkin`. - -## Contents - -* [General notes](#general-notes) -* [Exporters](#exporters) - + [OTLP exporter (span, metric, and log exporters)](#otlp-exporter-span-metric-and-log-exporters) - + [Jaeger exporter](#jaeger-exporter) - + [Zipkin exporter](#zipkin-exporter) - + [Prometheus exporter](#prometheus-exporter) - + [Logging exporter](#logging-exporter) -* [Trace context propagation](#propagator) -* [OpenTelemetry Resource](#opentelemetry-resource) - + [Resource Provider SPI](#resource-provider-spi) - + [Disabling automatic ResourceProviders](#disabling-automatic-resourceproviders) -* [Batch span processor](#batch-span-processor) -* [Sampler](#sampler) -* [Span limits](#span-limits) -* [Periodic Metric Reader](#periodic-metric-reader) -* [Customizing the OpenTelemetry SDK](#customizing-the-opentelemetry-sdk) - -## General notes - -- The autoconfigure module registers Java shutdown hooks to shut down the SDK when appropriate. Please note that since this project uses -java.util.logging for all of it's logging, some of that logging may be suppressed during shutdown hooks. This is a bug in the JDK itself, -and not something we can control. If you require logging during shutdown hooks, please consider using `System.out` rather than a logging framework -that might shut itself down in a shutdown hook, thus suppressing your log messages. See this [JDK bug](https://bugs.openjdk.java.net/browse/JDK-8161253) -for more details. - -## Exporters - -The following configuration properties are common to all exporters: - -| System property | Environment variable | Purpose | -|-----------------------|-----------------------|----------------------------------------------------------------------------------------------------------------------------| -| otel.traces.exporter | OTEL_TRACES_EXPORTER | List of exporters to be used for tracing, separated by commas. Default is `otlp`. `none` means no autoconfigured exporter. | -| otel.metrics.exporter | OTEL_METRICS_EXPORTER | The exporter to be used for metrics. Default is `otlp`. `none` means no autoconfigured exporter. | -| otel.logs.exporter | OTEL_LOGS_EXPORTER | The exporter to be used for logs. Default is `none`. | - -### OTLP exporter (span, metric, and log exporters) - -The [OpenTelemetry Protocol (OTLP)](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md) span, metric, and log exporters - -| System property | Environment variable | Description | -|---------------------------------------------------|---------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| otel.traces.exporter=otlp (default) | OTEL_TRACES_EXPORTER=otlp | Select the OpenTelemetry exporter for tracing (default) | -| otel.metrics.exporter=otlp | OTEL_METRICS_EXPORTER=otlp | Select the OpenTelemetry exporter for metrics (default) | -| otel.logs.exporter=otlp | OTEL_LOGS_EXPORTER=otlp | Select the OpenTelemetry exporter for logs | -| otel.exporter.otlp.endpoint | OTEL_EXPORTER_OTLP_ENDPOINT | The OTLP traces, metrics, and logs endpoint to connect to. Must be a URL with a scheme of either `http` or `https` based on the use of TLS. If protocol is `http/protobuf` the version and signal will be appended to the path (e.g. `v1/traces`, `v1/metrics`, or `v1/logs`). Default is `http://localhost:4317` when protocol is `grpc`, and `http://localhost:4318/v1/{signal}` when protocol is `http/protobuf`. | -| otel.exporter.otlp.traces.endpoint | OTEL_EXPORTER_OTLP_TRACES_ENDPOINT | The OTLP traces endpoint to connect to. Must be a URL with a scheme of either `http` or `https` based on the use of TLS. Default is `http://localhost:4317` when protocol is `grpc`, and `http://localhost:4318/v1/traces` when protocol is `http/protobuf`. | -| otel.exporter.otlp.metrics.endpoint | OTEL_EXPORTER_OTLP_METRICS_ENDPOINT | The OTLP metrics endpoint to connect to. Must be a URL with a scheme of either `http` or `https` based on the use of TLS. Default is `http://localhost:4317` when protocol is `grpc`, and `http://localhost:4318/v1/metrics` when protocol is `http/protobuf`. | -| otel.exporter.otlp.logs.endpoint | OTEL_EXPORTER_OTLP_LOGS_ENDPOINT | The OTLP logs endpoint to connect to. Must be a URL with a scheme of either `http` or `https` based on the use of TLS. Default is `http://localhost:4317` when protocol is `grpc`, and `http://localhost:4318/v1/logs` when protocol is `http/protobuf`. | -| otel.exporter.otlp.certificate | OTEL_EXPORTER_OTLP_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP trace, metric, or log server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default the host platform's trusted root certificates are used. | -| otel.exporter.otlp.traces.certificate | OTEL_EXPORTER_OTLP_TRACES_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP trace server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default the host platform's trusted root certificates are used. | -| otel.exporter.otlp.metrics.certificate | OTEL_EXPORTER_OTLP_METRICS_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP metric server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default the host platform's trusted root certificates are used. | -| otel.exporter.otlp.logs.certificate | OTEL_EXPORTER_OTLP_LOGS_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP log server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default the host platform's trusted root certificates are used. | -| otel.exporter.otlp.client.key | OTEL_EXPORTER_OTLP_CLIENT_KEY | The path to the file containing private client key to use when verifying an OTLP trace, metric, or log client's TLS credentials. The file should contain one private key PKCS8 PEM format. By default no client key is used. | -| otel.exporter.otlp.traces.client.key | OTEL_EXPORTER_OTLP_TRACES_CLIENT_KEY | The path to the file containing private client key to use when verifying an OTLP trace client's TLS credentials. The file should contain one private key PKCS8 PEM format. By default no client key file is used. | -| otel.exporter.otlp.metrics.client.key | OTEL_EXPORTER_OTLP_METRICS_CLIENT_KEY | The path to the file containing private client key to use when verifying an OTLP metric client's TLS credentials. The file should contain one private key PKCS8 PEM format. By default no client key file is used. | -| otel.exporter.otlp.logs.client.key | OTEL_EXPORTER_OTLP_LOGS_CLIENT_KEY | The path to the file containing private client key to use when verifying an OTLP log client's TLS credentials. The file should contain one private key PKCS8 PEM format. By default no client key file is used. | -| otel.exporter.otlp.client.certificate | OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP trace, metric, or log client's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default no chain file is used. | -| otel.exporter.otlp.traces.client.certificate | OTEL_EXPORTER_OTLP_TRACES_CLIENT_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP trace server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default no chain file is used. | -| otel.exporter.otlp.metrics.client.certificate | OTEL_EXPORTER_OTLP_METRICS_CLIENT_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP metric server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default no chain file is used. | -| otel.exporter.otlp.logs.client.certificate | OTEL_EXPORTER_OTLP_LOGS_CLIENT_CERTIFICATE | The path to the file containing trusted certificates to use when verifying an OTLP log server's TLS credentials. The file should contain one or more X.509 certificates in PEM format. By default no chain file is used. | -| otel.exporter.otlp.headers | OTEL_EXPORTER_OTLP_HEADERS | Key-value pairs separated by commas to pass as request headers on OTLP trace, metric, and log requests. | -| otel.exporter.otlp.traces.headers | OTEL_EXPORTER_OTLP_TRACES_HEADERS | Key-value pairs separated by commas to pass as request headers on OTLP trace requests. | -| otel.exporter.otlp.metrics.headers | OTEL_EXPORTER_OTLP_METRICS_HEADERS | Key-value pairs separated by commas to pass as request headers on OTLP metrics requests. | -| otel.exporter.otlp.logs.headers | OTEL_EXPORTER_OTLP_LOGS_HEADERS | Key-value pairs separated by commas to pass as request headers on OTLP logs requests. | -| otel.exporter.otlp.compression | OTEL_EXPORTER_OTLP_COMPRESSION | The compression type to use on OTLP trace, metric, and log requests. Options include `gzip`. By default no compression will be used. | -| otel.exporter.otlp.traces.compression | OTEL_EXPORTER_OTLP_TRACES_COMPRESSION | The compression type to use on OTLP trace requests. Options include `gzip`. By default no compression will be used. | -| otel.exporter.otlp.metrics.compression | OTEL_EXPORTER_OTLP_METRICS_COMPRESSION | The compression type to use on OTLP metric requests. Options include `gzip`. By default no compression will be used. | -| otel.exporter.otlp.logs.compression | OTEL_EXPORTER_OTLP_LOGS_COMPRESSION | The compression type to use on OTLP log requests. Options include `gzip`. By default no compression will be used. | -| otel.exporter.otlp.timeout | OTEL_EXPORTER_OTLP_TIMEOUT | The maximum waiting time, in milliseconds, allowed to send each OTLP trace, metric, and log batch. Default is `10000`. | -| otel.exporter.otlp.traces.timeout | OTEL_EXPORTER_OTLP_TRACES_TIMEOUT | The maximum waiting time, in milliseconds, allowed to send each OTLP trace batch. Default is `10000`. | -| otel.exporter.otlp.metrics.timeout | OTEL_EXPORTER_OTLP_METRICS_TIMEOUT | The maximum waiting time, in milliseconds, allowed to send each OTLP metric batch. Default is `10000`. | -| otel.exporter.otlp.logs.timeout | OTEL_EXPORTER_OTLP_LOGS_TIMEOUT | The maximum waiting time, in milliseconds, allowed to send each OTLP log batch. Default is `10000`. | -| otel.exporter.otlp.protocol | OTEL_EXPORTER_OTLP_PROTOCOL | The transport protocol to use on OTLP trace, metric, and log requests. Options include `grpc` and `http/protobuf`. Default is `grpc`. | -| otel.exporter.otlp.traces.protocol | OTEL_EXPORTER_OTLP_TRACES_PROTOCOL | The transport protocol to use on OTLP trace requests. Options include `grpc` and `http/protobuf`. Default is `grpc`. | -| otel.exporter.otlp.metrics.protocol | OTEL_EXPORTER_OTLP_METRICS_PROTOCOL | The transport protocol to use on OTLP metric requests. Options include `grpc` and `http/protobuf`. Default is `grpc`. | -| otel.exporter.otlp.logs.protocol | OTEL_EXPORTER_OTLP_LOGS_PROTOCOL | The transport protocol to use on OTLP log requests. Options include `grpc` and `http/protobuf`. Default is `grpc`. | -| otel.exporter.otlp.metrics.temporality.preference | OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE | The preferred output aggregation temporality. Options include `DELTA` and `CUMULATIVE`. If `CUMULATIVE`, all instruments will have cumulative temporality. If `DELTA`, counter (sync and async) and histograms will be delta, up down counters (sync and async) will be cumulative. Default is `CUMULATIVE`. | -| otel.experimental.exporter.otlp.retry.enabled | OTEL_EXPERIMENTAL_EXPORTER_OTLP_RETRY_ENABLED | If `true`, enable [experimental retry support](#otlp-exporter-retry). Default is `false`. | - -To configure the service name for the OTLP exporter, add the `service.name` key -to the OpenTelemetry Resource ([see below](#opentelemetry-resource)), e.g. `OTEL_RESOURCE_ATTRIBUTES=service.name=myservice`. - -#### OTLP exporter retry - -[OTLP](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#otlpgrpc-response) requires that [transient](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#retry) errors be handled with a retry strategy. When retry is enabled, retryable gRPC status codes will be retried using an exponential backoff with jitter algorithm as described in the [gRPC Retry Design](https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff). - -The policy has the following configuration, which there is currently no way to customize. - -- `maxAttempts`: The maximum number of attempts, including the original request. Defaults to `5`. -- `initialBackoff`: The initial backoff duration. Defaults to `1s` -- `maxBackoff`: The maximum backoff duration. Defaults to `5s`. -- `backoffMultiplier` THe backoff multiplier. Defaults to `1.5`. - -### Jaeger exporter - -The [Jaeger](https://www.jaegertracing.io/docs/1.21/apis/#protobuf-via-grpc-stable) exporter. This exporter uses gRPC for its communications protocol. - -| System property | Environment variable | Description | -|-----------------------------------|-----------------------------------|----------------------------------------------------------------------------------------------------| -| otel.traces.exporter=jaeger | OTEL_TRACES_EXPORTER=jaeger | Select the Jaeger exporter | -| otel.exporter.jaeger.endpoint | OTEL_EXPORTER_JAEGER_ENDPOINT | The Jaeger gRPC endpoint to connect to. Default is `http://localhost:14250`. | -| otel.exporter.jaeger.timeout | OTEL_EXPORTER_JAEGER_TIMEOUT | The maximum waiting time, in milliseconds, allowed to send each batch. Default is `10000`. | - -### Zipkin exporter - -The [Zipkin](https://zipkin.io/zipkin-api/) exporter. It sends JSON in [Zipkin format](https://zipkin.io/zipkin-api/#/default/post_spans) to a specified HTTP URL. - -| System property | Environment variable | Description | -|-------------------------------|-------------------------------|-----------------------------------------------------------------------------------------------------------------------| -| otel.traces.exporter=zipkin | OTEL_TRACES_EXPORTER=zipkin | Select the Zipkin exporter | -| otel.exporter.zipkin.endpoint | OTEL_EXPORTER_ZIPKIN_ENDPOINT | The Zipkin endpoint to connect to. Default is `http://localhost:9411/api/v2/spans`. Currently only HTTP is supported. | - -### Prometheus exporter - -The [Prometheus](https://github.com/prometheus/docs/blob/master/content/docs/instrumenting/exposition_formats.md) exporter. - -| System property | Environment variable | Description | -|----------------------------------|----------------------------------|------------------------------------------------------------------------------------| -| otel.metrics.exporter=prometheus | OTEL_METRICS_EXPORTER=prometheus | Select the Prometheus exporter | -| otel.exporter.prometheus.port | OTEL_EXPORTER_PROMETHEUS_PORT | The local port used to bind the prometheus metric server. Default is `9464`. | -| otel.exporter.prometheus.host | OTEL_EXPORTER_PROMETHEUS_HOST | The local address used to bind the prometheus metric server. Default is `0.0.0.0`. | - -Note that this is a pull exporter - it opens up a server on the local process listening on the specified host and port, which -a Prometheus server scrapes from. - -### Logging exporter - -The logging exporter prints the name of the span along with its attributes to stdout. It's mainly used for testing and debugging. - -| System property | Environment variable | Description | -|-------------------------------|-------------------------------|----------------------------------------------------------------------| -| otel.traces.exporter=logging | OTEL_TRACES_EXPORTER=logging | Select the logging exporter for tracing | -| otel.metrics.exporter=logging | OTEL_METRICS_EXPORTER=logging | Select the logging exporter for metrics | -| otel.logs.exporter=logging | OTEL_LOGS_EXPORTER=logging | Select the logging exporter for logs | - -## Propagator - -The propagators determine which distributed tracing header formats are used, and which baggage propagation header formats are used. - -| System property | Environment variable | Description | -|------------------|----------------------|---------------------------------------------------------------------------------------------------------------------------| -| otel.propagators | OTEL_PROPAGATORS | The propagators to be used. Use a comma-separated list for multiple propagators. Default is `tracecontext,baggage` (W3C). | - -Supported values are - -- `"tracecontext"`: [W3C Trace Context](https://www.w3.org/TR/trace-context/) (add `baggage` as well to include W3C baggage) -- `"baggage"`: [W3C Baggage](https://www.w3.org/TR/baggage/) -- `"b3"`: [B3 Single](https://github.com/openzipkin/b3-propagation#single-header) -- `"b3multi"`: [B3 Multi](https://github.com/openzipkin/b3-propagation#multiple-headers) -- `"jaeger"`: [Jaeger](https://www.jaegertracing.io/docs/1.21/client-libraries/#propagation-format) (includes Jaeger baggage) -- `"xray"`: [AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/xray-concepts.html#xray-concepts-tracingheader) -- `"ottrace"`: [OT Trace](https://github.com/opentracing?q=basic&type=&language=) - -## OpenTelemetry Resource - -The [OpenTelemetry Resource](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/sdk.md) -is a representation of the entity producing telemetry. - -| System property | Environment variable | Description | -|------------------------------------------|------------------------------------------|------------------------------------------------------------------------------------------------------------| -| otel.resource.attributes | OTEL_RESOURCE_ATTRIBUTES | Specify resource attributes in the following format: key1=val1,key2=val2,key3=val3 | -| otel.service.name | OTEL_SERVICE_NAME | Specify logical service name. Takes precedence over `service.name` defined with `otel.resource.attributes` | -| otel.experimental.resource.disabled-keys | OTEL_EXPERIMENTAL_RESOURCE_DISABLED_KEYS | Specify resource attribute keys that are filtered. | - -You almost always want to specify the [`service.name`](https://github.com/open-telemetry/opentelemetry-specification/tree/main/specification/resource/semantic_conventions#service) for your application. -It corresponds to how you describe the application, for example `authservice` could be an application that authenticates requests, and `cats` could be an application that returns information about [cats](https://en.wikipedia.org/wiki/Cat). -You would specify that by setting service name property in one of the following ways: -* directly via `OTEL_SERVICE_NAME=authservice` or `-Dotel.service.name=cats` -* by `service.name` resource attribute like `OTEL_RESOURCE_ATTRIBUTES=service.name=authservice`, or `-Dotel.resource.attributes=service.name=cats,service.namespace=mammals`. - -If not specified, SDK defaults the service name to `unknown_service:java`. - -### Resource Provider SPI - -The [autoconfigure-spi](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/autoconfigure-spi), -part of the SDK extensions, provides a convenient ResourceProvider SPI that adds -[common resource attributes](https://github.com/open-telemetry/opentelemetry-java/tree/main/sdk-extensions/resources) automatically. The SDK extensions include a [predefined set of common resources](https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk-extensions/resources/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider), -[common cloud vendor resources](https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk-extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider), -or you can create your own. - -### Disabling Automatic ResourceProviders - -If you are using the `ResourceProvider` SPI (many instrumentation agent distributions include this automatically), -you can enable / disable one or more of them by using the following configuration items: - -| System property | Environment variable | Description | -|---------------------------------------|---------------------------------------|---------------------------------------------------------------------------------------------| -| otel.java.enabled.resource-providers | OTEL_JAVA_ENABLED_RESOURCE_PROVIDERS | Enables one or more `ResourceProvider` types. If unset, all resource providers are enabled. | -| otel.java.disabled.resource-providers | OTEL_JAVA_DISABLED_RESOURCE_PROVIDERS | Disables one or more `ResourceProvider` types | - -The value for these properties must be a comma separated list of fully qualified `ResourceProvider` classnames. -For example, if you don't want to expose the name of the operating system through the resource, you -can pass the following JVM argument: - -``` --Dotel.java.disabled.resource-providers=io.opentelemetry.sdk.extension.resources.OsResourceProvider -``` - -## Batch span processor - -| System property | Environment variable | Description | -|--------------------------------|--------------------------------|------------------------------------------------------------------------------------| -| otel.bsp.schedule.delay | OTEL_BSP_SCHEDULE_DELAY | The interval, in milliseconds, between two consecutive exports. Default is `5000`. | -| otel.bsp.max.queue.size | OTEL_BSP_MAX_QUEUE_SIZE | The maximum queue size. Default is `2048`. | -| otel.bsp.max.export.batch.size | OTEL_BSP_MAX_EXPORT_BATCH_SIZE | The maximum batch size. Default is `512`. | -| otel.bsp.export.timeout | OTEL_BSP_EXPORT_TIMEOUT | The maximum allowed time, in milliseconds, to export data. Default is `30000`. | - -## Sampler - -The sampler configures whether spans will be recorded for any call to `SpanBuilder.startSpan`. - -| System property | Environment variable | Description | -|-------------------------|-------------------------|-------------------------------------------------------------------------| -| otel.traces.sampler | OTEL_TRACES_SAMPLER | The sampler to use for tracing. Defaults to `parentbased_always_on` | -| otel.traces.sampler.arg | OTEL_TRACES_SAMPLER_ARG | An argument to the configured tracer if supported, for example a ratio. | - -Supported values for `otel.traces.sampler` are - -- "always_on": AlwaysOnSampler -- "always_off": AlwaysOffSampler -- "traceidratio": TraceIdRatioBased. `otel.traces.sampler.arg` sets the ratio. -- "parentbased_always_on": ParentBased(root=AlwaysOnSampler) -- "parentbased_always_off": ParentBased(root=AlwaysOffSampler) -- "parentbased_traceidratio": ParentBased(root=TraceIdRatioBased). `otel.traces.sampler.arg` sets the ratio. - -## Attribute limits - -These properties can be used to control the maximum number and length of attributes. - -| System property | Environment variable | Description | -|-----------------------------------|-----------------------------------|----------------------------------------------------------------------------------------------------------| -| otel.attribute.value.length.limit | OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT | The maximum length of attribute values. Applies to spans and logs. By default there is no limit. | -| otel.attribute.count.limit | OTEL_ATTRIBUTE_COUNT_LIMIT | The maximum number of attributes. Applies to spans, span events, span links, and logs. Default is `128`. | - -## Span limits - -These properties can be used to control the maximum size of spans by placing limits on attributes, events, and links. - -| System property | Environment variable | Description | -|----------------------------------------|----------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------| -| otel.span.attribute.value.length.limit | OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT | The maximum length of span attribute values. Takes precedence over `otel.attribute.value.length.limit`. By default there is no limit. | -| otel.span.attribute.count.limit | OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT | The maximum number of attributes per span. Takes precedence over `otel.attribute.count.limit`. Default is `128`. | -| otel.span.event.count.limit | OTEL_SPAN_EVENT_COUNT_LIMIT | The maximum number of events per span. Default is `128`. | -| otel.span.link.count.limit | OTEL_SPAN_LINK_COUNT_LIMIT | The maximum number of links per span. Default is `128` | - -## Exemplars - -| System property | Environment variable | Description | -|------------------------------|------------------------------|-------------------------------------------------------------------------------------------------------------------| -| otel.metrics.exemplar.filter | OTEL_METRICS_EXEMPLAR_FILTER | The filter for exemplar sampling. Can be `NONE`, `ALL` or `WITH_SAMPLED_TRACE`. Default is `WITH_SAMPLED_TRACE`. | - -## Periodic Metric Reader - -| System property | Environment variable | Description | -|-----------------------------|-----------------------------|----------------------------------------------------------------------------------------------| -| otel.metric.export.interval | OTEL_METRIC_EXPORT_INTERVAL | The interval, in milliseconds, between the start of two export attempts. Default is `60000`. | - -## Customizing the OpenTelemetry SDK - -Autoconfiguration exposes SPI [hooks](../autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi) for customizing behavior programmatically as needed. -It's recommended to use the above configuration properties where possible, only implementing the SPI to add functionality not found in the -SDK by default. -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-autoconfigure +The full documentation on the available configuration options has been moved to +[opentelemetry.io](https://opentelemetry.io/docs/languages/java/configuration/) diff --git a/sdk-extensions/autoconfigure/build.gradle.kts b/sdk-extensions/autoconfigure/build.gradle.kts index e1b51ca4705..692bb0c7812 100644 --- a/sdk-extensions/autoconfigure/build.gradle.kts +++ b/sdk-extensions/autoconfigure/build.gradle.kts @@ -5,211 +5,123 @@ plugins { description = "OpenTelemetry SDK Auto-configuration" otelJava.moduleName.set("io.opentelemetry.sdk.autoconfigure") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf( + "io.opentelemetry.sdk.extension.incubator", + "io.opentelemetry.api.incubator", + "io.opentelemetry.sdk.autoconfigure.declarativeconfig", +)) +// autoconfigure discovers these SPI types at runtime via ServiceLoader +otelJava.osgiServiceLoaderRequires.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider", + "io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider", + "io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider", + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider", + "io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider", + "io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider", + "io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider", +)) +// autoconfigure provides EnvironmentResourceProvider via META-INF/services +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider", +)) dependencies { api(project(":sdk:all")) - api(project(":sdk:metrics")) - api(project(":sdk:logs")) api(project(":sdk-extensions:autoconfigure-spi")) - implementation(project(":semconv")) - - compileOnly(project(":exporters:jaeger")) - compileOnly(project(":exporters:logging")) - compileOnly(project(":exporters:otlp:all")) - compileOnly(project(":exporters:otlp:logs")) - compileOnly(project(":exporters:otlp:common")) - compileOnly(project(":exporters:otlp-http:trace")) - compileOnly(project(":exporters:otlp-http:metrics")) - compileOnly(project(":exporters:otlp-http:logs")) - compileOnly(project(":exporters:prometheus")) - compileOnly(project(":exporters:zipkin")) + compileOnly(project(":api:incubator")) + compileOnly(project(":sdk-extensions:declarative-config")) annotationProcessor("com.google.auto.value:auto-value") - testImplementation(project(path = ":sdk:trace-shaded-deps")) - + testImplementation(project(":sdk:trace-shaded-deps")) testImplementation(project(":sdk:testing")) - testImplementation("com.linecorp.armeria:armeria-junit5") - testImplementation("com.linecorp.armeria:armeria-grpc") - testRuntimeOnly("io.grpc:grpc-netty-shaded") - testImplementation("io.opentelemetry.proto:opentelemetry-proto") + + testImplementation("com.google.guava:guava") + testImplementation("edu.berkeley.cs.jqf:jqf-fuzz") } testing { suites { - val testConfigError by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":extensions:trace-propagators")) - implementation(project(":exporters:jaeger")) - implementation(project(":exporters:logging")) - implementation(project(":exporters:otlp:all")) - implementation(project(":exporters:otlp:logs")) - implementation(project(":exporters:prometheus")) - implementation(project(":exporters:zipkin")) - } - } - val testFullConfig by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":extensions:aws")) - implementation(project(":extensions:trace-propagators")) - implementation(project(":exporters:jaeger")) - implementation(project(":exporters:logging")) - implementation(project(":exporters:otlp:all")) - implementation(project(":exporters:otlp:logs")) - implementation(project(":exporters:otlp:common")) - implementation(project(":exporters:prometheus")) - implementation(project(":exporters:zipkin")) - implementation(project(":sdk-extensions:resources")) - implementation(project(":sdk:testing")) - implementation(project(":semconv")) - - implementation("com.google.guava:guava") - implementation("io.opentelemetry.proto:opentelemetry-proto") - implementation("com.linecorp.armeria:armeria-junit5") - implementation("com.linecorp.armeria:armeria-grpc") - runtimeOnly("io.grpc:grpc-netty-shaded") - } - + register("testAutoConfigureOrder") { targets { all { testTask { - environment("OTEL_LOGS_EXPORTER", "otlp") - environment("OTEL_RESOURCE_ATTRIBUTES", "service.name=test,cat=meow") - environment("OTEL_PROPAGATORS", "tracecontext,baggage,b3,b3multi,jaeger,ottrace,xray,test") - environment("OTEL_BSP_SCHEDULE_DELAY", "10") - environment("OTEL_METRIC_EXPORT_INTERVAL", "10") - environment("OTEL_EXPORTER_OTLP_HEADERS", "cat=meow,dog=bark") - environment("OTEL_EXPORTER_OTLP_TIMEOUT", "5000") - environment("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "2") - environment("OTEL_TEST_CONFIGURED", "true") - environment("OTEL_TEST_WRAPPED", "1") + environment("OTEL_TRACES_EXPORTER", "none") + environment("OTEL_METRICS_EXPORTER", "none") + environment("OTEL_LOGS_EXPORTER", "none") } } } } - val testInitializeRegistersGlobal by registering(JvmTestSuite::class) { + register("testConditionalResourceProvider") { targets { all { testTask { environment("OTEL_TRACES_EXPORTER", "none") environment("OTEL_METRICS_EXPORTER", "none") + environment("OTEL_LOGS_EXPORTER", "none") } } } } - val testJaeger by registering(JvmTestSuite::class) { + register("testFullConfig") { dependencies { - implementation(project(":exporters:jaeger")) - implementation(project(":exporters:jaeger-proto")) + implementation(project(":extensions:trace-propagators")) + implementation(project(":exporters:logging")) + implementation(project(":exporters:logging-otlp")) + implementation(project(":exporters:otlp:all")) + implementation(project(":exporters:prometheus")) + implementation("io.prometheus:prometheus-metrics-exporter-httpserver") { + exclude(group = "io.prometheus", module = "prometheus-metrics-exposition-formats") + } + implementation(project(":sdk:testing")) + implementation(project(":sdk:trace-shaded-deps")) + implementation(project(":sdk-extensions:jaeger-remote-sampler")) + implementation(project(":sdk-extensions:incubator")) + implementation(project(":sdk-extensions:declarative-config")) + implementation("com.google.guava:guava") + implementation("io.opentelemetry.proto:opentelemetry-proto") implementation("com.linecorp.armeria:armeria-junit5") implementation("com.linecorp.armeria:armeria-grpc") - runtimeOnly("io.grpc:grpc-netty-shaded") } targets { all { testTask { - environment("OTEL_METRICS_EXPORTER", "none") - environment("OTEL_TRACES_EXPORTER", "jaeger") - environment("OTEL_BSP_SCHEDULE_DELAY", "10") + environment("OTEL_SERVICE_NAME", "test") + environment("OTEL_RESOURCE_ATTRIBUTES", "cat=meow") + environment("OTEL_PROPAGATORS", "tracecontext,baggage,b3,b3multi,jaeger,ottrace,test") + environment("OTEL_EXPORTER_OTLP_HEADERS", "cat=meow,dog=bark") + environment("OTEL_EXPORTER_OTLP_TIMEOUT", "5000") + environment("OTEL_TEST_CONFIGURED", "true") + environment("OTEL_TEST_WRAPPED", "1") + environment("OTEL_EXPERIMENTAL_SDK_TELEMETRY_VERSION", "latest") } } } } - val testOtlpGrpc by registering(JvmTestSuite::class) { + register("testIncubating") { dependencies { + implementation(project(":sdk-extensions:declarative-config")) + implementation(project(":exporters:logging")) implementation(project(":exporters:otlp:all")) - implementation(project(":exporters:otlp:logs")) - implementation(project(":exporters:otlp:common")) implementation(project(":sdk:testing")) implementation("io.opentelemetry.proto:opentelemetry-proto") implementation("com.linecorp.armeria:armeria-junit5") implementation("com.linecorp.armeria:armeria-grpc") - runtimeOnly("io.grpc:grpc-netty-shaded") - } - } - val testOtlpHttp by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:otlp-http:trace")) - implementation(project(":exporters:otlp-http:metrics")) - implementation(project(":exporters:otlp-http:logs")) - implementation(project(":exporters:otlp:common")) - implementation(project(":sdk:testing")) - - implementation("com.google.guava:guava") - implementation("com.linecorp.armeria:armeria-junit5") - implementation("com.squareup.okhttp3:okhttp") - implementation("com.squareup.okhttp3:okhttp-tls") - implementation("io.opentelemetry.proto:opentelemetry-proto") - } - } - val testPrometheus by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":exporters:prometheus")) - - implementation("com.linecorp.armeria:armeria-junit5") - } - - targets { - all { - testTask { - environment("OTEL_TRACES_EXPORTER", "none") - environment("OTEL_METRICS_EXPORTER", "prometheus") - environment("OTEL_METRIC_EXPORT_INTERVAL", "10") - } - } - } - } - val testResourceDisabledByProperty by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":sdk-extensions:resources")) - } - - targets { - all { - testTask { - jvmArgs("-Dotel.java.disabled.resource-providers=io.opentelemetry.sdk.extension.resources.OsResourceProvider,io.opentelemetry.sdk.extension.resources.ProcessResourceProvider") - // Properties win, this is ignored. - environment("OTEL_JAVA_DISABLED_RESOURCE_PROVIDERS", "io.opentelemetry.sdk.extension.resources.ProcessRuntimeResourceProvider") - environment("OTEL_TRACES_EXPORTER", "none") - environment("OTEL_METRICS_EXPORTER", "none") - } - } } } - val testResourceDisabledByEnv by registering(JvmTestSuite::class) { - dependencies { - implementation(project(":sdk-extensions:resources")) - } - targets { - all { - testTask { - environment("OTEL_JAVA_DISABLED_RESOURCE_PROVIDERS", "io.opentelemetry.sdk.extension.resources.OsResourceProvider,io.opentelemetry.sdk.extension.resources.ProcessResourceProvider") - environment("OTEL_TRACES_EXPORTER", "none") - environment("OTEL_METRICS_EXPORTER", "none") - } - } - } - } - val testZipkin by registering(JvmTestSuite::class) { + register("testDeclarativeConfigSpi") { dependencies { - implementation(project(":exporters:zipkin")) - - implementation("com.linecorp.armeria:armeria-junit5") - } - - targets { - all { - testTask { - environment("OTEL_METRICS_EXPORTER", "none") - environment("OTEL_TRACES_EXPORTER", "zipkin") - environment("OTEL_BSP_SCHEDULE_DELAY", "10") - } - } + implementation(project(":sdk-extensions:declarative-config")) + implementation(project(":exporters:logging")) + implementation(project(":sdk:testing")) } } } diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdk.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdk.java index 3576236a7bc..d83fc3b7479 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdk.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdk.java @@ -6,15 +6,22 @@ package io.opentelemetry.sdk.autoconfigure; import com.google.auto.value.AutoValue; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.incubator.ExtendedOpenTelemetry; import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.internal.AutoConfigureUtil; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** * An auto-configured OpenTelemetry SDK. As an alternative to programmatically configuring the SDK * using {@link OpenTelemetrySdk#builder()}, this package can be used to automatically configure the * SDK using environment properties specified by OpenTelemetry. + * + * @since 1.28.0 */ @Immutable @AutoValue @@ -24,11 +31,10 @@ public abstract class AutoConfiguredOpenTelemetrySdk { * Returns an {@link AutoConfiguredOpenTelemetrySdk} automatically initialized through recognized * system properties and environment variables. * - *

      This will automatically set the resulting SDK as the {@link - * io.opentelemetry.api.GlobalOpenTelemetry} instance. + *

      This will automatically set the resulting SDK as the {@link GlobalOpenTelemetry} instance. */ public static AutoConfiguredOpenTelemetrySdk initialize() { - return builder().build(); + return builder().setResultAsGlobal().build(); } /** @@ -40,18 +46,36 @@ public static AutoConfiguredOpenTelemetrySdkBuilder builder() { } static AutoConfiguredOpenTelemetrySdk create( - OpenTelemetrySdk sdk, Resource resource, ConfigProperties config) { + OpenTelemetrySdk sdk, Resource resource, @Nullable ConfigProperties config) { return new AutoValue_AutoConfiguredOpenTelemetrySdk(sdk, resource, config); } - /** Returns the {@link OpenTelemetrySdk} that was auto-configured. */ + /** + * Returns the {@link OpenTelemetrySdk} that was auto-configured, or an effectively noop instance + * if the SDK has been disabled. + * + *

      The instance returned if the SDK is disabled is equivalent to {@code + * OpenTelemetrySdk.builder().build()}, which is notably not the same as {@link + * OpenTelemetry#noop()}. + */ public abstract OpenTelemetrySdk getOpenTelemetrySdk(); /** Returns the {@link Resource} that was auto-configured. */ - public abstract Resource getResource(); + abstract Resource getResource(); - /** Returns the {@link ConfigProperties} used for auto-configuration. */ - public abstract ConfigProperties getConfig(); + /** + * Returns the {@link ConfigProperties} used for auto-configuration, or {@code null} if + * declarative configuration was used. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * AutoConfigureUtil#getConfig(AutoConfiguredOpenTelemetrySdk)}. + * + *

      If declarative config was used, {@link #getOpenTelemetrySdk()} will return an instance of + * {@link ExtendedOpenTelemetry} and you can use {@link ExtendedOpenTelemetry#getConfigProvider()} + * to access the configuration. + */ + @Nullable + abstract ConfigProperties getConfig(); AutoConfiguredOpenTelemetrySdk() {} } diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java index b95de992d2e..95faa9284eb 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkBuilder.java @@ -8,33 +8,44 @@ import static java.util.Objects.requireNonNull; import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.common.ComponentLoader; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.OpenTelemetrySdkBuilder; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; -import io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder; -import io.opentelemetry.sdk.logs.export.LogExporter; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.io.Closeable; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.ServiceLoader; -import java.util.concurrent.TimeUnit; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; +import java.util.function.Function; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -44,11 +55,28 @@ * A builder for configuring auto-configuration of the OpenTelemetry SDK. Notably, auto-configured * components can be customized, for example by delegating to them from a wrapper that tweaks * behavior such as filtering out telemetry attributes. + * + * @since 1.28.0 */ public final class AutoConfiguredOpenTelemetrySdkBuilder implements AutoConfigurationCustomizer { private static final Logger logger = Logger.getLogger(AutoConfiguredOpenTelemetrySdkBuilder.class.getName()); + private static final boolean DECLARATIVE_CONFIG_AVAILABLE; + + static { + boolean declarativeConfigAvailable = false; + try { + Class.forName( + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration", + false, + AutoConfiguredOpenTelemetrySdkBuilder.class.getClassLoader()); + declarativeConfigAvailable = true; + } catch (ClassNotFoundException e) { + // Not available + } + DECLARATIVE_CONFIG_AVAILABLE = declarativeConfigAvailable; + } @Nullable private ConfigProperties config; @@ -58,6 +86,9 @@ public final class AutoConfiguredOpenTelemetrySdkBuilder implements AutoConfigur propagatorCustomizer = (a, unused) -> a; private BiFunction spanExporterCustomizer = (a, unused) -> a; + + private BiFunction + spanProcessorCustomizer = (a, unused) -> a; private BiFunction samplerCustomizer = (a, unused) -> a; @@ -65,23 +96,33 @@ public final class AutoConfiguredOpenTelemetrySdkBuilder implements AutoConfigur meterProviderCustomizer = (a, unused) -> a; private BiFunction metricExporterCustomizer = (a, unused) -> a; + private BiFunction + metricReaderCustomizer = (a, unused) -> a; - private BiFunction - logEmitterProviderCustomizer = (a, unused) -> a; - private BiFunction - logExporterCustomizer = (a, unused) -> a; + private BiFunction + loggerProviderCustomizer = (a, unused) -> a; + private BiFunction + logRecordExporterCustomizer = (a, unused) -> a; + private BiFunction + logRecordProcessorCustomizer = (a, unused) -> a; private BiFunction resourceCustomizer = (a, unused) -> a; private Supplier> propertiesSupplier = Collections::emptyMap; - private ClassLoader serviceClassLoader = - AutoConfiguredOpenTelemetrySdkBuilder.class.getClassLoader(); + private final List>> propertiesCustomizers = + new ArrayList<>(); + + private Function configPropertiesCustomizer = + Function.identity(); + + private ComponentLoader componentLoader = + ComponentLoader.forClassLoader(AutoConfiguredOpenTelemetrySdk.class.getClassLoader()); private boolean registerShutdownHook = true; - private boolean setResultAsGlobal = true; + private boolean setResultAsGlobal = false; private boolean customized; @@ -89,7 +130,8 @@ public final class AutoConfiguredOpenTelemetrySdkBuilder implements AutoConfigur /** * Sets the {@link ConfigProperties} to use when resolving properties for auto-configuration. - * {@link #addPropertiesSupplier(Supplier)} will have no effect if this method is used. + * {@link #addPropertiesSupplier(Supplier)} and {@link #addPropertiesCustomizer(Function)} will + * have no effect if this method is used. */ AutoConfiguredOpenTelemetrySdkBuilder setConfig(ConfigProperties config) { requireNonNull(config, "config"); @@ -98,7 +140,7 @@ AutoConfiguredOpenTelemetrySdkBuilder setConfig(ConfigProperties config) { } /** - * Adds a {@link BiFunction} to invoke the with the {@link SdkTracerProviderBuilder} to allow + * Adds a {@link BiFunction} to invoke with the {@link SdkTracerProviderBuilder} to allow * customization. The return value of the {@link BiFunction} will replace the passed-in argument. * *

      Multiple calls will execute the customizers in order. @@ -174,6 +216,26 @@ public AutoConfiguredOpenTelemetrySdkBuilder addSpanExporterCustomizer( return this; } + /** + * Adds a {@link BiFunction} to invoke for all autoconfigured {@link + * io.opentelemetry.sdk.trace.SpanProcessor}. The return value of the {@link BiFunction} will + * replace the passed-in argument. In contrast to {@link #addSpanExporterCustomizer(BiFunction)} + * this allows modifications to happen before batching occurs. As a result, it is possible to + * efficiently filter spans, add artificial spans or delay spans for enhancing them with external, + * delayed data. + * + *

      Multiple calls will execute the customizers in order. + */ + @Override + public AutoConfiguredOpenTelemetrySdkBuilder addSpanProcessorCustomizer( + BiFunction + spanProcessorCustomizer) { + requireNonNull(spanProcessorCustomizer, "spanProcessorCustomizer"); + this.spanProcessorCustomizer = + mergeCustomizer(this.spanProcessorCustomizer, spanProcessorCustomizer); + return this; + } + /** * Adds a {@link Supplier} of a map of property names and values to use as defaults for the {@link * ConfigProperties} used during auto-configuration. The order of precedence of properties is @@ -191,7 +253,38 @@ public AutoConfiguredOpenTelemetrySdkBuilder addPropertiesSupplier( } /** - * Adds a {@link BiFunction} to invoke the with the {@link SdkMeterProviderBuilder} to allow + * Adds a {@link Function} to invoke with the {@link ConfigProperties} to allow customization. The + * return value of the {@link Function} will be merged into the {@link ConfigProperties} before it + * is used for auto-configuration, overwriting the properties that are already there. + * + *

      Multiple calls will cause properties to be merged in order, with later ones overwriting + * duplicate keys in earlier ones. + */ + @Override + public AutoConfiguredOpenTelemetrySdkBuilder addPropertiesCustomizer( + Function> propertiesCustomizer) { + requireNonNull(propertiesCustomizer, "propertiesCustomizer"); + this.propertiesCustomizers.add(propertiesCustomizer); + return this; + } + + /** + * Adds a {@link Function} to invoke with the {@link ConfigProperties} to allow customization. + * + *

      The argument to the function is the {@link ConfigProperties}, with the {@link + * #addPropertiesCustomizer(Function)} already applied. + * + *

      The return value of the {@link Function} replace the {@link ConfigProperties} to be used. + */ + AutoConfiguredOpenTelemetrySdkBuilder setConfigPropertiesCustomizer( + Function configPropertiesCustomizer) { + requireNonNull(configPropertiesCustomizer, "configPropertiesCustomizer"); + this.configPropertiesCustomizer = configPropertiesCustomizer; + return this; + } + + /** + * Adds a {@link BiFunction} to invoke with the {@link SdkMeterProviderBuilder} to allow * customization. The return value of the {@link BiFunction} will replace the passed-in argument. * *

      Multiple calls will execute the customizers in order. @@ -224,59 +317,93 @@ public AutoConfiguredOpenTelemetrySdkBuilder addMetricExporterCustomizer( } /** - * Adds a {@link BiFunction} to invoke the with the {@link SdkLogEmitterProviderBuilder} to allow + * Adds a {@link BiFunction} to invoke with the autoconfigured {@link MetricReader} to allow * customization. The return value of the {@link BiFunction} will replace the passed-in argument. * *

      Multiple calls will execute the customizers in order. */ @Override - public AutoConfiguredOpenTelemetrySdkBuilder addLogEmitterProviderCustomizer( - BiFunction - logEmitterProviderCustomizer) { - requireNonNull(logEmitterProviderCustomizer, "logEmitterProviderCustomizer"); - this.logEmitterProviderCustomizer = - mergeCustomizer(this.logEmitterProviderCustomizer, logEmitterProviderCustomizer); + public AutoConfiguredOpenTelemetrySdkBuilder addMetricReaderCustomizer( + BiFunction readerCustomizer) { + requireNonNull(readerCustomizer, "readerCustomizer"); + this.metricReaderCustomizer = mergeCustomizer(this.metricReaderCustomizer, readerCustomizer); return this; } /** - * Adds a {@link BiFunction} to invoke with the default autoconfigured {@link LogExporter} to - * allow customization. The return value of the {@link BiFunction} will replace the passed-in + * Adds a {@link BiFunction} to invoke with the {@link SdkLoggerProviderBuilder} to allow + * customization. The return value of the {@link BiFunction} will replace the passed-in argument. + * + *

      Multiple calls will execute the customizers in order. + */ + @Override + public AutoConfiguredOpenTelemetrySdkBuilder addLoggerProviderCustomizer( + BiFunction + loggerProviderCustomizer) { + requireNonNull(loggerProviderCustomizer, "loggerProviderCustomizer"); + this.loggerProviderCustomizer = + mergeCustomizer(this.loggerProviderCustomizer, loggerProviderCustomizer); + return this; + } + + /** + * Adds a {@link BiFunction} to invoke with the default autoconfigured {@link LogRecordExporter} + * to allow customization. The return value of the {@link BiFunction} will replace the passed-in * argument. * *

      Multiple calls will execute the customizers in order. */ @Override - public AutoConfiguredOpenTelemetrySdkBuilder addLogExporterCustomizer( - BiFunction - logExporterCustomizer) { - requireNonNull(logExporterCustomizer, "logExporterCustomizer"); - this.logExporterCustomizer = mergeCustomizer(this.logExporterCustomizer, logExporterCustomizer); + public AutoConfiguredOpenTelemetrySdkBuilder addLogRecordExporterCustomizer( + BiFunction + logRecordExporterCustomizer) { + requireNonNull(logRecordExporterCustomizer, "logRecordExporterCustomizer"); + this.logRecordExporterCustomizer = + mergeCustomizer(this.logRecordExporterCustomizer, logRecordExporterCustomizer); return this; } /** - * Control the registration of a shutdown hook to shut down the SDK when appropriate. By default, + * Adds a {@link BiFunction} to invoke for all autoconfigured {@link + * io.opentelemetry.sdk.logs.LogRecordProcessor}s. The return value of the {@link BiFunction} will + * replace the passed-in argument. In contrast to {@link + * #addLogRecordExporterCustomizer(BiFunction)} this allows modifications to happen before + * batching occurs. As a result, it is possible to efficiently filter logs, add artificial logs or + * delay logs for enhancing them with external, delayed data. + * + *

      Multiple calls will execute the customizers in order. + */ + @Override + public AutoConfiguredOpenTelemetrySdkBuilder addLogRecordProcessorCustomizer( + BiFunction + logRecordProcessorCustomizer) { + requireNonNull(logRecordProcessorCustomizer, "logRecordProcessorCustomizer"); + this.logRecordProcessorCustomizer = + mergeCustomizer(this.logRecordProcessorCustomizer, logRecordProcessorCustomizer); + return this; + } + + /** + * Disable the registration of a shutdown hook to shut down the SDK when appropriate. By default, * the shutdown hook is registered. * *

      Skipping the registration of the shutdown hook may cause unexpected behavior. This * configuration is for SDK consumers that require control over the SDK lifecycle. In this case, * alternatives must be provided by the SDK consumer to shut down the SDK. - * - * @param registerShutdownHook a boolean true will register the hook, otherwise - * false will skip registration. */ - public AutoConfiguredOpenTelemetrySdkBuilder registerShutdownHook(boolean registerShutdownHook) { - this.registerShutdownHook = registerShutdownHook; + public AutoConfiguredOpenTelemetrySdkBuilder disableShutdownHook() { + this.registerShutdownHook = false; return this; } /** * Sets whether the configured {@link OpenTelemetrySdk} should be set as the application's * {@linkplain io.opentelemetry.api.GlobalOpenTelemetry global} instance. + * + *

      By default, {@link GlobalOpenTelemetry} is not set. */ - public AutoConfiguredOpenTelemetrySdkBuilder setResultAsGlobal(boolean setResultAsGlobal) { - this.setResultAsGlobal = setResultAsGlobal; + public AutoConfiguredOpenTelemetrySdkBuilder setResultAsGlobal() { + this.setResultAsGlobal = true; return this; } @@ -284,7 +411,14 @@ public AutoConfiguredOpenTelemetrySdkBuilder setResultAsGlobal(boolean setResult public AutoConfiguredOpenTelemetrySdkBuilder setServiceClassLoader( ClassLoader serviceClassLoader) { requireNonNull(serviceClassLoader, "serviceClassLoader"); - this.serviceClassLoader = serviceClassLoader; + this.componentLoader = ComponentLoader.forClassLoader(serviceClassLoader); + return this; + } + + /** Sets the {@link ComponentLoader} to be used to load SPI implementations. */ + public AutoConfiguredOpenTelemetrySdkBuilder setComponentLoader(ComponentLoader componentLoader) { + requireNonNull(componentLoader, "componentLoader"); + this.componentLoader = componentLoader; return this; } @@ -293,104 +427,230 @@ public AutoConfiguredOpenTelemetrySdkBuilder setServiceClassLoader( * the settings of this {@link AutoConfiguredOpenTelemetrySdkBuilder}. */ public AutoConfiguredOpenTelemetrySdk build() { + if (!setResultAsGlobal) { + return buildImpl(); + } + AtomicReference autoConfiguredRef = new AtomicReference<>(); + GlobalOpenTelemetry.set(() -> { + AutoConfiguredOpenTelemetrySdk sdk = buildImpl(); + autoConfiguredRef.set(sdk); + return sdk.getOpenTelemetrySdk(); + }); + AutoConfiguredOpenTelemetrySdk sdk = Objects.requireNonNull(autoConfiguredRef.get()); + logger.log( + Level.FINE, + "Global OpenTelemetry set to {0} by autoconfiguration", + sdk.getOpenTelemetrySdk()); + return sdk; + } + + private AutoConfiguredOpenTelemetrySdk buildImpl() { + AutoConfiguredOpenTelemetrySdk fromFileConfiguration = + maybeConfigureFromFile( + this.config != null + ? this.config + : DefaultConfigProperties.create(Collections.emptyMap(), componentLoader), + componentLoader); + if (fromFileConfiguration != null) { + maybeRegisterShutdownHook(fromFileConfiguration.getOpenTelemetrySdk()); + return fromFileConfiguration; + } + + SpiHelper spiHelper = SpiHelper.create(componentLoader); if (!customized) { customized = true; mergeSdkTracerProviderConfigurer(); for (AutoConfigurationCustomizerProvider customizer : - ServiceLoader.load(AutoConfigurationCustomizerProvider.class, serviceClassLoader)) { + spiHelper.loadOrdered(AutoConfigurationCustomizerProvider.class)) { customizer.customize(this); } } - ConfigProperties config = getConfig(); Resource resource = - ResourceConfiguration.configureResource(config, serviceClassLoader, resourceCustomizer); + ResourceConfiguration.configureResource(config, spiHelper, resourceCustomizer); + + // Track any closeable resources created throughout configuration. If an exception short + // circuits configuration, partially configured components will be closed. + List closeables = new ArrayList<>(); + + try { + OpenTelemetrySdkBuilder sdkBuilder = OpenTelemetrySdk.builder(); + + // The propagation system is part of the API and functions in the absence of an SDK. + ContextPropagators propagators = + PropagatorConfiguration.configurePropagators(config, spiHelper, propagatorCustomizer); + sdkBuilder.setPropagators(propagators); + + boolean sdkEnabled = !config.getBoolean("otel.sdk.disabled", false); + if (sdkEnabled) { + configureSdk(sdkBuilder, config, resource, spiHelper, closeables); + } + + OpenTelemetrySdk openTelemetrySdk = sdkBuilder.build(); + maybeRegisterShutdownHook(openTelemetrySdk); + callAutoConfigureListeners(spiHelper, openTelemetrySdk); + + return AutoConfiguredOpenTelemetrySdk.create(openTelemetrySdk, resource, config); + } catch (RuntimeException e) { + logger.info( + "Error encountered during autoconfiguration. Closing partially configured components."); + for (Closeable closeable : closeables) { + try { + logger.fine("Closing " + closeable.getClass().getName()); + closeable.close(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Error closing " + closeable.getClass().getName(), ex); + } + } + if (e instanceof ConfigurationException) { + throw e; + } + throw new ConfigurationException("Unexpected configuration error", e); + } + } + // Visible for testing + void configureSdk( + OpenTelemetrySdkBuilder sdkBuilder, + ConfigProperties config, + Resource resource, + SpiHelper spiHelper, + List closeables) { SdkMeterProviderBuilder meterProviderBuilder = SdkMeterProvider.builder(); meterProviderBuilder.setResource(resource); + MeterProviderConfiguration.configureMeterProvider( - meterProviderBuilder, config, serviceClassLoader, metricExporterCustomizer); + meterProviderBuilder, + config, + spiHelper, + metricReaderCustomizer, + metricExporterCustomizer, + closeables); meterProviderBuilder = meterProviderCustomizer.apply(meterProviderBuilder, config); SdkMeterProvider meterProvider = meterProviderBuilder.build(); + closeables.add(meterProvider); SdkTracerProviderBuilder tracerProviderBuilder = SdkTracerProvider.builder(); tracerProviderBuilder.setResource(resource); TracerProviderConfiguration.configureTracerProvider( tracerProviderBuilder, config, - serviceClassLoader, + spiHelper, meterProvider, spanExporterCustomizer, - samplerCustomizer); + spanProcessorCustomizer, + samplerCustomizer, + closeables); tracerProviderBuilder = tracerProviderCustomizer.apply(tracerProviderBuilder, config); SdkTracerProvider tracerProvider = tracerProviderBuilder.build(); + closeables.add(tracerProvider); - SdkLogEmitterProviderBuilder logEmitterProviderBuilder = SdkLogEmitterProvider.builder(); - logEmitterProviderBuilder.setResource(resource); - LogEmitterProviderConfiguration.configureLogEmitterProvider( - logEmitterProviderBuilder, config, meterProvider, logExporterCustomizer); - logEmitterProviderBuilder = - logEmitterProviderCustomizer.apply(logEmitterProviderBuilder, config); - SdkLogEmitterProvider logEmitterProvider = logEmitterProviderBuilder.build(); - - if (registerShutdownHook) { - Runtime.getRuntime() - .addShutdownHook( - new Thread( - () -> { - List shutdown = new ArrayList<>(); - shutdown.add(tracerProvider.shutdown()); - shutdown.add(meterProvider.shutdown()); - shutdown.add(logEmitterProvider.shutdown()); - CompletableResultCode.ofAll(shutdown).join(10, TimeUnit.SECONDS); - })); - } + SdkLoggerProviderBuilder loggerProviderBuilder = SdkLoggerProvider.builder(); + loggerProviderBuilder.setResource(resource); + LoggerProviderConfiguration.configureLoggerProvider( + loggerProviderBuilder, + config, + spiHelper, + meterProvider, + logRecordExporterCustomizer, + logRecordProcessorCustomizer, + closeables); + loggerProviderBuilder = loggerProviderCustomizer.apply(loggerProviderBuilder, config); + SdkLoggerProvider loggerProvider = loggerProviderBuilder.build(); + closeables.add(loggerProvider); + + sdkBuilder + .setTracerProvider(tracerProvider) + .setLoggerProvider(loggerProvider) + .setMeterProvider(meterProvider); + } - ContextPropagators propagators = - PropagatorConfiguration.configurePropagators( - config, serviceClassLoader, propagatorCustomizer); + @Nullable + private static AutoConfiguredOpenTelemetrySdk maybeConfigureFromFile( + ConfigProperties config, ComponentLoader componentLoader) { + if (DECLARATIVE_CONFIG_AVAILABLE) { + AutoConfiguredOpenTelemetrySdk sdk = DeclarativeConfigUtil.configureFromSpi(componentLoader); + if (sdk != null) { + logger.fine("Autoconfigured from SPI by opentelemetry-sdk-extension-declarative-config"); + return sdk; + } + } - OpenTelemetrySdkBuilder sdkBuilder = - OpenTelemetrySdk.builder() - .setTracerProvider(tracerProvider) - .setLogEmitterProvider(logEmitterProvider) - .setMeterProvider(meterProvider) - .setPropagators(propagators); + String configurationFile = config.getString("otel.config.file"); + if (configurationFile == null || configurationFile.isEmpty()) { + return null; + } - OpenTelemetrySdk openTelemetrySdk = sdkBuilder.build(); + if (!DECLARATIVE_CONFIG_AVAILABLE) { + throw new ConfigurationException( + "Cannot autoconfigure from config file without opentelemetry-sdk-extension-declarative-config on the classpath"); + } + return DeclarativeConfigUtil.configureFromFile(logger, configurationFile, componentLoader); + } - if (setResultAsGlobal) { - GlobalOpenTelemetry.set(openTelemetrySdk); - logger.log( - Level.FINE, "Global OpenTelemetrySdk set to {0} by autoconfiguration", openTelemetrySdk); + private void maybeRegisterShutdownHook(OpenTelemetrySdk openTelemetrySdk) { + if (!registerShutdownHook) { + return; } + Runtime.getRuntime().addShutdownHook(shutdownHook(openTelemetrySdk)); + } - return AutoConfiguredOpenTelemetrySdk.create(openTelemetrySdk, resource, config); + // Visible for testing + void callAutoConfigureListeners(SpiHelper spiHelper, OpenTelemetrySdk openTelemetrySdk) { + for (AutoConfigureListener listener : spiHelper.getListeners()) { + try { + listener.afterAutoConfigure(openTelemetrySdk); + } catch (Throwable throwable) { + logger.log( + Level.WARNING, "Error invoking listener " + listener.getClass().getName(), throwable); + } + } } @SuppressWarnings("deprecation") // Support deprecated SdkTracerProviderConfigurer - private void mergeSdkTracerProviderConfigurer() { - for (io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer configurer : - ServiceLoader.load( - io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer.class, - serviceClassLoader)) { - addTracerProviderCustomizer( - (builder, config) -> { - configurer.configure(builder, config); - return builder; - }); + void mergeSdkTracerProviderConfigurer() { + for (SdkTracerProviderConfigurer configurer : + componentLoader.load(SdkTracerProviderConfigurer.class)) { + addTracerProviderCustomizer((builder, config) -> { + configurer.configure(builder, config); + return builder; + }); } } private ConfigProperties getConfig() { ConfigProperties config = this.config; if (config == null) { - config = DefaultConfigProperties.get(propertiesSupplier.get()); + config = computeConfigProperties(); } return config; } + private ConfigProperties computeConfigProperties() { + DefaultConfigProperties properties = + DefaultConfigProperties.create(propertiesSupplier.get(), componentLoader); + for (Function> customizer : propertiesCustomizers) { + Map overrides = customizer.apply(properties); + properties = properties.withOverrides(overrides); + } + return configPropertiesCustomizer.apply(properties); + } + + // Visible for testing + @SuppressWarnings("SystemOut") + Thread shutdownHook(OpenTelemetrySdk sdk) { + return new Thread(() -> { + try { + sdk.close(); + } catch (Throwable e) { + // https://github.com/open-telemetry/opentelemetry-java/issues/6827 + // logging deps might not be on the classpath at this point + System.out.printf("%s Flush failed during shutdown: %s%n", Level.WARNING, e); + } + }); + } + private static BiFunction mergeCustomizer( BiFunction first, BiFunction second) { diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ClasspathUtil.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ClasspathUtil.java deleted file mode 100644 index 82d67de1145..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ClasspathUtil.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; - -final class ClasspathUtil { - - @SuppressWarnings("UnusedException") - static void checkClassExists(String className, String featureName, String requiredLibrary) { - try { - Class.forName(className); - } catch (ClassNotFoundException unused) { - throw new ConfigurationException( - featureName - + " enabled but " - + requiredLibrary - + " not found on classpath. " - + "Make sure to add it as a dependency to enable this feature."); - } - } - - private ClasspathUtil() {} -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigUtil.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigUtil.java new file mode 100644 index 00000000000..32fab92b655 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigUtil.java @@ -0,0 +1,77 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigResult; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * Utilities for interacting with ({@code + * io.opentelemetry:opentelemetry-sdk-extension-declarative-config}, which is not guaranteed to be + * present on the classpath. For all methods, callers MUST first separately reflectively confirm + * that declarative config is available on the classpath. + */ +final class DeclarativeConfigUtil { + + private DeclarativeConfigUtil() {} + + static AutoConfiguredOpenTelemetrySdk configureFromFile( + Logger logger, String configurationFile, ComponentLoader componentLoader) { + logger.fine("Autoconfiguring from configuration file: " + configurationFile); + try (FileInputStream fis = new FileInputStream(configurationFile)) { + OpenTelemetryConfigurationModel model = DeclarativeConfiguration.parse(fis); + return create(model, componentLoader); + } catch (DeclarativeConfigException e) { + throw toConfigurationException(e); + } catch (FileNotFoundException e) { + throw new ConfigurationException("Configuration file not found", e); + } catch (IOException e) { + // IOException (other than FileNotFoundException which is caught above) is only thrown + // above by FileInputStream.close() + throw new ConfigurationException("Error closing file", e); + } + } + + @Nullable + public static AutoConfiguredOpenTelemetrySdk configureFromSpi(ComponentLoader componentLoader) { + for (DeclarativeConfigurationProvider provider : + componentLoader.load(DeclarativeConfigurationProvider.class)) { + OpenTelemetryConfigurationModel model = provider.getConfigurationModel(); + if (model != null) { + return create(model, componentLoader); + } + } + return null; + } + + private static AutoConfiguredOpenTelemetrySdk create( + OpenTelemetryConfigurationModel model, ComponentLoader componentLoader) { + try { + DeclarativeConfigResult result = DeclarativeConfiguration.create(model, componentLoader); + return AutoConfiguredOpenTelemetrySdk.create(result.getSdk(), result.getResource(), null); + } catch (DeclarativeConfigException e) { + throw toConfigurationException(e); + } + } + + private static ConfigurationException toConfigurationException( + DeclarativeConfigException exception) { + String message = requireNonNull(exception.getMessage()); + return new ConfigurationException(message, exception); + } +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/DefaultConfigProperties.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/DefaultConfigProperties.java deleted file mode 100644 index 97a20fb90e0..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/DefaultConfigProperties.java +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static java.util.stream.Collectors.groupingBy; -import static java.util.stream.Collectors.joining; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import java.time.Duration; -import java.util.AbstractMap; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -/** - * Properties to be used for auto-configuration of the OpenTelemetry SDK components. These - * properties will be a combination of system properties and environment variables. The properties - * for both of these will be normalized to be all lower case, and underscores will be replaced with - * periods. - */ -final class DefaultConfigProperties implements ConfigProperties { - - private final Map config; - - static ConfigProperties get(Map defaultProperties) { - return new DefaultConfigProperties(System.getProperties(), System.getenv(), defaultProperties); - } - - // Visible for testing - static ConfigProperties createForTest(Map properties) { - return new DefaultConfigProperties(properties, Collections.emptyMap(), Collections.emptyMap()); - } - - private DefaultConfigProperties( - Map systemProperties, - Map environmentVariables, - Map defaultProperties) { - Map config = new HashMap<>(); - defaultProperties.forEach( - (name, value) -> config.put(name.toLowerCase(Locale.ROOT).replace('-', '.'), value)); - environmentVariables.forEach( - (name, value) -> config.put(name.toLowerCase(Locale.ROOT).replace('_', '.'), value)); - systemProperties.forEach( - (key, value) -> - config.put(((String) key).toLowerCase(Locale.ROOT).replace('-', '.'), (String) value)); - - this.config = config; - } - - @Override - @Nullable - public String getString(String name) { - return config.get(name); - } - - @Override - @Nullable - public Boolean getBoolean(String name) { - String value = config.get(name); - if (value == null || value.isEmpty()) { - return null; - } - return Boolean.parseBoolean(value); - } - - @Override - @Nullable - @SuppressWarnings("UnusedException") - public Integer getInt(String name) { - String value = config.get(name); - if (value == null || value.isEmpty()) { - return null; - } - try { - return Integer.parseInt(value); - } catch (NumberFormatException ex) { - throw newInvalidPropertyException(name, value, "integer"); - } - } - - @Override - @Nullable - @SuppressWarnings("UnusedException") - public Long getLong(String name) { - String value = config.get(name); - if (value == null || value.isEmpty()) { - return null; - } - try { - return Long.parseLong(value); - } catch (NumberFormatException ex) { - throw newInvalidPropertyException(name, value, "long"); - } - } - - @Override - @Nullable - @SuppressWarnings("UnusedException") - public Double getDouble(String name) { - String value = config.get(name); - if (value == null || value.isEmpty()) { - return null; - } - try { - return Double.parseDouble(value); - } catch (NumberFormatException ex) { - throw newInvalidPropertyException(name, value, "double"); - } - } - - @Override - @Nullable - @SuppressWarnings("UnusedException") - public Duration getDuration(String name) { - String value = config.get(name); - if (value == null || value.isEmpty()) { - return null; - } - String unitString = getUnitString(value); - // TODO: Environment variables have unknown encoding. `trim()` may cut codepoints oddly - // but likely we'll fail for malformed unit string either way. - String numberString = value.substring(0, value.length() - unitString.length()); - try { - long rawNumber = Long.parseLong(numberString.trim()); - TimeUnit unit = getDurationUnit(unitString.trim()); - return Duration.ofMillis(TimeUnit.MILLISECONDS.convert(rawNumber, unit)); - } catch (NumberFormatException ex) { - throw new ConfigurationException( - "Invalid duration property " - + name - + "=" - + value - + ". Expected number, found: " - + numberString, - ex); - } catch (ConfigurationException ex) { - throw new ConfigurationException( - "Invalid duration property " + name + "=" + value + ". " + ex.getMessage()); - } - } - - @Override - public List getList(String name) { - String value = config.get(name); - if (value == null) { - return Collections.emptyList(); - } - return filterBlanksAndNulls(value.split(",")); - } - - /** - * Returns {@link ConfigProperties#getList(String)} as a {@link Set} after validating there are no - * duplicate entries. - * - * @throws ConfigurationException if {@code name} contains duplicate entries - */ - static Set getSet(ConfigProperties config, String name) { - List list = config.getList(name); - Set set = new HashSet<>(list); - if (set.size() != list.size()) { - String duplicates = - list.stream() - .collect(groupingBy(Function.identity(), Collectors.counting())) - .entrySet() - .stream() - .filter(entry -> entry.getValue() > 1) - .map(Map.Entry::getKey) - .collect(joining(",", "[", "]")); - throw new ConfigurationException(name + " contains duplicates: " + duplicates); - } - return set; - } - - @Override - public Map getMap(String name) { - return getList(name).stream() - .map(keyValuePair -> filterBlanksAndNulls(keyValuePair.split("=", 2))) - .map( - splitKeyValuePairs -> { - if (splitKeyValuePairs.size() != 2) { - throw new ConfigurationException( - "Invalid map property: " + name + "=" + config.get(name)); - } - return new AbstractMap.SimpleImmutableEntry<>( - splitKeyValuePairs.get(0), splitKeyValuePairs.get(1)); - }) - // If duplicate keys, prioritize later ones similar to duplicate system properties on a - // Java command line. - .collect( - Collectors.toMap( - Map.Entry::getKey, Map.Entry::getValue, (first, next) -> next, LinkedHashMap::new)); - } - - private static ConfigurationException newInvalidPropertyException( - String name, String value, String type) { - throw new ConfigurationException( - "Invalid value for property " + name + "=" + value + ". Must be a " + type + "."); - } - - private static List filterBlanksAndNulls(String[] values) { - return Arrays.stream(values) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .collect(Collectors.toList()); - } - - /** Returns the TimeUnit associated with a unit string. Defaults to milliseconds. */ - private static TimeUnit getDurationUnit(String unitString) { - switch (unitString) { - case "": // Fallthrough expected - case "ms": - return TimeUnit.MILLISECONDS; - case "s": - return TimeUnit.SECONDS; - case "m": - return TimeUnit.MINUTES; - case "h": - return TimeUnit.HOURS; - case "d": - return TimeUnit.DAYS; - default: - throw new ConfigurationException("Invalid duration string, found: " + unitString); - } - } - - /** - * Fragments the 'units' portion of a config value from the 'value' portion. - * - *

      E.g. "1ms" would return the string "ms". - */ - private static String getUnitString(String rawValue) { - int lastDigitIndex = rawValue.length() - 1; - while (lastDigitIndex >= 0) { - char c = rawValue.charAt(lastDigitIndex); - if (Character.isDigit(c)) { - break; - } - lastDigitIndex -= 1; - } - // Pull everything after the last digit. - return rawValue.substring(lastDigitIndex + 1); - } -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResource.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResource.java new file mode 100644 index 00000000000..4254b56e608 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResource.java @@ -0,0 +1,449 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityBuilder; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import javax.annotation.Nullable; + +/** + * Creates an OpenTelemetry {@link Resource} from environment configuration. + * + *

      This class is intentionally self-contained (no dependencies on other autoconfigure-internal + * classes) so that it can be copied wholesale into declarative configuration without pulling in + * additional dependencies. Do not add dependencies on non-API, non-SPI classes. + */ +final class EnvironmentResource { + + // Visible for testing + static final String ATTRIBUTE_PROPERTY = "otel.resource.attributes"; + static final String SERVICE_NAME_PROPERTY = "otel.service.name"; + static final String ENTITIES_PROPERTY = "otel.entities"; + + /** + * Create a {@link Resource} from the environment. The resource contains attributes parsed from + * environment variables and system property keys {@code otel.resource.attributes} and {@code + * otel.service.name}. + * + * @param config the {@link ConfigProperties} used to obtain resource properties + * @return the resource. + */ + @SuppressWarnings("JdkObsolete") // Recommended alternative was introduced in java 10 + static Resource createEnvironmentResource(ConfigProperties config) { + ResourceBuilder resourceBuilder = + addEntities(Resource.builder(), config.getString(ENTITIES_PROPERTY)); + for (Map.Entry entry : config.getMap(ATTRIBUTE_PROPERTY).entrySet()) { + resourceBuilder.put( + entry.getKey(), + // Attributes specified via otel.resource.attributes follow the W3C Baggage spec and + // characters outside the baggage-octet range are percent encoded + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/sdk.md#specifying-resource-information-via-an-environment-variable + decodeResourceAttributes(entry.getValue())); + } + String serviceName = config.getString(SERVICE_NAME_PROPERTY); + if (serviceName != null) { + EntityUtil.addEntity( + resourceBuilder, + Entity.builder( + SemConvConstants.SERVICE_TYPE, + Attributes.of(SemConvConstants.SERVICE_NAME, serviceName)) + .setSchemaUrl(SemConvConstants.SCHEMA_URL_V1_40_0) + .build()); + } + + return resourceBuilder.build(); + } + + /** + * Create a {@link Resource} containing only the entities parsed from {@code otel.entities}. + * + * @param entities the {@code otel.entities} value, or null if unset + * @return the resource. + */ + static Resource createEntitiesResource(@Nullable String entities) { + return addEntities(Resource.builder(), entities).build(); + } + + private static ResourceBuilder addEntities( + ResourceBuilder resourceBuilder, @Nullable String entities) { + if (entities != null && !entities.isEmpty()) { + for (Entity entity : new EntityParser(entities).parse()) { + EntityUtil.addEntity(resourceBuilder, entity); + } + } + return resourceBuilder; + } + + /** + * Decodes percent-encoded characters in resource attribute values per W3C Baggage spec. + * + *

      Unlike {@link java.net.URLDecoder}, this method: + * + *

        + *
      • Preserves '+' as a literal plus sign (URLDecoder decodes '+' as space) + *
      • Preserves invalid percent sequences as literals (e.g., "%2G", "%", "%2") + *
      • Supports multi-byte UTF-8 sequences (e.g., "%C3%A9" decodes to "Γ©") + *
      + * + * @param value the percent-encoded string + * @return the decoded string + */ + private static String decodeResourceAttributes(String value) { + // no percent signs means nothing to decode + if (value.indexOf('%') < 0) { + return value; + } + + int n = value.length(); + StringBuilder result = new StringBuilder(n); + // Collect consecutive percent-encoded bytes so multi-byte UTF-8 sequences decode together + byte[] bytes = new byte[n]; + int pos = 0; + + for (int i = 0; i < n; i++) { + char c = value.charAt(i); + // Check for percent-encoded sequence i.e. '%' followed by two hex digits + if (c == '%' && i + 2 < n) { + int d1 = Character.digit(value.charAt(i + 1), 16); + int d2 = Character.digit(value.charAt(i + 2), 16); + // Valid hex digits return 0-15, invalid returns -1 + if (d1 != -1 && d2 != -1) { + // Combine two hex digits into a single byte (e.g., "2F" becomes 0x2F) + bytes[pos++] = (byte) ((d1 << 4) + d2); + // Skip the two hex digits (loop will also do i++) + i += 2; + continue; + } + } + if (pos > 0) { + result.append(new String(bytes, 0, pos, StandardCharsets.UTF_8)); + pos = 0; + } + // Keep '+' as '+' (unlike URLDecoder), preserve invalid percent sequences which will be + // treated as literals, and keep characters that are not percent-encoded (including + // non-ASCII) as is + result.append(c); + } + if (pos > 0) { + result.append(new String(bytes, 0, pos, StandardCharsets.UTF_8)); + } + return result.toString(); + } + + private static final class Segment { + private final String source; + private int start; + private int end; + private boolean needsDecoding; + + Segment(String source) { + this.source = source; + reset(0); + } + + void reset(int start) { + this.start = start; + this.end = start; + this.needsDecoding = false; + } + + void markEnd(int end) { + this.end = end; + } + + void markNeedsDecoding() { + this.needsDecoding = true; + } + + boolean isEmpty() { + return start >= end; + } + + String getValue() { + if (isEmpty()) { + return ""; + } + String substring = source.substring(start, end).trim(); + return needsDecoding ? decodeResourceAttributes(substring) : substring; + } + } + + // State machine parser + private static final class EntityParser { + private static final Logger logger = Logger.getLogger(EntityParser.class.getName()); + private static final Pattern NAME_PATTERN = Pattern.compile("[a-zA-Z][a-zA-Z0-9._-]*"); + + private enum State { + TYPE, + ID_KEY, + ID_VAL, + AFTER_ID, + DESC_KEY, + DESC_VAL, + AFTER_DESC, + SCHEMA_URL, + SKIP_TO_NEXT + } + + private final String input; + private State state = State.TYPE; + private final Segment currentSegment; + private final List entities = new ArrayList<>(); + + @Nullable private String currentType; + private Attributes currentIdAttrs = Attributes.empty(); + private Attributes currentDescAttrs = Attributes.empty(); + @Nullable private String currentSchemaUrl; + private AttributesBuilder currentBuilder = Attributes.builder(); + @Nullable private String currentKey; + + EntityParser(String input) { + this.input = input; + this.currentSegment = new Segment(input); + } + + List parse() { + int n = input.length(); + for (int i = 0; i < n; i++) { + char c = input.charAt(i); + + if (state == State.SKIP_TO_NEXT) { + if (c == ';') { + resetEntityState(i + 1); + state = State.TYPE; + } + continue; + } + if (state == State.SCHEMA_URL && c != ';') { + continue; + } + + switch (c) { + case '{': + if (state == State.TYPE) { + currentSegment.markEnd(i); + currentType = currentSegment.getValue(); + if (!NAME_PATTERN.matcher(currentType).matches()) { + malformed("invalid type"); + } else { + state = State.ID_KEY; + currentSegment.reset(i + 1); + currentBuilder = Attributes.builder(); + } + } else { + malformed("unexpected '{'"); + } + break; + case '}': + if (state == State.ID_VAL || state == State.ID_KEY) { + currentSegment.markEnd(i); + if (state == State.ID_KEY + && (!currentSegment.getValue().isEmpty() || currentKey != null)) { + malformed("missing identifying attribute value"); + break; + } + if (state == State.ID_VAL) { + putAttr(); + } + currentIdAttrs = currentBuilder.build(); + if (currentIdAttrs.isEmpty()) { + malformed("missing identifying attributes"); + } else { + state = State.AFTER_ID; + currentSegment.reset(i + 1); + } + } else { + malformed("unexpected '}'"); + } + break; + case '[': + if (state == State.AFTER_ID) { + state = State.DESC_KEY; + currentSegment.reset(i + 1); + currentBuilder = Attributes.builder(); + currentKey = null; + } else { + malformed("unexpected '['"); + } + break; + case ']': + if (state == State.DESC_VAL || state == State.DESC_KEY) { + currentSegment.markEnd(i); + if (state == State.DESC_KEY + && (!currentSegment.getValue().isEmpty() || currentKey != null)) { + malformed("missing descriptive attribute value"); + break; + } + if (state == State.DESC_VAL) { + putAttr(); + } + currentDescAttrs = currentBuilder.build(); + state = State.AFTER_DESC; + currentSegment.reset(i + 1); + } else { + malformed("unexpected ']'"); + } + break; + case '=': + if (state == State.ID_KEY || state == State.DESC_KEY) { + currentSegment.markEnd(i); + currentKey = currentSegment.getValue(); + if (!NAME_PATTERN.matcher(currentKey).matches()) { + malformed("invalid attribute key"); + } else { + state = (state == State.ID_KEY) ? State.ID_VAL : State.DESC_VAL; + currentSegment.reset(i + 1); + } + } else { + malformed("unexpected '='"); + } + break; + case ',': + if (state == State.ID_VAL || state == State.DESC_VAL) { + currentSegment.markEnd(i); + putAttr(); + state = (state == State.ID_VAL) ? State.ID_KEY : State.DESC_KEY; + currentSegment.reset(i + 1); + } else { + malformed("unexpected ','"); + } + break; + case '@': + if (state == State.AFTER_ID || state == State.AFTER_DESC) { + state = State.SCHEMA_URL; + currentSegment.reset(i + 1); + } else { + malformed("unexpected '@'"); + } + break; + case ';': + if (state == State.AFTER_ID || state == State.AFTER_DESC || state == State.SCHEMA_URL) { + if (state == State.SCHEMA_URL) { + currentSegment.markEnd(i); + currentSchemaUrl = currentSegment.getValue(); + } + buildAndAddEntity(); + } else { + currentSegment.markEnd(i); + if (state != State.TYPE || !currentSegment.getValue().isEmpty()) { + malformed("unexpected ';'"); + } + } + resetEntityState(i + 1); + state = State.TYPE; + break; + case '%': + if (state == State.ID_VAL || state == State.DESC_VAL) { + currentSegment.markNeedsDecoding(); + } else { + malformed("unexpected '%'"); + } + break; + default: + if ((state == State.AFTER_ID || state == State.AFTER_DESC) + && !Character.isWhitespace(c)) { + malformed("unexpected trailing characters"); + } + break; + } + } + + if (state == State.AFTER_ID || state == State.AFTER_DESC || state == State.SCHEMA_URL) { + if (state == State.SCHEMA_URL) { + currentSegment.markEnd(input.length()); + currentSchemaUrl = currentSegment.getValue(); + } + buildAndAddEntity(); + } else if (state != State.SKIP_TO_NEXT) { + currentSegment.markEnd(input.length()); + if (state != State.TYPE || !currentSegment.getValue().isEmpty()) { + malformed("incomplete definition"); + } + } + + return entities; + } + + private void putAttr() { + if (currentKey != null) { + currentBuilder.put(currentKey, currentSegment.getValue()); + } + } + + // Only reached after a valid type and nonempty identifying attributes were parsed. + private void buildAndAddEntity() { + if (currentType == null) { + return; + } + try { + EntityBuilder builder = + Entity.builder(currentType, currentIdAttrs).setDescription(currentDescAttrs); + String schemaUrl = validateSchemaUrl(currentSchemaUrl); + if (schemaUrl != null) { + builder.setSchemaUrl(schemaUrl); + } + Entity entity = builder.build(); + if (entities.removeIf(previous -> previous.getType().equals(entity.getType()))) { + logger.warning( + "Duplicate entity type [" + entity.getType() + "]; using the last definition."); + } + entities.add(entity); + } catch (IllegalArgumentException e) { + logger.log(Level.WARNING, "Malformed entity definition: " + input, e); + } + } + + private void malformed(String reason) { + logger.warning("Malformed entity definition (" + reason + "): " + input); + state = State.SKIP_TO_NEXT; + } + + @Nullable + private static String validateSchemaUrl(@Nullable String schemaUrl) { + if (schemaUrl == null) { + return null; + } + try { + if (!new URI(schemaUrl).isAbsolute()) { + logger.warning("Ignoring invalid entity schema URL: " + schemaUrl); + return null; + } + return schemaUrl; + } catch (URISyntaxException e) { + logger.log(Level.WARNING, "Ignoring invalid entity schema URL: " + schemaUrl, e); + return null; + } + } + + private void resetEntityState(int nextStart) { + currentType = null; + currentIdAttrs = Attributes.empty(); + currentDescAttrs = Attributes.empty(); + currentSchemaUrl = null; + currentBuilder = Attributes.builder(); + currentKey = null; + currentSegment.reset(nextStart); + } + } + + private EnvironmentResource() {} +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResourceProvider.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResourceProvider.java new file mode 100644 index 00000000000..648c5b858e1 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResourceProvider.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +/** + * {@link ResourceProvider} for automatically configuring {@link + * ResourceConfiguration#createEnvironmentResource(ConfigProperties)}. + * + * @since 1.47.0 + */ +public final class EnvironmentResourceProvider implements ResourceProvider { + @Override + public Resource createResource(ConfigProperties config) { + return ResourceConfiguration.createEnvironmentResource(config); + } + + @Override + public int order() { + // Environment resource takes precedence over all other ResourceProviders. + return Integer.MAX_VALUE - 1; + } +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/InternalTelemetryConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/InternalTelemetryConfiguration.java new file mode 100644 index 00000000000..7f16f705c0b --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/InternalTelemetryConfiguration.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import java.util.Locale; + +/** + * Reads the desired SDK internal telemetry version from {@link ConfigProperties}. + * + *

      This is the same as {@code + * io.opentelemetry.exporter.otlp.internal.InternalTelemetryConfiguration}. Any changes should be + * reflected there as well. + */ +final class InternalTelemetryConfiguration { + + static InternalTelemetryVersion getVersion(ConfigProperties config) { + String version = config.getString("otel.experimental.sdk.telemetry.version"); + if (version == null) { + return InternalTelemetryVersion.LEGACY; + } + + switch (version.toLowerCase(Locale.ROOT)) { + case "legacy": + return InternalTelemetryVersion.LEGACY; + case "latest": + return InternalTelemetryVersion.LATEST; + default: + throw new ConfigurationException("Invalid sdk telemetry version: " + version); + } + } + + private InternalTelemetryConfiguration() {} +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfiguration.java deleted file mode 100644 index c74ae0a2a38..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfiguration.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.LogExporterConfiguration.configureLogExporters; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.logs.LogLimits; -import io.opentelemetry.sdk.logs.LogLimitsBuilder; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder; -import io.opentelemetry.sdk.logs.export.BatchLogProcessor; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.logs.export.SimpleLogProcessor; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.BiFunction; - -final class LogEmitterProviderConfiguration { - - static void configureLogEmitterProvider( - SdkLogEmitterProviderBuilder logEmitterProviderBuilder, - ConfigProperties config, - MeterProvider meterProvider, - BiFunction - logExporterCustomizer) { - - logEmitterProviderBuilder.setLogLimits(() -> configureLogLimits(config)); - - Map exportersByName = - configureLogExporters(config, meterProvider, logExporterCustomizer); - - configureLogProcessors(exportersByName, meterProvider) - .forEach(logEmitterProviderBuilder::addLogProcessor); - } - - // Visible for testing - static List configureLogProcessors( - Map exportersByName, MeterProvider meterProvider) { - Map exportersByNameCopy = new HashMap<>(exportersByName); - List logProcessors = new ArrayList<>(); - - LogExporter exporter = exportersByNameCopy.remove("logging"); - if (exporter != null) { - logProcessors.add(SimpleLogProcessor.create(exporter)); - } - - if (!exportersByNameCopy.isEmpty()) { - LogExporter compositeLogExporter = LogExporter.composite(exportersByNameCopy.values()); - logProcessors.add( - BatchLogProcessor.builder(compositeLogExporter).setMeterProvider(meterProvider).build()); - } - - return logProcessors; - } - - // Visible for testing - static LogLimits configureLogLimits(ConfigProperties config) { - LogLimitsBuilder builder = LogLimits.builder(); - - Integer maxAttrLength = config.getInt("otel.attribute.value.length.limit"); - if (maxAttrLength != null) { - builder.setMaxAttributeValueLength(maxAttrLength); - } - - Integer maxAttrs = config.getInt("otel.attribute.count.limit"); - if (maxAttrs != null) { - builder.setMaxNumberOfAttributes(maxAttrs); - } - - return builder.build(); - } - - private LogEmitterProviderConfiguration() {} -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogExporterConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogExporterConfiguration.java deleted file mode 100644 index a4eb9e0bdb3..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogExporterConfiguration.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.DATA_TYPE_LOGS; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_GRPC; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.logging.SystemOutLogExporter; -import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogExporter; -import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogExporterBuilder; -import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogExporter; -import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogExporterBuilder; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.logs.export.LogExporter; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.function.BiFunction; -import javax.annotation.Nullable; - -class LogExporterConfiguration { - - private static final String EXPORTER_NONE = "none"; - - // Visible for test - static Map configureLogExporters( - ConfigProperties config, - MeterProvider meterProvider, - BiFunction - logExporterCustomizer) { - Set exporterNames = DefaultConfigProperties.getSet(config, "otel.logs.exporter"); - - // Default to no exporter - if (exporterNames.isEmpty()) { - exporterNames = Collections.singleton(EXPORTER_NONE); - } - - if (exporterNames.contains(EXPORTER_NONE)) { - if (exporterNames.size() > 1) { - throw new ConfigurationException( - "otel.logs.exporter contains " + EXPORTER_NONE + " along with other exporters"); - } - return Collections.emptyMap(); - } - - Map exportersByName = new HashMap<>(); - for (String name : exporterNames) { - LogExporter logExporter = configureExporter(name, config, meterProvider); - if (logExporter != null) { - LogExporter customizedLogExporter = logExporterCustomizer.apply(logExporter, config); - exportersByName.put(name, customizedLogExporter); - } - } - - return Collections.unmodifiableMap(exportersByName); - } - - // Visible for testing - @Nullable - static LogExporter configureExporter( - String name, ConfigProperties config, MeterProvider meterProvider) { - switch (name) { - case "otlp": - return configureOtlpLogs(config, meterProvider); - case "logging": - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.logging.SystemOutLogExporter", - "Logging Log Exporter", - "opentelemetry-exporter-logging"); - return SystemOutLogExporter.create(); - default: - throw new ConfigurationException("Unrecognized value for otel.logs.exporter: " + name); - } - } - - // Visible for testing - @Nullable - static LogExporter configureOtlpLogs(ConfigProperties config, MeterProvider meterProvider) { - String protocol = OtlpConfigUtil.getOtlpProtocol(DATA_TYPE_LOGS, config); - - if (protocol.equals(PROTOCOL_HTTP_PROTOBUF)) { - try { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogExporter", - "OTLP HTTP Log Exporter", - "opentelemetry-exporter-otlp-http-logs"); - } catch (ConfigurationException e) { - // Squash this for now until logs are stable - return null; - } - OtlpHttpLogExporterBuilder builder = OtlpHttpLogExporter.builder(); - - OtlpConfigUtil.configureOtlpExporterBuilder( - DATA_TYPE_LOGS, - config, - builder::setEndpoint, - builder::addHeader, - builder::setCompression, - builder::setTimeout, - builder::setTrustedCertificates, - builder::setClientTls, - retryPolicy -> RetryUtil.setRetryPolicyOnDelegate(builder, retryPolicy)); - - builder.setMeterProvider(meterProvider); - - return builder.build(); - } else if (protocol.equals(PROTOCOL_GRPC)) { - try { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogExporter", - "OTLP gRPC Log Exporter", - "opentelemetry-exporter-otlp-logs"); - } catch (ConfigurationException e) { - // Squash this for now until logs are stable - return null; - } - OtlpGrpcLogExporterBuilder builder = OtlpGrpcLogExporter.builder(); - - OtlpConfigUtil.configureOtlpExporterBuilder( - DATA_TYPE_LOGS, - config, - builder::setEndpoint, - builder::addHeader, - builder::setCompression, - builder::setTimeout, - builder::setTrustedCertificates, - builder::setClientTls, - retryPolicy -> RetryUtil.setRetryPolicyOnDelegate(builder, retryPolicy)); - builder.setMeterProvider(meterProvider); - - return builder.build(); - } else { - throw new ConfigurationException("Unsupported OTLP logs protocol: " + protocol); - } - } - - private LogExporterConfiguration() {} -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfiguration.java new file mode 100644 index 00000000000..fa8729fcdaf --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfiguration.java @@ -0,0 +1,105 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.io.Closeable; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; + +final class LogRecordExporterConfiguration { + + private static final String EXPORTER_NONE = "none"; + private static final Map EXPORTER_ARTIFACT_ID_BY_NAME; + + static { + EXPORTER_ARTIFACT_ID_BY_NAME = new HashMap<>(); + EXPORTER_ARTIFACT_ID_BY_NAME.put("console", "opentelemetry-exporter-logging"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("logging", "opentelemetry-exporter-logging"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("logging-otlp", "opentelemetry-exporter-logging-otlp"); + EXPORTER_ARTIFACT_ID_BY_NAME.put( + "experimental-otlp/stdout", "opentelemetry-exporter-logging-otlp"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("otlp", "opentelemetry-exporter-otlp"); + } + + @SuppressWarnings("ReferenceEquality") + static Map configureLogRecordExporters( + ConfigProperties config, + SpiHelper spiHelper, + BiFunction + logRecordExporterCustomizer, + List closeables) { + Set exporterNames = DefaultConfigProperties.getSet(config, "otel.logs.exporter"); + if (exporterNames.contains(EXPORTER_NONE)) { + if (exporterNames.size() > 1) { + throw new ConfigurationException( + "otel.logs.exporter contains " + EXPORTER_NONE + " along with other exporters"); + } + return Collections.emptyMap(); + } + + if (exporterNames.isEmpty()) { + exporterNames = Collections.singleton("otlp"); + } + + NamedSpiManager spiExportersManager = + logRecordExporterSpiManager(config, spiHelper); + + Map map = new HashMap<>(); + for (String exporterName : exporterNames) { + LogRecordExporter logRecordExporter = configureExporter(exporterName, spiExportersManager); + closeables.add(logRecordExporter); + LogRecordExporter customizedLogRecordExporter = + logRecordExporterCustomizer.apply(logRecordExporter, config); + if (customizedLogRecordExporter != logRecordExporter) { + closeables.add(customizedLogRecordExporter); + } + map.put(exporterName, customizedLogRecordExporter); + } + return Collections.unmodifiableMap(map); + } + + // Visible for testing + static NamedSpiManager logRecordExporterSpiManager( + ConfigProperties config, SpiHelper spiHelper) { + return spiHelper.loadConfigurable( + ConfigurableLogRecordExporterProvider.class, + ConfigurableLogRecordExporterProvider::getName, + ConfigurableLogRecordExporterProvider::createExporter, + config); + } + + // Visible for testing + static LogRecordExporter configureExporter( + String name, NamedSpiManager spiExportersManager) { + LogRecordExporter spiExporter = spiExportersManager.getByName(name); + if (spiExporter == null) { + String artifactId = EXPORTER_ARTIFACT_ID_BY_NAME.get(name); + if (artifactId != null) { + throw new ConfigurationException( + "otel.logs.exporter set to \"" + + name + + "\" but " + + artifactId + + " not found on classpath. Make sure to add it as a dependency."); + } + throw new ConfigurationException("Unrecognized value for otel.logs.exporter: " + name); + } + return spiExporter; + } + + private LogRecordExporterConfiguration() {} +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfiguration.java new file mode 100644 index 00000000000..c1373166da4 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfiguration.java @@ -0,0 +1,159 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.autoconfigure.LogRecordExporterConfiguration.configureLogRecordExporters; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.logs.LogLimitsBuilder; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessorBuilder; +import java.io.Closeable; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +final class LoggerProviderConfiguration { + + private static final List simpleProcessorExporterNames = + Arrays.asList("console", "logging"); + + @SuppressWarnings("ReferenceEquality") + static void configureLoggerProvider( + SdkLoggerProviderBuilder loggerProviderBuilder, + ConfigProperties config, + SpiHelper spiHelper, + MeterProvider meterProvider, + BiFunction + logRecordExporterCustomizer, + BiFunction + logRecordProcessorCustomizer, + List closeables) { + + loggerProviderBuilder.setLogLimits(() -> configureLogLimits(config)); + InternalTelemetryVersion telemetryVersion = InternalTelemetryConfiguration.getVersion(config); + if (telemetryVersion != InternalTelemetryVersion.LEGACY) { + loggerProviderBuilder.setMeterProvider(() -> meterProvider); + } + + Map exportersByName = + configureLogRecordExporters(config, spiHelper, logRecordExporterCustomizer, closeables); + + List processors = + configureLogRecordProcessors( + config, exportersByName, telemetryVersion, meterProvider, closeables); + for (LogRecordProcessor processor : processors) { + LogRecordProcessor wrapped = logRecordProcessorCustomizer.apply(processor, config); + if (wrapped != processor) { + closeables.add(wrapped); + } + loggerProviderBuilder.addLogRecordProcessor(wrapped); + } + } + + // Visible for testing + static List configureLogRecordProcessors( + ConfigProperties config, + Map exportersByName, + InternalTelemetryVersion telemetryVersion, + MeterProvider meterProvider, + List closeables) { + Map exportersByNameCopy = new HashMap<>(exportersByName); + List logRecordProcessors = new ArrayList<>(); + + for (String simpleProcessorExporterName : simpleProcessorExporterNames) { + LogRecordExporter exporter = exportersByNameCopy.remove(simpleProcessorExporterName); + if (exporter != null) { + SimpleLogRecordProcessorBuilder logRecordProcessorBuilder = + SimpleLogRecordProcessor.builder(exporter); + if (telemetryVersion != InternalTelemetryVersion.LEGACY) { + logRecordProcessorBuilder.setMeterProvider(() -> meterProvider); + } + LogRecordProcessor logRecordProcessor = logRecordProcessorBuilder.build(); + closeables.add(logRecordProcessor); + logRecordProcessors.add(logRecordProcessor); + } + } + + if (!exportersByNameCopy.isEmpty()) { + LogRecordExporter compositeLogRecordExporter = + LogRecordExporter.composite(exportersByNameCopy.values()); + LogRecordProcessor logRecordProcessor = + configureBatchLogRecordProcessor( + config, compositeLogRecordExporter, telemetryVersion, meterProvider); + closeables.add(logRecordProcessor); + logRecordProcessors.add(logRecordProcessor); + } + + return logRecordProcessors; + } + + // VisibleForTesting + static BatchLogRecordProcessor configureBatchLogRecordProcessor( + ConfigProperties config, + LogRecordExporter exporter, + InternalTelemetryVersion telemetryVersion, + MeterProvider meterProvider) { + BatchLogRecordProcessorBuilder builder = + BatchLogRecordProcessor.builder(exporter).setMeterProvider(meterProvider); + + Duration scheduleDelay = config.getDuration("otel.blrp.schedule.delay"); + if (scheduleDelay != null) { + builder.setScheduleDelay(scheduleDelay); + } + + Integer maxQueue = config.getInt("otel.blrp.max.queue.size"); + if (maxQueue != null) { + builder.setMaxQueueSize(maxQueue); + } + + Integer maxExportBatch = config.getInt("otel.blrp.max.export.batch.size"); + if (maxExportBatch != null) { + builder.setMaxExportBatchSize(maxExportBatch); + } + + Duration timeout = config.getDuration("otel.blrp.export.timeout"); + if (timeout != null) { + builder.setExporterTimeout(timeout); + } + + builder.setInternalTelemetryVersion(telemetryVersion); + + return builder.build(); + } + + // Visible for testing + static LogLimits configureLogLimits(ConfigProperties config) { + LogLimitsBuilder builder = LogLimits.builder(); + + Integer maxAttrLength = config.getInt("otel.attribute.value.length.limit"); + if (maxAttrLength != null) { + builder.setMaxAttributeValueLength(maxAttrLength); + } + + Integer maxAttrs = config.getInt("otel.attribute.count.limit"); + if (maxAttrs != null) { + builder.setMaxNumberOfAttributes(maxAttrs); + } + + return builder.build(); + } + + private LoggerProviderConfiguration() {} +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java index 356100d566d..8e17b0670f3 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfiguration.java @@ -5,15 +5,19 @@ package io.opentelemetry.sdk.autoconfigure; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.metrics.ExemplarFilter; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.export.MetricExporter; import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; +import java.io.Closeable; import java.util.Collections; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.function.BiFunction; import java.util.stream.Collectors; @@ -23,38 +27,51 @@ final class MeterProviderConfiguration { static void configureMeterProvider( SdkMeterProviderBuilder meterProviderBuilder, ConfigProperties config, - ClassLoader serviceClassLoader, + SpiHelper spiHelper, + BiFunction + metricReaderCustomizer, BiFunction - metricExporterCustomizer) { + metricExporterCustomizer, + List closeables) { // Configure default exemplar filters. - String exemplarFilter = config.getString("otel.metrics.exemplar.filter"); - if (exemplarFilter == null) { - exemplarFilter = "with_sampled_trace"; - } + String exemplarFilter = + config.getString("otel.metrics.exemplar.filter", "trace_based").toLowerCase(Locale.ROOT); switch (exemplarFilter) { - case "none": - SdkMeterProviderUtil.setExemplarFilter(meterProviderBuilder, ExemplarFilter.neverSample()); + case "always_off": + meterProviderBuilder.setExemplarFilter(ExemplarFilter.alwaysOff()); break; - case "all": - SdkMeterProviderUtil.setExemplarFilter(meterProviderBuilder, ExemplarFilter.alwaysSample()); + case "always_on": + meterProviderBuilder.setExemplarFilter(ExemplarFilter.alwaysOn()); break; - case "with_sampled_trace": + case "trace_based": default: - SdkMeterProviderUtil.setExemplarFilter( - meterProviderBuilder, ExemplarFilter.sampleWithTraces()); + meterProviderBuilder.setExemplarFilter(ExemplarFilter.traceBased()); break; } - configureMetricReaders(config, serviceClassLoader, metricExporterCustomizer) - .forEach(meterProviderBuilder::registerMetricReader); + Integer cardinalityLimit = config.getInt("otel.java.metrics.cardinality.limit"); + if (cardinalityLimit != null && cardinalityLimit < 1) { + throw new ConfigurationException("otel.java.metrics.cardinality.limit must be >= 1"); + } + int resolvedCardinalityLimit = + cardinalityLimit == null ? MetricStorage.DEFAULT_MAX_CARDINALITY : cardinalityLimit; + + configureMetricReaders( + config, spiHelper, metricReaderCustomizer, metricExporterCustomizer, closeables) + .forEach(reader -> + meterProviderBuilder.registerMetricReader( + reader, instrumentType -> resolvedCardinalityLimit)); } static List configureMetricReaders( ConfigProperties config, - ClassLoader serviceClassLoader, + SpiHelper spiHelper, + BiFunction + metricReaderCustomizer, BiFunction - metricExporterCustomizer) { + metricExporterCustomizer, + List closeables) { Set exporterNames = DefaultConfigProperties.getSet(config, "otel.metrics.exporter"); if (exporterNames.contains("none")) { if (exporterNames.size() > 1) { @@ -68,10 +85,14 @@ static List configureMetricReaders( exporterNames = Collections.singleton("otlp"); } return exporterNames.stream() - .map( - exporterName -> - MetricExporterConfiguration.configureExporter( - exporterName, config, serviceClassLoader, metricExporterCustomizer)) + .map(exporterName -> + MetricExporterConfiguration.configureReader( + exporterName, + config, + spiHelper, + metricReaderCustomizer, + metricExporterCustomizer, + closeables)) .collect(Collectors.toList()); } diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfiguration.java index 45e0ced4b2e..bbbf4d1b339 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfiguration.java @@ -5,159 +5,162 @@ package io.opentelemetry.sdk.autoconfigure; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.DATA_TYPE_METRICS; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_GRPC; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; - -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.logging.LoggingMetricExporter; -import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; -import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporterBuilder; -import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; -import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporterBuilder; -import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; -import io.opentelemetry.exporter.prometheus.PrometheusHttpServerBuilder; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConfigurableMetricReaderProvider; import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; import io.opentelemetry.sdk.metrics.export.MetricExporter; import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder; +import java.io.Closeable; import java.time.Duration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.function.BiFunction; import javax.annotation.Nullable; final class MetricExporterConfiguration { - static MetricReader configureExporter( + + private static final Duration DEFAULT_EXPORT_INTERVAL = Duration.ofMinutes(1); + private static final Map EXPORTER_ARTIFACT_ID_BY_NAME; + private static final Map READER_ARTIFACT_ID_BY_NAME; + + static { + EXPORTER_ARTIFACT_ID_BY_NAME = new HashMap<>(); + EXPORTER_ARTIFACT_ID_BY_NAME.put("console", "opentelemetry-exporter-logging"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("logging", "opentelemetry-exporter-logging"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("logging-otlp", "opentelemetry-exporter-logging-otlp"); + EXPORTER_ARTIFACT_ID_BY_NAME.put( + "experimental-otlp/stdout", "opentelemetry-exporter-logging-otlp"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("otlp", "opentelemetry-exporter-otlp"); + + READER_ARTIFACT_ID_BY_NAME = new HashMap<>(); + READER_ARTIFACT_ID_BY_NAME.put("prometheus", "opentelemetry-exporter-prometheus"); + } + + @SuppressWarnings("ReferenceEquality") + static MetricReader configureReader( String name, ConfigProperties config, - ClassLoader serviceClassLoader, + SpiHelper spiHelper, + BiFunction + metricReaderCustomizer, BiFunction - metricExporterCustomizer) { - if (name.equals("prometheus")) { - return configurePrometheusMetricReader(config); - } - - MetricExporter metricExporter; - switch (name) { - case "otlp": - metricExporter = configureOtlpMetrics(config); - break; - case "logging": - metricExporter = configureLoggingExporter(); - break; - default: - MetricExporter spiExporter = configureSpiExporter(name, config, serviceClassLoader); - if (spiExporter == null) { - throw new ConfigurationException("Unrecognized value for otel.metrics.exporter: " + name); + metricExporterCustomizer, + List closeables) { + NamedSpiManager spiExportersManager = + metricExporterSpiManager(config, spiHelper); + MetricExporter metricExporter = configureExporter(name, spiExportersManager); + + // If no metric exporter with name, try to load metric reader + if (metricExporter == null) { + NamedSpiManager spiMetricReadersManager = + metricReadersSpiManager(config, spiHelper); + MetricReader metricReader = configureMetricReader(name, spiMetricReadersManager); + if (metricReader != null) { + closeables.add(metricReader); + + // Customize metric reader + MetricReader customizedMetricReader = metricReaderCustomizer.apply(metricReader, config); + if (customizedMetricReader != metricReader) { + closeables.add(customizedMetricReader); } - metricExporter = spiExporter; + + return customizedMetricReader; + } + // No exporter or reader with the name + throw new ConfigurationException("Unrecognized value for otel.metrics.exporter: " + name); } - metricExporter = metricExporterCustomizer.apply(metricExporter, config); - return configurePeriodicMetricReader(config, metricExporter); + // Customize metric exporter and associate it with PeriodicMetricReader + closeables.add(metricExporter); + MetricExporter customizedMetricExporter = + metricExporterCustomizer.apply(metricExporter, config); + if (customizedMetricExporter != metricExporter) { + closeables.add(customizedMetricExporter); + } + InternalTelemetryVersion telemetryVersion = InternalTelemetryConfiguration.getVersion(config); + PeriodicMetricReaderBuilder readerBuilder = + PeriodicMetricReader.builder(customizedMetricExporter) + .setInternalTelemetryVersion(telemetryVersion) + .setInterval( + config.getDuration("otel.metric.export.interval", DEFAULT_EXPORT_INTERVAL)); + Integer maxExportBatchSize = config.getInt("otel.metric.export.max.batch.size"); + if (maxExportBatchSize != null) { + readerBuilder.setMaxExportBatchSize(maxExportBatchSize); + } + MetricReader reader = readerBuilder.build(); + closeables.add(reader); + MetricReader customizedMetricReader = metricReaderCustomizer.apply(reader, config); + if (customizedMetricReader != reader) { + closeables.add(customizedMetricReader); + } + return customizedMetricReader; } - private static MetricExporter configureLoggingExporter() { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.logging.LoggingMetricExporter", - "Logging Metrics Exporter", - "opentelemetry-exporter-logging"); - return LoggingMetricExporter.create(); + // Visible for testing + static NamedSpiManager metricReadersSpiManager( + ConfigProperties config, SpiHelper spiHelper) { + return spiHelper.loadConfigurable( + ConfigurableMetricReaderProvider.class, + ConfigurableMetricReaderProvider::getName, + ConfigurableMetricReaderProvider::createMetricReader, + config); } // Visible for testing. @Nullable - static MetricExporter configureSpiExporter( - String name, ConfigProperties config, ClassLoader serviceClassLoader) { - NamedSpiManager spiExportersManager = - SpiUtil.loadConfigurable( - ConfigurableMetricExporterProvider.class, - ConfigurableMetricExporterProvider::getName, - ConfigurableMetricExporterProvider::createExporter, - config, - serviceClassLoader); - return spiExportersManager.getByName(name); + static MetricReader configureMetricReader( + String name, NamedSpiManager spiMetricReadersManager) { + MetricReader metricReader = spiMetricReadersManager.getByName(name); + if (metricReader == null) { + String artifactId = READER_ARTIFACT_ID_BY_NAME.get(name); + if (artifactId != null) { + throw missingArtifactException(name, artifactId); + } + return null; + } + return metricReader; } // Visible for testing - static MetricExporter configureOtlpMetrics(ConfigProperties config) { - String protocol = OtlpConfigUtil.getOtlpProtocol(DATA_TYPE_METRICS, config); - - if (protocol.equals(PROTOCOL_HTTP_PROTOBUF)) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter", - "OTLP HTTP Metrics Exporter", - "opentelemetry-exporter-otlp-http-metrics"); - OtlpHttpMetricExporterBuilder builder = OtlpHttpMetricExporter.builder(); - - OtlpConfigUtil.configureOtlpExporterBuilder( - DATA_TYPE_METRICS, - config, - builder::setEndpoint, - builder::addHeader, - builder::setCompression, - builder::setTimeout, - builder::setTrustedCertificates, - builder::setClientTls, - retryPolicy -> RetryUtil.setRetryPolicyOnDelegate(builder, retryPolicy)); - OtlpConfigUtil.configureOtlpAggregationTemporality( - config, builder::setAggregationTemporalitySelector); - - return builder.build(); - } else if (protocol.equals(PROTOCOL_GRPC)) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter", - "OTLP gRPC Metrics Exporter", - "opentelemetry-exporter-otlp"); - OtlpGrpcMetricExporterBuilder builder = OtlpGrpcMetricExporter.builder(); - - OtlpConfigUtil.configureOtlpExporterBuilder( - DATA_TYPE_METRICS, - config, - builder::setEndpoint, - builder::addHeader, - builder::setCompression, - builder::setTimeout, - builder::setTrustedCertificates, - builder::setClientTls, - retryPolicy -> RetryUtil.setRetryPolicyOnDelegate(builder, retryPolicy)); - OtlpConfigUtil.configureOtlpAggregationTemporality( - config, builder::setAggregationTemporalitySelector); - - return builder.build(); - } else { - throw new ConfigurationException("Unsupported OTLP metrics protocol: " + protocol); - } + static NamedSpiManager metricExporterSpiManager( + ConfigProperties config, SpiHelper spiHelper) { + return spiHelper.loadConfigurable( + ConfigurableMetricExporterProvider.class, + ConfigurableMetricExporterProvider::getName, + ConfigurableMetricExporterProvider::createExporter, + config); } - private static PeriodicMetricReader configurePeriodicMetricReader( - ConfigProperties config, MetricExporter exporter) { - - Duration exportInterval = config.getDuration("otel.metric.export.interval"); - if (exportInterval == null) { - exportInterval = Duration.ofMinutes(1); + // Visible for testing. + @Nullable + static MetricExporter configureExporter( + String name, NamedSpiManager spiExportersManager) { + MetricExporter metricExporter = spiExportersManager.getByName(name); + if (metricExporter == null) { + String artifactId = EXPORTER_ARTIFACT_ID_BY_NAME.get(name); + if (artifactId != null) { + throw missingArtifactException(name, artifactId); + } + return null; } - - return PeriodicMetricReader.builder(exporter).setInterval(exportInterval).build(); + return metricExporter; } - private static PrometheusHttpServer configurePrometheusMetricReader(ConfigProperties config) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.prometheus.PrometheusHttpServer", - "Prometheus Metrics Server", - "opentelemetry-exporter-prometheus"); - PrometheusHttpServerBuilder prom = PrometheusHttpServer.builder(); - - Integer port = config.getInt("otel.exporter.prometheus.port"); - if (port != null) { - prom.setPort(port); - } - String host = config.getString("otel.exporter.prometheus.host"); - if (host != null) { - prom.setHost(host); - } - return prom.build(); + private static ConfigurationException missingArtifactException( + String exporterName, String artifactId) { + return new ConfigurationException( + "otel.metrics.exporter set to \"" + + exporterName + + "\" but " + + artifactId + + " not found on classpath. Make sure to add it as a dependency."); } private MetricExporterConfiguration() {} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/NamedSpiManager.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/NamedSpiManager.java deleted file mode 100644 index 0c4e50b8830..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/NamedSpiManager.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import java.util.Collections; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Supplier; -import javax.annotation.Nullable; - -class NamedSpiManager { - - private final Map> nameToProvider; - private final ConcurrentMap> nameToImplementation = new ConcurrentHashMap<>(); - - private NamedSpiManager(Map> nameToProvider) { - this.nameToProvider = nameToProvider; - } - - static NamedSpiManager create(Map> nameToProvider) { - return new NamedSpiManager<>(nameToProvider); - } - - static NamedSpiManager createEmpty() { - return create(Collections.emptyMap()); - } - - @Nullable - T getByName(String name) { - return nameToImplementation - .computeIfAbsent(name, this::tryLoadImplementationForName) - .orElse(null); - } - - private Optional tryLoadImplementationForName(String name) { - Supplier provider = nameToProvider.get(name); - if (provider == null) { - return Optional.empty(); - } - - return Optional.ofNullable(provider.get()); - } -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/OtlpConfigUtil.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/OtlpConfigUtil.java deleted file mode 100644 index cf29078a709..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/OtlpConfigUtil.java +++ /dev/null @@ -1,233 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.time.Duration; -import java.util.Map; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import javax.annotation.Nullable; - -final class OtlpConfigUtil { - - static final String DATA_TYPE_TRACES = "traces"; - static final String DATA_TYPE_METRICS = "metrics"; - static final String DATA_TYPE_LOGS = "logs"; - - static final String PROTOCOL_GRPC = "grpc"; - static final String PROTOCOL_HTTP_PROTOBUF = "http/protobuf"; - - static String getOtlpProtocol(String dataType, ConfigProperties config) { - String protocol = config.getString("otel.exporter.otlp." + dataType + ".protocol"); - if (protocol == null) { - protocol = config.getString("otel.exporter.otlp.protocol"); - } - return (protocol == null) ? PROTOCOL_GRPC : protocol; - } - - static void configureOtlpExporterBuilder( - String dataType, - ConfigProperties config, - Consumer setEndpoint, - BiConsumer addHeader, - Consumer setCompression, - Consumer setTimeout, - Consumer setTrustedCertificates, - BiConsumer setClientTls, - Consumer setRetryPolicy) { - String protocol = getOtlpProtocol(dataType, config); - boolean isHttpProtobuf = protocol.equals(PROTOCOL_HTTP_PROTOBUF); - URL endpoint = - validateEndpoint( - config.getString("otel.exporter.otlp." + dataType + ".endpoint"), isHttpProtobuf); - if (endpoint != null) { - if (endpoint.getPath().isEmpty()) { - endpoint = createUrl(endpoint, "/"); - } - } else { - endpoint = validateEndpoint(config.getString("otel.exporter.otlp.endpoint"), isHttpProtobuf); - if (endpoint != null && isHttpProtobuf) { - String path = endpoint.getPath(); - if (!path.endsWith("/")) { - path += "/"; - } - path += signalPath(dataType); - endpoint = createUrl(endpoint, path); - } - } - if (endpoint != null) { - setEndpoint.accept(endpoint.toString()); - } - - Map headers = config.getMap("otel.exporter.otlp." + dataType + ".headers"); - if (headers.isEmpty()) { - headers = config.getMap("otel.exporter.otlp.headers"); - } - headers.forEach(addHeader); - - String compression = config.getString("otel.exporter.otlp." + dataType + ".compression"); - if (compression == null) { - compression = config.getString("otel.exporter.otlp.compression"); - } - if (compression != null) { - setCompression.accept(compression); - } - - Duration timeout = config.getDuration("otel.exporter.otlp." + dataType + ".timeout"); - if (timeout == null) { - timeout = config.getDuration("otel.exporter.otlp.timeout"); - } - if (timeout != null) { - setTimeout.accept(timeout); - } - - String certificatePath = - config.getString( - determinePropertyByType(config, "otel.exporter.otlp", dataType, "certificate")); - String clientKeyPath = - config.getString( - determinePropertyByType(config, "otel.exporter.otlp", dataType, "client.key")); - String clientKeyChainPath = - config.getString( - determinePropertyByType(config, "otel.exporter.otlp", dataType, "client.certificate")); - - if (clientKeyPath != null && clientKeyChainPath == null) { - throw new ConfigurationException("Client key provided but certification chain is missing"); - } else if (clientKeyPath == null && clientKeyChainPath != null) { - throw new ConfigurationException("Client key chain provided but key is missing"); - } - - byte[] certificateBytes = readFileBytes(certificatePath); - if (certificateBytes != null) { - setTrustedCertificates.accept(certificateBytes); - } - - byte[] clientKeyBytes = readFileBytes(clientKeyPath); - byte[] clientKeyChainBytes = readFileBytes(clientKeyChainPath); - - if (clientKeyBytes != null && clientKeyChainBytes != null) { - setClientTls.accept(clientKeyBytes, clientKeyChainBytes); - } - - Boolean retryEnabled = config.getBoolean("otel.experimental.exporter.otlp.retry.enabled"); - if (retryEnabled != null && retryEnabled) { - setRetryPolicy.accept(RetryPolicy.getDefault()); - } - } - - static void configureOtlpAggregationTemporality( - ConfigProperties config, - Consumer aggregationTemporalitySelectorConsumer) { - String temporalityStr = config.getString("otel.exporter.otlp.metrics.temporality.preference"); - if (temporalityStr == null) { - return; - } - AggregationTemporality temporality; - try { - temporality = AggregationTemporality.valueOf(temporalityStr.toUpperCase()); - } catch (IllegalArgumentException e) { - throw new ConfigurationException( - "Unrecognized aggregation temporality: " + temporalityStr, e); - } - AggregationTemporalitySelector temporalitySelector = - temporality == AggregationTemporality.CUMULATIVE - ? AggregationTemporalitySelector.alwaysCumulative() - : AggregationTemporalitySelector.deltaPreferred(); - aggregationTemporalitySelectorConsumer.accept(temporalitySelector); - } - - private static URL createUrl(URL context, String spec) { - try { - return new URL(context, spec); - } catch (MalformedURLException e) { - throw new ConfigurationException("Unexpected exception creating URL.", e); - } - } - - @Nullable - private static URL validateEndpoint(@Nullable String endpoint, boolean allowPath) { - if (endpoint == null) { - return null; - } - URL endpointUrl; - try { - endpointUrl = new URL(endpoint); - } catch (MalformedURLException e) { - throw new ConfigurationException("OTLP endpoint must be a valid URL: " + endpoint, e); - } - if (!endpointUrl.getProtocol().equals("http") && !endpointUrl.getProtocol().equals("https")) { - throw new ConfigurationException( - "OTLP endpoint scheme must be http or https: " + endpointUrl.getProtocol()); - } - if (endpointUrl.getQuery() != null) { - throw new ConfigurationException( - "OTLP endpoint must not have a query string: " + endpointUrl.getQuery()); - } - if (endpointUrl.getRef() != null) { - throw new ConfigurationException( - "OTLP endpoint must not have a fragment: " + endpointUrl.getRef()); - } - if (!allowPath && (!endpointUrl.getPath().isEmpty() && !endpointUrl.getPath().equals("/"))) { - throw new ConfigurationException( - "OTLP endpoint must not have a path: " + endpointUrl.getPath()); - } - return endpointUrl; - } - - @Nullable - private static byte[] readFileBytes(@Nullable String filePath) { - if (filePath == null) { - return null; - } - Path path = Paths.get(filePath); - if (!Files.exists(path)) { - throw new ConfigurationException("Invalid OTLP certificate/key path: " + path); - } - try { - return Files.readAllBytes(path); - } catch (IOException e) { - throw new ConfigurationException("Error reading content of file (" + path + ")", e); - } - } - - private static String determinePropertyByType( - ConfigProperties config, String prefix, String dataType, String suffix) { - String propertyToRead = prefix + "." + dataType + "." + suffix; - String value = config.getString(propertyToRead); - if (value == null) { - return prefix + "." + suffix; - } else { - return propertyToRead; - } - } - - private static String signalPath(String dataType) { - switch (dataType) { - case DATA_TYPE_METRICS: - return "v1/metrics"; - case DATA_TYPE_TRACES: - return "v1/traces"; - case DATA_TYPE_LOGS: - return "v1/logs"; - default: - throw new IllegalArgumentException( - "Cannot determine signal path for unrecognized data type: " + dataType); - } - } - - private OtlpConfigUtil() {} -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfiguration.java index f692f12aefa..fea60b18f80 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfiguration.java @@ -9,6 +9,8 @@ import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; @@ -20,25 +22,30 @@ final class PropagatorConfiguration { + private static final List DEFAULT_PROPAGATORS = Arrays.asList("tracecontext", "baggage"); + static ContextPropagators configurePropagators( ConfigProperties config, - ClassLoader serviceClassLoader, + SpiHelper spiHelper, BiFunction propagatorCustomizer) { Set propagators = new LinkedHashSet<>(); - List requestedPropagators = config.getList("otel.propagators"); - if (requestedPropagators.isEmpty()) { - requestedPropagators = Arrays.asList("tracecontext", "baggage"); - } + List requestedPropagators = config.getList("otel.propagators", DEFAULT_PROPAGATORS); NamedSpiManager spiPropagatorsManager = - SpiUtil.loadConfigurable( + spiHelper.loadConfigurable( ConfigurablePropagatorProvider.class, ConfigurablePropagatorProvider::getName, ConfigurablePropagatorProvider::getPropagator, - config, - serviceClassLoader); + config); + if (requestedPropagators.contains("none")) { + if (requestedPropagators.size() > 1) { + throw new ConfigurationException( + "otel.propagators contains 'none' along with other propagators"); + } + return ContextPropagators.noop(); + } for (String propagatorName : requestedPropagators) { propagators.add( propagatorCustomizer.apply(getPropagator(propagatorName, spiPropagatorsManager), config)); diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ResourceConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ResourceConfiguration.java index 19ed04edfcb..9f1a1c4d03c 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ResourceConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ResourceConfiguration.java @@ -5,41 +5,68 @@ package io.opentelemetry.sdk.autoconfigure; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConditionalResourceProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.resources.ResourceBuilder; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; +import java.util.Collections; import java.util.HashSet; -import java.util.ServiceLoader; +import java.util.List; import java.util.Set; import java.util.function.BiFunction; -/** Auto-configuration for the OpenTelemetry {@link Resource}. */ -final class ResourceConfiguration { +/** + * Auto-configuration for the OpenTelemetry {@link Resource}. + * + * @since 1.28.0 + */ +public final class ResourceConfiguration { // Visible for testing - static final String ATTRIBUTE_PROPERTY = "otel.resource.attributes"; - static final String SERVICE_NAME_PROPERTY = "otel.service.name"; - static final String DISABLED_ATTRIBUTE_KEYS = "otel.experimental.resource.disabled.keys"; + static final String DISABLED_ATTRIBUTE_KEYS = "otel.resource.disabled.keys"; + static final String ENABLED_RESOURCE_PROVIDERS = "otel.java.enabled.resource.providers"; + static final String DISABLED_RESOURCE_PROVIDERS = "otel.java.disabled.resource.providers"; + + /** + * Create a {@link Resource} from the environment. The resource contains attributes parsed from + * environment variables and system property keys {@code otel.resource.attributes} and {@code + * otel.service.name}. + * + * @return the resource. + */ + public static Resource createEnvironmentResource() { + return createEnvironmentResource( + DefaultConfigProperties.create( + Collections.emptyMap(), + ComponentLoader.forClassLoader(ResourceConfiguration.class.getClassLoader()))); + } + + /** + * Create a {@link Resource} from the environment. The resource contains attributes parsed from + * environment variables and system property keys {@code otel.resource.attributes} and {@code + * otel.service.name}. + * + * @param config the {@link ConfigProperties} used to obtain resource properties + * @return the resource. + */ + public static Resource createEnvironmentResource(ConfigProperties config) { + return EnvironmentResource.createEnvironmentResource(config); + } static Resource configureResource( ConfigProperties config, - ClassLoader serviceClassLoader, + SpiHelper spiHelper, BiFunction resourceCustomizer) { Resource result = Resource.getDefault(); - Set enabledProviders = - new HashSet<>(config.getList("otel.java.enabled.resource.providers")); - // TODO(anuraaga): We use a hyphen only once in this artifact, for - // otel.java.disabled.resource-providers. But fetching by the dot version is the simplest way - // to implement it for now. - Set disabledProviders = - new HashSet<>(config.getList("otel.java.disabled.resource.providers")); - for (ResourceProvider resourceProvider : - ServiceLoader.load(ResourceProvider.class, serviceClassLoader)) { + Set enabledProviders = new HashSet<>(config.getList(ENABLED_RESOURCE_PROVIDERS)); + Set disabledProviders = new HashSet<>(config.getList(DISABLED_RESOURCE_PROVIDERS)); + + for (ResourceProvider resourceProvider : spiHelper.loadOrdered(ResourceProvider.class)) { if (!enabledProviders.isEmpty() && !enabledProviders.contains(resourceProvider.getClass().getName())) { continue; @@ -47,34 +74,22 @@ static Resource configureResource( if (disabledProviders.contains(resourceProvider.getClass().getName())) { continue; } + if (resourceProvider instanceof ConditionalResourceProvider + && !((ConditionalResourceProvider) resourceProvider).shouldApply(config, result)) { + continue; + } result = result.merge(resourceProvider.createResource(config)); } - result = result.merge(createEnvironmentResource(config)); - result = filterAttributes(result, config); return resourceCustomizer.apply(result, config); } - private static Resource createEnvironmentResource(ConfigProperties config) { - return Resource.create(getAttributes(config), ResourceAttributes.SCHEMA_URL); - } - - // visible for testing - static Attributes getAttributes(ConfigProperties configProperties) { - AttributesBuilder resourceAttributes = Attributes.builder(); - configProperties.getMap(ATTRIBUTE_PROPERTY).forEach(resourceAttributes::put); - String serviceName = configProperties.getString(SERVICE_NAME_PROPERTY); - if (serviceName != null) { - resourceAttributes.put(ResourceAttributes.SERVICE_NAME, serviceName); - } - return resourceAttributes.build(); - } - // visible for testing static Resource filterAttributes(Resource resource, ConfigProperties configProperties) { - Set disabledKeys = new HashSet<>(configProperties.getList(DISABLED_ATTRIBUTE_KEYS)); + List disabledAttibuteKeys = configProperties.getList(DISABLED_ATTRIBUTE_KEYS); + Set disabledKeys = new HashSet<>(disabledAttibuteKeys); ResourceBuilder builder = resource.toBuilder().removeIf(attributeKey -> disabledKeys.contains(attributeKey.getKey())); diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ServiceInstanceIdResourceProvider.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ServiceInstanceIdResourceProvider.java new file mode 100644 index 00000000000..43de8f4fd53 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/ServiceInstanceIdResourceProvider.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Collections; +import java.util.UUID; + +/** + * A {@link ResourceProvider} which supplies a {@code service.instance} entity with a random UUID + * {@code service.instance.id}, stable for the lifetime of the JVM. Runs at {@link + * Integer#MIN_VALUE} so that any other {@link ResourceProvider} or user configuration which sets + * {@code service.instance.id} takes precedence. + * + * @since 1.67.0 + */ +public final class ServiceInstanceIdResourceProvider implements ResourceProvider { + + private static final Resource RANDOM = + EntityUtil.createResource( + Collections.singletonList( + Entity.builder( + SemConvConstants.SERVICE_INSTANCE_TYPE, + Attributes.of( + SemConvConstants.SERVICE_INSTANCE_ID, UUID.randomUUID().toString())) + .setSchemaUrl(SemConvConstants.SCHEMA_URL_V1_40_0) + .build())); + + @Override + public Resource createResource(ConfigProperties config) { + return RANDOM; + } + + @Override + public int order() { + return Integer.MIN_VALUE; + } +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfiguration.java index a3d2c394783..f7232ae0013 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfiguration.java @@ -5,199 +5,100 @@ package io.opentelemetry.sdk.autoconfigure; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.DATA_TYPE_TRACES; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_GRPC; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; -import static java.util.stream.Collectors.toMap; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter; -import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporterBuilder; -import io.opentelemetry.exporter.logging.LoggingSpanExporter; -import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; -import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporterBuilder; -import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; -import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporterBuilder; -import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter; -import io.opentelemetry.exporter.zipkin.ZipkinSpanExporterBuilder; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.time.Duration; +import java.io.Closeable; import java.util.Collections; +import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.BiFunction; -import java.util.function.Function; final class SpanExporterConfiguration { private static final String EXPORTER_NONE = "none"; + private static final Map EXPORTER_ARTIFACT_ID_BY_NAME; + + static { + EXPORTER_ARTIFACT_ID_BY_NAME = new HashMap<>(); + EXPORTER_ARTIFACT_ID_BY_NAME.put("console", "opentelemetry-exporter-logging"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("jaeger", "opentelemetry-exporter-jaeger"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("logging", "opentelemetry-exporter-logging"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("logging-otlp", "opentelemetry-exporter-logging-otlp"); + EXPORTER_ARTIFACT_ID_BY_NAME.put( + "experimental-otlp/stdout", "opentelemetry-exporter-logging-otlp"); + EXPORTER_ARTIFACT_ID_BY_NAME.put("otlp", "opentelemetry-exporter-otlp"); + } // Visible for testing + @SuppressWarnings("ReferenceEquality") static Map configureSpanExporters( ConfigProperties config, - ClassLoader serviceClassLoader, - MeterProvider meterProvider, + SpiHelper spiHelper, BiFunction - spanExporterCustomizer) { + spanExporterCustomizer, + List closeables) { Set exporterNames = DefaultConfigProperties.getSet(config, "otel.traces.exporter"); if (exporterNames.contains(EXPORTER_NONE)) { if (exporterNames.size() > 1) { throw new ConfigurationException( "otel.traces.exporter contains " + EXPORTER_NONE + " along with other exporters"); } - SpanExporter noop = SpanExporter.composite(); - SpanExporter customized = spanExporterCustomizer.apply(noop, config); - if (customized == noop) { - return Collections.emptyMap(); - } - return Collections.singletonMap(EXPORTER_NONE, customized); + return Collections.emptyMap(); } if (exporterNames.isEmpty()) { exporterNames = Collections.singleton("otlp"); } - NamedSpiManager spiExportersManager = - SpiUtil.loadConfigurable( - ConfigurableSpanExporterProvider.class, - ConfigurableSpanExporterProvider::getName, - ConfigurableSpanExporterProvider::createExporter, - config, - serviceClassLoader); - - return exporterNames.stream() - .collect( - toMap( - Function.identity(), - exporterName -> - spanExporterCustomizer.apply( - configureExporter(exporterName, config, spiExportersManager, meterProvider), - config))); - } + NamedSpiManager spiExportersManager = spanExporterSpiManager(config, spiHelper); - // Visible for testing - static SpanExporter configureExporter( - String name, - ConfigProperties config, - NamedSpiManager spiExportersManager, - MeterProvider meterProvider) { - switch (name) { - case "otlp": - return configureOtlp(config, meterProvider); - case "jaeger": - return configureJaeger(config, meterProvider); - case "zipkin": - return configureZipkin(config); - case "logging": - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.logging.LoggingSpanExporter", - "Logging Trace Exporter", - "opentelemetry-exporter-logging"); - return LoggingSpanExporter.create(); - default: - SpanExporter spiExporter = spiExportersManager.getByName(name); - if (spiExporter == null) { - throw new ConfigurationException("Unrecognized value for otel.traces.exporter: " + name); - } - return spiExporter; + Map map = new HashMap<>(); + for (String exporterName : exporterNames) { + SpanExporter spanExporter = configureExporter(exporterName, spiExportersManager); + closeables.add(spanExporter); + SpanExporter customizedSpanExporter = spanExporterCustomizer.apply(spanExporter, config); + if (customizedSpanExporter != spanExporter) { + closeables.add(customizedSpanExporter); + } + map.put(exporterName, customizedSpanExporter); } + return Collections.unmodifiableMap(map); } // Visible for testing - static SpanExporter configureOtlp(ConfigProperties config, MeterProvider meterProvider) { - String protocol = OtlpConfigUtil.getOtlpProtocol(DATA_TYPE_TRACES, config); - - if (protocol.equals(PROTOCOL_HTTP_PROTOBUF)) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter", - "OTLP HTTP Trace Exporter", - "opentelemetry-exporter-otlp-http-trace"); - OtlpHttpSpanExporterBuilder builder = OtlpHttpSpanExporter.builder(); - - OtlpConfigUtil.configureOtlpExporterBuilder( - DATA_TYPE_TRACES, - config, - builder::setEndpoint, - builder::addHeader, - builder::setCompression, - builder::setTimeout, - builder::setTrustedCertificates, - builder::setClientTls, - retryPolicy -> RetryUtil.setRetryPolicyOnDelegate(builder, retryPolicy)); - - builder.setMeterProvider(meterProvider); - - return builder.build(); - } else if (protocol.equals(PROTOCOL_GRPC)) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter", - "OTLP gRPC Trace Exporter", - "opentelemetry-exporter-otlp"); - OtlpGrpcSpanExporterBuilder builder = OtlpGrpcSpanExporter.builder(); - - OtlpConfigUtil.configureOtlpExporterBuilder( - DATA_TYPE_TRACES, - config, - builder::setEndpoint, - builder::addHeader, - builder::setCompression, - builder::setTimeout, - builder::setTrustedCertificates, - builder::setClientTls, - retryPolicy -> RetryUtil.setRetryPolicyOnDelegate(builder, retryPolicy)); - builder.setMeterProvider(meterProvider); - - return builder.build(); - } else { - throw new ConfigurationException("Unsupported OTLP traces protocol: " + protocol); - } + static NamedSpiManager spanExporterSpiManager( + ConfigProperties config, SpiHelper spiHelper) { + return spiHelper.loadConfigurable( + ConfigurableSpanExporterProvider.class, + ConfigurableSpanExporterProvider::getName, + ConfigurableSpanExporterProvider::createExporter, + config); } - private static SpanExporter configureJaeger( - ConfigProperties config, MeterProvider meterProvider) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter", - "Jaeger gRPC Exporter", - "opentelemetry-exporter-jaeger"); - JaegerGrpcSpanExporterBuilder builder = JaegerGrpcSpanExporter.builder(); - - String endpoint = config.getString("otel.exporter.jaeger.endpoint"); - if (endpoint != null) { - builder.setEndpoint(endpoint); - } - - Duration timeout = config.getDuration("otel.exporter.jaeger.timeout"); - if (timeout != null) { - builder.setTimeout(timeout); - } - - builder.setMeterProvider(meterProvider); - - return builder.build(); - } - - private static SpanExporter configureZipkin(ConfigProperties config) { - ClasspathUtil.checkClassExists( - "io.opentelemetry.exporter.zipkin.ZipkinSpanExporter", - "Zipkin Exporter", - "opentelemetry-exporter-zipkin"); - ZipkinSpanExporterBuilder builder = ZipkinSpanExporter.builder(); - - String endpoint = config.getString("otel.exporter.zipkin.endpoint"); - if (endpoint != null) { - builder.setEndpoint(endpoint); - } - - Duration timeout = config.getDuration("otel.exporter.zipkin.timeout"); - if (timeout != null) { - builder.setReadTimeout(timeout); + // Visible for testing + static SpanExporter configureExporter( + String name, NamedSpiManager spiExportersManager) { + SpanExporter spiExporter = spiExportersManager.getByName(name); + if (spiExporter == null) { + String artifactId = EXPORTER_ARTIFACT_ID_BY_NAME.get(name); + if (artifactId != null) { + throw new ConfigurationException( + "otel.traces.exporter set to \"" + + name + + "\" but " + + artifactId + + " not found on classpath. Make sure to add it as a dependency."); + } + throw new ConfigurationException("Unrecognized value for otel.traces.exporter: " + name); } - - return builder.build(); + return spiExporter; } private SpanExporterConfiguration() {} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpiUtil.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpiUtil.java deleted file mode 100644 index dbd2613baae..00000000000 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/SpiUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import java.util.HashMap; -import java.util.Map; -import java.util.ServiceLoader; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; - -final class SpiUtil { - - interface ServiceLoaderFinder { - - Iterable load(Class spiClass, ClassLoader classLoader); - } - - static NamedSpiManager loadConfigurable( - Class spiClass, - Function getName, - BiFunction getConfigurable, - ConfigProperties config, - ClassLoader serviceClassLoader) { - return loadConfigurable( - spiClass, getName, getConfigurable, config, serviceClassLoader, ServiceLoader::load); - } - - // VisibleForTesting - static NamedSpiManager loadConfigurable( - Class spiClass, - Function getName, - BiFunction getConfigurable, - ConfigProperties config, - ClassLoader serviceClassLoader, - ServiceLoaderFinder serviceLoaderFinder) { - Map> nameToProvider = new HashMap<>(); - for (U provider : serviceLoaderFinder.load(spiClass, serviceClassLoader)) { - String name = getName.apply(provider); - nameToProvider.put(name, () -> getConfigurable.apply(provider, config)); - } - return NamedSpiManager.create(nameToProvider); - } - - private SpiUtil() {} -} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfiguration.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfiguration.java index 78a239597cb..3ca75b483d3 100644 --- a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfiguration.java +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfiguration.java @@ -6,9 +6,12 @@ package io.opentelemetry.sdk.autoconfigure; import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; import io.opentelemetry.sdk.trace.SpanLimits; import io.opentelemetry.sdk.trace.SpanLimitsBuilder; @@ -16,10 +19,13 @@ import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; import io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder; import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.io.Closeable; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -27,47 +33,79 @@ final class TracerProviderConfiguration { + private static final double DEFAULT_TRACEIDRATIO_SAMPLE_RATIO = 1.0d; + private static final String PARENTBASED_ALWAYS_ON = "parentbased_always_on"; + private static final List simpleProcessorExporterNames = + Arrays.asList("console", "logging"); + + @SuppressWarnings("ReferenceEquality") static void configureTracerProvider( SdkTracerProviderBuilder tracerProviderBuilder, ConfigProperties config, - ClassLoader serviceClassLoader, + SpiHelper spiHelper, MeterProvider meterProvider, BiFunction spanExporterCustomizer, - BiFunction samplerCustomizer) { + BiFunction + spanProcessorCustomizer, + BiFunction samplerCustomizer, + List closeables) { tracerProviderBuilder.setSpanLimits(configureSpanLimits(config)); - - String sampler = config.getString("otel.traces.sampler"); - if (sampler == null) { - sampler = "parentbased_always_on"; + InternalTelemetryVersion telemetryVersion = InternalTelemetryConfiguration.getVersion(config); + if (telemetryVersion != InternalTelemetryVersion.LEGACY) { + tracerProviderBuilder.setMeterProvider(() -> meterProvider); } + + String sampler = config.getString("otel.traces.sampler", PARENTBASED_ALWAYS_ON); tracerProviderBuilder.setSampler( - samplerCustomizer.apply(configureSampler(sampler, config, serviceClassLoader), config)); + samplerCustomizer.apply(configureSampler(sampler, config, spiHelper), config)); Map exportersByName = SpanExporterConfiguration.configureSpanExporters( - config, serviceClassLoader, meterProvider, spanExporterCustomizer); - - configureSpanProcessors(config, exportersByName, meterProvider) - .forEach(tracerProviderBuilder::addSpanProcessor); + config, spiHelper, spanExporterCustomizer, closeables); + + List processors = + configureSpanProcessors( + config, exportersByName, telemetryVersion, meterProvider, closeables); + for (SpanProcessor processor : processors) { + SpanProcessor wrapped = spanProcessorCustomizer.apply(processor, config); + if (wrapped != processor) { + closeables.add(wrapped); + } + tracerProviderBuilder.addSpanProcessor(wrapped); + } } static List configureSpanProcessors( ConfigProperties config, Map exportersByName, - MeterProvider meterProvider) { + InternalTelemetryVersion telemetryVersion, + MeterProvider meterProvider, + List closeables) { Map exportersByNameCopy = new HashMap<>(exportersByName); List spanProcessors = new ArrayList<>(); - SpanExporter exporter = exportersByNameCopy.remove("logging"); - if (exporter != null) { - spanProcessors.add(SimpleSpanProcessor.create(exporter)); + for (String simpleProcessorExporterNames : simpleProcessorExporterNames) { + SpanExporter exporter = exportersByNameCopy.remove(simpleProcessorExporterNames); + if (exporter != null) { + SimpleSpanProcessorBuilder spanProcessorBuilder = SimpleSpanProcessor.builder(exporter); + if (telemetryVersion != InternalTelemetryVersion.LEGACY) { + spanProcessorBuilder.setMeterProvider(() -> meterProvider); + } + SpanProcessor spanProcessor = spanProcessorBuilder.build(); + closeables.add(spanProcessor); + spanProcessors.add(spanProcessor); + } } if (!exportersByNameCopy.isEmpty()) { SpanExporter compositeSpanExporter = SpanExporter.composite(exportersByNameCopy.values()); - spanProcessors.add(configureBatchSpanProcessor(config, compositeSpanExporter, meterProvider)); + SpanProcessor spanProcessor = + configureBatchSpanProcessor( + config, compositeSpanExporter, telemetryVersion, meterProvider); + closeables.add(spanProcessor); + spanProcessors.add(spanProcessor); } return spanProcessors; @@ -75,9 +113,12 @@ static List configureSpanProcessors( // VisibleForTesting static BatchSpanProcessor configureBatchSpanProcessor( - ConfigProperties config, SpanExporter exporter, MeterProvider meterProvider) { + ConfigProperties config, + SpanExporter exporter, + InternalTelemetryVersion telemetryVersion, + MeterProvider meterProvider) { BatchSpanProcessorBuilder builder = - BatchSpanProcessor.builder(exporter).setMeterProvider(meterProvider); + BatchSpanProcessor.builder(exporter).setMeterProvider(() -> meterProvider); Duration scheduleDelay = config.getDuration("otel.bsp.schedule.delay"); if (scheduleDelay != null) { @@ -99,6 +140,8 @@ static BatchSpanProcessor configureBatchSpanProcessor( builder.setExporterTimeout(timeout); } + builder.setInternalTelemetryVersion(telemetryVersion); + return builder.build(); } @@ -140,15 +183,13 @@ static SpanLimits configureSpanLimits(ConfigProperties config) { } // Visible for testing - static Sampler configureSampler( - String sampler, ConfigProperties config, ClassLoader serviceClassLoader) { + static Sampler configureSampler(String sampler, ConfigProperties config, SpiHelper spiHelper) { NamedSpiManager spiSamplersManager = - SpiUtil.loadConfigurable( + spiHelper.loadConfigurable( ConfigurableSamplerProvider.class, ConfigurableSamplerProvider::getName, ConfigurableSamplerProvider::createSampler, - config, - serviceClassLoader); + config); switch (sampler) { case "always_on": @@ -156,25 +197,20 @@ static Sampler configureSampler( case "always_off": return Sampler.alwaysOff(); case "traceidratio": - { - Double ratio = config.getDouble("otel.traces.sampler.arg"); - if (ratio == null) { - ratio = 1.0d; - } - return Sampler.traceIdRatioBased(ratio); - } - case "parentbased_always_on": + return ratioSampler(config); + case PARENTBASED_ALWAYS_ON: return Sampler.parentBased(Sampler.alwaysOn()); case "parentbased_always_off": return Sampler.parentBased(Sampler.alwaysOff()); case "parentbased_traceidratio": - { - Double ratio = config.getDouble("otel.traces.sampler.arg"); - if (ratio == null) { - ratio = 1.0d; - } - return Sampler.parentBased(Sampler.traceIdRatioBased(ratio)); + return Sampler.parentBased(ratioSampler(config)); + case "parentbased_jaeger_remote": + Sampler jaegerRemote = spiSamplersManager.getByName("jaeger_remote"); + if (jaegerRemote == null) { + throw new ConfigurationException( + "parentbased_jaeger_remote configured but opentelemetry-sdk-extension-jaeger-remote-sampler not on classpath"); } + return Sampler.parentBased(jaegerRemote); default: Sampler spiSampler = spiSamplersManager.getByName(sampler); if (spiSampler == null) { @@ -185,5 +221,10 @@ static Sampler configureSampler( } } + private static Sampler ratioSampler(ConfigProperties config) { + double ratio = config.getDouble("otel.traces.sampler.arg", DEFAULT_TRACEIDRATIO_SAMPLE_RATIO); + return Sampler.traceIdRatioBased(ratio); + } + private TracerProviderConfiguration() {} } diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/AutoConfigureUtil.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/AutoConfigureUtil.java new file mode 100644 index 00000000000..c100ee20b25 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/AutoConfigureUtil.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.internal; + +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdkBuilder; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.function.Function; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class AutoConfigureUtil { + + private AutoConfigureUtil() {} + + /** + * Returns the {@link ConfigProperties} used for auto-configuration. + * + * @return the config properties, or {@code null} if declarative configuration is used + */ + @Nullable + public static ConfigProperties getConfig( + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk) { + try { + Method method = AutoConfiguredOpenTelemetrySdk.class.getDeclaredMethod("getConfig"); + method.setAccessible(true); + return (ConfigProperties) method.invoke(autoConfiguredOpenTelemetrySdk); + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + throw new IllegalStateException( + "Error calling getConfig on AutoConfiguredOpenTelemetrySdk", e); + } + } + + /** Sets the {@link ConfigProperties} customizer to be used in the auto-configuration process. */ + public static AutoConfiguredOpenTelemetrySdkBuilder setConfigPropertiesCustomizer( + AutoConfiguredOpenTelemetrySdkBuilder builder, + Function customizer) { + try { + Method method = + AutoConfiguredOpenTelemetrySdkBuilder.class.getDeclaredMethod( + "setConfigPropertiesCustomizer", Function.class); + method.setAccessible(true); + method.invoke(builder, customizer); + return builder; + } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { + throw new IllegalStateException( + "Error calling setConfigPropertiesCustomizer on AutoConfiguredOpenTelemetrySdkBuilder", + e); + } + } +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/NamedSpiManager.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/NamedSpiManager.java new file mode 100644 index 00000000000..cde40120c16 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/NamedSpiManager.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.internal; + +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class NamedSpiManager { + + private final Map> nameToProvider; + private final ConcurrentMap> nameToImplementation = new ConcurrentHashMap<>(); + + private NamedSpiManager(Map> nameToProvider) { + this.nameToProvider = nameToProvider; + } + + static NamedSpiManager create(Map> nameToProvider) { + return new NamedSpiManager<>(nameToProvider); + } + + public static NamedSpiManager createEmpty() { + return create(Collections.emptyMap()); + } + + /** Return an implementation by name, invoking the supplier if not previously invoked. */ + @Nullable + public T getByName(String name) { + return nameToImplementation + .computeIfAbsent(name, this::tryLoadImplementationForName) + .orElse(null); + } + + private Optional tryLoadImplementationForName(String name) { + Supplier provider = nameToProvider.get(name); + if (provider == null) { + return Optional.empty(); + } + + return Optional.ofNullable(provider.get()); + } +} diff --git a/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/SpiHelper.java b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/SpiHelper.java new file mode 100644 index 00000000000..96107c11ff3 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/java/io/opentelemetry/sdk/autoconfigure/internal/SpiHelper.java @@ -0,0 +1,120 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.internal; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.Ordered; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import java.util.Collections; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.function.Supplier; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class SpiHelper { + + private final ComponentLoader componentLoader; + private final Set listeners = + Collections.newSetFromMap(new IdentityHashMap<>()); + + private SpiHelper(ComponentLoader componentLoader) { + this.componentLoader = componentLoader; + } + + /** Create a {@link SpiHelper} which loads SPIs using the {@code classLoader}. */ + public static SpiHelper create(ClassLoader classLoader) { + return new SpiHelper(ComponentLoader.forClassLoader(classLoader)); + } + + /** Create a {@link SpiHelper} which loads SPIs using the {@code componentLoader}. */ + public static SpiHelper create(ComponentLoader componentLoader) { + return new SpiHelper(componentLoader); + } + + /** Return the backing underlying {@link ComponentLoader}. */ + public ComponentLoader getComponentLoader() { + return componentLoader; + } + + /** + * Load implementations of an SPI which are configurable (i.e. they accept {@link + * ConfigProperties}. + * + * @param spiClass the SPI class + * @param getName function returning the name of an SPI implementation + * @param getConfigurable function returning a configured instance + * @param config the configuration to pass to invocations of {@code #getConfigurable} + * @param the configurable type + * @param the SPI type + * @return a {@link NamedSpiManager} used to access configured instances of the SPI by name + */ + public NamedSpiManager loadConfigurable( + Class spiClass, + Function getName, + BiFunction getConfigurable, + ConfigProperties config) { + Map> nameToProvider = new HashMap<>(); + for (S provider : load(spiClass)) { + String name = getName.apply(provider); + nameToProvider.put( + name, + () -> { + T result = getConfigurable.apply(provider, config); + maybeAddListener(Collections.singletonList(result)); + return result; + }); + } + return NamedSpiManager.create(nameToProvider); + } + + /** + * Load implementations of an ordered SPI (i.e. implements {@link Ordered}). + * + * @param spiClass the SPI class + * @param the SPI type + * @return list of SPI implementations, in order + */ + public List loadOrdered(Class spiClass) { + List result = Ordered.loadOrderedList(componentLoader, spiClass); + maybeAddListener(result); + return result; + } + + /** + * Load implementations of an SPI. + * + * @param spiClass the SPI class + * @param the SPI type + * @return list of SPI implementations + */ + public List load(Class spiClass) { + List result = ComponentLoader.loadList(componentLoader, spiClass); + maybeAddListener(result); + return result; + } + + private void maybeAddListener(List objects) { + for (Object object : objects) { + if (object instanceof AutoConfigureListener) { + listeners.add((AutoConfigureListener) object); + } + } + } + + /** Return the set of SPIs loaded which implement {@link AutoConfigureListener}. */ + public Set getListeners() { + return Collections.unmodifiableSet(listeners); + } +} diff --git a/sdk-extensions/autoconfigure/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider b/sdk-extensions/autoconfigure/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider new file mode 100644 index 00000000000..94ba757434d --- /dev/null +++ b/sdk-extensions/autoconfigure/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider @@ -0,0 +1,2 @@ +io.opentelemetry.sdk.autoconfigure.ServiceInstanceIdResourceProvider +io.opentelemetry.sdk.autoconfigure.EnvironmentResourceProvider diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfigureUtilTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfigureUtilTest.java new file mode 100644 index 00000000000..33dd1ba01dd --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfigureUtilTest.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static java.util.Collections.singletonMap; + +import io.opentelemetry.sdk.autoconfigure.internal.AutoConfigureUtil; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class AutoConfigureUtilTest { + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk; + + @BeforeEach + void beforeEach() { + autoConfiguredOpenTelemetrySdk = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .build(); + } + + @Test + void getConfig() { + Assertions.assertThat(AutoConfigureUtil.getConfig(autoConfiguredOpenTelemetrySdk)) + .isSameAs(autoConfiguredOpenTelemetrySdk.getConfig()); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java index 88d0777a84a..daf12698cd5 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java @@ -6,71 +6,159 @@ package io.opentelemetry.sdk.autoconfigure; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.common.ComponentLoader; import io.opentelemetry.context.Context; import io.opentelemetry.context.ContextKey; import io.opentelemetry.context.propagation.TextMapGetter; import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.internal.AutoConfigureUtil; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; import io.opentelemetry.sdk.trace.IdGenerator; import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.samplers.Sampler; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; +import java.io.IOException; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; +import java.util.Properties; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.function.BiFunction; +import java.util.function.Consumer; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class AutoConfiguredOpenTelemetrySdkTest { + @RegisterExtension + LogCapturer logs = + LogCapturer.create().captureForType(AutoConfiguredOpenTelemetrySdkBuilder.class); + @Mock private IdGenerator idGenerator; @Mock private TextMapPropagator propagator1; @Mock private TextMapPropagator propagator2; @Mock private TextMapGetter> getter; @Mock private Sampler sampler1; @Mock private Sampler sampler2; - @Mock private SpanExporter spanExporter1; - @Mock private SpanExporter spanExporter2; @Mock private MetricReader metricReader; - @Mock private LogProcessor logProcessor; + @Mock private LogRecordProcessor logRecordProcessor; private AutoConfiguredOpenTelemetrySdkBuilder builder; + private static BiFunction + getTracerProviderBuilderSpy() { + BiFunction + traceCustomizer = + spy( + new BiFunction< + SdkTracerProviderBuilder, ConfigProperties, SdkTracerProviderBuilder>() { + @Override + public SdkTracerProviderBuilder apply( + SdkTracerProviderBuilder builder, ConfigProperties config) { + return builder; + } + }); + return traceCustomizer; + } + + private static BiFunction + getMeterProviderBuilderSpy() { + BiFunction + metricCustomizer = + spy( + new BiFunction< + SdkMeterProviderBuilder, ConfigProperties, SdkMeterProviderBuilder>() { + @Override + public SdkMeterProviderBuilder apply( + SdkMeterProviderBuilder builder, ConfigProperties config) { + return builder; + } + }); + return metricCustomizer; + } + + private static BiFunction + getLoggerProviderBuilderSpy() { + BiFunction logCustomizer = + spy( + new BiFunction() { + @Override + public SdkLoggerProviderBuilder apply( + SdkLoggerProviderBuilder builder, ConfigProperties config) { + return builder; + } + }); + return logCustomizer; + } + @BeforeEach void resetGlobal() { GlobalOpenTelemetry.resetForTest(); builder = AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) .addPropertiesSupplier(disableExportPropertySupplier()); } @@ -81,9 +169,10 @@ void builder_addTracerProviderCustomizer() { Span span = builder - .addTracerProviderCustomizer( - (tracerProviderBuilder, config) -> - tracerProviderBuilder.setIdGenerator(idGenerator)) + .addTracerProviderCustomizer((tracerProviderBuilder, config) -> + tracerProviderBuilder + .setIdGenerator(idGenerator) + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop()))) .build() .getOpenTelemetrySdk() .getTracer("test") @@ -104,18 +193,15 @@ void builder_addPropagatorCustomizer() { OpenTelemetrySdk sdk = builder - .addPropertiesSupplier( - () -> Collections.singletonMap("otel.propagators", "tracecontext")) - .addPropagatorCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); - return propagator1; - }) - .addPropagatorCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(propagator1); - return propagator2; - }) + .addPropertiesSupplier(() -> singletonMap("otel.propagators", "tracecontext")) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); + return propagator1; + }) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(propagator1); + return propagator2; + }) .build() .getOpenTelemetrySdk(); @@ -130,9 +216,8 @@ void builder_addPropagatorCustomizer() { void builder_addResourceCustomizer() { Resource autoConfiguredResource = builder - .addResourceCustomizer( - (resource, config) -> - resource.merge(Resource.builder().put("key2", "value2").build())) + .addResourceCustomizer((resource, config) -> + resource.merge(Resource.builder().put("key2", "value2").build())) .build() .getResource(); @@ -143,16 +228,14 @@ void builder_addResourceCustomizer() { void builder_addSamplerCustomizer() { SdkTracerProvider sdkTracerProvider = builder - .addSamplerCustomizer( - (previous, config) -> { - assertThat(previous).isEqualTo(Sampler.parentBased(Sampler.alwaysOn())); - return sampler1; - }) - .addSamplerCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(sampler1); - return sampler2; - }) + .addSamplerCustomizer((previous, config) -> { + assertThat(previous).isEqualTo(Sampler.parentBased(Sampler.alwaysOn())); + return sampler1; + }) + .addSamplerCustomizer((previous, config) -> { + assertThat(previous).isSameAs(sampler1); + return sampler2; + }) .build() .getOpenTelemetrySdk() .getSdkTracerProvider(); @@ -164,61 +247,104 @@ void builder_addSamplerCustomizer() { } @Test - void builder_addSpanExporterCustomizer() { - Mockito.lenient().when(spanExporter2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + void builder_addAutoConfigurationCustomizerProviderUsingComponentLoader() { + AutoConfigurationCustomizerProvider customizerProvider = + mock(AutoConfigurationCustomizerProvider.class); + + SpiHelper spiHelper = + SpiHelper.create(AutoConfiguredOpenTelemetrySdkBuilder.class.getClassLoader()); + + ComponentLoader componentLoader = + new ComponentLoader() { + @SuppressWarnings("unchecked") + @Override + public Iterable load(Class spiClass) { + if (spiClass.equals(AutoConfigurationCustomizerProvider.class)) { + return Collections.singletonList((T) customizerProvider); + } + return spiHelper.load(spiClass); + } + }; + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = + builder.setComponentLoader(componentLoader).build(); - SdkTracerProvider sdkTracerProvider = - builder - .addSpanExporterCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(SpanExporter.composite()); - return spanExporter1; - }) - .addSpanExporterCustomizer( - (previous, config) -> { - assertThat(previous).isSameAs(spanExporter1); - return spanExporter2; - }) - .build() - .getOpenTelemetrySdk() - .getSdkTracerProvider(); + assertThat( + Objects.requireNonNull(autoConfiguredOpenTelemetrySdk.getConfig()).getComponentLoader()) + .isSameAs(componentLoader); + verify(customizerProvider).customize(any()); + verifyNoMoreInteractions(customizerProvider); - assertThat(sdkTracerProvider) - .extracting("sharedState") - .extracting("activeSpanProcessor") - .extracting("worker") - .extracting("spanExporter") - .isEqualTo(spanExporter2); + autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().shutdown().join(10, TimeUnit.SECONDS); } @Test void builder_addPropertiesSupplier() { AutoConfiguredOpenTelemetrySdk autoConfigured = builder - .addPropertiesSupplier(() -> Collections.singletonMap("key", "valueUnused")) - .addPropertiesSupplier(() -> Collections.singletonMap("key", "value")) - .addPropertiesSupplier(() -> Collections.singletonMap("otel-key", "otel-value")) - .addPropertiesSupplier( - () -> Collections.singletonMap("otel.service.name", "test-service")) - .setResultAsGlobal(false) + .addPropertiesSupplier(() -> singletonMap("key", "valueUnused")) + .addPropertiesSupplier(() -> singletonMap("key", "value")) + .addPropertiesSupplier(() -> singletonMap("otel-key", "otel-value")) + .addPropertiesSupplier(() -> singletonMap("otel.service.name", "test-service")) .build(); - assertThat(autoConfigured.getResource().getAttribute(ResourceAttributes.SERVICE_NAME)) + assertThat(autoConfigured.getResource().getAttribute(stringKey("service.name"))) .isEqualTo("test-service"); assertThat(autoConfigured.getConfig().getString("key")).isEqualTo("value"); assertThat(autoConfigured.getConfig().getString("otel.key")).isEqualTo("otel-value"); } + @Test + void builder_addPropertiesCustomizer() { + AutoConfiguredOpenTelemetrySdk autoConfigured = + builder + .addPropertiesSupplier(() -> singletonMap("some-key", "defaultValue")) + .addPropertiesSupplier(() -> singletonMap("otel.service.name", "default-service-name")) + .addPropertiesCustomizer(config -> { + Map overrides = new HashMap<>(); + overrides.put("some-key", "override"); + overrides.put( + "otel.service.name", + config.getString("otel.service.name", "").replace("default", "overridden")); + return overrides; + }) + .addPropertiesCustomizer( + config -> singletonMap("some-key", config.getString("some-key", "") + "-2")) + .build(); + + assertThat(autoConfigured.getResource().getAttribute(stringKey("service.name"))) + .isEqualTo("overridden-service-name"); + assertThat(autoConfigured.getConfig().getString("some-key")).isEqualTo("override-2"); + assertThat(autoConfigured.getConfig().getString("some.key")).isEqualTo("override-2"); + } + + @Test + void builder_setConfigPropertiesCustomizer() { + AutoConfiguredOpenTelemetrySdk autoConfigured = + AutoConfigureUtil.setConfigPropertiesCustomizer( + builder.addPropertiesCustomizer(config -> singletonMap("some-key", "defaultValue")), + config -> { + assertThat(config.getString("some-key")).isEqualTo("defaultValue"); + + Map map = new HashMap<>(singletonMap("some-key", "override")); + map.putAll(disableExportPropertySupplier().get()); + return DefaultConfigProperties.createFromMap(map); + }) + .build(); + + assertThat(autoConfigured.getConfig().getString("some.key")).isEqualTo("override"); + } + @Test void builder_addMeterProviderCustomizer() { Mockito.lenient().when(metricReader.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); when(metricReader.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); + when(metricReader.getDefaultAggregation(any())).thenCallRealMethod(); SdkMeterProvider sdkMeterProvider = builder - .addMeterProviderCustomizer( - (meterProviderBuilder, configProperties) -> - meterProviderBuilder.registerMetricReader(metricReader)) + .addMeterProviderCustomizer((meterProviderBuilder, configProperties) -> + meterProviderBuilder.registerMetricReader(metricReader)) .build() .getOpenTelemetrySdk() .getSdkMeterProvider(); @@ -227,44 +353,109 @@ void builder_addMeterProviderCustomizer() { verify(metricReader).forceFlush(); } - // TODO: add test for addMetricExporterCustomizer once OTLP export is enabled by default - @Test - void builder_addLogEmitterProviderCustomizer() { - Mockito.lenient().when(logProcessor.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - when(logProcessor.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); + void builder_addLoggerProviderCustomizer() { + Mockito.lenient() + .when(logRecordProcessor.shutdown()) + .thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordProcessor.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); - SdkLogEmitterProvider sdkLogEmitterProvider = + SdkLoggerProvider sdkLoggerProvider = builder - .addLogEmitterProviderCustomizer( - (logEmitterProviderBuilder, configProperties) -> - logEmitterProviderBuilder.addLogProcessor(logProcessor)) + .addLoggerProviderCustomizer((loggerProviderBuilder, configProperties) -> + loggerProviderBuilder.addLogRecordProcessor(logRecordProcessor)) .build() .getOpenTelemetrySdk() - .getSdkLogEmitterProvider(); - sdkLogEmitterProvider.forceFlush().join(10, TimeUnit.SECONDS); + .getSdkLoggerProvider(); + sdkLoggerProvider.forceFlush().join(10, TimeUnit.SECONDS); - verify(logProcessor).forceFlush(); + verify(logRecordProcessor).forceFlush(); } - // TODO: add test for addLogExporterCustomizer once OTLP export is enabled by default - @Test void builder_setResultAsGlobalFalse() { GlobalOpenTelemetry.set(OpenTelemetry.noop()); - OpenTelemetry openTelemetry = builder.setResultAsGlobal(false).build().getOpenTelemetrySdk(); + OpenTelemetrySdk openTelemetry = builder.build().getOpenTelemetrySdk(); assertThat(GlobalOpenTelemetry.get()).extracting("delegate").isNotSameAs(openTelemetry); } @Test void builder_setResultAsGlobalTrue() { - OpenTelemetrySdk openTelemetry = builder.setResultAsGlobal(true).build().getOpenTelemetrySdk(); + OpenTelemetrySdk openTelemetry = builder.setResultAsGlobal().build().getOpenTelemetrySdk(); assertThat(GlobalOpenTelemetry.get()).extracting("delegate").isSameAs(openTelemetry); } + @Test + void builder_registersShutdownHook() { + builder = spy(builder); + Thread thread = new Thread(); + doReturn(thread).when(builder).shutdownHook(any()); + + OpenTelemetrySdk sdk = builder.build().getOpenTelemetrySdk(); + + verify(builder, times(1)).shutdownHook(sdk); + assertThat(Runtime.getRuntime().removeShutdownHook(thread)).isTrue(); + } + + @Test + void builder_customizes() { + builder = spy(builder); + OpenTelemetrySdk sdk = builder.build().getOpenTelemetrySdk(); + assertThat(sdk).isNotNull(); + verify(builder, times(1)).mergeSdkTracerProviderConfigurer(); + } + + @Test + void builder_shutdownHook() throws InterruptedException { + OpenTelemetrySdk sdk = mock(OpenTelemetrySdk.class); + + Thread thread = builder.shutdownHook(sdk); + thread.start(); + thread.join(); + + verify(sdk).close(); + } + + @Test + void builder_CallAutoConfigureListeners() { + builder = spy(builder); + + assertThatCode(() -> builder.build()).doesNotThrowAnyException(); + + verify(builder, times(1)).callAutoConfigureListeners(any(), any()); + } + + @Test + void builder_callAutoConfigureListeners() { + AutoConfigureListener listener = mock(AutoConfigureListener.class); + SpiHelper spiHelper = mock(SpiHelper.class); + when(spiHelper.getListeners()).thenReturn(Collections.singleton(listener)); + OpenTelemetrySdk sdk = mock(OpenTelemetrySdk.class); + + builder.callAutoConfigureListeners(spiHelper, sdk); + + verify(listener).afterAutoConfigure(sdk); + } + + @Test + void builder_catchesException() throws InterruptedException { + OpenTelemetrySdk sdk = mock(OpenTelemetrySdk.class); + doThrow(NoClassDefFoundError.class).when(sdk).close(); + + try { + Thread thread = builder.shutdownHook(sdk); + thread.start(); + thread.join(); + } catch (NoClassDefFoundError e) { + fail("shutdownHook threw unexpected NoClassDefFoundError", e); + } + + verify(sdk).close(); + } + private static Supplier> disableExportPropertySupplier() { Map props = new HashMap<>(); props.put("otel.metrics.exporter", "none"); @@ -273,25 +464,78 @@ private static Supplier> disableExportPropertySupplier() { return () -> props; } + @Test + void disableSdk() { + BiFunction + traceCustomizer = getTracerProviderBuilderSpy(); + BiFunction + metricCustomizer = getMeterProviderBuilderSpy(); + BiFunction logCustomizer = + getLoggerProviderBuilderSpy(); + + AutoConfiguredOpenTelemetrySdk autoConfiguredSdk = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .build(); + + assertThat(autoConfiguredSdk.getOpenTelemetrySdk()).isInstanceOf(OpenTelemetrySdk.class); + + // When the SDK is disabled, configuration is skipped and none of the customizers are called + verify(traceCustomizer, never()).apply(any(), any()); + verify(metricCustomizer, never()).apply(any(), any()); + verify(logCustomizer, never()).apply(any(), any()); + } + + @Test + void disableSdk_PropagatorCustomizer() { + Context extracted = Context.root().with(ContextKey.named("animal"), "bear"); + + when(propagator2.extract(any(), any(), any())).thenReturn(extracted); + + AutoConfiguredOpenTelemetrySdk autoConfiguredSdk = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) + .addPropertiesSupplier(() -> singletonMap("otel.propagators", "tracecontext")) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(W3CTraceContextPropagator.getInstance()); + return propagator1; + }) + .addPropagatorCustomizer((previous, config) -> { + assertThat(previous).isSameAs(propagator1); + return propagator2; + }) + .build(); + + // When the SDK is disabled, propagators are still configured + assertThat(autoConfiguredSdk.getOpenTelemetrySdk().getPropagators()).isNotNull(); + Consumer propagatorConsumer = + propagator -> { + assertThat(propagator.extract(Context.root(), Collections.emptyMap(), getter)) + .isEqualTo(extracted); + }; + assertThat(autoConfiguredSdk.getOpenTelemetrySdk().getPropagators().getTextMapPropagator()) + .isInstanceOfSatisfying(TextMapPropagator.class, propagatorConsumer); + } + @Test void tracerProviderCustomizer() { InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); AutoConfiguredOpenTelemetrySdkBuilder autoConfiguration = AutoConfiguredOpenTelemetrySdk.builder() - .addTracerProviderCustomizer( - (tracerProviderBuilder, config) -> { - tracerProviderBuilder.setResource(Resource.builder().put("cat", "meow").build()); - return tracerProviderBuilder.addSpanProcessor( - SimpleSpanProcessor.create(spanExporter)); - }) + .addTracerProviderCustomizer((tracerProviderBuilder, config) -> { + tracerProviderBuilder.setResource(Resource.builder().put("cat", "meow").build()); + return tracerProviderBuilder.addSpanProcessor( + SimpleSpanProcessor.create(spanExporter)); + }) .addResourceCustomizer( (resource, config) -> resource.merge(Resource.builder().put("cow", "moo").build())) - .addPropertiesSupplier(() -> Collections.singletonMap("otel.metrics.exporter", "none")) - .addPropertiesSupplier(() -> Collections.singletonMap("otel.traces.exporter", "none")) - .addPropertiesSupplier(() -> Collections.singletonMap("otel.logs.exporter", "none")) - .setResultAsGlobal(false); + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")); - GlobalOpenTelemetry.set(OpenTelemetry.noop()); AutoConfiguredOpenTelemetrySdk autoConfigured = autoConfiguration.build(); assertThat(autoConfigured.getResource().getAttribute(stringKey("cow"))).isEqualTo("moo"); @@ -303,6 +547,210 @@ void tracerProviderCustomizer() { assertThat(spanData.getResource().getAttribute(stringKey("cat"))).isEqualTo("meow"); // Ensures the export happened. - sdk.getSdkTracerProvider().shutdown().join(10, TimeUnit.SECONDS); + sdk.shutdown().join(10, TimeUnit.SECONDS); + } + + @Test + void testNonStringProperties() { + Properties properties = System.getProperties(); + + properties.putIfAbsent("my-key", 7); + properties.putIfAbsent(7.39, "my-value"); + properties.putIfAbsent(new BigDecimal("7.397"), new BigInteger("7")); + + AutoConfiguredOpenTelemetrySdk autoConfigured = builder.build(); + + assertThat(autoConfigured) + .extracting("config") + .isInstanceOfSatisfying( + ConfigProperties.class, + config -> { + String value1 = config.getString("my.key"); + assertThat(value1).isEqualTo("7"); + String value2 = config.getString("7.39"); + assertThat(value2).isEqualTo("my-value"); + String value3 = config.getString("7.397"); + assertThat(value3).isEqualTo("7"); + }); + } + + @Test + @SuppressLogger(AutoConfiguredOpenTelemetrySdkBuilder.class) + void configurationError_propagators() { + BiFunction + traceCustomizer = getTracerProviderBuilderSpy(); + BiFunction + metricCustomizer = getMeterProviderBuilderSpy(); + BiFunction logCustomizer = + getLoggerProviderBuilderSpy(); + + assertThatThrownBy(() -> + // Override the provider builders with mocks which we can verify are closed + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.propagators", "foo")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) + .build()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized value for otel.propagators"); + + // When the SDK is disabled and propagators are mis-configured, none of the customizers are + // called + verify(traceCustomizer, never()).apply(any(), any()); + verify(metricCustomizer, never()).apply(any(), any()); + verify(logCustomizer, never()).apply(any(), any()); + + assertThatThrownBy(() -> + // Override the provider builders with mocks which we can verify are closed + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.propagators", "foo")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) + .build()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized value for otel.propagators"); + + // When the SDK is enabled and propagators are mis-configured, none of the customizers are + // called + verify(traceCustomizer, never()).apply(any(), any()); + verify(metricCustomizer, never()).apply(any(), any()); + verify(logCustomizer, never()).apply(any(), any()); + } + + @Test + @SuppressLogger(AutoConfiguredOpenTelemetrySdkBuilder.class) + void configurationError_runtime() { + BiFunction + traceCustomizer = getTracerProviderBuilderSpy(); + BiFunction + metricCustomizer = getMeterProviderBuilderSpy(); + BiFunction logCustomizer = + getLoggerProviderBuilderSpy(); + + doThrow(new RuntimeException()).when(traceCustomizer).apply(any(), any()); + + assertThatThrownBy(() -> + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer(traceCustomizer) + .addMeterProviderCustomizer(metricCustomizer) + .addLoggerProviderCustomizer(logCustomizer) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) + .build()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unexpected configuration error"); + } + + @Test + @SuppressLogger(AutoConfiguredOpenTelemetrySdkBuilder.class) + void configurationError_ClosesResources() { + // AutoConfiguredOpenTelemetrySdk should close partially configured resources if an exception + // short circuits configuration. Verify that SdkTracerProvider, SdkMeterProvider, and + // SdkLoggerProvider + // are closed when configuration fails late due to an invalid propagator. + SdkTracerProvider tracerProvider = mock(SdkTracerProvider.class); + SdkMeterProvider meterProvider = mock(SdkMeterProvider.class); + SdkLoggerProvider loggerProvider = mock(SdkLoggerProvider.class); + SdkTracerProviderBuilder tracerProviderBuilder = mock(SdkTracerProviderBuilder.class); + SdkMeterProviderBuilder meterProviderBuilder = mock(SdkMeterProviderBuilder.class); + SdkLoggerProviderBuilder loggerProviderBuilder = mock(SdkLoggerProviderBuilder.class); + when(tracerProviderBuilder.build()).thenReturn(tracerProvider); + when(meterProviderBuilder.build()).thenReturn(meterProvider); + when(loggerProviderBuilder.build()).thenReturn(loggerProvider); + + // Throw an error when closing and verify other resources are still closed + doThrow(new IOException("Error!")).when(tracerProvider).close(); + + assertThatThrownBy(() -> + // Override the provider builders with mocks which we can verify are closed + AutoConfiguredOpenTelemetrySdk.builder() + .addTracerProviderCustomizer((u1, u2) -> tracerProviderBuilder) + .addMeterProviderCustomizer((u1, u2) -> meterProviderBuilder) + .addLoggerProviderCustomizer((u1, u2) -> loggerProviderBuilder) + .addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.traces.exporter", "none")) + .addPropertiesSupplier(() -> singletonMap("otel.logs.exporter", "foo")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "false")) + .build()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized value for otel.logs.exporter: foo"); + + verify(tracerProvider).close(); + verify(meterProvider).close(); + + logs.assertContains("Error closing io.opentelemetry.sdk.trace.SdkTracerProvider"); + } + + @Test + void globalOpenTelemetryLock() throws InterruptedException, ExecutionException, TimeoutException { + CountDownLatch autoconfigStarted = new CountDownLatch(1); + CountDownLatch completeAutoconfig = new CountDownLatch(1); + ExecutorService executorService = Executors.newFixedThreadPool(2); + + // Submit a future to autoconfigure the SDK and set the result as global. Add a customization + // hook which blocks until we say so. + CompletableFuture autoConfiguredOpenTelemetryFuture = + CompletableFuture.supplyAsync( + () -> + builder + .addLoggerProviderCustomizer((sdkLoggerProviderBuilder, configProperties) -> { + autoconfigStarted.countDown(); + try { + completeAutoconfig.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return sdkLoggerProviderBuilder; + }) + .setResultAsGlobal() + .build() + .getOpenTelemetrySdk(), + executorService); + + // Wait for autoconfiguration to enter our callback, then try to get an instance of + // GlobalOpenTelemetry. GlobalOpenTelemetry.get() should block until we release the + // completeAutoconfig latch and allow autoconfiguration to complete. + autoconfigStarted.await(); + CompletableFuture globalOpenTelemetryFuture = + CompletableFuture.supplyAsync(GlobalOpenTelemetry::get, executorService); + Thread.sleep(10); + assertThat(globalOpenTelemetryFuture.isDone()).isFalse(); + assertThat(autoConfiguredOpenTelemetryFuture.isDone()).isFalse(); + + // Release the latch, allowing autoconfiguration to complete. Confirm that our + // GlobalOpenTelemetry.get() future resolved to the same instance as autoconfiguration. + completeAutoconfig.countDown(); + assertThat(unobfuscate(globalOpenTelemetryFuture.get(10, TimeUnit.SECONDS))) + .isSameAs(autoConfiguredOpenTelemetryFuture.get(10, TimeUnit.SECONDS)); + + // Cleanup + executorService.shutdown(); + autoConfiguredOpenTelemetryFuture.get().shutdown().join(10, TimeUnit.SECONDS); + GlobalOpenTelemetry.resetForTest(); + } + + private static OpenTelemetry unobfuscate(OpenTelemetry openTelemetry) { + try { + Field delegateField = + Class.forName("io.opentelemetry.api.GlobalOpenTelemetry$ObfuscatedOpenTelemetry") + .getDeclaredField("delegate"); + delegateField.setAccessible(true); + Object delegate = delegateField.get(openTelemetry); + return (OpenTelemetry) delegate; + } catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) { + throw new IllegalStateException("Error unobfuscating OpenTelemetry", e); + } } } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ConfigPropertiesTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ConfigPropertiesTest.java deleted file mode 100644 index 589e8190be7..00000000000 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ConfigPropertiesTest.java +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.entry; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import java.time.Duration; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.Test; - -class ConfigPropertiesTest { - - @Test - void allValid() { - Map properties = new HashMap<>(); - properties.put("string", "str"); - properties.put("int", "10"); - properties.put("long", "20"); - properties.put("double", "5.4"); - properties.put("list", "cat,dog,bear"); - properties.put("map", "cat=meow,dog=bark,bear=growl"); - properties.put("duration", "1s"); - - ConfigProperties config = DefaultConfigProperties.createForTest(properties); - assertThat(config.getString("string")).isEqualTo("str"); - assertThat(config.getInt("int")).isEqualTo(10); - assertThat(config.getLong("long")).isEqualTo(20); - assertThat(config.getDouble("double")).isEqualTo(5.4); - assertThat(config.getList("list")).containsExactly("cat", "dog", "bear"); - assertThat(config.getMap("map")) - .containsExactly(entry("cat", "meow"), entry("dog", "bark"), entry("bear", "growl")); - assertThat(config.getDuration("duration")).isEqualTo(Duration.ofSeconds(1)); - } - - @Test - void allMissing() { - ConfigProperties config = DefaultConfigProperties.createForTest(Collections.emptyMap()); - assertThat(config.getString("string")).isNull(); - assertThat(config.getInt("int")).isNull(); - assertThat(config.getLong("long")).isNull(); - assertThat(config.getDouble("double")).isNull(); - assertThat(config.getList("list")).isEmpty(); - assertThat(config.getMap("map")).isEmpty(); - assertThat(config.getDuration("duration")).isNull(); - } - - @Test - void allEmpty() { - Map properties = new HashMap<>(); - properties.put("string", ""); - properties.put("int", ""); - properties.put("long", ""); - properties.put("double", ""); - properties.put("list", ""); - properties.put("map", ""); - properties.put("duration", ""); - - ConfigProperties config = DefaultConfigProperties.createForTest(properties); - assertThat(config.getString("string")).isEmpty(); - assertThat(config.getInt("int")).isNull(); - assertThat(config.getLong("long")).isNull(); - assertThat(config.getDouble("double")).isNull(); - assertThat(config.getList("list")).isEmpty(); - assertThat(config.getMap("map")).isEmpty(); - assertThat(config.getDuration("duration")).isNull(); - } - - @Test - void invalidInt() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("int", "bar")) - .getInt("int")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid value for property int=bar. Must be a integer."); - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest( - Collections.singletonMap("int", "999999999999999")) - .getInt("int")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid value for property int=999999999999999. Must be a integer."); - } - - @Test - void invalidLong() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("long", "bar")) - .getLong("long")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid value for property long=bar. Must be a long."); - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest( - Collections.singletonMap("long", "99223372036854775807")) - .getLong("long")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid value for property long=99223372036854775807. Must be a long."); - } - - @Test - void invalidDouble() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("double", "bar")) - .getDouble("double")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid value for property double=bar. Must be a double."); - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("double", "1.0.1")) - .getDouble("double")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid value for property double=1.0.1. Must be a double."); - } - - @Test - void uncleanList() { - assertThat( - DefaultConfigProperties.createForTest( - Collections.singletonMap("list", " a ,b,c , d,, ,")) - .getList("list")) - .containsExactly("a", "b", "c", "d"); - } - - @Test - void uncleanMap() { - assertThat( - DefaultConfigProperties.createForTest( - Collections.singletonMap("map", " a=1 ,b=2,c = 3 , d= 4,, ,")) - .getMap("map")) - .containsExactly(entry("a", "1"), entry("b", "2"), entry("c", "3"), entry("d", "4")); - } - - @Test - void invalidMap() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("map", "a=1,b=")) - .getMap("map")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid map property: map=a=1,b="); - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("map", "a=1,b")) - .getMap("map")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid map property: map=a=1,b"); - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("map", "a=1,=b")) - .getMap("map")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid map property: map=a=1,=b"); - } - - @Test - void invalidDuration() { - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "1a1ms")) - .getDuration("duration")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid duration property duration=1a1ms. Expected number, found: 1a1"); - assertThatThrownBy( - () -> - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "9mm")) - .getDuration("duration")) - .isInstanceOf(ConfigurationException.class) - .hasMessage("Invalid duration property duration=9mm. Invalid duration string, found: mm"); - } - - @Test - void durationUnitParsing() { - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "1")) - .getDuration("duration")) - .isEqualTo(Duration.ofMillis(1)); - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "2ms")) - .getDuration("duration")) - .isEqualTo(Duration.ofMillis(2)); - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "3s")) - .getDuration("duration")) - .isEqualTo(Duration.ofSeconds(3)); - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "4m")) - .getDuration("duration")) - .isEqualTo(Duration.ofMinutes(4)); - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "5h")) - .getDuration("duration")) - .isEqualTo(Duration.ofHours(5)); - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "6d")) - .getDuration("duration")) - .isEqualTo(Duration.ofDays(6)); - // Check Space handling - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "7 ms")) - .getDuration("duration")) - .isEqualTo(Duration.ofMillis(7)); - assertThat( - DefaultConfigProperties.createForTest(Collections.singletonMap("duration", "8 ms")) - .getDuration("duration")) - .isEqualTo(Duration.ofMillis(8)); - } -} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java new file mode 100644 index 00000000000..6345d6cba9c --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; + +class DeclarativeConfigurationTest { + + @RegisterExtension + LogCapturer logs = + LogCapturer.create().captureForType(AutoConfiguredOpenTelemetrySdkBuilder.class); + + @Test + void configFile(@TempDir Path tempDir) throws IOException { + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: test\n" + + "tracer_provider:\n" + + " processors:\n" + + " - simple:\n" + + " exporter:\n" + + " console: {}\n"; + Path path = tempDir.resolve("otel-config.yaml"); + Files.write(path, yaml.getBytes(StandardCharsets.UTF_8)); + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", path.toString())); + + assertThatThrownBy(() -> AutoConfiguredOpenTelemetrySdk.builder().setConfig(config).build()) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "Cannot autoconfigure from config file without opentelemetry-sdk-extension-declarative-config on the classpath"); + } + + @Test + void noLogMessages_whenBuildingWithDefaults() { + Map props = new HashMap<>(); + props.put("otel.metrics.exporter", "none"); + props.put("otel.traces.exporter", "none"); + props.put("otel.logs.exporter", "none"); + AutoConfiguredOpenTelemetrySdk sdk = + AutoConfiguredOpenTelemetrySdk.builder().addPropertiesSupplier(() -> props).build(); + sdk.getOpenTelemetrySdk().shutdown(); + + assertThat(logs.getEvents()).isEmpty(); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResourceTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResourceTest.java new file mode 100644 index 00000000000..30b08d24546 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResourceTest.java @@ -0,0 +1,232 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.slf4j.event.Level.WARN; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@SuppressLogger(loggerName = "io.opentelemetry.sdk.autoconfigure.EnvironmentResource$EntityParser") +@SuppressLogger(ResourceBuilder.class) +class EnvironmentResourceTest { + + @RegisterExtension + LogCapturer logs = + LogCapturer.create() + .captureForLogger(EnvironmentResource.class.getName() + "$EntityParser") + .captureForType(ResourceBuilder.class); + + private static Resource parse(String entities) { + return EnvironmentResource.createEnvironmentResource( + DefaultConfigProperties.createFromMap(Collections.singletonMap("otel.entities", entities))); + } + + @Test + void reservedCharactersAreDecodedInValues() { + Resource resource = parse("host{host.id=H1}[config=%7B%7D%5B%5D%40%3B%2C%3D,empty=]"); + Entity expected = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.builder().put("config", "{}[]@;,=").put("empty", "").build()) + .build(); + assertThat(EntityUtil.getEntities(resource)).containsExactly(expected); + } + + @Test + void percentDecodingFollowsBaggageRules() { + Resource resource = + parse( + "service{service.name=my+app,space=hello%20world,utf8=%C3%A9,invalid=%2G,incomplete=%2,end=%}"); + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder( + "service", + Attributes.builder() + .put("service.name", "my+app") + .put("space", "hello world") + .put("utf8", "Γ©") + .put("invalid", "%2G") + .put("incomplete", "%2") + .put("end", "%") + .build()) + .build()); + } + + @Test + void emptyDefinitionsAreIgnored() { + Resource resource = parse(";host{host.id=H1};;;"); + assertThat(EntityUtil.getEntities(resource)) + .containsExactly(Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build()); + } + + @Test + void emptyDescriptionIsAllowed() { + assertThat(EntityUtil.getEntities(parse("host{host.id=H1}[]"))) + .containsExactly(Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build()); + } + + @ParameterizedTest + @MethodSource("malformedDefinitions") + void malformedDefinitionDoesNotDiscardValidNeighbors(String malformed) { + Resource resource = parse("host{host.id=H1};" + malformed + ";service{service.name=S1}"); + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(), + Entity.builder("service", Attributes.of(stringKey("service.name"), "S1")).build()); + logs.assertContains(event -> event.getLevel().equals(WARN), "Malformed entity definition"); + } + + @ParameterizedTest + @MethodSource("incompleteDefinitions") + void incompleteDefinitionAtEndOfInput(String incomplete) { + assertThat(parse(incomplete)).isEqualTo(Resource.empty()); + logs.assertContains( + event -> event.getLevel().equals(WARN), + "Malformed entity definition (incomplete definition)"); + } + + static Stream incompleteDefinitions() { + return Stream.of( + Arguments.argumentSet("type only", "test"), + Arguments.argumentSet("dangling identity key", "test{id"), + Arguments.argumentSet("missing closing brace", "test{id=1"), + Arguments.argumentSet("unclosed description", "test{id=1}[name=broken")); + } + + static Stream malformedDefinitions() { + return Stream.of( + Arguments.argumentSet("empty type", "{id=1}"), + Arguments.argumentSet("missing identity", "test{}"), + Arguments.argumentSet("description before identity", "test[name=broken]{id=1}"), + Arguments.argumentSet("missing opening brace", "testid=1}"), + Arguments.argumentSet("missing closing brace", "test{id=1"), + Arguments.argumentSet("unclosed description", "test{id=1}[name=broken"), + Arguments.argumentSet("extra identity block", "test{id=1}{id=2}"), + Arguments.argumentSet("extra description block", "test{id=1}[name=1][name=2]"), + Arguments.argumentSet("trailing garbage", "test{id=1}garbage"), + Arguments.argumentSet("missing equals", "test{id}"), + Arguments.argumentSet("dangling identity key", "test{id=1,dangling}"), + Arguments.argumentSet("dangling description key", "test{id=1}[name=1,dangling]"), + Arguments.argumentSet("empty key", "test{=1}"), + Arguments.argumentSet("trailing comma", "test{id=1,}"), + Arguments.argumentSet( + "overlapping identifying/descriptive attribute keys", "test{id=1}[id=2]"), + Arguments.argumentSet("type starts with digit", "1test{id=1}"), + Arguments.argumentSet("invalid type character", "test/type{id=1}"), + Arguments.argumentSet("non-ASCII type", "tΓ©st{id=1}"), + Arguments.argumentSet("invalid key character", "test{invalid/key=1}"), + Arguments.argumentSet("key starts with digit", "test{1key=1}"), + Arguments.argumentSet("unencoded equals", "test{id=a=b}"), + Arguments.argumentSet("unencoded at", "test{id=a@b}"), + Arguments.argumentSet("unencoded bracket", "test{id=a[b}"), + Arguments.argumentSet( + "type too long", String.join("", Collections.nCopies(256, "t")) + "{id=1}"), + Arguments.argumentSet( + "key too long", "test{" + String.join("", Collections.nCopies(256, "k")) + "=1}")); + } + + @ParameterizedTest + @MethodSource("schemaUrls") + void schemaUrlValidation(String input, @Nullable String expected) { + Resource resource = parse("host{host.id=H1}@" + input); + assertThat(EntityUtil.getEntities(resource)).hasSize(1); + assertThat(EntityUtil.getEntities(resource).iterator().next().getSchemaUrl()) + .isEqualTo(expected); + if (expected == null) { + logs.assertContains( + event -> event.getLevel().equals(WARN), "Ignoring invalid entity schema URL"); + } + } + + static Stream schemaUrls() { + return Stream.of( + Arguments.argumentSet( + "absolute URL", "https://example.com/schema", "https://example.com/schema"), + Arguments.argumentSet( + "URL delimiters stay in the schema", + "https://[::1]/schema?a=b,c@d", + "https://[::1]/schema?a=b,c@d"), + Arguments.argumentSet( + "encoded URL retained", + "https://example.com/schema%20version", + "https://example.com/schema%20version"), + Arguments.argumentSet("URN", "urn:example:schema", "urn:example:schema"), + Arguments.argumentSet("relative URL ignored", "invalid-url", null), + Arguments.argumentSet("invalid host ignored", "http://[", null), + Arguments.argumentSet("space ignored", "http://bad host", null), + Arguments.argumentSet("invalid percent escape ignored", "https://example.com/%ZZ", null), + Arguments.argumentSet("empty URL ignored", "", null)); + } + + @ParameterizedTest + @MethodSource("duplicateEntities") + void duplicateEntityUsesOnlyLastDefinition(String input, Entity expected) { + Resource resource = parse(input); + assertThat(EntityUtil.getEntities(resource)).containsExactly(expected); + assertThat(resource.getAttributes()) + .isEqualTo( + Attributes.builder() + .putAll(expected.getId()) + .putAll(expected.getDescription()) + .build()); + logs.assertContains(event -> event.getLevel().equals(WARN), "Duplicate entity type [host]"); + } + + static Stream duplicateEntities() { + return Stream.of( + Arguments.argumentSet( + "identical identity", + "host{host.id=H1}[host.name=old,host.type=discarded];host{host.id=H1}[host.name=new]", + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "new")) + .build()), + Arguments.argumentSet( + "different identity", + "host{host.id=H1}[host.name=discarded];host{host.id=H2}", + Entity.builder("host", Attributes.of(stringKey("host.id"), "H2")).build())); + } + + @Test + void conflictingTypesPreserveNonConflictingAttributes() { + Resource resource = parse("process{process.pid=1}[env=dev];host{host.id=H1}[env=prod]"); + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("env"), "prod")) + .build()); + assertThat(EntityUtil.getUnassociatedAttributes(resource)) + .isEqualTo(Attributes.of(stringKey("process.pid"), "1")); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Removing entity association [process]"); + } + + @Test + void repeatedSameTypePreservesLastOccurrenceOrder() { + Resource resource = parse("host{host.id=H1};service{service.name=S1};host{host.id=H2}"); + assertThat(EntityUtil.getEntities(resource)) + .containsExactlyElementsOf( + Arrays.asList( + Entity.builder("service", Attributes.of(stringKey("service.name"), "S1")).build(), + Entity.builder("host", Attributes.of(stringKey("host.id"), "H2")).build())); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfigurationTest.java deleted file mode 100644 index 784ae7bf48e..00000000000 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfigurationTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.as; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.logs.LogLimits; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; -import io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder; -import io.opentelemetry.sdk.trace.SpanLimits; -import java.util.Collections; -import java.util.Map; -import java.util.function.Supplier; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.jupiter.api.Test; - -class LogEmitterProviderConfigurationTest { - - private static final ConfigProperties EMPTY = - DefaultConfigProperties.createForTest(Collections.emptyMap()); - - @Test - void configureLogEmitterProvider() { - Map properties = - ImmutableMap.of( - "otel.logs.exporter", "none", - "otel.attribute.count.limit", "5"); - - // We don't have any exporters on classpath for this test so check no-op case. Exporter cases - // are verified in other test sets like testFullConfig. - SdkLogEmitterProviderBuilder builder = SdkLogEmitterProvider.builder(); - LogEmitterProviderConfiguration.configureLogEmitterProvider( - builder, - DefaultConfigProperties.createForTest(properties), - MeterProvider.noop(), - (a, unused) -> a); - SdkLogEmitterProvider logEmitterProvider = builder.build(); - - try { - assertThat(logEmitterProvider) - .extracting("sharedState") - .satisfies( - sharedState -> { - assertThat(sharedState) - .extracting("logProcessor") - .isEqualTo(LogProcessor.composite()); - assertThat(sharedState) - .extracting( - "logLimitsSupplier", as(InstanceOfAssertFactories.type(Supplier.class))) - .extracting(supplier -> (LogLimits) supplier.get()) - .isEqualTo(LogLimits.builder().setMaxNumberOfAttributes(5).build()); - }); - } finally { - logEmitterProvider.shutdown(); - } - } - - @Test - void configureSpanLimits() { - assertThat(LogEmitterProviderConfiguration.configureLogLimits(EMPTY)) - .isEqualTo(LogLimits.getDefault()); - - SpanLimits config = - TracerProviderConfiguration.configureSpanLimits( - DefaultConfigProperties.createForTest( - ImmutableMap.of( - "otel.attribute.value.length.limit", "100", - "otel.attribute.count.limit", "5"))); - assertThat(config.getMaxAttributeValueLength()).isEqualTo(100); - assertThat(config.getMaxNumberOfAttributes()).isEqualTo(5); - } -} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogExporterConfigurationTest.java deleted file mode 100644 index a8e9ed92c9b..00000000000 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogExporterConfigurationTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import org.junit.jupiter.api.Test; - -class LogExporterConfigurationTest { - - @Test - void configureLogExporters_duplicates() { - ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("otel.logs.exporter", "otlp,otlp")); - - assertThatThrownBy( - () -> - LogExporterConfiguration.configureLogExporters( - config, MeterProvider.noop(), (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("otel.logs.exporter contains duplicates: [otlp]"); - } - - @Test - void configureLogExporters_unrecognized() { - ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("otel.logs.exporter", "foo")); - - assertThatThrownBy( - () -> - LogExporterConfiguration.configureLogExporters( - config, MeterProvider.noop(), (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Unrecognized value for otel.logs.exporter: foo"); - } - - @Test - void configureLogExporters_multipleWithNone() { - ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("otel.logs.exporter", "otlp,none")); - - assertThatThrownBy( - () -> - LogExporterConfiguration.configureLogExporters( - config, MeterProvider.noop(), (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("otel.logs.exporter contains none along with other exporters"); - } - - @Test - void configureOtlpLogs_unsupportedProtocol() { - assertThatThrownBy( - () -> - LogExporterConfiguration.configureOtlpLogs( - DefaultConfigProperties.createForTest( - ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), - MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Unsupported OTLP logs protocol: foo"); - } -} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java new file mode 100644 index 00000000000..cbdc3dfdc94 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.autoconfigure.LogRecordExporterConfiguration.configureExporter; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class LogRecordExporterConfigurationTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final SpiHelper spiHelper = + SpiHelper.create(LogRecordExporterConfigurationTest.class.getClassLoader()); + + @Test + void configureExporter_KnownSpiExportersNotOnClasspath() { + NamedSpiManager spiExportersManager = + LogRecordExporterConfiguration.logRecordExporterSpiManager( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), spiHelper); + + assertThatThrownBy(() -> configureExporter("logging", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.logs.exporter set to \"logging\" but opentelemetry-exporter-logging" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("logging-otlp", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.logs.exporter set to \"logging-otlp\" but opentelemetry-exporter-logging-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("experimental-otlp/stdout", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.logs.exporter set to \"experimental-otlp/stdout\" but opentelemetry-exporter-logging-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("otlp", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.logs.exporter set to \"otlp\" but opentelemetry-exporter-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + + // Unrecognized exporter + assertThatThrownBy(() -> configureExporter("foo", spiExportersManager)) + .hasMessage("Unrecognized value for otel.logs.exporter: foo"); + } + + @Test + void configureLogRecordExporters_duplicates() { + List closeables = new ArrayList<>(); + + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.logs.exporter", "otlp,otlp")), + spiHelper, + (a, unused) -> a, + closeables)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("otel.logs.exporter contains duplicates: [otlp]"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); + } + + @Test + void configureLogRecordExporters_unrecognized() { + List closeables = new ArrayList<>(); + + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + DefaultConfigProperties.createFromMap(ImmutableMap.of("otel.logs.exporter", "foo")), + spiHelper, + (a, unused) -> a, + new ArrayList<>())) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized value for otel.logs.exporter: foo"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); + } + + @Test + void configureLogRecordExporters_multipleWithNone() { + List closeables = new ArrayList<>(); + + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.logs.exporter", "otlp,none")), + spiHelper, + (a, unused) -> a, + closeables)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("otel.logs.exporter contains none along with other exporters"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java new file mode 100644 index 00000000000..b7c4f9c50bb --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class LoggerProviderConfigurationTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + @Test + void configureLoggerProvider() { + Map properties = + ImmutableMap.of( + "otel.logs.exporter", "none", + "otel.attribute.count.limit", "5"); + List closeables = new ArrayList<>(); + + // We don't have any exporters on classpath for this test so check no-op case. Exporter cases + // are verified in other test sets like testFullConfig. + SdkLoggerProviderBuilder builder = SdkLoggerProvider.builder(); + LoggerProviderConfiguration.configureLoggerProvider( + builder, + DefaultConfigProperties.createFromMap(properties), + SpiHelper.create(LoggerProviderConfiguration.class.getClassLoader()), + MeterProvider.noop(), + (a, unused) -> a, + (a, unused) -> a, + closeables); + cleanup.addCloseables(closeables); + + try (SdkLoggerProvider loggerProvider = builder.build()) { + assertThat(loggerProvider) + .extracting("sharedState") + .satisfies(sharedState -> { + assertThat(sharedState) + .extracting("logRecordProcessor") + .isEqualTo(LogRecordProcessor.composite()); + assertThat(sharedState) + .extracting("logLimitsSupplier", as(InstanceOfAssertFactories.type(Supplier.class))) + .extracting(supplier -> (LogLimits) supplier.get()) + .isEqualTo(LogLimits.builder().setMaxNumberOfAttributes(5).build()); + }); + assertThat(closeables).isEmpty(); + } + } + + @Test + void configureLogLimits() { + assertThat( + LoggerProviderConfiguration.configureLogLimits( + DefaultConfigProperties.createFromMap(Collections.emptyMap()))) + .isEqualTo(LogLimits.getDefault()); + + LogLimits config = + LoggerProviderConfiguration.configureLogLimits( + DefaultConfigProperties.createFromMap( + ImmutableMap.of( + "otel.attribute.value.length.limit", "100", + "otel.attribute.count.limit", "5"))); + assertThat(config.getMaxAttributeValueLength()).isEqualTo(100); + assertThat(config.getMaxNumberOfAttributes()).isEqualTo(5); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java new file mode 100644 index 00000000000..43f12ae6e0a --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.BDDAssertions.as; + +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.internal.exemplar.AlwaysOffExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.AlwaysOnExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; +import io.opentelemetry.sdk.metrics.internal.exemplar.TraceBasedExemplarFilter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.assertj.core.api.ObjectAssert; +import org.junit.jupiter.api.Test; + +class MeterProviderConfigurationTest { + + @Test + void configureMeterProvider_ConfiguresExemplarFilter() { + assertExemplarFilter(Collections.emptyMap()).isInstanceOf(TraceBasedExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "foo")) + .isInstanceOf(TraceBasedExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "trace_based")) + .isInstanceOf(TraceBasedExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "Trace_based")) + .isInstanceOf(TraceBasedExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "always_off")) + .isInstanceOf(AlwaysOffExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "always_Off")) + .isInstanceOf(AlwaysOffExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "always_on")) + .isInstanceOf(AlwaysOnExemplarFilter.class); + assertExemplarFilter(Collections.singletonMap("otel.metrics.exemplar.filter", "ALWAYS_ON")) + .isInstanceOf(AlwaysOnExemplarFilter.class); + } + + private static ObjectAssert assertExemplarFilter( + Map config) { + Map configWithDefault = new HashMap<>(config); + configWithDefault.put("otel.metrics.exporter", "none"); + SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); + MeterProviderConfiguration.configureMeterProvider( + builder, + DefaultConfigProperties.createFromMap(configWithDefault), + SpiHelper.create(MeterProviderConfigurationTest.class.getClassLoader()), + (a, b) -> a, + (a, b) -> a, + new ArrayList<>()); + return assertThat(builder) + .extracting( + "exemplarFilter", as(InstanceOfAssertFactories.type(ExemplarFilterInternal.class))); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java new file mode 100644 index 00000000000..4c47ab20d39 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java @@ -0,0 +1,85 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.autoconfigure.MetricExporterConfiguration.configureExporter; +import static io.opentelemetry.sdk.autoconfigure.MetricExporterConfiguration.configureMetricReader; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class MetricExporterConfigurationTest { + + private static final ConfigProperties EMPTY = + DefaultConfigProperties.createFromMap(Collections.emptyMap()); + + private final SpiHelper spiHelper = + SpiHelper.create(MetricExporterConfigurationTest.class.getClassLoader()); + + @Test + void configureExporter_UnknownExporter() { + NamedSpiManager spiExportersManager = + MetricExporterConfiguration.metricExporterSpiManager(EMPTY, spiHelper); + + assertThat(configureExporter("foo", spiExportersManager)).isNull(); + } + + @Test + void configureExporter_KnownSpiExportersNotOnClasspath() { + NamedSpiManager spiExportersManager = + MetricExporterConfiguration.metricExporterSpiManager(EMPTY, spiHelper); + + assertThatThrownBy(() -> configureExporter("logging", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.metrics.exporter set to \"logging\" but opentelemetry-exporter-logging" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("logging-otlp", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.metrics.exporter set to \"logging-otlp\" but opentelemetry-exporter-logging-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("experimental-otlp/stdout", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.metrics.exporter set to \"experimental-otlp/stdout\" but opentelemetry-exporter-logging-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("otlp", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.metrics.exporter set to \"otlp\" but opentelemetry-exporter-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + } + + @Test + void configureMetricReader_UnknownExporter() { + NamedSpiManager spiMetricReadersManager = + MetricExporterConfiguration.metricReadersSpiManager(EMPTY, spiHelper); + + assertThat(configureMetricReader("foo", spiMetricReadersManager)).isNull(); + } + + @Test + void configureMetricReader_KnownSpiExportersNotOnClasspath() { + NamedSpiManager spiMetricReadersManager = + MetricExporterConfiguration.metricReadersSpiManager(EMPTY, spiHelper); + + assertThatThrownBy(() -> configureMetricReader("prometheus", spiMetricReadersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.metrics.exporter set to \"prometheus\" but opentelemetry-exporter-prometheus" + + " not found on classpath. Make sure to add it as a dependency."); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/NotOnClasspathTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/NotOnClasspathTest.java deleted file mode 100644 index 233ce760b14..00000000000 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/NotOnClasspathTest.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import java.util.Collections; -import org.junit.jupiter.api.Test; - -class NotOnClasspathTest { - - private static final ConfigProperties EMPTY = - DefaultConfigProperties.createForTest(Collections.emptyMap()); - - @Test - void otlpGrpcSpans() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", EMPTY, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "OTLP gRPC Trace Exporter enabled but opentelemetry-exporter-otlp not found on " - + "classpath"); - } - - @Test - void otlpHttpSpans() { - ConfigProperties config = - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.exporter.otlp.protocol", "http/protobuf")); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", config, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "OTLP HTTP Trace Exporter enabled but opentelemetry-exporter-otlp-http-trace not found on " - + "classpath"); - } - - @Test - void jaeger() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "jaeger", EMPTY, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "Jaeger gRPC Exporter enabled but opentelemetry-exporter-jaeger not found on " - + "classpath"); - } - - @Test - void zipkin() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "zipkin", EMPTY, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "Zipkin Exporter enabled but opentelemetry-exporter-zipkin not found on classpath"); - } - - @Test - void loggingSpans() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "logging", EMPTY, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "Logging Trace Exporter enabled but opentelemetry-exporter-logging not found on " - + "classpath"); - } - - @Test - void loggingMetrics() { - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureExporter( - "logging", - EMPTY, - MetricExporterConfiguration.class.getClassLoader(), - (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "Logging Metrics Exporter enabled but opentelemetry-exporter-logging not found on " - + "classpath"); - } - - @Test - void loggingLogs() { - assertThatThrownBy( - () -> - LogExporterConfiguration.configureExporter("logging", EMPTY, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "Logging Log Exporter enabled but opentelemetry-exporter-logging not found on " - + "classpath"); - } - - @Test - void otlpGrpcMetrics() { - assertThatCode( - () -> - MetricExporterConfiguration.configureExporter( - "otlp", - EMPTY, - MetricExporterConfiguration.class.getClassLoader(), - (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "OTLP gRPC Metrics Exporter enabled but opentelemetry-exporter-otlp not found on " - + "classpath"); - } - - @Test - void otlpHttpMetrics() { - ConfigProperties config = - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.exporter.otlp.protocol", "http/protobuf")); - assertThatCode( - () -> - MetricExporterConfiguration.configureExporter( - "otlp", - config, - MetricExporterConfiguration.class.getClassLoader(), - (a, unused) -> a)) - .hasMessageContaining( - "OTLP HTTP Metrics Exporter enabled but opentelemetry-exporter-otlp-http-metrics not found on classpath"); - } - - @Test - void prometheus() { - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureExporter( - "prometheus", - EMPTY, - MetricExporterConfiguration.class.getClassLoader(), - (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining( - "Prometheus Metrics Server enabled but opentelemetry-exporter-prometheus not found on " - + "classpath"); - } - - @Test - void b3propagator() { - assertThatThrownBy( - () -> - PropagatorConfiguration.configurePropagators( - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.propagators", "b3")), - PropagatorConfiguration.class.getClassLoader(), - (a, config) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Unrecognized value for otel.propagators: b3"); - } - - @Test - void otlpGrpcLogs() { - assertThatCode( - () -> LogExporterConfiguration.configureExporter("otlp", EMPTY, MeterProvider.noop())) - .doesNotThrowAnyException(); - } - - @Test - void otlpHttpLogs() { - ConfigProperties config = - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.exporter.otlp.protocol", "http/protobuf")); - assertThatCode( - () -> LogExporterConfiguration.configureExporter("otlp", config, MeterProvider.noop())) - .doesNotThrowAnyException(); - } -} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java index 74aca205711..b5afae9845d 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/PropagatorConfigurationTest.java @@ -6,22 +6,65 @@ package io.opentelemetry.sdk.autoconfigure; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import java.util.Collections; import org.junit.jupiter.api.Test; class PropagatorConfigurationTest { + private final SpiHelper spiHelper = + SpiHelper.create(PropagatorConfigurationTest.class.getClassLoader()); + @Test void defaultPropagators() { ContextPropagators contextPropagators = PropagatorConfiguration.configurePropagators( - DefaultConfigProperties.createForTest(Collections.emptyMap()), - PropagatorConfiguration.class.getClassLoader(), + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + spiHelper, (a, unused) -> a); assertThat(contextPropagators.getTextMapPropagator().fields()) .containsExactlyInAnyOrder("traceparent", "tracestate", "baggage"); } + + @Test + void configurePropagators_none() { + ContextPropagators contextPropagators = + PropagatorConfiguration.configurePropagators( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.propagators", "none")), + spiHelper, + (a, unused) -> a); + + assertThat(contextPropagators.getTextMapPropagator().fields()).isEmpty(); + } + + @Test + void configurePropagators_none_withOthers() { + assertThatThrownBy(() -> + PropagatorConfiguration.configurePropagators( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.propagators", "none,blather")), + spiHelper, + (a, unused) -> a)) + .isInstanceOf(ConfigurationException.class) + .hasMessage("otel.propagators contains 'none' along with other propagators"); + } + + @Test + void configurePropagators_NotOnClasspath() { + assertThatThrownBy(() -> + PropagatorConfiguration.configurePropagators( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.propagators", "b3")), + spiHelper, + (a, config) -> a)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unrecognized value for otel.propagators: b3"); + } } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationFuzzTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationFuzzTest.java new file mode 100644 index 00000000000..5fd36956189 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationFuzzTest.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static java.util.Collections.singletonMap; + +import edu.berkeley.cs.jqf.fuzz.Fuzz; +import edu.berkeley.cs.jqf.fuzz.JQF; +import edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing; +import edu.berkeley.cs.jqf.fuzz.random.NoGuidance; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.internal.PercentEscaper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import org.junit.jupiter.api.Test; +import org.junit.runner.Result; +import org.junit.runner.RunWith; + +@SuppressWarnings("SystemOut") +class ResourceConfigurationFuzzTest { + + @RunWith(JQF.class) + public static class TestCases { + + private static final PercentEscaper escaper = PercentEscaper.create(); + + @Fuzz + public void getAttributesWithRandomValues(String value1, String value2) { + Attributes attributes = + ResourceConfiguration.createEnvironmentResource( + DefaultConfigProperties.createFromMap( + singletonMap( + "otel.resource.attributes", + "key1=" + escaper.escape(value1) + ",key2=" + escaper.escape(value2)))) + .getAttributes(); + + assertThat(attributes).hasSize(2).containsEntry("key1", value1).containsEntry("key2", value2); + } + } + + // driver methods to avoid having to use the vintage junit engine, and to enable increasing the + // number of iterations: + + @Test + void getAttributesWithFuzzing() { + Result result = + GuidedFuzzing.run( + TestCases.class, + "getAttributesWithRandomValues", + new NoGuidance(10000, System.out), + System.out); + assertThat(result.wasSuccessful()).isTrue(); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java index 7993074bca3..03e36f32962 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java @@ -5,102 +5,232 @@ package io.opentelemetry.sdk.autoconfigure; +import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.sdk.autoconfigure.ResourceConfiguration.DISABLED_ATTRIBUTE_KEYS; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static java.util.Collections.emptyMap; import static java.util.Collections.singletonMap; +import static org.slf4j.event.Level.WARN; import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.common.AttributeKey; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Arrays; +import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.junitpioneer.jupiter.SetSystemProperty; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) class ResourceConfigurationTest { + @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(ResourceBuilder.class); + + private static final ComponentLoader componentLoader = + ComponentLoader.forClassLoader(ResourceConfigurationTest.class.getClassLoader()); + @Test - void customConfigResource() { + void customConfigResourceWithDisabledKeys() { Map props = new HashMap<>(); props.put("otel.service.name", "test-service"); - props.put("otel.resource.attributes", "food=cheesecake,drink=juice"); - props.put("otel.experimental.resource.disabled-keys", "drink"); + props.put( + "otel.resource.attributes", "food=cheesecake,drink=juice,animal= ,color=,shape=square"); + props.put("otel.resource.disabled-keys", "drink"); + ConfigProperties config = DefaultConfigProperties.create(props, componentLoader); assertThat( ResourceConfiguration.configureResource( - DefaultConfigProperties.get(props), - ResourceConfigurationTest.class.getClassLoader(), + config, + SpiHelper.create(ResourceConfigurationTest.class.getClassLoader()), (r, c) -> r)) .isEqualTo( Resource.getDefault().toBuilder() - .put(ResourceAttributes.SERVICE_NAME, "test-service") + .putAll(new ServiceInstanceIdResourceProvider().createResource(config)) + .putAll( + EntityUtil.createResource( + Collections.singletonList(serviceEntity("test-service")))) .put("food", "cheesecake") - .setSchemaUrl(ResourceAttributes.SCHEMA_URL) + .put("shape", "square") .build()); } @Test - void resourceFromConfig_empty() { - Attributes attributes = - ResourceConfiguration.getAttributes(DefaultConfigProperties.createForTest(emptyMap())); + void serviceInstanceIdFallback_defaultBehavior() { + Map props = new HashMap<>(); + props.put("otel.service.name", "test-service"); + + Resource result = + ResourceConfiguration.configureResource( + DefaultConfigProperties.create(props, componentLoader), + SpiHelper.create(ResourceConfigurationTest.class.getClassLoader()), + (r, c) -> r); + + String serviceInstanceId = result.getAttribute(stringKey("service.instance.id")); + assertThat(serviceInstanceId).isNotNull(); + assertThat(UUID.fromString(serviceInstanceId)).isNotNull(); + assertThat(result.getAttribute(stringKey("service.name"))).isEqualTo("test-service"); + assertThat(EntityUtil.getEntities(result)) + .containsExactlyInAnyOrder( + serviceEntity("test-service"), + Entity.builder( + "service.instance", + Attributes.of(stringKey("service.instance.id"), serviceInstanceId)) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build()); + } + + @Test + @SuppressLogger(ResourceBuilder.class) + void serviceInstanceIdExplicitValuePreserved() { + Map props = new HashMap<>(); + props.put("otel.service.name", "test-service"); + props.put("otel.resource.attributes", "service.instance.id=my-custom-id-123"); + + Resource result = + ResourceConfiguration.configureResource( + DefaultConfigProperties.create(props, componentLoader), + SpiHelper.create(ResourceConfigurationTest.class.getClassLoader()), + (r, c) -> r); + + assertThat(result.getAttribute(stringKey("service.instance.id"))).isEqualTo("my-custom-id-123"); + assertThat(EntityUtil.getEntities(result)).containsExactly(serviceEntity("test-service")); + assertThat(EntityUtil.getUnassociatedAttributes(result)) + .containsEntry(stringKey("service.instance.id"), "my-custom-id-123"); + } + + @Test + @SuppressLogger(ResourceBuilder.class) + void serviceInstanceEntityOverridesFallback() { + ConfigProperties config = + DefaultConfigProperties.createFromMap( + singletonMap("otel.entities", "service.instance{service.instance.id=custom}")); + Resource result = + ResourceConfiguration.configureResource( + config, + SpiHelper.create(ResourceConfigurationTest.class.getClassLoader()), + (r, c) -> r); + + assertThat(EntityUtil.getEntities(result)) + .containsExactly( + Entity.builder( + "service.instance", Attributes.of(stringKey("service.instance.id"), "custom")) + .build()); + assertThat(result.getAttribute(stringKey("service.instance.id"))).isEqualTo("custom"); + } + + @ParameterizedTest + @MethodSource("decodeResourceAttributesArgs") + void decodeResourceAttributes(String input, String expectedKey, String expectedValue) { + Map props = new HashMap<>(); + props.put("otel.resource.attributes", input); + + assertThat( + ResourceConfiguration.createEnvironmentResource( + DefaultConfigProperties.createFromMap(props))) + .isEqualTo(Resource.create(Attributes.of(stringKey(expectedKey), expectedValue))); + } + + private static Stream decodeResourceAttributesArgs() { + return Stream.of( + Arguments.argumentSet("plus sign preserved", "food=cheese+cake", "food", "cheese+cake"), + Arguments.argumentSet("percent-encoded space", "key=hello%20world", "key", "hello world"), + Arguments.argumentSet("invalid percent encoding", "key=abc%2Gdef", "key", "abc%2Gdef"), + Arguments.argumentSet("incomplete percent encoding", "key=abc%2", "key", "abc%2"), + Arguments.argumentSet("percent at end", "key=abc%", "key", "abc%"), + Arguments.argumentSet("multiple percent encodings", "key=a%20b%2Bc%3Dd", "key", "a b+c=d"), + Arguments.argumentSet("no percent encoding", "key=plain-value", "key", "plain-value"), + Arguments.argumentSet( + "unencoded non-ASCII with percent encoding", "key=cafΓ©%20bar", "key", "cafΓ© bar"), + Arguments.argumentSet( + "encoded and unencoded multi-byte", "key=%C3%A9t%C3%A9 Γ©tΓ©", "key", "Γ©tΓ© Γ©tΓ©"), + Arguments.argumentSet( + "unencoded supplementary character with percent encoding", + "key=πŸ˜€%20x", + "key", + "πŸ˜€ x")); + } + + @Test + void createEnvironmentResource_Empty() { + Attributes attributes = ResourceConfiguration.createEnvironmentResource().getAttributes(); assertThat(attributes).isEmpty(); } @Test - void resourceFromConfig() { - Attributes attributes = - ResourceConfiguration.getAttributes( - DefaultConfigProperties.createForTest( + void createEnvironmentResource_WithResourceAttributes() { + Resource resource = + ResourceConfiguration.createEnvironmentResource( + DefaultConfigProperties.createFromMap( singletonMap( - ResourceConfiguration.ATTRIBUTE_PROPERTY, - "service.name=myService,appName=MyApp"))); + "otel.resource.attributes", + "service.name=myService,service.instance.id=custom,appName=MyApp"))); + Attributes attributes = resource.getAttributes(); + assertThat(EntityUtil.getEntities(resource)).isEmpty(); + assertThat(EntityUtil.getUnassociatedAttributes(resource)).isEqualTo(attributes); assertThat(attributes) - .hasSize(2) - .containsEntry(ResourceAttributes.SERVICE_NAME, "myService") + .hasSize(3) + .containsEntry(stringKey("service.name"), "myService") + .containsEntry(stringKey("service.instance.id"), "custom") .containsEntry("appName", "MyApp"); } @Test - void serviceName() { - Attributes attributes = - ResourceConfiguration.getAttributes( - DefaultConfigProperties.createForTest( - singletonMap(ResourceConfiguration.SERVICE_NAME_PROPERTY, "myService"))); + @SetSystemProperty(key = "otel.service.name", value = "myService") + void createEnvironmentResource_WithServiceName() { + Resource resource = ResourceConfiguration.createEnvironmentResource(); - assertThat(attributes).hasSize(1).containsEntry(ResourceAttributes.SERVICE_NAME, "myService"); + assertThat(resource.getAttributes()) + .hasSize(1) + .containsEntry(stringKey("service.name"), "myService"); + assertThat(EntityUtil.getEntities(resource)).containsExactly(serviceEntity("myService")); + assertThat(EntityUtil.getUnassociatedAttributes(resource)).isEmpty(); + assertThat(resource.getSchemaUrl()).isEqualTo("https://opentelemetry.io/schemas/1.40.0"); } @Test - void resourceFromConfig_overrideServiceName() { - Attributes attributes = - ResourceConfiguration.getAttributes( - DefaultConfigProperties.createForTest( + void createEnvironmentResource_ServiceNamePriority() { + Resource resource = + ResourceConfiguration.createEnvironmentResource( + DefaultConfigProperties.createFromMap( ImmutableMap.of( - ResourceConfiguration.ATTRIBUTE_PROPERTY, + "otel.resource.attributes", "service.name=myService,appName=MyApp", - ResourceConfiguration.SERVICE_NAME_PROPERTY, + "otel.service.name", "ReallyMyService"))); + Attributes attributes = resource.getAttributes(); + assertThat(EntityUtil.getEntities(resource)).containsExactly(serviceEntity("ReallyMyService")); assertThat(attributes) .hasSize(2) - .containsEntry(ResourceAttributes.SERVICE_NAME, "ReallyMyService") + .containsEntry(stringKey("service.name"), "ReallyMyService") .containsEntry("appName", "MyApp"); } @Test - void resourceFromConfig_emptyEnvVar() { + void createEnvironmentResource_EmptyResourceAttributes() { Attributes attributes = - ResourceConfiguration.getAttributes( - DefaultConfigProperties.createForTest( - singletonMap(ResourceConfiguration.ATTRIBUTE_PROPERTY, ""))); + ResourceConfiguration.createEnvironmentResource( + DefaultConfigProperties.createFromMap(singletonMap("otel.resource.attributes", ""))) + .getAttributes(); assertThat(attributes).isEmpty(); } @@ -108,7 +238,7 @@ void resourceFromConfig_emptyEnvVar() { @Test void filterAttributes() { ConfigProperties configProperties = - DefaultConfigProperties.createForTest(ImmutableMap.of(DISABLED_ATTRIBUTE_KEYS, "foo,bar")); + DefaultConfigProperties.createFromMap(ImmutableMap.of(DISABLED_ATTRIBUTE_KEYS, "foo,bar")); Resource resourceNoSchema = Resource.builder().put("foo", "val").put("bar", "val").put("baz", "val").build(); @@ -116,21 +246,68 @@ void filterAttributes() { resourceNoSchema.toBuilder().setSchemaUrl("http://example.com").build(); assertThat(ResourceConfiguration.filterAttributes(resourceNoSchema, configProperties)) - .satisfies( - resource -> { - assertThat(resource.getSchemaUrl()).isNull(); - assertThat(resource.getAttributes()).containsEntry("baz", "val"); - assertThat(resource.getAttributes().get(AttributeKey.stringKey("foo"))).isNull(); - assertThat(resource.getAttributes().get(AttributeKey.stringKey("bar"))).isNull(); - }); + .satisfies(resource -> { + assertThat(resource.getSchemaUrl()).isNull(); + assertThat(resource.getAttributes()).containsEntry("baz", "val"); + assertThat(resource.getAttributes().get(stringKey("foo"))).isNull(); + assertThat(resource.getAttributes().get(stringKey("bar"))).isNull(); + }); assertThat(ResourceConfiguration.filterAttributes(resourceWithSchema, configProperties)) - .satisfies( - resource -> { - assertThat(resource.getSchemaUrl()).isEqualTo("http://example.com"); - assertThat(resource.getAttributes()).containsEntry("baz", "val"); - assertThat(resource.getAttributes().get(AttributeKey.stringKey("foo"))).isNull(); - assertThat(resource.getAttributes().get(AttributeKey.stringKey("bar"))).isNull(); - }); + .satisfies(resource -> { + assertThat(resource.getSchemaUrl()).isEqualTo("http://example.com"); + assertThat(resource.getAttributes()).containsEntry("baz", "val"); + assertThat(resource.getAttributes().get(stringKey("foo"))).isNull(); + assertThat(resource.getAttributes().get(stringKey("bar"))).isNull(); + }); + } + + @ParameterizedTest + @MethodSource("legacyEntityOverrides") + @SuppressLogger(ResourceBuilder.class) + void legacyEntityOverride(Map overrides, Resource expectedResource) { + Map properties = new HashMap<>(overrides); + properties.put( + "otel.entities", "service{service.name=detected}[service.version=1.0];host{host.id=H1}"); + Resource resource = + ResourceConfiguration.createEnvironmentResource( + DefaultConfigProperties.createFromMap(properties)); + + assertThat(resource).isEqualTo(expectedResource); + logs.assertContains( + event -> event.getLevel().equals(WARN), + overrides.containsKey("otel.resource.attributes") + ? "Removing entity association [service]" + : "Replacing entity [service]"); + } + + static Stream legacyEntityOverrides() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + Resource configuredService = + EntityUtil.createResource(Arrays.asList(host, serviceEntity("configured"))); + return Stream.of( + Arguments.argumentSet( + "resource attributes", + singletonMap("otel.resource.attributes", "service.name=resource"), + EntityUtil.createResource(Collections.singletonList(host)).toBuilder() + .put("service.name", "resource") + .put("service.version", "1.0") + .build()), + Arguments.argumentSet( + "service name", singletonMap("otel.service.name", "configured"), configuredService), + Arguments.argumentSet( + "service name beats resource attributes", + ImmutableMap.of( + "otel.resource.attributes", + "service.name=resource", + "otel.service.name", + "configured"), + configuredService.toBuilder().put("service.version", "1.0").build())); + } + + private static Entity serviceEntity(String name) { + return Entity.builder("service", Attributes.of(stringKey("service.name"), name)) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build(); } } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ServiceInstanceIdResourceProviderTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ServiceInstanceIdResourceProviderTest.java new file mode 100644 index 00000000000..fe4281a3429 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/ServiceInstanceIdResourceProviderTest.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Collections; +import java.util.UUID; +import org.junit.jupiter.api.Test; + +class ServiceInstanceIdResourceProviderTest { + + private static final AttributeKey SERVICE_INSTANCE_ID = stringKey("service.instance.id"); + + @Test + void createResource() { + DefaultConfigProperties config = DefaultConfigProperties.createFromMap(Collections.emptyMap()); + + Resource resource = new ServiceInstanceIdResourceProvider().createResource(config); + String serviceInstanceId = resource.getAttribute(SERVICE_INSTANCE_ID); + assertThat(serviceInstanceId).isNotNull(); + assertThat(UUID.fromString(serviceInstanceId)).isNotNull(); + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder( + "service.instance", Attributes.of(SERVICE_INSTANCE_ID, serviceInstanceId)) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build()); + assertThat(EntityUtil.getUnassociatedAttributes(resource)).isEmpty(); + assertThat(resource.getSchemaUrl()).isEqualTo("https://opentelemetry.io/schemas/1.40.0"); + + // Stable across calls and instances + assertThat( + new ServiceInstanceIdResourceProvider() + .createResource(config) + .getAttribute(SERVICE_INSTANCE_ID)) + .isEqualTo(serviceInstanceId); + assertThat(new ServiceInstanceIdResourceProvider().createResource(config)).isEqualTo(resource); + } + + @Test + void order_returnsMinValue() { + ServiceInstanceIdResourceProvider provider = new ServiceInstanceIdResourceProvider(); + assertThat(provider.order()).isEqualTo(Integer.MIN_VALUE); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java new file mode 100644 index 00000000000..0de288efc7f --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.autoconfigure.SpanExporterConfiguration.configureExporter; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class SpanExporterConfigurationTest { + + @Test + void configureExporter_KnownSpiExportersNotOnClasspath() { + NamedSpiManager spiExportersManager = + SpanExporterConfiguration.spanExporterSpiManager( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + SpiHelper.create(SpanExporterConfigurationTest.class.getClassLoader())); + + assertThatThrownBy(() -> configureExporter("jaeger", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.traces.exporter set to \"jaeger\" but opentelemetry-exporter-jaeger" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("logging", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.traces.exporter set to \"logging\" but opentelemetry-exporter-logging" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("logging-otlp", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.traces.exporter set to \"logging-otlp\" but opentelemetry-exporter-logging-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("experimental-otlp/stdout", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.traces.exporter set to \"experimental-otlp/stdout\" but opentelemetry-exporter-logging-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + assertThatThrownBy(() -> configureExporter("otlp", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "otel.traces.exporter set to \"otlp\" but opentelemetry-exporter-otlp" + + " not found on classpath. Make sure to add it as a dependency."); + + // Unrecognized exporter + assertThatThrownBy(() -> configureExporter("foo", spiExportersManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessage("Unrecognized value for otel.traces.exporter: foo"); + } +} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/SpiUtilTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/SpiUtilTest.java deleted file mode 100644 index 6bad1a5641d..00000000000 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/SpiUtilTest.java +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertThrows; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import java.util.Collections; -import org.junit.jupiter.api.Test; - -public class SpiUtilTest { - - private static final ConfigProperties EMPTY = - DefaultConfigProperties.createForTest(Collections.emptyMap()); - - @Test - public void canRetrieveByName() { - SpiUtil.ServiceLoaderFinder mockFinder = mock(SpiUtil.ServiceLoaderFinder.class); - when(mockFinder.load(any(), any())) - .thenReturn(Collections.singletonList(new SpiExampleProviderImplementation())); - - NamedSpiManager spiProvider = - SpiUtil.loadConfigurable( - SpiExampleProvider.class, - SpiExampleProvider::getName, - SpiExampleProvider::createSpiExample, - EMPTY, - SpiUtilTest.class.getClassLoader(), - mockFinder); - - assertNotNull(spiProvider.getByName(SpiExampleProviderImplementation.NAME)); - assertNull(spiProvider.getByName("invalid-provider")); - } - - @Test - public void instantiatesImplementationsLazily() { - SpiExampleProvider mockProvider = mock(SpiExampleProvider.class); - when(mockProvider.getName()).thenReturn("lazy-init-example"); - - SpiUtil.ServiceLoaderFinder mockFinder = mock(SpiUtil.ServiceLoaderFinder.class); - when(mockFinder.load(any(), any())).thenReturn(Collections.singletonList(mockProvider)); - - NamedSpiManager spiProvider = - SpiUtil.loadConfigurable( - SpiExampleProvider.class, - SpiExampleProvider::getName, - SpiExampleProvider::createSpiExample, - EMPTY, - SpiUtilTest.class.getClassLoader(), - mockFinder); - - verify(mockProvider, never()).createSpiExample(any()); // not requested yet - spiProvider.getByName("lazy-init-example"); - verify(mockProvider).createSpiExample(EMPTY); // initiated upon request - } - - @Test - public void onlyInstantiatesOnce() { - SpiUtil.ServiceLoaderFinder mockFinder = mock(SpiUtil.ServiceLoaderFinder.class); - when(mockFinder.load(any(), any())) - .thenReturn(Collections.singletonList(new SpiExampleProviderImplementation())); - - NamedSpiManager spiProvider = - SpiUtil.loadConfigurable( - SpiExampleProvider.class, - SpiExampleProvider::getName, - SpiExampleProvider::createSpiExample, - EMPTY, - SpiUtilTest.class.getClassLoader(), - mockFinder); - - SpiExample first = spiProvider.getByName(SpiExampleProviderImplementation.NAME); - SpiExample second = spiProvider.getByName(SpiExampleProviderImplementation.NAME); - assertEquals(first, second); - } - - @Test - public void failureToInitializeThrows() { - String exceptionMessage = "failure to initialize should throw"; - SpiExampleProvider mockProvider = mock(SpiExampleProvider.class); - when(mockProvider.getName()).thenReturn("init-failure-example"); - when(mockProvider.createSpiExample(any())).thenThrow(new RuntimeException()); - - SpiUtil.ServiceLoaderFinder mockFinder = mock(SpiUtil.ServiceLoaderFinder.class); - when(mockFinder.load(any(), any())).thenReturn(Collections.singletonList(mockProvider)); - - NamedSpiManager spiProvider = - SpiUtil.loadConfigurable( - SpiExampleProvider.class, - SpiExampleProvider::getName, - SpiExampleProvider::createSpiExample, - EMPTY, - SpiUtilTest.class.getClassLoader(), - mockFinder); - - assertThrows( - RuntimeException.class, - () -> spiProvider.getByName("init-failure-example"), - exceptionMessage); - } - - private interface SpiExampleProvider { - - String getName(); - - SpiExample createSpiExample(ConfigProperties config); - } - - private static class SpiExampleProviderImplementation implements SpiExampleProvider { - - private static final String NAME = "spi-example"; - - @Override - public String getName() { - return NAME; - } - - @Override - public SpiExample createSpiExample(ConfigProperties config) { - return new SpiExample() {}; - } - } - - private interface SpiExample {} -} diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java index 43f464f8a49..42919587ba1 100644 --- a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java @@ -10,12 +10,14 @@ import static org.mockito.Mockito.when; import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; import io.opentelemetry.sdk.trace.SpanLimits; @@ -24,27 +26,34 @@ import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.internal.JcTools; import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.io.Closeable; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -// NB: We use AssertJ extracting to reflectively access implementation details to test configuration -// because the use of BatchSpanProcessor makes it difficult to verify values through public means. @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) class TracerProviderConfigurationTest { private static final ConfigProperties EMPTY = - DefaultConfigProperties.createForTest(Collections.emptyMap()); + DefaultConfigProperties.createFromMap(Collections.emptyMap()); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final SpiHelper spiHelper = + SpiHelper.create(TracerProviderConfigurationTest.class.getClassLoader()); @Mock private SpanExporter mockSpanExporter; @@ -59,63 +68,55 @@ void configureTracerProvider() { properties.put("otel.bsp.schedule.delay", "100000"); properties.put("otel.traces.sampler", "always_off"); properties.put("otel.traces.exporter", "none"); + List closeables = new ArrayList<>(); - Resource resource = Resource.create(Attributes.builder().put("cat", "meow").build()); // We don't have any exporters on classpath for this test so check no-op case. Exporter cases // are verified in other test sets like testFullConfig. - SdkTracerProviderBuilder tracerProviderBuilder = - SdkTracerProvider.builder().setResource(resource); + SdkTracerProviderBuilder tracerProviderBuilder = SdkTracerProvider.builder(); TracerProviderConfiguration.configureTracerProvider( tracerProviderBuilder, - DefaultConfigProperties.createForTest(properties), - TracerProviderConfiguration.class.getClassLoader(), + DefaultConfigProperties.createFromMap(properties), + spiHelper, MeterProvider.noop(), (a, unused) -> a, - (a, unused) -> a); - SdkTracerProvider tracerProvider = tracerProviderBuilder.build(); - try { + (a, unused) -> a, + (a, unused) -> a, + closeables); + + try (SdkTracerProvider tracerProvider = tracerProviderBuilder.build()) { assertThat(tracerProvider.getSampler()).isEqualTo(Sampler.alwaysOff()); assertThat(tracerProvider) .extracting("sharedState") - .satisfies( - sharedState -> { - assertThat(sharedState).extracting("resource").isEqualTo(resource); - assertThat(sharedState) - .extracting("activeSpanProcessor") - .isEqualTo(SpanProcessor.composite()); - }); - } finally { - tracerProvider.shutdown(); + .satisfies(sharedState -> + assertThat(sharedState) + .extracting("activeSpanProcessor") + .isEqualTo(SpanProcessor.composite())); + assertThat(closeables).isEmpty(); } } @Test void configureBatchSpanProcessor_empty() { - BatchSpanProcessor processor = + try (BatchSpanProcessor processor = TracerProviderConfiguration.configureBatchSpanProcessor( - EMPTY, mockSpanExporter, MeterProvider.noop()); - - try { + EMPTY, mockSpanExporter, InternalTelemetryVersion.LEGACY, MeterProvider.noop())) { assertThat(processor) .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(5000)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2048)); - assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); - }); - } finally { - processor.shutdown(); + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(5000)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2048)); + assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); + }); } } @@ -124,35 +125,31 @@ void configureBatchSpanProcessor_configured() { Map properties = new HashMap<>(); properties.put("otel.bsp.schedule.delay", "100000"); properties.put("otel.bsp.max.queue.size", "2"); - properties.put("otel.bsp.max.export.batch.size", "3"); + properties.put("otel.bsp.max.export.batch.size", "2"); properties.put("otel.bsp.export.timeout", "4"); - BatchSpanProcessor processor = + try (BatchSpanProcessor processor = TracerProviderConfiguration.configureBatchSpanProcessor( - DefaultConfigProperties.createForTest(properties), + DefaultConfigProperties.createFromMap(properties), mockSpanExporter, - MeterProvider.noop()); - - try { + InternalTelemetryVersion.LEGACY, + MeterProvider.noop())) { assertThat(processor) .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(3); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2)); - assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); - }); - } finally { - processor.shutdown(); + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(2); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + Queue.class, queue -> assertThat(JcTools.capacity(queue)).isEqualTo(2)); + assertThat(worker).extracting("spanExporter").isEqualTo(mockSpanExporter); + }); } } @@ -163,7 +160,7 @@ void configureSpanLimits() { SpanLimits config = TracerProviderConfiguration.configureSpanLimits( - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( ImmutableMap.of( "otel.attribute.value.length.limit", "100", "otel.attribute.count.limit", "5"))); @@ -178,7 +175,7 @@ void configureSpanLimits() { config = TracerProviderConfiguration.configureSpanLimits( - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( ImmutableMap.of( "otel.attribute.value.length.limit", "100", "otel.span.attribute.value.length.limit", "200", @@ -196,54 +193,47 @@ void configureSpanLimits() { @Test void configureSampler() { - assertThat( - TracerProviderConfiguration.configureSampler( - "always_on", EMPTY, TracerProviderConfiguration.class.getClassLoader())) + assertThat(TracerProviderConfiguration.configureSampler("always_on", EMPTY, spiHelper)) .isEqualTo(Sampler.alwaysOn()); - assertThat( - TracerProviderConfiguration.configureSampler( - "always_off", EMPTY, TracerProviderConfiguration.class.getClassLoader())) + assertThat(TracerProviderConfiguration.configureSampler("always_off", EMPTY, spiHelper)) .isEqualTo(Sampler.alwaysOff()); assertThat( TracerProviderConfiguration.configureSampler( "traceidratio", - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( Collections.singletonMap("otel.traces.sampler.arg", "0.5")), - TracerProviderConfiguration.class.getClassLoader())) + spiHelper)) .isEqualTo(Sampler.traceIdRatioBased(0.5)); - assertThat( - TracerProviderConfiguration.configureSampler( - "traceidratio", EMPTY, TracerProviderConfiguration.class.getClassLoader())) + assertThat(TracerProviderConfiguration.configureSampler("traceidratio", EMPTY, spiHelper)) .isEqualTo(Sampler.traceIdRatioBased(1.0d)); assertThat( - TracerProviderConfiguration.configureSampler( - "parentbased_always_on", EMPTY, TracerProviderConfiguration.class.getClassLoader())) + TracerProviderConfiguration.configureSampler("parentbased_always_on", EMPTY, spiHelper)) .isEqualTo(Sampler.parentBased(Sampler.alwaysOn())); assertThat( TracerProviderConfiguration.configureSampler( - "parentbased_always_off", - EMPTY, - TracerProviderConfiguration.class.getClassLoader())) + "parentbased_always_off", EMPTY, spiHelper)) .isEqualTo(Sampler.parentBased(Sampler.alwaysOff())); assertThat( TracerProviderConfiguration.configureSampler( "parentbased_traceidratio", - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( Collections.singletonMap("otel.traces.sampler.arg", "0.4")), - TracerProviderConfiguration.class.getClassLoader())) + spiHelper)) .isEqualTo(Sampler.parentBased(Sampler.traceIdRatioBased(0.4))); assertThat( TracerProviderConfiguration.configureSampler( - "parentbased_traceidratio", - EMPTY, - TracerProviderConfiguration.class.getClassLoader())) + "parentbased_traceidratio", EMPTY, spiHelper)) .isEqualTo(Sampler.parentBased(Sampler.traceIdRatioBased(1.0d))); assertThatThrownBy( - () -> - TracerProviderConfiguration.configureSampler( - "catsampler", EMPTY, TracerProviderConfiguration.class.getClassLoader())) + () -> TracerProviderConfiguration.configureSampler("catsampler", EMPTY, spiHelper)) .isInstanceOf(ConfigurationException.class) .hasMessage("Unrecognized value for otel.traces.sampler: catsampler"); + assertThatThrownBy(() -> + TracerProviderConfiguration.configureSampler( + "parentbased_jaeger_remote", EMPTY, spiHelper)) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "parentbased_jaeger_remote configured but opentelemetry-sdk-extension-jaeger-remote-sampler not on classpath"); } } diff --git a/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/internal/SpiHelperTest.java b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/internal/SpiHelperTest.java new file mode 100644 index 00000000000..b1497079a9e --- /dev/null +++ b/sdk-extensions/autoconfigure/src/test/java/io/opentelemetry/sdk/autoconfigure/internal/SpiHelperTest.java @@ -0,0 +1,158 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.internal; + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +public class SpiHelperTest { + + private static final ConfigProperties EMPTY = + DefaultConfigProperties.createFromMap(Collections.emptyMap()); + + @Test + public void canRetrieveByName() { + ComponentLoader mockLoader = spy(ComponentLoader.class); + when(mockLoader.load(any())) + .thenReturn(Collections.singletonList(new SpiExampleProviderImplementation())); + + SpiHelper spiHelper = SpiHelper.create(mockLoader); + + NamedSpiManager spiProvider = + spiHelper.loadConfigurable( + SpiExampleProvider.class, + SpiExampleProvider::getName, + SpiExampleProvider::createSpiExample, + EMPTY); + + assertThat(spiProvider.getByName(SpiExampleProviderImplementation.NAME)).isNotNull(); + assertThat(spiProvider.getByName("invalid-provider")).isNull(); + } + + @Test + public void instantiatesImplementationsLazily() { + SpiExampleProvider mockProvider = mock(SpiExampleProvider.class); + when(mockProvider.getName()).thenReturn("lazy-init-example"); + ComponentLoader mockLoader = spy(ComponentLoader.class); + when(mockLoader.load(any())).thenReturn(Collections.singletonList(mockProvider)); + + SpiHelper spiHelper = SpiHelper.create(mockLoader); + + NamedSpiManager spiProvider = + spiHelper.loadConfigurable( + SpiExampleProvider.class, + SpiExampleProvider::getName, + SpiExampleProvider::createSpiExample, + EMPTY); + + verify(mockProvider, never()).createSpiExample(any()); // not requested yet + spiProvider.getByName("lazy-init-example"); + verify(mockProvider).createSpiExample(EMPTY); // initiated upon request + } + + @Test + public void onlyInstantiatesOnce() { + ComponentLoader mockLoader = mock(ComponentLoader.class); + when(mockLoader.load(any())) + .thenReturn(Collections.singletonList(new SpiExampleProviderImplementation())); + + SpiHelper spiHelper = SpiHelper.create(mockLoader); + + NamedSpiManager spiProvider = + spiHelper.loadConfigurable( + SpiExampleProvider.class, + SpiExampleProvider::getName, + SpiExampleProvider::createSpiExample, + EMPTY); + + SpiExample first = spiProvider.getByName(SpiExampleProviderImplementation.NAME); + SpiExample second = spiProvider.getByName(SpiExampleProviderImplementation.NAME); + assertThat(second).isEqualTo(first); + } + + @Test + public void failureToInitializeThrows() { + String exceptionMessage = "failure to initialize should throw"; + SpiExampleProvider mockProvider = mock(SpiExampleProvider.class); + when(mockProvider.getName()).thenReturn("init-failure-example"); + when(mockProvider.createSpiExample(any())).thenThrow(new RuntimeException()); + + ComponentLoader mockLoader = spy(ComponentLoader.class); + when(mockLoader.load(any())).thenReturn(Collections.singletonList(mockProvider)); + + SpiHelper spiHelper = SpiHelper.create(mockLoader); + + NamedSpiManager spiProvider = + spiHelper.loadConfigurable( + SpiExampleProvider.class, + SpiExampleProvider::getName, + SpiExampleProvider::createSpiExample, + EMPTY); + + assertThatThrownBy(() -> spiProvider.getByName("init-failure-example")) + .withFailMessage(exceptionMessage) + .isInstanceOf(RuntimeException.class); + } + + @Test + void loadsOrderedSpi() { + ResourceProvider spi1 = mock(ResourceProvider.class); + ResourceProvider spi2 = mock(ResourceProvider.class); + ResourceProvider spi3 = mock(ResourceProvider.class); + + when(spi1.order()).thenReturn(2); + when(spi2.order()).thenReturn(0); + when(spi3.order()).thenReturn(1); + + ComponentLoader mockLoader = spy(ComponentLoader.class); + when(mockLoader.load(ResourceProvider.class)).thenReturn(asList(spi1, spi2, spi3)); + + SpiHelper spiHelper = SpiHelper.create(mockLoader); + + List loadedSpi = spiHelper.loadOrdered(ResourceProvider.class); + + assertThat(loadedSpi).containsExactly(spi2, spi3, spi1); + } + + private interface SpiExampleProvider { + + String getName(); + + SpiExample createSpiExample(ConfigProperties config); + } + + private static class SpiExampleProviderImplementation implements SpiExampleProvider { + + private static final String NAME = "spi-example"; + + @Override + public String getName() { + return NAME; + } + + @Override + public SpiExample createSpiExample(ConfigProperties config) { + return new SpiExample() {}; + } + } + + private interface SpiExample {} +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/OrderedSpiTest.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/OrderedSpiTest.java new file mode 100644 index 00000000000..5d55c2fc679 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/OrderedSpiTest.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; + +import org.junit.jupiter.api.Test; + +class OrderedSpiTest { + + @Test + void shouldLoadSpiImplementationsInOrder() { + AutoConfiguredOpenTelemetrySdk sdk = AutoConfiguredOpenTelemetrySdk.builder().build(); + + assertThat(sdk.getResource().getAttributes().asMap()) + .contains( + entry(stringKey("otel.some_resource"), "real value"), + entry(stringKey("otel.from_config"), "configured value")); + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/FirstCustomizerProvider.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/FirstCustomizerProvider.java new file mode 100644 index 00000000000..960544e0203 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/FirstCustomizerProvider.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static java.util.Collections.singletonMap; + +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; + +public class FirstCustomizerProvider implements AutoConfigurationCustomizerProvider { + + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + autoConfiguration.addPropertiesSupplier(() -> singletonMap("otel.from-config", "unused")); + } + + @Override + public int order() { + return 1000; + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/FirstResourceProvider.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/FirstResourceProvider.java new file mode 100644 index 00000000000..1e2d7dacd9f --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/FirstResourceProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class FirstResourceProvider implements ResourceProvider { + + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create( + Attributes.of( + stringKey("otel.some_resource"), + "unused", + stringKey("otel.from_config"), + config.getString("otel.from-config", "default"))); + } + + @Override + public int order() { + return 100; + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/SecondCustomizerProvider.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/SecondCustomizerProvider.java new file mode 100644 index 00000000000..7b3888e4bf6 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/SecondCustomizerProvider.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static java.util.Collections.singletonMap; + +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; + +public class SecondCustomizerProvider implements AutoConfigurationCustomizerProvider { + + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + autoConfiguration.addPropertiesSupplier(() -> singletonMap("otel.from-config", "still unused")); + } + + @Override + public int order() { + return 2000; + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/SecondResourceProvider.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/SecondResourceProvider.java new file mode 100644 index 00000000000..22ca22b5256 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/SecondResourceProvider.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class SecondResourceProvider implements ResourceProvider { + + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create(Attributes.of(stringKey("otel.some_resource"), "still unused")); + } + + @Override + public int order() { + return 200; + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/ThirdCustomizerProvider.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/ThirdCustomizerProvider.java new file mode 100644 index 00000000000..2a859b99d22 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/ThirdCustomizerProvider.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static java.util.Collections.singletonMap; + +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; + +public class ThirdCustomizerProvider implements AutoConfigurationCustomizerProvider { + + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + autoConfiguration.addPropertiesSupplier( + () -> singletonMap("otel.from-config", "configured value")); + } + + @Override + public int order() { + return 3000; + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/ThirdResourceProvider.java b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/ThirdResourceProvider.java new file mode 100644 index 00000000000..6e86a03dd4f --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/java/io/opentelemetry/sdk/autoconfigure/provider/ThirdResourceProvider.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class ThirdResourceProvider implements ResourceProvider { + + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create(Attributes.of(stringKey("otel.some_resource"), "real value")); + } + + @Override + public int order() { + return 300; + } +} diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider new file mode 100644 index 00000000000..db8cfa36d0b --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider @@ -0,0 +1,3 @@ +io.opentelemetry.sdk.autoconfigure.provider.SecondCustomizerProvider +io.opentelemetry.sdk.autoconfigure.provider.ThirdCustomizerProvider +io.opentelemetry.sdk.autoconfigure.provider.FirstCustomizerProvider diff --git a/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider new file mode 100644 index 00000000000..996b25b48d6 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testAutoConfigureOrder/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider @@ -0,0 +1,3 @@ +io.opentelemetry.sdk.autoconfigure.provider.ThirdResourceProvider +io.opentelemetry.sdk.autoconfigure.provider.SecondResourceProvider +io.opentelemetry.sdk.autoconfigure.provider.FirstResourceProvider diff --git a/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/ConditionalResourceProviderTest.java b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/ConditionalResourceProviderTest.java new file mode 100644 index 00000000000..6d3c90bb620 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/ConditionalResourceProviderTest.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; + +import org.junit.jupiter.api.Test; + +class ConditionalResourceProviderTest { + + @Test + void shouldConditionallyProvideResourceAttributes_skipBasedOnPreviousResource() { + AutoConfiguredOpenTelemetrySdk sdk = AutoConfiguredOpenTelemetrySdk.builder().build(); + + assertThat(sdk.getResource().getAttributes().asMap()) + .contains(entry(stringKey("service.name"), "test-service")); + } + + @Test + void shouldConditionallyProvideResourceAttributes_skipBasedOnConfig() { + AutoConfiguredOpenTelemetrySdk sdk = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> singletonMap("skip-first-resource-provider", "true")) + .build(); + + assertThat(sdk.getResource().getAttributes().asMap()) + .contains(entry(stringKey("service.name"), "test-service-2")); + } +} diff --git a/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/provider/FirstResourceProvider.java b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/provider/FirstResourceProvider.java new file mode 100644 index 00000000000..97dfc1b1b7b --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/provider/FirstResourceProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConditionalResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class FirstResourceProvider implements ConditionalResourceProvider { + + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create(Attributes.of(stringKey("service.name"), "test-service")); + } + + @Override + public int order() { + return 100; + } + + @Override + public boolean shouldApply(ConfigProperties config, Resource existing) { + return !config.getBoolean("skip-first-resource-provider", false); + } +} diff --git a/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/provider/SecondResourceProvider.java b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/provider/SecondResourceProvider.java new file mode 100644 index 00000000000..d8978b8bfde --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/java/io/opentelemetry/sdk/autoconfigure/provider/SecondResourceProvider.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ConditionalResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class SecondResourceProvider implements ConditionalResourceProvider { + + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create(Attributes.of(stringKey("service.name"), "test-service-2")); + } + + @Override + public int order() { + return 200; + } + + @Override + public boolean shouldApply(ConfigProperties config, Resource existing) { + String serviceName = existing.getAttribute(stringKey("service.name")); + return serviceName == null || "unknown_service:java".equals(serviceName); + } +} diff --git a/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider new file mode 100644 index 00000000000..39614eeb248 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testConditionalResourceProvider/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider @@ -0,0 +1,2 @@ +io.opentelemetry.sdk.autoconfigure.provider.SecondResourceProvider +io.opentelemetry.sdk.autoconfigure.provider.FirstResourceProvider diff --git a/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationSpiTest.java b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationSpiTest.java new file mode 100644 index 00000000000..4190df36cae --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationSpiTest.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.internal.OpenTelemetrySdkBuilderUtil; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class DeclarativeConfigurationSpiTest { + + @RegisterExtension private static final CleanupExtension cleanup = new CleanupExtension(); + + @Test + void configFromSpi() { + Resource resource = Resource.getDefault().toBuilder().put("service.name", "test").build(); + OpenTelemetrySdk expectedSdk = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder() + .setMeterProvider(SdkMeterProvider.builder().setResource(resource).build()) + .setLoggerProvider(SdkLoggerProvider.builder().setResource(resource).build()) + .setTracerProvider( + SdkTracerProvider.builder() + .setResource(resource) + .addSpanProcessor( + SimpleSpanProcessor.create(LoggingSpanExporter.create())) + .build()), + SdkConfigProvider.create(DeclarativeConfigProperties.empty())) + .build(); + cleanup.addCloseable(expectedSdk); + AutoConfiguredOpenTelemetrySdkBuilder builder = spy(AutoConfiguredOpenTelemetrySdk.builder()); + Thread thread = new Thread(); + doReturn(thread).when(builder).shutdownHook(any()); + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = builder.build(); + cleanup.addCloseable(autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk()); + + assertThat(autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().toString()) + .isEqualTo(expectedSdk.toString()); + + assertThat(TestResourceDetector.initialized).isTrue(); + } +} diff --git a/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/TestDeclarativeConfigurationProvider.java b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/TestDeclarativeConfigurationProvider.java new file mode 100644 index 00000000000..565ae7ea31c --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/TestDeclarativeConfigurationProvider.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; + +public class TestDeclarativeConfigurationProvider implements DeclarativeConfigurationProvider { + @Override + public OpenTelemetryConfigurationModel getConfigurationModel() { + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " detection/development:\n" + + " detectors:\n" + + " - test:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: test\n" + + "tracer_provider:\n" + + " processors:\n" + + " - simple:\n" + + " exporter:\n" + + " console: {}\n"; + + return DeclarativeConfiguration.parse( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/TestResourceDetector.java b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/TestResourceDetector.java new file mode 100644 index 00000000000..b20a098afa3 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/java/io/opentelemetry/sdk/autoconfigure/TestResourceDetector.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.resources.Resource; + +public class TestResourceDetector implements ComponentProvider, AutoConfigureListener { + + @SuppressWarnings("NonFinalStaticField") + static boolean initialized = false; + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) { + initialized = true; + } + + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public Resource create(DeclarativeConfigProperties config) { + return Resource.empty(); + } +} diff --git a/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationProvider b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationProvider new file mode 100644 index 00000000000..80610d72e48 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationProvider @@ -0,0 +1 @@ +io.opentelemetry.sdk.autoconfigure.TestDeclarativeConfigurationProvider diff --git a/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..3d7137e5568 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testDeclarativeConfigSpi/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,2 @@ +io.opentelemetry.sdk.autoconfigure.TestResourceDetector + diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java new file mode 100644 index 00000000000..9886e84409e --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import com.linecorp.armeria.client.WebClient; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import java.lang.reflect.Field; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junitpioneer.jupiter.SetSystemProperty; + +@SetSystemProperty(key = "otel.traces.exporter", value = "none") +@SetSystemProperty(key = "otel.metrics.exporter", value = "none") +class AutoConfiguredOpenTelemetrySdkTest { + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(GlobalOpenTelemetry.class); + + @BeforeEach + void setUp() { + GlobalOpenTelemetry.resetForTest(); + } + + @SuppressWarnings("ResultOfMethodCallIgnored") + @Test + void build_addMetricReaderCustomizerPrometheus() { + AutoConfiguredOpenTelemetrySdkBuilder builder = AutoConfiguredOpenTelemetrySdk.builder(); + builder.addPropertiesSupplier(() -> singletonMap("otel.metrics.exporter", "prometheus")); + + int port = FreePortFinder.getFreePort(); + builder.addMetricReaderCustomizer((reader, config) -> { + assertThat(reader).isInstanceOf(PrometheusHttpServer.class); + return PrometheusHttpServer.builder().setPort(port).build(); + }); + + try (OpenTelemetrySdk ignored = builder.build().getOpenTelemetrySdk()) { + WebClient client = WebClient.builder("http://localhost:" + port).build(); + assertThatCode(() -> client.get("/metrics")).doesNotThrowAnyException(); + } + } + + @Test + void initializeAndGet() { + try (OpenTelemetrySdk sdk = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk()) { + assertThat(GlobalOpenTelemetry.get()) + // ObfuscatedOpenTelemetry + .extracting("delegate") + .isSameAs(sdk); + } + } + + @Test + void initializeAndGet_noGlobal() { + try (OpenTelemetrySdk sdk = + AutoConfiguredOpenTelemetrySdk.builder().build().getOpenTelemetrySdk()) { + assertThat(GlobalOpenTelemetry.get()).isNotSameAs(sdk); + } + } + + @Test + void globalOpenTelemetry_AutoConfigureDisabled() { + // Autoconfigure is disabled by default and enabled via otel.java.global-autoconfigure.enabled + assertThat(GlobalOpenTelemetry.get()).extracting("delegate").isSameAs(OpenTelemetry.noop()); + + logs.assertContains( + "AutoConfiguredOpenTelemetrySdk found on classpath but automatic configuration is disabled." + + " To enable, run your JVM with -Dotel.java.global-autoconfigure.enabled=true"); + } + + @Test + @SetSystemProperty(key = "otel.java.global-autoconfigure.enabled", value = "true") + void globalOpenTelemetry_AutoConfigureEnabled() { + OpenTelemetry openTelemetry = unobfuscate(GlobalOpenTelemetry.get()); + assertThat(openTelemetry).isInstanceOf(OpenTelemetrySdk.class); + ((OpenTelemetrySdk) openTelemetry).close(); + } + + private static OpenTelemetry unobfuscate(OpenTelemetry openTelemetry) { + try { + Field delegateField = + Class.forName("io.opentelemetry.api.incubator.internal.ObfuscatedExtendedOpenTelemetry") + .getDeclaredField("delegate"); + delegateField.setAccessible(true); + Object delegate = delegateField.get(openTelemetry); + return (OpenTelemetry) delegate; + } catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) { + throw new IllegalStateException("Error unobfuscating OpenTelemetry", e); + } + } +} diff --git a/sdk-extensions/autoconfigure/src/testConfigError/java/io/opentelemetry/sdk/autoconfigure/ConfigErrorTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigErrorTest.java similarity index 92% rename from sdk-extensions/autoconfigure/src/testConfigError/java/io/opentelemetry/sdk/autoconfigure/ConfigErrorTest.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigErrorTest.java index 7e35b32a09f..e0c66b5e2ad 100644 --- a/sdk-extensions/autoconfigure/src/testConfigError/java/io/opentelemetry/sdk/autoconfigure/ConfigErrorTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigErrorTest.java @@ -14,6 +14,7 @@ import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junitpioneer.jupiter.SetSystemProperty; @@ -22,11 +23,17 @@ // All tests fail due to config errors so never register a global. We can test everything here // without separating test sets. +@SuppressLogger(loggerName = "io.opentelemetry.sdk.metrics.export.PeriodicMetricReader") class ConfigErrorTest { @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(GlobalOpenTelemetry.class); + @BeforeEach + void setup() { + GlobalOpenTelemetry.resetForTest(); + } + @Test @SetSystemProperty(key = "otel.propagators", value = "cat") void invalidPropagator() { @@ -66,6 +73,7 @@ void invalidSampler() { @Test @SetSystemProperty(key = "otel.traces.sampler", value = "traceidratio") @SetSystemProperty(key = "otel.traces.sampler.arg", value = "bar") + @SetSystemProperty(key = "otel.java.global-autoconfigure.enabled", value = "true") @SuppressLogger(GlobalOpenTelemetry.class) void globalOpenTelemetryWhenError() { assertThat(GlobalOpenTelemetry.get()) diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java new file mode 100644 index 00000000000..9cce9b26ba2 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableLogRecordExporterTest.java @@ -0,0 +1,90 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.exporter.otlp.internal.OtlpLogRecordExporterProvider; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.io.Closeable; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class ConfigurableLogRecordExporterTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + @Test + void configureLogRecordExporters_spiExporter() { + ConfigProperties config = + DefaultConfigProperties.createFromMap( + ImmutableMap.of("test.option", "true", "otel.logs.exporter", "testExporter")); + List closeables = new ArrayList<>(); + + SpiHelper spiHelper = SpiHelper.create(LogRecordExporterConfiguration.class.getClassLoader()); + Map exportersByName = + LogRecordExporterConfiguration.configureLogRecordExporters( + config, spiHelper, (a, unused) -> a, closeables); + cleanup.addCloseables(closeables); + + assertThat(exportersByName) + .hasSize(1) + .containsKey("testExporter") + .extracting(map -> map.get("testExporter")) + .isInstanceOf(TestConfigurableLogRecordExporterProvider.TestLogRecordExporter.class) + .extracting("config") + .isSameAs(config); + assertThat(closeables) + .hasExactlyElementsOfTypes( + TestConfigurableLogRecordExporterProvider.TestLogRecordExporter.class); + assertThat(spiHelper.getListeners()) + .satisfiesExactlyInAnyOrder( + listener -> + assertThat(listener).isInstanceOf(TestConfigurableLogRecordExporterProvider.class), + listener -> assertThat(listener).isInstanceOf(OtlpLogRecordExporterProvider.class)); + } + + @Test + void configureLogRecordExporters_emptyClassLoader() { + ConfigProperties config = + DefaultConfigProperties.createFromMap( + ImmutableMap.of("test.option", "true", "otel.logs.exporter", "testExporter")); + List closeables = new ArrayList<>(); + + SpiHelper spiHelper = SpiHelper.create(new URLClassLoader(new URL[0], null)); + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureLogRecordExporters( + config, spiHelper, (a, unused) -> a, closeables)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("testExporter"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); + assertThat(spiHelper.getListeners()).isEmpty(); + } + + @Test + void configureExporter_NotFound() { + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureExporter( + "catExporter", NamedSpiManager.createEmpty())) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("catExporter"); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java index f2b48063a0b..7392c1bd86e 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableMetricExporterTest.java @@ -9,111 +9,137 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.collect.ImmutableMap; +import io.opentelemetry.exporter.logging.LoggingMetricExporter; +import io.opentelemetry.exporter.otlp.internal.OtlpMetricExporterProvider; import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; -import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableMetricExporterProvider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import java.io.Closeable; import java.net.URL; import java.net.URLClassLoader; +import java.util.ArrayList; import java.util.Collections; -import java.util.concurrent.TimeUnit; +import java.util.List; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; -public class ConfigurableMetricExporterTest { +class ConfigurableMetricExporterTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final SpiHelper spiHelper = + SpiHelper.create(ConfigurableMetricExporterTest.class.getClassLoader()); @Test - void configuration() { + void configureExporter_spiExporter() { ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("test.option", "true")); - MetricExporter metricExporter = - MetricExporterConfiguration.configureSpiExporter( - "testExporter", config, MetricExporterConfiguration.class.getClassLoader()); - - assertThat(metricExporter) - .isInstanceOf(TestConfigurableMetricExporterProvider.TestMetricExporter.class) - .extracting("config") - .isSameAs(config); + DefaultConfigProperties.createFromMap(ImmutableMap.of("test.option", "true")); + + try (MetricExporter metricExporter = + MetricExporterConfiguration.configureExporter( + "testExporter", + MetricExporterConfiguration.metricExporterSpiManager(config, spiHelper))) { + assertThat(metricExporter) + .isInstanceOf(TestConfigurableMetricExporterProvider.TestMetricExporter.class) + .extracting("config") + .isSameAs(config); + assertThat(spiHelper.getListeners()) + .satisfiesExactlyInAnyOrder( + listener -> + assertThat(listener).isInstanceOf(TestConfigurableMetricExporterProvider.class), + listener -> assertThat(listener).isInstanceOf(OtlpMetricExporterProvider.class)); + } } @Test - void emptyClassLoader() { - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureExporter( - "testExporter", - DefaultConfigProperties.createForTest(Collections.emptyMap()), - new URLClassLoader(new URL[0], null), - (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("testExporter"); + void configureExporter_emptyClassLoader() { + assertThat( + MetricExporterConfiguration.configureExporter( + "testExporter", + MetricExporterConfiguration.metricExporterSpiManager( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + SpiHelper.create(new URLClassLoader(new URL[] {}, null))))) + .isNull(); } @Test - void exporterNotFound() { - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureExporter( - "catExporter", - DefaultConfigProperties.createForTest(Collections.emptyMap()), - MetricExporterConfiguration.class.getClassLoader(), - (a, unused) -> a)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("catExporter"); + void configureExporter_exporterNotFound() { + assertThat( + MetricExporterConfiguration.configureExporter( + "catExporter", + MetricExporterConfiguration.metricExporterSpiManager( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), spiHelper))) + .isNull(); } @Test - void configureMetricExporters_multipleWithNone() { + void configureMetricReaders_multipleWithNone() { ConfigProperties config = - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( ImmutableMap.of("otel.metrics.exporter", "otlp,none")); + List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - MeterProviderConfiguration.configureMeterProvider( - SdkMeterProvider.builder(), - config, - MetricExporterConfiguration.class.getClassLoader(), - (a, unused) -> a)) + assertThatThrownBy(() -> + MeterProviderConfiguration.configureMetricReaders( + config, spiHelper, (a, unused) -> a, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.metrics.exporter contains none along with other exporters"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); + assertThat(spiHelper.getListeners()).isEmpty(); } @Test - void defaultExporter() { - ConfigProperties config = DefaultConfigProperties.createForTest(Collections.emptyMap()); + void configureMetricReaders_defaultExporter() { + ConfigProperties config = DefaultConfigProperties.createFromMap(Collections.emptyMap()); + List closeables = new ArrayList<>(); - assertThat( - MeterProviderConfiguration.configureMetricReaders( - config, - MeterProviderConfiguration.class.getClassLoader(), - (metricExporter, unused) -> metricExporter)) - .hasSize(1) - .first() - .isInstanceOf(PeriodicMetricReader.class) - .extracting("exporter") - .isInstanceOf(OtlpGrpcMetricExporter.class) - .satisfies( - metricExporter -> - ((OtlpGrpcMetricExporter) metricExporter).shutdown().join(10, TimeUnit.SECONDS)); + List metricReaders = + MeterProviderConfiguration.configureMetricReaders( + config, + spiHelper, + (a, unused) -> a, + (metricExporter, unused) -> metricExporter, + closeables); + cleanup.addCloseables(closeables); + + assertThat(metricReaders) + .satisfiesExactly(metricReader -> + assertThat(metricReader) + .isInstanceOf(PeriodicMetricReader.class) + .extracting("exporter") + .isInstanceOf(OtlpGrpcMetricExporter.class)); + assertThat(closeables) + .hasExactlyElementsOfTypes(OtlpGrpcMetricExporter.class, PeriodicMetricReader.class); } @Test - void configureMultipleMetricExporters() { + void configureMetricReaders_multipleExporters() { ConfigProperties config = - DefaultConfigProperties.createForTest( - ImmutableMap.of("otel.metrics.exporter", "otlp,prometheus")); + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.metrics.exporter", "otlp,logging")); + List closeables = new ArrayList<>(); - assertThat( - MeterProviderConfiguration.configureMetricReaders( - config, - MeterProviderConfiguration.class.getClassLoader(), - (metricExporter, unused) -> metricExporter)) - .hasSize(2) - .hasAtLeastOneElementOfType(PeriodicMetricReader.class) - .hasAtLeastOneElementOfType(PrometheusHttpServer.class) - .allSatisfy(metricReader -> metricReader.shutdown().join(10, TimeUnit.SECONDS)); + List metricReaders = + MeterProviderConfiguration.configureMetricReaders( + config, + spiHelper, + (a, unused) -> a, + (metricExporter, unused) -> metricExporter, + closeables); + cleanup.addCloseables(closeables); + + assertThat(metricReaders).hasSize(2).hasOnlyElementsOfType(PeriodicMetricReader.class); + assertThat(closeables) + .hasSize(4) + .hasOnlyElementsOfTypes( + PeriodicMetricReader.class, LoggingMetricExporter.class, OtlpGrpcMetricExporter.class); } } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSamplerTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSamplerTest.java deleted file mode 100644 index c61f94f90b3..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSamplerTest.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.Collections; -import org.junit.jupiter.api.Test; - -public class ConfigurableSamplerTest { - - @Test - void configuration() { - ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("test.option", "true")); - Sampler sampler = - TracerProviderConfiguration.configureSampler( - "testSampler", config, TracerProviderConfiguration.class.getClassLoader()); - - assertThat(sampler) - .isInstanceOfSatisfying( - TestConfigurableSamplerProvider.TestSampler.class, - s -> assertThat(s.getConfig()).isSameAs(config)); - } - - @Test - void emptyClassLoader() { - ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("test.option", "true")); - assertThatThrownBy( - () -> - TracerProviderConfiguration.configureSampler( - "testSampler", config, new URLClassLoader(new URL[0], null))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("testSampler"); - } - - @Test - void samplerNotFound() { - assertThatThrownBy( - () -> - TracerProviderConfiguration.configureSampler( - "catSampler", - DefaultConfigProperties.createForTest(Collections.emptyMap()), - TracerProviderConfiguration.class.getClassLoader())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("catSampler"); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java index 3f5e3d59279..9ee26ec2365 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ConfigurableSpanExporterTest.java @@ -11,33 +11,51 @@ import com.google.common.collect.ImmutableMap; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.exporter.otlp.internal.OtlpSpanExporterProvider; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; -import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableSpanExporterProvider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.Closeable; import java.net.URL; import java.net.URLClassLoader; +import java.util.ArrayList; import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; -public class ConfigurableSpanExporterTest { +@SuppressWarnings("deprecation") // testing deprecated code +class ConfigurableSpanExporterTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final SpiHelper spiHelper = + SpiHelper.create(ConfigurableSpanExporterTest.class.getClassLoader()); @Test void configureSpanExporters_spiExporter() { ConfigProperties config = - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( ImmutableMap.of("test.option", "true", "otel.traces.exporter", "testExporter")); + List closeables = new ArrayList<>(); + Map exportersByName = SpanExporterConfiguration.configureSpanExporters( - config, - SpanExporterConfiguration.class.getClassLoader(), - MeterProvider.noop(), - (a, unused) -> a); + config, spiHelper, (a, unused) -> a, closeables); + cleanup.addCloseables(closeables); assertThat(exportersByName) .hasSize(1) @@ -46,150 +64,175 @@ void configureSpanExporters_spiExporter() { .isInstanceOf(TestConfigurableSpanExporterProvider.TestSpanExporter.class) .extracting("config") .isSameAs(config); + assertThat(closeables) + .hasExactlyElementsOfTypes(TestConfigurableSpanExporterProvider.TestSpanExporter.class); + assertThat(spiHelper.getListeners()) + .satisfiesExactlyInAnyOrder( + listener -> + assertThat(listener).isInstanceOf(TestConfigurableSpanExporterProvider.class), + listener -> assertThat(listener).isInstanceOf(OtlpSpanExporterProvider.class)); } @Test void configureSpanExporters_emptyClassLoader() { ConfigProperties config = - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( ImmutableMap.of("test.option", "true", "otel.traces.exporter", "testExporter")); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureSpanExporters( - config, - new URLClassLoader(new URL[0], null), - MeterProvider.noop(), - (a, unused) -> a)) + List closeables = new ArrayList<>(); + + assertThatThrownBy(() -> + SpanExporterConfiguration.configureSpanExporters( + config, + SpiHelper.create(new URLClassLoader(new URL[0], null)), + (a, unused) -> a, + new ArrayList<>())) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("testExporter"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); + assertThat(spiHelper.getListeners()).isEmpty(); } @Test void configureSpanExporters_duplicates() { ConfigProperties config = - DefaultConfigProperties.createForTest( + DefaultConfigProperties.createFromMap( ImmutableMap.of("otel.traces.exporter", "otlp,otlp,logging")); + List closeables = new ArrayList<>(); - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureSpanExporters( - config, - SpanExporterConfiguration.class.getClassLoader(), - MeterProvider.noop(), - (a, unused) -> a)) + assertThatThrownBy(() -> + SpanExporterConfiguration.configureSpanExporters( + config, spiHelper, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.traces.exporter contains duplicates: [otlp]"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); } @Test void configureSpanExporters_multipleWithNone() { ConfigProperties config = - DefaultConfigProperties.createForTest(ImmutableMap.of("otel.traces.exporter", "otlp,none")); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureSpanExporters( - config, - SpanExporterConfiguration.class.getClassLoader(), - MeterProvider.noop(), - (a, unused) -> a)) + DefaultConfigProperties.createFromMap(ImmutableMap.of("otel.traces.exporter", "otlp,none")); + List closeables = new ArrayList<>(); + + assertThatThrownBy(() -> + SpanExporterConfiguration.configureSpanExporters( + config, spiHelper, (a, unused) -> a, closeables)) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("otel.traces.exporter contains none along with other exporters"); + cleanup.addCloseables(closeables); + assertThat(closeables).isEmpty(); } @Test - void exporterNotFound() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "catExporter", - DefaultConfigProperties.createForTest(Collections.emptyMap()), - NamedSpiManager.createEmpty(), - MeterProvider.noop())) + void configureExporter_NotFound() { + assertThatThrownBy(() -> + SpanExporterConfiguration.configureExporter( + "catExporter", NamedSpiManager.createEmpty())) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("catExporter"); } @Test void configureSpanProcessors_simpleSpanProcessor() { - String exporterName = "logging"; - Map propMap = Collections.singletonMap("otel.traces.exporter", exporterName); - SpanExporter exporter = LoggingSpanExporter.create(); - ConfigProperties properties = DefaultConfigProperties.createForTest(propMap); - - assertThat( - TracerProviderConfiguration.configureSpanProcessors( - properties, ImmutableMap.of(exporterName, exporter), MeterProvider.noop())) - .hasSize(1) - .first() - .isInstanceOf(SimpleSpanProcessor.class); + List closeables = new ArrayList<>(); + + Map exportersByName = new LinkedHashMap<>(); + exportersByName.put("console", LoggingSpanExporter.create()); + exportersByName.put("logging", LoggingSpanExporter.create()); + + List spanProcessors = + TracerProviderConfiguration.configureSpanProcessors( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.traces.exporter", "console,logging")), + exportersByName, + InternalTelemetryVersion.LEGACY, + MeterProvider.noop(), + closeables); + cleanup.addCloseables(closeables); + + assertThat(spanProcessors) + .hasExactlyElementsOfTypes(SimpleSpanProcessor.class, SimpleSpanProcessor.class); + assertThat(closeables) + .hasExactlyElementsOfTypes(SimpleSpanProcessor.class, SimpleSpanProcessor.class); } @Test void configureSpanProcessors_batchSpanProcessor() { - String exporterName = "zipkin"; - Map propMap = Collections.singletonMap("otel.traces.exporter", exporterName); - SpanExporter exporter = ZipkinSpanExporter.builder().build(); - ConfigProperties properties = DefaultConfigProperties.createForTest(propMap); - - assertThat( - TracerProviderConfiguration.configureSpanProcessors( - properties, ImmutableMap.of(exporterName, exporter), MeterProvider.noop())) - .hasSize(1) - .first() - .isInstanceOf(BatchSpanProcessor.class); + String exporterName = "noop"; + List closeables = new ArrayList<>(); + + List spanProcessors = + TracerProviderConfiguration.configureSpanProcessors( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.traces.exporter", exporterName)), + ImmutableMap.of(exporterName, SpanExporter.noop()), + InternalTelemetryVersion.LEGACY, + MeterProvider.noop(), + closeables); + cleanup.addCloseables(closeables); + + assertThat(spanProcessors).hasExactlyElementsOfTypes(BatchSpanProcessor.class); + assertThat(closeables).hasExactlyElementsOfTypes(BatchSpanProcessor.class); } @Test void configureSpanProcessors_multipleExporters() { - SpanExporter otlpExporter = OtlpGrpcSpanExporter.builder().build(); - SpanExporter zipkinExporter = ZipkinSpanExporter.builder().build(); - ConfigProperties properties = - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.traces.exporter", "otlp,zipkin")); - - assertThat( - TracerProviderConfiguration.configureSpanProcessors( - properties, - ImmutableMap.of("otlp", otlpExporter, "zipkin", zipkinExporter), - MeterProvider.noop())) - .hasSize(1) - .hasAtLeastOneElementOfType(BatchSpanProcessor.class) + List closeables = new ArrayList<>(); + + List spanProcessors = + TracerProviderConfiguration.configureSpanProcessors( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.traces.exporter", "otlp,noop")), + ImmutableMap.of( + "otlp", OtlpGrpcSpanExporter.builder().build(), "noop", SpanExporter.noop()), + InternalTelemetryVersion.LEGACY, + MeterProvider.noop(), + closeables); + cleanup.addCloseables(closeables); + + assertThat(spanProcessors) + .hasExactlyElementsOfTypes(BatchSpanProcessor.class) .first() .extracting("worker") .extracting("spanExporter") .asInstanceOf(InstanceOfAssertFactories.type(SpanExporter.class)) - .satisfies( - spanExporter -> { - assertThat(spanExporter) - .extracting(spanExporter1 -> spanExporter1.getClass().getSimpleName()) - .isEqualTo("MultiSpanExporter"); - assertThat(spanExporter) - .extracting("spanExporters") - .asInstanceOf(InstanceOfAssertFactories.type(SpanExporter[].class)) - .satisfies( - spanExporters -> { - assertThat(spanExporters.length).isEqualTo(2); - assertThat(spanExporters) - .hasAtLeastOneElementOfType(ZipkinSpanExporter.class) - .hasAtLeastOneElementOfType(OtlpGrpcSpanExporter.class); - }); - }); + .satisfies(spanExporter -> { + assertThat(spanExporter) + .extracting(spanExporter1 -> spanExporter1.getClass().getSimpleName()) + .isEqualTo("MultiSpanExporter"); + assertThat(spanExporter) + .extracting("spanExporters") + .asInstanceOf(InstanceOfAssertFactories.type(SpanExporter[].class)) + .satisfies(spanExporters -> { + assertThat(spanExporters.length).isEqualTo(2); + assertThat(spanExporters) + .hasAtLeastOneElementOfType(SpanExporter.noop().getClass()) + .hasAtLeastOneElementOfType(OtlpGrpcSpanExporter.class); + }); + }); + assertThat(closeables).hasExactlyElementsOfTypes(BatchSpanProcessor.class); } @Test void configureSpanProcessors_multipleExportersWithLogging() { - SpanExporter loggingExporter = LoggingSpanExporter.create(); - SpanExporter zipkinExporter = ZipkinSpanExporter.builder().build(); - ConfigProperties properties = - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.traces.exporter", "logging,zipkin")); - - assertThat( - TracerProviderConfiguration.configureSpanProcessors( - properties, - ImmutableMap.of("logging", loggingExporter, "zipkin", zipkinExporter), - MeterProvider.noop())) + List closeables = new ArrayList<>(); + + List spanProcessors = + TracerProviderConfiguration.configureSpanProcessors( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.traces.exporter", "logging,noop")), + ImmutableMap.of("logging", LoggingSpanExporter.create(), "noop", SpanExporter.noop()), + InternalTelemetryVersion.LEGACY, + MeterProvider.noop(), + closeables); + cleanup.addCloseables(closeables); + + assertThat(spanProcessors) + .hasSize(2) + .hasAtLeastOneElementOfType(SimpleSpanProcessor.class) + .hasAtLeastOneElementOfType(BatchSpanProcessor.class); + assertThat(closeables) .hasSize(2) .hasAtLeastOneElementOfType(SimpleSpanProcessor.class) .hasAtLeastOneElementOfType(BatchSpanProcessor.class); diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FreePortFinder.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FreePortFinder.java new file mode 100644 index 00000000000..92c2b7640c7 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FreePortFinder.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import java.io.IOException; +import java.net.ServerSocket; + +final class FreePortFinder { + + static int getFreePort() { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private FreePortFinder() {} +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java index 53c72a3c31e..3cfc260edcd 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/FullConfigTest.java @@ -18,9 +18,10 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; -import io.opentelemetry.extension.aws.AwsXrayPropagator; import io.opentelemetry.extension.trace.propagation.B3Propagator; import io.opentelemetry.extension.trace.propagation.JaegerPropagator; import io.opentelemetry.extension.trace.propagation.OtTracePropagator; @@ -35,25 +36,24 @@ import io.opentelemetry.proto.collector.trace.v1.TraceServiceGrpc; import io.opentelemetry.proto.common.v1.AnyValue; import io.opentelemetry.proto.common.v1.KeyValue; -import io.opentelemetry.proto.logs.v1.LogRecord; import io.opentelemetry.proto.metrics.v1.Metric; -import io.opentelemetry.proto.metrics.v1.ResourceMetrics; import io.opentelemetry.proto.metrics.v1.ScopeMetrics; -import io.opentelemetry.sdk.logs.LogEmitter; -import io.opentelemetry.sdk.logs.data.Severity; +import io.opentelemetry.proto.trace.v1.Span; +import io.opentelemetry.sdk.OpenTelemetrySdk; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @SuppressWarnings("InterruptedExceptionSwallowed") -class FullConfigTest { +public class FullConfigTest { private static final BlockingQueue otlpTraceRequests = new LinkedBlockingDeque<>(); @@ -143,7 +143,7 @@ public void export( } }; - private AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk; + private OpenTelemetrySdk openTelemetrySdk; @BeforeEach void setUp() { @@ -154,31 +154,23 @@ void setUp() { String endpoint = "http://localhost:" + server.httpPort(); System.setProperty("otel.exporter.otlp.endpoint", endpoint); System.setProperty("otel.exporter.otlp.timeout", "10000"); + // Set log exporter interval to a high value and rely on flushing to produce reliable export + // batches + System.setProperty("otel.blrp.schedule.delay", "60000"); - // Initialize here so we get SdkLogEmitterProvider and shutdown when done - autoConfiguredOpenTelemetrySdk = AutoConfiguredOpenTelemetrySdk.initialize(); + // Initialize here so we can shutdown when done + GlobalOpenTelemetry.resetForTest(); + openTelemetrySdk = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); } @AfterEach void afterEach() { - autoConfiguredOpenTelemetrySdk - .getOpenTelemetrySdk() - .getSdkMeterProvider() - .shutdown() - .join(10, TimeUnit.SECONDS); - autoConfiguredOpenTelemetrySdk - .getOpenTelemetrySdk() - .getSdkLogEmitterProvider() - .shutdown() - .join(10, TimeUnit.SECONDS); - autoConfiguredOpenTelemetrySdk - .getOpenTelemetrySdk() - .getSdkTracerProvider() - .shutdown() - .join(10, TimeUnit.SECONDS); + openTelemetrySdk.close(); + GlobalOpenTelemetry.resetForTest(); } @Test + @SuppressWarnings("deprecation") void configures() throws Exception { Collection fields = GlobalOpenTelemetry.get().getPropagators().getTextMapPropagator().fields(); @@ -189,7 +181,6 @@ void configures() throws Exception { keys.addAll(B3Propagator.injectingMultiHeaders().fields()); keys.addAll(JaegerPropagator.getInstance().fields()); keys.addAll(OtTracePropagator.getInstance().fields()); - keys.addAll(AwsXrayPropagator.getInstance().fields()); // Added by TestPropagatorProvider keys.add("test"); assertThat(fields).containsExactlyInAnyOrderElementsOf(keys); @@ -201,7 +192,6 @@ void configures() throws Exception { .spanBuilder("test") .startSpan() .setAttribute("cat", "meow") - .setAttribute("dog", "bark") .end(); Meter meter = GlobalOpenTelemetry.get().getMeter("test"); @@ -211,99 +201,159 @@ void configures() throws Exception { .add(1, Attributes.builder().put("allowed", "bear").put("not allowed", "dog").build()); meter.counterBuilder("my-other-metric").build().add(1); - LogEmitter logEmitter = - autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk().getSdkLogEmitterProvider().get("test"); - logEmitter.logBuilder().setBody("debug log message").setSeverity(Severity.DEBUG).emit(); - logEmitter.logBuilder().setBody("info log message").setSeverity(Severity.INFO).emit(); + Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("test"); + logger.logRecordBuilder().setBody("debug log message").setSeverity(Severity.DEBUG).emit(); + logger.logRecordBuilder().setBody("info log message").setSeverity(Severity.INFO).emit(); + + openTelemetrySdk.getSdkTracerProvider().forceFlush().join(10, TimeUnit.SECONDS); + openTelemetrySdk.getSdkLoggerProvider().forceFlush().join(10, TimeUnit.SECONDS); + openTelemetrySdk.getSdkMeterProvider().forceFlush().join(10, TimeUnit.SECONDS); await().untilAsserted(() -> assertThat(otlpTraceRequests).hasSize(1)); ExportTraceServiceRequest traceRequest = otlpTraceRequests.take(); - assertThat(traceRequest.getResourceSpans(0).getResource().getAttributesList()) - .contains( - KeyValue.newBuilder() - .setKey("service.name") - .setValue(AnyValue.newBuilder().setStringValue("test").build()) - .build(), - KeyValue.newBuilder() - .setKey("cat") - .setValue(AnyValue.newBuilder().setStringValue("meow").build()) - .build()); - io.opentelemetry.proto.trace.v1.Span span = - traceRequest.getResourceSpans(0).getScopeSpans(0).getSpans(0); - // Dog dropped by attribute limit. - assertThat(span.getAttributesList()) - .containsExactlyInAnyOrder( - KeyValue.newBuilder() - .setKey("configured") - .setValue(AnyValue.newBuilder().setBoolValue(true).build()) - .build(), - KeyValue.newBuilder() - .setKey("wrapped") - .setValue(AnyValue.newBuilder().setIntValue(1).build()) - .build(), - KeyValue.newBuilder() - .setKey("cat") - .setValue(AnyValue.newBuilder().setStringValue("meow").build()) - .build()); + List spanResourceAttributes = + traceRequest.getResourceSpans(0).getResource().getAttributesList(); + assertHasKeyValue(spanResourceAttributes, "service.name", "test"); + assertHasKeyValue(spanResourceAttributes, "cat", "meow"); + Span span = traceRequest.getResourceSpans(0).getScopeSpans(0).getSpans(0); + assertHasKeyValue(span.getAttributesList(), "configured", true); + assertHasKeyValue(span.getAttributesList(), "wrapped", 1); + assertHasKeyValue(span.getAttributesList(), "cat", "meow"); + assertHasKeyValue(span.getAttributesList(), "extra-key", "extra-value"); + // Flush again to get metric exporter metrics. + openTelemetrySdk.getSdkMeterProvider().forceFlush().join(10, TimeUnit.SECONDS); // await on assertions since metrics may come in different order for BatchSpanProcessor, - // exporter, or the ones we - // created in the test. + // exporter, or the ones we created in the test. await() - .untilAsserted( - () -> { - ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); - assertThat(metricRequest.getResourceMetrics(0).getResource().getAttributesList()) - .contains( - KeyValue.newBuilder() - .setKey("service.name") - .setValue(AnyValue.newBuilder().setStringValue("test").build()) - .build(), - KeyValue.newBuilder() - .setKey("cat") - .setValue(AnyValue.newBuilder().setStringValue("meow").build()) - .build()); + .untilAsserted(() -> { + ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); - for (ResourceMetrics resourceMetrics : metricRequest.getResourceMetricsList()) { + assertThat(metricRequest.getResourceMetricsList()) + .satisfiesExactly(resourceMetrics -> { + List metricResourceAttributes = + resourceMetrics.getResource().getAttributesList(); + assertHasKeyValue(metricResourceAttributes, "service.name", "test"); + assertHasKeyValue(metricResourceAttributes, "cat", "meow"); assertThat(resourceMetrics.getScopeMetricsList()) - .anySatisfy(ilm -> assertThat(ilm.getScope().getName()).isEqualTo("test")); - for (ScopeMetrics instrumentationLibraryMetrics : - resourceMetrics.getScopeMetricsList()) { - for (Metric metric : instrumentationLibraryMetrics.getMetricsList()) { - // SPI was loaded - // MetricExporterCustomizer filters metrics not named my-metric - assertThat(metric.getName()).isEqualTo("my-metric"); - // TestMeterProviderConfigurer configures a view that only passes on attribute - // named allowed - // configured-test - assertThat(getFirstDataPointLabels(metric)) - .contains( - KeyValue.newBuilder() - .setKey("allowed") - .setValue(AnyValue.newBuilder().setStringValue("bear").build()) - .build()); - } - } - } - }); + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()).isEqualTo("test"); + assertThat(scopeMetrics.getMetricsList()) + .satisfiesExactly(metric -> { + // SPI was loaded + assertThat(metric.getName()).isEqualTo("my-metric"); + // TestMeterProviderConfigurer configures a view that + // only passes an attribute named "allowed" + // configured-test + assertHasKeyValue(getFirstDataPointLabels(metric), "allowed", "bear"); + }); + }) + // This verifies that AutoConfigureListener was invoked and the OTLP + // span / log exporters received the autoconfigured OpenTelemetrySdk + // instance as well as setting telemetry version. + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_metric_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.metric_data_point.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.metric_data_point.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_log_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.log.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.log.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_span_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.span.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.span.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.logs"); + assertMetricNames( + scopeMetrics, + "otel.sdk.log.created", + "otel.sdk.processor.log.processed", + "otel.sdk.processor.log.queue.capacity", + "otel.sdk.processor.log.queue.size"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.trace"); + assertMetricNames( + scopeMetrics, + "otel.sdk.span.live", + "otel.sdk.span.started", + "otel.sdk.processor.span.processed", + "otel.sdk.processor.span.queue.capacity", + "otel.sdk.processor.span.queue.size"); + }); + }); + }); await().untilAsserted(() -> assertThat(otlpLogsRequests).hasSize(1)); ExportLogsServiceRequest logRequest = otlpLogsRequests.take(); - assertThat(logRequest.getResourceLogs(0).getResource().getAttributesList()) + List logResourceAttributes = + logRequest.getResourceLogs(0).getResource().getAttributesList(); + assertHasKeyValue(logResourceAttributes, "service.name", "test"); + assertHasKeyValue(logResourceAttributes, "cat", "meow"); + + assertThat(logRequest.getResourceLogs(0).getScopeLogs(0).getLogRecordsList()) + // LogRecordCustomizer customizes BatchLogProcessor to add an extra attribute on every log + // record + .allSatisfy(logRecord -> + assertHasKeyValue(logRecord.getAttributesList(), "extra-key", "extra-value")) + .satisfiesExactlyInAnyOrder(logRecord -> { + // LogRecordCustomizer filters logs not whose level is less than Severity.INFO + assertThat(logRecord.getBody().getStringValue()).isEqualTo("info log message"); + assertThat(logRecord.getSeverityNumberValue()) + .isEqualTo(Severity.INFO.getSeverityNumber()); + }); + } + + private static void assertHasKeyValue(List keyValues, String key, boolean value) { + assertThat(keyValues) .contains( KeyValue.newBuilder() - .setKey("service.name") - .setValue(AnyValue.newBuilder().setStringValue("test").build()) - .build(), + .setKey(key) + .setValue(AnyValue.newBuilder().setBoolValue(value)) + .build()); + } + + private static void assertHasKeyValue(List keyValues, String key, long value) { + assertThat(keyValues) + .contains( KeyValue.newBuilder() - .setKey("cat") - .setValue(AnyValue.newBuilder().setStringValue("meow").build()) + .setKey(key) + .setValue(AnyValue.newBuilder().setIntValue(value)) .build()); - // MetricExporterCustomizer filters logs not whose level is less than Severity.INFO - LogRecord log = logRequest.getResourceLogs(0).getScopeLogs(0).getLogRecords(0); - assertThat(log.getBody().getStringValue()).isEqualTo("info log message"); - assertThat(log.getSeverityNumberValue()).isEqualTo(Severity.INFO.getSeverityNumber()); + } + + private static void assertHasKeyValue(List keyValues, String key, String value) { + assertThat(keyValues) + .contains( + KeyValue.newBuilder() + .setKey(key) + .setValue(AnyValue.newBuilder().setStringValue(value)) + .build()); + } + + private static void assertMetricNames(ScopeMetrics scopeMetrics, String... names) { + assertThat( + scopeMetrics.getMetricsList().stream().map(Metric::getName).collect(Collectors.toSet())) + .containsExactlyInAnyOrder(names); } private static List getFirstDataPointLabels(Metric metric) { diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfigurationTest.java deleted file mode 100644 index 0eaae92a5a8..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogEmitterProviderConfigurationTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.logging.SystemOutLogExporter; -import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogExporter; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; -import io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder; -import io.opentelemetry.sdk.logs.export.BatchLogProcessor; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.logs.export.SimpleLogProcessor; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class LogEmitterProviderConfigurationTest { - - @Test - void configureLogEmitterProvider() { - Map properties = Collections.singletonMap("otel.logs.exporter", "otlp"); - - SdkLogEmitterProviderBuilder builder = SdkLogEmitterProvider.builder(); - LogEmitterProviderConfiguration.configureLogEmitterProvider( - builder, - DefaultConfigProperties.createForTest(properties), - MeterProvider.noop(), - (a, unused) -> a); - SdkLogEmitterProvider logEmitterProvider = builder.build(); - - try { - assertThat(logEmitterProvider) - .extracting("sharedState") - .satisfies( - sharedState -> - assertThat(sharedState) - .extracting("logProcessor") - .isInstanceOf(BatchLogProcessor.class) - .extracting("worker") - .satisfies( - worker -> { - assertThat(worker) - .extracting("scheduleDelayNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(200)); - assertThat(worker) - .extracting("exporterTimeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); - assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); - assertThat(worker) - .extracting("queue") - .isInstanceOfSatisfying( - ArrayBlockingQueue.class, - queue -> assertThat(queue.remainingCapacity()).isEqualTo(2048)); - })); - } finally { - logEmitterProvider.shutdown(); - } - } - - @Test - void configureSpanProcessors_multipleExportersWithLogging() { - LogExporter loggingExporter = SystemOutLogExporter.create(); - LogExporter otlpExporter = OtlpGrpcLogExporter.builder().build(); - - assertThat( - LogEmitterProviderConfiguration.configureLogProcessors( - ImmutableMap.of("logging", loggingExporter, "otlp", otlpExporter), - MeterProvider.noop())) - .hasSize(2) - .hasAtLeastOneElementOfType(SimpleLogProcessor.class) - .hasAtLeastOneElementOfType(BatchLogProcessor.class); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogExporterCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogExporterCustomizer.java deleted file mode 100644 index 7b2ac4e2c6b..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogExporterCustomizer.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; -import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.logs.export.LogExporter; -import java.util.Collection; -import java.util.stream.Collectors; - -public class LogExporterCustomizer implements AutoConfigurationCustomizerProvider { - @Override - public void customize(AutoConfigurationCustomizer autoConfiguration) { - autoConfiguration.addLogExporterCustomizer( - (delegate, config) -> - new LogExporter() { - @Override - public CompletableResultCode export(Collection logs) { - Collection filtered = - logs.stream() - .filter( - log -> - log.getSeverity().getSeverityNumber() - >= Severity.INFO.getSeverityNumber()) - .collect(Collectors.toList()); - return delegate.export(filtered); - } - - @Override - public CompletableResultCode flush() { - return delegate.flush(); - } - - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } - }); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java new file mode 100644 index 00000000000..de9b275bb1a --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LogRecordExporterConfigurationTest.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.exporter.logging.SystemOutLogRecordExporter; +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingLogRecordExporter; +import io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class LogRecordExporterConfigurationTest { + + private final SpiHelper spiHelper = + SpiHelper.create(LogRecordExporterConfigurationTest.class.getClassLoader()); + + @Test + void configureExporter_KnownSpiExportersOnClasspath() { + NamedSpiManager spiExportersManager = + LogRecordExporterConfiguration.logRecordExporterSpiManager( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), spiHelper); + + assertThat(LogRecordExporterConfiguration.configureExporter("console", spiExportersManager)) + .isInstanceOf(SystemOutLogRecordExporter.class); + assertThat(LogRecordExporterConfiguration.configureExporter("logging", spiExportersManager)) + .isInstanceOf(SystemOutLogRecordExporter.class); + assertThat( + LogRecordExporterConfiguration.configureExporter("logging-otlp", spiExportersManager)) + .isInstanceOf(OtlpJsonLoggingLogRecordExporter.class); + assertThat( + LogRecordExporterConfiguration.configureExporter( + "experimental-otlp/stdout", spiExportersManager)) + .isInstanceOf(OtlpStdoutLogRecordExporter.class); + assertThat(LogRecordExporterConfiguration.configureExporter("otlp", spiExportersManager)) + .isInstanceOf(OtlpGrpcLogRecordExporter.class); + } + + @Test + void configureExporter_UnsupportedOtlpProtocol() { + assertThatThrownBy(() -> + LogRecordExporterConfiguration.configureExporter( + "otlp", + LogRecordExporterConfiguration.logRecordExporterSpiManager( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), + spiHelper))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unsupported OTLP logs protocol: foo"); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java new file mode 100644 index 00000000000..1e64a151538 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/LoggerProviderConfigurationTest.java @@ -0,0 +1,149 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.exporter.logging.SystemOutLogRecordExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class LoggerProviderConfigurationTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + @Test + void configureLoggerProvider() { + List closeables = new ArrayList<>(); + + SdkLoggerProviderBuilder builder = SdkLoggerProvider.builder(); + LoggerProviderConfiguration.configureLoggerProvider( + builder, + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + SpiHelper.create(LoggerProviderConfiguration.class.getClassLoader()), + MeterProvider.noop(), + (a, unused) -> a, + (a, unused) -> a, + closeables); + cleanup.addCloseables(closeables); + + try (SdkLoggerProvider loggerProvider = builder.build()) { + assertThat(loggerProvider) + .extracting("sharedState") + .satisfies(sharedState -> + assertThat(sharedState) + .extracting("logRecordProcessor") + .isInstanceOf(BatchLogRecordProcessor.class) + .extracting("worker") + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.SECONDS.toNanos(1)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(30000)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(512); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + ArrayBlockingQueue.class, + queue -> assertThat(queue.remainingCapacity()).isEqualTo(2048)); + })); + assertThat(closeables) + .hasExactlyElementsOfTypes( + OtlpGrpcLogRecordExporter.class, BatchLogRecordProcessor.class); + } + } + + @Test + void configureLogRecordProcessors_multipleExportersWithLogging() { + List closeables = new ArrayList<>(); + + Map exportersByName = new LinkedHashMap<>(); + exportersByName.put("console", SystemOutLogRecordExporter.create()); + exportersByName.put("logging", SystemOutLogRecordExporter.create()); + exportersByName.put("otlp", OtlpGrpcLogRecordExporter.builder().build()); + + List logRecordProcessors = + LoggerProviderConfiguration.configureLogRecordProcessors( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + exportersByName, + InternalTelemetryVersion.LEGACY, + MeterProvider.noop(), + closeables); + cleanup.addCloseables(closeables); + + assertThat(logRecordProcessors) + .hasSize(3) + .hasExactlyElementsOfTypes( + SimpleLogRecordProcessor.class, + SimpleLogRecordProcessor.class, + BatchLogRecordProcessor.class); + assertThat(closeables) + .hasSize(3) + .hasExactlyElementsOfTypes( + SimpleLogRecordProcessor.class, + SimpleLogRecordProcessor.class, + BatchLogRecordProcessor.class); + } + + @Test + void configureBatchLogRecordProcessor() { + Map properties = new HashMap<>(); + properties.put("otel.blrp.schedule.delay", "100000"); + properties.put("otel.blrp.max.queue.size", "2"); + properties.put("otel.blrp.max.export.batch.size", "2"); + properties.put("otel.blrp.export.timeout", "4"); + + try (BatchLogRecordProcessor processor = + LoggerProviderConfiguration.configureBatchLogRecordProcessor( + DefaultConfigProperties.createFromMap(properties), + SystemOutLogRecordExporter.create(), + InternalTelemetryVersion.LEGACY, + MeterProvider.noop())) { + assertThat(processor) + .extracting("worker") + .satisfies(worker -> { + assertThat(worker) + .extracting("scheduleDelayNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(100000)); + assertThat(worker) + .extracting("exporterTimeoutNanos") + .isEqualTo(TimeUnit.MILLISECONDS.toNanos(4)); + assertThat(worker).extracting("maxExportBatchSize").isEqualTo(2); + assertThat(worker) + .extracting("queue") + .isInstanceOfSatisfying( + ArrayBlockingQueue.class, + queue -> assertThat(queue.remainingCapacity()).isEqualTo(2)); + assertThat(worker) + .extracting("logRecordExporter") + .isInstanceOf(SystemOutLogRecordExporter.class); + }); + } + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java new file mode 100644 index 00000000000..2a8a31a5dac --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MeterProviderConfigurationTest.java @@ -0,0 +1,107 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class MeterProviderConfigurationTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final SpiHelper spiHelper = + SpiHelper.create(MeterProviderConfigurationTest.class.getClassLoader()); + + @Test + void configureMeterProvider_InvalidCardinalityLimit() { + List closeables = new ArrayList<>(); + + assertThatThrownBy( + () -> { + MeterProviderConfiguration.configureMeterProvider( + SdkMeterProvider.builder(), + DefaultConfigProperties.createFromMap( + ImmutableMap.of( + "otel.metrics.exporter", + "logging", + "otel.java.metrics.cardinality.limit", + "0")), + spiHelper, + (a, b) -> a, + (a, b) -> a, + closeables); + }) + .isInstanceOf(ConfigurationException.class) + .hasMessage("otel.java.metrics.cardinality.limit must be >= 1"); + cleanup.addCloseables(closeables); + } + + @Test + void configureMeterProvider_ConfiguresCardinalityLimit() { + List closeables = new ArrayList<>(); + + // Verify default cardinality + SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); + MeterProviderConfiguration.configureMeterProvider( + builder, + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.metrics.exporter", "logging")), + spiHelper, + (a, b) -> a, + (a, b) -> a, + closeables); + cleanup.addCloseables(closeables); + assertCardinalityLimit(builder, 2000); + + // Customized limit cardinality limit to 100 + builder = SdkMeterProvider.builder(); + MeterProviderConfiguration.configureMeterProvider( + builder, + DefaultConfigProperties.createFromMap( + ImmutableMap.of( + "otel.metrics.exporter", "logging", "otel.java.metrics.cardinality.limit", "100")), + spiHelper, + (a, b) -> a, + (a, b) -> a, + closeables); + cleanup.addCloseables(closeables); + assertCardinalityLimit(builder, 100); + } + + private static void assertCardinalityLimit( + SdkMeterProviderBuilder builder, int expectedCardinalityLimit) { + assertThat(builder) + .extracting( + "metricReaders", + as(InstanceOfAssertFactories.map(MetricReader.class, CardinalityLimitSelector.class))) + .hasSizeGreaterThan(0) + .allSatisfy((metricReader, cardinalityLimitSelector) -> { + for (InstrumentType instrumentType : InstrumentType.values()) { + assertThat(cardinalityLimitSelector.getCardinalityLimit(instrumentType)) + .isEqualTo(expectedCardinalityLimit); + } + }); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java index a0bdb80102a..387dd991364 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricExporterConfigurationTest.java @@ -5,21 +5,200 @@ package io.opentelemetry.sdk.autoconfigure; +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.collect.ImmutableMap; +import io.opentelemetry.exporter.logging.LoggingMetricExporter; +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.prometheus.metrics.exporter.httpserver.HTTPServer; +import java.io.Closeable; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.BiFunction; +import java.util.stream.Stream; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -public class MetricExporterConfigurationTest { +class MetricExporterConfigurationTest { + + private static final ConfigProperties CONFIG_PROPERTIES = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.prometheus.port", "0")); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final SpiHelper spiHelper = + SpiHelper.create(MetricExporterConfigurationTest.class.getClassLoader()); + + @Test + void configureReader_PrometheusOnClasspath() { + List closeables = new ArrayList<>(); + + MetricReader reader = + MetricExporterConfiguration.configureReader( + "prometheus", CONFIG_PROPERTIES, spiHelper, (a, b) -> a, (a, b) -> a, closeables); + cleanup.addCloseables(closeables); + + assertThat(reader).isInstanceOf(PrometheusHttpServer.class); + assertThat(closeables).hasSize(1); + } + + @Test + void configureReader_customizeReader_prometheus() { + List closeables = new ArrayList<>(); + + int port = FreePortFinder.getFreePort(); + BiFunction readerCustomizer = + (existingReader, config) -> PrometheusHttpServer.builder().setPort(port).build(); + MetricReader reader = + MetricExporterConfiguration.configureReader( + "prometheus", CONFIG_PROPERTIES, spiHelper, readerCustomizer, (a, b) -> a, closeables); + cleanup.addCloseables(closeables); + + assertThat(reader).isInstanceOf(PrometheusHttpServer.class); + assertThat(closeables).hasSize(2); + PrometheusHttpServer prometheusHttpServer = (PrometheusHttpServer) reader; + assertThat(prometheusHttpServer) + .extracting("httpServer", as(InstanceOfAssertFactories.type(HTTPServer.class))) + .satisfies(httpServer -> assertThat(httpServer.getPort()).isEqualTo(port)); + } + + @Test + void configureReader_customizeReader_otlp() { + List closeables = new ArrayList<>(); + + BiFunction readerCustomizer = + (existingReader, config) -> + PeriodicMetricReader.builder(OtlpGrpcMetricExporter.builder().build()) + .setInterval(Duration.ofSeconds(123)) + .build(); + MetricReader reader = + MetricExporterConfiguration.configureReader( + "otlp", CONFIG_PROPERTIES, spiHelper, readerCustomizer, (a, b) -> a, closeables); + cleanup.addCloseables(closeables); + + assertThat(reader).isInstanceOf(PeriodicMetricReader.class); + assertThat(closeables).hasSize(3); + PeriodicMetricReader periodicMetricReader = (PeriodicMetricReader) reader; + assertThat(periodicMetricReader) + .extracting("intervalNanos") + .isEqualTo(Duration.ofSeconds(123).toNanos()); + } + + @Test + void configureReader_periodicMetricReader_defaults() { + List closeables = new ArrayList<>(); + + MetricReader reader = + MetricExporterConfiguration.configureReader( + "otlp", CONFIG_PROPERTIES, spiHelper, (a, b) -> a, (a, b) -> a, closeables); + cleanup.addCloseables(closeables); + + assertThat(reader).isInstanceOf(PeriodicMetricReader.class); + assertThat(reader).extracting("intervalNanos").isEqualTo(Duration.ofMinutes(1).toNanos()); + assertThat(reader).extracting("maxExportBatchSize").isEqualTo(0); + } + + @Test + void configureReader_periodicMetricReader_configured() { + List closeables = new ArrayList<>(); + ConfigProperties config = + DefaultConfigProperties.createFromMap( + ImmutableMap.of( + "otel.metric.export.interval", "10s", "otel.metric.export.max.batch.size", "200")); + + MetricReader reader = + MetricExporterConfiguration.configureReader( + "otlp", config, spiHelper, (a, b) -> a, (a, b) -> a, closeables); + cleanup.addCloseables(closeables); + + assertThat(reader).isInstanceOf(PeriodicMetricReader.class); + assertThat(reader).extracting("intervalNanos").isEqualTo(Duration.ofSeconds(10).toNanos()); + assertThat(reader).extracting("maxExportBatchSize").isEqualTo(200); + } + + @Test + void configureReader_periodicMetricReader_invalidMaxExportBatchSize() { + List closeables = new ArrayList<>(); + ConfigProperties config = + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.metric.export.max.batch.size", "0")); + + assertThatThrownBy(() -> + MetricExporterConfiguration.configureReader( + "otlp", config, spiHelper, (a, b) -> a, (a, b) -> a, closeables)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxExportBatchSize must be positive"); + cleanup.addCloseables(closeables); + } + + @ParameterizedTest + @MethodSource("knownExporters") + void configureExporter_KnownSpiExportersOnClasspath( + String exporterName, Class expectedExporter) { + NamedSpiManager spiExportersManager = + MetricExporterConfiguration.metricExporterSpiManager(CONFIG_PROPERTIES, spiHelper); + + MetricExporter metricExporter = + MetricExporterConfiguration.configureExporter(exporterName, spiExportersManager); + cleanup.addCloseable(metricExporter); + + assertThat(metricExporter).isInstanceOf(expectedExporter); + } + + private static Stream knownExporters() { + return Stream.of( + Arguments.argumentSet("logging", "logging", LoggingMetricExporter.class), + Arguments.argumentSet("logging-otlp", "logging-otlp", OtlpJsonLoggingMetricExporter.class), + Arguments.argumentSet("otlp", "otlp", OtlpGrpcMetricExporter.class)); + } + + @ParameterizedTest + @MethodSource("knownReaders") + void configureMetricReader_KnownSpiExportersOnClasspath( + String exporterName, Class expectedExporter) { + NamedSpiManager spiMetricReadersManager = + MetricExporterConfiguration.metricReadersSpiManager(CONFIG_PROPERTIES, spiHelper); + + MetricReader metricReader = + MetricExporterConfiguration.configureMetricReader(exporterName, spiMetricReadersManager); + cleanup.addCloseable(metricReader); + + assertThat(metricReader).isInstanceOf(expectedExporter); + } + + private static Stream knownReaders() { + return Stream.of(Arguments.argumentSet("prometheus", "prometheus", PrometheusHttpServer.class)); + } @Test void configureOtlpMetricsUnsupportedProtocol() { - assertThatThrownBy( - () -> - MetricExporterConfiguration.configureOtlpMetrics( - DefaultConfigProperties.createForTest( - ImmutableMap.of("otel.exporter.otlp.protocol", "foo")))) + assertThatThrownBy(() -> + MetricExporterConfiguration.configureExporter( + "otlp", + MetricExporterConfiguration.metricExporterSpiManager( + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), + spiHelper))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP metrics protocol: foo"); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/OtlpConfigUtilTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/OtlpConfigUtilTest.java deleted file mode 100644 index 11ada7bff32..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/OtlpConfigUtilTest.java +++ /dev/null @@ -1,366 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.DATA_TYPE_LOGS; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.DATA_TYPE_METRICS; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.DATA_TYPE_TRACES; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_GRPC; -import static io.opentelemetry.sdk.autoconfigure.OtlpConfigUtil.PROTOCOL_HTTP_PROTOBUF; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; -import org.assertj.core.api.ThrowableAssert.ThrowingCallable; -import org.junit.jupiter.api.Test; - -class OtlpConfigUtilTest { - - private static final String GENERIC_ENDPOINT_KEY = "otel.exporter.otlp.endpoint"; - private static final String TRACES_ENDPOINT_KEY = "otel.exporter.otlp.traces.endpoint"; - private static final String METRICS_ENDPOINT_KEY = "otel.exporter.otlp.metrics.endpoint"; - private static final String LOGS_ENDPOINT_KEY = "otel.exporter.otlp.logs.endpoint"; - - @Test - void getOtlpProtocolDefault() { - assertThat( - OtlpConfigUtil.getOtlpProtocol( - DATA_TYPE_TRACES, DefaultConfigProperties.createForTest(Collections.emptyMap()))) - .isEqualTo(PROTOCOL_GRPC); - - assertThat( - OtlpConfigUtil.getOtlpProtocol( - DATA_TYPE_TRACES, - DefaultConfigProperties.createForTest( - ImmutableMap.of("otel.exporter.otlp.protocol", "foo")))) - .isEqualTo("foo"); - - assertThat( - OtlpConfigUtil.getOtlpProtocol( - DATA_TYPE_TRACES, - DefaultConfigProperties.createForTest( - ImmutableMap.of( - "otel.exporter.otlp.protocol", "foo", - "otel.exporter.otlp.traces.protocol", "bar")))) - .isEqualTo("bar"); - } - - @Test - void configureOtlpExporterBuilder_ValidEndpoints() { - assertThatCode( - configureEndpointCallable( - ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317"))) - .doesNotThrowAnyException(); - assertThatCode( - configureEndpointCallable( - ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317/"))) - .doesNotThrowAnyException(); - assertThatCode( - configureEndpointCallable(ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost"))) - .doesNotThrowAnyException(); - assertThatCode( - configureEndpointCallable(ImmutableMap.of(GENERIC_ENDPOINT_KEY, "https://localhost"))) - .doesNotThrowAnyException(); - assertThatCode( - configureEndpointCallable( - ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://foo:bar@localhost"))) - .doesNotThrowAnyException(); - assertThatCode( - configureEndpointCallable( - ImmutableMap.of( - GENERIC_ENDPOINT_KEY, - "http://localhost:4318/path", - "otel.exporter.otlp.protocol", - "http/protobuf"))) - .doesNotThrowAnyException(); - } - - @Test - void configureOtlpExporterBuilder_InvalidEndpoints() { - assertThatThrownBy(configureEndpointCallable(ImmutableMap.of(GENERIC_ENDPOINT_KEY, "/foo/bar"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("OTLP endpoint must be a valid URL:"); - assertThatThrownBy( - configureEndpointCallable( - ImmutableMap.of(GENERIC_ENDPOINT_KEY, "file://localhost:4317"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("OTLP endpoint scheme must be http or https:"); - assertThatThrownBy( - configureEndpointCallable( - ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317?foo=bar"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("OTLP endpoint must not have a query string:"); - assertThatThrownBy( - configureEndpointCallable( - ImmutableMap.of(GENERIC_ENDPOINT_KEY, "http://localhost:4317#fragment"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("OTLP endpoint must not have a fragment:"); - assertThatThrownBy( - configureEndpointCallable( - ImmutableMap.of( - GENERIC_ENDPOINT_KEY, - "http://localhost:4317/path", - "otel.exporter.otlp.protocol", - "grpc"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("OTLP endpoint must not have a path:"); - } - - private static ThrowingCallable configureEndpointCallable(Map properties) { - return () -> configureEndpoint(DATA_TYPE_TRACES, properties); - } - - @Test - void configureOtlpExporterBuilder_HttpGenericEndpointKey() { - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/")) - .isEqualTo("http://localhost:4318/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo")) - .isEqualTo("http://localhost:4318/foo/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo/")) - .isEqualTo("http://localhost:4318/foo/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) - .isEqualTo("http://localhost:4318/v1/traces/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/metrics")) - .isEqualTo("http://localhost:4318/v1/metrics/v1/traces"); - - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/v1/metrics"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/")) - .isEqualTo("http://localhost:4318/v1/metrics"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo")) - .isEqualTo("http://localhost:4318/foo/v1/metrics"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo/")) - .isEqualTo("http://localhost:4318/foo/v1/metrics"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/metrics")) - .isEqualTo("http://localhost:4318/v1/metrics/v1/metrics"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) - .isEqualTo("http://localhost:4318/v1/traces/v1/metrics"); - - assertThat( - configureEndpointForHttp(DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/v1/logs"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/")) - .isEqualTo("http://localhost:4318/v1/logs"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo")) - .isEqualTo("http://localhost:4318/foo/v1/logs"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/foo/")) - .isEqualTo("http://localhost:4318/foo/v1/logs"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/logs")) - .isEqualTo("http://localhost:4318/v1/logs/v1/logs"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, GENERIC_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) - .isEqualTo("http://localhost:4318/v1/traces/v1/logs"); - } - - @Test - void configureOtlpExporterBuilder_HttpTracesEndpointKey() { - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318/")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) - .isEqualTo("http://localhost:4318/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_TRACES, TRACES_ENDPOINT_KEY, "http://localhost:4318/foo/bar")) - .isEqualTo("http://localhost:4318/foo/bar"); - assertThat( - configureEndpoint( - DATA_TYPE_TRACES, - ImmutableMap.of( - "otel.exporter.otlp.protocol", - PROTOCOL_HTTP_PROTOBUF, - GENERIC_ENDPOINT_KEY, - "http://localhost:4318/foo/bar", - TRACES_ENDPOINT_KEY, - "http://localhost:4318/baz/qux"))) - .isEqualTo("http://localhost:4318/baz/qux"); - } - - @Test - void configureOtlpExporterBuilder_HttpMetricsEndpointKey() { - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318/")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318/v1/traces")) - .isEqualTo("http://localhost:4318/v1/traces"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_METRICS, METRICS_ENDPOINT_KEY, "http://localhost:4318/foo/bar")) - .isEqualTo("http://localhost:4318/foo/bar"); - assertThat( - configureEndpoint( - DATA_TYPE_METRICS, - ImmutableMap.of( - "otel.exporter.otlp.protocol", - PROTOCOL_HTTP_PROTOBUF, - GENERIC_ENDPOINT_KEY, - "http://localhost:4318/foo/bar", - METRICS_ENDPOINT_KEY, - "http://localhost:4318/baz/qux"))) - .isEqualTo("http://localhost:4318/baz/qux"); - } - - @Test - void configureOtlpExporterBuilder_HttpLogsEndpointKey() { - assertThat(configureEndpointForHttp(DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/"); - assertThat(configureEndpointForHttp(DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp(DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318/")) - .isEqualTo("http://localhost:4318/"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318/v1/logs")) - .isEqualTo("http://localhost:4318/v1/logs"); - assertThat( - configureEndpointForHttp( - DATA_TYPE_LOGS, LOGS_ENDPOINT_KEY, "http://localhost:4318/foo/bar")) - .isEqualTo("http://localhost:4318/foo/bar"); - assertThat( - configureEndpoint( - DATA_TYPE_LOGS, - ImmutableMap.of( - "otel.exporter.otlp.protocol", - PROTOCOL_HTTP_PROTOBUF, - GENERIC_ENDPOINT_KEY, - "http://localhost:4318/foo/bar", - LOGS_ENDPOINT_KEY, - "http://localhost:4318/baz/qux"))) - .isEqualTo("http://localhost:4318/baz/qux"); - } - - private static String configureEndpointForHttp( - String dataType, String endpointPropertyKey, String endpointPropertyValue) { - return configureEndpoint( - dataType, - ImmutableMap.of( - "otel.exporter.otlp.protocol", - PROTOCOL_HTTP_PROTOBUF, - endpointPropertyKey, - endpointPropertyValue)); - } - - /** Configure and return the endpoint for the data type using the given properties. */ - private static String configureEndpoint(String dataType, Map properties) { - AtomicReference endpoint = new AtomicReference<>(""); - - OtlpConfigUtil.configureOtlpExporterBuilder( - dataType, - DefaultConfigProperties.createForTest(properties), - endpoint::set, - (value1, value2) -> {}, - value -> {}, - value -> {}, - value -> {}, - (value1, value2) -> {}, - value -> {}); - - return endpoint.get(); - } - - @Test - void configureOtlpAggregationTemporality() { - assertThatThrownBy( - () -> - configureAggregationTemporality( - ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "foo"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Unrecognized aggregation temporality:"); - - assertThat( - configureAggregationTemporality( - ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "CUMULATIVE"))) - .isEqualTo(AggregationTemporality.CUMULATIVE); - assertThat( - configureAggregationTemporality( - ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "cumulative"))) - .isEqualTo(AggregationTemporality.CUMULATIVE); - assertThat( - configureAggregationTemporality( - ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "DELTA"))) - .isEqualTo(AggregationTemporality.DELTA); - assertThat( - configureAggregationTemporality( - ImmutableMap.of("otel.exporter.otlp.metrics.temporality.preference", "delta"))) - .isEqualTo(AggregationTemporality.DELTA); - } - - /** Configure and return the aggregation temporality using the given properties. */ - private static AggregationTemporality configureAggregationTemporality( - Map properties) { - AtomicReference temporalityRef = new AtomicReference<>(); - OtlpConfigUtil.configureOtlpAggregationTemporality( - DefaultConfigProperties.createForTest(properties), temporalityRef::set); - // We apply the temporality selector to a HISTOGRAM instrument to simplify assertions - return temporalityRef.get().getAggregationTemporality(InstrumentType.HISTOGRAM); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java index 8b83569f90c..d169918a157 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceConfigurationTest.java @@ -9,119 +9,161 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import io.opentelemetry.sdk.testing.assertj.AttributesAssert; import java.net.URL; import java.net.URLClassLoader; import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.function.Consumer; +import java.util.stream.Stream; +import javax.annotation.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +@SuppressLogger(ResourceConfiguration.class) class ResourceConfigurationTest { - @Test - void resource() { - Attributes attributes = - ResourceConfiguration.configureResource( - DefaultConfigProperties.get(Collections.emptyMap()), - ResourceConfigurationTest.class.getClassLoader(), - (r, c) -> r) - .getAttributes(); - - assertThat(attributes.get(ResourceAttributes.OS_TYPE)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.OS_DESCRIPTION)).isNotNull(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_PID)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_COMMAND_LINE)).isNotNull(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_NAME)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_VERSION)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_DESCRIPTION)).isNotNull(); - } + private final ComponentLoader componentLoader = + ComponentLoader.forClassLoader(ResourceConfigurationTest.class.getClassLoader()); + private final SpiHelper spiHelper = SpiHelper.create(componentLoader); @Test - void emptyClassLoader() { + void configureResource_EmptyClassLoader() { Attributes attributes = ResourceConfiguration.configureResource( - DefaultConfigProperties.get(Collections.emptyMap()), - new URLClassLoader(new URL[0], null), + DefaultConfigProperties.create(Collections.emptyMap(), componentLoader), + SpiHelper.create(new URLClassLoader(new URL[0], null)), (r, c) -> r) .getAttributes(); - assertProcessAttributeIsNull(attributes); + assertThat(attributes.get(AttributeKey.stringKey("service.name"))) + .isEqualTo("unknown_service:java"); + assertThat(attributes.get(AttributeKey.stringKey("cat"))).isNull(); + assertThat(attributes.get(AttributeKey.stringKey("animal"))).isNull(); + assertThat(attributes.get(AttributeKey.stringKey("color"))).isNull(); } @Test - void onlyEnabledCustomResourceProvider() { - Map customConfigs = new HashMap<>(1); - customConfigs.put( - "otel.java.enabled.resource.providers", - "io.opentelemetry.sdk.autoconfigure.ResourceProviderCustomizer"); - Attributes attributes = + void configureResource_ServiceNameFromEnvironment() { + Resource resource = ResourceConfiguration.configureResource( - DefaultConfigProperties.get(customConfigs), - ResourceConfigurationTest.class.getClassLoader(), - (r, c) -> r) - .getAttributes(); - - assertProcessAttributeIsNull(attributes); - assertThat(attributes.get(AttributeKey.stringKey("animal"))).isEqualTo("cat"); + DefaultConfigProperties.create(Collections.emptyMap(), componentLoader), + spiHelper, + (r, c) -> r); + + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder("service", Attributes.of(AttributeKey.stringKey("service.name"), "test")) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build()); + assertThat(EntityUtil.getUnassociatedAttributes(resource)) + .containsEntry("cat", "meow") + .containsEntry("service.instance.id", "override-id"); } - @Test - void settingEnabledAndDisabledConfiguration() { - Map customConfigs = new HashMap<>(2); - customConfigs.put( - "otel.java.enabled.resource.providers", - "io.opentelemetry.sdk.autoconfigure.ResourceProviderCustomizer,io.opentelemetry.sdk.extension.resources.OsResourceProvider,io.opentelemetry.sdk.extension.resources.ProcessResourceProvider"); - customConfigs.put( - "otel.java.disabled.resource.providers", - "io.opentelemetry.sdk.extension.resources.OsResourceProvider"); + @ParameterizedTest + @MethodSource("configureResourceArgs") + void configureResource( + @Nullable String enabledProviders, + @Nullable String disabledProviders, + Consumer attributeAssertion) { + // build.gradle.kts sets: + // OTEL_SERVICE_NAME=test + // OTEL_RESOURCE_ATTRIBUTES=cat=meow + Map config = new HashMap<>(); + if (enabledProviders != null) { + config.put("otel.java.enabled.resource.providers", enabledProviders); + } + if (disabledProviders != null) { + config.put("otel.java.disabled.resource.providers", disabledProviders); + } Attributes attributes = ResourceConfiguration.configureResource( - DefaultConfigProperties.get(customConfigs), - ResourceConfigurationTest.class.getClassLoader(), - (r, c) -> r) + DefaultConfigProperties.create(config, componentLoader), spiHelper, (r, c) -> r) .getAttributes(); - assertThat(attributes.get(ResourceAttributes.OS_TYPE)).isNull(); - assertThat(attributes.get(ResourceAttributes.OS_DESCRIPTION)).isNull(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_PID)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)).isNotNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_COMMAND_LINE)).isNotNull(); - - assertThat(attributes.get(AttributeKey.stringKey("animal"))).isEqualTo("cat"); + attributeAssertion.accept(assertThat(attributes)); } - @Test - void onlySettingEnabledConfiguration() { - Map customConfigs = new HashMap<>(1); - customConfigs.put( - "otel.java.enabled.resource.providers", - "io.opentelemetry.sdk.autoconfigure.ResourceProviderCustomizer"); - Attributes attributes = - ResourceConfiguration.configureResource( - DefaultConfigProperties.get(customConfigs), - ResourceConfigurationTest.class.getClassLoader(), - (r, c) -> r) - .getAttributes(); - - assertProcessAttributeIsNull(attributes); - assertThat(attributes.get(AttributeKey.stringKey("animal"))).isEqualTo("cat"); + private static Stream configureResourceArgs() { + return Stream.of( + Arguments.argumentSet( + "default", + null, + null, + attributeConsumer(attr -> + attr.containsEntry("service.name", "test") + .containsEntry("cat", "meow") + .containsEntry("service.instance.id", "override-id"))), + Arguments.argumentSet( + "only enabled animal provider", + "io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", + null, + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .containsEntry("animal", "cat") + .doesNotContainKey("color"))), + Arguments.argumentSet( + "only disabled color provider", + null, + "io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider", + attributeConsumer(attr -> + attr.containsEntry("service.name", "test") + .containsEntry("cat", "meow") + .containsEntry("animal", "cat") + .doesNotContainKey("color"))), + Arguments.argumentSet( + "enabled animal disabled color", + "io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", + "io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider", + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .containsEntry("animal", "cat") + .doesNotContainKey("color"))), + Arguments.argumentSet( + "enabled animal disabled color and animal", + "io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", + "io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider,io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider", + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .doesNotContainKey("animal") + .doesNotContainKey("color"))), + Arguments.argumentSet( + "only environment provider enabled", + "io.opentelemetry.sdk.autoconfigure.EnvironmentResourceProvider", + null, + attributeConsumer(attr -> + attr.containsEntry("service.name", "test") + .containsEntry("cat", "meow") + .doesNotContainKey("service.instance.id") + .doesNotContainKey("animal") + .doesNotContainKey("color"))), + Arguments.argumentSet( + "environment provider disabled", + null, + "io.opentelemetry.sdk.autoconfigure.EnvironmentResourceProvider", + attributeConsumer(attr -> + attr.containsEntry("service.name", "unknown_service:java") + .doesNotContainKey("cat") + .containsEntry("animal", "cat") + .containsEntry("color", "blue")))); } - void assertProcessAttributeIsNull(Attributes attributes) { - assertThat(attributes.get(ResourceAttributes.OS_TYPE)).isNull(); - assertThat(attributes.get(ResourceAttributes.OS_DESCRIPTION)).isNull(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_PID)).isNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)).isNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_COMMAND_LINE)).isNull(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_NAME)).isNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_VERSION)).isNull(); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_DESCRIPTION)).isNull(); + private static Consumer attributeConsumer( + Consumer attributesAssertConsumer) { + return attributesAssertConsumer; } } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceProviderCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceProviderCustomizer.java deleted file mode 100644 index f6abd2451f8..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ResourceProviderCustomizer.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -public class ResourceProviderCustomizer implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return Resource.create(Attributes.of(AttributeKey.stringKey("animal"), "cat")); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java index c39f0c30b5c..d0c3d312963 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterConfigurationTest.java @@ -9,25 +9,48 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.jaeger.JaegerGrpcSpanExporter; +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.exporter.logging.otlp.OtlpJsonLoggingSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.sdk.autoconfigure.internal.NamedSpiManager; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; import io.opentelemetry.sdk.trace.export.SpanExporter; import java.util.Collections; -import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") // testing deprecated code class SpanExporterConfigurationTest { + private final SpiHelper spiHelper = + SpiHelper.create(SpanExporterConfigurationTest.class.getClassLoader()); + + @Test + void configureExporter_KnownSpiExportersOnClasspath() { + NamedSpiManager spiExportersManager = + SpanExporterConfiguration.spanExporterSpiManager( + DefaultConfigProperties.createFromMap(Collections.emptyMap()), spiHelper); + + assertThat(SpanExporterConfiguration.configureExporter("console", spiExportersManager)) + .isInstanceOf(LoggingSpanExporter.class); + assertThat(SpanExporterConfiguration.configureExporter("logging", spiExportersManager)) + .isInstanceOf(LoggingSpanExporter.class); + assertThat(SpanExporterConfiguration.configureExporter("logging-otlp", spiExportersManager)) + .isInstanceOf(OtlpJsonLoggingSpanExporter.class); + assertThat(SpanExporterConfiguration.configureExporter("otlp", spiExportersManager)) + .isInstanceOf(OtlpGrpcSpanExporter.class); + } + @Test void configureOtlpSpansUnsupportedProtocol() { - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureOtlp( - DefaultConfigProperties.createForTest( - ImmutableMap.of("otel.exporter.otlp.protocol", "foo")), - MeterProvider.noop())) + ConfigProperties config = + DefaultConfigProperties.createFromMap( + ImmutableMap.of("otel.exporter.otlp.protocol", "foo")); + assertThatThrownBy(() -> + SpanExporterConfiguration.configureExporter( + "otlp", SpanExporterConfiguration.spanExporterSpiManager(config, spiHelper))) .isInstanceOf(ConfigurationException.class) .hasMessageContaining("Unsupported OTLP traces protocol: foo"); } @@ -35,63 +58,19 @@ void configureOtlpSpansUnsupportedProtocol() { // Timeout difficult to test using real exports so just check implementation detail here. @Test void configureOtlpTimeout() { - SpanExporter exporter = + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.exporter.otlp.timeout", "10")); + try (SpanExporter exporter = SpanExporterConfiguration.configureExporter( - "otlp", - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.exporter.otlp.timeout", "10")), - NamedSpiManager.createEmpty(), - MeterProvider.noop()); - try { + "otlp", SpanExporterConfiguration.spanExporterSpiManager(config, spiHelper))) { assertThat(exporter) .isInstanceOfSatisfying( OtlpGrpcSpanExporter.class, otlp -> assertThat(otlp) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(10L))); - } finally { - exporter.shutdown(); - } - } - - // Timeout difficult to test using real exports so just check implementation detail here. - @Test - void configureJaegerTimeout() { - SpanExporter exporter = - SpanExporterConfiguration.configureExporter( - "jaeger", - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.exporter.jaeger.timeout", "10")), - NamedSpiManager.createEmpty(), - MeterProvider.noop()); - try { - assertThat(exporter) - .isInstanceOfSatisfying( - JaegerGrpcSpanExporter.class, - jaeger -> - assertThat(jaeger) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.MILLISECONDS.toNanos(10L))); - } finally { - exporter.shutdown(); - } - } - - // Timeout difficult to test using real exports so just check that things don't blow up. - @Test - void configureZipkinTimeout() { - SpanExporter exporter = - SpanExporterConfiguration.configureExporter( - "zipkin", - DefaultConfigProperties.createForTest( - Collections.singletonMap("otel.exporter.zipkin.timeout", "5s")), - NamedSpiManager.createEmpty(), - MeterProvider.noop()); - try { - assertThat(exporter).isNotNull(); - } finally { - exporter.shutdown(); + .extracting("delegate.grpcSender.client.callTimeoutMillis") + .isEqualTo(10)); } } } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterCustomizer.java deleted file mode 100644 index a2a44262125..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/SpanExporterCustomizer.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; -import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.data.DelegatingSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Collection; -import java.util.stream.Collectors; - -public class SpanExporterCustomizer implements AutoConfigurationCustomizerProvider { - @Override - public void customize(AutoConfigurationCustomizer autoConfiguration) { - autoConfiguration.addSpanExporterCustomizer( - (delegate, config) -> - new SpanExporter() { - @Override - public CompletableResultCode export(Collection spans) { - return delegate.export( - spans.stream() - .map( - span -> - new DelegatingSpanData(span) { - @Override - public Attributes getAttributes() { - return span.getAttributes().toBuilder() - .put("wrapped", config.getInt("otel.test.wrapped")) - .build(); - } - }) - .collect(Collectors.toList())); - } - - @Override - public CompletableResultCode flush() { - return delegate.flush(); - } - - @Override - public CompletableResultCode shutdown() { - return delegate.shutdown(); - } - }); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestTracerProviderConfigurer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestTracerProviderConfigurer.java deleted file mode 100644 index 5afa2fab100..00000000000 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestTracerProviderConfigurer.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.trace.ReadWriteSpan; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; -import io.opentelemetry.sdk.trace.SpanProcessor; - -@SuppressWarnings("deprecation") // Support testing of SdkTracerProviderConfigurer -public class TestTracerProviderConfigurer - implements io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer { - @Override - public void configure(SdkTracerProviderBuilder tracerProvider, ConfigProperties config) { - tracerProvider.addSpanProcessor( - new SpanProcessor() { - @Override - public void onStart(Context parentContext, ReadWriteSpan span) { - span.setAttribute("configured", config.getBoolean("otel.test.configured")); - } - - @Override - public boolean isStartRequired() { - return true; - } - - @Override - public void onEnd(ReadableSpan span) {} - - @Override - public boolean isEndRequired() { - return false; - } - }); - } -} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java new file mode 100644 index 00000000000..6f60fa9fa8f --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TracerProviderConfigurationTest.java @@ -0,0 +1,82 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.common.collect.ImmutableMap; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.internal.SpiHelper; +import io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableSamplerProvider; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSampler; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.io.Closeable; +import java.lang.reflect.Field; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +public class TracerProviderConfigurationTest { + + private final SpiHelper spiHelper = + SpiHelper.create(TracerProviderConfigurationTest.class.getClassLoader()); + + @Test + void configuration() { + ConfigProperties config = + DefaultConfigProperties.createFromMap(ImmutableMap.of("test.option", "true")); + Sampler sampler = + TracerProviderConfiguration.configureSampler("testSampler", config, spiHelper); + + assertThat(sampler) + .isInstanceOfSatisfying( + TestConfigurableSamplerProvider.TestSampler.class, + s -> assertThat(s.getConfig()).isSameAs(config)); + } + + @Test + void emptyClassLoader() { + ConfigProperties config = + DefaultConfigProperties.createFromMap(ImmutableMap.of("test.option", "true")); + assertThatThrownBy(() -> + TracerProviderConfiguration.configureSampler( + "testSampler", config, SpiHelper.create(new URLClassLoader(new URL[0], null)))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("testSampler"); + } + + @Test + void samplerNotFound() { + assertThatThrownBy(() -> + TracerProviderConfiguration.configureSampler( + "catSampler", + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + spiHelper)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("catSampler"); + } + + @Test + @SuppressLogger(JaegerRemoteSampler.class) + void configureSampler_JaegerRemoteSampler() throws Exception { + Sampler sampler = + TracerProviderConfiguration.configureSampler( + "parentbased_jaeger_remote", + DefaultConfigProperties.createFromMap(Collections.emptyMap()), + spiHelper); + assertThat(sampler.getClass().getSimpleName()).isEqualTo("ParentBasedSampler"); + assertThat(sampler).extracting("root").isInstanceOf(JaegerRemoteSampler.class); + // Close the inner JaegerRemoteSampler to shut down its background thread. + Field rootField = sampler.getClass().getDeclaredField("root"); + rootField.setAccessible(true); + ((Closeable) rootField.get(sampler)).close(); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java new file mode 100644 index 00000000000..ff4a694e40e --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/LogRecordCustomizer.java @@ -0,0 +1,77 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.ReadWriteLogRecord; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; +import java.util.stream.Collectors; + +/** Behavior asserted in {@link io.opentelemetry.sdk.autoconfigure.FullConfigTest}. */ +public class LogRecordCustomizer implements AutoConfigurationCustomizerProvider { + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + autoConfiguration.addLogRecordProcessorCustomizer(LogRecordCustomizer::processorCustomizer); + autoConfiguration.addLogRecordExporterCustomizer(LogRecordCustomizer::exporterCustomizer); + } + + private static LogRecordProcessor processorCustomizer( + LogRecordProcessor delegate, ConfigProperties config) { + return new LogRecordProcessor() { + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) { + logRecord.setAttribute(AttributeKey.stringKey("extra-key"), "extra-value"); + delegate.onEmit(context, logRecord); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public CompletableResultCode forceFlush() { + return delegate.forceFlush(); + } + }; + } + + private static LogRecordExporter exporterCustomizer( + LogRecordExporter delegate, ConfigProperties config) { + return new LogRecordExporter() { + @Override + public CompletableResultCode export(Collection logs) { + Collection filtered = + logs.stream() + .filter(log -> + log.getSeverity() == Severity.UNDEFINED_SEVERITY_NUMBER + || log.getSeverity().getSeverityNumber() + >= Severity.INFO.getSeverityNumber()) + .collect(Collectors.toList()); + return delegate.export(filtered); + } + + @Override + public CompletableResultCode flush() { + return delegate.flush(); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + }; + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java similarity index 79% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricCustomizer.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java index 32e857f8286..53da532f574 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/MetricCustomizer.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/MetricCustomizer.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; @@ -19,6 +19,7 @@ import java.util.Collection; import java.util.stream.Collectors; +/** Behavior asserted in {@link io.opentelemetry.sdk.autoconfigure.FullConfigTest}. */ public class MetricCustomizer implements AutoConfigurationCustomizerProvider { @Override public void customize(AutoConfigurationCustomizer autoConfiguration) { @@ -48,7 +49,16 @@ public CompletableResultCode export(Collection metrics) { // please configure the SdkMeterProvider with the appropriate view. Collection filtered = metrics.stream() - .filter(metricData -> metricData.getName().equals("my-metric")) + .filter(metricData -> + metricData.getName().equals("my-metric") + || metricData + .getInstrumentationScopeInfo() + .getName() + .startsWith("io.opentelemetry.exporters") + || metricData + .getInstrumentationScopeInfo() + .getName() + .startsWith("io.opentelemetry.sdk")) .collect(Collectors.toList()); return delegate.export(filtered); } diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/NotEnabledConfigurablePropagatorProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/NotEnabledConfigurablePropagatorProvider.java similarity index 96% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/NotEnabledConfigurablePropagatorProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/NotEnabledConfigurablePropagatorProvider.java index 06316ce9811..a4a0e175ba8 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/NotEnabledConfigurablePropagatorProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/NotEnabledConfigurablePropagatorProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java new file mode 100644 index 00000000000..1e937dff970 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/SpanCustomizer.java @@ -0,0 +1,101 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; +import io.opentelemetry.sdk.trace.data.DelegatingSpanData; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; +import java.util.stream.Collectors; + +/** Behavior asserted in {@link io.opentelemetry.sdk.autoconfigure.FullConfigTest}. */ +public class SpanCustomizer implements AutoConfigurationCustomizerProvider { + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + autoConfiguration.addSpanProcessorCustomizer(SpanCustomizer::processorCustomizer); + autoConfiguration.addSpanExporterCustomizer(SpanCustomizer::exporterCustomizer); + } + + private static SpanProcessor processorCustomizer( + SpanProcessor delegate, ConfigProperties config) { + return new SpanProcessor() { + @Override + public void onStart(Context parentContext, ReadWriteSpan span) { + span.setAttribute(AttributeKey.stringKey("extra-key"), "extra-value"); + if (delegate.isStartRequired()) { + delegate.onStart(parentContext, span); + } + } + + @Override + public boolean isStartRequired() { + return true; + } + + @Override + public void onEnd(ReadableSpan span) { + if (delegate.isEndRequired()) { + delegate.onEnd(span); + } + } + + @Override + public boolean isEndRequired() { + return delegate.isEndRequired(); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + + @Override + public CompletableResultCode forceFlush() { + return delegate.forceFlush(); + } + }; + } + + private static SpanExporter exporterCustomizer(SpanExporter delegate, ConfigProperties config) { + return new SpanExporter() { + @Override + public CompletableResultCode export(Collection spans) { + return delegate.export( + spans.stream() + .map(span -> + new DelegatingSpanData(span) { + @Override + public Attributes getAttributes() { + return span.getAttributes().toBuilder() + .put("wrapped", config.getInt("otel.test.wrapped")) + .build(); + } + }) + .collect(Collectors.toList())); + } + + @Override + public CompletableResultCode flush() { + return delegate.flush(); + } + + @Override + public CompletableResultCode shutdown() { + return delegate.shutdown(); + } + }; + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestAnimalResourceProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestAnimalResourceProvider.java new file mode 100644 index 00000000000..98801538fdd --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestAnimalResourceProvider.java @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class TestAnimalResourceProvider implements ResourceProvider { + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create(Attributes.of(AttributeKey.stringKey("animal"), "cat")); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestColorResourceProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestColorResourceProvider.java new file mode 100644 index 00000000000..2d071ed4649 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestColorResourceProvider.java @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class TestColorResourceProvider implements ResourceProvider { + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create(Attributes.of(AttributeKey.stringKey("color"), "blue")); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableLogRecordExporterProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableLogRecordExporterProvider.java new file mode 100644 index 00000000000..2b94eda22ff --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableLogRecordExporterProvider.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; + +public class TestConfigurableLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider, AutoConfigureListener { + + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + return new TestLogRecordExporter(config); + } + + @Override + public String getName() { + return "testExporter"; + } + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) {} + + public static class TestLogRecordExporter implements LogRecordExporter { + private final ConfigProperties config; + + public TestLogRecordExporter(ConfigProperties config) { + this.config = config; + } + + @Override + public CompletableResultCode export(Collection logs) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + public ConfigProperties getConfig() { + return config; + } + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableMetricExporterProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableMetricExporterProvider.java similarity index 80% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableMetricExporterProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableMetricExporterProvider.java index 78a6b25d762..49ed7986477 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableMetricExporterProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableMetricExporterProvider.java @@ -3,9 +3,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; +import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.metrics.InstrumentType; @@ -14,7 +16,8 @@ import io.opentelemetry.sdk.metrics.export.MetricExporter; import java.util.Collection; -public class TestConfigurableMetricExporterProvider implements ConfigurableMetricExporterProvider { +public class TestConfigurableMetricExporterProvider + implements ConfigurableMetricExporterProvider, AutoConfigureListener { @Override public MetricExporter createExporter(ConfigProperties config) { @@ -26,6 +29,9 @@ public String getName() { return "testExporter"; } + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) {} + public static class TestMetricExporter implements MetricExporter { private final ConfigProperties config; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurablePropagatorProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurablePropagatorProvider.java similarity index 95% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurablePropagatorProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurablePropagatorProvider.java index c614b54129c..ebce24be933 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurablePropagatorProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurablePropagatorProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.context.Context; import io.opentelemetry.context.propagation.TextMapGetter; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSamplerProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableSamplerProvider.java similarity index 96% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSamplerProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableSamplerProvider.java index 3fb8da6d1f5..7f903a3349f 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSamplerProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableSamplerProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanKind; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSpanExporterProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableSpanExporterProvider.java similarity index 77% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSpanExporterProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableSpanExporterProvider.java index 61777959a69..a4c7fef26ab 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/TestConfigurableSpanExporterProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestConfigurableSpanExporterProvider.java @@ -3,16 +3,19 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; +import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.SpanExporter; import java.util.Collection; -public class TestConfigurableSpanExporterProvider implements ConfigurableSpanExporterProvider { +public class TestConfigurableSpanExporterProvider + implements ConfigurableSpanExporterProvider, AutoConfigureListener { @Override public SpanExporter createExporter(ConfigProperties config) { return new TestSpanExporter(config); @@ -23,6 +26,9 @@ public String getName() { return "testExporter"; } + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) {} + public static class TestSpanExporter implements SpanExporter { private final ConfigProperties config; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestServiceInstanceIdOverrideProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestServiceInstanceIdOverrideProvider.java new file mode 100644 index 00000000000..50f364f53b8 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestServiceInstanceIdOverrideProvider.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; +import io.opentelemetry.sdk.resources.Resource; + +/** + * Test ResourceProvider that overrides service.instance.id to test provider ordering. Runs at a + * higher order than ServiceInstanceIdResourceProvider to ensure it can override the fallback UUID. + */ +public class TestServiceInstanceIdOverrideProvider implements ResourceProvider { + + @Override + public Resource createResource(ConfigProperties config) { + return Resource.create( + Attributes.of(AttributeKey.stringKey("service.instance.id"), "override-id")); + } + + @Override + public int order() { + // Run after ServiceInstanceIdResourceProvider (Integer.MIN_VALUE) to override the fallback UUID + return 0; + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java new file mode 100644 index 00000000000..ca47b0503fe --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/TestTracerProviderConfigurer.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer; +import io.opentelemetry.sdk.extension.incubator.trace.OnStartSpanProcessor; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; + +@SuppressWarnings("deprecation") // Support testing of SdkTracerProviderConfigurer +public class TestTracerProviderConfigurer implements SdkTracerProviderConfigurer { + @Override + public void configure(SdkTracerProviderBuilder tracerProvider, ConfigProperties config) { + tracerProvider.addSpanProcessor( + OnStartSpanProcessor.create((ctx, span) -> + span.setAttribute("configured", config.getBoolean("otel.test.configured")))); + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableLogRecordExporterProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableLogRecordExporterProvider.java new file mode 100644 index 00000000000..2ed5c105c67 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableLogRecordExporterProvider.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.provider; + +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +public class ThrowingConfigurableLogRecordExporterProvider + implements ConfigurableLogRecordExporterProvider { + @Override + public LogRecordExporter createExporter(ConfigProperties config) { + throw new IllegalStateException("always throws"); + } + + @Override + public String getName() { + return "throwing"; + } +} diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableMetricExporterProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableMetricExporterProvider.java similarity index 92% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableMetricExporterProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableMetricExporterProvider.java index f19eea81f63..65461a74d7c 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableMetricExporterProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableMetricExporterProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurablePropagatorProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurablePropagatorProvider.java similarity index 91% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurablePropagatorProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurablePropagatorProvider.java index 2cc233299ef..834abd54b4d 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurablePropagatorProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurablePropagatorProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableSamplerProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableSamplerProvider.java similarity index 91% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableSamplerProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableSamplerProvider.java index e7e09dd04e7..e3bb7ae4fb2 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableSamplerProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableSamplerProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableSpanExporterProvider.java b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableSpanExporterProvider.java similarity index 91% rename from sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableSpanExporterProvider.java rename to sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableSpanExporterProvider.java index 3c886493d73..8306c70d7d7 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/ThrowingConfigurableSpanExporterProvider.java +++ b/sdk-extensions/autoconfigure/src/testFullConfig/java/io/opentelemetry/sdk/autoconfigure/provider/ThrowingConfigurableSpanExporterProvider.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.autoconfigure; +package io.opentelemetry.sdk.autoconfigure.provider; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider; diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider index 32ee9ebc98b..38b64bf91d3 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider @@ -1,3 +1,3 @@ -io.opentelemetry.sdk.autoconfigure.SpanExporterCustomizer -io.opentelemetry.sdk.autoconfigure.MetricCustomizer -io.opentelemetry.sdk.autoconfigure.LogExporterCustomizer \ No newline at end of file +io.opentelemetry.sdk.autoconfigure.provider.SpanCustomizer +io.opentelemetry.sdk.autoconfigure.provider.MetricCustomizer +io.opentelemetry.sdk.autoconfigure.provider.LogRecordCustomizer diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider index 52790aadee6..22b782eae22 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ConfigurablePropagatorProvider @@ -1,2 +1,2 @@ -io.opentelemetry.sdk.autoconfigure.TestConfigurablePropagatorProvider -io.opentelemetry.sdk.autoconfigure.ThrowingConfigurablePropagatorProvider +io.opentelemetry.sdk.autoconfigure.provider.TestConfigurablePropagatorProvider +io.opentelemetry.sdk.autoconfigure.provider.ThrowingConfigurablePropagatorProvider diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider index 88f0e92b239..b20c5c4fe9a 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider @@ -1 +1,3 @@ -io.opentelemetry.sdk.autoconfigure.ResourceProviderCustomizer \ No newline at end of file +io.opentelemetry.sdk.autoconfigure.provider.TestAnimalResourceProvider +io.opentelemetry.sdk.autoconfigure.provider.TestColorResourceProvider +io.opentelemetry.sdk.autoconfigure.provider.TestServiceInstanceIdOverrideProvider \ No newline at end of file diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider new file mode 100644 index 00000000000..b3aac6b53f5 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.logs.ConfigurableLogRecordExporterProvider @@ -0,0 +1,2 @@ +io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableLogRecordExporterProvider +io.opentelemetry.sdk.autoconfigure.provider.ThrowingConfigurableLogRecordExporterProvider diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider index a673483f187..b28b2e7e3e0 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.metrics.ConfigurableMetricExporterProvider @@ -1,2 +1,2 @@ -io.opentelemetry.sdk.autoconfigure.TestConfigurableMetricExporterProvider -io.opentelemetry.sdk.autoconfigure.ThrowingConfigurableMetricExporterProvider +io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableMetricExporterProvider +io.opentelemetry.sdk.autoconfigure.provider.ThrowingConfigurableMetricExporterProvider diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider index fd49dbccdef..8e9fe9058c1 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider @@ -1,2 +1,2 @@ -io.opentelemetry.sdk.autoconfigure.TestConfigurableSamplerProvider -io.opentelemetry.sdk.autoconfigure.ThrowingConfigurableSamplerProvider +io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableSamplerProvider +io.opentelemetry.sdk.autoconfigure.provider.ThrowingConfigurableSamplerProvider diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider index e9d86c5d908..7bf76539410 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSpanExporterProvider @@ -1,2 +1,2 @@ -io.opentelemetry.sdk.autoconfigure.TestConfigurableSpanExporterProvider -io.opentelemetry.sdk.autoconfigure.ThrowingConfigurableSpanExporterProvider +io.opentelemetry.sdk.autoconfigure.provider.TestConfigurableSpanExporterProvider +io.opentelemetry.sdk.autoconfigure.provider.ThrowingConfigurableSpanExporterProvider diff --git a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer index c4233f93235..c1bcee73bd0 100644 --- a/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer +++ b/sdk-extensions/autoconfigure/src/testFullConfig/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.traces.SdkTracerProviderConfigurer @@ -1 +1 @@ -io.opentelemetry.sdk.autoconfigure.TestTracerProviderConfigurer +io.opentelemetry.sdk.autoconfigure.provider.TestTracerProviderConfigurer diff --git a/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java new file mode 100644 index 00000000000..a8e30d9f6d1 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/DeclarativeConfigurationTest.java @@ -0,0 +1,244 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static java.util.Collections.singletonMap; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.incubator.ExtendedOpenTelemetry; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.incubator.config.InstrumentationConfigUtil; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.internal.OpenTelemetrySdkBuilderUtil; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.slf4j.event.Level; + +class DeclarativeConfigurationTest { + + @RegisterExtension private static final CleanupExtension cleanup = new CleanupExtension(); + + @RegisterExtension + static final LogCapturer logCapturer = + LogCapturer.create() + .captureForLogger(AutoConfiguredOpenTelemetrySdkBuilder.class.getName(), Level.TRACE); + + @TempDir private Path tempDir; + private Path configFilePath; + + @BeforeEach + void setup() throws IOException { + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: test\n" + + "tracer_provider:\n" + + " processors:\n" + + " - simple:\n" + + " exporter:\n" + + " console: {}\n" + + "instrumentation/development:\n" + + " general:\n" + + " http:\n" + + " client:\n" + + " request_captured_headers:\n" + + " - Content-Type\n" + + " - Accept\n" + + " java:\n" + + " example:\n" + + " key: value\n"; + configFilePath = tempDir.resolve("otel-config.yaml"); + Files.write(configFilePath, yaml.getBytes(StandardCharsets.UTF_8)); + GlobalOpenTelemetry.resetForTest(); + } + + @Test + @SuppressLogger(AutoConfiguredOpenTelemetrySdkBuilder.class) + void configFile_fileNotFound() { + assertThatThrownBy(() -> + AutoConfiguredOpenTelemetrySdk.builder() + .setConfig( + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", "foo"))) + .build()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Configuration file not found"); + + assertThatCode(() -> + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> singletonMap("otel.config.file", "")) + .addPropertiesSupplier(() -> singletonMap("otel.sdk.disabled", "true")) + .build()) + .doesNotThrowAnyException(); + } + + @Test + void configFile_Valid() { + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", configFilePath.toString())); + AutoConfiguredOpenTelemetrySdkBuilder builder = spy(AutoConfiguredOpenTelemetrySdk.builder()); + Thread thread = new Thread(); + doReturn(thread).when(builder).shutdownHook(any()); + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = + builder.setConfig(config).build(); + cleanup.addCloseable(autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk()); + + OpenTelemetrySdk openTelemetrySdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk(); + Resource resource = Resource.getDefault().toBuilder().put("service.name", "test").build(); + OpenTelemetrySdk expectedSdk = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder() + .setMeterProvider(SdkMeterProvider.builder().setResource(resource).build()) + .setLoggerProvider(SdkLoggerProvider.builder().setResource(resource).build()) + .setTracerProvider( + SdkTracerProvider.builder() + .setResource(resource) + .addSpanProcessor( + SimpleSpanProcessor.create(LoggingSpanExporter.create())) + .build()), + ((ExtendedOpenTelemetrySdk) openTelemetrySdk).getSdkConfigProvider()) + .build(); + + cleanup.addCloseable(expectedSdk); + assertThat(openTelemetrySdk.toString()).hasToString(expectedSdk.toString()); + // AutoConfiguredOpenTelemetrySdk#getResource() is set to a dummy value when configuring from + // file + assertThat(autoConfiguredOpenTelemetrySdk.getResource()).isEqualTo(resource); + verify(builder, times(1)).shutdownHook(autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk()); + assertThat(Runtime.getRuntime().removeShutdownHook(thread)).isTrue(); + logCapturer.assertContains("Autoconfiguring from configuration file: " + configFilePath); + } + + @Test + void configFile_setComponentLoader() { + ComponentLoader componentLoader = + ComponentLoader.forClassLoader(DeclarativeConfigurationTest.class.getClassLoader()); + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", configFilePath.toString())); + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = + AutoConfiguredOpenTelemetrySdk.builder() + .setConfig(config) + .setComponentLoader(componentLoader) + .build(); + cleanup.addCloseable(autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk()); + + assertThat( + ((ExtendedOpenTelemetry) autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk()) + .getConfigProvider() + .getInstrumentationConfig() + .getComponentLoader()) + .isSameAs(componentLoader); + } + + @Test + void configFile_NoShutdownHook() { + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", configFilePath.toString())); + AutoConfiguredOpenTelemetrySdkBuilder builder = spy(AutoConfiguredOpenTelemetrySdk.builder()); + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = + builder.setConfig(config).disableShutdownHook().build(); + cleanup.addCloseable(autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk()); + + verify(builder, never()).shutdownHook(any()); + } + + @Test + void configFile_Error(@TempDir Path tempDir) throws IOException { + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: test\n" + + "tracer_provider:\n" + + " processors:\n" + + " - simple:\n" + + " exporter:\n" + + " foo: {}\n"; + Path path = tempDir.resolve("otel-config.yaml"); + Files.write(path, yaml.getBytes(StandardCharsets.UTF_8)); + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", path.toString())); + + assertThatThrownBy(() -> AutoConfiguredOpenTelemetrySdk.builder().setConfig(config).build()) + .isInstanceOf(ConfigurationException.class) + .hasMessage( + "No component provider detected for io.opentelemetry.sdk.trace.export.SpanExporter with name \"foo\"."); + } + + @Test + void configFile_ConfigProvider() { + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", configFilePath.toString())); + + AutoConfiguredOpenTelemetrySdk autoConfiguredOpenTelemetrySdk = + AutoConfiguredOpenTelemetrySdk.builder().setConfig(config).setResultAsGlobal().build(); + OpenTelemetrySdk openTelemetrySdk = autoConfiguredOpenTelemetrySdk.getOpenTelemetrySdk(); + cleanup.addCloseable(openTelemetrySdk); + + ConfigProvider globalConfigProvider = + ((ExtendedOpenTelemetry) GlobalOpenTelemetry.get()).getConfigProvider(); + + // Extract instrumentation config from ConfigProvider + assertThat(InstrumentationConfigUtil.httpClientRequestCapturedHeaders(globalConfigProvider)) + .isEqualTo(Arrays.asList("Content-Type", "Accept")); + assertThat(InstrumentationConfigUtil.javaInstrumentationConfig(globalConfigProvider, "example")) + .isNotNull() + .satisfies(exampleConfig -> assertThat(exampleConfig.getString("key")).isEqualTo("value")); + + // shortcuts to get specific instrumentation config + assertThat(globalConfigProvider.getInstrumentationConfig("example").getString("key")) + .isEqualTo("value"); + assertThat( + globalConfigProvider + .getGeneralInstrumentationConfig() + .get("http") + .get("client") + .getScalarList("request_captured_headers", String.class)) + .isEqualTo(Arrays.asList("Content-Type", "Accept")); + } +} diff --git a/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java new file mode 100644 index 00000000000..bfba04a1140 --- /dev/null +++ b/sdk-extensions/autoconfigure/src/testIncubating/java/io/opentelemetry/sdk/autoconfigure/FullDeclarativeConfigTest.java @@ -0,0 +1,330 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.awaitility.Awaitility.await; + +import com.linecorp.armeria.server.ServerBuilder; +import com.linecorp.armeria.server.grpc.GrpcService; +import com.linecorp.armeria.server.logging.LoggingService; +import com.linecorp.armeria.testing.junit5.server.ServerExtension; +import io.grpc.stub.StreamObserver; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; +import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse; +import io.opentelemetry.proto.collector.logs.v1.LogsServiceGrpc; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; +import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; +import io.opentelemetry.proto.collector.metrics.v1.MetricsServiceGrpc; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; +import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; +import io.opentelemetry.proto.collector.trace.v1.TraceServiceGrpc; +import io.opentelemetry.proto.common.v1.AnyValue; +import io.opentelemetry.proto.common.v1.KeyValue; +import io.opentelemetry.proto.metrics.v1.Metric; +import io.opentelemetry.proto.metrics.v1.ScopeMetrics; +import io.opentelemetry.proto.trace.v1.Span; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; + +/** Same as {@code FullConfigTest}, but using declarative configuration. */ +@SuppressWarnings("InterruptedExceptionSwallowed") +public class FullDeclarativeConfigTest { + + private static final BlockingQueue otlpTraceRequests = + new LinkedBlockingDeque<>(); + private static final BlockingQueue otlpMetricsRequests = + new LinkedBlockingDeque<>(); + private static final BlockingQueue otlpLogsRequests = + new LinkedBlockingDeque<>(); + + @RegisterExtension + public static final ServerExtension server = + new ServerExtension() { + @Override + protected void configure(ServerBuilder sb) { + sb.service( + GrpcService.builder() + // OTLP spans + .addService( + new TraceServiceGrpc.TraceServiceImplBase() { + @Override + public void export( + ExportTraceServiceRequest request, + StreamObserver responseObserver) { + otlpTraceRequests.add(request); + responseObserver.onNext(ExportTraceServiceResponse.getDefaultInstance()); + responseObserver.onCompleted(); + } + }) + // OTLP metrics + .addService( + new MetricsServiceGrpc.MetricsServiceImplBase() { + @Override + public void export( + ExportMetricsServiceRequest request, + StreamObserver responseObserver) { + if (request.getResourceMetricsCount() > 0) { + otlpMetricsRequests.add(request); + } + responseObserver.onNext( + ExportMetricsServiceResponse.getDefaultInstance()); + responseObserver.onCompleted(); + } + }) + // OTLP logs + .addService( + new LogsServiceGrpc.LogsServiceImplBase() { + @Override + public void export( + ExportLogsServiceRequest request, + StreamObserver responseObserver) { + if (request.getResourceLogsCount() > 0) { + otlpLogsRequests.add(request); + } + responseObserver.onNext(ExportLogsServiceResponse.getDefaultInstance()); + responseObserver.onCompleted(); + } + }) + .useBlockingTaskExecutor(true) + .build()); + sb.decorator(LoggingService.newDecorator()); + } + }; + + private OpenTelemetrySdk openTelemetrySdk; + + @BeforeEach + void setUp(@TempDir Path tempDir) throws IOException { + otlpTraceRequests.clear(); + otlpMetricsRequests.clear(); + otlpLogsRequests.clear(); + + String endpoint = "http://localhost:" + server.httpPort(); + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: test\n" + + "propagator:\n" + + " composite:\n" + + " - tracecontext:\n" + + " - baggage:\n" + + "tracer_provider:\n" + + " processors:\n" + + " - batch:\n" + + " schedule_delay: 60000\n" // High delay for reliable export batches after + // flushing + + " exporter:\n" + + " otlp_grpc:\n" + + " endpoint: " + + endpoint + + "\n" + + "meter_provider:\n" + + " readers:\n" + + " - periodic:\n" + + " exporter:\n" + + " otlp_grpc:\n" + + " endpoint: " + + endpoint + + "\n" + + "logger_provider:\n" + + " processors:\n" + + " - batch:\n" + + " schedule_delay: 60000\n" // High delay for reliable export batches after + // flushing + + " exporter:\n" + + " otlp_grpc:\n" + + " endpoint: " + + endpoint + + "\n" + + "instrumentation/development:\n" + + " java:\n" + + " otel_sdk:\n" + + " internal_telemetry_version: latest\n"; + + Path path = tempDir.resolve("otel-config.yaml"); + Files.write(path, yaml.getBytes(StandardCharsets.UTF_8)); + + // Initialize here so we can shutdown when done + GlobalOpenTelemetry.resetForTest(); + ConfigProperties config = + DefaultConfigProperties.createFromMap( + Collections.singletonMap("otel.config.file", path.toString())); + openTelemetrySdk = + AutoConfiguredOpenTelemetrySdk.builder() + .setConfig(config) + .setResultAsGlobal() + .build() + .getOpenTelemetrySdk(); + } + + @AfterEach + void afterEach() { + openTelemetrySdk.close(); + GlobalOpenTelemetry.resetForTest(); + } + + @Test + void configures() throws Exception { + Collection fields = + GlobalOpenTelemetry.get().getPropagators().getTextMapPropagator().fields(); + List keys = new ArrayList<>(); + keys.addAll(W3CTraceContextPropagator.getInstance().fields()); + keys.addAll(W3CBaggagePropagator.getInstance().fields()); + assertThat(fields).containsExactlyInAnyOrderElementsOf(keys); + + GlobalOpenTelemetry.get() + .getTracer("test") + .spanBuilder("test") + .startSpan() + .setAttribute("cat", "meow") + .end(); + + Meter meter = GlobalOpenTelemetry.get().getMeter("test"); + meter.counterBuilder("my-metric").build().add(1); + + Logger logger = GlobalOpenTelemetry.get().getLogsBridge().get("test"); + logger.logRecordBuilder().setBody("info log message").setSeverity(Severity.INFO).emit(); + + openTelemetrySdk.getSdkTracerProvider().forceFlush().join(10, TimeUnit.SECONDS); + openTelemetrySdk.getSdkLoggerProvider().forceFlush().join(10, TimeUnit.SECONDS); + openTelemetrySdk.getSdkMeterProvider().forceFlush().join(10, TimeUnit.SECONDS); + + await().untilAsserted(() -> assertThat(otlpTraceRequests).hasSize(1)); + + ExportTraceServiceRequest traceRequest = otlpTraceRequests.take(); + List spanResourceAttributes = + traceRequest.getResourceSpans(0).getResource().getAttributesList(); + assertHasKeyValue(spanResourceAttributes, "service.name", "test"); + Span span = traceRequest.getResourceSpans(0).getScopeSpans(0).getSpans(0); + assertHasKeyValue(span.getAttributesList(), "cat", "meow"); + + // Flush again to get metric exporter metrics. + openTelemetrySdk.getSdkMeterProvider().forceFlush().join(10, TimeUnit.SECONDS); + // await on assertions since metrics may come in different order for BatchSpanProcessor, + // exporter, or the ones we created in the test. + await() + .untilAsserted(() -> { + ExportMetricsServiceRequest metricRequest = otlpMetricsRequests.take(); + + assertThat(metricRequest.getResourceMetricsList()) + .satisfiesExactly(resourceMetrics -> { + List metricResourceAttributes = + resourceMetrics.getResource().getAttributesList(); + assertHasKeyValue(metricResourceAttributes, "service.name", "test"); + assertThat(resourceMetrics.getScopeMetricsList()) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()).isEqualTo("test"); + assertMetricNames(scopeMetrics, "my-metric"); + }) + // This verifies that MeterProvider was injected into OTLP exporters and + // the internal telemetry version was set. + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_metric_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.metric_data_point.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.metric_data_point.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_log_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.log.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.log.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.exporters.otlp_grpc_span_exporter"); + assertMetricNames( + scopeMetrics, + "otel.sdk.exporter.span.inflight", + "otel.sdk.exporter.operation.duration", + "otel.sdk.exporter.span.exported"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.logs"); + assertMetricNames( + scopeMetrics, + "otel.sdk.log.created", + "otel.sdk.processor.log.processed", + "otel.sdk.processor.log.queue.capacity", + "otel.sdk.processor.log.queue.size"); + }) + .anySatisfy(scopeMetrics -> { + assertThat(scopeMetrics.getScope().getName()) + .isEqualTo("io.opentelemetry.sdk.trace"); + assertMetricNames( + scopeMetrics, + "otel.sdk.span.live", + "otel.sdk.span.started", + "otel.sdk.processor.span.processed", + "otel.sdk.processor.span.queue.capacity", + "otel.sdk.processor.span.queue.size"); + }); + }); + }); + + await().untilAsserted(() -> assertThat(otlpLogsRequests).hasSize(1)); + ExportLogsServiceRequest logRequest = otlpLogsRequests.take(); + List logResourceAttributes = + logRequest.getResourceLogs(0).getResource().getAttributesList(); + assertHasKeyValue(logResourceAttributes, "service.name", "test"); + + assertThat(logRequest.getResourceLogs(0).getScopeLogs(0).getLogRecordsList()) + .satisfiesExactlyInAnyOrder(logRecord -> { + assertThat(logRecord.getBody().getStringValue()).isEqualTo("info log message"); + assertThat(logRecord.getSeverityNumberValue()) + .isEqualTo(Severity.INFO.getSeverityNumber()); + }); + } + + private static void assertHasKeyValue(List keyValues, String key, String value) { + assertThat(keyValues) + .contains( + KeyValue.newBuilder() + .setKey(key) + .setValue(AnyValue.newBuilder().setStringValue(value)) + .build()); + } + + private static void assertMetricNames(ScopeMetrics scopeMetrics, String... names) { + assertThat( + scopeMetrics.getMetricsList().stream().map(Metric::getName).collect(Collectors.toSet())) + .containsExactlyInAnyOrder(names); + } +} diff --git a/sdk-extensions/autoconfigure/src/testInitializeRegistersGlobal/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java b/sdk-extensions/autoconfigure/src/testInitializeRegistersGlobal/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java deleted file mode 100644 index f92982bf05d..00000000000 --- a/sdk-extensions/autoconfigure/src/testInitializeRegistersGlobal/java/io/opentelemetry/sdk/autoconfigure/AutoConfiguredOpenTelemetrySdkTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.sdk.OpenTelemetrySdk; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class AutoConfiguredOpenTelemetrySdkTest { - - @BeforeEach - void setUp() { - GlobalOpenTelemetry.resetForTest(); - } - - @Test - void initializeAndGet() { - OpenTelemetrySdk sdk = AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); - assertThat(GlobalOpenTelemetry.get()) - // ObfuscatedOpenTelemetry - .extracting("delegate") - .isSameAs(sdk); - } - - @Test - void initializeAndGet_noGlobal() { - OpenTelemetrySdk sdk = - AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .build() - .getOpenTelemetrySdk(); - // TODO: calling get() will call initialize() again and autoconfigure another instance of the - // SDK; in that case the get() method will return OpenTelemetrySdk and not - // ObfuscatedOpenTelemetry - assertThat(GlobalOpenTelemetry.get()).isNotSameAs(sdk); - } -} diff --git a/sdk-extensions/autoconfigure/src/testJaeger/java/io/opentelemetry/sdk/autoconfigure/JaegerConfigTest.java b/sdk-extensions/autoconfigure/src/testJaeger/java/io/opentelemetry/sdk/autoconfigure/JaegerConfigTest.java deleted file mode 100644 index 0f4d443f6bd..00000000000 --- a/sdk-extensions/autoconfigure/src/testJaeger/java/io/opentelemetry/sdk/autoconfigure/JaegerConfigTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.server.grpc.GrpcService; -import com.linecorp.armeria.testing.junit5.server.ServerExtension; -import io.grpc.stub.StreamObserver; -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.exporter.jaeger.proto.api_v2.Collector; -import io.opentelemetry.exporter.jaeger.proto.api_v2.CollectorServiceGrpc; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingDeque; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class JaegerConfigTest { - - private static final BlockingQueue jaegerRequests = - new LinkedBlockingDeque<>(); - - @RegisterExtension - public static final ServerExtension server = - new ServerExtension() { - @Override - protected void configure(ServerBuilder sb) { - sb.service( - GrpcService.builder() - // Jaeger - .addService( - new CollectorServiceGrpc.CollectorServiceImplBase() { - @Override - public void postSpans( - Collector.PostSpansRequest request, - StreamObserver responseObserver) { - jaegerRequests.add(request); - responseObserver.onNext(Collector.PostSpansResponse.getDefaultInstance()); - responseObserver.onCompleted(); - } - }) - .useBlockingTaskExecutor(true) - .build()); - } - }; - - @BeforeEach - void setUp() { - jaegerRequests.clear(); - } - - @Test - void configures() { - String endpoint = "http://localhost:" + server.httpPort(); - - System.setProperty("otel.exporter.jaeger.endpoint", endpoint); - - AutoConfiguredOpenTelemetrySdk.initialize(); - - GlobalOpenTelemetry.get().getTracer("test").spanBuilder("test").startSpan().end(); - - await().untilAsserted(() -> assertThat(jaegerRequests).hasSize(1)); - } -} diff --git a/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcConfigTest.java b/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcConfigTest.java deleted file mode 100644 index 8be803c3ac1..00000000000 --- a/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcConfigTest.java +++ /dev/null @@ -1,327 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.OtlpGrpcServerExtension.generateFakeLog; -import static io.opentelemetry.sdk.autoconfigure.OtlpGrpcServerExtension.generateFakeMetric; -import static io.opentelemetry.sdk.autoconfigure.OtlpGrpcServerExtension.generateFakeSpan; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.awaitility.Awaitility.await; - -import com.google.common.collect.Lists; -import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class OtlpGrpcConfigTest { - - private static final List SPAN_DATA = Lists.newArrayList(generateFakeSpan()); - private static final List METRIC_DATA = Lists.newArrayList(generateFakeMetric()); - private static final List LOG_DATA = Lists.newArrayList(generateFakeLog()); - - @RegisterExtension - @Order(1) - public static final SelfSignedCertificateExtension certificate = - new SelfSignedCertificateExtension(); - - @RegisterExtension - @Order(2) - public static final OtlpGrpcServerExtension server = new OtlpGrpcServerExtension(certificate); - - @BeforeEach - void setUp() { - GlobalOpenTelemetry.resetForTest(); - } - - @AfterEach - public void tearDown() { - server.reset(); - GlobalOpenTelemetry.resetForTest(); - } - - @Test - void configureExportersGeneral() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.endpoint", "https://localhost:" + server.httpsPort()); - props.put("otel.exporter.otlp.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.exporter.otlp.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.compression", "gzip"); - props.put("otel.exporter.otlp.timeout", "15s"); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - try (SpanExporter spanExporter = - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop()); - MetricExporter metricExporter = - MetricExporterConfiguration.configureOtlpMetrics(properties); - LogExporter logExporter = - LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) { - assertThat(spanExporter) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(15)); - assertThat(spanExporter.export(SPAN_DATA).join(15, TimeUnit.SECONDS).isSuccess()).isTrue(); - assertThat(server.traceRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains( - ":path", "/opentelemetry.proto.collector.trace.v1.TraceService/Export") - && headers.contains("header-key", "header-value") - && headers.contains("grpc-encoding", "gzip")); - - assertThat(metricExporter) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(15)); - assertThat(metricExporter.export(METRIC_DATA).join(15, TimeUnit.SECONDS).isSuccess()) - .isTrue(); - assertThat(server.metricRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains( - ":path", - "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export") - && headers.contains("header-key", "header-value") - && headers.contains("grpc-encoding", "gzip")); - - assertThat(logExporter) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(15)); - assertThat(logExporter.export(LOG_DATA).join(15, TimeUnit.SECONDS).isSuccess()).isTrue(); - assertThat(server.logRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains( - ":path", "/opentelemetry.proto.collector.logs.v1.LogsService/Export") - && headers.contains("header-key", "header-value") - && headers.contains("grpc-encoding", "gzip")); - } - } - - @Test - void configureSpanExporter() { - // Set values for general and signal specific properties. Signal specific should override - // general. - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.endpoint", "http://foo.bar"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - props.put("otel.exporter.otlp.headers", "header-key=dummy-value"); - props.put("otel.exporter.otlp.compression", "foo"); - props.put("otel.exporter.otlp.timeout", "10s"); - props.put("otel.exporter.otlp.traces.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.traces.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.exporter.otlp.traces.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.traces.compression", "gzip"); - props.put("otel.exporter.otlp.traces.timeout", "15s"); - try (SpanExporter spanExporter = - SpanExporterConfiguration.configureExporter( - "otlp", - DefaultConfigProperties.createForTest(props), - NamedSpiManager.createEmpty(), - MeterProvider.noop())) { - assertThat(spanExporter) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(15)); - assertThat(spanExporter.export(SPAN_DATA).join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); - assertThat(server.traceRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains( - ":path", "/opentelemetry.proto.collector.trace.v1.TraceService/Export") - && headers.contains("header-key", "header-value")); - } - } - - @Test - public void configureMetricExporter() { - // Set values for general and signal specific properties. Signal specific should override - // general. - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.endpoint", "http://foo.bar"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - props.put("otel.exporter.otlp.headers", "header-key=dummy-value"); - props.put("otel.exporter.otlp.compression", "gzip"); - props.put("otel.exporter.otlp.timeout", "10s"); - props.put("otel.exporter.otlp.metrics.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.metrics.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.exporter.otlp.metrics.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.metrics.compression", "gzip"); - props.put("otel.exporter.otlp.metrics.timeout", "15s"); - props.put("otel.exporter.otlp.metrics.temporality.preference", "DELTA"); - try (MetricExporter metricExporter = - MetricExporterConfiguration.configureOtlpMetrics( - DefaultConfigProperties.createForTest(props))) { - - assertThat(metricExporter) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(15)); - assertThat(metricExporter.getAggregationTemporality(InstrumentType.COUNTER)) - .isEqualTo(AggregationTemporality.DELTA); - assertThat(metricExporter.getAggregationTemporality(InstrumentType.UP_DOWN_COUNTER)) - .isEqualTo(AggregationTemporality.CUMULATIVE); - assertThat(metricExporter.export(METRIC_DATA).join(15, TimeUnit.SECONDS).isSuccess()) - .isTrue(); - assertThat(server.metricRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains( - ":path", - "/opentelemetry.proto.collector.metrics.v1.MetricsService/Export") - && headers.contains("header-key", "header-value") - && headers.contains("grpc-encoding", "gzip")); - } - } - - @Test - public void configureLogExporter() { - // Set values for general and signal specific properties. Signal specific should override - // general. - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.endpoint", "http://foo.bar"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - props.put("otel.exporter.otlp.headers", "header-key=dummy-value"); - props.put("otel.exporter.otlp.compression", "gzip"); - props.put("otel.exporter.otlp.timeout", "10s"); - props.put("otel.exporter.otlp.logs.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.logs.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.exporter.otlp.logs.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.logs.compression", "gzip"); - props.put("otel.exporter.otlp.logs.timeout", "15s"); - try (LogExporter logExporter = - LogExporterConfiguration.configureOtlpLogs( - DefaultConfigProperties.createForTest(props), MeterProvider.noop())) { - - assertThat(logExporter) - .extracting("delegate.timeoutNanos") - .isEqualTo(TimeUnit.SECONDS.toNanos(15)); - assertThat(logExporter.export(LOG_DATA).join(15, TimeUnit.SECONDS).isSuccess()).isTrue(); - assertThat(server.logRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains( - ":path", "/opentelemetry.proto.collector.logs.v1.LogsService/Export") - && headers.contains("header-key", "header-value") - && headers.contains("grpc-encoding", "gzip")); - } - } - - @Test - void configureTlsInvalidCertificatePath() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Invalid OTLP certificate/key path:"); - - assertThatThrownBy(() -> MetricExporterConfiguration.configureOtlpMetrics(properties)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Invalid OTLP certificate/key path:"); - - assertThatThrownBy( - () -> LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Invalid OTLP certificate/key path:"); - } - - @Test - void configureTlsMissingClientCertificatePath() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.client.key", Paths.get("foo", "bar", "baz").toString()); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key provided but certification chain is missing"); - - assertThatThrownBy(() -> MetricExporterConfiguration.configureOtlpMetrics(properties)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key provided but certification chain is missing"); - - assertThatThrownBy( - () -> LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key provided but certification chain is missing"); - } - - @Test - void configureTlsMissingClientKeyPath() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.client.certificate", Paths.get("foo", "bar", "baz").toString()); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key chain provided but key is missing"); - - assertThatThrownBy(() -> MetricExporterConfiguration.configureOtlpMetrics(properties)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key chain provided but key is missing"); - - assertThatThrownBy( - () -> LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key chain provided but key is missing"); - } - - @Test - void configuresGlobal() { - System.setProperty("otel.exporter.otlp.endpoint", "https://localhost:" + server.httpsPort()); - System.setProperty( - "otel.exporter.otlp.certificate", certificate.certificateFile().getAbsolutePath()); - System.setProperty("otel.metric.export.interval", "1s"); - - GlobalOpenTelemetry.get().getTracer("test").spanBuilder("test").startSpan().end(); - - await() - .untilAsserted( - () -> { - assertThat(server.traceRequests).hasSize(1); - - // Not well defined how many metric exports would have happened by now, check that - // any did. Metrics are recorded by OtlpGrpcSpanExporter, BatchSpanProcessor, and - // potentially others. - assertThat(server.metricRequests).isNotEmpty(); - }); - } -} diff --git a/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcRetryTest.java b/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcRetryTest.java deleted file mode 100644 index 5e9ea1f5828..00000000000 --- a/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcRetryTest.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.OtlpGrpcServerExtension.generateFakeLog; -import static io.opentelemetry.sdk.autoconfigure.OtlpGrpcServerExtension.generateFakeMetric; -import static io.opentelemetry.sdk.autoconfigure.OtlpGrpcServerExtension.generateFakeSpan; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.Lists; -import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; -import io.grpc.Status; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.grpc.DefaultGrpcExporter; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import java.util.function.Supplier; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressLogger(DefaultGrpcExporter.class) -class OtlpGrpcRetryTest { - - private static final List SPAN_DATA = Lists.newArrayList(generateFakeSpan()); - private static final List METRIC_DATA = Lists.newArrayList(generateFakeMetric()); - private static final List LOG_DATA = Lists.newArrayList(generateFakeLog()); - - @RegisterExtension - @Order(1) - public static final SelfSignedCertificateExtension certificate = - new SelfSignedCertificateExtension(); - - @RegisterExtension - @Order(2) - public static final OtlpGrpcServerExtension server = new OtlpGrpcServerExtension(certificate); - - @Test - @SuppressLogger(DefaultGrpcExporter.class) - void configureSpanExporterRetryPolicy() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.traces.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.traces.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.experimental.exporter.otlp.retry.enabled", "true"); - try (SpanExporter spanExporter = - SpanExporterConfiguration.configureExporter( - "otlp", - DefaultConfigProperties.createForTest(props), - NamedSpiManager.createEmpty(), - MeterProvider.noop())) { - - testRetryableStatusCodes(() -> SPAN_DATA, spanExporter::export, server.traceRequests::size); - testDefaultRetryPolicy(() -> SPAN_DATA, spanExporter::export, server.traceRequests::size); - } - } - - @Test - @SuppressLogger(DefaultGrpcExporter.class) - void configureMetricExporterRetryPolicy() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.metrics.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.metrics.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.experimental.exporter.otlp.retry.enabled", "true"); - try (MetricExporter metricExporter = - MetricExporterConfiguration.configureOtlpMetrics( - DefaultConfigProperties.createForTest(props))) { - - testRetryableStatusCodes( - () -> METRIC_DATA, metricExporter::export, server.metricRequests::size); - testDefaultRetryPolicy( - () -> METRIC_DATA, metricExporter::export, server.metricRequests::size); - } - } - - @Test - @SuppressLogger(DefaultGrpcExporter.class) - void configureLogExporterRetryPolicy() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.logs.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.logs.certificate", certificate.certificateFile().getAbsolutePath()); - props.put("otel.experimental.exporter.otlp.retry.enabled", "true"); - try (LogExporter logExporter = - LogExporterConfiguration.configureOtlpLogs( - DefaultConfigProperties.createForTest(props), MeterProvider.noop())) { - - testRetryableStatusCodes(() -> LOG_DATA, logExporter::export, server.logRequests::size); - testDefaultRetryPolicy(() -> LOG_DATA, logExporter::export, server.logRequests::size); - } - } - - private static void testRetryableStatusCodes( - Supplier dataSupplier, - Function exporter, - Supplier serverRequestCountSupplier) { - for (Status.Code code : Status.Code.values()) { - server.reset(); - - server.responseStatuses.add(Status.fromCode(code)); - server.responseStatuses.add(Status.OK); - - CompletableResultCode resultCode = - exporter.apply(dataSupplier.get()).join(10, TimeUnit.SECONDS); - boolean retryable = - RetryUtil.retryableGrpcStatusCodes().contains(String.valueOf(code.value())); - boolean expectedResult = retryable || code == Status.Code.OK; - assertThat(resultCode.isSuccess()) - .as( - "status code %s should export %s", - code, expectedResult ? "successfully" : "unsuccessfully") - .isEqualTo(expectedResult); - int expectedRequests = retryable ? 2 : 1; - assertThat(serverRequestCountSupplier.get()) - .as("status code %s should make %s requests", code, expectedRequests) - .isEqualTo(expectedRequests); - } - } - - private static void testDefaultRetryPolicy( - Supplier dataSupplier, - Function exporter, - Supplier serverRequestCountSupplier) { - server.reset(); - - // Set the server to fail with a retryable status code for the max attempts - int maxAttempts = RetryPolicy.getDefault().getMaxAttempts(); - int retryableCode = - RetryUtil.retryableGrpcStatusCodes().stream().map(Integer::parseInt).findFirst().get(); - for (int i = 0; i < maxAttempts; i++) { - server.responseStatuses.add(Status.fromCodeValue(retryableCode)); - } - - // Result should be failure, sever should have received maxAttempts requests - CompletableResultCode resultCode = - exporter.apply(dataSupplier.get()).join(10, TimeUnit.SECONDS); - assertThat(resultCode.isSuccess()).isFalse(); - assertThat(serverRequestCountSupplier.get()).isEqualTo(maxAttempts); - } -} diff --git a/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcServerExtension.java b/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcServerExtension.java deleted file mode 100644 index 52759f81363..00000000000 --- a/sdk-extensions/autoconfigure/src/testOtlpGrpc/java/io/opentelemetry/sdk/autoconfigure/OtlpGrpcServerExtension.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -import com.linecorp.armeria.common.RequestHeaders; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.server.grpc.GrpcService; -import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; -import com.linecorp.armeria.testing.junit5.server.ServerExtension; -import io.grpc.Status; -import io.grpc.stub.StreamObserver; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; -import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse; -import io.opentelemetry.proto.collector.logs.v1.LogsServiceGrpc; -import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; -import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse; -import io.opentelemetry.proto.collector.metrics.v1.MetricsServiceGrpc; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse; -import io.opentelemetry.proto.collector.trace.v1.TraceServiceGrpc; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.time.Instant; -import java.util.ArrayDeque; -import java.util.Collections; -import java.util.Queue; - -class OtlpGrpcServerExtension extends ServerExtension { - - final Queue traceRequests = new ArrayDeque<>(); - final Queue metricRequests = new ArrayDeque<>(); - final Queue logRequests = new ArrayDeque<>(); - final Queue responseStatuses = new ArrayDeque<>(); - final Queue requestHeaders = new ArrayDeque<>(); - private final SelfSignedCertificateExtension certificate; - - OtlpGrpcServerExtension(SelfSignedCertificateExtension certificate) { - this.certificate = certificate; - } - - @Override - protected void configure(ServerBuilder sb) { - sb.service( - GrpcService.builder() - .addService( - new TraceServiceGrpc.TraceServiceImplBase() { - @Override - public void export( - ExportTraceServiceRequest request, - StreamObserver responseObserver) { - exportHelper( - traceRequests, - ExportTraceServiceResponse.getDefaultInstance(), - request, - responseObserver); - } - }) - .addService( - new MetricsServiceGrpc.MetricsServiceImplBase() { - @Override - public void export( - ExportMetricsServiceRequest request, - StreamObserver responseObserver) { - exportHelper( - metricRequests, - ExportMetricsServiceResponse.getDefaultInstance(), - request, - responseObserver); - } - }) - .addService( - new LogsServiceGrpc.LogsServiceImplBase() { - @Override - public void export( - ExportLogsServiceRequest request, - StreamObserver responseObserver) { - exportHelper( - logRequests, - ExportLogsServiceResponse.getDefaultInstance(), - request, - responseObserver); - } - }) - .useBlockingTaskExecutor(true) - .build()); - sb.decorator( - (delegate, ctx, req) -> { - requestHeaders.add(req.headers()); - return delegate.serve(ctx, req); - }); - sb.tls(certificate.certificateFile(), certificate.privateKeyFile()); - } - - private void exportHelper( - Queue requests, - ResponseT defaultResponse, - RequestT request, - StreamObserver responseObserver) { - requests.add(request); - Status responseStatus = responseStatuses.peek() != null ? responseStatuses.poll() : Status.OK; - if (responseStatus.isOk()) { - responseObserver.onNext(defaultResponse); - responseObserver.onCompleted(); - return; - } - responseObserver.onError(responseStatus.asRuntimeException()); - } - - void reset() { - traceRequests.clear(); - metricRequests.clear(); - logRequests.clear(); - requestHeaders.clear(); - responseStatuses.clear(); - } - - static SpanData generateFakeSpan() { - return TestSpanData.builder() - .setHasEnded(true) - .setName("name") - .setStartEpochNanos(MILLISECONDS.toNanos(System.currentTimeMillis())) - .setEndEpochNanos(MILLISECONDS.toNanos(System.currentTimeMillis())) - .setKind(SpanKind.SERVER) - .setStatus(StatusData.error()) - .setTotalRecordedEvents(0) - .setTotalRecordedLinks(0) - .build(); - } - - static MetricData generateFakeMetric() { - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "metric_name", - "metric_description", - "ms", - ImmutableSumData.create( - false, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - MILLISECONDS.toNanos(System.currentTimeMillis()), - MILLISECONDS.toNanos(System.currentTimeMillis()), - Attributes.of(stringKey("key"), "value"), - 10)))); - } - - static LogData generateFakeLog() { - return LogDataBuilder.create(Resource.empty(), InstrumentationScopeInfo.empty()) - .setEpoch(Instant.now()) - .setBody("log body") - .build(); - } -} diff --git a/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpConfigTest.java b/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpConfigTest.java deleted file mode 100644 index b1d659a0ad1..00000000000 --- a/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpConfigTest.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.OtlpHttpServerExtension.generateFakeLog; -import static io.opentelemetry.sdk.autoconfigure.OtlpHttpServerExtension.generateFakeMetric; -import static io.opentelemetry.sdk.autoconfigure.OtlpHttpServerExtension.generateFakeSpan; -import static org.assertj.core.api.Assertions.as; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.awaitility.Awaitility.await; - -import com.google.common.collect.Lists; -import io.opentelemetry.api.GlobalOpenTelemetry; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import okhttp3.OkHttpClient; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class OtlpHttpConfigTest { - - @RegisterExtension - public static final OtlpHttpServerExtension server = new OtlpHttpServerExtension(); - - @BeforeEach - void setUp() { - server.reset(); - GlobalOpenTelemetry.resetForTest(); - } - - @AfterEach - public void tearDown() { - GlobalOpenTelemetry.resetForTest(); - } - - @Test - void configureExportersGeneral() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "http/protobuf"); - props.put("otel.exporter.otlp.endpoint", "https://localhost:" + server.httpsPort()); - props.put( - "otel.exporter.otlp.certificate", server.selfSignedCertificate.certificate().getPath()); - props.put("otel.exporter.otlp.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.compression", "gzip"); - props.put("otel.exporter.otlp.timeout", "15s"); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - SpanExporter spanExporter = - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop()); - MetricExporter metricExporter = MetricExporterConfiguration.configureOtlpMetrics(properties); - LogExporter logExporter = - LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop()); - - assertThat(spanExporter) - .extracting("delegate.client", as(InstanceOfAssertFactories.type(OkHttpClient.class))) - .extracting(OkHttpClient::callTimeoutMillis) - .isEqualTo((int) TimeUnit.SECONDS.toMillis(15)); - assertThat( - spanExporter - .export(Lists.newArrayList(generateFakeSpan())) - .join(15, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - assertThat(server.traceRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains(":path", "/v1/traces") - && headers.contains("header-key", "header-value") - && headers.contains("content-encoding", "gzip")); - - assertThat(metricExporter) - .extracting("delegate.client", as(InstanceOfAssertFactories.type(OkHttpClient.class))) - .extracting(OkHttpClient::callTimeoutMillis) - .isEqualTo((int) TimeUnit.SECONDS.toMillis(15)); - assertThat( - metricExporter - .export(Lists.newArrayList(generateFakeMetric())) - .join(15, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - assertThat(server.metricRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains(":path", "/v1/metrics") - && headers.contains("header-key", "header-value") - && headers.contains("content-encoding", "gzip")); - - assertThat(logExporter) - .extracting("delegate.client", as(InstanceOfAssertFactories.type(OkHttpClient.class))) - .extracting(OkHttpClient::callTimeoutMillis) - .isEqualTo((int) TimeUnit.SECONDS.toMillis(15)); - assertThat( - logExporter - .export(Lists.newArrayList(generateFakeLog())) - .join(15, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - assertThat(server.logRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains(":path", "/v1/logs") - && headers.contains("header-key", "header-value") - && headers.contains("content-encoding", "gzip")); - } - - @Test - void configureSpanExporter() { - // Set values for general and signal specific properties. Signal specific should override - // general. - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "grpc"); - props.put("otel.exporter.otlp.endpoint", "http://foo.bar"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - props.put("otel.exporter.otlp.headers", "header-key=dummy-value"); - props.put("otel.exporter.otlp.compression", "foo"); - props.put("otel.exporter.otlp.timeout", "10s"); - props.put("otel.exporter.otlp.traces.protocol", "http/protobuf"); - props.put( - "otel.exporter.otlp.traces.endpoint", - "https://localhost:" + server.httpsPort() + "/v1/traces"); - props.put( - "otel.exporter.otlp.traces.certificate", - server.selfSignedCertificate.certificate().getPath()); - props.put("otel.exporter.otlp.traces.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.traces.compression", "gzip"); - props.put("otel.exporter.otlp.traces.timeout", "15s"); - SpanExporter spanExporter = - SpanExporterConfiguration.configureExporter( - "otlp", - DefaultConfigProperties.createForTest(props), - NamedSpiManager.createEmpty(), - MeterProvider.noop()); - - assertThat(spanExporter) - .extracting("delegate.client", as(InstanceOfAssertFactories.type(OkHttpClient.class))) - .extracting(OkHttpClient::callTimeoutMillis) - .isEqualTo((int) TimeUnit.SECONDS.toMillis(15)); - assertThat( - spanExporter - .export(Lists.newArrayList(generateFakeSpan())) - .join(10, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - assertThat(server.traceRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains(":path", "/v1/traces") - && headers.contains("header-key", "header-value") - && headers.contains("content-encoding", "gzip")); - } - - @Test - public void configureMetricExporter() { - // Set values for general and signal specific properties. Signal specific should override - // general. - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "grpc"); - props.put("otel.exporter.otlp.endpoint", "http://foo.bar"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - props.put("otel.exporter.otlp.headers", "header-key=dummy-value"); - props.put("otel.exporter.otlp.compression", "foo"); - props.put("otel.exporter.otlp.timeout", "10s"); - props.put("otel.exporter.otlp.metrics.protocol", "http/protobuf"); - props.put( - "otel.exporter.otlp.metrics.endpoint", - "https://localhost:" + server.httpsPort() + "/v1/metrics"); - props.put( - "otel.exporter.otlp.metrics.certificate", - server.selfSignedCertificate.certificate().getPath()); - props.put("otel.exporter.otlp.metrics.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.metrics.compression", "gzip"); - props.put("otel.exporter.otlp.metrics.timeout", "15s"); - props.put("otel.exporter.otlp.metrics.temporality.preference", "DELTA"); - MetricExporter metricExporter = - MetricExporterConfiguration.configureOtlpMetrics( - DefaultConfigProperties.createForTest(props)); - - assertThat(metricExporter) - .extracting("delegate.client", as(InstanceOfAssertFactories.type(OkHttpClient.class))) - .extracting(OkHttpClient::callTimeoutMillis) - .isEqualTo((int) TimeUnit.SECONDS.toMillis(15)); - assertThat(metricExporter.getAggregationTemporality(InstrumentType.COUNTER)) - .isEqualTo(AggregationTemporality.DELTA); - assertThat( - metricExporter - .export(Lists.newArrayList(generateFakeMetric())) - .join(15, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - assertThat(server.metricRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains(":path", "/v1/metrics") - && headers.contains("header-key", "header-value")); - } - - @Test - public void configureLogExporter() { - // Set values for general and signal specific properties. Signal specific should override - // general. - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "grpc"); - props.put("otel.exporter.otlp.endpoint", "http://foo.bar"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - props.put("otel.exporter.otlp.headers", "header-key=dummy-value"); - props.put("otel.exporter.otlp.compression", "foo"); - props.put("otel.exporter.otlp.timeout", "10s"); - props.put("otel.exporter.otlp.logs.protocol", "http/protobuf"); - props.put( - "otel.exporter.otlp.logs.endpoint", "https://localhost:" + server.httpsPort() + "/v1/logs"); - props.put( - "otel.exporter.otlp.logs.certificate", - server.selfSignedCertificate.certificate().getPath()); - props.put("otel.exporter.otlp.logs.headers", "header-key=header-value"); - props.put("otel.exporter.otlp.logs.compression", "gzip"); - props.put("otel.exporter.otlp.logs.timeout", "15s"); - LogExporter logExporter = - LogExporterConfiguration.configureOtlpLogs( - DefaultConfigProperties.createForTest(props), MeterProvider.noop()); - - assertThat(logExporter) - .extracting("delegate.client", as(InstanceOfAssertFactories.type(OkHttpClient.class))) - .extracting(OkHttpClient::callTimeoutMillis) - .isEqualTo((int) TimeUnit.SECONDS.toMillis(15)); - assertThat( - logExporter - .export(Lists.newArrayList(generateFakeLog())) - .join(15, TimeUnit.SECONDS) - .isSuccess()) - .isTrue(); - assertThat(server.logRequests).hasSize(1); - assertThat(server.requestHeaders) - .anyMatch( - headers -> - headers.contains(":path", "/v1/logs") - && headers.contains("header-key", "header-value")); - } - - @Test - void configureTlsInvalidCertificatePath() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "http/protobuf"); - props.put("otel.exporter.otlp.certificate", Paths.get("foo", "bar", "baz").toString()); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Invalid OTLP certificate/key path:"); - - assertThatThrownBy(() -> MetricExporterConfiguration.configureOtlpMetrics(properties)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Invalid OTLP certificate/key path:"); - - assertThatThrownBy( - () -> LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Invalid OTLP certificate/key path:"); - } - - @Test - void configureTlsMissingClientCertificatePath() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "http/protobuf"); - props.put("otel.exporter.otlp.client.key", Paths.get("foo", "bar", "baz").toString()); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key provided but certification chain is missing"); - - assertThatThrownBy(() -> MetricExporterConfiguration.configureOtlpMetrics(properties)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key provided but certification chain is missing"); - - assertThatThrownBy( - () -> LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key provided but certification chain is missing"); - } - - @Test - void configureTlsMissingClientKeyPath() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.protocol", "http/protobuf"); - props.put("otel.exporter.otlp.client.certificate", Paths.get("foo", "bar", "baz").toString()); - ConfigProperties properties = DefaultConfigProperties.createForTest(props); - - assertThatThrownBy( - () -> - SpanExporterConfiguration.configureExporter( - "otlp", properties, NamedSpiManager.createEmpty(), MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key chain provided but key is missing"); - - assertThatThrownBy(() -> MetricExporterConfiguration.configureOtlpMetrics(properties)) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key chain provided but key is missing"); - - assertThatThrownBy( - () -> LogExporterConfiguration.configureOtlpLogs(properties, MeterProvider.noop())) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Client key chain provided but key is missing"); - } - - @Test - void configuresGlobal() { - System.setProperty("otel.exporter.otlp.protocol", "http/protobuf"); - System.setProperty( - "otel.exporter.otlp.endpoint", "https://localhost:" + server.httpsPort() + "/"); - System.setProperty( - "otel.exporter.otlp.certificate", server.selfSignedCertificate.certificate().getPath()); - System.setProperty("otel.metric.export.interval", "1s"); - - GlobalOpenTelemetry.get().getTracer("test").spanBuilder("test").startSpan().end(); - - await() - .untilAsserted( - () -> { - assertThat(server.traceRequests).hasSize(1); - - // Not well defined how many metric exports would have happened by now, check that - // any did. Metrics are recorded by OtlpHttpSpanExporter, BatchSpanProcessor, and - // potentially others. - assertThat(server.metricRequests).isNotEmpty(); - }); - } -} diff --git a/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpRetryTest.java b/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpRetryTest.java deleted file mode 100644 index 8fb520d7db3..00000000000 --- a/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpRetryTest.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.sdk.autoconfigure.OtlpHttpServerExtension.generateFakeLog; -import static io.opentelemetry.sdk.autoconfigure.OtlpHttpServerExtension.generateFakeMetric; -import static io.opentelemetry.sdk.autoconfigure.OtlpHttpServerExtension.generateFakeSpan; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.Lists; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter; -import io.opentelemetry.exporter.internal.okhttp.OkHttpExporter; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.export.LogExporter; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.MetricExporter; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import java.util.function.Supplier; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressLogger(OkHttpExporter.class) -class OtlpHttpRetryTest { - - private static final List SPAN_DATA = Lists.newArrayList(generateFakeSpan()); - private static final List METRIC_DATA = Lists.newArrayList(generateFakeMetric()); - private static final List LOG_DATA = Lists.newArrayList(generateFakeLog()); - - @RegisterExtension - public static final OtlpHttpServerExtension server = new OtlpHttpServerExtension(); - - @Test - @SuppressLogger(OkHttpGrpcExporter.class) - void configureSpanExporterRetryPolicy() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.traces.protocol", "http/protobuf"); - props.put( - "otel.exporter.otlp.traces.endpoint", - "https://localhost:" + server.httpsPort() + "/v1/traces"); - props.put( - "otel.exporter.otlp.traces.certificate", - server.selfSignedCertificate.certificate().getPath()); - props.put("otel.experimental.exporter.otlp.retry.enabled", "true"); - try (SpanExporter spanExporter = - SpanExporterConfiguration.configureExporter( - "otlp", - DefaultConfigProperties.createForTest(props), - NamedSpiManager.createEmpty(), - MeterProvider.noop())) { - - testRetryableStatusCodes(() -> SPAN_DATA, spanExporter::export, server.traceRequests::size); - testDefaultRetryPolicy(() -> SPAN_DATA, spanExporter::export, server.traceRequests::size); - } - } - - @Test - @SuppressLogger(OkHttpGrpcExporter.class) - void configureMetricExporterRetryPolicy() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.metrics.protocol", "http/protobuf"); - props.put( - "otel.exporter.otlp.metrics.endpoint", - "https://localhost:" + server.httpsPort() + "/v1/metrics"); - props.put( - "otel.exporter.otlp.metrics.certificate", - server.selfSignedCertificate.certificate().getPath()); - props.put("otel.experimental.exporter.otlp.retry.enabled", "true"); - try (MetricExporter metricExporter = - MetricExporterConfiguration.configureOtlpMetrics( - DefaultConfigProperties.createForTest(props))) { - - testRetryableStatusCodes( - () -> METRIC_DATA, metricExporter::export, server.metricRequests::size); - testDefaultRetryPolicy( - () -> METRIC_DATA, metricExporter::export, server.metricRequests::size); - } - } - - @Test - @SuppressLogger(OkHttpGrpcExporter.class) - void configureLogExporterRetryPolicy() { - Map props = new HashMap<>(); - props.put("otel.exporter.otlp.logs.protocol", "http/protobuf"); - props.put( - "otel.exporter.otlp.logs.endpoint", "https://localhost:" + server.httpsPort() + "/v1/logs"); - props.put( - "otel.exporter.otlp.logs.certificate", - server.selfSignedCertificate.certificate().getPath()); - props.put("otel.experimental.exporter.otlp.retry.enabled", "true"); - try (LogExporter logExporter = - LogExporterConfiguration.configureOtlpLogs( - DefaultConfigProperties.createForTest(props), MeterProvider.noop())) { - - testRetryableStatusCodes(() -> LOG_DATA, logExporter::export, server.logRequests::size); - testDefaultRetryPolicy(() -> LOG_DATA, logExporter::export, server.logRequests::size); - } - } - - private static void testRetryableStatusCodes( - Supplier dataSupplier, - Function exporter, - Supplier serverRequestCountSupplier) { - - List statusCodes = Arrays.asList(200, 400, 401, 403, 429, 500, 501, 502, 503); - - for (Integer code : statusCodes) { - server.reset(); - - server.responses.add(HttpResponse.of(HttpStatus.valueOf(code))); - server.responses.add(HttpResponse.of(HttpStatus.OK)); - - CompletableResultCode resultCode = - exporter.apply(dataSupplier.get()).join(10, TimeUnit.SECONDS); - boolean retryable = code != 200 && RetryUtil.retryableHttpResponseCodes().contains(code); - boolean expectedResult = retryable || code == 200; - assertThat(resultCode.isSuccess()) - .as( - "status code %s should export %s", - code, expectedResult ? "successfully" : "unsuccessfully") - .isEqualTo(expectedResult); - int expectedRequests = retryable ? 2 : 1; - assertThat(serverRequestCountSupplier.get()) - .as("status code %s should make %s requests", code, expectedRequests) - .isEqualTo(expectedRequests); - } - } - - private static void testDefaultRetryPolicy( - Supplier dataSupplier, - Function exporter, - Supplier serverRequestCountSupplier) { - server.reset(); - - // Set the server to fail with a retryable status code for the max attempts - int maxAttempts = RetryPolicy.getDefault().getMaxAttempts(); - int retryableCode = 503; - for (int i = 0; i < maxAttempts; i++) { - server.responses.add(HttpResponse.of(retryableCode)); - } - - // Result should be failure, sever should have received maxAttempts requests - CompletableResultCode resultCode = - exporter.apply(dataSupplier.get()).join(10, TimeUnit.SECONDS); - assertThat(resultCode.isSuccess()).isFalse(); - assertThat(serverRequestCountSupplier.get()).isEqualTo(maxAttempts); - } -} diff --git a/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpServerExtension.java b/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpServerExtension.java deleted file mode 100644 index 276843ba99a..00000000000 --- a/sdk-extensions/autoconfigure/src/testOtlpHttp/java/io/opentelemetry/sdk/autoconfigure/OtlpHttpServerExtension.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static java.util.concurrent.TimeUnit.MILLISECONDS; - -import com.google.protobuf.Message; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.common.RequestHeaders; -import com.linecorp.armeria.internal.common.util.SelfSignedCertificate; -import com.linecorp.armeria.server.HttpService; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.testing.junit5.server.ServerExtension; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest; -import io.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest; -import io.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.security.cert.CertificateException; -import java.time.Instant; -import java.util.ArrayDeque; -import java.util.Collections; -import java.util.Queue; -import okio.Buffer; -import okio.GzipSource; -import okio.Okio; - -class OtlpHttpServerExtension extends ServerExtension { - - final SelfSignedCertificate selfSignedCertificate; - - final Queue traceRequests = new ArrayDeque<>(); - final Queue metricRequests = new ArrayDeque<>(); - final Queue logRequests = new ArrayDeque<>(); - final Queue responses = new ArrayDeque<>(); - final Queue requestHeaders = new ArrayDeque<>(); - - OtlpHttpServerExtension() { - try { - selfSignedCertificate = new SelfSignedCertificate(); - } catch (CertificateException e) { - throw new IllegalStateException("Unable to setup certificate.", e); - } - } - - @Override - protected void configure(ServerBuilder sb) { - sb.service( - "/v1/traces", - httpService(traceRequests, ExportTraceServiceRequest.getDefaultInstance())) - .service( - "/v1/metrics", - httpService(metricRequests, ExportMetricsServiceRequest.getDefaultInstance())) - .service( - "/v1/logs", httpService(logRequests, ExportLogsServiceRequest.getDefaultInstance())); - sb.tls(selfSignedCertificate.certificate(), selfSignedCertificate.privateKey()); - } - - @SuppressWarnings("unchecked") - private HttpService httpService(Queue queue, T defaultMessage) { - return (ctx, req) -> - HttpResponse.from( - req.aggregate() - .thenApply( - aggReq -> { - requestHeaders.add(aggReq.headers()); - try { - byte[] requestBody = - maybeGzipInflate(aggReq.headers(), aggReq.content().array()); - queue.add((T) defaultMessage.getParserForType().parseFrom(requestBody)); - } catch (IOException e) { - return HttpResponse.of(HttpStatus.BAD_REQUEST); - } - return responses.peek() != null - ? responses.poll() - : HttpResponse.of(HttpStatus.OK); - })); - } - - private static byte[] maybeGzipInflate(RequestHeaders requestHeaders, byte[] content) - throws IOException { - if (!requestHeaders.contains("content-encoding", "gzip")) { - return content; - } - Buffer buffer = new Buffer(); - GzipSource gzipSource = new GzipSource(Okio.source(new ByteArrayInputStream(content))); - gzipSource.read(buffer, Integer.MAX_VALUE); - return buffer.readByteArray(); - } - - void reset() { - traceRequests.clear(); - metricRequests.clear(); - logRequests.clear(); - requestHeaders.clear(); - responses.clear(); - } - - static SpanData generateFakeSpan() { - return TestSpanData.builder() - .setHasEnded(true) - .setName("name") - .setStartEpochNanos(MILLISECONDS.toNanos(System.currentTimeMillis())) - .setEndEpochNanos(MILLISECONDS.toNanos(System.currentTimeMillis())) - .setKind(SpanKind.SERVER) - .setStatus(StatusData.error()) - .setTotalRecordedEvents(0) - .setTotalRecordedLinks(0) - .build(); - } - - static MetricData generateFakeMetric() { - return ImmutableMetricData.createLongSum( - Resource.empty(), - InstrumentationScopeInfo.empty(), - "metric_name", - "metric_description", - "ms", - ImmutableSumData.create( - false, - AggregationTemporality.CUMULATIVE, - Collections.singletonList( - ImmutableLongPointData.create( - MILLISECONDS.toNanos(System.currentTimeMillis()), - MILLISECONDS.toNanos(System.currentTimeMillis()), - Attributes.of(stringKey("key"), "value"), - 10)))); - } - - static LogData generateFakeLog() { - return LogDataBuilder.create(Resource.empty(), InstrumentationScopeInfo.empty()) - .setEpoch(Instant.now()) - .setBody("log body") - .build(); - } -} diff --git a/sdk-extensions/autoconfigure/src/testPrometheus/java/io/opentelemetry/sdk/autoconfigure/PrometheusTest.java b/sdk-extensions/autoconfigure/src/testPrometheus/java/io/opentelemetry/sdk/autoconfigure/PrometheusTest.java deleted file mode 100644 index 0655f731557..00000000000 --- a/sdk-extensions/autoconfigure/src/testPrometheus/java/io/opentelemetry/sdk/autoconfigure/PrometheusTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.linecorp.armeria.client.WebClient; -import com.linecorp.armeria.common.AggregatedHttpResponse; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.OpenTelemetrySdk; -import java.io.IOException; -import java.net.ServerSocket; -import org.junit.jupiter.api.Test; - -class PrometheusTest { - - @Test - void prometheusExporter() throws Exception { - int port = 9464; - // Just use prometheus standard port if it's available - try (ServerSocket unused = new ServerSocket(port)) { - // Port available - } catch (IOException e) { - // Otherwise use a random port. There's a small race if another process takes it before we - // initialize. Consider adding retries to this test if it flakes, presumably it never will on - // CI since there's no prometheus there blocking the well-known port. - try (ServerSocket socket2 = new ServerSocket(0)) { - port = socket2.getLocalPort(); - } - } - System.setProperty("otel.exporter.prometheus.host", "127.0.0.1"); - System.setProperty("otel.exporter.prometheus.port", String.valueOf(port)); - OpenTelemetrySdk openTelemetrySdk = - AutoConfiguredOpenTelemetrySdk.initialize().getOpenTelemetrySdk(); - - openTelemetrySdk - .getMeterProvider() - .get("test") - .gaugeBuilder("test") - .ofLongs() - .buildWithCallback(result -> result.record(2, Attributes.empty())); - - WebClient client = WebClient.of("http://127.0.0.1:" + port); - AggregatedHttpResponse response = client.get("/metrics").aggregate().join(); - assertThat(response.contentUtf8()).contains("test 2.0"); - } -} diff --git a/sdk-extensions/autoconfigure/src/testZipkin/java/io/opentelemetry/sdk/autoconfigure/ZipkinConfigTest.java b/sdk-extensions/autoconfigure/src/testZipkin/java/io/opentelemetry/sdk/autoconfigure/ZipkinConfigTest.java deleted file mode 100644 index 58e5046c91c..00000000000 --- a/sdk-extensions/autoconfigure/src/testZipkin/java/io/opentelemetry/sdk/autoconfigure/ZipkinConfigTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.autoconfigure; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.awaitility.Awaitility.await; - -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.testing.junit5.server.ServerExtension; -import io.opentelemetry.api.GlobalOpenTelemetry; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingDeque; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class ZipkinConfigTest { - - private static final BlockingQueue zipkinJsonRequests = new LinkedBlockingDeque<>(); - - @RegisterExtension - public static final ServerExtension server = - new ServerExtension() { - @Override - protected void configure(ServerBuilder sb) { - // Zipkin - sb.service( - "/api/v2/spans", - (ctx, req) -> - HttpResponse.from( - req.aggregate() - .thenApply( - aggRes -> { - zipkinJsonRequests.add(aggRes.contentUtf8()); - return HttpResponse.of(HttpStatus.OK); - }))); - } - }; - - @BeforeEach - void setUp() { - zipkinJsonRequests.clear(); - } - - @Test - void configures() { - String endpoint = "localhost:" + server.httpPort(); - - System.setProperty("otel.exporter.zipkin.endpoint", "http://" + endpoint + "/api/v2/spans"); - System.setProperty("otel.exporter.zipkin.timeout", "5s"); - - AutoConfiguredOpenTelemetrySdk.initialize(); - - GlobalOpenTelemetry.get().getTracer("test").spanBuilder("test").startSpan().end(); - - await().untilAsserted(() -> assertThat(zipkinJsonRequests).hasSize(1)); - } -} diff --git a/sdk-extensions/aws/README.md b/sdk-extensions/aws/README.md deleted file mode 100644 index 459cd3419b3..00000000000 --- a/sdk-extensions/aws/README.md +++ /dev/null @@ -1,12 +0,0 @@ -# OpenTelemetry AWS Utils - -[![Javadocs][javadoc-image]][javadoc-url] - ---- -#### Running micro-benchmarks -From the root of the repo run `./gradlew clean :opentelemetry-sdk-extension-aws:jmh` to run all the benchmarks -or run `./gradlew clean :opentelemetry-sdk-extension-aws:jmh -PjmhIncludeSingleClass=` -to run a specific benchmark class. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-aws.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-aws diff --git a/sdk-extensions/aws/build.gradle.kts b/sdk-extensions/aws/build.gradle.kts deleted file mode 100644 index e185d54f766..00000000000 --- a/sdk-extensions/aws/build.gradle.kts +++ /dev/null @@ -1,32 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.jmh-conventions") -} - -description = "OpenTelemetry SDK AWS Instrumentation Support" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.trace.aws") - -dependencies { - api(project(":api:all")) - api(project(":sdk:all")) - - compileOnly(project(":sdk-extensions:autoconfigure")) - - annotationProcessor("com.google.auto.value:auto-value") - - implementation(project(":semconv")) - - implementation("com.fasterxml.jackson.core:jackson-core") - implementation("com.squareup.okhttp3:okhttp") - - testImplementation(project(":sdk:testing")) - testImplementation(project(":sdk-extensions:autoconfigure")) - - testImplementation("com.linecorp.armeria:armeria-junit5") - testRuntimeOnly("org.bouncycastle:bcpkix-jdk15on") - - testImplementation("com.google.guava:guava") - testImplementation("org.skyscreamer:jsonassert") -} diff --git a/sdk-extensions/aws/src/jmh/java/io/opentelemetry/sdk/extension/aws/AwsXrayIdGeneratorBenchmark.java b/sdk-extensions/aws/src/jmh/java/io/opentelemetry/sdk/extension/aws/AwsXrayIdGeneratorBenchmark.java deleted file mode 100644 index 103836cbbb4..00000000000 --- a/sdk-extensions/aws/src/jmh/java/io/opentelemetry/sdk/extension/aws/AwsXrayIdGeneratorBenchmark.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws; - -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Warmup; - -@State(Scope.Benchmark) -@SuppressWarnings("deprecation") // Moved to contrib -public class AwsXrayIdGeneratorBenchmark { - private final io.opentelemetry.sdk.extension.aws.trace.AwsXrayIdGenerator idGenerator = - io.opentelemetry.sdk.extension.aws.trace.AwsXrayIdGenerator.getInstance(); - - @Benchmark - @Measurement(iterations = 15, time = 1) - @Warmup(iterations = 5, time = 1) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @BenchmarkMode(Mode.AverageTime) - @Fork(1) - public String generateTraceId() { - return idGenerator.generateTraceId(); - } - - @Benchmark - @Measurement(iterations = 15, time = 1) - @Warmup(iterations = 5, time = 1) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @BenchmarkMode(Mode.AverageTime) - @Fork(1) - public String generateSpanId() { - return idGenerator.generateSpanId(); - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResource.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResource.java deleted file mode 100644 index b9f24fe6517..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResource.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.File; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A factory for a {@link Resource} which provides information about the current EC2 instance if - * running on AWS Elastic Beanstalk. - */ -public final class BeanstalkResource { - - private static final Logger logger = Logger.getLogger(BeanstalkResource.class.getName()); - - private static final String DEVELOPMENT_ID = "deployment_id"; - private static final String VERSION_LABEL = "version_label"; - private static final String ENVIRONMENT_NAME = "environment_name"; - private static final String BEANSTALK_CONF_PATH = "/var/elasticbeanstalk/xray/environment.conf"; - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a factory for a {@link Resource} which provides information about the current EC2 - * instance if running on AWS Elastic Beanstalk. - */ - public static Resource get() { - return INSTANCE; - } - - private static Resource buildResource() { - return buildResource(BEANSTALK_CONF_PATH); - } - - // Visible for testing - static Resource buildResource(String configPath) { - File configFile = new File(configPath); - if (!configFile.exists()) { - return Resource.empty(); - } - - AttributesBuilder attrBuilders = Attributes.builder(); - try (JsonParser parser = JSON_FACTORY.createParser(configFile)) { - parser.nextToken(); - - if (!parser.isExpectedStartObjectToken()) { - logger.log(Level.WARNING, "Invalid Beanstalk config: ", configPath); - return Resource.create(attrBuilders.build(), ResourceAttributes.SCHEMA_URL); - } - - while (parser.nextToken() != JsonToken.END_OBJECT) { - parser.nextValue(); - String value = parser.getText(); - switch (parser.getCurrentName()) { - case DEVELOPMENT_ID: - attrBuilders.put(ResourceAttributes.SERVICE_INSTANCE_ID, value); - break; - case VERSION_LABEL: - attrBuilders.put(ResourceAttributes.SERVICE_VERSION, value); - break; - case ENVIRONMENT_NAME: - attrBuilders.put(ResourceAttributes.SERVICE_NAMESPACE, value); - break; - default: - parser.skipChildren(); - } - } - } catch (IOException e) { - logger.log(Level.WARNING, "Could not parse Beanstalk config.", e); - return Resource.empty(); - } - - attrBuilders.put(ResourceAttributes.CLOUD_PROVIDER, ResourceAttributes.CloudProviderValues.AWS); - attrBuilders.put( - ResourceAttributes.CLOUD_PLATFORM, - ResourceAttributes.CloudPlatformValues.AWS_ELASTIC_BEANSTALK); - - return Resource.create(attrBuilders.build(), ResourceAttributes.SCHEMA_URL); - } - - private BeanstalkResource() {} -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResourceProvider.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResourceProvider.java deleted file mode 100644 index 400b3d753b1..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link BeanstalkResource}. */ -public final class BeanstalkResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return BeanstalkResource.get(); - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/DockerHelper.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/DockerHelper.java deleted file mode 100644 index 72206ec0185..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/DockerHelper.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import java.io.BufferedReader; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.io.IOException; -import java.util.logging.Level; -import java.util.logging.Logger; - -class DockerHelper { - - private static final Logger logger = Logger.getLogger(DockerHelper.class.getName()); - private static final int CONTAINER_ID_LENGTH = 64; - private static final String DEFAULT_CGROUP_PATH = "/proc/self/cgroup"; - - private final String cgroupPath; - - DockerHelper() { - this(DEFAULT_CGROUP_PATH); - } - - // Visible for testing - DockerHelper(String cgroupPath) { - this.cgroupPath = cgroupPath; - } - - /** - * Get docker container id from local cgroup file. - * - * @return docker container ID. Empty string if it can`t be found. - */ - @SuppressWarnings("DefaultCharset") - public String getContainerId() { - try (BufferedReader br = new BufferedReader(new FileReader(cgroupPath))) { - String line; - while ((line = br.readLine()) != null) { - if (line.length() > CONTAINER_ID_LENGTH) { - return line.substring(line.length() - CONTAINER_ID_LENGTH); - } - } - } catch (FileNotFoundException e) { - logger.log(Level.WARNING, "Failed to read container id, cgroup file does not exist."); - } catch (IOException e) { - logger.log(Level.WARNING, "Unable to read container id: " + e.getMessage()); - } - - return ""; - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/Ec2Resource.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/Ec2Resource.java deleted file mode 100644 index 34df4e58983..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/Ec2Resource.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A factory for a {@link Resource} which provides information about the current EC2 instance if - * running on AWS EC2. - */ -public final class Ec2Resource { - - private static final Logger logger = Logger.getLogger(Ec2Resource.class.getName()); - - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - - private static final String DEFAULT_IMDS_ENDPOINT = "169.254.169.254"; - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a @link Resource} which provides information about the current EC2 instance if running - * on AWS EC2. - */ - public static Resource get() { - return INSTANCE; - } - - private static Resource buildResource() { - // This property is only for testing e.g., with a mock IMDS server and never in production so we - // just - // read from a system property. This is similar to the AWS SDK. - return buildResource( - System.getProperty("otel.aws.imds.endpointOverride", DEFAULT_IMDS_ENDPOINT)); - } - - // Visible for testing - static Resource buildResource(String endpoint) { - String urlBase = "http://" + endpoint; - URL identityDocumentUrl; - URL hostnameUrl; - URL tokenUrl; - try { - identityDocumentUrl = new URL(urlBase + "/latest/dynamic/instance-identity/document"); - hostnameUrl = new URL(urlBase + "/latest/meta-data/hostname"); - tokenUrl = new URL(urlBase + "/latest/api/token"); - } catch (MalformedURLException e) { - // Can only happen when overriding the endpoint in testing so just throw. - throw new IllegalArgumentException("Illegal endpoint: " + endpoint, e); - } - - String token = fetchToken(tokenUrl); - - // If token is empty, either IMDSv2 isn't enabled or an unexpected failure happened. We can - // still get data if IMDSv1 is enabled. - String identity = fetchIdentity(identityDocumentUrl, token); - if (identity.isEmpty()) { - // If no identity document, assume we are not actually running on EC2. - return Resource.empty(); - } - - String hostname = fetchHostname(hostnameUrl, token); - - AttributesBuilder attrBuilders = Attributes.builder(); - attrBuilders.put(ResourceAttributes.CLOUD_PROVIDER, ResourceAttributes.CloudProviderValues.AWS); - attrBuilders.put( - ResourceAttributes.CLOUD_PLATFORM, ResourceAttributes.CloudPlatformValues.AWS_EC2); - - try (JsonParser parser = JSON_FACTORY.createParser(identity)) { - parser.nextToken(); - - if (!parser.isExpectedStartObjectToken()) { - throw new IOException("Invalid JSON:" + identity); - } - - while (parser.nextToken() != JsonToken.END_OBJECT) { - String value = parser.nextTextValue(); - switch (parser.getCurrentName()) { - case "instanceId": - attrBuilders.put(ResourceAttributes.HOST_ID, value); - break; - case "availabilityZone": - attrBuilders.put(ResourceAttributes.CLOUD_AVAILABILITY_ZONE, value); - break; - case "instanceType": - attrBuilders.put(ResourceAttributes.HOST_TYPE, value); - break; - case "imageId": - attrBuilders.put(ResourceAttributes.HOST_IMAGE_ID, value); - break; - case "accountId": - attrBuilders.put(ResourceAttributes.CLOUD_ACCOUNT_ID, value); - break; - case "region": - attrBuilders.put(ResourceAttributes.CLOUD_REGION, value); - break; - default: - parser.skipChildren(); - } - } - } catch (IOException e) { - logger.log(Level.WARNING, "Could not parse identity document, resource not filled.", e); - return Resource.empty(); - } - - attrBuilders.put(ResourceAttributes.HOST_NAME, hostname); - - return Resource.create(attrBuilders.build(), ResourceAttributes.SCHEMA_URL); - } - - private static String fetchToken(URL tokenUrl) { - return fetchString("PUT", tokenUrl, "", /* includeTtl= */ true); - } - - private static String fetchIdentity(URL identityDocumentUrl, String token) { - return fetchString("GET", identityDocumentUrl, token, /* includeTtl= */ false); - } - - private static String fetchHostname(URL hostnameUrl, String token) { - return fetchString("GET", hostnameUrl, token, /* includeTtl= */ false); - } - - // Generic HTTP fetch function for IMDS. - private static String fetchString(String httpMethod, URL url, String token, boolean includeTtl) { - SimpleHttpClient client = new SimpleHttpClient(); - Map headers = new HashMap<>(); - - if (includeTtl) { - headers.put("X-aws-ec2-metadata-token-ttl-seconds", "60"); - } - if (!token.isEmpty()) { - headers.put("X-aws-ec2-metadata-token", token); - } - - return client.fetchString(httpMethod, url.toString(), headers, null); - } - - private Ec2Resource() {} -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/Ec2ResourceProvider.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/Ec2ResourceProvider.java deleted file mode 100644 index dcbe6825d2a..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/Ec2ResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link Ec2Resource}. */ -public final class Ec2ResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return Ec2Resource.get(); - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EcsResource.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EcsResource.java deleted file mode 100644 index 913439eda34..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EcsResource.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A factory for a {@link Resource} which provides information about the current ECS container if - * running on AWS ECS. - */ -public final class EcsResource { - private static final Logger logger = Logger.getLogger(EcsResource.class.getName()); - - private static final String ECS_METADATA_KEY_V4 = "ECS_CONTAINER_METADATA_URI_V4"; - private static final String ECS_METADATA_KEY_V3 = "ECS_CONTAINER_METADATA_URI"; - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a factory for a {@link Resource} which provides information about the current ECS - * container if running on AWS ECS. - */ - public static Resource get() { - return INSTANCE; - } - - private static Resource buildResource() { - return buildResource(System.getenv(), new DockerHelper()); - } - - // Visible for testing - static Resource buildResource(Map sysEnv, DockerHelper dockerHelper) { - if (!isOnEcs(sysEnv)) { - return Resource.empty(); - } - - AttributesBuilder attrBuilders = Attributes.builder(); - attrBuilders.put(ResourceAttributes.CLOUD_PROVIDER, ResourceAttributes.CloudProviderValues.AWS); - attrBuilders.put( - ResourceAttributes.CLOUD_PLATFORM, ResourceAttributes.CloudPlatformValues.AWS_ECS); - try { - String hostName = InetAddress.getLocalHost().getHostName(); - attrBuilders.put(ResourceAttributes.CONTAINER_NAME, hostName); - } catch (UnknownHostException e) { - logger.log(Level.WARNING, "Could not get docker container name from hostname.", e); - } - - String containerId = dockerHelper.getContainerId(); - if (containerId != null && !containerId.isEmpty()) { - attrBuilders.put(ResourceAttributes.CONTAINER_ID, containerId); - } - - return Resource.create(attrBuilders.build(), ResourceAttributes.SCHEMA_URL); - } - - private static boolean isOnEcs(Map sysEnv) { - return !sysEnv.getOrDefault(ECS_METADATA_KEY_V3, "").isEmpty() - || !sysEnv.getOrDefault(ECS_METADATA_KEY_V4, "").isEmpty(); - } - - private EcsResource() {} -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EcsResourceProvider.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EcsResourceProvider.java deleted file mode 100644 index 6bf61fc9a1f..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EcsResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link EcsResource}. */ -public final class EcsResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return EcsResource.get(); - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EksResource.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EksResource.java deleted file mode 100644 index 2832a6a74a9..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EksResource.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * A factory for a {@link Resource} which provides information about the current ECS container if - * running on AWS EKS. - */ -public final class EksResource { - private static final Logger logger = Logger.getLogger(EksResource.class.getName()); - - private static final JsonFactory JSON_FACTORY = new JsonFactory(); - - static final String K8S_SVC_URL = "https://kubernetes.default.svc"; - static final String AUTH_CONFIGMAP_PATH = "/api/v1/namespaces/kube-system/configmaps/aws-auth"; - static final String CW_CONFIGMAP_PATH = - "/api/v1/namespaces/amazon-cloudwatch/configmaps/cluster-info"; - private static final String K8S_TOKEN_PATH = - "/var/run/secrets/kubernetes.io/serviceaccount/token"; - private static final String K8S_CERT_PATH = - "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt"; - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a factory for a {@link Resource} which provides information about the current ECS - * container if running on AWS EKS. - */ - public static Resource get() { - return INSTANCE; - } - - private static Resource buildResource() { - return buildResource(new SimpleHttpClient(), new DockerHelper(), K8S_TOKEN_PATH, K8S_CERT_PATH); - } - - // Visible for testing - static Resource buildResource( - SimpleHttpClient httpClient, - DockerHelper dockerHelper, - String k8sTokenPath, - String k8sKeystorePath) { - if (!isEks(k8sTokenPath, k8sKeystorePath, httpClient)) { - return Resource.empty(); - } - - AttributesBuilder attrBuilders = Attributes.builder(); - attrBuilders.put(ResourceAttributes.CLOUD_PROVIDER, ResourceAttributes.CloudProviderValues.AWS); - attrBuilders.put( - ResourceAttributes.CLOUD_PLATFORM, ResourceAttributes.CloudPlatformValues.AWS_EKS); - - String clusterName = getClusterName(httpClient); - if (clusterName != null && !clusterName.isEmpty()) { - attrBuilders.put(ResourceAttributes.K8S_CLUSTER_NAME, clusterName); - } - - String containerId = dockerHelper.getContainerId(); - if (containerId != null && !containerId.isEmpty()) { - attrBuilders.put(ResourceAttributes.CONTAINER_ID, containerId); - } - - return Resource.create(attrBuilders.build(), ResourceAttributes.SCHEMA_URL); - } - - private static boolean isEks( - String k8sTokenPath, String k8sKeystorePath, SimpleHttpClient httpClient) { - if (!isK8s(k8sTokenPath, k8sKeystorePath)) { - logger.log(Level.FINE, "Not running on k8s."); - return false; - } - - Map requestProperties = new HashMap<>(); - requestProperties.put("Authorization", getK8sCredHeader()); - String awsAuth = - httpClient.fetchString( - "GET", K8S_SVC_URL + AUTH_CONFIGMAP_PATH, requestProperties, K8S_CERT_PATH); - - return awsAuth != null && !awsAuth.isEmpty(); - } - - private static boolean isK8s(String k8sTokenPath, String k8sKeystorePath) { - File k8sTokeyFile = new File(k8sTokenPath); - File k8sKeystoreFile = new File(k8sKeystorePath); - return k8sTokeyFile.exists() && k8sKeystoreFile.exists(); - } - - private static String getClusterName(SimpleHttpClient httpClient) { - Map requestProperties = new HashMap<>(); - requestProperties.put("Authorization", getK8sCredHeader()); - String json = - httpClient.fetchString( - "GET", K8S_SVC_URL + CW_CONFIGMAP_PATH, requestProperties, K8S_CERT_PATH); - - try (JsonParser parser = JSON_FACTORY.createParser(json)) { - parser.nextToken(); - - if (!parser.isExpectedStartObjectToken()) { - throw new IOException("Invalid JSON:" + json); - } - - while (parser.nextToken() != JsonToken.END_OBJECT) { - parser.nextToken(); - if (!parser.getCurrentName().equals("data")) { - parser.skipChildren(); - continue; - } - - if (!parser.isExpectedStartObjectToken()) { - throw new IOException("Invalid JSON:" + json); - } - - while (parser.nextToken() != JsonToken.END_OBJECT) { - String value = parser.nextTextValue(); - if (!parser.getCurrentName().equals("cluster.name")) { - parser.skipChildren(); - continue; - } - return value; - } - } - } catch (IOException e) { - logger.log(Level.WARNING, "Can't get cluster name on EKS.", e); - } - return ""; - } - - private static String getK8sCredHeader() { - try { - String content = - new String(Files.readAllBytes(Paths.get(K8S_TOKEN_PATH)), StandardCharsets.UTF_8); - return "Bearer " + content; - } catch (IOException e) { - logger.log(Level.WARNING, "Unable to load K8s client token.", e); - } - return ""; - } - - private EksResource() {} -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EksResourceProvider.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EksResourceProvider.java deleted file mode 100644 index 55c491903f8..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/EksResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link EksResource}. */ -public final class EksResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return EksResource.get(); - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResource.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResource.java deleted file mode 100644 index 8e6f4c540f2..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResource.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.util.Map; -import java.util.stream.Stream; - -/** A factory for a {@link Resource} which provides information about the AWS Lambda function. */ -public final class LambdaResource { - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a factory for a {@link Resource} which provides information about the AWS Lambda - * function. - */ - public static Resource get() { - return INSTANCE; - } - - private static Resource buildResource() { - return buildResource(System.getenv()); - } - - // Visible for testing - static Resource buildResource(Map environmentVariables) { - String region = environmentVariables.getOrDefault("AWS_REGION", ""); - String functionName = environmentVariables.getOrDefault("AWS_LAMBDA_FUNCTION_NAME", ""); - String functionVersion = environmentVariables.getOrDefault("AWS_LAMBDA_FUNCTION_VERSION", ""); - - if (!isLambda(functionName, functionVersion)) { - return Resource.empty(); - } - - AttributesBuilder builder = - Attributes.builder() - .put(ResourceAttributes.CLOUD_PROVIDER, ResourceAttributes.CloudProviderValues.AWS); - builder.put( - ResourceAttributes.CLOUD_PLATFORM, ResourceAttributes.CloudPlatformValues.AWS_LAMBDA); - - if (!region.isEmpty()) { - builder.put(ResourceAttributes.CLOUD_REGION, region); - } - if (!functionName.isEmpty()) { - builder.put(ResourceAttributes.FAAS_NAME, functionName); - } - if (!functionVersion.isEmpty()) { - builder.put(ResourceAttributes.FAAS_VERSION, functionVersion); - } - - return Resource.create(builder.build(), ResourceAttributes.SCHEMA_URL); - } - - private static boolean isLambda(String... envVariables) { - return Stream.of(envVariables).anyMatch(v -> !v.isEmpty()); - } - - private LambdaResource() {} -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResourceProvider.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResourceProvider.java deleted file mode 100644 index d0e9a7c8508..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link LambdaResource}. */ -public final class LambdaResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return LambdaResource.get(); - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/SimpleHttpClient.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/SimpleHttpClient.java deleted file mode 100644 index 85f29001ef0..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/SimpleHttpClient.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyStore; -import java.security.cert.Certificate; -import java.security.cert.CertificateFactory; -import java.time.Duration; -import java.util.Collection; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okhttp3.ResponseBody; - -/** A simple HTTP client based on OkHttp. Not meant for high throughput. */ -final class SimpleHttpClient { - - private static final Logger logger = Logger.getLogger(SimpleHttpClient.class.getName()); - - private static final Duration TIMEOUT = Duration.ofSeconds(2); - - private static final RequestBody EMPTY_BODY = RequestBody.create(new byte[0]); - - /** Fetch a string from a remote server. */ - public String fetchString( - String httpMethod, String urlStr, Map headers, @Nullable String certPath) { - - OkHttpClient.Builder clientBuilder = - new OkHttpClient.Builder() - .callTimeout(TIMEOUT) - .connectTimeout(TIMEOUT) - .readTimeout(TIMEOUT); - - if (urlStr.startsWith("https") && certPath != null) { - KeyStore keyStore = getKeystoreForTrustedCert(certPath); - X509TrustManager trustManager = buildTrustManager(keyStore); - SSLSocketFactory socketFactory = buildSslSocketFactory(trustManager); - if (socketFactory != null) { - clientBuilder.sslSocketFactory(socketFactory, trustManager); - } - } - - OkHttpClient client = clientBuilder.build(); - - // AWS incorrectly uses PUT despite having no request body, OkHttp will only allow us to send - // GET with null body or PUT with empty string body - RequestBody requestBody = null; - if (httpMethod.equals("PUT")) { - requestBody = EMPTY_BODY; - } - Request.Builder requestBuilder = - new Request.Builder().url(urlStr).method(httpMethod, requestBody); - - headers.forEach(requestBuilder::addHeader); - - try (Response response = client.newCall(requestBuilder.build()).execute()) { - int responseCode = response.code(); - if (responseCode != 200) { - logger.log( - Level.FINE, - "Error response from " - + urlStr - + " code (" - + responseCode - + ") text " - + response.message()); - return ""; - } - ResponseBody body = response.body(); - return body != null ? body.string() : ""; - } catch (IOException e) { - logger.log(Level.FINE, "SimpleHttpClient fetch string failed.", e); - } - - return ""; - } - - @Nullable - private static X509TrustManager buildTrustManager(@Nullable KeyStore keyStore) { - if (keyStore == null) { - return null; - } - try { - String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); - TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); - tmf.init(keyStore); - return (X509TrustManager) tmf.getTrustManagers()[0]; - } catch (Exception e) { - logger.log(Level.WARNING, "Build SslSocketFactory for K8s restful client exception.", e); - return null; - } - } - - @Nullable - private static SSLSocketFactory buildSslSocketFactory(@Nullable TrustManager trustManager) { - if (trustManager == null) { - return null; - } - try { - SSLContext context = SSLContext.getInstance("TLS"); - context.init(null, new TrustManager[] {trustManager}, null); - return context.getSocketFactory(); - - } catch (Exception e) { - logger.log(Level.WARNING, "Build SslSocketFactory for K8s restful client exception.", e); - } - return null; - } - - @Nullable - private static KeyStore getKeystoreForTrustedCert(String certPath) { - try (FileInputStream fis = new FileInputStream(certPath)) { - KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); - trustStore.load(null, null); - CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); - - Collection certificates = certificateFactory.generateCertificates(fis); - - int i = 0; - for (Certificate certificate : certificates) { - trustStore.setCertificateEntry("cert_" + i, certificate); - i++; - } - return trustStore; - } catch (Exception e) { - logger.log(Level.WARNING, "Cannot load KeyStore from " + certPath); - return null; - } - } -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/package-info.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/package-info.java deleted file mode 100644 index 00f61ac2263..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/resource/package-info.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * {@link io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider} implementations for inferring - * resource information for AWS services. - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.extension.aws.resource; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/trace/AwsXrayIdGenerator.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/trace/AwsXrayIdGenerator.java deleted file mode 100644 index d09d2c43c4a..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/trace/AwsXrayIdGenerator.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.trace; - -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.sdk.trace.IdGenerator; -import java.util.Random; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.TimeUnit; - -/** - * Generates tracing ids compatible with the AWS X-Ray tracing service. In the X-Ray system the - * first 32 bits of the trace id are the Unix epoch time in secords. Spans (AWS calls them segments) - * submit with trace id timestamps outside of the last 30 days are rejected. - * - * @see Generating - * Trace IDs - * @deprecated Use the AwsXrayIdGenerator provided in the - * io.opentelemetry.contrib:opentelemetry-aws-xray artifact instead of this one. - */ -@Deprecated -public final class AwsXrayIdGenerator implements IdGenerator { - - private static final AwsXrayIdGenerator INSTANCE = new AwsXrayIdGenerator(); - - private static final IdGenerator RANDOM_ID_GENERATOR = IdGenerator.random(); - - /** Returns a singleton instance of {@link AwsXrayIdGenerator}. */ - public static AwsXrayIdGenerator getInstance() { - return INSTANCE; - } - - @Override - public String generateSpanId() { - return RANDOM_ID_GENERATOR.generateSpanId(); - } - - @Override - public String generateTraceId() { - // hi - 4 bytes timestamp, 4 bytes random - // low - 8 bytes random. - // Since we include timestamp, impossible to be invalid. - - Random random = ThreadLocalRandom.current(); - long timestampSecs = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); - long hiRandom = random.nextInt() & 0xFFFFFFFFL; - - long lowRandom = random.nextLong(); - - return TraceId.fromLongs(timestampSecs << 32 | hiRandom, lowRandom); - } - - private AwsXrayIdGenerator() {} -} diff --git a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/trace/package-info.java b/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/trace/package-info.java deleted file mode 100644 index 74a856bfca6..00000000000 --- a/sdk-extensions/aws/src/main/java/io/opentelemetry/sdk/extension/aws/trace/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** Provides implementations of SDK interfaces which integrate natively with AWS infrastructure. */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.extension.aws.trace; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider b/sdk-extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider deleted file mode 100644 index 37eddafc861..00000000000 --- a/sdk-extensions/aws/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider +++ /dev/null @@ -1,5 +0,0 @@ -io.opentelemetry.sdk.extension.aws.resource.BeanstalkResourceProvider -io.opentelemetry.sdk.extension.aws.resource.Ec2ResourceProvider -io.opentelemetry.sdk.extension.aws.resource.EcsResourceProvider -io.opentelemetry.sdk.extension.aws.resource.EksResourceProvider -io.opentelemetry.sdk.extension.aws.resource.LambdaResourceProvider diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResourceTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResourceTest.java deleted file mode 100644 index 161b17315b9..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/BeanstalkResourceTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.assertj.core.api.Assertions.entry; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.File; -import java.io.IOException; -import java.util.ServiceLoader; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class BeanstalkResourceTest { - - @Test - void testCreateAttributes(@TempDir File tempFolder) throws IOException { - File file = new File(tempFolder, "beanstalk.config"); - String content = - "{\"noise\": \"noise\", \"deployment_id\":4,\"" - + "version_label\":\"2\",\"environment_name\":\"HttpSubscriber-env\"}"; - Files.write(content.getBytes(Charsets.UTF_8), file); - Resource resource = BeanstalkResource.buildResource(file.getPath()); - Attributes attributes = resource.getAttributes(); - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_elastic_beanstalk"), - entry(ResourceAttributes.SERVICE_INSTANCE_ID, "4"), - entry(ResourceAttributes.SERVICE_VERSION, "2"), - entry(ResourceAttributes.SERVICE_NAMESPACE, "HttpSubscriber-env")); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - } - - @Test - void testConfigFileMissing() { - Attributes attributes = - BeanstalkResource.buildResource("a_file_never_existing").getAttributes(); - assertThat(attributes).isEmpty(); - } - - @Test - @SuppressLogger(BeanstalkResource.class) - void testBadConfigFile(@TempDir File tempFolder) throws IOException { - File file = new File(tempFolder, "beanstalk.config"); - String content = - "\"deployment_id\":4,\"version_label\":\"2\",\"" - + "environment_name\":\"HttpSubscriber-env\"}"; - Files.write(content.getBytes(Charsets.UTF_8), file); - Attributes attributes = BeanstalkResource.buildResource(file.getPath()).getAttributes(); - assertThat(attributes).isEmpty(); - } - - @Test - void inServiceLoader() { - // No practical way to test the attributes themselves so at least check the service loader picks - // it up. - assertThat(ServiceLoader.load(ResourceProvider.class)) - .anyMatch(BeanstalkResourceProvider.class::isInstance); - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/DockerHelperTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/DockerHelperTest.java deleted file mode 100644 index ed204d3ce16..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/DockerHelperTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import java.io.File; -import java.io.IOException; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -class DockerHelperTest { - - @Test - @SuppressLogger(DockerHelper.class) - void testCgroupFileMissing() { - DockerHelper dockerHelper = new DockerHelper("a_file_never_existing"); - assertThat(dockerHelper.getContainerId()).isEmpty(); - } - - @Test - void testContainerIdMissing(@TempDir File tempFolder) throws IOException { - File file = new File(tempFolder, "no_container_id"); - String content = "13:pids:/\n" + "12:hugetlb:/\n" + "11:net_prio:/"; - Files.write(content.getBytes(Charsets.UTF_8), file); - - DockerHelper dockerHelper = new DockerHelper(file.getPath()); - assertThat(dockerHelper.getContainerId()).isEmpty(); - } - - @Test - void testGetContainerId(@TempDir File tempFolder) throws IOException { - File file = new File(tempFolder, "cgroup"); - String expected = "386a1920640799b5bf5a39bd94e489e5159a88677d96ca822ce7c433ff350163"; - String content = "dummy\n11:devices:/ecs/bbc36dd0-5ee0-4007-ba96-c590e0b278d2/" + expected; - Files.write(content.getBytes(Charsets.UTF_8), file); - - DockerHelper dockerHelper = new DockerHelper(file.getPath()); - assertThat(dockerHelper.getContainerId()).isEqualTo(expected); - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/Ec2ResourceTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/Ec2ResourceTest.java deleted file mode 100644 index 4d0a657f51c..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/Ec2ResourceTest.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.assertj.core.api.Assertions.entry; - -import com.linecorp.armeria.common.AggregatedHttpRequest; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.common.HttpStatus; -import com.linecorp.armeria.common.MediaType; -import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.util.ServiceLoader; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -class Ec2ResourceTest { - - // From https://docs.amazonaws.cn/en_us/AWSEC2/latest/UserGuide/instance-identity-documents.html - private static final String IDENTITY_DOCUMENT = - "{\n" - + " \"devpayProductCodes\" : null,\n" - + " \"marketplaceProductCodes\" : [ \"1abc2defghijklm3nopqrs4tu\" ], \n" - + " \"availabilityZone\" : \"us-west-2b\",\n" - + " \"privateIp\" : \"10.158.112.84\",\n" - + " \"version\" : \"2017-09-30\",\n" - + " \"instanceId\" : \"i-1234567890abcdef0\",\n" - + " \"billingProducts\" : null,\n" - + " \"instanceType\" : \"t2.micro\",\n" - + " \"accountId\" : \"123456789012\",\n" - + " \"imageId\" : \"ami-5fb8c835\",\n" - + " \"pendingTime\" : \"2016-11-19T16:32:11Z\",\n" - + " \"architecture\" : \"x86_64\",\n" - + " \"kernelId\" : null,\n" - + " \"ramdiskId\" : null,\n" - + " \"region\" : \"us-west-2\"\n" - + "}"; - - @RegisterExtension public static MockWebServerExtension server = new MockWebServerExtension(); - - @Test - void imdsv2() { - server.enqueue(HttpResponse.of("token")); - server.enqueue(HttpResponse.of(MediaType.JSON_UTF_8, IDENTITY_DOCUMENT)); - server.enqueue(HttpResponse.of("ec2-1-2-3-4")); - - Resource resource = Ec2Resource.buildResource("localhost:" + server.httpPort()); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - Attributes attributes = resource.getAttributes(); - - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_ec2"), - entry(ResourceAttributes.HOST_ID, "i-1234567890abcdef0"), - entry(ResourceAttributes.CLOUD_AVAILABILITY_ZONE, "us-west-2b"), - entry(ResourceAttributes.HOST_TYPE, "t2.micro"), - entry(ResourceAttributes.HOST_IMAGE_ID, "ami-5fb8c835"), - entry(ResourceAttributes.CLOUD_ACCOUNT_ID, "123456789012"), - entry(ResourceAttributes.CLOUD_REGION, "us-west-2"), - entry(ResourceAttributes.HOST_NAME, "ec2-1-2-3-4")); - - AggregatedHttpRequest request1 = server.takeRequest().request(); - assertThat(request1.path()).isEqualTo("/latest/api/token"); - assertThat(request1.headers().get("X-aws-ec2-metadata-token-ttl-seconds")).isEqualTo("60"); - - AggregatedHttpRequest request2 = server.takeRequest().request(); - assertThat(request2.path()).isEqualTo("/latest/dynamic/instance-identity/document"); - assertThat(request2.headers().get("X-aws-ec2-metadata-token")).isEqualTo("token"); - - AggregatedHttpRequest request3 = server.takeRequest().request(); - assertThat(request3.path()).isEqualTo("/latest/meta-data/hostname"); - assertThat(request3.headers().get("X-aws-ec2-metadata-token")).isEqualTo("token"); - } - - @Test - void imdsv1() { - server.enqueue(HttpResponse.of(HttpStatus.NOT_FOUND)); - server.enqueue(HttpResponse.of(MediaType.JSON_UTF_8, IDENTITY_DOCUMENT)); - server.enqueue(HttpResponse.of("ec2-1-2-3-4")); - - Resource resource = Ec2Resource.buildResource("localhost:" + server.httpPort()); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - Attributes attributes = resource.getAttributes(); - - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_ec2"), - entry(ResourceAttributes.HOST_ID, "i-1234567890abcdef0"), - entry(ResourceAttributes.CLOUD_AVAILABILITY_ZONE, "us-west-2b"), - entry(ResourceAttributes.HOST_TYPE, "t2.micro"), - entry(ResourceAttributes.HOST_IMAGE_ID, "ami-5fb8c835"), - entry(ResourceAttributes.CLOUD_ACCOUNT_ID, "123456789012"), - entry(ResourceAttributes.CLOUD_REGION, "us-west-2"), - entry(ResourceAttributes.HOST_NAME, "ec2-1-2-3-4")); - - AggregatedHttpRequest request1 = server.takeRequest().request(); - assertThat(request1.path()).isEqualTo("/latest/api/token"); - assertThat(request1.headers().get("X-aws-ec2-metadata-token-ttl-seconds")).isEqualTo("60"); - - AggregatedHttpRequest request2 = server.takeRequest().request(); - assertThat(request2.path()).isEqualTo("/latest/dynamic/instance-identity/document"); - assertThat(request2.headers().get("X-aws-ec2-metadata-token")).isNull(); - } - - @Test - @SuppressLogger(Ec2Resource.class) - void badJson() { - server.enqueue(HttpResponse.of(HttpStatus.NOT_FOUND)); - server.enqueue(HttpResponse.of(MediaType.JSON_UTF_8, "I'm not JSON")); - - Attributes attributes = - Ec2Resource.buildResource("localhost:" + server.httpPort()).getAttributes(); - assertThat(attributes).isEmpty(); - - AggregatedHttpRequest request1 = server.takeRequest().request(); - assertThat(request1.path()).isEqualTo("/latest/api/token"); - assertThat(request1.headers().get("X-aws-ec2-metadata-token-ttl-seconds")).isEqualTo("60"); - - AggregatedHttpRequest request2 = server.takeRequest().request(); - assertThat(request2.path()).isEqualTo("/latest/dynamic/instance-identity/document"); - assertThat(request2.headers().get("X-aws-ec2-metadata-token")).isNull(); - } - - @Test - void inServiceLoader() { - // No practical way to test the attributes themselves so at least check the service loader picks - // it up. - assertThat(ServiceLoader.load(ResourceProvider.class)) - .anyMatch(Ec2ResourceProvider.class::isInstance); - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/EcsResourceTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/EcsResourceTest.java deleted file mode 100644 index 7ac1a81122c..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/EcsResourceTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.assertj.core.api.Assertions.entry; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.util.HashMap; -import java.util.Map; -import java.util.ServiceLoader; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class EcsResourceTest { - private static final String ECS_METADATA_KEY_V4 = "ECS_CONTAINER_METADATA_URI_V4"; - private static final String ECS_METADATA_KEY_V3 = "ECS_CONTAINER_METADATA_URI"; - - @Mock private DockerHelper mockDockerHelper; - - @Test - void testCreateAttributes() throws UnknownHostException { - when(mockDockerHelper.getContainerId()).thenReturn("0123456789A"); - Map mockSysEnv = new HashMap<>(); - mockSysEnv.put(ECS_METADATA_KEY_V3, "ecs_metadata_v3_uri"); - Resource resource = EcsResource.buildResource(mockSysEnv, mockDockerHelper); - Attributes attributes = resource.getAttributes(); - - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_ecs"), - entry(ResourceAttributes.CONTAINER_NAME, InetAddress.getLocalHost().getHostName()), - entry(ResourceAttributes.CONTAINER_ID, "0123456789A")); - } - - @Test - void testNotOnEcs() { - Map mockSysEnv = new HashMap<>(); - mockSysEnv.put(ECS_METADATA_KEY_V3, ""); - mockSysEnv.put(ECS_METADATA_KEY_V4, ""); - Attributes attributes = EcsResource.buildResource(mockSysEnv, mockDockerHelper).getAttributes(); - assertThat(attributes).isEmpty(); - } - - @Test - void testContainerIdMissing() throws UnknownHostException { - when(mockDockerHelper.getContainerId()).thenReturn(""); - Map mockSysEnv = new HashMap<>(); - mockSysEnv.put(ECS_METADATA_KEY_V4, "ecs_metadata_v4_uri"); - Attributes attributes = EcsResource.buildResource(mockSysEnv, mockDockerHelper).getAttributes(); - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_ecs"), - entry(ResourceAttributes.CONTAINER_NAME, InetAddress.getLocalHost().getHostName())); - } - - @Test - void inServiceLoader() { - // No practical way to test the attributes themselves so at least check the service loader picks - // it up. - assertThat(ServiceLoader.load(ResourceProvider.class)) - .anyMatch(EcsResourceProvider.class::isInstance); - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/EksResourceTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/EksResourceTest.java deleted file mode 100644 index ffb4a68c68d..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/EksResourceTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static io.opentelemetry.sdk.extension.aws.resource.EksResource.AUTH_CONFIGMAP_PATH; -import static io.opentelemetry.sdk.extension.aws.resource.EksResource.CW_CONFIGMAP_PATH; -import static io.opentelemetry.sdk.extension.aws.resource.EksResource.K8S_SVC_URL; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.assertj.core.api.Assertions.entry; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; - -import com.google.common.base.Charsets; -import com.google.common.io.Files; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.File; -import java.io.IOException; -import java.util.ServiceLoader; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.api.io.TempDir; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -public class EksResourceTest { - - @Mock private DockerHelper mockDockerHelper; - - @Mock private SimpleHttpClient httpClient; - - @Test - @SuppressLogger(EksResource.class) - void testEks(@TempDir File tempFolder) throws IOException { - File mockK8sTokenFile = new File(tempFolder, "k8sToken"); - String token = "token123"; - Files.write(token.getBytes(Charsets.UTF_8), mockK8sTokenFile); - File mockK8sKeystoreFile = new File(tempFolder, "k8sCert"); - String truststore = "truststore123"; - Files.write(truststore.getBytes(Charsets.UTF_8), mockK8sKeystoreFile); - - when(httpClient.fetchString(any(), Mockito.eq(K8S_SVC_URL + AUTH_CONFIGMAP_PATH), any(), any())) - .thenReturn("not empty"); - when(httpClient.fetchString(any(), Mockito.eq(K8S_SVC_URL + CW_CONFIGMAP_PATH), any(), any())) - .thenReturn("{\"data\":{\"cluster.name\":\"my-cluster\"}}"); - when(mockDockerHelper.getContainerId()).thenReturn("0123456789A"); - - Resource eksResource = - EksResource.buildResource( - httpClient, - mockDockerHelper, - mockK8sTokenFile.getPath(), - mockK8sKeystoreFile.getPath()); - Attributes attributes = eksResource.getAttributes(); - - assertThat(eksResource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_eks"), - entry(ResourceAttributes.K8S_CLUSTER_NAME, "my-cluster"), - entry(ResourceAttributes.CONTAINER_ID, "0123456789A")); - } - - @Test - void testNotEks() { - Resource eksResource = EksResource.buildResource(httpClient, mockDockerHelper, "", ""); - Attributes attributes = eksResource.getAttributes(); - assertThat(attributes).isEmpty(); - } - - @Test - void inServiceLoader() { - // No practical way to test the attributes themselves so at least check the service loader picks - // it up. - assertThat(ServiceLoader.load(ResourceProvider.class)) - .anyMatch(EksResourceProvider.class::isInstance); - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResourceTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResourceTest.java deleted file mode 100644 index 1692b3f0bac..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/LambdaResourceTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static java.util.Collections.emptyMap; -import static java.util.Collections.singletonMap; -import static org.assertj.core.api.Assertions.entry; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.util.HashMap; -import java.util.Map; -import java.util.ServiceLoader; -import org.junit.jupiter.api.Test; - -class LambdaResourceTest { - @Test - void shouldNotCreateResourceForNotLambda() { - Attributes attributes = LambdaResource.buildResource(emptyMap()).getAttributes(); - assertThat(attributes).isEmpty(); - } - - @Test - void shouldAddNonEmptyAttributes() { - Resource resource = - LambdaResource.buildResource(singletonMap("AWS_LAMBDA_FUNCTION_NAME", "my-function")); - Attributes attributes = resource.getAttributes(); - - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_lambda"), - entry(ResourceAttributes.FAAS_NAME, "my-function")); - } - - @Test - void shouldAddAllAttributes() { - Map envVars = new HashMap<>(); - envVars.put("AWS_REGION", "us-east-1"); - envVars.put("AWS_LAMBDA_FUNCTION_NAME", "my-function"); - envVars.put("AWS_LAMBDA_FUNCTION_VERSION", "1.2.3"); - - Resource resource = LambdaResource.buildResource(envVars); - Attributes attributes = resource.getAttributes(); - - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(attributes) - .containsOnly( - entry(ResourceAttributes.CLOUD_PROVIDER, "aws"), - entry(ResourceAttributes.CLOUD_PLATFORM, "aws_lambda"), - entry(ResourceAttributes.CLOUD_REGION, "us-east-1"), - entry(ResourceAttributes.FAAS_NAME, "my-function"), - entry(ResourceAttributes.FAAS_VERSION, "1.2.3")); - } - - @Test - void inServiceLoader() { - // No practical way to test the attributes themselves so at least check the service loader picks - // it up. - assertThat(ServiceLoader.load(ResourceProvider.class)) - .anyMatch(LambdaResourceProvider.class::isInstance); - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/SimpleHttpClientTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/SimpleHttpClientTest.java deleted file mode 100644 index a6104805b20..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/resource/SimpleHttpClientTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.resource; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableMap; -import com.linecorp.armeria.common.AggregatedHttpRequest; -import com.linecorp.armeria.common.HttpResponse; -import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; -import com.linecorp.armeria.testing.junit5.server.ServerExtension; -import com.linecorp.armeria.testing.junit5.server.mock.MockWebServerExtension; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Map; -import org.junit.jupiter.api.Order; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; -import org.junit.jupiter.api.io.TempDir; - -class SimpleHttpClientTest { - - @RegisterExtension public static MockWebServerExtension server = new MockWebServerExtension(); - - @Test - void testFetchString() { - server.enqueue(HttpResponse.of("expected result")); - - Map requestPropertyMap = ImmutableMap.of("key1", "value1", "key2", "value2"); - String urlStr = String.format("http://localhost:%s%s", server.httpPort(), "/path"); - SimpleHttpClient httpClient = new SimpleHttpClient(); - String result = httpClient.fetchString("GET", urlStr, requestPropertyMap, null); - - assertThat(result).isEqualTo("expected result"); - - AggregatedHttpRequest request1 = server.takeRequest().request(); - assertThat(request1.path()).isEqualTo("/path"); - assertThat(request1.headers().get("key1")).isEqualTo("value1"); - assertThat(request1.headers().get("key2")).isEqualTo("value2"); - } - - @Test - void testFailedFetchString() { - Map requestPropertyMap = ImmutableMap.of("key1", "value1", "key2", "value2"); - String urlStr = String.format("http://localhost:%s%s", server.httpPort(), "/path"); - SimpleHttpClient httpClient = new SimpleHttpClient(); - String result = httpClient.fetchString("GET", urlStr, requestPropertyMap, null); - assertThat(result).isEmpty(); - } - - static class HttpsServerTest { - @RegisterExtension - @Order(1) - public static SelfSignedCertificateExtension certificate = new SelfSignedCertificateExtension(); - - @RegisterExtension - @Order(2) - public static ServerExtension server = - new ServerExtension() { - @Override - protected void configure(ServerBuilder sb) { - sb.tls(certificate.certificateFile(), certificate.privateKeyFile()); - - sb.service("/", (ctx, req) -> HttpResponse.of("Thanks for trusting me")); - } - }; - - @Test - void goodCert() { - SimpleHttpClient httpClient = new SimpleHttpClient(); - String result = - httpClient.fetchString( - "GET", - "https://localhost:" + server.httpsPort() + "/", - Collections.emptyMap(), - certificate.certificateFile().getAbsolutePath()); - assertThat(result).isEqualTo("Thanks for trusting me"); - } - - @Test - @SuppressLogger(SimpleHttpClient.class) - void missingCert() { - SimpleHttpClient httpClient = new SimpleHttpClient(); - String result = - httpClient.fetchString( - "GET", - "https://localhost:" + server.httpsPort() + "/", - Collections.emptyMap(), - "/foo/bar/bad"); - assertThat(result).isEmpty(); - } - - @Test - @SuppressLogger(SimpleHttpClient.class) - void badCert(@TempDir Path tempDir) throws Exception { - Path certFile = tempDir.resolve("test.crt"); - Files.write(certFile, "bad cert".getBytes(StandardCharsets.UTF_8)); - SimpleHttpClient httpClient = new SimpleHttpClient(); - String result = - httpClient.fetchString( - "GET", - "https://localhost:" + server.httpsPort() + "/", - Collections.emptyMap(), - certFile.toString()); - assertThat(result).isEmpty(); - } - } -} diff --git a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/trace/AwsXRayIdGeneratorTest.java b/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/trace/AwsXRayIdGeneratorTest.java deleted file mode 100644 index 1f98a1b541d..00000000000 --- a/sdk-extensions/aws/src/test/java/io/opentelemetry/sdk/extension/aws/trace/AwsXRayIdGeneratorTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.aws.trace; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.sdk.trace.IdGenerator; -import java.util.Set; -import java.util.concurrent.BrokenBarrierException; -import java.util.concurrent.CopyOnWriteArraySet; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.Executor; -import java.util.concurrent.Executors; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link AwsXrayIdGenerator}. */ -@SuppressWarnings("deprecation") // Moved to contrib -class AwsXRayIdGeneratorTest { - - @Test - void shouldGenerateValidIds() { - AwsXrayIdGenerator generator = AwsXrayIdGenerator.getInstance(); - for (int i = 0; i < 1000; i++) { - String traceId = generator.generateTraceId(); - assertThat(TraceId.isValid(traceId)).isTrue(); - String spanId = generator.generateSpanId(); - assertThat(SpanId.isValid(spanId)).isTrue(); - } - } - - @Test - void shouldGenerateTraceIdsWithTimestampsWithAllowedXrayTimeRange() { - AwsXrayIdGenerator generator = AwsXrayIdGenerator.getInstance(); - for (int i = 0; i < 1000; i++) { - String traceId = generator.generateTraceId(); - long unixSeconds = Long.valueOf(traceId.subSequence(0, 8).toString(), 16); - long ts = unixSeconds * 1000L; - long currentTs = System.currentTimeMillis(); - assertThat(ts).isLessThanOrEqualTo(currentTs); - long month = 86400000L * 30L; - assertThat(ts).isGreaterThan(currentTs - month); - } - } - - @Test - void shouldGenerateUniqueIdsInMultithreadedEnvironment() - throws BrokenBarrierException, InterruptedException { - AwsXrayIdGenerator generator = AwsXrayIdGenerator.getInstance(); - Set traceIds = new CopyOnWriteArraySet<>(); - Set spanIds = new CopyOnWriteArraySet<>(); - int threads = 8; - int generations = 128; - CyclicBarrier barrier = new CyclicBarrier(threads + 1); - Executor executor = Executors.newFixedThreadPool(threads); - for (int i = 0; i < threads; i++) { - executor.execute(new GenerateRunner(generations, generator, barrier, traceIds, spanIds)); - } - barrier.await(); - barrier.await(); - assertThat(traceIds).hasSize(threads * generations); - assertThat(spanIds).hasSize(threads * generations); - } - - static class GenerateRunner implements Runnable { - - private final int generations; - private final IdGenerator idsGenerator; - private final CyclicBarrier barrier; - private final Set traceIds; - private final Set spanIds; - - GenerateRunner( - int generations, - IdGenerator idsGenerator, - CyclicBarrier barrier, - Set traceIds, - Set spanIds) { - this.generations = generations; - this.idsGenerator = idsGenerator; - this.barrier = barrier; - this.traceIds = traceIds; - this.spanIds = spanIds; - } - - @Override - public void run() { - try { - barrier.await(); - for (int i = 0; i < generations; i++) { - traceIds.add(idsGenerator.generateTraceId()); - spanIds.add(idsGenerator.generateSpanId()); - } - barrier.await(); - } catch (InterruptedException | BrokenBarrierException cause) { - throw new IllegalStateException(cause); - } - } - } -} diff --git a/sdk-extensions/aws/src/test/resources/get-sampling-rules-response.json b/sdk-extensions/aws/src/test/resources/get-sampling-rules-response.json deleted file mode 100644 index 8706104a304..00000000000 --- a/sdk-extensions/aws/src/test/resources/get-sampling-rules-response.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "SamplingRuleRecords": [ - { - "SamplingRule": { - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "*", - "Priority": 1, - "FixedRate": 0.9, - "ReservoirSize": 1000, - "ServiceName": "test-service-foo-bar", - "ServiceType": "*", - "Host": "*", - "HTTPMethod": "*", - "URLPath": "*", - "Version": 1, - "Attributes": { - "animal": "cat", - "speed": "10" - } - }, - "CreatedAt": "2021-06-18T17:28:15+09:00", - "ModifiedAt": "2021-06-18T17:28:15+09:00" - }, - { - "SamplingRule": { - "RuleName": "Default", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Default", - "ResourceARN": "*", - "Priority": 10000, - "FixedRate": 0.05, - "ReservoirSize": 1, - "ServiceName": "*", - "ServiceType": "*", - "Host": "*", - "HTTPMethod": "*", - "URLPath": "*", - "Version": 1, - "Attributes": {} - }, - "CreatedAt": "1970-01-01T09:00:00+09:00", - "ModifiedAt": "1970-01-01T09:00:00+09:00" - } - ] -} \ No newline at end of file diff --git a/sdk-extensions/aws/src/test/resources/get-sampling-targets-request.json b/sdk-extensions/aws/src/test/resources/get-sampling-targets-request.json deleted file mode 100644 index b75d750d730..00000000000 --- a/sdk-extensions/aws/src/test/resources/get-sampling-targets-request.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "SamplingStatisticsDocuments":[ - { - "RuleName":"Test", - "ClientID":"ABCDEF1234567890ABCDEF10", - "Timestamp":"2021-06-21T06:46:07", - "RequestCount":110, - "SampledCount":30, - "BorrowCount":20 - }, - { - "RuleName":"polling-scorekeep", - "ClientID":"ABCDEF1234567890ABCDEF11", - "Timestamp":"2018-07-07T00:20:06", - "RequestCount":10500, - "SampledCount":31, - "BorrowCount":0 - } - ] -} diff --git a/sdk-extensions/aws/src/test/resources/get-sampling-targets-response.json b/sdk-extensions/aws/src/test/resources/get-sampling-targets-response.json deleted file mode 100644 index cb1fae68b11..00000000000 --- a/sdk-extensions/aws/src/test/resources/get-sampling-targets-response.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "SamplingTargetDocuments": [ - { - "RuleName": "base-scorekeep", - "FixedRate": 0.1, - "ReservoirQuota": 2, - "ReservoirQuotaTTL": 1530923107.0, - "Interval": 10 - }, - { - "RuleName": "polling-scorekeep", - "FixedRate": 0.003 - } - ], - "LastRuleModification": 1530920505.0, - "UnprocessedStatistics": [ - { - "RuleName": "cats-rule", - "ErrorCode": "400", - "Message": "Unknown rule" - } - ] -} \ No newline at end of file diff --git a/sdk-extensions/aws/src/test/resources/sampling-rule-awslambda.json b/sdk-extensions/aws/src/test/resources/sampling-rule-awslambda.json deleted file mode 100644 index c9ef96014e6..00000000000 --- a/sdk-extensions/aws/src/test/resources/sampling-rule-awslambda.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "arn:aws:xray:us-east-1:595986152929:my-service", - "Priority": 1, - "FixedRate": 1.0, - "ReservoirSize": 1000, - "ServiceName": "test-service-foo-bar", - "ServiceType": "AWS::Lambda::Function", - "Host": "opentelemetry.io", - "HTTPMethod": "GET", - "URLPath": "/instrument-me", - "Version": 1, - "Attributes": { - "animal": "cat", - "speed": "10" - } -} diff --git a/sdk-extensions/aws/src/test/resources/sampling-rule-exactmatch.json b/sdk-extensions/aws/src/test/resources/sampling-rule-exactmatch.json deleted file mode 100644 index 3d20523af7b..00000000000 --- a/sdk-extensions/aws/src/test/resources/sampling-rule-exactmatch.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "arn:aws:xray:us-east-1:595986152929:my-service", - "Priority": 1, - "FixedRate": 1.0, - "ReservoirSize": 0, - "ServiceName": "test-service-foo-bar", - "ServiceType": "AWS::EKS::Container", - "Host": "opentelemetry.io", - "HTTPMethod": "GET", - "URLPath": "/instrument-me", - "Version": 1, - "Attributes": { - "animal": "cat", - "speed": "10" - } -} diff --git a/sdk-extensions/aws/src/test/resources/sampling-rule-reservoir.json b/sdk-extensions/aws/src/test/resources/sampling-rule-reservoir.json deleted file mode 100644 index 9923f63aa25..00000000000 --- a/sdk-extensions/aws/src/test/resources/sampling-rule-reservoir.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "arn:aws:xray:us-east-1:595986152929:my-service", - "Priority": 1, - "FixedRate": 0.0, - "ReservoirSize": 1000, - "ServiceName": "test-service-foo-bar", - "ServiceType": "AWS::EKS::Container", - "Host": "opentelemetry.io", - "HTTPMethod": "GET", - "URLPath": "/instrument-me", - "Version": 1, - "Attributes": { - "animal": "cat", - "speed": "10" - } -} diff --git a/sdk-extensions/aws/src/test/resources/sampling-rule-wildcards.json b/sdk-extensions/aws/src/test/resources/sampling-rule-wildcards.json deleted file mode 100644 index d975a1b6b87..00000000000 --- a/sdk-extensions/aws/src/test/resources/sampling-rule-wildcards.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "arn:aws:*:us-east-?:*:my-service", - "Priority": 1, - "FixedRate": 0.0, - "ReservoirSize": 0, - "ServiceName": "test-service-foo-*", - "ServiceType": "*", - "Host": "*op*t?lem*r?.io*", - "HTTPMethod": "**GET**", - "URLPath": "/instrument-me?foo=bar&cat=*", - "Version": 1, - "Attributes": { - "animal": "cat*", - "speed": "?0" - } -} diff --git a/sdk-extensions/aws/src/test/resources/test-sampling-rules-response-1.json b/sdk-extensions/aws/src/test/resources/test-sampling-rules-response-1.json deleted file mode 100644 index 2b121c7a692..00000000000 --- a/sdk-extensions/aws/src/test/resources/test-sampling-rules-response-1.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "SamplingRuleRecords": [ - { - "SamplingRule": { - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "*", - "Priority": 1, - "FixedRate": 1.0, - "ReservoirSize": 1, - "ServiceName": "cat-service", - "ServiceType": "*", - "Host": "*", - "HTTPMethod": "*", - "URLPath": "*", - "Version": 1, - "Attributes": {} - }, - "CreatedAt": "2021-06-18T17:28:15+09:00", - "ModifiedAt": "2021-06-18T17:28:15+09:00" - }, - { - "SamplingRule": { - "RuleName": "Default", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Default", - "ResourceARN": "*", - "Priority": 10000, - "FixedRate": 0.0, - "ReservoirSize": 1, - "ServiceName": "*", - "ServiceType": "*", - "Host": "*", - "HTTPMethod": "*", - "URLPath": "*", - "Version": 1, - "Attributes": {} - }, - "CreatedAt": "1970-01-01T09:00:00+09:00", - "ModifiedAt": "1970-01-01T09:00:00+09:00" - } - ] -} \ No newline at end of file diff --git a/sdk-extensions/aws/src/test/resources/test-sampling-rules-response-2.json b/sdk-extensions/aws/src/test/resources/test-sampling-rules-response-2.json deleted file mode 100644 index 19929eb4d07..00000000000 --- a/sdk-extensions/aws/src/test/resources/test-sampling-rules-response-2.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "SamplingRuleRecords": [ - { - "SamplingRule": { - "RuleName": "Test", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Test", - "ResourceARN": "*", - "Priority": 1, - "FixedRate": 0.0, - "ReservoirSize": 1, - "ServiceName": "cat-service", - "ServiceType": "*", - "Host": "*", - "HTTPMethod": "*", - "URLPath": "*", - "Version": 1, - "Attributes": {} - }, - "CreatedAt": "2021-06-18T17:28:15+09:00", - "ModifiedAt": "2021-06-18T17:28:15+09:00" - }, - { - "SamplingRule": { - "RuleName": "Default", - "RuleARN": "arn:aws:xray:us-east-1:595986152929:sampling-rule/Default", - "ResourceARN": "*", - "Priority": 10000, - "FixedRate": 1.0, - "ReservoirSize": 1, - "ServiceName": "*", - "ServiceType": "*", - "Host": "*", - "HTTPMethod": "*", - "URLPath": "*", - "Version": 1, - "Attributes": {} - }, - "CreatedAt": "1970-01-01T09:00:00+09:00", - "ModifiedAt": "1970-01-01T09:00:00+09:00" - } - ] -} \ No newline at end of file diff --git a/sdk-extensions/build.gradle.kts b/sdk-extensions/build.gradle.kts index 0f94cb7c259..bcb76a95ae0 100644 --- a/sdk-extensions/build.gradle.kts +++ b/sdk-extensions/build.gradle.kts @@ -1,4 +1,6 @@ subprojects { + // Workaround https://github.com/gradle/gradle/issues/847 + group = "io.opentelemetry.sdk.extensions" val proj = this plugins.withId("java") { configure { diff --git a/sdk-extensions/declarative-config-jackson2/README.md b/sdk-extensions/declarative-config-jackson2/README.md new file mode 100644 index 00000000000..041479e874b --- /dev/null +++ b/sdk-extensions/declarative-config-jackson2/README.md @@ -0,0 +1,9 @@ +# Declarative Configuration Jackson 2 Mapper + +This extension provides a Jackson 2 implementation of the `DeclarativeConfigurationMapper` SPI. +It is included as a runtime dependency by `opentelemetry-sdk-extension-declarative-config` from +the `opentelemetry-sdk-extension-declarative-config-jackson2` artifact. + +Projects using another mapper can exclude this artifact from the declarative-config dependency and +register their own `DeclarativeConfigurationMapper` provider. For example, a project using Jackson 3 +can implement the SPI with its Jackson 3 `ObjectMapper`. diff --git a/sdk-extensions/declarative-config-jackson2/build.gradle.kts b/sdk-extensions/declarative-config-jackson2/build.gradle.kts new file mode 100644 index 00000000000..abac59989a5 --- /dev/null +++ b/sdk-extensions/declarative-config-jackson2/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry SDK Declarative Config Jackson 2 Mapper" +otelJava.moduleName.set("io.opentelemetry.sdk.autoconfigure.declarativeconfig.jackson2") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper", +)) + +dependencies { + api(project(":sdk-extensions:autoconfigure-spi")) + implementation("com.fasterxml.jackson.core:jackson-databind") +} diff --git a/extensions/noop-api/gradle.properties b/sdk-extensions/declarative-config-jackson2/gradle.properties similarity index 100% rename from extensions/noop-api/gradle.properties rename to sdk-extensions/declarative-config-jackson2/gradle.properties diff --git a/sdk-extensions/declarative-config-jackson2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonDeclarativeConfigurationMapper.java b/sdk-extensions/declarative-config-jackson2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonDeclarativeConfigurationMapper.java new file mode 100644 index 00000000000..e546a4e9762 --- /dev/null +++ b/sdk-extensions/declarative-config-jackson2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonDeclarativeConfigurationMapper.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.jackson2.internal; + +import com.fasterxml.jackson.core.type.TypeReference; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class JacksonDeclarativeConfigurationMapper implements DeclarativeConfigurationMapper { + + @Override + public T convert(Object value, Class targetType) { + try { + return JacksonModelMapper.MAPPER.convertValue(value, targetType); + } catch (IllegalArgumentException e) { + throw new DeclarativeConfigException("Unable to convert value to " + targetType, e); + } + } + + @Nullable + @Override + public Map toMap(Object value) { + try { + return JacksonModelMapper.MAPPER.convertValue( + value, new TypeReference>() {}); + } catch (IllegalArgumentException e) { + throw new DeclarativeConfigException("Unable to convert value to a map", e); + } + } +} diff --git a/sdk-extensions/declarative-config-jackson2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonModelMapper.java b/sdk-extensions/declarative-config-jackson2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonModelMapper.java new file mode 100644 index 00000000000..11444cf9d98 --- /dev/null +++ b/sdk-extensions/declarative-config-jackson2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonModelMapper.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.jackson2.internal; + +import com.fasterxml.jackson.annotation.JsonSetter; +import com.fasterxml.jackson.annotation.Nulls; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class JacksonModelMapper { + + public static final ObjectMapper MAPPER; + + static { + MAPPER = + new ObjectMapper() + // Create empty object instances for keys which are present but have null values. + .setDefaultSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY)); + // Boxed primitives which are present but have null values should be set to null, rather than + // empty instances. + MAPPER.configOverride(String.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.SET)); + MAPPER.configOverride(Integer.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.SET)); + MAPPER.configOverride(Double.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.SET)); + MAPPER.configOverride(Boolean.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.SET)); + } + + private JacksonModelMapper() {} +} diff --git a/sdk-extensions/declarative-config-jackson2/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper b/sdk-extensions/declarative-config-jackson2/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper new file mode 100644 index 00000000000..08b2e458c0a --- /dev/null +++ b/sdk-extensions/declarative-config-jackson2/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper @@ -0,0 +1 @@ +io.opentelemetry.sdk.autoconfigure.declarativeconfig.jackson2.internal.JacksonDeclarativeConfigurationMapper diff --git a/sdk-extensions/declarative-config-jackson2/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonDeclarativeConfigurationMapperTest.java b/sdk-extensions/declarative-config-jackson2/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonDeclarativeConfigurationMapperTest.java new file mode 100644 index 00000000000..c04b0064282 --- /dev/null +++ b/sdk-extensions/declarative-config-jackson2/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/jackson2/internal/JacksonDeclarativeConfigurationMapperTest.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.jackson2.internal; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import org.junit.jupiter.api.Test; + +class JacksonDeclarativeConfigurationMapperTest { + + private final JacksonDeclarativeConfigurationMapper mapper = + new JacksonDeclarativeConfigurationMapper(); + + @Test + void convertWrapsJacksonException() { + assertThatThrownBy(() -> mapper.convert("not-an-integer", Integer.class)) + .isInstanceOf(DeclarativeConfigException.class) + .hasCauseInstanceOf(IllegalArgumentException.class); + } + + @Test + void toMapWrapsJacksonException() { + assertThatThrownBy(() -> mapper.toMap(42)) + .isInstanceOf(DeclarativeConfigException.class) + .hasCauseInstanceOf(IllegalArgumentException.class); + } +} diff --git a/sdk-extensions/declarative-config-snakeyaml-engine2/README.md b/sdk-extensions/declarative-config-snakeyaml-engine2/README.md new file mode 100644 index 00000000000..2f31842550d --- /dev/null +++ b/sdk-extensions/declarative-config-snakeyaml-engine2/README.md @@ -0,0 +1,9 @@ +# SnakeYAML Engine 2 Declarative Configuration Parser + +This module provides the default `DeclarativeConfigurationYamlParser` implementation using +SnakeYAML Engine 2. It is included as a runtime dependency by +`opentelemetry-sdk-extension-declarative-config`. + +Applications that provide a custom YAML parser can exclude this module from the declarative config +dependency and register their parser with `ServiceLoader`. If neither this adapter nor another +parser provider is present, YAML parsing fails with a `DeclarativeConfigException`. diff --git a/sdk-extensions/declarative-config-snakeyaml-engine2/build.gradle.kts b/sdk-extensions/declarative-config-snakeyaml-engine2/build.gradle.kts new file mode 100644 index 00000000000..99d83cfe73a --- /dev/null +++ b/sdk-extensions/declarative-config-snakeyaml-engine2/build.gradle.kts @@ -0,0 +1,17 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry SDK Declarative Config SnakeYAML Engine 2 Parser" +otelJava.moduleName.set("io.opentelemetry.sdk.autoconfigure.declarativeconfig.snakeyamlengine2") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser", +)) + +dependencies { + api(project(":sdk-extensions:autoconfigure-spi")) + implementation("org.snakeyaml:snakeyaml-engine") +} diff --git a/micrometer1-shim/gradle.properties b/sdk-extensions/declarative-config-snakeyaml-engine2/gradle.properties similarity index 100% rename from micrometer1-shim/gradle.properties rename to sdk-extensions/declarative-config-snakeyaml-engine2/gradle.properties diff --git a/sdk-extensions/declarative-config-snakeyaml-engine2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/snakeyamlengine2/internal/SnakeYamlDeclarativeConfigurationParser.java b/sdk-extensions/declarative-config-snakeyaml-engine2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/snakeyamlengine2/internal/SnakeYamlDeclarativeConfigurationParser.java new file mode 100644 index 00000000000..d16a514eb92 --- /dev/null +++ b/sdk-extensions/declarative-config-snakeyaml-engine2/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/snakeyamlengine2/internal/SnakeYamlDeclarativeConfigurationParser.java @@ -0,0 +1,220 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.snakeyamlengine2.internal; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser; +import java.io.InputStream; +import java.util.Map; +import java.util.Objects; +import java.util.regex.MatchResult; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.annotation.Nullable; +import org.snakeyaml.engine.v2.api.Load; +import org.snakeyaml.engine.v2.api.LoadSettings; +import org.snakeyaml.engine.v2.api.YamlUnicodeReader; +import org.snakeyaml.engine.v2.common.ScalarStyle; +import org.snakeyaml.engine.v2.composer.Composer; +import org.snakeyaml.engine.v2.exceptions.YamlEngineException; +import org.snakeyaml.engine.v2.nodes.MappingNode; +import org.snakeyaml.engine.v2.nodes.Node; +import org.snakeyaml.engine.v2.nodes.ScalarNode; +import org.snakeyaml.engine.v2.nodes.Tag; +import org.snakeyaml.engine.v2.parser.ParserImpl; +import org.snakeyaml.engine.v2.resolver.ScalarResolver; +import org.snakeyaml.engine.v2.scanner.StreamReader; +import org.snakeyaml.engine.v2.schema.CoreSchema; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class SnakeYamlDeclarativeConfigurationParser + implements DeclarativeConfigurationYamlParser { + + // Matches ${VAR_NAME}, ${env:VAR_NAME}, or ${sys:property.name} with optional :-default + private static final Pattern ENV_VARIABLE_REFERENCE = + Pattern.compile("\\$\\{(?:(env|sys):)?([a-zA-Z_][a-zA-Z0-9_.]*)(?::-([^\\n}]*))?}"); + + private static final String ESCAPE_SEQUENCE = "$$"; + private static final int ESCAPE_SEQUENCE_LENGTH = ESCAPE_SEQUENCE.length(); + private static final char ESCAPE_SEQUENCE_REPLACEMENT = '$'; + + @Override + public Object parse( + InputStream configuration, + Map environmentVariables, + Map systemProperties) { + LoadSettings settings = LoadSettings.builder().setSchema(new CoreSchema()).build(); + Load yaml = new EnvLoad(settings, environmentVariables, systemProperties); + try { + return yaml.loadFromInputStream(configuration); + } catch (YamlEngineException e) { + throw new DeclarativeConfigException("Unable to parse configuration input stream", e); + } + } + + private static final class EnvLoad extends Load { + + private final LoadSettings settings; + private final Map environmentVariables; + private final Map systemProperties; + + private EnvLoad( + LoadSettings settings, + Map environmentVariables, + Map systemProperties) { + super(settings); + this.settings = settings; + this.environmentVariables = environmentVariables; + this.systemProperties = systemProperties; + } + + @Override + public Object loadFromInputStream(InputStream yamlStream) { + Objects.requireNonNull(yamlStream, "InputStream cannot be null"); + return loadOne( + new EnvComposer( + settings, + new ParserImpl( + settings, new StreamReader(settings, new YamlUnicodeReader(yamlStream))), + environmentVariables, + systemProperties)); + } + } + + /** + * A YAML Composer that performs environment variable and system property substitution according + * to the OpenTelemetry Configuration Data Model specification. + */ + private static final class EnvComposer extends Composer { + + private final Load load; + private final Map environmentVariables; + private final Map systemProperties; + private final ScalarResolver scalarResolver; + + private EnvComposer( + LoadSettings settings, + ParserImpl parser, + Map environmentVariables, + Map systemProperties) { + super(settings, parser); + this.load = new Load(settings); + this.environmentVariables = environmentVariables; + this.systemProperties = systemProperties; + this.scalarResolver = settings.getSchema().getScalarResolver(); + } + + @Override + protected Node composeValueNode(MappingNode node) { + Node itemValue = super.composeValueNode(node); + if (!(itemValue instanceof ScalarNode)) { + // Only apply environment variable substitution to ScalarNodes + return itemValue; + } + ScalarNode scalarNode = (ScalarNode) itemValue; + String envSubstitution = envSubstitution(scalarNode.getValue()); + + // If the environment variable substitution does not change the value, do not modify the node + if (envSubstitution.equals(scalarNode.getValue())) { + return itemValue; + } + + Object envSubstitutionObj = load.loadFromString(envSubstitution); + Tag tag = itemValue.getTag(); + ScalarStyle scalarStyle = scalarNode.getScalarStyle(); + + Tag resolvedTag = + envSubstitutionObj == null + ? Tag.NULL + : scalarResolver.resolve(envSubstitutionObj.toString(), true); + + // Only non-quoted substituted scalars can have their tag changed + if (!itemValue.getTag().equals(resolvedTag) + && scalarStyle != ScalarStyle.SINGLE_QUOTED + && scalarStyle != ScalarStyle.DOUBLE_QUOTED) { + tag = resolvedTag; + } + + boolean resolved = true; + return new ScalarNode( + tag, + resolved, + envSubstitution, + scalarStyle, + itemValue.getStartMark(), + itemValue.getEndMark()); + } + + private String envSubstitution(String val) { + // Substitute each portion between escaped dollar signs independently. Each "$$" becomes + // one literal "$" and prevents substitution in the adjacent portion. + int lastEscapeIndexEnd = 0; + StringBuilder newVal = null; + while (true) { + int escapeIndex = val.indexOf(ESCAPE_SEQUENCE, lastEscapeIndexEnd); + int substitutionEndIndex = escapeIndex == -1 ? val.length() : escapeIndex; + newVal = envVarSubstitution(newVal, val, lastEscapeIndexEnd, substitutionEndIndex); + if (escapeIndex == -1) { + break; + } else { + newVal.append(ESCAPE_SEQUENCE_REPLACEMENT); + } + lastEscapeIndexEnd = escapeIndex + ESCAPE_SEQUENCE_LENGTH; + if (lastEscapeIndexEnd >= val.length()) { + break; + } + } + + return newVal.toString(); + } + + private StringBuilder envVarSubstitution( + @Nullable StringBuilder newVal, String source, int startIndex, int endIndex) { + String val = source.substring(startIndex, endIndex); + Matcher matcher = ENV_VARIABLE_REFERENCE.matcher(val); + + if (!matcher.find()) { + return newVal == null ? new StringBuilder(val) : newVal.append(val); + } + + if (newVal == null) { + newVal = new StringBuilder(); + } + + int offset = 0; + do { + MatchResult matchResult = matcher.toMatchResult(); + String prefix = matcher.group(1); // "env", "sys", or null + String key = matcher.group(2); // variable/property name + String defaultValue = matcher.group(3); + if (defaultValue == null) { + defaultValue = ""; + } + + String replacement; + if ("sys".equals(prefix)) { + // System property substitution + Object sysProp = systemProperties.get(key); + replacement = sysProp != null ? sysProp.toString() : defaultValue; + } else { + // Environment variable substitution (default or explicit "env:" prefix) + replacement = environmentVariables.getOrDefault(key, defaultValue); + } + + newVal.append(val, offset, matchResult.start()).append(replacement); + offset = matchResult.end(); + } while (matcher.find()); + if (offset != val.length()) { + newVal.append(val, offset, val.length()); + } + + return newVal; + } + } +} diff --git a/sdk-extensions/declarative-config-snakeyaml-engine2/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser b/sdk-extensions/declarative-config-snakeyaml-engine2/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser new file mode 100644 index 00000000000..0f77cf3d548 --- /dev/null +++ b/sdk-extensions/declarative-config-snakeyaml-engine2/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser @@ -0,0 +1 @@ +io.opentelemetry.sdk.autoconfigure.declarativeconfig.snakeyamlengine2.internal.SnakeYamlDeclarativeConfigurationParser diff --git a/sdk-extensions/declarative-config-snakeyaml-engine2/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/snakeyamlengine2/internal/SnakeYamlDeclarativeConfigurationParserTest.java b/sdk-extensions/declarative-config-snakeyaml-engine2/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/snakeyamlengine2/internal/SnakeYamlDeclarativeConfigurationParserTest.java new file mode 100644 index 00000000000..35eb5ce29b2 --- /dev/null +++ b/sdk-extensions/declarative-config-snakeyaml-engine2/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/snakeyamlengine2/internal/SnakeYamlDeclarativeConfigurationParserTest.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.snakeyamlengine2.internal; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import org.junit.jupiter.api.Test; +import org.snakeyaml.engine.v2.exceptions.YamlEngineException; + +class SnakeYamlDeclarativeConfigurationParserTest { + + @Test + void wrapsSnakeYamlException() { + ByteArrayInputStream input = + new ByteArrayInputStream("key: [unclosed".getBytes(StandardCharsets.UTF_8)); + assertThatThrownBy(() -> + new SnakeYamlDeclarativeConfigurationParser() + .parse(input, Collections.emptyMap(), Collections.emptyMap())) + .isInstanceOf(DeclarativeConfigException.class) + .hasCauseInstanceOf(YamlEngineException.class); + } +} diff --git a/sdk-extensions/declarative-config/README.md b/sdk-extensions/declarative-config/README.md new file mode 100644 index 00000000000..0bc14aa7a6e --- /dev/null +++ b/sdk-extensions/declarative-config/README.md @@ -0,0 +1,133 @@ +# Declarative Configuration + +The [declarative configuration interface](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/README.md#declarative-configuration) allows for YAML based file configuration of `OpenTelemetrySdk`. + +Usage: + +```shell +File yamlConfigFile = new File("/path/to/config.yaml"); +OpenTelemetrySdk openTelemetrySdk; +try (FileInputStream yamlConfigFileInputStream = new FileInputStream("/path/to/config.yaml")) { + openTelemetrySdk = DeclarativeConfiguration.parseAndCreate(yamlConfigFileInputStream).getSdk(); +} +// ...proceed with application after successful initialization of OpenTelemetrySdk +``` + +Notes: +* Environment variable substitution is supported as [defined in the spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/data-model.md#environment-variable-substitution) +* Customization is limited to customizing the in-memory config model, or exporters. See `DeclarativeConfigurationCustomizer` SPI for details. +* The parser and mapper are internal, unstable SPIs in `opentelemetry-sdk-extension-autoconfigure-spi` (`io.opentelemetry.sdk.autoconfigure.spi.internal`). `ServiceLoader` loads providers; when several are present, the first is used with a warning unless selected through the corresponding system property or environment variable. +* The SnakeYAML parser and Jackson 2 mapper adapters are included by default. Exclude an adapter to use a custom provider. If no provider is available, the operation fails with a `DeclarativeConfigException`. +* Custom SDK extension components which reference the [ComponentProvider](https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk-extensions/autoconfigure-spi/src/main/java/io/opentelemetry/sdk/autoconfigure/spi/declarativeconfig/ComponentProvider.java) SPI can be referenced in declarative configuration. Supported types include: + * `Resource` + * `SpanExporter` + * `MetricExporter` + * `LogRecordExporter` + * `SpanProcessor` + * `LogRecordProcessor` + * `TextMapPropagator` + * `Sampler` +* You can use declarative configuration with [autoconfigure](https://opentelemetry.io/docs/languages/java/configuration/#declarative-configuration) to specify a configuration file via environment variable, e.g. `OTEL_CONFIG_FILE=/path/to/config.yaml`. + +## Use a custom mapper + +To use a mapper such as Jackson 3, exclude the default +`opentelemetry-sdk-extension-declarative-config-jackson2` adapter from the declarative config +dependency and add Jackson 3 Databind. This Gradle example uses Jackson 3.2.3: + +```kotlin +dependencies { + implementation("io.opentelemetry:opentelemetry-sdk-extension-declarative-config:$version") { + exclude( + group = "io.opentelemetry", + module = "opentelemetry-sdk-extension-declarative-config-jackson2", + ) + } + implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:$version") + implementation("tools.jackson.core:jackson-databind:3.2.3") +} +``` + +Implement `DeclarativeConfigurationMapper` and override these methods: + +* `convert(Object value, Class targetType)` converts parsed configuration values to a model. +* `toMap(Object value)` converts a model or configuration value to a map with string keys. Return + `null` when the input is `null`. + +Mapper methods and `DeclarativeConfigurationYamlParser.parse` report conversion and parsing +failures with `DeclarativeConfigException`. The declarative configuration implementation wraps +other runtime exceptions thrown by providers in this exception. + +Configure your mapper to preserve the null and extension-property behavior expected by the models. + +Register the class with `ServiceLoader` by adding this file to your application or mapper module: + +```text +META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper +``` + +Put your provider's fully qualified class name in that file: + +```text +your.package.YourMapper +``` + +With the service file on the runtime classpath, declarative config discovers your mapper. + +## Select a mapper + +If exactly one mapper provider is on the classpath, it is used. If multiple providers are present, +select one by setting the following system property or environment variable to the provider's fully +qualified class name: + +| Configuration source | Name | +| --- | --- | +| System property | `io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper` | +| Environment variable | `IO_OPENTELEMETRY_SDK_AUTOCONFIGURE_SPI_INTERNAL_DECLARATIVECONFIGURATIONMAPPER` | + +When multiple providers are present and neither setting is set, the first discovered provider is +used and a warning is logged. If the setting names a provider that is not present, declarative +configuration fails with a `DeclarativeConfigException`. + +## Use a custom YAML parser + +To replace the default SnakeYAML parser, exclude the +`opentelemetry-sdk-extension-declarative-config-snakeyaml-engine2` adapter from the declarative config +dependency: + +```kotlin +dependencies { + implementation("io.opentelemetry:opentelemetry-sdk-extension-declarative-config:$version") { + exclude( + group = "io.opentelemetry", + module = "opentelemetry-sdk-extension-declarative-config-snakeyaml-engine2", + ) + } + implementation("io.opentelemetry:opentelemetry-sdk-extension-autoconfigure-spi:$version") +} +``` + +Implement `DeclarativeConfigurationYamlParser` and register it with `ServiceLoader` by adding this +file to your application or parser module: + +```text +META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser +``` + +Put your parser's fully qualified class name in the service file. The parser receives the YAML +stream and the environment variables and system properties to use for substitution. + +## Select a YAML parser + +If exactly one YAML parser provider is on the classpath, it is used. If multiple providers are +present, select one by setting the following system property or environment variable to the +provider's fully qualified class name: + +| Configuration source | Name | +| --- | --- | +| System property | `io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser` | +| Environment variable | `IO_OPENTELEMETRY_SDK_AUTOCONFIGURE_SPI_INTERNAL_DECLARATIVECONFIGURATIONYAMLPARSER` | + +When multiple providers are present and neither setting is set, the first discovered provider is +used and a warning is logged. If the setting names a provider that is not present, declarative +configuration fails with a `DeclarativeConfigException`. diff --git a/sdk-extensions/declarative-config/build.gradle.kts b/sdk-extensions/declarative-config/build.gradle.kts new file mode 100644 index 00000000000..3b4e36ec043 --- /dev/null +++ b/sdk-extensions/declarative-config/build.gradle.kts @@ -0,0 +1,239 @@ +import de.undercouch.gradle.tasks.download.Download +import io.opentelemetry.gradle.DeclarativeConfigPojoGenerator + +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") + + id("de.undercouch.download") +} + +description = "OpenTelemetry SDK Declarative Config" +otelJava.moduleName.set("io.opentelemetry.sdk.autoconfigure.declarativeconfig") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) +// declarative-config discovers these providers at runtime via ServiceLoader +otelJava.osgiServiceLoaderRequires.set(listOf( + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider", + "io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser", + "io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper", +)) + +dependencies { + api(project(":sdk:all")) + api(project(":api:incubator")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + runtimeOnly(project(":sdk-extensions:declarative-config-jackson2")) + runtimeOnly(project(":sdk-extensions:declarative-config-snakeyaml-engine2")) + // Needed for composable samplers + implementation(project(":sdk-extensions:incubator")) + + annotationProcessor("com.google.auto.value:auto-value") + + api("com.fasterxml.jackson.core:jackson-annotations") + + testImplementation(project(":sdk:testing")) + testImplementation(project(":sdk-extensions:autoconfigure-spi")) + testImplementation(project(":exporters:logging")) + testImplementation(project(":exporters:logging-otlp")) + testImplementation(project(":exporters:otlp:all")) + testImplementation(project(":exporters:prometheus")) + testImplementation(project(":sdk-extensions:jaeger-remote-sampler")) + testImplementation(project(":extensions:trace-propagators")) + testImplementation("io.opentelemetry.contrib:opentelemetry-aws-xray-propagator") + testImplementation("io.opentelemetry.instrumentation:opentelemetry-resources") + testImplementation("com.linecorp.armeria:armeria-junit5") + testRuntimeOnly(project(":sdk-extensions:declarative-config-jackson2")) + testRuntimeOnly(project(":sdk-extensions:declarative-config-snakeyaml-engine2")) +// + testImplementation("com.google.guava:guava-testlib") + testImplementation("nl.jqno.equalsverifier:equalsverifier") +} + +// The following tasks download the JSON Schema files from open-telemetry/opentelemetry-configuration +// and regenerate the committed model POJOs in src/main/java. The sequence is: +// 1. downloadConfigurationSchema - download configuration schema from open-telemetry/opentelemetry-configuration +// 2. unzipConfigurationSchema - unzip the schema archive to $buildDir/configuration/ +// 3. syncPojoModelsToSrc - run PojoGenerator to write Java sources into src/main/java +// The generated POJOs are committed to src/main/java and are NOT regenerated as part of the normal build. +// To regenerate (e.g. after a schema update), run: ./gradlew :sdk-extensions:declarative-config:syncPojoModelsToSrc + +val configurationTag = "1.2.0" +val configurationRef = "refs/tags/v$configurationTag" // Replace with commit SHA to point to experiment with a specific commit +val configurationRepoZip = "https://github.com/open-telemetry/opentelemetry-configuration/archive/$configurationRef.zip" +val buildDirectory = layout.buildDirectory.asFile.get() + +val downloadConfigurationSchema = tasks.register("downloadConfigurationSchema") { + src(configurationRepoZip) + // The version is encoded in the filename so that a configurationTag change results in a new + // path that doesn't yet exist, triggering a fresh download. On subsequent builds with the same + // tag the file already exists and overwrite(false) skips the network request. Note: the + // de.undercouch Download task always reports itself as not up-to-date, so overwrite(false) is + // the intended mechanism for avoiding redundant downloads. + // + // The zip is stored in tmp/ so it is outside the Sync task's output directory (configuration/). + dest("$buildDirectory/tmp/opentelemetry-configuration-v$configurationTag.zip") + overwrite(false) +} + +val unzipConfigurationSchema = tasks.register("unzipConfigurationSchema") { + // Sync (not Copy) removes stale files from the destination when the source changes, ensuring + // files deleted or renamed between schema versions don't linger in the build dir. + dependsOn(downloadConfigurationSchema) + + from(zipTree(downloadConfigurationSchema.get().dest)) + eachFile(closureOf { + // Remove the top level folder "/opentelemetry-configuration-$configurationRef" + val pathParts = path.split("/") + path = pathParts.subList(1, pathParts.size).joinToString("/") + }) + into("$buildDirectory/configuration/") + includeEmptyDirs = false +} + +// Generates POJOs from the configuration schema and writes them to src/main/java. +// The generated POJOs are committed to src/main/java and are NOT regenerated as part of the normal +// build. To regenerate (e.g. after a schema update), run: +// ./gradlew :sdk-extensions:declarative-config:syncPojoModelsToSrc +val syncPojoModelsToSrc = tasks.register("syncPojoModelsToSrc") { + // This task is only run manually (to regenerate committed model POJOs after a schema update). + // It writes into src/main/java, which is outside the normal Gradle output boundary, so it + // intentionally doesn't participate in the configuration cache. + notCompatibleWithConfigurationCache("Regenerates committed model POJOs in src/main/java") + dependsOn(unzipConfigurationSchema) + finalizedBy("spotlessApply") + val schemaFile = File("$buildDirectory/configuration/opentelemetry_configuration.json") + val modelPackage = "io.opentelemetry.sdk.autoconfigure.declarativeconfig.model" + val modelSrcDir = File(projectDir, "src/main/java") + doLast { + val modelDir = File(modelSrcDir, modelPackage.replace('.', '/')) + // Delete only @Generated files so hand-written files (ExtensionPropertyUtil) in model.internal + // survive the regeneration cycle. + modelDir.walkTopDown() + .filter { it.isFile && it.extension == "java" } + .filter { it.readText().contains("@Generated(") } + .forEach { it.delete() } + DeclarativeConfigPojoGenerator(schemaFile, modelSrcDir, modelPackage).generate() + } +} + +// Copies EnvironmentResource.java from the autoconfigure module into a generated source set so +// that declarative config can use the exact same source without taking a runtime dependency on +// autoconfigure and without the risk of divergence from manual syncing. +val generatedResourceConfigDir = + layout.buildDirectory.dir("generated/sources/resource-configuration/java/main") +val copyResourceConfiguration = tasks.register("copyResourceConfiguration") { + from( + project(":sdk-extensions:autoconfigure").file( + "src/main/java/io/opentelemetry/sdk/autoconfigure/EnvironmentResource.java" + ) + ) + into(generatedResourceConfigDir.map { it.dir("io/opentelemetry/sdk/autoconfigure/declarativeconfig") }) + // Only the package declaration needs rewriting; everything else is copied verbatim. + filter { line: String -> + line.replace( + "package io.opentelemetry.sdk.autoconfigure;", + "package io.opentelemetry.sdk.autoconfigure.declarativeconfig;" + ) + } +} + +sourceSets { + main { + java { + srcDir(generatedResourceConfigDir) + } + } +} + +val buildGraalVmReflectionJson = tasks.register("buildGraalVmReflectionJson") { + val buildDir = buildDirectory + val targetFile = File( + buildDir, + "resources/main/META-INF/native-image/io.opentelemetry/io.opentelemetry.sdk.autoconfigure.declarativeconfig/reflect-config.json" + ) + val sourcePackage = + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.model" + val sourcePackagePath = sourcePackage.replace(".", "/") + val classesDir = + File( + buildDir, + "classes/java/main/$sourcePackagePath" + ) + + inputs.dir(classesDir) + outputs.file(targetFile) + + onlyIf { !targetFile.exists() } + + dependsOn("compileJava") + + doLast { + println("Generating GraalVM reflection config at: ${targetFile.absolutePath}") + + val classes = mutableListOf() + classesDir.walkTopDown().filter { it.isFile && it.extension == "class" }.forEach { file -> + val relativePath = file.toRelativeString(classesDir) + val className = relativePath + .removeSuffix(".class") + .replace(File.separatorChar, '.') + classes.add("$sourcePackage.$className") + } + classes.sort() + + targetFile.parentFile.mkdirs() + targetFile.bufferedWriter().use { writer -> + writer.write("[\n") + classes.forEachIndexed { index, className -> + writer.write(" {\n") + writer.write(" \"name\": \"$className\",\n") + writer.write(" \"allDeclaredMethods\": true,\n") + writer.write(" \"allDeclaredFields\": true,\n") + writer.write(" \"allDeclaredConstructors\": true\n") + writer.write(" }") + if (index < classes.size - 1) { + writer.write(",\n") + } else { + writer.write("\n") + } + } + writer.write("]\n") + } + } +} + +tasks.getByName("compileJava").dependsOn(copyResourceConfiguration) +tasks.getByName("sourcesJar").dependsOn(buildGraalVmReflectionJson, copyResourceConfiguration) +tasks.getByName("jar").dependsOn(buildGraalVmReflectionJson) +tasks.getByName("javadoc").dependsOn(buildGraalVmReflectionJson) +tasks.getByName("compileTestJava").dependsOn(buildGraalVmReflectionJson) + +// When syncPojoModelsToSrc runs it writes to src/main/java. Both spotlessJava and spotlessMisc +// declare the module directory as an input region, so Gradle requires ordering to be explicit. +// mustRunAfter satisfies the implicit-dependency validator without making spotless depend on +// generation during normal builds. +tasks.named("spotlessJava") { mustRunAfter(syncPojoModelsToSrc) } +tasks.named("spotlessMisc") { mustRunAfter(syncPojoModelsToSrc) } + +// Exclude committed generated POJO sources from checkstyle +tasks.named("checkstyleMain") { + dependsOn(buildGraalVmReflectionJson) + exclude("**/declarativeconfig/model/**") +} + +tasks { + withType().configureEach { + dependsOn(unzipConfigurationSchema) + environment( + mapOf( + // Expose the kitchen sink example file to tests + "CONFIG_REPO_ROOT" to "$buildDirectory/configuration" + ) + ) + } +} diff --git a/opentracing-shim/gradle.properties b/sdk-extensions/declarative-config/gradle.properties similarity index 100% rename from opentracing-shim/gradle.properties rename to sdk-extensions/declarative-config/gradle.properties diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AggregationFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AggregationFactory.java new file mode 100644 index 00000000000..be0c890f996 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AggregationFactory.java @@ -0,0 +1,81 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.Base2ExponentialBucketHistogramAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExplicitBucketHistogramAggregationModel; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions; +import io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions; +import java.util.List; + +final class AggregationFactory implements Factory { + + private static final AggregationFactory INSTANCE = new AggregationFactory(); + + private AggregationFactory() {} + + static AggregationFactory getInstance() { + return INSTANCE; + } + + @Override + public Aggregation create(AggregationModel model, DeclarativeConfigContext context) { + if (model.getDrop() != null) { + return Aggregation.drop(); + } + if (model.getSum() != null) { + return Aggregation.sum(); + } + if (model.getLastValue() != null) { + return Aggregation.lastValue(); + } + Base2ExponentialBucketHistogramAggregationModel exponentialBucketHistogram = + model.getBase2ExponentialBucketHistogram(); + if (exponentialBucketHistogram != null) { + Integer maxScale = exponentialBucketHistogram.getMaxScale(); + Integer maxSize = exponentialBucketHistogram.getMaxSize(); + Boolean recordMinMax = exponentialBucketHistogram.getRecordMinMax(); + Base2ExponentialHistogramOptions.Builder builder = Base2ExponentialHistogramOptions.builder(); + if (maxScale != null) { + builder.setMaxScale(maxScale); + } + if (maxSize != null) { + builder.setMaxBuckets(maxSize); + } + if (recordMinMax != null) { + builder.setRecordMinMax(recordMinMax); + } + try { + return Aggregation.base2ExponentialBucketHistogram(builder.build()); + } catch (IllegalArgumentException e) { + throw new DeclarativeConfigException("Invalid exponential bucket histogram", e); + } + } + ExplicitBucketHistogramAggregationModel explicitBucketHistogram = + model.getExplicitBucketHistogram(); + if (explicitBucketHistogram != null) { + List boundaries = explicitBucketHistogram.getBoundaries(); + Boolean recordMinMax = explicitBucketHistogram.getRecordMinMax(); + ExplicitBucketHistogramOptions.Builder builder = ExplicitBucketHistogramOptions.builder(); + if (boundaries != null) { + builder.setBucketBoundaries(boundaries); + } + if (recordMinMax != null) { + builder.setRecordMinMax(recordMinMax); + } + try { + return Aggregation.explicitBucketHistogram(builder.build()); + } catch (IllegalArgumentException e) { + throw new DeclarativeConfigException("Invalid explicit bucket histogram", e); + } + } + + return Aggregation.defaultAggregation(); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactory.java new file mode 100644 index 00000000000..1e1a46afae6 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactory.java @@ -0,0 +1,142 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static java.util.stream.Collectors.toList; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeTypeModel; +import java.util.List; +import javax.annotation.Nullable; + +final class AttributeListFactory implements Factory, Attributes> { + + private static final AttributeListFactory INSTANCE = new AttributeListFactory(); + + private AttributeListFactory() {} + + static AttributeListFactory getInstance() { + return INSTANCE; + } + + @Override + public Attributes create(List model, DeclarativeConfigContext context) { + AttributesBuilder builder = Attributes.builder(); + + for (AttributeNameValueModel nameValueModel : model) { + addToBuilder(nameValueModel, builder); + } + + return builder.build(); + } + + private static void addToBuilder( + AttributeNameValueModel nameValueModel, AttributesBuilder builder) { + String name = FileConfigUtil.requireNonNull(nameValueModel.getName(), "attribute name"); + Object value = nameValueModel.getValue(); + if (value == null) { + // Per the configuration schema, an entry with a null value is ignored + return; + } + AttributeTypeModel type = nameValueModel.getType(); + if (type == null) { + type = AttributeTypeModel.STRING; + } + switch (type) { + case STRING: + if (value instanceof String) { + builder.put(name, (String) value); + return; + } + break; + case BOOL: + if (value instanceof Boolean) { + builder.put(name, (boolean) value); + return; + } + break; + case INT: + if ((value instanceof Integer) || (value instanceof Long)) { + builder.put(name, ((Number) value).longValue()); + return; + } + break; + case DOUBLE: + if (value instanceof Number) { + builder.put(name, ((Number) value).doubleValue()); + return; + } + break; + case STRING_ARRAY: + List stringList = checkListOfType(value, String.class); + if (stringList != null) { + builder.put(AttributeKey.stringArrayKey(name), stringList); + return; + } + break; + case BOOL_ARRAY: + List boolList = checkListOfType(value, Boolean.class); + if (boolList != null) { + builder.put(AttributeKey.booleanArrayKey(name), boolList); + return; + } + break; + case INT_ARRAY: + List longList = checkListOfType(value, Long.class); + if (longList != null) { + builder.put(AttributeKey.longArrayKey(name), longList); + return; + } + List intList = checkListOfType(value, Integer.class); + if (intList != null) { + builder.put( + AttributeKey.longArrayKey(name), + intList.stream().map(i -> (long) i).collect(toList())); + return; + } + break; + case DOUBLE_ARRAY: + List doubleList = checkListOfType(value, Double.class); + if (doubleList != null) { + builder.put(AttributeKey.doubleArrayKey(name), doubleList); + return; + } + List floatList = checkListOfType(value, Float.class); + if (floatList != null) { + builder.put( + AttributeKey.doubleArrayKey(name), + floatList.stream().map(i -> (double) i).collect(toList())); + return; + } + break; + } + throw new DeclarativeConfigException( + "Error processing attribute with name \"" + + name + + "\": value did not match type " + + type.name()); + } + + @SuppressWarnings("unchecked") + @Nullable + private static List checkListOfType(Object value, Class expectedType) { + if (!(value instanceof List)) { + return null; + } + List list = (List) value; + if (list.isEmpty()) { + return null; + } + if (!list.stream().allMatch(entry -> expectedType.isAssignableFrom(entry.getClass()))) { + return null; + } + return (List) value; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/CardinalityLimitsFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/CardinalityLimitsFactory.java new file mode 100644 index 00000000000..6ebe53c3ef8 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/CardinalityLimitsFactory.java @@ -0,0 +1,61 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; +import javax.annotation.Nullable; + +final class CardinalityLimitsFactory + implements Factory { + + private static final CardinalityLimitsFactory INSTANCE = new CardinalityLimitsFactory(); + + private CardinalityLimitsFactory() {} + + static CardinalityLimitsFactory getInstance() { + return INSTANCE; + } + + @Override + public CardinalityLimitSelector create( + CardinalityLimitsModel model, DeclarativeConfigContext context) { + int defaultLimit = getOrDefault(model.getDefault(), MetricStorage.DEFAULT_MAX_CARDINALITY); + int counterLimit = getOrDefault(model.getCounter(), defaultLimit); + int gaugeLimit = getOrDefault(model.getGauge(), defaultLimit); + int histogramLimit = getOrDefault(model.getHistogram(), defaultLimit); + int observableCounterLimit = getOrDefault(model.getObservableCounter(), defaultLimit); + int observableGaugeLimit = getOrDefault(model.getObservableGauge(), defaultLimit); + int observableUpDownCounterLimit = + getOrDefault(model.getObservableUpDownCounter(), defaultLimit); + int upDownCounterLimit = getOrDefault(model.getUpDownCounter(), defaultLimit); + + return instrumentType -> { + switch (instrumentType) { + case COUNTER: + return counterLimit; + case UP_DOWN_COUNTER: + return upDownCounterLimit; + case HISTOGRAM: + return histogramLimit; + case OBSERVABLE_COUNTER: + return observableCounterLimit; + case OBSERVABLE_UP_DOWN_COUNTER: + return observableUpDownCounterLimit; + case OBSERVABLE_GAUGE: + return observableGaugeLimit; + case GAUGE: + return gaugeLimit; + } + return defaultLimit; + }; + } + + private static int getOrDefault(@Nullable Integer value, int defaultValue) { + return value == null ? defaultValue : value; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java new file mode 100644 index 00000000000..3a7cd48b248 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactory.java @@ -0,0 +1,280 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigUtil.requireNonNull; +import static java.util.stream.Collectors.toSet; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanKindModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerRuleModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalSpanParentModel; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.ComposableRuleBasedSamplerBuilder; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.ComposableSampler; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.SamplingPredicate; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.StringJoiner; +import java.util.function.Predicate; +import javax.annotation.Nullable; + +final class ComposableRuleBasedSamplerFactory + implements Factory { + + private static final ComposableRuleBasedSamplerFactory INSTANCE = + new ComposableRuleBasedSamplerFactory(); + + private ComposableRuleBasedSamplerFactory() {} + + static ComposableRuleBasedSamplerFactory getInstance() { + return INSTANCE; + } + + @Override + public ComposableSampler create( + ExperimentalComposableRuleBasedSamplerModel model, DeclarativeConfigContext context) { + ComposableRuleBasedSamplerBuilder builder = ComposableSampler.ruleBasedBuilder(); + + List rules = model.getRules(); + if (rules != null) { + rules.forEach(rule -> { + AttributeMatcher valueMatcher = attributeValuesMatcher(rule.getAttributeValues()); + AttributeMatcher patternMatcher = attributePatternsMatcher(rule.getAttributePatterns()); + Set matchingParents = + rule.getParent() != null && !rule.getParent().isEmpty() + ? new HashSet<>(rule.getParent()) + : null; + Set matchingSpanKinds = + rule.getSpanKinds() != null && !rule.getSpanKinds().isEmpty() + ? rule.getSpanKinds().stream() + .map(DeclarativeConfigSamplingPredicate::toSpanKind) + .collect(toSet()) + : null; + + SamplingPredicate predicate = + new DeclarativeConfigSamplingPredicate( + valueMatcher, patternMatcher, matchingParents, matchingSpanKinds); + ComposableSampler sampler = + ComposableSamplerFactory.getInstance() + .create(requireNonNull(rule.getSampler(), "rule sampler"), context); + builder.add(predicate, sampler); + }); + } + + return builder.build(); + } + + @Nullable + private static AttributeMatcher attributeValuesMatcher( + @Nullable + ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel attributeValuesModel) { + if (attributeValuesModel == null) { + return null; + } + List values = attributeValuesModel.getValues(); + if (values == null || values.isEmpty()) { + throw new DeclarativeConfigException(".values is required and must be non-empty"); + } + return new AttributeMatcher( + requireNonNull(attributeValuesModel.getKey(), "attribute_values key"), + IncludeExcludePredicate.createExactMatching(values, null)); + } + + @Nullable + private static AttributeMatcher attributePatternsMatcher( + @Nullable + ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel attributePatternsModel) { + if (attributePatternsModel == null) { + return null; + } + List included = attributePatternsModel.getIncluded(); + if (included != null && included.isEmpty()) { + throw new DeclarativeConfigException("included must not be empty"); + } + List excluded = attributePatternsModel.getExcluded(); + if (excluded != null && excluded.isEmpty()) { + throw new DeclarativeConfigException("excluded must not be empty"); + } + return new AttributeMatcher( + requireNonNull(attributePatternsModel.getKey(), "attribute_patterns key"), + IncludeExcludePredicate.createPatternMatching(included, excluded)); + } + + // Visible for testing + static final class DeclarativeConfigSamplingPredicate implements SamplingPredicate { + @Nullable private final AttributeMatcher attributeValuesMatcher; + @Nullable private final AttributeMatcher attributePatternsMatcher; + @Nullable private final Set matchingParents; + @Nullable private final Set matchingSpanKinds; + + DeclarativeConfigSamplingPredicate( + @Nullable AttributeMatcher attributeValuesMatcher, + @Nullable AttributeMatcher attributePatternsMatcher, + @Nullable Set matchingParents, + @Nullable Set matchingSpanKinds) { + this.attributeValuesMatcher = attributeValuesMatcher; + this.attributePatternsMatcher = attributePatternsMatcher; + this.matchingParents = matchingParents; + this.matchingSpanKinds = matchingSpanKinds; + } + + @Override + public boolean matches( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + // all conditions must match + + // check attribute value condition + if (attributeValuesMatcher != null && !attributesMatch(attributeValuesMatcher, attributes)) { + return false; + } + + // check attribute pattern condition + if (attributePatternsMatcher != null + && !attributesMatch(attributePatternsMatcher, attributes)) { + return false; + } + + // check parent condition + if (matchingParents != null + && !matchingParents.contains( + toSpanParent(Span.fromContext(parentContext).getSpanContext()))) { + return false; + } + + // check span kind conditions + if (matchingSpanKinds != null && !matchingSpanKinds.contains(spanKind)) { + return false; + } + + // If no conditions are specified, match all spans + return true; + } + + private static boolean attributesMatch(AttributeMatcher matcher, Attributes attributes) { + boolean[] match = new boolean[] {false}; + attributes.forEach((key, value) -> { + if (!matcher.matchesKey(key.getKey())) { + return; + } + if (value instanceof List) { + // For array attributes, it is a match if any item matches + for (Object item : (List) value) { + if (matcher.matchesValue(String.valueOf(item))) { + match[0] = true; + return; + } + } + } else if (matcher.matchesValue(String.valueOf(value))) { + match[0] = true; + } + }); + return match[0]; + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "DeclarativeConfigSamplingPredicate{", "}"); + joiner.add("attributeValuesMatcher=" + attributeValuesMatcher); + joiner.add("attributePatterns=" + attributePatternsMatcher); + joiner.add("matchingParents=" + matchingParents); + joiner.add("matchingSpanKinds=" + matchingSpanKinds); + return joiner.toString(); + } + + private static SpanKind toSpanKind(SpanKindModel spanKind) { + switch (spanKind) { + case INTERNAL: + return SpanKind.INTERNAL; + case SERVER: + return SpanKind.SERVER; + case CLIENT: + return SpanKind.CLIENT; + case PRODUCER: + return SpanKind.PRODUCER; + case CONSUMER: + return SpanKind.CONSUMER; + } + throw new IllegalArgumentException("Unrecognized span kind: " + spanKind); + } + + // Visible for testing + static ExperimentalSpanParentModel toSpanParent(SpanContext parentSpanContext) { + if (!parentSpanContext.isValid()) { + return ExperimentalSpanParentModel.NONE; + } + if (parentSpanContext.isRemote()) { + return ExperimentalSpanParentModel.REMOTE; + } + return ExperimentalSpanParentModel.LOCAL; + } + } + + // Visible for testing + static class AttributeMatcher { + private final Predicate attributeKeyMatcher; + private final Predicate attributeValueMatcher; + + AttributeMatcher(String attributeKey, Predicate attributeValueMatcher) { + this(new EqualsPredicate(attributeKey), attributeValueMatcher); + } + + AttributeMatcher( + Predicate attributeKeyMatcher, Predicate attributeValueMatcher) { + this.attributeKeyMatcher = attributeKeyMatcher; + this.attributeValueMatcher = attributeValueMatcher; + } + + boolean matchesKey(String attributeKey) { + return attributeKeyMatcher.test(attributeKey); + } + + boolean matchesValue(String attributeValue) { + return attributeValueMatcher.test(attributeValue); + } + + @Override + public String toString() { + return "AttributeMatcher{keyMatcher=" + + attributeKeyMatcher + + ", valueMatcher=" + + attributeValueMatcher + + '}'; + } + } + + private static class EqualsPredicate implements Predicate { + private final String value; + + private EqualsPredicate(String value) { + this.value = value; + } + + @Override + public boolean test(String s) { + return value.equals(s); + } + + @Override + public String toString() { + return "EqualsPredicate{" + value + '}'; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableSamplerFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableSamplerFactory.java new file mode 100644 index 00000000000..0ce055c0ddd --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableSamplerFactory.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableParentThresholdSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableProbabilitySamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerModel; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.ComposableSampler; + +final class ComposableSamplerFactory + implements Factory { + + private static final ComposableSamplerFactory INSTANCE = new ComposableSamplerFactory(); + + private ComposableSamplerFactory() {} + + static ComposableSamplerFactory getInstance() { + return INSTANCE; + } + + @Override + public ComposableSampler create( + ExperimentalComposableSamplerModel model, DeclarativeConfigContext context) { + // We don't use the variable till later but call validate first to confirm there are not + // multiple samplers. + ConfigKeyValue samplerKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "composable sampler"); + + if (model.getAlwaysOn() != null) { + return ComposableSampler.alwaysOn(); + } + if (model.getAlwaysOff() != null) { + return ComposableSampler.alwaysOff(); + } + if (model.getProbability() != null) { + return createProbabilitySampler(model.getProbability()); + } + if (model.getRuleBased() != null) { + return ComposableRuleBasedSamplerFactory.getInstance().create(model.getRuleBased(), context); + } + if (model.getParentThreshold() != null) { + return createParentThresholdSampler(model.getParentThreshold(), context); + } + + return context.loadComponent(ComposableSampler.class, samplerKeyValue); + } + + private static ComposableSampler createProbabilitySampler( + ExperimentalComposableProbabilitySamplerModel probabilityModel) { + Double ratio = probabilityModel.getRatio(); + if (ratio == null) { + ratio = 1.0d; + } + return ComposableSampler.probability(ratio); + } + + private static ComposableSampler createParentThresholdSampler( + ExperimentalComposableParentThresholdSamplerModel parentThresholdModel, + DeclarativeConfigContext context) { + ExperimentalComposableSamplerModel rootModel = + FileConfigUtil.requireNonNull( + parentThresholdModel.getRoot(), "parent threshold sampler root"); + ComposableSampler rootSampler = INSTANCE.create(rootModel, context); + return ComposableSampler.parentThreshold(rootSampler); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ConfigKeyValue.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ConfigKeyValue.java new file mode 100644 index 00000000000..c7793805e5d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ConfigKeyValue.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; + +/** A key value pair for a YAML mapping node. */ +class ConfigKeyValue { + + private final String key; + private final DeclarativeConfigProperties value; + + private ConfigKeyValue(String key, DeclarativeConfigProperties value) { + this.key = key; + this.value = value; + } + + static ConfigKeyValue of(String key, DeclarativeConfigProperties value) { + return new ConfigKeyValue(key, value); + } + + String getKey() { + return key; + } + + DeclarativeConfigProperties getValue() { + return value; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java new file mode 100644 index 00000000000..aeb44fd2e0d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContext.java @@ -0,0 +1,356 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.internal.ExtendedDeclarativeConfigProperties; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Collectors; +import javax.annotation.Nullable; + +/** + * Declarative configuration context and state carrier. + * + *

      This implements {@link ComponentLoader} with an implementation which delegates to an + * underlying instance while tracking instances which implement {@link AutoConfigureListener}, + * accessible via {@link #getListeners()}. + */ +class DeclarativeConfigContext implements ComponentLoader { + + private final ComponentLoader componentLoader; + private final Set listeners = + Collections.newSetFromMap(new IdentityHashMap<>()); + private final List closeables = new ArrayList<>(); + @Nullable private volatile MeterProvider meterProvider; + @Nullable private ConfigProvider configProvider; + @Nullable private List componentProviders = null; + + @Nullable + @SuppressWarnings("deprecation") + private List + legacyComponentProviders = null; + + @Nullable private DeclarativeConfigurationBuilder builder; + + DeclarativeConfigContext(ComponentLoader componentLoader) { + this.componentLoader = componentLoader; + } + + /** Return the underlying component loader. */ + ComponentLoader getDelegateComponentLoader() { + return componentLoader; + } + + /** + * Add the {@code closeable} to the list of closeables to clean up if configuration fails + * exceptionally, and return it. + */ + T addCloseable(T closeable) { + closeables.add(closeable); + return closeable; + } + + List getCloseables() { + return Collections.unmodifiableList(closeables); + } + + public void setMeterProvider(MeterProvider meterProvider) { + this.meterProvider = meterProvider; + } + + public void setConfigProvider(ConfigProvider configProvider) { + this.configProvider = configProvider; + } + + void setBuilder(DeclarativeConfigurationBuilder builder) { + this.builder = builder; + } + + DeclarativeConfigurationBuilder getBuilder() { + return Objects.requireNonNull(builder, "builder has not been set"); + } + + /** + * Overload of {@link #setInternalTelemetry(Consumer, Consumer)} for components which do not + * support setting {@link InternalTelemetryVersion} because they only support {@link + * InternalTelemetryVersion#LATEST}. + */ + public void setInternalTelemetry(Consumer> meterProviderSetter) { + setInternalTelemetry(meterProviderSetter, unused -> {}); + } + + /** + * Set internal telemetry on built-in components. + * + * @param meterProviderSetter the component meter provider setter + * @param internalTelemetrySetter the component internal telemetry setter + */ + public void setInternalTelemetry( + Consumer> meterProviderSetter, + Consumer internalTelemetrySetter) { + InternalTelemetryVersion telemetryVersion = getInternalTelemetryVersion(); + if (telemetryVersion != null) { + meterProviderSetter.accept(() -> Objects.requireNonNull(meterProvider)); + internalTelemetrySetter.accept(telemetryVersion); + } else { + meterProviderSetter.accept(MeterProvider::noop); + } + } + + @Nullable + private InternalTelemetryVersion getInternalTelemetryVersion() { + if (configProvider == null) { + return null; + } + String internalTelemetryVersion = + configProvider.getInstrumentationConfig("otel_sdk").getString("internal_telemetry_version"); + if (internalTelemetryVersion == null) { + return null; + } + switch (internalTelemetryVersion.toLowerCase(Locale.ROOT)) { + case "legacy": + return InternalTelemetryVersion.LEGACY; + case "latest": + return InternalTelemetryVersion.LATEST; + default: + throw new DeclarativeConfigException( + "Invalid sdk telemetry version: " + internalTelemetryVersion); + } + } + + /** + * Find a registered {@link ComponentProvider} with {@link ComponentProvider#getType()} matching + * {@code type}, {@link ComponentProvider#getName()} matching {@code name}, and call {@link + * ComponentProvider#create(DeclarativeConfigProperties)} with the given {@code model}. + * + * @throws DeclarativeConfigException if no matching providers are found, or if multiple are found + * (i.e. conflict), or if {@link ComponentProvider#create(DeclarativeConfigProperties)} throws + */ + @SuppressWarnings({"unchecked", "deprecation"}) + T loadComponent(Class type, ConfigKeyValue configKeyValue) { + String name = configKeyValue.getKey(); + ExtendedDeclarativeConfigProperties config = + new ExtendedDeclarativeConfigPropertiesImpl( + configKeyValue.getValue(), + configProvider == null ? ConfigProvider.noop() : configProvider); + + List providers = this.componentProviders; + List legacyProviders = + this.legacyComponentProviders; + if (providers == null || legacyProviders == null) { + providers = ComponentLoader.loadList(this, ComponentProvider.class); + legacyProviders = + ComponentLoader.loadList( + this, io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider.class); + this.componentProviders = providers; + this.legacyComponentProviders = legacyProviders; + } + List matchedProviders = + providers.stream() + .filter(componentProvider -> + componentProvider.getType() == type && name.equals(componentProvider.getName())) + .collect(Collectors.toList()); + List matchedLegacyProviders = + legacyProviders.stream() + .filter(componentProvider -> + componentProvider.getType() == type && name.equals(componentProvider.getName())) + .collect(Collectors.toList()); + + int totalMatches = matchedProviders.size() + matchedLegacyProviders.size(); + if (totalMatches == 0) { + throw new DeclarativeConfigException( + "No component provider detected for " + type.getName() + " with name \"" + name + "\"."); + } + if (totalMatches > 1) { + List providerClassNames = new ArrayList<>(); + matchedProviders.forEach(provider -> providerClassNames.add(provider.getClass().getName())); + matchedLegacyProviders.forEach( + provider -> providerClassNames.add(provider.getClass().getName())); + throw new DeclarativeConfigException( + "Component provider conflict. Multiple providers detected for " + + type.getName() + + " with name \"" + + name + + "\": " + + providerClassNames.stream().collect(Collectors.joining(",", "[", "]"))); + } + + Object component; + String providerClassName; + try { + if (!matchedProviders.isEmpty()) { + ComponentProvider provider = matchedProviders.get(0); + providerClassName = provider.getClass().getName(); + component = provider.create(config); + } else { + io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider provider = + matchedLegacyProviders.get(0); + providerClassName = provider.getClass().getName(); + component = provider.create(new LegacyYamlDeclarativeConfigProperties(config)); + } + if (component instanceof Closeable) { + closeables.add((Closeable) component); + } + if (component != null && !type.isInstance(component)) { + throw new DeclarativeConfigException( + "Error configuring " + + type.getName() + + " with name \"" + + name + + "\". Component provider " + + providerClassName + + " returned an unexpected component type: " + + component.getClass().getName()); + } + return (T) component; + } catch (Throwable throwable) { + throw new DeclarativeConfigException( + "Error configuring " + type.getName() + " with name \"" + name + "\"", throwable); + } + } + + @Override + public String toString() { + return "DeclarativeConfigContext{componentLoader=" + componentLoader + '}'; + } + + @Override + public Iterable load(Class spiClass) { + List result = ComponentLoader.loadList(componentLoader, spiClass); + result.forEach(entry -> { + if (entry instanceof AutoConfigureListener) { + listeners.add((AutoConfigureListener) entry); + } + }); + return result; + } + + Set getListeners() { + return Collections.unmodifiableSet(listeners); + } + + private static class ExtendedDeclarativeConfigPropertiesImpl + implements ExtendedDeclarativeConfigProperties { + + private final DeclarativeConfigProperties delegate; + private final ConfigProvider configProvider; + + ExtendedDeclarativeConfigPropertiesImpl( + DeclarativeConfigProperties delegate, ConfigProvider configProvider) { + this.delegate = delegate; + this.configProvider = configProvider; + } + + @Override + public ConfigProvider getConfigProvider() { + return configProvider; + } + + @Nullable + @Override + public String getString(String name) { + return delegate.getString(name); + } + + @Nullable + @Override + public Boolean getBoolean(String name) { + return delegate.getBoolean(name); + } + + @Nullable + @Override + public Integer getInt(String name) { + return delegate.getInt(name); + } + + @Nullable + @Override + public Long getLong(String name) { + return delegate.getLong(name); + } + + @Nullable + @Override + public Double getDouble(String name) { + return delegate.getDouble(name); + } + + @Override + public boolean isString(String name) { + return delegate.isString(name); + } + + @Override + public boolean isBoolean(String name) { + return delegate.isBoolean(name); + } + + @Override + public boolean isInt(String name) { + return delegate.isInt(name); + } + + @Override + public boolean isLong(String name) { + return delegate.isLong(name); + } + + @Override + public boolean isDouble(String name) { + return delegate.isDouble(name); + } + + @Nullable + @Override + public List getScalarList(String name, Class scalarType) { + return delegate.getScalarList(name, scalarType); + } + + @Nullable + @Override + public DeclarativeConfigProperties getStructured(String name) { + return delegate.getStructured(name); + } + + @Nullable + @Override + public List getStructuredList(String name) { + return delegate.getStructuredList(name); + } + + @Override + public Set getPropertyKeys() { + return delegate.getPropertyKeys(); + } + + @Override + public ComponentLoader getComponentLoader() { + return delegate.getComponentLoader(); + } + + @Override + public String toString() { + return "ExtendedDeclarativeConfigPropertiesImpl{" + delegate + '}'; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigResult.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigResult.java new file mode 100644 index 00000000000..cdfb8623b61 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigResult.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.resources.Resource; + +/** The result of {@link DeclarativeConfiguration#create(OpenTelemetryConfigurationModel)}. */ +public final class DeclarativeConfigResult { + + private final ExtendedOpenTelemetrySdk sdk; + private final Resource resource; + + DeclarativeConfigResult(ExtendedOpenTelemetrySdk sdk, Resource resource) { + this.sdk = sdk; + this.resource = resource; + } + + public ExtendedOpenTelemetrySdk getSdk() { + return sdk; + } + + public Resource getResource() { + return resource; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfiguration.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfiguration.java new file mode 100644 index 00000000000..d0c80d36a2c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfiguration.java @@ -0,0 +1,259 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal.DeclarativeConfigProviderLoader; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal.DeclarativeConfigurationMapperUtil; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.spi.Ordered; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.io.Closeable; +import java.io.IOException; +import java.io.InputStream; +import java.util.Collections; +import java.util.Map; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Configure {@link OpenTelemetrySdk} using declarative + * configuration. For most users, this means calling {@link #parseAndCreate(InputStream)} with a + * YAML + * configuration file. + * + *

      For Implementers

      + * + *

      YAML parsing and model mapping can be replaced by implementations of {@link + * DeclarativeConfigurationYamlParser} and {@link DeclarativeConfigurationMapper}. + */ +public final class DeclarativeConfiguration { + + private static final Logger logger = Logger.getLogger(DeclarativeConfiguration.class.getName()); + private static final ComponentLoader DEFAULT_COMPONENT_LOADER = + ComponentLoader.forClassLoader(DeclarativeConfigProperties.class.getClassLoader()); + + private DeclarativeConfiguration() {} + + /** + * Combines {@link #parse(InputStream)} and {@link #create(OpenTelemetryConfigurationModel)}. + * + * @throws DeclarativeConfigException if unable to parse or interpret + */ + public static DeclarativeConfigResult parseAndCreate(InputStream inputStream) { + OpenTelemetryConfigurationModel configurationModel = parse(inputStream); + return create(configurationModel); + } + + /** + * Interpret the {@code configurationModel} to create {@link OpenTelemetrySdk} instance + * corresponding to the configuration. + * + * @param configurationModel the configuration model + * @return the {@link DeclarativeConfigResult} + * @throws DeclarativeConfigException if unable to interpret + */ + public static DeclarativeConfigResult create(OpenTelemetryConfigurationModel configurationModel) { + return create(configurationModel, DEFAULT_COMPONENT_LOADER); + } + + /** + * Interpret the {@code configurationModel} to create {@link OpenTelemetrySdk} instance + * corresponding to the configuration. + * + * @param configurationModel the configuration model + * @param componentLoader the component loader used to load {@link ComponentProvider} + * implementations + * @return the {@link DeclarativeConfigResult} + * @throws DeclarativeConfigException if unable to interpret + */ + public static DeclarativeConfigResult create( + OpenTelemetryConfigurationModel configurationModel, ComponentLoader componentLoader) { + return create(configurationModel, new DeclarativeConfigContext(componentLoader)); + } + + private static DeclarativeConfigResult create( + OpenTelemetryConfigurationModel configurationModel, DeclarativeConfigContext context) { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + context.setBuilder(builder); + + for (DeclarativeConfigurationCustomizerProvider provider : + Ordered.loadOrderedList(context, DeclarativeConfigurationCustomizerProvider.class)) { + provider.customize(builder); + } + + DeclarativeConfigResult result = + createAndMaybeCleanup( + OpenTelemetryConfigurationFactory.getInstance(), + context, + builder.customizeModel(configurationModel)); + callAutoConfigureListeners(context, result.getSdk()); + return result; + } + + /** + * Parse the {@code configuration} YAML and return the {@link OpenTelemetryConfigurationModel}. + * + *

      During parsing, environment variable and system property substitution is performed as + * defined in the + * OpenTelemetry Configuration Data Model specification. + * + * @throws DeclarativeConfigException if unable to parse + */ + public static OpenTelemetryConfigurationModel parse(InputStream configuration) { + try { + return parse(configuration, System.getenv(), System.getProperties()); + } catch (DeclarativeConfigException e) { + throw e; + } catch (RuntimeException e) { + throw new DeclarativeConfigException("Unable to parse configuration input stream", e); + } + } + + // Visible for testing + static OpenTelemetryConfigurationModel parse( + InputStream configuration, + Map environmentVariables, + Map systemProperties) { + Object yamlObj = loadYaml(configuration, environmentVariables, systemProperties); + OpenTelemetryConfigurationModel model; + try { + model = + DeclarativeConfigurationMapperUtil.convert( + yamlObj, OpenTelemetryConfigurationModel.class); + } catch (DeclarativeConfigException e) { + throw new DeclarativeConfigException("Unable to parse configuration input stream", e); + } + return Objects.requireNonNull(model, "Unable to map configuration to model"); + } + + // Visible for testing + static Object loadYaml( + InputStream inputStream, + Map environmentVariables, + Map systemProperties) { + try { + return DeclarativeConfigProviderLoader.getYamlParser() + .parse(inputStream, environmentVariables, systemProperties); + } catch (DeclarativeConfigException e) { + throw e; + } catch (RuntimeException e) { + throw new DeclarativeConfigException("Unable to parse configuration input stream", e); + } + } + + /** + * Convert the {@code model} to a generic {@link DeclarativeConfigProperties}. + * + * @param model the configuration model + * @return a generic {@link DeclarativeConfigProperties} representation of the model + * @throws DeclarativeConfigException if unable to convert + */ + public static DeclarativeConfigProperties toConfigProperties(Object model) { + return toConfigProperties(model, DEFAULT_COMPONENT_LOADER); + } + + /** + * Convert the {@code configuration} YAML to a generic {@link DeclarativeConfigProperties}. + * + * @param configuration configuration YAML + * @return a generic {@link DeclarativeConfigProperties} representation of the model + * @throws DeclarativeConfigException if unable to parse or convert + */ + public static DeclarativeConfigProperties toConfigProperties(InputStream configuration) { + Object yamlObj = loadYaml(configuration, System.getenv(), System.getProperties()); + return toConfigProperties(yamlObj, DEFAULT_COMPONENT_LOADER); + } + + static DeclarativeConfigProperties toConfigProperties( + Object model, ComponentLoader componentLoader) { + Map configurationMap = DeclarativeConfigurationMapperUtil.toMap(model); + if (configurationMap == null) { + configurationMap = Collections.emptyMap(); + } + return YamlDeclarativeConfigProperties.create(configurationMap, componentLoader); + } + + /** + * Create a {@link SamplerModel} from the {@code samplerModel} representing the sampler config. + * + *

      This is used when samplers are composed, with one sampler accepting one or more additional + * samplers as config properties. The {@link ComponentProvider} implementation can call this to + * configure a delegate {@link SamplerModel} from the {@link DeclarativeConfigProperties} + * corresponding to a particular config property. + */ + // TODO(jack-berg): add create methods for all SDK extension components supported by + // ComponentProvider + public static Sampler createSampler(DeclarativeConfigProperties genericSamplerModel) { + YamlDeclarativeConfigProperties yamlDeclarativeConfigProperties = + requireYamlDeclarativeConfigProperties(genericSamplerModel); + SamplerModel samplerModel = + Objects.requireNonNull( + DeclarativeConfigurationMapperUtil.convert( + DeclarativeConfigProperties.toMap(yamlDeclarativeConfigProperties), + SamplerModel.class), + "Unable to map sampler configuration to model"); + return createAndMaybeCleanup( + SamplerFactory.getInstance(), + new DeclarativeConfigContext(yamlDeclarativeConfigProperties.getComponentLoader()), + samplerModel); + } + + private static YamlDeclarativeConfigProperties requireYamlDeclarativeConfigProperties( + DeclarativeConfigProperties declarativeConfigProperties) { + if (!(declarativeConfigProperties instanceof YamlDeclarativeConfigProperties)) { + throw new DeclarativeConfigException( + "Only YamlDeclarativeConfigProperties can be converted to model"); + } + return (YamlDeclarativeConfigProperties) declarativeConfigProperties; + } + + static R createAndMaybeCleanup( + Factory factory, DeclarativeConfigContext context, M model) { + try { + return factory.create(model, context); + } catch (RuntimeException e) { + logger.info("Error encountered interpreting model. Closing partially configured components."); + for (Closeable closeable : context.getCloseables()) { + try { + logger.fine("Closing " + closeable.getClass().getName()); + closeable.close(); + } catch (IOException ex) { + logger.log(Level.WARNING, "Error closing " + closeable.getClass().getName(), ex); + } + } + if (e instanceof DeclarativeConfigException) { + throw e; + } + throw new DeclarativeConfigException("Unexpected configuration error", e); + } + } + + // Visible for testing + static void callAutoConfigureListeners( + DeclarativeConfigContext context, OpenTelemetrySdk openTelemetrySdk) { + for (AutoConfigureListener listener : context.getListeners()) { + try { + listener.afterAutoConfigure(openTelemetrySdk); + } catch (Throwable throwable) { + logger.log( + Level.WARNING, "Error invoking listener " + listener.getClass().getName(), throwable); + } + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationBuilder.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationBuilder.java new file mode 100644 index 00000000000..176302cc561 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationBuilder.java @@ -0,0 +1,117 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.function.BiFunction; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** Builder for the declarative configuration. */ +public class DeclarativeConfigurationBuilder implements DeclarativeConfigurationCustomizer { + private Function + modelCustomizer = Function.identity(); + + private final List> spanExporterCustomizers = new ArrayList<>(); + private final List> metricExporterCustomizers = new ArrayList<>(); + private final List> logRecordExporterCustomizers = + new ArrayList<>(); + + @Override + public void addModelCustomizer( + Function customizer) { + modelCustomizer = mergeCustomizer(modelCustomizer, customizer); + } + + @Override + public void addSpanExporterCustomizer( + Class exporterType, BiFunction customizer) { + spanExporterCustomizers.add(new Customizer<>(exporterType, customizer)); + } + + @Override + public void addMetricExporterCustomizer( + Class exporterType, BiFunction customizer) { + metricExporterCustomizers.add(new Customizer<>(exporterType, customizer)); + } + + @Override + public void addLogRecordExporterCustomizer( + Class exporterType, BiFunction customizer) { + logRecordExporterCustomizers.add(new Customizer<>(exporterType, customizer)); + } + + List> getSpanExporterCustomizers() { + return Collections.unmodifiableList(spanExporterCustomizers); + } + + List> getMetricExporterCustomizers() { + return Collections.unmodifiableList(metricExporterCustomizers); + } + + List> getLogRecordExporterCustomizers() { + return Collections.unmodifiableList(logRecordExporterCustomizers); + } + + private static Function mergeCustomizer( + Function first, Function second) { + return (I configured) -> { + O1 firstResult = first.apply(configured); + return second.apply(firstResult); + }; + } + + /** Customize the configuration model. */ + public OpenTelemetryConfigurationModel customizeModel( + OpenTelemetryConfigurationModel configurationModel) { + return modelCustomizer.apply(configurationModel); + } + + static class Customizer { + private static final Logger logger = Logger.getLogger(Customizer.class.getName()); + + private final Class exporterType; + private final BiFunction customizer; + + @SuppressWarnings({"unchecked", "ReferenceEquality"}) + Customizer( + Class exporterType, BiFunction customizer) { + this.exporterType = exporterType; + this.customizer = (BiFunction) customizer; + } + + @SuppressWarnings("ReferenceEquality") + T maybeCustomize(T exporter, String name, DeclarativeConfigProperties properties) { + if (!exporterType.isInstance(exporter)) { + return exporter; + } + T customized = customizer.apply(exporter, properties); + if (customized == null) { + throw new DeclarativeConfigException( + "Customizer returned null for " + exporterType.getSimpleName() + ": " + name); + } + if (customized != exporter && exporter instanceof Closeable) { + try { + ((Closeable) exporter).close(); + } catch (IOException e) { + logger.log(Level.WARNING, "Failed to close exporter after customization", e); + } + } + return customized; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCustomizer.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCustomizer.java new file mode 100644 index 00000000000..13f8454a9c0 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCustomizer.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.function.BiFunction; +import java.util.function.Function; + +/** A service provider interface (SPI) for customizing declarative configuration. */ +public interface DeclarativeConfigurationCustomizer { + /** + * Method invoked when configuring the SDK to allow further customization of the declarative + * configuration. + * + * @param customizer the customizer to add + */ + void addModelCustomizer( + Function customizer); + + /** + * Add customizer for {@link SpanExporter} instances created from declarative configuration. + * Multiple customizers compose in registration order. + * + * @param exporterType the exporter type to customize + * @param customizer function receiving (exporter, properties) and returning customized exporter; + * must not return null + * @param the exporter type + */ + void addSpanExporterCustomizer( + Class exporterType, BiFunction customizer); + + /** + * Add customizer for {@link MetricExporter} instances created from declarative configuration. + * Multiple customizers compose in registration order. + * + * @param exporterType the exporter type to customize + * @param customizer function receiving (exporter, properties) and returning customized exporter; + * must not return null + * @param the exporter type + */ + void addMetricExporterCustomizer( + Class exporterType, BiFunction customizer); + + /** + * Add customizer for {@link LogRecordExporter} instances created from declarative configuration. + * Multiple customizers compose in registration order. + * + *

      If the customizer wraps the exporter in a new {@link java.io.Closeable} instance, the + * customizer is responsible for resource cleanup. + * + * @param exporterType the exporter type to customize + * @param customizer function receiving (exporter, properties) and returning customized exporter; + * must not return null + * @param the exporter type + */ + void addLogRecordExporterCustomizer( + Class exporterType, BiFunction customizer); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCustomizerProvider.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCustomizerProvider.java new file mode 100644 index 00000000000..1e0f3676299 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCustomizerProvider.java @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.spi.Ordered; + +/** A service provider interface (SPI) for customizing declarative configuration. */ +public interface DeclarativeConfigurationCustomizerProvider extends Ordered { + /** + * Method invoked when configuring the SDK to allow further customization of the declarative + * configuration. + * + * @param customizer the customizer to add + */ + void customize(DeclarativeConfigurationCustomizer customizer); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationProvider.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationProvider.java new file mode 100644 index 00000000000..f8915f669fa --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationProvider.java @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import javax.annotation.Nullable; + +/** A service provider interface (SPI) for providing a declarative configuration model. */ +public interface DeclarativeConfigurationProvider { + /** + * Returns an OpenTelemetry configuration model to be used when configuring the SDK, or {@code + * null} if no configuration is provided by this provider. + */ + @Nullable + OpenTelemetryConfigurationModel getConfigurationModel(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/EntitiesEnvResourceDetector.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/EntitiesEnvResourceDetector.java new file mode 100644 index 00000000000..e8502228e77 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/EntitiesEnvResourceDetector.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.EnvironmentResource.ENTITIES_PROPERTY; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collections; + +/** Detects entities set from {@code OTEL_ENTITIES} for declarative configuration. */ +public class EntitiesEnvResourceDetector implements ComponentProvider { + + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "env"; + } + + @Override + public Resource create(DeclarativeConfigProperties config) { + ConfigProperties properties = + DefaultConfigProperties.create(Collections.emptyMap(), config.getComponentLoader()); + return EnvironmentResource.createEntitiesResource(properties.getString(ENTITIES_PROPERTY)); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExemplarFilterFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExemplarFilterFactory.java new file mode 100644 index 00000000000..ded6d9dde1c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExemplarFilterFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExemplarFilterModel; +import io.opentelemetry.sdk.metrics.ExemplarFilter; + +final class ExemplarFilterFactory implements Factory { + + private static final ExemplarFilterFactory INSTANCE = new ExemplarFilterFactory(); + + private ExemplarFilterFactory() {} + + static ExemplarFilterFactory getInstance() { + return INSTANCE; + } + + @Override + public ExemplarFilter create(ExemplarFilterModel model, DeclarativeConfigContext context) { + switch (model) { + case ALWAYS_ON: + return ExemplarFilter.alwaysOn(); + case ALWAYS_OFF: + return ExemplarFilter.alwaysOff(); + case TRACE_BASED: + return ExemplarFilter.traceBased(); + } + throw new DeclarativeConfigException("Unrecognized exemplar filter: " + model); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/Factory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/Factory.java new file mode 100644 index 00000000000..f38ffc99515 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/Factory.java @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +interface Factory { + + /** + * Interpret the model and create {@link ResultT} with corresponding configuration. + * + * @param model the configuration model + * @param context the configuration context + * @return the {@link ResultT} + */ + ResultT create(ModelT model, DeclarativeConfigContext context); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/FileConfigUtil.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/FileConfigUtil.java new file mode 100644 index 00000000000..dfb0df29289 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/FileConfigUtil.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static java.util.stream.Collectors.joining; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import java.util.Set; +import javax.annotation.Nullable; + +final class FileConfigUtil { + + private FileConfigUtil() {} + + static T requireNonNull(@Nullable T object, String description) { + if (object == null) { + throw new DeclarativeConfigException(description + " is required but is null"); + } + return object; + } + + static ConfigKeyValue validateSingleKeyValue( + DeclarativeConfigContext context, Object model, String resourceName) { + DeclarativeConfigProperties modelConfigProperties = + DeclarativeConfiguration.toConfigProperties(model, context); + Set propertyKeys = modelConfigProperties.getPropertyKeys(); + if (propertyKeys.size() != 1) { + String suffix = + propertyKeys.isEmpty() + ? "" + : ": " + propertyKeys.stream().collect(joining(",", "[", "]")); + throw new DeclarativeConfigException( + resourceName + " must have exactly one entry but has " + propertyKeys.size() + suffix); + } + String key = propertyKeys.iterator().next(); + DeclarativeConfigProperties value = modelConfigProperties.getStructured(key); + return ConfigKeyValue.of(key, value == null ? DeclarativeConfigProperties.empty() : value); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IdGeneratorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IdGeneratorFactory.java new file mode 100644 index 00000000000..219d332f461 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IdGeneratorFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IdGeneratorModel; +import io.opentelemetry.sdk.trace.IdGenerator; + +final class IdGeneratorFactory implements Factory { + + private static final IdGeneratorFactory INSTANCE = new IdGeneratorFactory(); + + private IdGeneratorFactory() {} + + static IdGeneratorFactory getInstance() { + return INSTANCE; + } + + @Override + public IdGenerator create(IdGeneratorModel model, DeclarativeConfigContext context) { + // We don't use the variable till later but call validate first to confirm there are not + // multiple IdGenerators. + ConfigKeyValue processorKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "id generator"); + + if (model.getRandom() != null) { + return IdGenerator.random(); + } + + return context.loadComponent(IdGenerator.class, processorKeyValue); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IncludeExcludeFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IncludeExcludeFactory.java new file mode 100644 index 00000000000..2506e8466a2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IncludeExcludeFactory.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import java.util.List; +import java.util.function.Predicate; + +final class IncludeExcludeFactory implements Factory> { + + private static final IncludeExcludeFactory INSTANCE = new IncludeExcludeFactory(); + + private IncludeExcludeFactory() {} + + static IncludeExcludeFactory getInstance() { + return INSTANCE; + } + + @Override + public Predicate create(IncludeExcludeModel model, DeclarativeConfigContext context) { + List included = model.getIncluded(); + if (included != null && included.isEmpty()) { + throw new DeclarativeConfigException("included must not be empty"); + } + List excluded = model.getExcluded(); + if (excluded != null && excluded.isEmpty()) { + throw new DeclarativeConfigException("excluded must not be empty"); + } + + return IncludeExcludePredicate.createPatternMatching(included, excluded); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactory.java new file mode 100644 index 00000000000..e7f40741e82 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactory.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.InstrumentSelectorBuilder; +import io.opentelemetry.sdk.metrics.InstrumentType; + +final class InstrumentSelectorFactory implements Factory { + + private static final InstrumentSelectorFactory INSTANCE = new InstrumentSelectorFactory(); + + private InstrumentSelectorFactory() {} + + static InstrumentSelectorFactory getInstance() { + return INSTANCE; + } + + @Override + public InstrumentSelector create(ViewSelectorModel model, DeclarativeConfigContext context) { + InstrumentSelectorBuilder builder = InstrumentSelector.builder(); + if (model.getInstrumentName() != null) { + builder.setName(model.getInstrumentName()); + } + if (model.getInstrumentType() != null) { + InstrumentType instrumentType; + try { + instrumentType = InstrumentType.valueOf(model.getInstrumentType().name()); + } catch (IllegalArgumentException e) { + throw new DeclarativeConfigException( + "Unrecognized instrument type: " + model.getInstrumentType(), e); + } + builder.setType(instrumentType); + } + if (model.getUnit() != null) { + builder.setUnit(model.getUnit()); + } + if (model.getMeterName() != null) { + builder.setMeterName(model.getMeterName()); + } + if (model.getMeterSchemaUrl() != null) { + builder.setMeterSchemaUrl(model.getMeterSchemaUrl()); + } + if (model.getMeterVersion() != null) { + builder.setMeterVersion(model.getMeterVersion()); + } + + try { + return builder.build(); + } catch (IllegalArgumentException e) { + throw new DeclarativeConfigException("Invalid selector", e); + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LegacyYamlDeclarativeConfigProperties.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LegacyYamlDeclarativeConfigProperties.java new file mode 100644 index 00000000000..623543756f3 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LegacyYamlDeclarativeConfigProperties.java @@ -0,0 +1,132 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.common.ComponentLoader; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import javax.annotation.Nullable; + +/** + * Temporary adapter of declarative config properties implementing the legacy incubator interface + * {@link io.opentelemetry.api.incubator.config.DeclarativeConfigProperties} for backwards + * compatibility with legacy {@link + * io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider}. + * + *

      Scheduled for removal after 1.68.0. + */ +@SuppressWarnings("deprecation") +final class LegacyYamlDeclarativeConfigProperties + implements io.opentelemetry.api.incubator.config.DeclarativeConfigProperties { + + private final DeclarativeConfigProperties delegate; + + LegacyYamlDeclarativeConfigProperties(DeclarativeConfigProperties delegate) { + this.delegate = delegate; + } + + @Nullable + @Override + public String getString(String name) { + return delegate.getString(name); + } + + @Nullable + @Override + public Boolean getBoolean(String name) { + return delegate.getBoolean(name); + } + + @Nullable + @Override + public Integer getInt(String name) { + return delegate.getInt(name); + } + + @Nullable + @Override + public Long getLong(String name) { + return delegate.getLong(name); + } + + @Nullable + @Override + public Double getDouble(String name) { + return delegate.getDouble(name); + } + + @Nullable + @Override + public List getScalarList(String name, Class scalarType) { + return delegate.getScalarList(name, scalarType); + } + + @Override + public boolean isString(String name) { + return delegate.isString(name); + } + + @Override + public boolean isBoolean(String name) { + return delegate.isBoolean(name); + } + + @Override + public boolean isInt(String name) { + return delegate.isInt(name); + } + + @Override + public boolean isLong(String name) { + return delegate.isLong(name); + } + + @Override + public boolean isDouble(String name) { + return delegate.isDouble(name); + } + + @Nullable + @Override + public io.opentelemetry.api.incubator.config.DeclarativeConfigProperties getStructured( + String name) { + DeclarativeConfigProperties structured = delegate.getStructured(name); + return structured == null ? null : new LegacyYamlDeclarativeConfigProperties(structured); + } + + @Nullable + @Override + public List getStructuredList( + String name) { + List list = delegate.getStructuredList(name); + if (list == null) { + return null; + } + List result = + new ArrayList<>(list.size()); + for (DeclarativeConfigProperties item : list) { + result.add(new LegacyYamlDeclarativeConfigProperties(item)); + } + return result; + } + + @Override + public Set getPropertyKeys() { + return delegate.getPropertyKeys(); + } + + @Override + public ComponentLoader getComponentLoader() { + return delegate.getComponentLoader(); + } + + @Override + public String toString() { + return "LegacyYamlDeclarativeConfigProperties{" + delegate + '}'; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogLimitsFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogLimitsFactory.java new file mode 100644 index 00000000000..8aa610d66ca --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogLimitsFactory.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.logs.LogLimitsBuilder; + +final class LogLimitsFactory implements Factory { + + private static final LogLimitsFactory INSTANCE = new LogLimitsFactory(); + + private LogLimitsFactory() {} + + static LogLimitsFactory getInstance() { + return INSTANCE; + } + + @Override + public LogLimits create( + LogRecordLimitsAndAttributeLimits model, DeclarativeConfigContext context) { + LogLimitsBuilder builder = LogLimits.builder(); + + AttributeLimitsModel attributeLimitsModel = model.getAttributeLimits(); + if (attributeLimitsModel != null) { + if (attributeLimitsModel.getAttributeCountLimit() != null) { + builder.setMaxNumberOfAttributes(attributeLimitsModel.getAttributeCountLimit()); + } + if (attributeLimitsModel.getAttributeValueLengthLimit() != null) { + builder.setMaxAttributeValueLength(attributeLimitsModel.getAttributeValueLengthLimit()); + } + } + + LogRecordLimitsModel logRecordLimitsModel = model.getLogRecordLimits(); + if (logRecordLimitsModel != null) { + if (logRecordLimitsModel.getAttributeCountLimit() != null) { + builder.setMaxNumberOfAttributes(logRecordLimitsModel.getAttributeCountLimit()); + } + if (logRecordLimitsModel.getAttributeValueLengthLimit() != null) { + builder.setMaxAttributeValueLength(logRecordLimitsModel.getAttributeValueLengthLimit()); + } + } + + return builder.build(); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactory.java new file mode 100644 index 00000000000..781f950663e --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; + +final class LogRecordExporterFactory implements Factory { + private static final LogRecordExporterFactory INSTANCE = new LogRecordExporterFactory(); + + private LogRecordExporterFactory() {} + + static LogRecordExporterFactory getInstance() { + return INSTANCE; + } + + @Override + public LogRecordExporter create(LogRecordExporterModel model, DeclarativeConfigContext context) { + ConfigKeyValue logRecordExporterKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "log record exporter"); + LogRecordExporter exporter = + context.loadComponent(LogRecordExporter.class, logRecordExporterKeyValue); + for (DeclarativeConfigurationBuilder.Customizer customizer : + context.getBuilder().getLogRecordExporterCustomizers()) { + exporter = + customizer.maybeCustomize( + exporter, logRecordExporterKeyValue.getKey(), logRecordExporterKeyValue.getValue()); + } + return exporter; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordLimitsAndAttributeLimits.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordLimitsAndAttributeLimits.java new file mode 100644 index 00000000000..5ffff22e45b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordLimitsAndAttributeLimits.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel; +import javax.annotation.Nullable; + +@AutoValue +abstract class LogRecordLimitsAndAttributeLimits { + + static LogRecordLimitsAndAttributeLimits create( + @Nullable AttributeLimitsModel attributeLimits, @Nullable LogRecordLimitsModel spanLimits) { + return new AutoValue_LogRecordLimitsAndAttributeLimits(attributeLimits, spanLimits); + } + + @Nullable + abstract AttributeLimitsModel getAttributeLimits(); + + @Nullable + abstract LogRecordLimitsModel getLogRecordLimits(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordProcessorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordProcessorFactory.java new file mode 100644 index 00000000000..81cfde81235 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordProcessorFactory.java @@ -0,0 +1,91 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LogRecordProcessorModelAccessor; +import io.opentelemetry.sdk.extension.incubator.logs.EventToSpanEventBridge; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessorBuilder; +import java.time.Duration; + +final class LogRecordProcessorFactory + implements Factory { + + private static final LogRecordProcessorFactory INSTANCE = new LogRecordProcessorFactory(); + + private LogRecordProcessorFactory() {} + + static LogRecordProcessorFactory getInstance() { + return INSTANCE; + } + + @Override + public LogRecordProcessor create( + LogRecordProcessorModel model, DeclarativeConfigContext context) { + // We don't use the variable till later but call validate first to confirm there are not + // multiple samplers. + ConfigKeyValue processorKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "log record processor"); + + if (model.getBatch() != null) { + return createBatchLogRecordProcessor(model.getBatch(), context); + } + if (model.getSimple() != null) { + return createSimpleLogRecordProcessor(model.getSimple(), context); + } + if (LogRecordProcessorModelAccessor.getEventToSpanEventBridge(model) != null) { + return EventToSpanEventBridge.create(); + } + + return context.loadComponent(LogRecordProcessor.class, processorKeyValue); + } + + private static LogRecordProcessor createBatchLogRecordProcessor( + BatchLogRecordProcessorModel batchModel, DeclarativeConfigContext context) { + LogRecordExporterModel exporterModel = + FileConfigUtil.requireNonNull( + batchModel.getExporter(), "batch log record processor exporter"); + + LogRecordExporter logRecordExporter = + LogRecordExporterFactory.getInstance().create(exporterModel, context); + BatchLogRecordProcessorBuilder builder = BatchLogRecordProcessor.builder(logRecordExporter); + if (batchModel.getExportTimeout() != null) { + builder.setExporterTimeout(Duration.ofMillis(batchModel.getExportTimeout())); + } + if (batchModel.getMaxExportBatchSize() != null) { + builder.setMaxExportBatchSize(batchModel.getMaxExportBatchSize()); + } + if (batchModel.getMaxQueueSize() != null) { + builder.setMaxQueueSize(batchModel.getMaxQueueSize()); + } + if (batchModel.getScheduleDelay() != null) { + builder.setScheduleDelay(Duration.ofMillis(batchModel.getScheduleDelay())); + } + context.setInternalTelemetry(builder::setMeterProvider, builder::setInternalTelemetryVersion); + + return context.addCloseable(builder.build()); + } + + private static LogRecordProcessor createSimpleLogRecordProcessor( + SimpleLogRecordProcessorModel simpleModel, DeclarativeConfigContext context) { + LogRecordExporterModel exporterModel = + FileConfigUtil.requireNonNull( + simpleModel.getExporter(), "simple log record processor exporter"); + LogRecordExporter logRecordExporter = + LogRecordExporterFactory.getInstance().create(exporterModel, context); + SimpleLogRecordProcessorBuilder builder = SimpleLogRecordProcessor.builder(logRecordExporter); + context.setInternalTelemetry(builder::setMeterProvider); + return context.addCloseable(builder.build()); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderAndAttributeLimits.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderAndAttributeLimits.java new file mode 100644 index 00000000000..143bb916c4a --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderAndAttributeLimits.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import javax.annotation.Nullable; + +@AutoValue +abstract class LoggerProviderAndAttributeLimits { + + static LoggerProviderAndAttributeLimits create( + @Nullable AttributeLimitsModel attributeLimits, + @Nullable LoggerProviderModel loggerProvider) { + return new AutoValue_LoggerProviderAndAttributeLimits(attributeLimits, loggerProvider); + } + + @Nullable + abstract AttributeLimitsModel getAttributeLimits(); + + @Nullable + abstract LoggerProviderModel getLoggerProvider(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java new file mode 100644 index 00000000000..a67ac48d781 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactory.java @@ -0,0 +1,173 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigUtil.requireNonNull; + +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SeverityNumberModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLoggerConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLoggerConfiguratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLoggerMatcherAndConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LoggerProviderModelAccessor; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.logs.internal.LoggerConfigBuilder; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import java.util.List; + +final class LoggerProviderFactory + implements Factory { + + private static final LoggerProviderFactory INSTANCE = new LoggerProviderFactory(); + + private LoggerProviderFactory() {} + + static LoggerProviderFactory getInstance() { + return INSTANCE; + } + + @Override + public SdkLoggerProviderBuilder create( + LoggerProviderAndAttributeLimits model, DeclarativeConfigContext context) { + SdkLoggerProviderBuilder builder = SdkLoggerProvider.builder(); + + LoggerProviderModel loggerProviderModel = model.getLoggerProvider(); + if (loggerProviderModel == null) { + return builder; + } + + context.setInternalTelemetry(builder::setMeterProvider); + + LogLimits logLimits = + LogLimitsFactory.getInstance() + .create( + LogRecordLimitsAndAttributeLimits.create( + model.getAttributeLimits(), loggerProviderModel.getLimits()), + context); + builder.setLogLimits(() -> logLimits); + + List processors = loggerProviderModel.getProcessors(); + if (processors != null) { + processors.forEach(processor -> + builder.addLogRecordProcessor( + LogRecordProcessorFactory.getInstance().create(processor, context))); + } + + ExperimentalLoggerConfiguratorModel loggerConfiguratorModel = + LoggerProviderModelAccessor.getLoggerConfigurator(loggerProviderModel); + if (loggerConfiguratorModel != null) { + ExperimentalLoggerConfigModel defaultConfigModel = loggerConfiguratorModel.getDefaultConfig(); + ScopeConfiguratorBuilder configuratorBuilder = ScopeConfigurator.builder(); + if (defaultConfigModel != null) { + configuratorBuilder.setDefault( + LoggerConfigFactory.INSTANCE.create(defaultConfigModel, context)); + } + List loggerMatcherAndConfigs = + loggerConfiguratorModel.getLoggers(); + if (loggerMatcherAndConfigs != null) { + for (ExperimentalLoggerMatcherAndConfigModel loggerMatcherAndConfig : + loggerMatcherAndConfigs) { + String name = requireNonNull(loggerMatcherAndConfig.getName(), "logger matcher name"); + ExperimentalLoggerConfigModel config = loggerMatcherAndConfig.getConfig(); + if (name == null || config == null) { + continue; + } + configuratorBuilder.addCondition( + ScopeConfiguratorBuilder.nameMatchesGlob(name), + LoggerProviderFactory.LoggerConfigFactory.INSTANCE.create(config, context)); + } + } + SdkLoggerProviderUtil.setLoggerConfigurator(builder, configuratorBuilder.build()); + } + + return builder; + } + + private static class LoggerConfigFactory + implements Factory { + + private static final LoggerProviderFactory.LoggerConfigFactory INSTANCE = + new LoggerProviderFactory.LoggerConfigFactory(); + + @Override + public LoggerConfig create( + ExperimentalLoggerConfigModel model, DeclarativeConfigContext context) { + LoggerConfigBuilder configBuilder = LoggerConfig.builder(); + if (model.getEnabled() != null && !model.getEnabled()) { + configBuilder.setEnabled(false); + } + if (model.getTraceBased() != null && model.getTraceBased()) { + configBuilder.setTraceBased(true); + } + if (model.getMinimumSeverity() != null) { + configBuilder.setMinimumSeverity(severityNumberToSeverity(model.getMinimumSeverity())); + } + return configBuilder.build(); + } + } + + // Visible for testing + static Severity severityNumberToSeverity(SeverityNumberModel model) { + switch (model) { + case TRACE: + return Severity.TRACE; + case TRACE_2: + return Severity.TRACE2; + case TRACE_3: + return Severity.TRACE3; + case TRACE_4: + return Severity.TRACE4; + case DEBUG: + return Severity.DEBUG; + case DEBUG_2: + return Severity.DEBUG2; + case DEBUG_3: + return Severity.DEBUG3; + case DEBUG_4: + return Severity.DEBUG4; + case INFO: + return Severity.INFO; + case INFO_2: + return Severity.INFO2; + case INFO_3: + return Severity.INFO3; + case INFO_4: + return Severity.INFO4; + case WARN: + return Severity.WARN; + case WARN_2: + return Severity.WARN2; + case WARN_3: + return Severity.WARN3; + case WARN_4: + return Severity.WARN4; + case ERROR: + return Severity.ERROR; + case ERROR_2: + return Severity.ERROR2; + case ERROR_3: + return Severity.ERROR3; + case ERROR_4: + return Severity.ERROR4; + case FATAL: + return Severity.FATAL; + case FATAL_2: + return Severity.FATAL2; + case FATAL_3: + return Severity.FATAL3; + case FATAL_4: + return Severity.FATAL4; + } + throw new IllegalArgumentException("Unrecognized severity number: " + model); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java new file mode 100644 index 00000000000..1eb96c282c6 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactory.java @@ -0,0 +1,121 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigUtil.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExemplarFilterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalMeterConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalMeterConfiguratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalMeterMatcherAndConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.MeterProviderModelAccessor; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import java.util.List; + +final class MeterProviderFactory implements Factory { + + private static final MeterProviderFactory INSTANCE = new MeterProviderFactory(); + + private MeterProviderFactory() {} + + static MeterProviderFactory getInstance() { + return INSTANCE; + } + + @Override + public SdkMeterProviderBuilder create( + MeterProviderModel model, DeclarativeConfigContext context) { + SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); + + List readerModels = model.getReaders(); + if (readerModels != null) { + readerModels.forEach(readerModel -> { + MetricReaderAndCardinalityLimits readerAndCardinalityLimits = + MetricReaderFactory.getInstance().create(readerModel, context); + CardinalityLimitSelector cardinalityLimits = + readerAndCardinalityLimits.getCardinalityLimitsSelector(); + if (cardinalityLimits == null) { + builder.registerMetricReader(readerAndCardinalityLimits.getMetricReader()); + } else { + builder.registerMetricReader( + readerAndCardinalityLimits.getMetricReader(), cardinalityLimits); + } + }); + } + + List viewModels = model.getViews(); + if (viewModels != null) { + viewModels.forEach(viewModel -> { + ViewSelectorModel selector = requireNonNull(viewModel.getSelector(), "view selector"); + ViewStreamModel stream = requireNonNull(viewModel.getStream(), "view stream"); + builder.registerView( + InstrumentSelectorFactory.getInstance().create(selector, context), + ViewFactory.getInstance().create(stream, context)); + }); + } + + ExperimentalMeterConfiguratorModel meterConfiguratorModel = + MeterProviderModelAccessor.getMeterConfigurator(model); + if (meterConfiguratorModel != null) { + ExperimentalMeterConfigModel defaultConfigModel = meterConfiguratorModel.getDefaultConfig(); + ScopeConfiguratorBuilder configuratorBuilder = ScopeConfigurator.builder(); + if (defaultConfigModel != null) { + configuratorBuilder.setDefault( + MeterConfigFactory.INSTANCE.create(defaultConfigModel, context)); + } + List meterMatcherAndConfigs = + meterConfiguratorModel.getMeters(); + if (meterMatcherAndConfigs != null) { + for (ExperimentalMeterMatcherAndConfigModel meterMatcherAndConfig : + meterMatcherAndConfigs) { + String name = requireNonNull(meterMatcherAndConfig.getName(), "meter matcher name"); + ExperimentalMeterConfigModel config = meterMatcherAndConfig.getConfig(); + if (name == null || config == null) { + continue; + } + configuratorBuilder.addCondition( + ScopeConfiguratorBuilder.nameMatchesGlob(name), + MeterConfigFactory.INSTANCE.create(config, context)); + } + } + SdkMeterProviderUtil.setMeterConfigurator(builder, configuratorBuilder.build()); + } + + ExemplarFilterModel exemplarFilterModel = model.getExemplarFilter(); + if (exemplarFilterModel != null) { + builder.setExemplarFilter( + ExemplarFilterFactory.getInstance().create(exemplarFilterModel, context)); + } + + return builder; + } + + private static class MeterConfigFactory + implements Factory { + + private static final MeterConfigFactory INSTANCE = new MeterConfigFactory(); + + @Override + public MeterConfig create( + ExperimentalMeterConfigModel model, DeclarativeConfigContext context) { + if (model.getEnabled() != null && !model.getEnabled()) { + return MeterConfig.disabled(); + } + return MeterConfig.defaultConfig(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactory.java new file mode 100644 index 00000000000..2bd715710a7 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactory.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import io.opentelemetry.sdk.metrics.export.MetricExporter; + +final class MetricExporterFactory implements Factory { + private static final MetricExporterFactory INSTANCE = new MetricExporterFactory(); + + private MetricExporterFactory() {} + + static MetricExporterFactory getInstance() { + return INSTANCE; + } + + @Override + public MetricExporter create(PushMetricExporterModel model, DeclarativeConfigContext context) { + ConfigKeyValue metricExporterKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "metric exporter"); + MetricExporter exporter = context.loadComponent(MetricExporter.class, metricExporterKeyValue); + for (DeclarativeConfigurationBuilder.Customizer customizer : + context.getBuilder().getMetricExporterCustomizers()) { + exporter = + customizer.maybeCustomize( + exporter, metricExporterKeyValue.getKey(), metricExporterKeyValue.getValue()); + } + return exporter; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderAndCardinalityLimits.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderAndCardinalityLimits.java new file mode 100644 index 00000000000..c5ee4e810cb --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderAndCardinalityLimits.java @@ -0,0 +1,25 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import javax.annotation.Nullable; + +@AutoValue +abstract class MetricReaderAndCardinalityLimits { + + static MetricReaderAndCardinalityLimits create( + MetricReader metricReader, @Nullable CardinalityLimitSelector cardinalityLimitSelector) { + return new AutoValue_MetricReaderAndCardinalityLimits(metricReader, cardinalityLimitSelector); + } + + abstract MetricReader getMetricReader(); + + @Nullable + abstract CardinalityLimitSelector getCardinalityLimitsSelector(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderFactory.java new file mode 100644 index 00000000000..cf5875a6b5f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderFactory.java @@ -0,0 +1,111 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigUtil.requireNonNull; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PeriodicMetricReaderModelAccessor; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReaderBuilder; +import java.time.Duration; + +final class MetricReaderFactory + implements Factory { + + private static final MetricReaderFactory INSTANCE = new MetricReaderFactory(); + + private MetricReaderFactory() {} + + static MetricReaderFactory getInstance() { + return INSTANCE; + } + + @Override + public MetricReaderAndCardinalityLimits create( + MetricReaderModel model, DeclarativeConfigContext context) { + FileConfigUtil.validateSingleKeyValue(context, model, "metric reader"); + + if (model.getPeriodic() != null) { + return PeriodicMetricReaderFactory.INSTANCE.create(model.getPeriodic(), context); + } + if (model.getPull() != null) { + return PullMetricReaderFactory.INSTANCE.create(model.getPull(), context); + } + + throw new DeclarativeConfigException("reader must be set"); + } + + private static class PeriodicMetricReaderFactory + implements Factory { + + private static final PeriodicMetricReaderFactory INSTANCE = new PeriodicMetricReaderFactory(); + + private PeriodicMetricReaderFactory() {} + + @Override + public MetricReaderAndCardinalityLimits create( + PeriodicMetricReaderModel model, DeclarativeConfigContext context) { + PushMetricExporterModel exporterModel = + requireNonNull(model.getExporter(), "periodic metric reader exporter"); + MetricExporter metricExporter = + MetricExporterFactory.getInstance().create(exporterModel, context); + + PeriodicMetricReaderBuilder builder = PeriodicMetricReader.builder(metricExporter); + + context.setInternalTelemetry(unused -> {}, builder::setInternalTelemetryVersion); + + if (model.getInterval() != null) { + builder.setInterval(Duration.ofMillis(model.getInterval())); + } + CardinalityLimitSelector cardinalityLimitSelector = null; + if (model.getCardinalityLimits() != null) { + cardinalityLimitSelector = + CardinalityLimitsFactory.getInstance().create(model.getCardinalityLimits(), context); + } + Integer maxExportBatchSize = PeriodicMetricReaderModelAccessor.getMaxExportBatchSize(model); + if (maxExportBatchSize != null) { + builder.setMaxExportBatchSize(maxExportBatchSize); + } + + MetricReader reader = context.addCloseable(builder.build()); + return MetricReaderAndCardinalityLimits.create(reader, cardinalityLimitSelector); + } + } + + private static class PullMetricReaderFactory + implements Factory { + + private static final PullMetricReaderFactory INSTANCE = new PullMetricReaderFactory(); + + private PullMetricReaderFactory() {} + + @Override + public MetricReaderAndCardinalityLimits create( + PullMetricReaderModel model, DeclarativeConfigContext context) { + PullMetricExporterModel exporterModel = + requireNonNull(model.getExporter(), "pull metric reader exporter"); + CardinalityLimitSelector cardinalityLimitSelector = null; + if (model.getCardinalityLimits() != null) { + cardinalityLimitSelector = + CardinalityLimitsFactory.getInstance().create(model.getCardinalityLimits(), context); + } + + ConfigKeyValue metricReaderKeyValue = + FileConfigUtil.validateSingleKeyValue(context, exporterModel, "metric reader"); + MetricReader metricReader = context.loadComponent(MetricReader.class, metricReaderKeyValue); + return MetricReaderAndCardinalityLimits.create(metricReader, cardinalityLimitSelector); + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactory.java new file mode 100644 index 00000000000..bdfa6bbaa55 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactory.java @@ -0,0 +1,125 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.OpenTelemetrySdkBuilder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.internal.OpenTelemetrySdkBuilderUtil; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Objects; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +final class OpenTelemetryConfigurationFactory + implements Factory { + + private static final Logger logger = + Logger.getLogger(OpenTelemetryConfigurationFactory.class.getName()); + private static final Pattern SUPPORTED_FILE_FORMATS = + Pattern.compile("^(0.4)|(1.\\d+(-rc.\\d+)?)$"); + private static final String EXPECTED_FILE_FORMAT = "1.2"; + + private static final OpenTelemetryConfigurationFactory INSTANCE = + new OpenTelemetryConfigurationFactory(); + + private OpenTelemetryConfigurationFactory() {} + + static OpenTelemetryConfigurationFactory getInstance() { + return INSTANCE; + } + + @Override + public DeclarativeConfigResult create( + OpenTelemetryConfigurationModel model, DeclarativeConfigContext context) { + DeclarativeConfigProperties modelProperties = + DeclarativeConfiguration.toConfigProperties(model, context.getDelegateComponentLoader()); + SdkConfigProvider sdkConfigProvider = SdkConfigProvider.create(modelProperties); + context.setConfigProvider(sdkConfigProvider); + OpenTelemetrySdkBuilder builder = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder(), sdkConfigProvider); + String fileFormat = model.getFileFormat(); + if (fileFormat == null || !SUPPORTED_FILE_FORMATS.matcher(fileFormat).matches()) { + throw new DeclarativeConfigException( + "Unsupported file format '" + fileFormat + "'. Supported formats include 0.4, 1.*"); + } + if (!EXPECTED_FILE_FORMAT.equals(fileFormat)) { + logger.warning( + "Configuration file_format '" + + fileFormat + + "' does not exactly match expected version '" + + EXPECTED_FILE_FORMAT + + "'. This may result in unexpected behavior for experimental properties."); + } + + if (Objects.equals(true, model.getDisabled())) { + return new DeclarativeConfigResult( + (ExtendedOpenTelemetrySdk) builder.build(), Resource.getDefault()); + } + + if (model.getPropagator() != null) { + builder.setPropagators( + PropagatorFactory.getInstance().create(model.getPropagator(), context)); + } + + Resource resource = Resource.getDefault(); + if (model.getResource() != null) { + resource = ResourceFactory.getInstance().create(model.getResource(), context); + } + + MeterProviderModel meterProviderModel = model.getMeterProvider(); + if (meterProviderModel == null) { + meterProviderModel = new MeterProviderModel(); + } + SdkMeterProvider meterProvider = + MeterProviderFactory.getInstance() + .create(meterProviderModel, context) + .setResource(resource) + .build(); + context.setMeterProvider(meterProvider); + builder.setMeterProvider(context.addCloseable(meterProvider)); + + LoggerProviderModel loggerProviderModel = model.getLoggerProvider(); + if (loggerProviderModel == null) { + loggerProviderModel = new LoggerProviderModel(); + } + builder.setLoggerProvider( + context.addCloseable( + LoggerProviderFactory.getInstance() + .create( + LoggerProviderAndAttributeLimits.create( + model.getAttributeLimits(), loggerProviderModel), + context) + .setResource(resource) + .build())); + + TracerProviderModel tracerProviderModel = model.getTracerProvider(); + if (tracerProviderModel == null) { + tracerProviderModel = new TracerProviderModel(); + } + builder.setTracerProvider( + context.addCloseable( + TracerProviderFactory.getInstance() + .create( + TracerProviderAndAttributeLimits.create( + model.getAttributeLimits(), tracerProviderModel), + context) + .setResource(resource) + .build())); + + return new DeclarativeConfigResult( + (ExtendedOpenTelemetrySdk) context.addCloseable(builder.build()), resource); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java new file mode 100644 index 00000000000..aecfa1b7624 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactory.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +final class PropagatorFactory implements Factory { + + private static final PropagatorFactory INSTANCE = new PropagatorFactory(); + + private PropagatorFactory() {} + + static PropagatorFactory getInstance() { + return INSTANCE; + } + + @Override + public ContextPropagators create(PropagatorModel model, DeclarativeConfigContext context) { + List textMapPropagatorModels = model.getComposite(); + Set propagatorNames = new HashSet<>(); + List textMapPropagators = new ArrayList<>(); + if (textMapPropagatorModels != null) { + textMapPropagatorModels.forEach(textMapPropagatorModel -> { + TextMapPropagatorAndName propagatorAndName = + TextMapPropagatorFactory.getInstance().create(textMapPropagatorModel, context); + textMapPropagators.add(propagatorAndName.getTextMapPropagator()); + propagatorNames.add(propagatorAndName.getName()); + }); + } + + String compositeList = model.getCompositeList(); + if (compositeList != null) { + List propagatorNamesList = + // Process string list same as we process OTEL_PROPAGATORS, trimming and filtering empty + // and 'none' + Stream.of(compositeList.split(",")) + .map(String::trim) + .filter(s -> !s.isEmpty()) + .filter(s -> !s.equals("none")) + .collect(Collectors.toList()); + for (String propagatorName : propagatorNamesList) { + // Only add entries which weren't already previously added + if (propagatorNames.add(propagatorName)) { + textMapPropagators.add( + TextMapPropagatorFactory.getPropagator( + context, + ConfigKeyValue.of(propagatorName, DeclarativeConfigProperties.empty())) + .getTextMapPropagator()); + } + } + } + + return ContextPropagators.create(TextMapPropagator.composite(textMapPropagators)); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceDetectorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceDetectorFactory.java new file mode 100644 index 00000000000..718c997ffa9 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceDetectorFactory.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectorModel; +import io.opentelemetry.sdk.resources.Resource; + +final class ResourceDetectorFactory + implements Factory { + private static final ResourceDetectorFactory INSTANCE = new ResourceDetectorFactory(); + + private ResourceDetectorFactory() {} + + static ResourceDetectorFactory getInstance() { + return INSTANCE; + } + + @Override + public Resource create( + ExperimentalResourceDetectorModel model, DeclarativeConfigContext context) { + ConfigKeyValue detectorKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "resource detector"); + return context.loadComponent(Resource.class, detectorKeyValue); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactory.java new file mode 100644 index 00000000000..a0102986229 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactory.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.EnvironmentResource.ATTRIBUTE_PROPERTY; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.EnvironmentResource.createEnvironmentResource; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectionModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ResourceModelAccessor; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import java.util.Collections; +import java.util.List; +import java.util.function.Predicate; + +final class ResourceFactory implements Factory { + + private static final ResourceFactory INSTANCE = new ResourceFactory(); + + private ResourceFactory() {} + + static ResourceFactory getInstance() { + return INSTANCE; + } + + @Override + public Resource create(ResourceModel model, DeclarativeConfigContext context) { + ResourceBuilder builder = Resource.getDefault().toBuilder(); + + ExperimentalResourceDetectionModel detectionModel = ResourceModelAccessor.getDetection(model); + if (detectionModel != null) { + ResourceBuilder detectedResourceBuilder = Resource.builder(); + + List detectorModels = detectionModel.getDetectors(); + if (detectorModels != null) { + for (ExperimentalResourceDetectorModel detectorModel : detectorModels) { + detectedResourceBuilder.putAll( + ResourceDetectorFactory.getInstance().create(detectorModel, context)); + } + } + + IncludeExcludeModel attributesIncludeExcludeModel = detectionModel.getAttributes(); + Predicate detectorAttributeFilter = + attributesIncludeExcludeModel == null + ? ResourceFactory::matchAll + : IncludeExcludeFactory.getInstance().create(attributesIncludeExcludeModel, context); + Resource filteredDetectedResource = + detectedResourceBuilder + .removeIf(attributeKey -> !detectorAttributeFilter.test(attributeKey.getKey())) + .build(); + + builder.putAll(filteredDetectedResource); + } + + String attributeList = model.getAttributesList(); + if (attributeList != null) { + builder.putAll( + createEnvironmentResource( + DefaultConfigProperties.createFromMap( + Collections.singletonMap(ATTRIBUTE_PROPERTY, attributeList)))); + } + + List attributeNameValueModel = model.getAttributes(); + if (attributeNameValueModel != null) { + builder + .putAll(AttributeListFactory.getInstance().create(attributeNameValueModel, context)) + .build(); + } + + if (model.getSchemaUrl() != null) { + builder.setSchemaUrl(model.getSchemaUrl()); + } + + return builder.build(); + } + + private static boolean matchAll(String attributeKey) { + return true; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SamplerFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SamplerFactory.java new file mode 100644 index 00000000000..8bb8868b173 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SamplerFactory.java @@ -0,0 +1,120 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysRecordSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TraceIdRatioBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalProbabilitySamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.SamplerModelAccessor; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.AlwaysRecordSampler; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.ComposableSampler; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.CompositeSampler; +import io.opentelemetry.sdk.trace.samplers.ParentBasedSamplerBuilder; +import io.opentelemetry.sdk.trace.samplers.Sampler; + +final class SamplerFactory implements Factory { + + private static final SamplerFactory INSTANCE = new SamplerFactory(); + + private SamplerFactory() {} + + static SamplerFactory getInstance() { + return INSTANCE; + } + + @Override + public Sampler create(SamplerModel model, DeclarativeConfigContext context) { + // We don't use the variable till later but call validate first to confirm there are not + // multiple samplers. + ConfigKeyValue samplerKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "sampler"); + + if (model.getAlwaysOn() != null) { + return Sampler.alwaysOn(); + } + if (model.getAlwaysOff() != null) { + return Sampler.alwaysOff(); + } + if (model.getTraceIdRatioBased() != null) { + return createTraceIdRatioBasedSampler(model.getTraceIdRatioBased()); + } + if (model.getParentBased() != null) { + return createParedBasedSampler(model.getParentBased(), context); + } + if (model.getAlwaysRecord() != null) { + return createAlwaysRecordSampler(model.getAlwaysRecord(), context); + } + ExperimentalProbabilitySamplerModel probabilityDevelopment = + SamplerModelAccessor.getProbability(model); + if (probabilityDevelopment != null) { + return createProbabilitySampler(probabilityDevelopment); + } + ExperimentalComposableSamplerModel compositeDevelopment = + SamplerModelAccessor.getComposite(model); + if (compositeDevelopment != null) { + return CompositeSampler.wrap( + ComposableSamplerFactory.getInstance().create(compositeDevelopment, context)); + } + + return context.loadComponent(Sampler.class, samplerKeyValue); + } + + private static Sampler createTraceIdRatioBasedSampler(TraceIdRatioBasedSamplerModel model) { + Double ratio = model.getRatio(); + if (ratio == null) { + ratio = 1.0d; + } + return Sampler.traceIdRatioBased(ratio); + } + + private static Sampler createParedBasedSampler( + ParentBasedSamplerModel parentBasedModel, DeclarativeConfigContext context) { + Sampler root = + parentBasedModel.getRoot() == null + ? Sampler.alwaysOn() + : INSTANCE.create(parentBasedModel.getRoot(), context); + ParentBasedSamplerBuilder builder = Sampler.parentBasedBuilder(root); + if (parentBasedModel.getRemoteParentSampled() != null) { + Sampler sampler = INSTANCE.create(parentBasedModel.getRemoteParentSampled(), context); + builder.setRemoteParentSampled(sampler); + } + if (parentBasedModel.getRemoteParentNotSampled() != null) { + Sampler sampler = INSTANCE.create(parentBasedModel.getRemoteParentNotSampled(), context); + builder.setRemoteParentNotSampled(sampler); + } + if (parentBasedModel.getLocalParentSampled() != null) { + Sampler sampler = INSTANCE.create(parentBasedModel.getLocalParentSampled(), context); + builder.setLocalParentSampled(sampler); + } + if (parentBasedModel.getLocalParentNotSampled() != null) { + Sampler sampler = INSTANCE.create(parentBasedModel.getLocalParentNotSampled(), context); + builder.setLocalParentNotSampled(sampler); + } + return builder.build(); + } + + private static Sampler createAlwaysRecordSampler( + AlwaysRecordSamplerModel alwaysRecordModel, DeclarativeConfigContext context) { + SamplerModel rootModel = alwaysRecordModel.getRoot(); + if (rootModel == null) { + throw new DeclarativeConfigException("always_record sampler .root is required"); + } + return AlwaysRecordSampler.create(INSTANCE.create(rootModel, context)); + } + + private static Sampler createProbabilitySampler( + ExperimentalProbabilitySamplerModel probabilityModel) { + Double ratio = probabilityModel.getRatio(); + if (ratio == null) { + ratio = 1.0d; + } + return CompositeSampler.wrap(ComposableSampler.probability(ratio)); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ServiceResourceDetector.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ServiceResourceDetector.java new file mode 100644 index 00000000000..1688557476d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ServiceResourceDetector.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DefaultConfigProperties; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Collections; +import java.util.UUID; + +/** Detects the service name and generates a service instance ID for declarative configuration. */ +public class ServiceResourceDetector implements ComponentProvider { + + // multiple calls to this resource provider should return the same value + private static final String RANDOM_SERVICE_INSTANCE_ID = UUID.randomUUID().toString(); + + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "service"; + } + + @Override + public Resource create(DeclarativeConfigProperties config) { + ResourceBuilder builder = Resource.builder(); + + ConfigProperties properties = + DefaultConfigProperties.create(Collections.emptyMap(), config.getComponentLoader()); + String serviceName = properties.getString("otel.service.name"); + if (serviceName != null) { + Entity serviceEntity = + Entity.builder( + SemConvConstants.SERVICE_TYPE, + Attributes.of(SemConvConstants.SERVICE_NAME, serviceName)) + .setSchemaUrl(SemConvConstants.SCHEMA_URL_V1_40_0) + .build(); + EntityUtil.addEntity(builder, serviceEntity); + } + Entity serviceInstanceEntity = + Entity.builder( + SemConvConstants.SERVICE_INSTANCE_TYPE, + Attributes.of(SemConvConstants.SERVICE_INSTANCE_ID, RANDOM_SERVICE_INSTANCE_ID)) + .setSchemaUrl(SemConvConstants.SCHEMA_URL_V1_40_0) + .build(); + EntityUtil.addEntity(builder, serviceInstanceEntity); + + return builder.build(); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactory.java new file mode 100644 index 00000000000..c1e6c721186 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactory.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.trace.export.SpanExporter; + +final class SpanExporterFactory implements Factory { + + private static final SpanExporterFactory INSTANCE = new SpanExporterFactory(); + + private SpanExporterFactory() {} + + static SpanExporterFactory getInstance() { + return INSTANCE; + } + + @Override + public SpanExporter create(SpanExporterModel model, DeclarativeConfigContext context) { + ConfigKeyValue spanExporterKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "span exporter"); + SpanExporter exporter = context.loadComponent(SpanExporter.class, spanExporterKeyValue); + for (DeclarativeConfigurationBuilder.Customizer customizer : + context.getBuilder().getSpanExporterCustomizers()) { + exporter = + customizer.maybeCustomize( + exporter, spanExporterKeyValue.getKey(), spanExporterKeyValue.getValue()); + } + return exporter; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsAndAttributeLimits.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsAndAttributeLimits.java new file mode 100644 index 00000000000..865bb2e54a8 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsAndAttributeLimits.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel; +import javax.annotation.Nullable; + +@AutoValue +abstract class SpanLimitsAndAttributeLimits { + + static SpanLimitsAndAttributeLimits create( + @Nullable AttributeLimitsModel attributeLimits, @Nullable SpanLimitsModel spanLimits) { + return new AutoValue_SpanLimitsAndAttributeLimits(attributeLimits, spanLimits); + } + + @Nullable + abstract AttributeLimitsModel getAttributeLimits(); + + @Nullable + abstract SpanLimitsModel getSpanLimits(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsFactory.java new file mode 100644 index 00000000000..38050eaf6b0 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsFactory.java @@ -0,0 +1,61 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel; +import io.opentelemetry.sdk.trace.SpanLimits; +import io.opentelemetry.sdk.trace.SpanLimitsBuilder; + +final class SpanLimitsFactory implements Factory { + + private static final SpanLimitsFactory INSTANCE = new SpanLimitsFactory(); + + private SpanLimitsFactory() {} + + static SpanLimitsFactory getInstance() { + return INSTANCE; + } + + @Override + public SpanLimits create(SpanLimitsAndAttributeLimits model, DeclarativeConfigContext context) { + SpanLimitsBuilder builder = SpanLimits.builder(); + + AttributeLimitsModel attributeLimitsModel = model.getAttributeLimits(); + if (attributeLimitsModel != null) { + if (attributeLimitsModel.getAttributeCountLimit() != null) { + builder.setMaxNumberOfAttributes(attributeLimitsModel.getAttributeCountLimit()); + } + if (attributeLimitsModel.getAttributeValueLengthLimit() != null) { + builder.setMaxAttributeValueLength(attributeLimitsModel.getAttributeValueLengthLimit()); + } + } + + SpanLimitsModel spanLimitsModel = model.getSpanLimits(); + if (spanLimitsModel != null) { + if (spanLimitsModel.getAttributeCountLimit() != null) { + builder.setMaxNumberOfAttributes(spanLimitsModel.getAttributeCountLimit()); + } + if (spanLimitsModel.getAttributeValueLengthLimit() != null) { + builder.setMaxAttributeValueLength(spanLimitsModel.getAttributeValueLengthLimit()); + } + if (spanLimitsModel.getEventCountLimit() != null) { + builder.setMaxNumberOfEvents(spanLimitsModel.getEventCountLimit()); + } + if (spanLimitsModel.getLinkCountLimit() != null) { + builder.setMaxNumberOfLinks(spanLimitsModel.getLinkCountLimit()); + } + if (spanLimitsModel.getEventAttributeCountLimit() != null) { + builder.setMaxNumberOfAttributesPerEvent(spanLimitsModel.getEventAttributeCountLimit()); + } + if (spanLimitsModel.getLinkAttributeCountLimit() != null) { + builder.setMaxNumberOfAttributesPerLink(spanLimitsModel.getLinkAttributeCountLimit()); + } + } + + return builder.build(); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanProcessorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanProcessorFactory.java new file mode 100644 index 00000000000..aeb1ba12103 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanProcessorFactory.java @@ -0,0 +1,79 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.trace.SpanProcessor; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessorBuilder; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessorBuilder; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.time.Duration; + +final class SpanProcessorFactory implements Factory { + + private static final SpanProcessorFactory INSTANCE = new SpanProcessorFactory(); + + private SpanProcessorFactory() {} + + static SpanProcessorFactory getInstance() { + return INSTANCE; + } + + @Override + public SpanProcessor create(SpanProcessorModel model, DeclarativeConfigContext context) { + // We don't use the variable till later but call validate first to confirm there are not + // multiple samplers. + ConfigKeyValue processorKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "span processor"); + + if (model.getBatch() != null) { + return createBatchLogRecordProcessor(model.getBatch(), context); + } + if (model.getSimple() != null) { + return createSimpleLogRecordProcessor(model.getSimple(), context); + } + + return context.loadComponent(SpanProcessor.class, processorKeyValue); + } + + private static SpanProcessor createBatchLogRecordProcessor( + BatchSpanProcessorModel batchModel, DeclarativeConfigContext context) { + SpanExporterModel exporterModel = + FileConfigUtil.requireNonNull(batchModel.getExporter(), "batch span processor exporter"); + SpanExporter spanExporter = SpanExporterFactory.getInstance().create(exporterModel, context); + BatchSpanProcessorBuilder builder = BatchSpanProcessor.builder(spanExporter); + if (batchModel.getExportTimeout() != null) { + builder.setExporterTimeout(Duration.ofMillis(batchModel.getExportTimeout())); + } + if (batchModel.getMaxExportBatchSize() != null) { + builder.setMaxExportBatchSize(batchModel.getMaxExportBatchSize()); + } + if (batchModel.getMaxQueueSize() != null) { + builder.setMaxQueueSize(batchModel.getMaxQueueSize()); + } + if (batchModel.getScheduleDelay() != null) { + builder.setScheduleDelay(Duration.ofMillis(batchModel.getScheduleDelay())); + } + context.setInternalTelemetry(builder::setMeterProvider, builder::setInternalTelemetryVersion); + + return context.addCloseable(builder.build()); + } + + private static SpanProcessor createSimpleLogRecordProcessor( + SimpleSpanProcessorModel simpleModel, DeclarativeConfigContext context) { + SpanExporterModel exporterModel = + FileConfigUtil.requireNonNull(simpleModel.getExporter(), "simple span processor exporter"); + SpanExporter spanExporter = SpanExporterFactory.getInstance().create(exporterModel, context); + SimpleSpanProcessorBuilder builder = SimpleSpanProcessor.builder(spanExporter); + context.setInternalTelemetry(builder::setMeterProvider); + return context.addCloseable(builder.build()); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TextMapPropagatorAndName.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TextMapPropagatorAndName.java new file mode 100644 index 00000000000..d32c1ee6d20 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TextMapPropagatorAndName.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.context.propagation.TextMapPropagator; + +@AutoValue +abstract class TextMapPropagatorAndName { + + static TextMapPropagatorAndName create(TextMapPropagator textMapPropagator, String name) { + return new AutoValue_TextMapPropagatorAndName(textMapPropagator, name); + } + + abstract TextMapPropagator getTextMapPropagator(); + + abstract String getName(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TextMapPropagatorFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TextMapPropagatorFactory.java new file mode 100644 index 00000000000..e580993e6f4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TextMapPropagatorFactory.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel; + +final class TextMapPropagatorFactory + implements Factory { + + private static final TextMapPropagatorFactory INSTANCE = new TextMapPropagatorFactory(); + + private TextMapPropagatorFactory() {} + + static TextMapPropagatorFactory getInstance() { + return INSTANCE; + } + + @Override + public TextMapPropagatorAndName create( + TextMapPropagatorModel model, DeclarativeConfigContext context) { + ConfigKeyValue propagatorKeyValue = + FileConfigUtil.validateSingleKeyValue(context, model, "propagator"); + return getPropagator(context, propagatorKeyValue); + } + + static TextMapPropagatorAndName getPropagator( + DeclarativeConfigContext context, ConfigKeyValue configKeyValue) { + String name = configKeyValue.getKey(); + + TextMapPropagator textMapPropagator; + if (name.equals("tracecontext")) { + textMapPropagator = W3CTraceContextPropagator.getInstance(); + } else if (name.equals("baggage")) { + textMapPropagator = W3CBaggagePropagator.getInstance(); + } else { + textMapPropagator = context.loadComponent(TextMapPropagator.class, configKeyValue); + } + return TextMapPropagatorAndName.create(textMapPropagator, name); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderAndAttributeLimits.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderAndAttributeLimits.java new file mode 100644 index 00000000000..9bac7952176 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderAndAttributeLimits.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import javax.annotation.Nullable; + +@AutoValue +abstract class TracerProviderAndAttributeLimits { + + static TracerProviderAndAttributeLimits create( + @Nullable AttributeLimitsModel attributeLimits, + @Nullable TracerProviderModel tracerProvider) { + return new AutoValue_TracerProviderAndAttributeLimits(attributeLimits, tracerProvider); + } + + @Nullable + abstract AttributeLimitsModel getAttributeLimits(); + + @Nullable + abstract TracerProviderModel getTracerProvider(); +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java new file mode 100644 index 00000000000..a51d09c6b37 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactory.java @@ -0,0 +1,117 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigUtil.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalTracerConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalTracerConfiguratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalTracerMatcherAndConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.TracerProviderModelAccessor; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.SpanLimits; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.internal.TracerConfig; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.util.List; + +final class TracerProviderFactory + implements Factory { + + private static final TracerProviderFactory INSTANCE = new TracerProviderFactory(); + + private TracerProviderFactory() {} + + static TracerProviderFactory getInstance() { + return INSTANCE; + } + + @Override + public SdkTracerProviderBuilder create( + TracerProviderAndAttributeLimits model, DeclarativeConfigContext context) { + SdkTracerProviderBuilder builder = SdkTracerProvider.builder(); + TracerProviderModel tracerProviderModel = model.getTracerProvider(); + if (tracerProviderModel == null) { + return builder; + } + + context.setInternalTelemetry(builder::setMeterProvider); + + SpanLimits spanLimits = + SpanLimitsFactory.getInstance() + .create( + SpanLimitsAndAttributeLimits.create( + model.getAttributeLimits(), tracerProviderModel.getLimits()), + context); + builder.setSpanLimits(spanLimits); + + if (tracerProviderModel.getSampler() != null) { + Sampler sampler = + SamplerFactory.getInstance().create(tracerProviderModel.getSampler(), context); + builder.setSampler(sampler); + } + + List processors = tracerProviderModel.getProcessors(); + if (processors != null) { + processors.forEach(processor -> + builder.addSpanProcessor(SpanProcessorFactory.getInstance().create(processor, context))); + } + + if (tracerProviderModel.getIdGenerator() != null) { + builder.setIdGenerator( + IdGeneratorFactory.getInstance().create(tracerProviderModel.getIdGenerator(), context)); + } + + ExperimentalTracerConfiguratorModel tracerConfiguratorModel = + TracerProviderModelAccessor.getTracerConfigurator(tracerProviderModel); + if (tracerConfiguratorModel != null) { + ExperimentalTracerConfigModel defaultConfigModel = tracerConfiguratorModel.getDefaultConfig(); + ScopeConfiguratorBuilder configuratorBuilder = ScopeConfigurator.builder(); + if (defaultConfigModel != null) { + configuratorBuilder.setDefault( + TracerConfigFactory.INSTANCE.create(defaultConfigModel, context)); + } + List tracerMatcherAndConfigs = + tracerConfiguratorModel.getTracers(); + if (tracerMatcherAndConfigs != null) { + for (ExperimentalTracerMatcherAndConfigModel tracerMatcherAndConfig : + tracerMatcherAndConfigs) { + String name = requireNonNull(tracerMatcherAndConfig.getName(), "tracer matcher name"); + ExperimentalTracerConfigModel config = tracerMatcherAndConfig.getConfig(); + if (name == null || config == null) { + continue; + } + configuratorBuilder.addCondition( + ScopeConfiguratorBuilder.nameMatchesGlob(name), + TracerConfigFactory.INSTANCE.create(config, context)); + } + } + SdkTracerProviderUtil.setTracerConfigurator(builder, configuratorBuilder.build()); + } + + return builder; + } + + private static class TracerConfigFactory + implements Factory { + + private static final TracerConfigFactory INSTANCE = new TracerConfigFactory(); + + @Override + public TracerConfig create( + ExperimentalTracerConfigModel model, DeclarativeConfigContext context) { + if (model.getEnabled() != null && !model.getEnabled()) { + return TracerConfig.disabled(); + } + return TracerConfig.defaultConfig(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ViewFactory.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ViewFactory.java new file mode 100644 index 00000000000..32185c1990a --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ViewFactory.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.ViewBuilder; + +final class ViewFactory implements Factory { + + private static final ViewFactory INSTANCE = new ViewFactory(); + + private ViewFactory() {} + + static ViewFactory getInstance() { + return INSTANCE; + } + + @Override + public View create(ViewStreamModel model, DeclarativeConfigContext context) { + ViewBuilder builder = View.builder(); + if (model.getName() != null) { + builder.setName(model.getName()); + } + if (model.getDescription() != null) { + builder.setDescription(model.getDescription()); + } + IncludeExcludeModel attributeKeys = model.getAttributeKeys(); + if (attributeKeys != null) { + builder.setAttributeFilter( + IncludeExcludeFactory.getInstance().create(attributeKeys, context)); + } + if (model.getAggregation() != null) { + builder.setAggregation( + AggregationFactory.getInstance().create(model.getAggregation(), context)); + } + if (model.getAggregationCardinalityLimit() != null) { + builder.setCardinalityLimit(model.getAggregationCardinalityLimit()); + } + return builder.build(); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java new file mode 100644 index 00000000000..1d57b78886d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigProperties.java @@ -0,0 +1,374 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static java.util.stream.Collectors.joining; +import static java.util.stream.Collectors.toList; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.common.ComponentLoader; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.StringJoiner; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * Implementation of {@link DeclarativeConfigProperties} which uses a file configuration model as a + * source. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @see #getStructured(String) Accessing nested maps + * @see #getStructuredList(String) Accessing lists of maps + * @see DeclarativeConfiguration#toConfigProperties(Object, ComponentLoader) Converting + * configuration model to properties + */ +public final class YamlDeclarativeConfigProperties implements DeclarativeConfigProperties { + + private static final Logger logger = + Logger.getLogger(YamlDeclarativeConfigProperties.class.getName()); + + private static final Set> SUPPORTED_SCALAR_TYPES = + Collections.unmodifiableSet( + new LinkedHashSet<>( + Arrays.asList(String.class, Boolean.class, Long.class, Double.class))); + + /** Values are {@link #isPrimitive(Object)}, {@link List} of scalars. */ + private final Map simpleEntries; + + private final Map> listEntries; + private final Map mapEntries; + private final ComponentLoader componentLoader; + + private YamlDeclarativeConfigProperties( + Map simpleEntries, + Map> listEntries, + Map mapEntries, + ComponentLoader componentLoader) { + this.simpleEntries = simpleEntries; + this.listEntries = listEntries; + this.mapEntries = mapEntries; + this.componentLoader = componentLoader; + } + + /** + * Create a {@link YamlDeclarativeConfigProperties} from the {@code properties} map. + * + *

      {@code properties} is expected to have values which are scalars, lists of scalars, lists of + * maps, and maps. + * + * @see DeclarativeConfiguration#toConfigProperties(Object) + */ + @SuppressWarnings("unchecked") + public static YamlDeclarativeConfigProperties create( + Map properties, ComponentLoader componentLoader) { + Map simpleEntries = new LinkedHashMap<>(); + Map> listEntries = new LinkedHashMap<>(); + Map mapEntries = new LinkedHashMap<>(); + for (Map.Entry entry : properties.entrySet()) { + String key = entry.getKey(); + Object value = entry.getValue(); + if (isPrimitive(value) || value == null) { + simpleEntries.put(key, value); + continue; + } + if (isPrimitiveList(value)) { + simpleEntries.put(key, value); + continue; + } + if (isListOfMaps(value)) { + List list = + ((List>) value) + .stream() + .map(map -> YamlDeclarativeConfigProperties.create(map, componentLoader)) + .collect(toList()); + listEntries.put(key, list); + continue; + } + if (isMap(value)) { + YamlDeclarativeConfigProperties configProperties = + YamlDeclarativeConfigProperties.create((Map) value, componentLoader); + mapEntries.put(key, configProperties); + continue; + } + throw new DeclarativeConfigException( + "Unable to initialize ExtendedConfigProperties. Key \"" + + key + + "\" has unrecognized object type " + + value.getClass().getName()); + } + return new YamlDeclarativeConfigProperties( + simpleEntries, listEntries, mapEntries, componentLoader); + } + + private static boolean isPrimitiveList(Object object) { + if (object instanceof List) { + List list = (List) object; + return list.stream().allMatch(YamlDeclarativeConfigProperties::isPrimitive); + } + return false; + } + + private static boolean isPrimitive(Object object) { + return object instanceof String + || object instanceof Integer + || object instanceof Long + || object instanceof Float + || object instanceof Double + || object instanceof Boolean; + } + + private static boolean isListOfMaps(Object object) { + if (object instanceof List) { + List list = (List) object; + return list.stream() + .allMatch(entry -> + entry instanceof Map + && ((Map) entry).keySet().stream().allMatch(key -> key instanceof String)); + } + return false; + } + + private static boolean isMap(Object object) { + if (object instanceof Map) { + Map map = (Map) object; + return map.keySet().stream().allMatch(entry -> entry instanceof String); + } + return false; + } + + @Nullable + @Override + public String getString(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + return stringOrNull(simpleEntries.get(name), name); + } + + @Nullable + @Override + public Boolean getBoolean(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + return booleanOrNull(simpleEntries.get(name), name); + } + + @Nullable + @Override + public Integer getInt(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + Object value = simpleEntries.get(name); + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof Long) { + return ((Long) value).intValue(); + } + if (value != null) { + logTypeWarning(name, value, Integer.class); + } + return null; + } + + @Nullable + @Override + public Long getLong(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + return longOrNull(simpleEntries.get(name), name); + } + + @Nullable + @Override + public Double getDouble(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + return doubleOrNull(simpleEntries.get(name), name); + } + + @Override + public boolean isString(String name) { + Objects.requireNonNull(name, "name"); + return simpleEntries.get(name) instanceof String; + } + + @Override + public boolean isBoolean(String name) { + Objects.requireNonNull(name, "name"); + return simpleEntries.get(name) instanceof Boolean; + } + + @Override + public boolean isInt(String name) { + Objects.requireNonNull(name, "name"); + Object value = simpleEntries.get(name); + return value instanceof Integer || value instanceof Long; + } + + @Override + public boolean isLong(String name) { + Objects.requireNonNull(name, "name"); + Object value = simpleEntries.get(name); + return value instanceof Integer || value instanceof Long; + } + + @Override + public boolean isDouble(String name) { + Objects.requireNonNull(name, "name"); + Object value = simpleEntries.get(name); + return value instanceof Float || value instanceof Double; + } + + @Nullable + @Override + public List getScalarList(String name, Class scalarType) { + Objects.requireNonNull(name, "Null configuration property name"); + if (!SUPPORTED_SCALAR_TYPES.contains(scalarType)) { + throw new DeclarativeConfigException( + "Unsupported scalar type " + + scalarType.getName() + + ". Supported types include " + + SUPPORTED_SCALAR_TYPES.stream() + .map(Class::getName) + .collect(joining(",", "[", "]"))); + } + Object value = simpleEntries.get(name); + if (value instanceof List) { + List objectList = (List) value; + if (objectList.isEmpty()) { + return Collections.emptyList(); + } + List result = + objectList.stream() + .map(entry -> { + if (scalarType == String.class) { + return stringOrNull(entry, name); + } else if (scalarType == Boolean.class) { + return booleanOrNull(entry, name); + } else if (scalarType == Long.class) { + return longOrNull(entry, name); + } else if (scalarType == Double.class) { + return doubleOrNull(entry, name); + } + return null; + }) + .filter(Objects::nonNull) + .map(scalarType::cast) + .collect(toList()); + if (result.isEmpty()) { + return null; + } + return result; + } + return null; + } + + @Nullable + private static String stringOrNull(@Nullable Object value, String name) { + if (value instanceof String) { + return (String) value; + } + if (value != null) { + logTypeWarning(name, value, String.class); + } + return null; + } + + @Nullable + private static Boolean booleanOrNull(@Nullable Object value, String name) { + if (value instanceof Boolean) { + return (Boolean) value; + } + if (value != null) { + logTypeWarning(name, value, Boolean.class); + } + return null; + } + + @Nullable + private static Long longOrNull(@Nullable Object value, String name) { + if (value instanceof Integer) { + return ((Integer) value).longValue(); + } + if (value instanceof Long) { + return (Long) value; + } + if (value != null) { + logTypeWarning(name, value, Long.class); + } + return null; + } + + @Nullable + private static Double doubleOrNull(@Nullable Object value, String name) { + if (value instanceof Float) { + return ((Float) value).doubleValue(); + } + if (value instanceof Double) { + return (Double) value; + } + if (value != null) { + logTypeWarning(name, value, Double.class); + } + return null; + } + + @Nullable + @Override + public DeclarativeConfigProperties getStructured(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + return mapEntries.get(name); + } + + @Nullable + @Override + public List getStructuredList(String name) { + Objects.requireNonNull(name, "Null configuration property name"); + List value = listEntries.get(name); + if (value != null) { + return Collections.unmodifiableList(value); + } + return null; + } + + @Override + public Set getPropertyKeys() { + Set keys = new LinkedHashSet<>(); + keys.addAll(simpleEntries.keySet()); + keys.addAll(listEntries.keySet()); + keys.addAll(mapEntries.keySet()); + return Collections.unmodifiableSet(keys); + } + + @Override + public String toString() { + StringJoiner joiner = + new StringJoiner(", ", YamlDeclarativeConfigProperties.class.getSimpleName() + "{", "}"); + simpleEntries.forEach((key, value) -> joiner.add(key + "=" + value)); + listEntries.forEach((key, value) -> joiner.add(key + "=" + value)); + mapEntries.forEach((key, value) -> joiner.add(key + "=" + value)); + return joiner.toString(); + } + + /** Return the {@link ComponentLoader}. */ + @Override + public ComponentLoader getComponentLoader() { + return componentLoader; + } + + private static void logTypeWarning(String key, Object value, Class expected) { + logger.log( + Level.WARNING, + "Ignoring value for key [{0}] because it is {1} instead of {2}: {3}", + new Object[] {key, value.getClass().getSimpleName(), expected.getSimpleName(), value}); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigProviderLoader.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigProviderLoader.java new file mode 100644 index 00000000000..14cda43af5d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigProviderLoader.java @@ -0,0 +1,124 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.common.impl.ConfigUtil; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationMapper; +import io.opentelemetry.sdk.autoconfigure.spi.internal.DeclarativeConfigurationYamlParser; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class DeclarativeConfigProviderLoader { + + private static final Logger LOGGER = + Logger.getLogger(DeclarativeConfigProviderLoader.class.getName()); + + // TODO(jack-berg): Allow callers to supply the ComponentLoader used to resolve parser and mapper + // providers. + private static final ComponentLoader COMPONENT_LOADER = + ComponentLoader.forClassLoader(DeclarativeConfigProperties.class.getClassLoader()); + + private static final AtomicReference MAPPER = + new AtomicReference<>(); + private static final AtomicReference YAML_PARSER = + new AtomicReference<>(); + + private DeclarativeConfigProviderLoader() {} + + /** Returns the cached model mapper, resolving it on first use. */ + public static DeclarativeConfigurationMapper getMapper() { + return resolveProvider( + MAPPER, + DeclarativeConfigurationMapper.class, + COMPONENT_LOADER, + "No DeclarativeConfigurationMapper provider is available. Add the optional " + + "opentelemetry-sdk-extension-declarative-config-jackson2 artifact or register a " + + "custom mapper provider."); + } + + /** Returns the cached YAML parser, resolving it on first use. */ + public static DeclarativeConfigurationYamlParser getYamlParser() { + return resolveProvider( + YAML_PARSER, + DeclarativeConfigurationYamlParser.class, + COMPONENT_LOADER, + "No DeclarativeConfigurationYamlParser provider is available. Add the optional " + + "opentelemetry-sdk-extension-declarative-config-snakeyaml-engine2 artifact or register a " + + "custom parser provider."); + } + + static T resolveProvider( + AtomicReference providerRef, + Class spiClass, + ComponentLoader componentLoader, + String missingProviderMessage) { + T provider = providerRef.get(); + if (provider != null) { + return provider; + } + String configProperty = spiClass.getName(); + T candidate = + loadFirstOrConfigured( + spiClass, + missingProviderMessage, + configProperty, + componentLoader, + ConfigUtil.getString(configProperty, "")); + return providerRef.compareAndSet(null, candidate) + ? candidate + : requireNonNull(providerRef.get()); + } + + private static T loadFirstOrConfigured( + Class spiClass, + String missingProviderMessage, + String configProperty, + ComponentLoader componentLoader, + String configuredProvider) { + List providers = ComponentLoader.loadList(componentLoader, spiClass); + if (providers.isEmpty()) { + throw new DeclarativeConfigException(missingProviderMessage); + } + if (providers.size() == 1) { + return providers.get(0); + } + + if (configuredProvider.isEmpty()) { + if (LOGGER.isLoggable(Level.WARNING)) { + LOGGER.log( + Level.WARNING, + "Multiple {0} providers found. Please include only one, or specify preference " + + "setting {1} to the FQCN of the preferred provider.", + new Object[] {spiClass.getSimpleName(), configProperty}); + } + return providers.get(0); + } + + for (T provider : providers) { + if (provider.getClass().getName().equals(configuredProvider)) { + return provider; + } + } + throw new IllegalStateException( + "No " + + spiClass.getSimpleName() + + " matched configured " + + configProperty + + ": " + + configuredProvider); + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigurationMapperUtil.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigurationMapperUtil.java new file mode 100644 index 00000000000..5b4c449588a --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigurationMapperUtil.java @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class DeclarativeConfigurationMapperUtil { + + private DeclarativeConfigurationMapperUtil() {} + + /** + * Convert a value to an instance of {@code targetType} using the selected mapper. + * + * @param value the value to convert + * @param targetType the target type + * @param the target type + * @return the converted value + */ + public static T convert(Object value, Class targetType) { + try { + return DeclarativeConfigProviderLoader.getMapper().convert(value, targetType); + } catch (DeclarativeConfigException e) { + throw e; + } catch (RuntimeException e) { + throw new DeclarativeConfigException("Unable to convert value to " + targetType, e); + } + } + + /** + * Convert a model or parsed configuration value to a generic map using the selected mapper. + * + * @param value the value to convert + * @return the converted map, or null if the mapper returns null + */ + @Nullable + public static Map toMap(Object value) { + try { + return DeclarativeConfigProviderLoader.getMapper().toMap(value); + } catch (DeclarativeConfigException e) { + throw e; + } catch (RuntimeException e) { + throw new DeclarativeConfigException("Unable to convert value to a map", e); + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AggregationModel.java new file mode 100644 index 00000000000..0a2fa727af5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AggregationModel.java @@ -0,0 +1,311 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel.BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel.DEFAULT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel.DROP; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel.EXPLICIT_BUCKET_HISTOGRAM; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel.LAST_VALUE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel.SUM; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + DEFAULT, + DROP, + EXPLICIT_BUCKET_HISTOGRAM, + BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM, + LAST_VALUE, + SUM +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class AggregationModel { + + static final String DEFAULT = "default"; + static final String DROP = "drop"; + static final String EXPLICIT_BUCKET_HISTOGRAM = "explicit_bucket_histogram"; + static final String BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM = "base2_exponential_bucket_histogram"; + static final String LAST_VALUE = "last_value"; + static final String SUM = "sum"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(DEFAULT, DefaultAggregationModel.class); + STABLE_PROPERTIES.put(DROP, DropAggregationModel.class); + STABLE_PROPERTIES.put(EXPLICIT_BUCKET_HISTOGRAM, ExplicitBucketHistogramAggregationModel.class); + STABLE_PROPERTIES.put( + BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM, Base2ExponentialBucketHistogramAggregationModel.class); + STABLE_PROPERTIES.put(LAST_VALUE, LastValueAggregationModel.class); + STABLE_PROPERTIES.put(SUM, SumAggregationModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private DefaultAggregationModel _default; + @Nullable private DropAggregationModel drop; + @Nullable private ExplicitBucketHistogramAggregationModel explicitBucketHistogram; + @Nullable private Base2ExponentialBucketHistogramAggregationModel base2ExponentialBucketHistogram; + @Nullable private LastValueAggregationModel lastValue; + @Nullable private SumAggregationModel sum; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configures the stream to use the instrument kind to select an aggregation and advisory + * parameters to influence aggregation configuration parameters. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#default-aggregation + * for details. + * + *

      If omitted, ignore. + */ + @JsonProperty(DEFAULT) + @Nullable + public DefaultAggregationModel getDefault() { + if (_default == null) { + return ExtensionPropertyUtil.getGraduated( + DEFAULT, extensionProperties, DefaultAggregationModel.class); + } + return _default; + } + + @JsonProperty(DEFAULT) + public AggregationModel setDefault(DefaultAggregationModel _default) { + this._default = _default; + return this; + } + + /** + * Configures the stream to ignore/drop all instrument measurements. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#drop-aggregation + * for details. + * + *

      If omitted, ignore. + */ + @JsonProperty(DROP) + @Nullable + public DropAggregationModel getDrop() { + if (drop == null) { + return ExtensionPropertyUtil.getGraduated( + DROP, extensionProperties, DropAggregationModel.class); + } + return drop; + } + + @JsonProperty(DROP) + public AggregationModel setDrop(DropAggregationModel drop) { + this.drop = drop; + return this; + } + + /** + * Configures the stream to collect data for the histogram metric point using a set of explicit + * boundary values for histogram bucketing. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#explicit-bucket-histogram-aggregation + * for details + * + *

      If omitted, ignore. + */ + @JsonProperty(EXPLICIT_BUCKET_HISTOGRAM) + @Nullable + public ExplicitBucketHistogramAggregationModel getExplicitBucketHistogram() { + if (explicitBucketHistogram == null) { + return ExtensionPropertyUtil.getGraduated( + EXPLICIT_BUCKET_HISTOGRAM, + extensionProperties, + ExplicitBucketHistogramAggregationModel.class); + } + return explicitBucketHistogram; + } + + @JsonProperty(EXPLICIT_BUCKET_HISTOGRAM) + public AggregationModel setExplicitBucketHistogram( + ExplicitBucketHistogramAggregationModel explicitBucketHistogram) { + this.explicitBucketHistogram = explicitBucketHistogram; + return this; + } + + /** + * Configures the stream to collect data for the exponential histogram metric point, which uses a + * base-2 exponential formula to determine bucket boundaries and an integer scale parameter to + * control resolution. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#base2-exponential-bucket-histogram-aggregation + * for details. + * + *

      If omitted, ignore. + */ + @JsonProperty(BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM) + @Nullable + public Base2ExponentialBucketHistogramAggregationModel getBase2ExponentialBucketHistogram() { + if (base2ExponentialBucketHistogram == null) { + return ExtensionPropertyUtil.getGraduated( + BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM, + extensionProperties, + Base2ExponentialBucketHistogramAggregationModel.class); + } + return base2ExponentialBucketHistogram; + } + + @JsonProperty(BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM) + public AggregationModel setBase2ExponentialBucketHistogram( + Base2ExponentialBucketHistogramAggregationModel base2ExponentialBucketHistogram) { + this.base2ExponentialBucketHistogram = base2ExponentialBucketHistogram; + return this; + } + + /** + * Configures the stream to collect data using the last measurement. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#last-value-aggregation + * for details. + * + *

      If omitted, ignore. + */ + @JsonProperty(LAST_VALUE) + @Nullable + public LastValueAggregationModel getLastValue() { + if (lastValue == null) { + return ExtensionPropertyUtil.getGraduated( + LAST_VALUE, extensionProperties, LastValueAggregationModel.class); + } + return lastValue; + } + + @JsonProperty(LAST_VALUE) + public AggregationModel setLastValue(LastValueAggregationModel lastValue) { + this.lastValue = lastValue; + return this; + } + + /** + * Configures the stream to collect the arithmetic sum of measurement values. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#sum-aggregation + * for details. + * + *

      If omitted, ignore. + */ + @JsonProperty(SUM) + @Nullable + public SumAggregationModel getSum() { + if (sum == null) { + return ExtensionPropertyUtil.getGraduated( + SUM, extensionProperties, SumAggregationModel.class); + } + return sum; + } + + @JsonProperty(SUM) + public AggregationModel setSum(SumAggregationModel sum) { + this.sum = sum; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public AggregationModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "AggregationModel{" + + "_default=" + + _default + + ", drop=" + + drop + + ", explicitBucketHistogram=" + + explicitBucketHistogram + + ", base2ExponentialBucketHistogram=" + + base2ExponentialBucketHistogram + + ", lastValue=" + + lastValue + + ", sum=" + + sum + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getDefault() == null) ? 0 : this.getDefault().hashCode(); + h *= 1000003; + h ^= (this.getDrop() == null) ? 0 : this.getDrop().hashCode(); + h *= 1000003; + h ^= + (this.getExplicitBucketHistogram() == null) + ? 0 + : this.getExplicitBucketHistogram().hashCode(); + h *= 1000003; + h ^= + (this.getBase2ExponentialBucketHistogram() == null) + ? 0 + : this.getBase2ExponentialBucketHistogram().hashCode(); + h *= 1000003; + h ^= (this.getLastValue() == null) ? 0 : this.getLastValue().hashCode(); + h *= 1000003; + h ^= (this.getSum() == null) ? 0 : this.getSum().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof AggregationModel) { + AggregationModel that = (AggregationModel) o; + return (this.getDefault() == null + ? that.getDefault() == null + : this.getDefault().equals(that.getDefault())) + && (this.getDrop() == null + ? that.getDrop() == null + : this.getDrop().equals(that.getDrop())) + && (this.getExplicitBucketHistogram() == null + ? that.getExplicitBucketHistogram() == null + : this.getExplicitBucketHistogram().equals(that.getExplicitBucketHistogram())) + && (this.getBase2ExponentialBucketHistogram() == null + ? that.getBase2ExponentialBucketHistogram() == null + : this.getBase2ExponentialBucketHistogram() + .equals(that.getBase2ExponentialBucketHistogram())) + && (this.getLastValue() == null + ? that.getLastValue() == null + : this.getLastValue().equals(that.getLastValue())) + && (this.getSum() == null ? that.getSum() == null : this.getSum().equals(that.getSum())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysOffSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysOffSamplerModel.java new file mode 100644 index 00000000000..849086d16be --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysOffSamplerModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class AlwaysOffSamplerModel { + + @Override + public String toString() { + return "AlwaysOffSamplerModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof AlwaysOffSamplerModel) { + AlwaysOffSamplerModel that = (AlwaysOffSamplerModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysOnSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysOnSamplerModel.java new file mode 100644 index 00000000000..167f8c43a88 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysOnSamplerModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class AlwaysOnSamplerModel { + + @Override + public String toString() { + return "AlwaysOnSamplerModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof AlwaysOnSamplerModel) { + AlwaysOnSamplerModel that = (AlwaysOnSamplerModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysRecordSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysRecordSamplerModel.java new file mode 100644 index 00000000000..083ec5aff97 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AlwaysRecordSamplerModel.java @@ -0,0 +1,119 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysRecordSamplerModel.ROOT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ROOT}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class AlwaysRecordSamplerModel { + + static final String ROOT = "root"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ROOT, SamplerModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private SamplerModel root; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure the wrapped sampler which provides the original sampling + * + *

      decision that AlwaysRecord modifies. DROP decisions are converted + * + *

      to RECORD_ONLY, allowing processors to see all spans without sending them to exporters. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(ROOT) + @Nullable + public SamplerModel getRoot() { + if (root == null) { + return ExtensionPropertyUtil.getGraduated(ROOT, extensionProperties, SamplerModel.class); + } + return root; + } + + @JsonProperty(ROOT) + public AlwaysRecordSamplerModel setRoot(SamplerModel root) { + this.root = root; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public AlwaysRecordSamplerModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "AlwaysRecordSamplerModel{" + + "root=" + + root + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getRoot() == null) ? 0 : this.getRoot().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof AlwaysRecordSamplerModel) { + AlwaysRecordSamplerModel that = (AlwaysRecordSamplerModel) o; + return (this.getRoot() == null + ? that.getRoot() == null + : this.getRoot().equals(that.getRoot())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeLimitsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeLimitsModel.java new file mode 100644 index 00000000000..61eb11777e2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeLimitsModel.java @@ -0,0 +1,201 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel.ATTRIBUTE_COUNT_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel.ATTRIBUTE_VALUE_DEPTH_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel.ATTRIBUTE_VALUE_LENGTH_LIMIT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ATTRIBUTE_VALUE_LENGTH_LIMIT, + ATTRIBUTE_VALUE_DEPTH_LIMIT, + ATTRIBUTE_COUNT_LIMIT +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class AttributeLimitsModel { + + static final String ATTRIBUTE_VALUE_LENGTH_LIMIT = "attribute_value_length_limit"; + static final String ATTRIBUTE_VALUE_DEPTH_LIMIT = "attribute_value_depth_limit"; + static final String ATTRIBUTE_COUNT_LIMIT = "attribute_count_limit"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ATTRIBUTE_VALUE_LENGTH_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_VALUE_DEPTH_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_COUNT_LIMIT, Integer.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer attributeValueLengthLimit; + @Nullable private Integer attributeValueDepthLimit; + @Nullable private Integer attributeCountLimit; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure max attribute value size. + * + *

      Value must be non-negative. + * + *

      If omitted or null, there is no limit. + */ + @JsonProperty(ATTRIBUTE_VALUE_LENGTH_LIMIT) + @Nullable + public Integer getAttributeValueLengthLimit() { + if (attributeValueLengthLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_VALUE_LENGTH_LIMIT, extensionProperties, Integer.class); + } + return attributeValueLengthLimit; + } + + @JsonProperty(ATTRIBUTE_VALUE_LENGTH_LIMIT) + public AttributeLimitsModel setAttributeValueLengthLimit(Integer attributeValueLengthLimit) { + this.attributeValueLengthLimit = attributeValueLengthLimit; + return this; + } + + /** + * Configure the maximum attribute value depth for nested array and map values. + * + *

      Depth starts at 1 for the top-level attribute value and increments when descending into + * array elements or map values. + * + *

      Array or map values deeper than the limit are replaced with an empty value. + * + *

      Value must be positive. + * + *

      If omitted or null, 64 is used. + */ + @JsonProperty(ATTRIBUTE_VALUE_DEPTH_LIMIT) + @Nullable + public Integer getAttributeValueDepthLimit() { + if (attributeValueDepthLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_VALUE_DEPTH_LIMIT, extensionProperties, Integer.class); + } + return attributeValueDepthLimit; + } + + @JsonProperty(ATTRIBUTE_VALUE_DEPTH_LIMIT) + public AttributeLimitsModel setAttributeValueDepthLimit(Integer attributeValueDepthLimit) { + this.attributeValueDepthLimit = attributeValueDepthLimit; + return this; + } + + /** + * Configure max attribute count. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(ATTRIBUTE_COUNT_LIMIT) + @Nullable + public Integer getAttributeCountLimit() { + if (attributeCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_COUNT_LIMIT, extensionProperties, Integer.class); + } + return attributeCountLimit; + } + + @JsonProperty(ATTRIBUTE_COUNT_LIMIT) + public AttributeLimitsModel setAttributeCountLimit(Integer attributeCountLimit) { + this.attributeCountLimit = attributeCountLimit; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public AttributeLimitsModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "AttributeLimitsModel{" + + "attributeValueLengthLimit=" + + attributeValueLengthLimit + + ", attributeValueDepthLimit=" + + attributeValueDepthLimit + + ", attributeCountLimit=" + + attributeCountLimit + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= + (this.getAttributeValueLengthLimit() == null) + ? 0 + : this.getAttributeValueLengthLimit().hashCode(); + h *= 1000003; + h ^= + (this.getAttributeValueDepthLimit() == null) + ? 0 + : this.getAttributeValueDepthLimit().hashCode(); + h *= 1000003; + h ^= (this.getAttributeCountLimit() == null) ? 0 : this.getAttributeCountLimit().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof AttributeLimitsModel) { + AttributeLimitsModel that = (AttributeLimitsModel) o; + return (this.getAttributeValueLengthLimit() == null + ? that.getAttributeValueLengthLimit() == null + : this.getAttributeValueLengthLimit().equals(that.getAttributeValueLengthLimit())) + && (this.getAttributeValueDepthLimit() == null + ? that.getAttributeValueDepthLimit() == null + : this.getAttributeValueDepthLimit().equals(that.getAttributeValueDepthLimit())) + && (this.getAttributeCountLimit() == null + ? that.getAttributeCountLimit() == null + : this.getAttributeCountLimit().equals(that.getAttributeCountLimit())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeNameValueModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeNameValueModel.java new file mode 100644 index 00000000000..990e55e5201 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeNameValueModel.java @@ -0,0 +1,198 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel.NAME; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel.TYPE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel.VALUE; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({NAME, VALUE, TYPE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class AttributeNameValueModel { + + static final String NAME = "name"; + static final String VALUE = "value"; + static final String TYPE = "type"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(NAME, String.class); + STABLE_PROPERTIES.put(VALUE, Object.class); + STABLE_PROPERTIES.put(TYPE, AttributeTypeModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String name; + @Nullable private Object value; + @Nullable private AttributeTypeModel type; + private Map extensionProperties = new LinkedHashMap(); + + /** + * The attribute name. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(NAME) + @Nullable + public String getName() { + if (name == null) { + return ExtensionPropertyUtil.getGraduated(NAME, extensionProperties, String.class); + } + return name; + } + + @JsonProperty(NAME) + public AttributeNameValueModel setName(String name) { + this.name = name; + return this; + } + + /** + * The attribute value. + * + *

      The type of value must match .type. + * + *

      Property must be present, but if null the entry is ignored. + */ + @JsonProperty(VALUE) + @Nullable + public Object getValue() { + if (value == null) { + return ExtensionPropertyUtil.getGraduated(VALUE, extensionProperties, Object.class); + } + return value; + } + + @JsonProperty(VALUE) + public AttributeNameValueModel setValue(Object value) { + this.value = value; + return this; + } + + /** + * The attribute type. + * + *

      Values include: + * + *

      * bool: Boolean attribute value. + * + *

      * bool_array: Boolean array attribute value. + * + *

      * double: Double attribute value. + * + *

      * double_array: Double array attribute value. + * + *

      * int: Integer attribute value. + * + *

      * int_array: Integer array attribute value. + * + *

      * string: String attribute value. + * + *

      * string_array: String array attribute value. + * + *

      If omitted, string is used. + */ + @JsonProperty(TYPE) + @Nullable + public AttributeTypeModel getType() { + if (type == null) { + return ExtensionPropertyUtil.getGraduated( + TYPE, extensionProperties, AttributeTypeModel.class); + } + return type; + } + + @JsonProperty(TYPE) + public AttributeNameValueModel setType(AttributeTypeModel type) { + this.type = type; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public AttributeNameValueModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "AttributeNameValueModel{" + + "name=" + + name + + ", value=" + + value + + ", type=" + + type + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getName() == null) ? 0 : this.getName().hashCode(); + h *= 1000003; + h ^= (this.getValue() == null) ? 0 : this.getValue().hashCode(); + h *= 1000003; + h ^= (this.getType() == null) ? 0 : this.getType().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof AttributeNameValueModel) { + AttributeNameValueModel that = (AttributeNameValueModel) o; + return (this.getName() == null + ? that.getName() == null + : this.getName().equals(that.getName())) + && (this.getValue() == null + ? that.getValue() == null + : this.getValue().equals(that.getValue())) + && (this.getType() == null + ? that.getType() == null + : this.getType().equals(that.getType())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeTypeModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeTypeModel.java new file mode 100644 index 00000000000..9280b6503b4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/AttributeTypeModel.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum AttributeTypeModel { + STRING("string"), + BOOL("bool"), + INT("int"), + DOUBLE("double"), + STRING_ARRAY("string_array"), + BOOL_ARRAY("bool_array"), + INT_ARRAY("int_array"), + DOUBLE_ARRAY("double_array"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (AttributeTypeModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + AttributeTypeModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static AttributeTypeModel fromValue(String value) { + AttributeTypeModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/B3MultiPropagatorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/B3MultiPropagatorModel.java new file mode 100644 index 00000000000..d05b3a7e375 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/B3MultiPropagatorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class B3MultiPropagatorModel { + + @Override + public String toString() { + return "B3MultiPropagatorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof B3MultiPropagatorModel) { + B3MultiPropagatorModel that = (B3MultiPropagatorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/B3PropagatorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/B3PropagatorModel.java new file mode 100644 index 00000000000..8846372d3cb --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/B3PropagatorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class B3PropagatorModel { + + @Override + public String toString() { + return "B3PropagatorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof B3PropagatorModel) { + B3PropagatorModel that = (B3PropagatorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BaggagePropagatorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BaggagePropagatorModel.java new file mode 100644 index 00000000000..e35b7e83348 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BaggagePropagatorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class BaggagePropagatorModel { + + @Override + public String toString() { + return "BaggagePropagatorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof BaggagePropagatorModel) { + BaggagePropagatorModel that = (BaggagePropagatorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/Base2ExponentialBucketHistogramAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/Base2ExponentialBucketHistogramAggregationModel.java new file mode 100644 index 00000000000..2af6dac098c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/Base2ExponentialBucketHistogramAggregationModel.java @@ -0,0 +1,180 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.Base2ExponentialBucketHistogramAggregationModel.MAX_SCALE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.Base2ExponentialBucketHistogramAggregationModel.MAX_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.Base2ExponentialBucketHistogramAggregationModel.RECORD_MIN_MAX; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({MAX_SCALE, MAX_SIZE, RECORD_MIN_MAX}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class Base2ExponentialBucketHistogramAggregationModel { + + static final String MAX_SCALE = "max_scale"; + static final String MAX_SIZE = "max_size"; + static final String RECORD_MIN_MAX = "record_min_max"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(MAX_SCALE, Integer.class); + STABLE_PROPERTIES.put(MAX_SIZE, Integer.class); + STABLE_PROPERTIES.put(RECORD_MIN_MAX, Boolean.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer maxScale; + @Nullable private Integer maxSize; + @Nullable private Boolean recordMinMax; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure the max scale factor. + * + *

      If omitted or null, 20 is used. + */ + @JsonProperty(MAX_SCALE) + @Nullable + public Integer getMaxScale() { + if (maxScale == null) { + return ExtensionPropertyUtil.getGraduated(MAX_SCALE, extensionProperties, Integer.class); + } + return maxScale; + } + + @JsonProperty(MAX_SCALE) + public Base2ExponentialBucketHistogramAggregationModel setMaxScale(Integer maxScale) { + this.maxScale = maxScale; + return this; + } + + /** + * Configure the maximum number of buckets in each of the positive and negative ranges, not + * counting the special zero bucket. + * + *

      If omitted or null, 160 is used. + */ + @JsonProperty(MAX_SIZE) + @Nullable + public Integer getMaxSize() { + if (maxSize == null) { + return ExtensionPropertyUtil.getGraduated(MAX_SIZE, extensionProperties, Integer.class); + } + return maxSize; + } + + @JsonProperty(MAX_SIZE) + public Base2ExponentialBucketHistogramAggregationModel setMaxSize(Integer maxSize) { + this.maxSize = maxSize; + return this; + } + + /** + * Configure whether or not to record min and max. + * + *

      If omitted or null, true is used. + */ + @JsonProperty(RECORD_MIN_MAX) + @Nullable + public Boolean getRecordMinMax() { + if (recordMinMax == null) { + return ExtensionPropertyUtil.getGraduated(RECORD_MIN_MAX, extensionProperties, Boolean.class); + } + return recordMinMax; + } + + @JsonProperty(RECORD_MIN_MAX) + public Base2ExponentialBucketHistogramAggregationModel setRecordMinMax(Boolean recordMinMax) { + this.recordMinMax = recordMinMax; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public Base2ExponentialBucketHistogramAggregationModel setExtensionProperty( + String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "Base2ExponentialBucketHistogramAggregationModel{" + + "maxScale=" + + maxScale + + ", maxSize=" + + maxSize + + ", recordMinMax=" + + recordMinMax + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getMaxScale() == null) ? 0 : this.getMaxScale().hashCode(); + h *= 1000003; + h ^= (this.getMaxSize() == null) ? 0 : this.getMaxSize().hashCode(); + h *= 1000003; + h ^= (this.getRecordMinMax() == null) ? 0 : this.getRecordMinMax().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof Base2ExponentialBucketHistogramAggregationModel) { + Base2ExponentialBucketHistogramAggregationModel that = + (Base2ExponentialBucketHistogramAggregationModel) o; + return (this.getMaxScale() == null + ? that.getMaxScale() == null + : this.getMaxScale().equals(that.getMaxScale())) + && (this.getMaxSize() == null + ? that.getMaxSize() == null + : this.getMaxSize().equals(that.getMaxSize())) + && (this.getRecordMinMax() == null + ? that.getRecordMinMax() == null + : this.getRecordMinMax().equals(that.getRecordMinMax())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BatchLogRecordProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BatchLogRecordProcessorModel.java new file mode 100644 index 00000000000..d466230aec2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BatchLogRecordProcessorModel.java @@ -0,0 +1,251 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel.EXPORTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel.EXPORT_TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel.MAX_EXPORT_BATCH_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel.MAX_QUEUE_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel.SCHEDULE_DELAY; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + SCHEDULE_DELAY, + EXPORT_TIMEOUT, + MAX_QUEUE_SIZE, + MAX_EXPORT_BATCH_SIZE, + EXPORTER +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class BatchLogRecordProcessorModel { + + static final String SCHEDULE_DELAY = "schedule_delay"; + static final String EXPORT_TIMEOUT = "export_timeout"; + static final String MAX_QUEUE_SIZE = "max_queue_size"; + static final String MAX_EXPORT_BATCH_SIZE = "max_export_batch_size"; + static final String EXPORTER = "exporter"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(SCHEDULE_DELAY, Integer.class); + STABLE_PROPERTIES.put(EXPORT_TIMEOUT, Integer.class); + STABLE_PROPERTIES.put(MAX_QUEUE_SIZE, Integer.class); + STABLE_PROPERTIES.put(MAX_EXPORT_BATCH_SIZE, Integer.class); + STABLE_PROPERTIES.put(EXPORTER, LogRecordExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer scheduleDelay; + @Nullable private Integer exportTimeout; + @Nullable private Integer maxQueueSize; + @Nullable private Integer maxExportBatchSize; + @Nullable private LogRecordExporterModel exporter; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure delay interval (in milliseconds) between two consecutive exports. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 1000 is used. + */ + @JsonProperty(SCHEDULE_DELAY) + @Nullable + public Integer getScheduleDelay() { + if (scheduleDelay == null) { + return ExtensionPropertyUtil.getGraduated(SCHEDULE_DELAY, extensionProperties, Integer.class); + } + return scheduleDelay; + } + + @JsonProperty(SCHEDULE_DELAY) + public BatchLogRecordProcessorModel setScheduleDelay(Integer scheduleDelay) { + this.scheduleDelay = scheduleDelay; + return this; + } + + /** + * Configure maximum allowed time (in milliseconds) to export data. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 30000 is used. + */ + @JsonProperty(EXPORT_TIMEOUT) + @Nullable + public Integer getExportTimeout() { + if (exportTimeout == null) { + return ExtensionPropertyUtil.getGraduated(EXPORT_TIMEOUT, extensionProperties, Integer.class); + } + return exportTimeout; + } + + @JsonProperty(EXPORT_TIMEOUT) + public BatchLogRecordProcessorModel setExportTimeout(Integer exportTimeout) { + this.exportTimeout = exportTimeout; + return this; + } + + /** + * Configure maximum queue size. Value must be positive. + * + *

      If omitted or null, 2048 is used. + */ + @JsonProperty(MAX_QUEUE_SIZE) + @Nullable + public Integer getMaxQueueSize() { + if (maxQueueSize == null) { + return ExtensionPropertyUtil.getGraduated(MAX_QUEUE_SIZE, extensionProperties, Integer.class); + } + return maxQueueSize; + } + + @JsonProperty(MAX_QUEUE_SIZE) + public BatchLogRecordProcessorModel setMaxQueueSize(Integer maxQueueSize) { + this.maxQueueSize = maxQueueSize; + return this; + } + + /** + * Configure maximum batch size. Value must be positive. + * + *

      If omitted or null, 512 is used. + */ + @JsonProperty(MAX_EXPORT_BATCH_SIZE) + @Nullable + public Integer getMaxExportBatchSize() { + if (maxExportBatchSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_EXPORT_BATCH_SIZE, extensionProperties, Integer.class); + } + return maxExportBatchSize; + } + + @JsonProperty(MAX_EXPORT_BATCH_SIZE) + public BatchLogRecordProcessorModel setMaxExportBatchSize(Integer maxExportBatchSize) { + this.maxExportBatchSize = maxExportBatchSize; + return this; + } + + /** + * Configure exporter. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(EXPORTER) + @Nullable + public LogRecordExporterModel getExporter() { + if (exporter == null) { + return ExtensionPropertyUtil.getGraduated( + EXPORTER, extensionProperties, LogRecordExporterModel.class); + } + return exporter; + } + + @JsonProperty(EXPORTER) + public BatchLogRecordProcessorModel setExporter(LogRecordExporterModel exporter) { + this.exporter = exporter; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public BatchLogRecordProcessorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "BatchLogRecordProcessorModel{" + + "scheduleDelay=" + + scheduleDelay + + ", exportTimeout=" + + exportTimeout + + ", maxQueueSize=" + + maxQueueSize + + ", maxExportBatchSize=" + + maxExportBatchSize + + ", exporter=" + + exporter + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getScheduleDelay() == null) ? 0 : this.getScheduleDelay().hashCode(); + h *= 1000003; + h ^= (this.getExportTimeout() == null) ? 0 : this.getExportTimeout().hashCode(); + h *= 1000003; + h ^= (this.getMaxQueueSize() == null) ? 0 : this.getMaxQueueSize().hashCode(); + h *= 1000003; + h ^= (this.getMaxExportBatchSize() == null) ? 0 : this.getMaxExportBatchSize().hashCode(); + h *= 1000003; + h ^= (this.getExporter() == null) ? 0 : this.getExporter().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof BatchLogRecordProcessorModel) { + BatchLogRecordProcessorModel that = (BatchLogRecordProcessorModel) o; + return (this.getScheduleDelay() == null + ? that.getScheduleDelay() == null + : this.getScheduleDelay().equals(that.getScheduleDelay())) + && (this.getExportTimeout() == null + ? that.getExportTimeout() == null + : this.getExportTimeout().equals(that.getExportTimeout())) + && (this.getMaxQueueSize() == null + ? that.getMaxQueueSize() == null + : this.getMaxQueueSize().equals(that.getMaxQueueSize())) + && (this.getMaxExportBatchSize() == null + ? that.getMaxExportBatchSize() == null + : this.getMaxExportBatchSize().equals(that.getMaxExportBatchSize())) + && (this.getExporter() == null + ? that.getExporter() == null + : this.getExporter().equals(that.getExporter())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BatchSpanProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BatchSpanProcessorModel.java new file mode 100644 index 00000000000..045dda964ac --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/BatchSpanProcessorModel.java @@ -0,0 +1,251 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel.EXPORTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel.EXPORT_TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel.MAX_EXPORT_BATCH_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel.MAX_QUEUE_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel.SCHEDULE_DELAY; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + SCHEDULE_DELAY, + EXPORT_TIMEOUT, + MAX_QUEUE_SIZE, + MAX_EXPORT_BATCH_SIZE, + EXPORTER +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class BatchSpanProcessorModel { + + static final String SCHEDULE_DELAY = "schedule_delay"; + static final String EXPORT_TIMEOUT = "export_timeout"; + static final String MAX_QUEUE_SIZE = "max_queue_size"; + static final String MAX_EXPORT_BATCH_SIZE = "max_export_batch_size"; + static final String EXPORTER = "exporter"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(SCHEDULE_DELAY, Integer.class); + STABLE_PROPERTIES.put(EXPORT_TIMEOUT, Integer.class); + STABLE_PROPERTIES.put(MAX_QUEUE_SIZE, Integer.class); + STABLE_PROPERTIES.put(MAX_EXPORT_BATCH_SIZE, Integer.class); + STABLE_PROPERTIES.put(EXPORTER, SpanExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer scheduleDelay; + @Nullable private Integer exportTimeout; + @Nullable private Integer maxQueueSize; + @Nullable private Integer maxExportBatchSize; + @Nullable private SpanExporterModel exporter; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure delay interval (in milliseconds) between two consecutive exports. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 5000 is used. + */ + @JsonProperty(SCHEDULE_DELAY) + @Nullable + public Integer getScheduleDelay() { + if (scheduleDelay == null) { + return ExtensionPropertyUtil.getGraduated(SCHEDULE_DELAY, extensionProperties, Integer.class); + } + return scheduleDelay; + } + + @JsonProperty(SCHEDULE_DELAY) + public BatchSpanProcessorModel setScheduleDelay(Integer scheduleDelay) { + this.scheduleDelay = scheduleDelay; + return this; + } + + /** + * Configure maximum allowed time (in milliseconds) to export data. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 30000 is used. + */ + @JsonProperty(EXPORT_TIMEOUT) + @Nullable + public Integer getExportTimeout() { + if (exportTimeout == null) { + return ExtensionPropertyUtil.getGraduated(EXPORT_TIMEOUT, extensionProperties, Integer.class); + } + return exportTimeout; + } + + @JsonProperty(EXPORT_TIMEOUT) + public BatchSpanProcessorModel setExportTimeout(Integer exportTimeout) { + this.exportTimeout = exportTimeout; + return this; + } + + /** + * Configure maximum queue size. Value must be positive. + * + *

      If omitted or null, 2048 is used. + */ + @JsonProperty(MAX_QUEUE_SIZE) + @Nullable + public Integer getMaxQueueSize() { + if (maxQueueSize == null) { + return ExtensionPropertyUtil.getGraduated(MAX_QUEUE_SIZE, extensionProperties, Integer.class); + } + return maxQueueSize; + } + + @JsonProperty(MAX_QUEUE_SIZE) + public BatchSpanProcessorModel setMaxQueueSize(Integer maxQueueSize) { + this.maxQueueSize = maxQueueSize; + return this; + } + + /** + * Configure maximum batch size. Value must be positive. + * + *

      If omitted or null, 512 is used. + */ + @JsonProperty(MAX_EXPORT_BATCH_SIZE) + @Nullable + public Integer getMaxExportBatchSize() { + if (maxExportBatchSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_EXPORT_BATCH_SIZE, extensionProperties, Integer.class); + } + return maxExportBatchSize; + } + + @JsonProperty(MAX_EXPORT_BATCH_SIZE) + public BatchSpanProcessorModel setMaxExportBatchSize(Integer maxExportBatchSize) { + this.maxExportBatchSize = maxExportBatchSize; + return this; + } + + /** + * Configure exporter. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(EXPORTER) + @Nullable + public SpanExporterModel getExporter() { + if (exporter == null) { + return ExtensionPropertyUtil.getGraduated( + EXPORTER, extensionProperties, SpanExporterModel.class); + } + return exporter; + } + + @JsonProperty(EXPORTER) + public BatchSpanProcessorModel setExporter(SpanExporterModel exporter) { + this.exporter = exporter; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public BatchSpanProcessorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "BatchSpanProcessorModel{" + + "scheduleDelay=" + + scheduleDelay + + ", exportTimeout=" + + exportTimeout + + ", maxQueueSize=" + + maxQueueSize + + ", maxExportBatchSize=" + + maxExportBatchSize + + ", exporter=" + + exporter + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getScheduleDelay() == null) ? 0 : this.getScheduleDelay().hashCode(); + h *= 1000003; + h ^= (this.getExportTimeout() == null) ? 0 : this.getExportTimeout().hashCode(); + h *= 1000003; + h ^= (this.getMaxQueueSize() == null) ? 0 : this.getMaxQueueSize().hashCode(); + h *= 1000003; + h ^= (this.getMaxExportBatchSize() == null) ? 0 : this.getMaxExportBatchSize().hashCode(); + h *= 1000003; + h ^= (this.getExporter() == null) ? 0 : this.getExporter().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof BatchSpanProcessorModel) { + BatchSpanProcessorModel that = (BatchSpanProcessorModel) o; + return (this.getScheduleDelay() == null + ? that.getScheduleDelay() == null + : this.getScheduleDelay().equals(that.getScheduleDelay())) + && (this.getExportTimeout() == null + ? that.getExportTimeout() == null + : this.getExportTimeout().equals(that.getExportTimeout())) + && (this.getMaxQueueSize() == null + ? that.getMaxQueueSize() == null + : this.getMaxQueueSize().equals(that.getMaxQueueSize())) + && (this.getMaxExportBatchSize() == null + ? that.getMaxExportBatchSize() == null + : this.getMaxExportBatchSize().equals(that.getMaxExportBatchSize())) + && (this.getExporter() == null + ? that.getExporter() == null + : this.getExporter().equals(that.getExporter())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/CardinalityLimitsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/CardinalityLimitsModel.java new file mode 100644 index 00000000000..f9e484fd8ea --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/CardinalityLimitsModel.java @@ -0,0 +1,350 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.COUNTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.DEFAULT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.GAUGE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.HISTOGRAM; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.OBSERVABLE_COUNTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.OBSERVABLE_GAUGE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.OBSERVABLE_UP_DOWN_COUNTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel.UP_DOWN_COUNTER; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + DEFAULT, + COUNTER, + GAUGE, + HISTOGRAM, + OBSERVABLE_COUNTER, + OBSERVABLE_GAUGE, + OBSERVABLE_UP_DOWN_COUNTER, + UP_DOWN_COUNTER +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class CardinalityLimitsModel { + + static final String DEFAULT = "default"; + static final String COUNTER = "counter"; + static final String GAUGE = "gauge"; + static final String HISTOGRAM = "histogram"; + static final String OBSERVABLE_COUNTER = "observable_counter"; + static final String OBSERVABLE_GAUGE = "observable_gauge"; + static final String OBSERVABLE_UP_DOWN_COUNTER = "observable_up_down_counter"; + static final String UP_DOWN_COUNTER = "up_down_counter"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(DEFAULT, Integer.class); + STABLE_PROPERTIES.put(COUNTER, Integer.class); + STABLE_PROPERTIES.put(GAUGE, Integer.class); + STABLE_PROPERTIES.put(HISTOGRAM, Integer.class); + STABLE_PROPERTIES.put(OBSERVABLE_COUNTER, Integer.class); + STABLE_PROPERTIES.put(OBSERVABLE_GAUGE, Integer.class); + STABLE_PROPERTIES.put(OBSERVABLE_UP_DOWN_COUNTER, Integer.class); + STABLE_PROPERTIES.put(UP_DOWN_COUNTER, Integer.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer _default; + @Nullable private Integer counter; + @Nullable private Integer gauge; + @Nullable private Integer histogram; + @Nullable private Integer observableCounter; + @Nullable private Integer observableGauge; + @Nullable private Integer observableUpDownCounter; + @Nullable private Integer upDownCounter; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure default cardinality limit for all instrument types. + * + *

      Instrument-specific cardinality limits take priority. + * + *

      If omitted or null, 2000 is used. + */ + @JsonProperty(DEFAULT) + @Nullable + public Integer getDefault() { + if (_default == null) { + return ExtensionPropertyUtil.getGraduated(DEFAULT, extensionProperties, Integer.class); + } + return _default; + } + + @JsonProperty(DEFAULT) + public CardinalityLimitsModel setDefault(Integer _default) { + this._default = _default; + return this; + } + + /** + * Configure default cardinality limit for counter instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(COUNTER) + @Nullable + public Integer getCounter() { + if (counter == null) { + return ExtensionPropertyUtil.getGraduated(COUNTER, extensionProperties, Integer.class); + } + return counter; + } + + @JsonProperty(COUNTER) + public CardinalityLimitsModel setCounter(Integer counter) { + this.counter = counter; + return this; + } + + /** + * Configure default cardinality limit for gauge instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(GAUGE) + @Nullable + public Integer getGauge() { + if (gauge == null) { + return ExtensionPropertyUtil.getGraduated(GAUGE, extensionProperties, Integer.class); + } + return gauge; + } + + @JsonProperty(GAUGE) + public CardinalityLimitsModel setGauge(Integer gauge) { + this.gauge = gauge; + return this; + } + + /** + * Configure default cardinality limit for histogram instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(HISTOGRAM) + @Nullable + public Integer getHistogram() { + if (histogram == null) { + return ExtensionPropertyUtil.getGraduated(HISTOGRAM, extensionProperties, Integer.class); + } + return histogram; + } + + @JsonProperty(HISTOGRAM) + public CardinalityLimitsModel setHistogram(Integer histogram) { + this.histogram = histogram; + return this; + } + + /** + * Configure default cardinality limit for observable_counter instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(OBSERVABLE_COUNTER) + @Nullable + public Integer getObservableCounter() { + if (observableCounter == null) { + return ExtensionPropertyUtil.getGraduated( + OBSERVABLE_COUNTER, extensionProperties, Integer.class); + } + return observableCounter; + } + + @JsonProperty(OBSERVABLE_COUNTER) + public CardinalityLimitsModel setObservableCounter(Integer observableCounter) { + this.observableCounter = observableCounter; + return this; + } + + /** + * Configure default cardinality limit for observable_gauge instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(OBSERVABLE_GAUGE) + @Nullable + public Integer getObservableGauge() { + if (observableGauge == null) { + return ExtensionPropertyUtil.getGraduated( + OBSERVABLE_GAUGE, extensionProperties, Integer.class); + } + return observableGauge; + } + + @JsonProperty(OBSERVABLE_GAUGE) + public CardinalityLimitsModel setObservableGauge(Integer observableGauge) { + this.observableGauge = observableGauge; + return this; + } + + /** + * Configure default cardinality limit for observable_up_down_counter instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(OBSERVABLE_UP_DOWN_COUNTER) + @Nullable + public Integer getObservableUpDownCounter() { + if (observableUpDownCounter == null) { + return ExtensionPropertyUtil.getGraduated( + OBSERVABLE_UP_DOWN_COUNTER, extensionProperties, Integer.class); + } + return observableUpDownCounter; + } + + @JsonProperty(OBSERVABLE_UP_DOWN_COUNTER) + public CardinalityLimitsModel setObservableUpDownCounter(Integer observableUpDownCounter) { + this.observableUpDownCounter = observableUpDownCounter; + return this; + } + + /** + * Configure default cardinality limit for up_down_counter instruments. + * + *

      If omitted or null, the value from .default is used. + */ + @JsonProperty(UP_DOWN_COUNTER) + @Nullable + public Integer getUpDownCounter() { + if (upDownCounter == null) { + return ExtensionPropertyUtil.getGraduated( + UP_DOWN_COUNTER, extensionProperties, Integer.class); + } + return upDownCounter; + } + + @JsonProperty(UP_DOWN_COUNTER) + public CardinalityLimitsModel setUpDownCounter(Integer upDownCounter) { + this.upDownCounter = upDownCounter; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public CardinalityLimitsModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "CardinalityLimitsModel{" + + "_default=" + + _default + + ", counter=" + + counter + + ", gauge=" + + gauge + + ", histogram=" + + histogram + + ", observableCounter=" + + observableCounter + + ", observableGauge=" + + observableGauge + + ", observableUpDownCounter=" + + observableUpDownCounter + + ", upDownCounter=" + + upDownCounter + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getDefault() == null) ? 0 : this.getDefault().hashCode(); + h *= 1000003; + h ^= (this.getCounter() == null) ? 0 : this.getCounter().hashCode(); + h *= 1000003; + h ^= (this.getGauge() == null) ? 0 : this.getGauge().hashCode(); + h *= 1000003; + h ^= (this.getHistogram() == null) ? 0 : this.getHistogram().hashCode(); + h *= 1000003; + h ^= (this.getObservableCounter() == null) ? 0 : this.getObservableCounter().hashCode(); + h *= 1000003; + h ^= (this.getObservableGauge() == null) ? 0 : this.getObservableGauge().hashCode(); + h *= 1000003; + h ^= + (this.getObservableUpDownCounter() == null) + ? 0 + : this.getObservableUpDownCounter().hashCode(); + h *= 1000003; + h ^= (this.getUpDownCounter() == null) ? 0 : this.getUpDownCounter().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof CardinalityLimitsModel) { + CardinalityLimitsModel that = (CardinalityLimitsModel) o; + return (this.getDefault() == null + ? that.getDefault() == null + : this.getDefault().equals(that.getDefault())) + && (this.getCounter() == null + ? that.getCounter() == null + : this.getCounter().equals(that.getCounter())) + && (this.getGauge() == null + ? that.getGauge() == null + : this.getGauge().equals(that.getGauge())) + && (this.getHistogram() == null + ? that.getHistogram() == null + : this.getHistogram().equals(that.getHistogram())) + && (this.getObservableCounter() == null + ? that.getObservableCounter() == null + : this.getObservableCounter().equals(that.getObservableCounter())) + && (this.getObservableGauge() == null + ? that.getObservableGauge() == null + : this.getObservableGauge().equals(that.getObservableGauge())) + && (this.getObservableUpDownCounter() == null + ? that.getObservableUpDownCounter() == null + : this.getObservableUpDownCounter().equals(that.getObservableUpDownCounter())) + && (this.getUpDownCounter() == null + ? that.getUpDownCounter() == null + : this.getUpDownCounter().equals(that.getUpDownCounter())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ConsoleExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ConsoleExporterModel.java new file mode 100644 index 00000000000..ffaa57b846e --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ConsoleExporterModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ConsoleExporterModel { + + @Override + public String toString() { + return "ConsoleExporterModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ConsoleExporterModel) { + ConsoleExporterModel that = (ConsoleExporterModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ConsoleMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ConsoleMetricExporterModel.java new file mode 100644 index 00000000000..c058fc7e2b6 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ConsoleMetricExporterModel.java @@ -0,0 +1,174 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ConsoleMetricExporterModel.DEFAULT_HISTOGRAM_AGGREGATION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ConsoleMetricExporterModel.TEMPORALITY_PREFERENCE; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({TEMPORALITY_PREFERENCE, DEFAULT_HISTOGRAM_AGGREGATION}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ConsoleMetricExporterModel { + + static final String TEMPORALITY_PREFERENCE = "temporality_preference"; + static final String DEFAULT_HISTOGRAM_AGGREGATION = "default_histogram_aggregation"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(TEMPORALITY_PREFERENCE, ExporterTemporalityPreferenceModel.class); + STABLE_PROPERTIES.put( + DEFAULT_HISTOGRAM_AGGREGATION, ExporterDefaultHistogramAggregationModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private ExporterTemporalityPreferenceModel temporalityPreference; + @Nullable private ExporterDefaultHistogramAggregationModel defaultHistogramAggregation; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure temporality preference. + * + *

      Values include: + * + *

      * cumulative: Use cumulative aggregation temporality for all instrument types. + * + *

      * delta: Use delta aggregation for all instrument types except up down counter and + * asynchronous up down counter. + * + *

      * low_memory: Use delta aggregation temporality for counter and histogram instrument types. + * Use cumulative aggregation temporality for all other instrument types. + * + *

      If omitted, cumulative is used. + */ + @JsonProperty(TEMPORALITY_PREFERENCE) + @Nullable + public ExporterTemporalityPreferenceModel getTemporalityPreference() { + if (temporalityPreference == null) { + return ExtensionPropertyUtil.getGraduated( + TEMPORALITY_PREFERENCE, extensionProperties, ExporterTemporalityPreferenceModel.class); + } + return temporalityPreference; + } + + @JsonProperty(TEMPORALITY_PREFERENCE) + public ConsoleMetricExporterModel setTemporalityPreference( + ExporterTemporalityPreferenceModel temporalityPreference) { + this.temporalityPreference = temporalityPreference; + return this; + } + + /** + * Configure default histogram aggregation. + * + *

      Values include: + * + *

      * base2_exponential_bucket_histogram: Use base2 exponential histogram as the default + * aggregation for histogram instruments. + * + *

      * explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for + * histogram instruments. + * + *

      If omitted, explicit_bucket_histogram is used. + */ + @JsonProperty(DEFAULT_HISTOGRAM_AGGREGATION) + @Nullable + public ExporterDefaultHistogramAggregationModel getDefaultHistogramAggregation() { + if (defaultHistogramAggregation == null) { + return ExtensionPropertyUtil.getGraduated( + DEFAULT_HISTOGRAM_AGGREGATION, + extensionProperties, + ExporterDefaultHistogramAggregationModel.class); + } + return defaultHistogramAggregation; + } + + @JsonProperty(DEFAULT_HISTOGRAM_AGGREGATION) + public ConsoleMetricExporterModel setDefaultHistogramAggregation( + ExporterDefaultHistogramAggregationModel defaultHistogramAggregation) { + this.defaultHistogramAggregation = defaultHistogramAggregation; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ConsoleMetricExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ConsoleMetricExporterModel{" + + "temporalityPreference=" + + temporalityPreference + + ", defaultHistogramAggregation=" + + defaultHistogramAggregation + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getTemporalityPreference() == null) ? 0 : this.getTemporalityPreference().hashCode(); + h *= 1000003; + h ^= + (this.getDefaultHistogramAggregation() == null) + ? 0 + : this.getDefaultHistogramAggregation().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ConsoleMetricExporterModel) { + ConsoleMetricExporterModel that = (ConsoleMetricExporterModel) o; + return (this.getTemporalityPreference() == null + ? that.getTemporalityPreference() == null + : this.getTemporalityPreference().equals(that.getTemporalityPreference())) + && (this.getDefaultHistogramAggregation() == null + ? that.getDefaultHistogramAggregation() == null + : this.getDefaultHistogramAggregation().equals(that.getDefaultHistogramAggregation())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DefaultAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DefaultAggregationModel.java new file mode 100644 index 00000000000..b0a84de4def --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DefaultAggregationModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class DefaultAggregationModel { + + @Override + public String toString() { + return "DefaultAggregationModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof DefaultAggregationModel) { + DefaultAggregationModel that = (DefaultAggregationModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DistributionModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DistributionModel.java new file mode 100644 index 00000000000..457649ddbc2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DistributionModel.java @@ -0,0 +1,71 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class DistributionModel { + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + private Map extensionProperties = new LinkedHashMap(); + + @JsonAnyGetter + public Map getExtensionProperties() { + return extensionProperties; + } + + @JsonAnySetter + public DistributionModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + Collections.emptyMap(), + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "DistributionModel{" + "extensionProperties=" + extensionProperties + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof DistributionModel) { + DistributionModel that = (DistributionModel) o; + return (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DropAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DropAggregationModel.java new file mode 100644 index 00000000000..520e9d12225 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/DropAggregationModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class DropAggregationModel { + + @Override + public String toString() { + return "DropAggregationModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof DropAggregationModel) { + DropAggregationModel that = (DropAggregationModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExemplarFilterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExemplarFilterModel.java new file mode 100644 index 00000000000..3ae48a36af4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExemplarFilterModel.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum ExemplarFilterModel { + ALWAYS_ON("always_on"), + ALWAYS_OFF("always_off"), + TRACE_BASED("trace_based"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (ExemplarFilterModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + ExemplarFilterModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static ExemplarFilterModel fromValue(String value) { + ExemplarFilterModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExplicitBucketHistogramAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExplicitBucketHistogramAggregationModel.java new file mode 100644 index 00000000000..55a0df19d46 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExplicitBucketHistogramAggregationModel.java @@ -0,0 +1,145 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExplicitBucketHistogramAggregationModel.BOUNDARIES; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExplicitBucketHistogramAggregationModel.RECORD_MIN_MAX; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({BOUNDARIES, RECORD_MIN_MAX}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExplicitBucketHistogramAggregationModel { + + static final String BOUNDARIES = "boundaries"; + static final String RECORD_MIN_MAX = "record_min_max"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(RECORD_MIN_MAX, Boolean.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private List boundaries; + @Nullable private Boolean recordMinMax; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure bucket boundaries. + * + *

      If omitted, [0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000] is + * used. + */ + @JsonProperty(BOUNDARIES) + @Nullable + public List getBoundaries() { + return boundaries; + } + + @JsonProperty(BOUNDARIES) + public ExplicitBucketHistogramAggregationModel setBoundaries(List boundaries) { + this.boundaries = boundaries; + return this; + } + + /** + * Configure record min and max. + * + *

      If omitted or null, true is used. + */ + @JsonProperty(RECORD_MIN_MAX) + @Nullable + public Boolean getRecordMinMax() { + if (recordMinMax == null) { + return ExtensionPropertyUtil.getGraduated(RECORD_MIN_MAX, extensionProperties, Boolean.class); + } + return recordMinMax; + } + + @JsonProperty(RECORD_MIN_MAX) + public ExplicitBucketHistogramAggregationModel setRecordMinMax(Boolean recordMinMax) { + this.recordMinMax = recordMinMax; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ExplicitBucketHistogramAggregationModel setExtensionProperty( + String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ExplicitBucketHistogramAggregationModel{" + + "boundaries=" + + boundaries + + ", recordMinMax=" + + recordMinMax + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.boundaries == null) ? 0 : this.boundaries.hashCode(); + h *= 1000003; + h ^= (this.getRecordMinMax() == null) ? 0 : this.getRecordMinMax().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExplicitBucketHistogramAggregationModel) { + ExplicitBucketHistogramAggregationModel that = (ExplicitBucketHistogramAggregationModel) o; + return (this.boundaries == null + ? that.boundaries == null + : this.boundaries.equals(that.boundaries)) + && (this.getRecordMinMax() == null + ? that.getRecordMinMax() == null + : this.getRecordMinMax().equals(that.getRecordMinMax())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExporterDefaultHistogramAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExporterDefaultHistogramAggregationModel.java new file mode 100644 index 00000000000..1b58a39500e --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExporterDefaultHistogramAggregationModel.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum ExporterDefaultHistogramAggregationModel { + EXPLICIT_BUCKET_HISTOGRAM("explicit_bucket_histogram"), + BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM("base2_exponential_bucket_histogram"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (ExporterDefaultHistogramAggregationModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + ExporterDefaultHistogramAggregationModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static ExporterDefaultHistogramAggregationModel fromValue(String value) { + ExporterDefaultHistogramAggregationModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExporterTemporalityPreferenceModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExporterTemporalityPreferenceModel.java new file mode 100644 index 00000000000..2fe55ea200b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ExporterTemporalityPreferenceModel.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum ExporterTemporalityPreferenceModel { + CUMULATIVE("cumulative"), + DELTA("delta"), + LOW_MEMORY("low_memory"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (ExporterTemporalityPreferenceModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + ExporterTemporalityPreferenceModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static ExporterTemporalityPreferenceModel fromValue(String value) { + ExporterTemporalityPreferenceModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/GrpcTlsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/GrpcTlsModel.java new file mode 100644 index 00000000000..3c896f2a967 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/GrpcTlsModel.java @@ -0,0 +1,219 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel.CA_FILE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel.CERT_FILE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel.INSECURE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel.KEY_FILE; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({CA_FILE, KEY_FILE, CERT_FILE, INSECURE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class GrpcTlsModel { + + static final String CA_FILE = "ca_file"; + static final String KEY_FILE = "key_file"; + static final String CERT_FILE = "cert_file"; + static final String INSECURE = "insecure"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(CA_FILE, String.class); + STABLE_PROPERTIES.put(KEY_FILE, String.class); + STABLE_PROPERTIES.put(CERT_FILE, String.class); + STABLE_PROPERTIES.put(INSECURE, Boolean.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String caFile; + @Nullable private String keyFile; + @Nullable private String certFile; + @Nullable private Boolean insecure; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure certificate used to verify a server's TLS credentials. + * + *

      Absolute path to certificate file in PEM format. + * + *

      If omitted or null, system default certificate verification is used for secure connections. + */ + @JsonProperty(CA_FILE) + @Nullable + public String getCaFile() { + if (caFile == null) { + return ExtensionPropertyUtil.getGraduated(CA_FILE, extensionProperties, String.class); + } + return caFile; + } + + @JsonProperty(CA_FILE) + public GrpcTlsModel setCaFile(String caFile) { + this.caFile = caFile; + return this; + } + + /** + * Configure mTLS private client key. + * + *

      Absolute path to client key file in PEM format. If set, .client_certificate must also be + * set. + * + *

      If omitted or null, mTLS is not used. + */ + @JsonProperty(KEY_FILE) + @Nullable + public String getKeyFile() { + if (keyFile == null) { + return ExtensionPropertyUtil.getGraduated(KEY_FILE, extensionProperties, String.class); + } + return keyFile; + } + + @JsonProperty(KEY_FILE) + public GrpcTlsModel setKeyFile(String keyFile) { + this.keyFile = keyFile; + return this; + } + + /** + * Configure mTLS client certificate. + * + *

      Absolute path to client certificate file in PEM format. If set, .client_key must also be + * set. + * + *

      If omitted or null, mTLS is not used. + */ + @JsonProperty(CERT_FILE) + @Nullable + public String getCertFile() { + if (certFile == null) { + return ExtensionPropertyUtil.getGraduated(CERT_FILE, extensionProperties, String.class); + } + return certFile; + } + + @JsonProperty(CERT_FILE) + public GrpcTlsModel setCertFile(String certFile) { + this.certFile = certFile; + return this; + } + + /** + * Configure client transport security for the exporter's connection. + * + *

      Only applicable when .endpoint is provided without http or https scheme. Implementations may + * choose to ignore .insecure. + * + *

      If omitted or null, false is used. + */ + @JsonProperty(INSECURE) + @Nullable + public Boolean getInsecure() { + if (insecure == null) { + return ExtensionPropertyUtil.getGraduated(INSECURE, extensionProperties, Boolean.class); + } + return insecure; + } + + @JsonProperty(INSECURE) + public GrpcTlsModel setInsecure(Boolean insecure) { + this.insecure = insecure; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public GrpcTlsModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "GrpcTlsModel{" + + "caFile=" + + caFile + + ", keyFile=" + + keyFile + + ", certFile=" + + certFile + + ", insecure=" + + insecure + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getCaFile() == null) ? 0 : this.getCaFile().hashCode(); + h *= 1000003; + h ^= (this.getKeyFile() == null) ? 0 : this.getKeyFile().hashCode(); + h *= 1000003; + h ^= (this.getCertFile() == null) ? 0 : this.getCertFile().hashCode(); + h *= 1000003; + h ^= (this.getInsecure() == null) ? 0 : this.getInsecure().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof GrpcTlsModel) { + GrpcTlsModel that = (GrpcTlsModel) o; + return (this.getCaFile() == null + ? that.getCaFile() == null + : this.getCaFile().equals(that.getCaFile())) + && (this.getKeyFile() == null + ? that.getKeyFile() == null + : this.getKeyFile().equals(that.getKeyFile())) + && (this.getCertFile() == null + ? that.getCertFile() == null + : this.getCertFile().equals(that.getCertFile())) + && (this.getInsecure() == null + ? that.getInsecure() == null + : this.getInsecure().equals(that.getInsecure())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/HttpTlsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/HttpTlsModel.java new file mode 100644 index 00000000000..128bb2d39b0 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/HttpTlsModel.java @@ -0,0 +1,185 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.HttpTlsModel.CA_FILE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.HttpTlsModel.CERT_FILE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.HttpTlsModel.KEY_FILE; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({CA_FILE, KEY_FILE, CERT_FILE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class HttpTlsModel { + + static final String CA_FILE = "ca_file"; + static final String KEY_FILE = "key_file"; + static final String CERT_FILE = "cert_file"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(CA_FILE, String.class); + STABLE_PROPERTIES.put(KEY_FILE, String.class); + STABLE_PROPERTIES.put(CERT_FILE, String.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String caFile; + @Nullable private String keyFile; + @Nullable private String certFile; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure certificate used to verify a server's TLS credentials. + * + *

      Absolute path to certificate file in PEM format. + * + *

      If omitted or null, system default certificate verification is used for secure connections. + */ + @JsonProperty(CA_FILE) + @Nullable + public String getCaFile() { + if (caFile == null) { + return ExtensionPropertyUtil.getGraduated(CA_FILE, extensionProperties, String.class); + } + return caFile; + } + + @JsonProperty(CA_FILE) + public HttpTlsModel setCaFile(String caFile) { + this.caFile = caFile; + return this; + } + + /** + * Configure mTLS private client key. + * + *

      Absolute path to client key file in PEM format. If set, .client_certificate must also be + * set. + * + *

      If omitted or null, mTLS is not used. + */ + @JsonProperty(KEY_FILE) + @Nullable + public String getKeyFile() { + if (keyFile == null) { + return ExtensionPropertyUtil.getGraduated(KEY_FILE, extensionProperties, String.class); + } + return keyFile; + } + + @JsonProperty(KEY_FILE) + public HttpTlsModel setKeyFile(String keyFile) { + this.keyFile = keyFile; + return this; + } + + /** + * Configure mTLS client certificate. + * + *

      Absolute path to client certificate file in PEM format. If set, .client_key must also be + * set. + * + *

      If omitted or null, mTLS is not used. + */ + @JsonProperty(CERT_FILE) + @Nullable + public String getCertFile() { + if (certFile == null) { + return ExtensionPropertyUtil.getGraduated(CERT_FILE, extensionProperties, String.class); + } + return certFile; + } + + @JsonProperty(CERT_FILE) + public HttpTlsModel setCertFile(String certFile) { + this.certFile = certFile; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public HttpTlsModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "HttpTlsModel{" + + "caFile=" + + caFile + + ", keyFile=" + + keyFile + + ", certFile=" + + certFile + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getCaFile() == null) ? 0 : this.getCaFile().hashCode(); + h *= 1000003; + h ^= (this.getKeyFile() == null) ? 0 : this.getKeyFile().hashCode(); + h *= 1000003; + h ^= (this.getCertFile() == null) ? 0 : this.getCertFile().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof HttpTlsModel) { + HttpTlsModel that = (HttpTlsModel) o; + return (this.getCaFile() == null + ? that.getCaFile() == null + : this.getCaFile().equals(that.getCaFile())) + && (this.getKeyFile() == null + ? that.getKeyFile() == null + : this.getKeyFile().equals(that.getKeyFile())) + && (this.getCertFile() == null + ? that.getCertFile() == null + : this.getCertFile().equals(that.getCertFile())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/IdGeneratorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/IdGeneratorModel.java new file mode 100644 index 00000000000..135d760554b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/IdGeneratorModel.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IdGeneratorModel.RANDOM; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({RANDOM}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class IdGeneratorModel { + + static final String RANDOM = "random"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(RANDOM, RandomIdGeneratorModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private RandomIdGeneratorModel random; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure the ID generator to randomly generate TraceIds and SpanIds (spec default). + * + *

      If omitted, ignore. + */ + @JsonProperty(RANDOM) + @Nullable + public RandomIdGeneratorModel getRandom() { + if (random == null) { + return ExtensionPropertyUtil.getGraduated( + RANDOM, extensionProperties, RandomIdGeneratorModel.class); + } + return random; + } + + @JsonProperty(RANDOM) + public IdGeneratorModel setRandom(RandomIdGeneratorModel random) { + this.random = random; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public IdGeneratorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "IdGeneratorModel{" + + "random=" + + random + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getRandom() == null) ? 0 : this.getRandom().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof IdGeneratorModel) { + IdGeneratorModel that = (IdGeneratorModel) o; + return (this.getRandom() == null + ? that.getRandom() == null + : this.getRandom().equals(that.getRandom())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/IncludeExcludeModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/IncludeExcludeModel.java new file mode 100644 index 00000000000..0083b9bd4df --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/IncludeExcludeModel.java @@ -0,0 +1,105 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel.EXCLUDED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel.INCLUDED; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({INCLUDED, EXCLUDED}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class IncludeExcludeModel { + + static final String INCLUDED = "included"; + static final String EXCLUDED = "excluded"; + + @Nullable private List included; + @Nullable private List excluded; + + /** + * Configure list of value patterns to include. + * + *

      Matching is case-sensitive. Values are evaluated to match as follows: + * + *

      * If the value exactly matches. + * + *

      * If the value matches the wildcard pattern, where '?' matches any single character and '*' + * matches any number of characters including none. + * + *

      If omitted, all values are included. + */ + @JsonProperty(INCLUDED) + @Nullable + public List getIncluded() { + return included; + } + + @JsonProperty(INCLUDED) + public IncludeExcludeModel setIncluded(List included) { + this.included = included; + return this; + } + + /** + * Configure list of value patterns to exclude. Applies after .included (i.e. excluded has higher + * priority than included). + * + *

      Matching is case-sensitive. Values are evaluated to match as follows: + * + *

      * If the value exactly matches. + * + *

      * If the value matches the wildcard pattern, where '?' matches any single character and '*' + * matches any number of characters including none. + * + *

      If omitted, .included attributes are included. + */ + @JsonProperty(EXCLUDED) + @Nullable + public List getExcluded() { + return excluded; + } + + @JsonProperty(EXCLUDED) + public IncludeExcludeModel setExcluded(List excluded) { + this.excluded = excluded; + return this; + } + + @Override + public String toString() { + return "IncludeExcludeModel{" + "included=" + included + ", excluded=" + excluded + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.included == null) ? 0 : this.included.hashCode(); + h *= 1000003; + h ^= (this.excluded == null) ? 0 : this.excluded.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof IncludeExcludeModel) { + IncludeExcludeModel that = (IncludeExcludeModel) o; + return (this.included == null ? that.included == null : this.included.equals(that.included)) + && (this.excluded == null ? that.excluded == null : this.excluded.equals(that.excluded)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/InstrumentTypeModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/InstrumentTypeModel.java new file mode 100644 index 00000000000..3688bc27553 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/InstrumentTypeModel.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum InstrumentTypeModel { + COUNTER("counter"), + GAUGE("gauge"), + HISTOGRAM("histogram"), + OBSERVABLE_COUNTER("observable_counter"), + OBSERVABLE_GAUGE("observable_gauge"), + OBSERVABLE_UP_DOWN_COUNTER("observable_up_down_counter"), + UP_DOWN_COUNTER("up_down_counter"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (InstrumentTypeModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + InstrumentTypeModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static InstrumentTypeModel fromValue(String value) { + InstrumentTypeModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LastValueAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LastValueAggregationModel.java new file mode 100644 index 00000000000..330f719e337 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LastValueAggregationModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class LastValueAggregationModel { + + @Override + public String toString() { + return "LastValueAggregationModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof LastValueAggregationModel) { + LastValueAggregationModel that = (LastValueAggregationModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordExporterModel.java new file mode 100644 index 00000000000..b82c8203ab4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordExporterModel.java @@ -0,0 +1,180 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel.CONSOLE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel.OTLP_GRPC; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel.OTLP_HTTP; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LogRecordExporterModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({OTLP_HTTP, OTLP_GRPC, CONSOLE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class LogRecordExporterModel { + + static final String OTLP_HTTP = "otlp_http"; + static final String OTLP_GRPC = "otlp_grpc"; + static final String CONSOLE = "console"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(OTLP_HTTP, OtlpHttpExporterModel.class); + STABLE_PROPERTIES.put(OTLP_GRPC, OtlpGrpcExporterModel.class); + STABLE_PROPERTIES.put(CONSOLE, ConsoleExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private OtlpHttpExporterModel otlpHttp; + @Nullable private OtlpGrpcExporterModel otlpGrpc; + @Nullable private ConsoleExporterModel console; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure exporter to be OTLP with HTTP transport. + * + *

      If omitted, ignore. + */ + @JsonProperty(OTLP_HTTP) + @Nullable + public OtlpHttpExporterModel getOtlpHttp() { + if (otlpHttp == null) { + return ExtensionPropertyUtil.getGraduated( + OTLP_HTTP, extensionProperties, OtlpHttpExporterModel.class); + } + return otlpHttp; + } + + @JsonProperty(OTLP_HTTP) + public LogRecordExporterModel setOtlpHttp(OtlpHttpExporterModel otlpHttp) { + this.otlpHttp = otlpHttp; + return this; + } + + /** + * Configure exporter to be OTLP with gRPC transport. + * + *

      If omitted, ignore. + */ + @JsonProperty(OTLP_GRPC) + @Nullable + public OtlpGrpcExporterModel getOtlpGrpc() { + if (otlpGrpc == null) { + return ExtensionPropertyUtil.getGraduated( + OTLP_GRPC, extensionProperties, OtlpGrpcExporterModel.class); + } + return otlpGrpc; + } + + @JsonProperty(OTLP_GRPC) + public LogRecordExporterModel setOtlpGrpc(OtlpGrpcExporterModel otlpGrpc) { + this.otlpGrpc = otlpGrpc; + return this; + } + + /** + * Configure exporter to be console. + * + *

      If omitted, ignore. + */ + @JsonProperty(CONSOLE) + @Nullable + public ConsoleExporterModel getConsole() { + if (console == null) { + return ExtensionPropertyUtil.getGraduated( + CONSOLE, extensionProperties, ConsoleExporterModel.class); + } + return console; + } + + @JsonProperty(CONSOLE) + public LogRecordExporterModel setConsole(ConsoleExporterModel console) { + this.console = console; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public LogRecordExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "LogRecordExporterModel{" + + "otlpHttp=" + + otlpHttp + + ", otlpGrpc=" + + otlpGrpc + + ", console=" + + console + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getOtlpHttp() == null) ? 0 : this.getOtlpHttp().hashCode(); + h *= 1000003; + h ^= (this.getOtlpGrpc() == null) ? 0 : this.getOtlpGrpc().hashCode(); + h *= 1000003; + h ^= (this.getConsole() == null) ? 0 : this.getConsole().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof LogRecordExporterModel) { + LogRecordExporterModel that = (LogRecordExporterModel) o; + return (this.getOtlpHttp() == null + ? that.getOtlpHttp() == null + : this.getOtlpHttp().equals(that.getOtlpHttp())) + && (this.getOtlpGrpc() == null + ? that.getOtlpGrpc() == null + : this.getOtlpGrpc().equals(that.getOtlpGrpc())) + && (this.getConsole() == null + ? that.getConsole() == null + : this.getConsole().equals(that.getConsole())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordLimitsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordLimitsModel.java new file mode 100644 index 00000000000..b0801cc5c1f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordLimitsModel.java @@ -0,0 +1,202 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel.ATTRIBUTE_COUNT_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel.ATTRIBUTE_VALUE_DEPTH_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel.ATTRIBUTE_VALUE_LENGTH_LIMIT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ATTRIBUTE_VALUE_LENGTH_LIMIT, + ATTRIBUTE_VALUE_DEPTH_LIMIT, + ATTRIBUTE_COUNT_LIMIT +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class LogRecordLimitsModel { + + static final String ATTRIBUTE_VALUE_LENGTH_LIMIT = "attribute_value_length_limit"; + static final String ATTRIBUTE_VALUE_DEPTH_LIMIT = "attribute_value_depth_limit"; + static final String ATTRIBUTE_COUNT_LIMIT = "attribute_count_limit"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ATTRIBUTE_VALUE_LENGTH_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_VALUE_DEPTH_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_COUNT_LIMIT, Integer.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer attributeValueLengthLimit; + @Nullable private Integer attributeValueDepthLimit; + @Nullable private Integer attributeCountLimit; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure max attribute value size. Overrides .attribute_limits.attribute_value_length_limit. + * + *

      Value must be non-negative. + * + *

      If omitted or null, there is no limit. + */ + @JsonProperty(ATTRIBUTE_VALUE_LENGTH_LIMIT) + @Nullable + public Integer getAttributeValueLengthLimit() { + if (attributeValueLengthLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_VALUE_LENGTH_LIMIT, extensionProperties, Integer.class); + } + return attributeValueLengthLimit; + } + + @JsonProperty(ATTRIBUTE_VALUE_LENGTH_LIMIT) + public LogRecordLimitsModel setAttributeValueLengthLimit(Integer attributeValueLengthLimit) { + this.attributeValueLengthLimit = attributeValueLengthLimit; + return this; + } + + /** + * Configure the maximum attribute value depth for nested array and map values. Overrides + * .attribute_limits.attribute_value_depth_limit. + * + *

      Depth starts at 1 for the top-level attribute value and increments when descending into + * array elements or map values. + * + *

      Array or map values deeper than the limit are replaced with an empty value. + * + *

      Value must be positive. + * + *

      If omitted or null, 64 is used. + */ + @JsonProperty(ATTRIBUTE_VALUE_DEPTH_LIMIT) + @Nullable + public Integer getAttributeValueDepthLimit() { + if (attributeValueDepthLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_VALUE_DEPTH_LIMIT, extensionProperties, Integer.class); + } + return attributeValueDepthLimit; + } + + @JsonProperty(ATTRIBUTE_VALUE_DEPTH_LIMIT) + public LogRecordLimitsModel setAttributeValueDepthLimit(Integer attributeValueDepthLimit) { + this.attributeValueDepthLimit = attributeValueDepthLimit; + return this; + } + + /** + * Configure max attribute count. Overrides .attribute_limits.attribute_count_limit. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(ATTRIBUTE_COUNT_LIMIT) + @Nullable + public Integer getAttributeCountLimit() { + if (attributeCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_COUNT_LIMIT, extensionProperties, Integer.class); + } + return attributeCountLimit; + } + + @JsonProperty(ATTRIBUTE_COUNT_LIMIT) + public LogRecordLimitsModel setAttributeCountLimit(Integer attributeCountLimit) { + this.attributeCountLimit = attributeCountLimit; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public LogRecordLimitsModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "LogRecordLimitsModel{" + + "attributeValueLengthLimit=" + + attributeValueLengthLimit + + ", attributeValueDepthLimit=" + + attributeValueDepthLimit + + ", attributeCountLimit=" + + attributeCountLimit + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= + (this.getAttributeValueLengthLimit() == null) + ? 0 + : this.getAttributeValueLengthLimit().hashCode(); + h *= 1000003; + h ^= + (this.getAttributeValueDepthLimit() == null) + ? 0 + : this.getAttributeValueDepthLimit().hashCode(); + h *= 1000003; + h ^= (this.getAttributeCountLimit() == null) ? 0 : this.getAttributeCountLimit().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof LogRecordLimitsModel) { + LogRecordLimitsModel that = (LogRecordLimitsModel) o; + return (this.getAttributeValueLengthLimit() == null + ? that.getAttributeValueLengthLimit() == null + : this.getAttributeValueLengthLimit().equals(that.getAttributeValueLengthLimit())) + && (this.getAttributeValueDepthLimit() == null + ? that.getAttributeValueDepthLimit() == null + : this.getAttributeValueDepthLimit().equals(that.getAttributeValueDepthLimit())) + && (this.getAttributeCountLimit() == null + ? that.getAttributeCountLimit() == null + : this.getAttributeCountLimit().equals(that.getAttributeCountLimit())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordProcessorModel.java new file mode 100644 index 00000000000..1e89db7e4ec --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LogRecordProcessorModel.java @@ -0,0 +1,148 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel.BATCH; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel.SIMPLE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LogRecordProcessorModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({BATCH, SIMPLE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class LogRecordProcessorModel { + + static final String BATCH = "batch"; + static final String SIMPLE = "simple"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(BATCH, BatchLogRecordProcessorModel.class); + STABLE_PROPERTIES.put(SIMPLE, SimpleLogRecordProcessorModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private BatchLogRecordProcessorModel batch; + @Nullable private SimpleLogRecordProcessorModel simple; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure a batch log record processor. + * + *

      If omitted, ignore. + */ + @JsonProperty(BATCH) + @Nullable + public BatchLogRecordProcessorModel getBatch() { + if (batch == null) { + return ExtensionPropertyUtil.getGraduated( + BATCH, extensionProperties, BatchLogRecordProcessorModel.class); + } + return batch; + } + + @JsonProperty(BATCH) + public LogRecordProcessorModel setBatch(BatchLogRecordProcessorModel batch) { + this.batch = batch; + return this; + } + + /** + * Configure a simple log record processor. + * + *

      If omitted, ignore. + */ + @JsonProperty(SIMPLE) + @Nullable + public SimpleLogRecordProcessorModel getSimple() { + if (simple == null) { + return ExtensionPropertyUtil.getGraduated( + SIMPLE, extensionProperties, SimpleLogRecordProcessorModel.class); + } + return simple; + } + + @JsonProperty(SIMPLE) + public LogRecordProcessorModel setSimple(SimpleLogRecordProcessorModel simple) { + this.simple = simple; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public LogRecordProcessorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "LogRecordProcessorModel{" + + "batch=" + + batch + + ", simple=" + + simple + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getBatch() == null) ? 0 : this.getBatch().hashCode(); + h *= 1000003; + h ^= (this.getSimple() == null) ? 0 : this.getSimple().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof LogRecordProcessorModel) { + LogRecordProcessorModel that = (LogRecordProcessorModel) o; + return (this.getBatch() == null + ? that.getBatch() == null + : this.getBatch().equals(that.getBatch())) + && (this.getSimple() == null + ? that.getSimple() == null + : this.getSimple().equals(that.getSimple())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LoggerProviderModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LoggerProviderModel.java new file mode 100644 index 00000000000..136070810b7 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/LoggerProviderModel.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel.LIMITS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel.PROCESSORS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LoggerProviderModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({PROCESSORS, LIMITS}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class LoggerProviderModel { + + static final String PROCESSORS = "processors"; + static final String LIMITS = "limits"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(LIMITS, LogRecordLimitsModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private List processors; + @Nullable private LogRecordLimitsModel limits; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure log record processors. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(PROCESSORS) + @Nullable + public List getProcessors() { + return processors; + } + + @JsonProperty(PROCESSORS) + public LoggerProviderModel setProcessors(List processors) { + this.processors = processors; + return this; + } + + /** + * Configure log record limits. See also attribute_limits. + * + *

      If omitted, default values as described in LogRecordLimits are used. + */ + @JsonProperty(LIMITS) + @Nullable + public LogRecordLimitsModel getLimits() { + if (limits == null) { + return ExtensionPropertyUtil.getGraduated( + LIMITS, extensionProperties, LogRecordLimitsModel.class); + } + return limits; + } + + @JsonProperty(LIMITS) + public LoggerProviderModel setLimits(LogRecordLimitsModel limits) { + this.limits = limits; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public LoggerProviderModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "LoggerProviderModel{" + + "processors=" + + processors + + ", limits=" + + limits + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.processors == null) ? 0 : this.processors.hashCode(); + h *= 1000003; + h ^= (this.getLimits() == null) ? 0 : this.getLimits().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof LoggerProviderModel) { + LoggerProviderModel that = (LoggerProviderModel) o; + return (this.processors == null + ? that.processors == null + : this.processors.equals(that.processors)) + && (this.getLimits() == null + ? that.getLimits() == null + : this.getLimits().equals(that.getLimits())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MeterProviderModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MeterProviderModel.java new file mode 100644 index 00000000000..670dec85cbd --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MeterProviderModel.java @@ -0,0 +1,179 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel.EXEMPLAR_FILTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel.READERS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel.VIEWS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.MeterProviderModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({READERS, VIEWS, EXEMPLAR_FILTER}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class MeterProviderModel { + + static final String READERS = "readers"; + static final String VIEWS = "views"; + static final String EXEMPLAR_FILTER = "exemplar_filter"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(EXEMPLAR_FILTER, ExemplarFilterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private List readers; + @Nullable private List views; + @Nullable private ExemplarFilterModel exemplarFilter; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure metric readers. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(READERS) + @Nullable + public List getReaders() { + return readers; + } + + @JsonProperty(READERS) + public MeterProviderModel setReaders(List readers) { + this.readers = readers; + return this; + } + + /** + * Configure views. + * + *

      Each view has a selector which determines the instrument(s) it applies to, and a + * configuration for the resulting stream(s). + * + *

      If omitted, no views are registered. + */ + @JsonProperty(VIEWS) + @Nullable + public List getViews() { + return views; + } + + @JsonProperty(VIEWS) + public MeterProviderModel setViews(List views) { + this.views = views; + return this; + } + + /** + * Configure the exemplar filter. + * + *

      Values include: + * + *

      * always_off: ExemplarFilter which makes no measurements eligible for being an Exemplar. + * + *

      * always_on: ExemplarFilter which makes all measurements eligible for being an Exemplar. + * + *

      * trace_based: ExemplarFilter which makes measurements recorded in the context of a sampled + * parent span eligible for being an Exemplar. + * + *

      If omitted, trace_based is used. + */ + @JsonProperty(EXEMPLAR_FILTER) + @Nullable + public ExemplarFilterModel getExemplarFilter() { + if (exemplarFilter == null) { + return ExtensionPropertyUtil.getGraduated( + EXEMPLAR_FILTER, extensionProperties, ExemplarFilterModel.class); + } + return exemplarFilter; + } + + @JsonProperty(EXEMPLAR_FILTER) + public MeterProviderModel setExemplarFilter(ExemplarFilterModel exemplarFilter) { + this.exemplarFilter = exemplarFilter; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public MeterProviderModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "MeterProviderModel{" + + "readers=" + + readers + + ", views=" + + views + + ", exemplarFilter=" + + exemplarFilter + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.readers == null) ? 0 : this.readers.hashCode(); + h *= 1000003; + h ^= (this.views == null) ? 0 : this.views.hashCode(); + h *= 1000003; + h ^= (this.getExemplarFilter() == null) ? 0 : this.getExemplarFilter().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof MeterProviderModel) { + MeterProviderModel that = (MeterProviderModel) o; + return (this.readers == null ? that.readers == null : this.readers.equals(that.readers)) + && (this.views == null ? that.views == null : this.views.equals(that.views)) + && (this.getExemplarFilter() == null + ? that.getExemplarFilter() == null + : this.getExemplarFilter().equals(that.getExemplarFilter())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MetricProducerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MetricProducerModel.java new file mode 100644 index 00000000000..ec78ceb0383 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MetricProducerModel.java @@ -0,0 +1,126 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricProducerModel.OPENCENSUS; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({OPENCENSUS}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class MetricProducerModel { + + static final String OPENCENSUS = "opencensus"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(OPENCENSUS, OpenCensusMetricProducerModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private OpenCensusMetricProducerModel opencensus; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure metric producer to be opencensus. + * + *

      **Deprecated** as of v1.2.0, may be removed in v2.0.0. The OpenCensus + * + *

      compatibility specification it relies on was deprecated in + * + *

      https://github.com/open-telemetry/opentelemetry-specification/pull/5138. + * + *

      SDKs MAY continue to support this entry for backwards compatibility; + * + *

      new configurations SHOULD NOT use it. + * + *

      If omitted, ignore. + */ + @JsonProperty(OPENCENSUS) + @Nullable + public OpenCensusMetricProducerModel getOpencensus() { + if (opencensus == null) { + return ExtensionPropertyUtil.getGraduated( + OPENCENSUS, extensionProperties, OpenCensusMetricProducerModel.class); + } + return opencensus; + } + + @JsonProperty(OPENCENSUS) + public MetricProducerModel setOpencensus(OpenCensusMetricProducerModel opencensus) { + this.opencensus = opencensus; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public MetricProducerModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "MetricProducerModel{" + + "opencensus=" + + opencensus + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getOpencensus() == null) ? 0 : this.getOpencensus().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof MetricProducerModel) { + MetricProducerModel that = (MetricProducerModel) o; + return (this.getOpencensus() == null + ? that.getOpencensus() == null + : this.getOpencensus().equals(that.getOpencensus())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MetricReaderModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MetricReaderModel.java new file mode 100644 index 00000000000..359b53b209b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/MetricReaderModel.java @@ -0,0 +1,148 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel.PERIODIC; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel.PULL; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({PERIODIC, PULL}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class MetricReaderModel { + + static final String PERIODIC = "periodic"; + static final String PULL = "pull"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(PERIODIC, PeriodicMetricReaderModel.class); + STABLE_PROPERTIES.put(PULL, PullMetricReaderModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private PeriodicMetricReaderModel periodic; + @Nullable private PullMetricReaderModel pull; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure a periodic metric reader. + * + *

      If omitted, ignore. + */ + @JsonProperty(PERIODIC) + @Nullable + public PeriodicMetricReaderModel getPeriodic() { + if (periodic == null) { + return ExtensionPropertyUtil.getGraduated( + PERIODIC, extensionProperties, PeriodicMetricReaderModel.class); + } + return periodic; + } + + @JsonProperty(PERIODIC) + public MetricReaderModel setPeriodic(PeriodicMetricReaderModel periodic) { + this.periodic = periodic; + return this; + } + + /** + * Configure a pull based metric reader. + * + *

      If omitted, ignore. + */ + @JsonProperty(PULL) + @Nullable + public PullMetricReaderModel getPull() { + if (pull == null) { + return ExtensionPropertyUtil.getGraduated( + PULL, extensionProperties, PullMetricReaderModel.class); + } + return pull; + } + + @JsonProperty(PULL) + public MetricReaderModel setPull(PullMetricReaderModel pull) { + this.pull = pull; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public MetricReaderModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "MetricReaderModel{" + + "periodic=" + + periodic + + ", pull=" + + pull + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getPeriodic() == null) ? 0 : this.getPeriodic().hashCode(); + h *= 1000003; + h ^= (this.getPull() == null) ? 0 : this.getPull().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof MetricReaderModel) { + MetricReaderModel that = (MetricReaderModel) o; + return (this.getPeriodic() == null + ? that.getPeriodic() == null + : this.getPeriodic().equals(that.getPeriodic())) + && (this.getPull() == null + ? that.getPull() == null + : this.getPull().equals(that.getPull())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/NameStringValuePairModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/NameStringValuePairModel.java new file mode 100644 index 00000000000..805182d77b0 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/NameStringValuePairModel.java @@ -0,0 +1,146 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.NameStringValuePairModel.NAME; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.NameStringValuePairModel.VALUE; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({NAME, VALUE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class NameStringValuePairModel { + + static final String NAME = "name"; + static final String VALUE = "value"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(NAME, String.class); + STABLE_PROPERTIES.put(VALUE, String.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String name; + @Nullable private String value; + private Map extensionProperties = new LinkedHashMap(); + + /** + * The name of the pair. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(NAME) + @Nullable + public String getName() { + if (name == null) { + return ExtensionPropertyUtil.getGraduated(NAME, extensionProperties, String.class); + } + return name; + } + + @JsonProperty(NAME) + public NameStringValuePairModel setName(String name) { + this.name = name; + return this; + } + + /** + * The value of the pair. + * + *

      Property must be present, but if null the behavior is dependent on usage context. + */ + @JsonProperty(VALUE) + @Nullable + public String getValue() { + if (value == null) { + return ExtensionPropertyUtil.getGraduated(VALUE, extensionProperties, String.class); + } + return value; + } + + @JsonProperty(VALUE) + public NameStringValuePairModel setValue(String value) { + this.value = value; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public NameStringValuePairModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "NameStringValuePairModel{" + + "name=" + + name + + ", value=" + + value + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getName() == null) ? 0 : this.getName().hashCode(); + h *= 1000003; + h ^= (this.getValue() == null) ? 0 : this.getValue().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof NameStringValuePairModel) { + NameStringValuePairModel that = (NameStringValuePairModel) o; + return (this.getName() == null + ? that.getName() == null + : this.getName().equals(that.getName())) + && (this.getValue() == null + ? that.getValue() == null + : this.getValue().equals(that.getValue())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OpenCensusMetricProducerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OpenCensusMetricProducerModel.java new file mode 100644 index 00000000000..d9589cf6ccd --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OpenCensusMetricProducerModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class OpenCensusMetricProducerModel { + + @Override + public String toString() { + return "OpenCensusMetricProducerModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof OpenCensusMetricProducerModel) { + OpenCensusMetricProducerModel that = (OpenCensusMetricProducerModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OpenTelemetryConfigurationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OpenTelemetryConfigurationModel.java new file mode 100644 index 00000000000..2aaf10e7b88 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OpenTelemetryConfigurationModel.java @@ -0,0 +1,477 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.ATTRIBUTE_LIMITS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.DISABLED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.DISTRIBUTION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.FILE_FORMAT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.LOGGER_PROVIDER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.LOG_LEVEL; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.METER_PROVIDER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.PROPAGATOR; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.RESOURCE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel.TRACER_PROVIDER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.OpenTelemetryConfigurationModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + FILE_FORMAT, + DISABLED, + LOG_LEVEL, + ATTRIBUTE_LIMITS, + LOGGER_PROVIDER, + METER_PROVIDER, + PROPAGATOR, + TRACER_PROVIDER, + RESOURCE, + DISTRIBUTION +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class OpenTelemetryConfigurationModel { + + static final String FILE_FORMAT = "file_format"; + static final String DISABLED = "disabled"; + static final String LOG_LEVEL = "log_level"; + static final String ATTRIBUTE_LIMITS = "attribute_limits"; + static final String LOGGER_PROVIDER = "logger_provider"; + static final String METER_PROVIDER = "meter_provider"; + static final String PROPAGATOR = "propagator"; + static final String TRACER_PROVIDER = "tracer_provider"; + static final String RESOURCE = "resource"; + static final String DISTRIBUTION = "distribution"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(FILE_FORMAT, String.class); + STABLE_PROPERTIES.put(DISABLED, Boolean.class); + STABLE_PROPERTIES.put(LOG_LEVEL, SeverityNumberModel.class); + STABLE_PROPERTIES.put(ATTRIBUTE_LIMITS, AttributeLimitsModel.class); + STABLE_PROPERTIES.put(LOGGER_PROVIDER, LoggerProviderModel.class); + STABLE_PROPERTIES.put(METER_PROVIDER, MeterProviderModel.class); + STABLE_PROPERTIES.put(PROPAGATOR, PropagatorModel.class); + STABLE_PROPERTIES.put(TRACER_PROVIDER, TracerProviderModel.class); + STABLE_PROPERTIES.put(RESOURCE, ResourceModel.class); + STABLE_PROPERTIES.put(DISTRIBUTION, DistributionModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private String fileFormat; + @Nullable private Boolean disabled; + @Nullable private SeverityNumberModel logLevel; + @Nullable private AttributeLimitsModel attributeLimits; + @Nullable private LoggerProviderModel loggerProvider; + @Nullable private MeterProviderModel meterProvider; + @Nullable private PropagatorModel propagator; + @Nullable private TracerProviderModel tracerProvider; + @Nullable private ResourceModel resource; + @Nullable private DistributionModel distribution; + private Map extensionProperties = new LinkedHashMap(); + + /** + * The file format version. + * + *

      Represented as a string including the semver major, minor version numbers (and optionally + * the meta tag). For example: "0.4", "1.0-rc.2", "1.0" (after stable release). + * + *

      See https://github.com/open-telemetry/opentelemetry-configuration/blob/main/VERSIONING.md + * for more details. + * + *

      The yaml format is documented at + * https://github.com/open-telemetry/opentelemetry-configuration/tree/main/schema + * + *

      Property is required and must be non-null. + */ + @JsonProperty(FILE_FORMAT) + @Nullable + public String getFileFormat() { + if (fileFormat == null) { + return ExtensionPropertyUtil.getGraduated(FILE_FORMAT, extensionProperties, String.class); + } + return fileFormat; + } + + @JsonProperty(FILE_FORMAT) + public OpenTelemetryConfigurationModel setFileFormat(String fileFormat) { + this.fileFormat = fileFormat; + return this; + } + + /** + * Configure if the SDK is disabled or not. + * + *

      If omitted or null, false is used. + */ + @JsonProperty(DISABLED) + @Nullable + public Boolean getDisabled() { + if (disabled == null) { + return ExtensionPropertyUtil.getGraduated(DISABLED, extensionProperties, Boolean.class); + } + return disabled; + } + + @JsonProperty(DISABLED) + public OpenTelemetryConfigurationModel setDisabled(Boolean disabled) { + this.disabled = disabled; + return this; + } + + /** + * Configure the log level of the internal logger used by the SDK. + * + *

      Values include: + * + *

      * debug: debug, severity number 5. + * + *

      * debug2: debug2, severity number 6. + * + *

      * debug3: debug3, severity number 7. + * + *

      * debug4: debug4, severity number 8. + * + *

      * error: error, severity number 17. + * + *

      * error2: error2, severity number 18. + * + *

      * error3: error3, severity number 19. + * + *

      * error4: error4, severity number 20. + * + *

      * fatal: fatal, severity number 21. + * + *

      * fatal2: fatal2, severity number 22. + * + *

      * fatal3: fatal3, severity number 23. + * + *

      * fatal4: fatal4, severity number 24. + * + *

      * info: info, severity number 9. + * + *

      * info2: info2, severity number 10. + * + *

      * info3: info3, severity number 11. + * + *

      * info4: info4, severity number 12. + * + *

      * trace: trace, severity number 1. + * + *

      * trace2: trace2, severity number 2. + * + *

      * trace3: trace3, severity number 3. + * + *

      * trace4: trace4, severity number 4. + * + *

      * warn: warn, severity number 13. + * + *

      * warn2: warn2, severity number 14. + * + *

      * warn3: warn3, severity number 15. + * + *

      * warn4: warn4, severity number 16. + * + *

      If omitted, INFO is used. + */ + @JsonProperty(LOG_LEVEL) + @Nullable + public SeverityNumberModel getLogLevel() { + if (logLevel == null) { + return ExtensionPropertyUtil.getGraduated( + LOG_LEVEL, extensionProperties, SeverityNumberModel.class); + } + return logLevel; + } + + @JsonProperty(LOG_LEVEL) + public OpenTelemetryConfigurationModel setLogLevel(SeverityNumberModel logLevel) { + this.logLevel = logLevel; + return this; + } + + /** + * Configure general attribute limits. See also tracer_provider.limits, logger_provider.limits. + * + *

      If omitted, default values as described in AttributeLimits are used. + */ + @JsonProperty(ATTRIBUTE_LIMITS) + @Nullable + public AttributeLimitsModel getAttributeLimits() { + if (attributeLimits == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_LIMITS, extensionProperties, AttributeLimitsModel.class); + } + return attributeLimits; + } + + @JsonProperty(ATTRIBUTE_LIMITS) + public OpenTelemetryConfigurationModel setAttributeLimits(AttributeLimitsModel attributeLimits) { + this.attributeLimits = attributeLimits; + return this; + } + + /** + * Configure logger provider. + * + *

      If omitted, a noop logger provider is used. + */ + @JsonProperty(LOGGER_PROVIDER) + @Nullable + public LoggerProviderModel getLoggerProvider() { + if (loggerProvider == null) { + return ExtensionPropertyUtil.getGraduated( + LOGGER_PROVIDER, extensionProperties, LoggerProviderModel.class); + } + return loggerProvider; + } + + @JsonProperty(LOGGER_PROVIDER) + public OpenTelemetryConfigurationModel setLoggerProvider(LoggerProviderModel loggerProvider) { + this.loggerProvider = loggerProvider; + return this; + } + + /** + * Configure meter provider. + * + *

      If omitted, a noop meter provider is used. + */ + @JsonProperty(METER_PROVIDER) + @Nullable + public MeterProviderModel getMeterProvider() { + if (meterProvider == null) { + return ExtensionPropertyUtil.getGraduated( + METER_PROVIDER, extensionProperties, MeterProviderModel.class); + } + return meterProvider; + } + + @JsonProperty(METER_PROVIDER) + public OpenTelemetryConfigurationModel setMeterProvider(MeterProviderModel meterProvider) { + this.meterProvider = meterProvider; + return this; + } + + /** + * Configure text map context propagators. + * + *

      If omitted, a noop propagator is used. + */ + @JsonProperty(PROPAGATOR) + @Nullable + public PropagatorModel getPropagator() { + if (propagator == null) { + return ExtensionPropertyUtil.getGraduated( + PROPAGATOR, extensionProperties, PropagatorModel.class); + } + return propagator; + } + + @JsonProperty(PROPAGATOR) + public OpenTelemetryConfigurationModel setPropagator(PropagatorModel propagator) { + this.propagator = propagator; + return this; + } + + /** + * Configure tracer provider. + * + *

      If omitted, a noop tracer provider is used. + */ + @JsonProperty(TRACER_PROVIDER) + @Nullable + public TracerProviderModel getTracerProvider() { + if (tracerProvider == null) { + return ExtensionPropertyUtil.getGraduated( + TRACER_PROVIDER, extensionProperties, TracerProviderModel.class); + } + return tracerProvider; + } + + @JsonProperty(TRACER_PROVIDER) + public OpenTelemetryConfigurationModel setTracerProvider(TracerProviderModel tracerProvider) { + this.tracerProvider = tracerProvider; + return this; + } + + /** + * Configure resource for all signals. + * + *

      If omitted, the default resource is used. + */ + @JsonProperty(RESOURCE) + @Nullable + public ResourceModel getResource() { + if (resource == null) { + return ExtensionPropertyUtil.getGraduated(RESOURCE, extensionProperties, ResourceModel.class); + } + return resource; + } + + @JsonProperty(RESOURCE) + public OpenTelemetryConfigurationModel setResource(ResourceModel resource) { + this.resource = resource; + return this; + } + + /** + * Defines configuration parameters specific to a particular OpenTelemetry distribution or vendor. + * + *

      This section provides a standardized location for distribution-specific settings + * + *

      that are not part of the OpenTelemetry configuration model. + * + *

      It allows vendors to expose their own extensions and general configuration options. + * + *

      If omitted, distribution defaults are used. + */ + @JsonProperty(DISTRIBUTION) + @Nullable + public DistributionModel getDistribution() { + if (distribution == null) { + return ExtensionPropertyUtil.getGraduated( + DISTRIBUTION, extensionProperties, DistributionModel.class); + } + return distribution; + } + + @JsonProperty(DISTRIBUTION) + public OpenTelemetryConfigurationModel setDistribution(DistributionModel distribution) { + this.distribution = distribution; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public OpenTelemetryConfigurationModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "OpenTelemetryConfigurationModel{" + + "fileFormat=" + + fileFormat + + ", disabled=" + + disabled + + ", logLevel=" + + logLevel + + ", attributeLimits=" + + attributeLimits + + ", loggerProvider=" + + loggerProvider + + ", meterProvider=" + + meterProvider + + ", propagator=" + + propagator + + ", tracerProvider=" + + tracerProvider + + ", resource=" + + resource + + ", distribution=" + + distribution + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getFileFormat() == null) ? 0 : this.getFileFormat().hashCode(); + h *= 1000003; + h ^= (this.getDisabled() == null) ? 0 : this.getDisabled().hashCode(); + h *= 1000003; + h ^= (this.getLogLevel() == null) ? 0 : this.getLogLevel().hashCode(); + h *= 1000003; + h ^= (this.getAttributeLimits() == null) ? 0 : this.getAttributeLimits().hashCode(); + h *= 1000003; + h ^= (this.getLoggerProvider() == null) ? 0 : this.getLoggerProvider().hashCode(); + h *= 1000003; + h ^= (this.getMeterProvider() == null) ? 0 : this.getMeterProvider().hashCode(); + h *= 1000003; + h ^= (this.getPropagator() == null) ? 0 : this.getPropagator().hashCode(); + h *= 1000003; + h ^= (this.getTracerProvider() == null) ? 0 : this.getTracerProvider().hashCode(); + h *= 1000003; + h ^= (this.getResource() == null) ? 0 : this.getResource().hashCode(); + h *= 1000003; + h ^= (this.getDistribution() == null) ? 0 : this.getDistribution().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof OpenTelemetryConfigurationModel) { + OpenTelemetryConfigurationModel that = (OpenTelemetryConfigurationModel) o; + return (this.getFileFormat() == null + ? that.getFileFormat() == null + : this.getFileFormat().equals(that.getFileFormat())) + && (this.getDisabled() == null + ? that.getDisabled() == null + : this.getDisabled().equals(that.getDisabled())) + && (this.getLogLevel() == null + ? that.getLogLevel() == null + : this.getLogLevel().equals(that.getLogLevel())) + && (this.getAttributeLimits() == null + ? that.getAttributeLimits() == null + : this.getAttributeLimits().equals(that.getAttributeLimits())) + && (this.getLoggerProvider() == null + ? that.getLoggerProvider() == null + : this.getLoggerProvider().equals(that.getLoggerProvider())) + && (this.getMeterProvider() == null + ? that.getMeterProvider() == null + : this.getMeterProvider().equals(that.getMeterProvider())) + && (this.getPropagator() == null + ? that.getPropagator() == null + : this.getPropagator().equals(that.getPropagator())) + && (this.getTracerProvider() == null + ? that.getTracerProvider() == null + : this.getTracerProvider().equals(that.getTracerProvider())) + && (this.getResource() == null + ? that.getResource() == null + : this.getResource().equals(that.getResource())) + && (this.getDistribution() == null + ? that.getDistribution() == null + : this.getDistribution().equals(that.getDistribution())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpGrpcExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpGrpcExporterModel.java new file mode 100644 index 00000000000..563d49e6bce --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpGrpcExporterModel.java @@ -0,0 +1,352 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.COMPRESSION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.ENDPOINT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.HEADERS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.HEADERS_LIST; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.MAX_REQUEST_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.MAX_RESPONSE_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel.TLS; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ENDPOINT, + TLS, + HEADERS, + HEADERS_LIST, + COMPRESSION, + MAX_REQUEST_SIZE, + MAX_RESPONSE_SIZE, + TIMEOUT +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class OtlpGrpcExporterModel { + + static final String ENDPOINT = "endpoint"; + static final String TLS = "tls"; + static final String HEADERS = "headers"; + static final String HEADERS_LIST = "headers_list"; + static final String COMPRESSION = "compression"; + static final String MAX_REQUEST_SIZE = "max_request_size"; + static final String MAX_RESPONSE_SIZE = "max_response_size"; + static final String TIMEOUT = "timeout"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ENDPOINT, String.class); + STABLE_PROPERTIES.put(TLS, GrpcTlsModel.class); + STABLE_PROPERTIES.put(HEADERS_LIST, String.class); + STABLE_PROPERTIES.put(COMPRESSION, String.class); + STABLE_PROPERTIES.put(MAX_REQUEST_SIZE, Integer.class); + STABLE_PROPERTIES.put(MAX_RESPONSE_SIZE, Integer.class); + STABLE_PROPERTIES.put(TIMEOUT, Integer.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String endpoint; + @Nullable private GrpcTlsModel tls; + @Nullable private List headers; + @Nullable private String headersList; + @Nullable private String compression; + @Nullable private Integer maxRequestSize; + @Nullable private Integer maxResponseSize; + @Nullable private Integer timeout; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure endpoint. + * + *

      If omitted or null, http://localhost:4317 is used. + */ + @JsonProperty(ENDPOINT) + @Nullable + public String getEndpoint() { + if (endpoint == null) { + return ExtensionPropertyUtil.getGraduated(ENDPOINT, extensionProperties, String.class); + } + return endpoint; + } + + @JsonProperty(ENDPOINT) + public OtlpGrpcExporterModel setEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * Configure TLS settings for the exporter. + * + *

      If omitted, system default TLS settings are used. + */ + @JsonProperty(TLS) + @Nullable + public GrpcTlsModel getTls() { + if (tls == null) { + return ExtensionPropertyUtil.getGraduated(TLS, extensionProperties, GrpcTlsModel.class); + } + return tls; + } + + @JsonProperty(TLS) + public OtlpGrpcExporterModel setTls(GrpcTlsModel tls) { + this.tls = tls; + return this; + } + + /** + * Configure headers. Entries have higher priority than entries from .headers_list. + * + *

      If an entry's .value is null, the entry is ignored. + * + *

      If omitted, no headers are added. + */ + @JsonProperty(HEADERS) + @Nullable + public List getHeaders() { + return headers; + } + + @JsonProperty(HEADERS) + public OtlpGrpcExporterModel setHeaders(List headers) { + this.headers = headers; + return this; + } + + /** + * Configure headers. Entries have lower priority than entries from .headers. + * + *

      The value is a list of comma separated key-value pairs matching the format of + * OTEL_EXPORTER_OTLP_HEADERS. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options + * for details. + * + *

      If omitted or null, no headers are added. + */ + @JsonProperty(HEADERS_LIST) + @Nullable + public String getHeadersList() { + if (headersList == null) { + return ExtensionPropertyUtil.getGraduated(HEADERS_LIST, extensionProperties, String.class); + } + return headersList; + } + + @JsonProperty(HEADERS_LIST) + public OtlpGrpcExporterModel setHeadersList(String headersList) { + this.headersList = headersList; + return this; + } + + /** + * Configure compression. + * + *

      Known values include: gzip, none. Implementations may support other compression algorithms. + * + *

      If omitted or null, none is used. + */ + @JsonProperty(COMPRESSION) + @Nullable + public String getCompression() { + if (compression == null) { + return ExtensionPropertyUtil.getGraduated(COMPRESSION, extensionProperties, String.class); + } + return compression; + } + + @JsonProperty(COMPRESSION) + public OtlpGrpcExporterModel setCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Configure the maximum size of each export request message in bytes, before compression. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity) and is not + * recommended. + * + *

      If omitted or null, 67108864 (64 MiB) is used. + */ + @JsonProperty(MAX_REQUEST_SIZE) + @Nullable + public Integer getMaxRequestSize() { + if (maxRequestSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_REQUEST_SIZE, extensionProperties, Integer.class); + } + return maxRequestSize; + } + + @JsonProperty(MAX_REQUEST_SIZE) + public OtlpGrpcExporterModel setMaxRequestSize(Integer maxRequestSize) { + this.maxRequestSize = maxRequestSize; + return this; + } + + /** + * Configure the maximum size of each export response in bytes, after decompression. + * + *

      Value must be positive. + * + *

      If omitted or null, 4194304 (4 MiB) is used. + */ + @JsonProperty(MAX_RESPONSE_SIZE) + @Nullable + public Integer getMaxResponseSize() { + if (maxResponseSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_RESPONSE_SIZE, extensionProperties, Integer.class); + } + return maxResponseSize; + } + + @JsonProperty(MAX_RESPONSE_SIZE) + public OtlpGrpcExporterModel setMaxResponseSize(Integer maxResponseSize) { + this.maxResponseSize = maxResponseSize; + return this; + } + + /** + * Configure max time (in milliseconds) to wait for each export. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 10000 is used. + */ + @JsonProperty(TIMEOUT) + @Nullable + public Integer getTimeout() { + if (timeout == null) { + return ExtensionPropertyUtil.getGraduated(TIMEOUT, extensionProperties, Integer.class); + } + return timeout; + } + + @JsonProperty(TIMEOUT) + public OtlpGrpcExporterModel setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public OtlpGrpcExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "OtlpGrpcExporterModel{" + + "endpoint=" + + endpoint + + ", tls=" + + tls + + ", headers=" + + headers + + ", headersList=" + + headersList + + ", compression=" + + compression + + ", maxRequestSize=" + + maxRequestSize + + ", maxResponseSize=" + + maxResponseSize + + ", timeout=" + + timeout + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getEndpoint() == null) ? 0 : this.getEndpoint().hashCode(); + h *= 1000003; + h ^= (this.getTls() == null) ? 0 : this.getTls().hashCode(); + h *= 1000003; + h ^= (this.headers == null) ? 0 : this.headers.hashCode(); + h *= 1000003; + h ^= (this.getHeadersList() == null) ? 0 : this.getHeadersList().hashCode(); + h *= 1000003; + h ^= (this.getCompression() == null) ? 0 : this.getCompression().hashCode(); + h *= 1000003; + h ^= (this.getMaxRequestSize() == null) ? 0 : this.getMaxRequestSize().hashCode(); + h *= 1000003; + h ^= (this.getMaxResponseSize() == null) ? 0 : this.getMaxResponseSize().hashCode(); + h *= 1000003; + h ^= (this.getTimeout() == null) ? 0 : this.getTimeout().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof OtlpGrpcExporterModel) { + OtlpGrpcExporterModel that = (OtlpGrpcExporterModel) o; + return (this.getEndpoint() == null + ? that.getEndpoint() == null + : this.getEndpoint().equals(that.getEndpoint())) + && (this.getTls() == null ? that.getTls() == null : this.getTls().equals(that.getTls())) + && (this.headers == null ? that.headers == null : this.headers.equals(that.headers)) + && (this.getHeadersList() == null + ? that.getHeadersList() == null + : this.getHeadersList().equals(that.getHeadersList())) + && (this.getCompression() == null + ? that.getCompression() == null + : this.getCompression().equals(that.getCompression())) + && (this.getMaxRequestSize() == null + ? that.getMaxRequestSize() == null + : this.getMaxRequestSize().equals(that.getMaxRequestSize())) + && (this.getMaxResponseSize() == null + ? that.getMaxResponseSize() == null + : this.getMaxResponseSize().equals(that.getMaxResponseSize())) + && (this.getTimeout() == null + ? that.getTimeout() == null + : this.getTimeout().equals(that.getTimeout())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpGrpcMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpGrpcMetricExporterModel.java new file mode 100644 index 00000000000..586c9c9262f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpGrpcMetricExporterModel.java @@ -0,0 +1,444 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.COMPRESSION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.DEFAULT_HISTOGRAM_AGGREGATION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.ENDPOINT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.HEADERS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.HEADERS_LIST; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.MAX_REQUEST_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.MAX_RESPONSE_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.TEMPORALITY_PREFERENCE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel.TLS; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ENDPOINT, + TLS, + HEADERS, + HEADERS_LIST, + COMPRESSION, + MAX_REQUEST_SIZE, + MAX_RESPONSE_SIZE, + TIMEOUT, + TEMPORALITY_PREFERENCE, + DEFAULT_HISTOGRAM_AGGREGATION +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class OtlpGrpcMetricExporterModel { + + static final String ENDPOINT = "endpoint"; + static final String TLS = "tls"; + static final String HEADERS = "headers"; + static final String HEADERS_LIST = "headers_list"; + static final String COMPRESSION = "compression"; + static final String MAX_REQUEST_SIZE = "max_request_size"; + static final String MAX_RESPONSE_SIZE = "max_response_size"; + static final String TIMEOUT = "timeout"; + static final String TEMPORALITY_PREFERENCE = "temporality_preference"; + static final String DEFAULT_HISTOGRAM_AGGREGATION = "default_histogram_aggregation"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ENDPOINT, String.class); + STABLE_PROPERTIES.put(TLS, GrpcTlsModel.class); + STABLE_PROPERTIES.put(HEADERS_LIST, String.class); + STABLE_PROPERTIES.put(COMPRESSION, String.class); + STABLE_PROPERTIES.put(MAX_REQUEST_SIZE, Integer.class); + STABLE_PROPERTIES.put(MAX_RESPONSE_SIZE, Integer.class); + STABLE_PROPERTIES.put(TIMEOUT, Integer.class); + STABLE_PROPERTIES.put(TEMPORALITY_PREFERENCE, ExporterTemporalityPreferenceModel.class); + STABLE_PROPERTIES.put( + DEFAULT_HISTOGRAM_AGGREGATION, ExporterDefaultHistogramAggregationModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String endpoint; + @Nullable private GrpcTlsModel tls; + @Nullable private List headers; + @Nullable private String headersList; + @Nullable private String compression; + @Nullable private Integer maxRequestSize; + @Nullable private Integer maxResponseSize; + @Nullable private Integer timeout; + @Nullable private ExporterTemporalityPreferenceModel temporalityPreference; + @Nullable private ExporterDefaultHistogramAggregationModel defaultHistogramAggregation; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure endpoint. + * + *

      If omitted or null, http://localhost:4317 is used. + */ + @JsonProperty(ENDPOINT) + @Nullable + public String getEndpoint() { + if (endpoint == null) { + return ExtensionPropertyUtil.getGraduated(ENDPOINT, extensionProperties, String.class); + } + return endpoint; + } + + @JsonProperty(ENDPOINT) + public OtlpGrpcMetricExporterModel setEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * Configure TLS settings for the exporter. + * + *

      If omitted, system default TLS settings are used. + */ + @JsonProperty(TLS) + @Nullable + public GrpcTlsModel getTls() { + if (tls == null) { + return ExtensionPropertyUtil.getGraduated(TLS, extensionProperties, GrpcTlsModel.class); + } + return tls; + } + + @JsonProperty(TLS) + public OtlpGrpcMetricExporterModel setTls(GrpcTlsModel tls) { + this.tls = tls; + return this; + } + + /** + * Configure headers. Entries have higher priority than entries from .headers_list. + * + *

      If an entry's .value is null, the entry is ignored. + * + *

      If omitted, no headers are added. + */ + @JsonProperty(HEADERS) + @Nullable + public List getHeaders() { + return headers; + } + + @JsonProperty(HEADERS) + public OtlpGrpcMetricExporterModel setHeaders(List headers) { + this.headers = headers; + return this; + } + + /** + * Configure headers. Entries have lower priority than entries from .headers. + * + *

      The value is a list of comma separated key-value pairs matching the format of + * OTEL_EXPORTER_OTLP_HEADERS. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options + * for details. + * + *

      If omitted or null, no headers are added. + */ + @JsonProperty(HEADERS_LIST) + @Nullable + public String getHeadersList() { + if (headersList == null) { + return ExtensionPropertyUtil.getGraduated(HEADERS_LIST, extensionProperties, String.class); + } + return headersList; + } + + @JsonProperty(HEADERS_LIST) + public OtlpGrpcMetricExporterModel setHeadersList(String headersList) { + this.headersList = headersList; + return this; + } + + /** + * Configure compression. + * + *

      Known values include: gzip, none. Implementations may support other compression algorithms. + * + *

      If omitted or null, none is used. + */ + @JsonProperty(COMPRESSION) + @Nullable + public String getCompression() { + if (compression == null) { + return ExtensionPropertyUtil.getGraduated(COMPRESSION, extensionProperties, String.class); + } + return compression; + } + + @JsonProperty(COMPRESSION) + public OtlpGrpcMetricExporterModel setCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Configure the maximum size of each export request message in bytes, before compression. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity) and is not + * recommended. + * + *

      If omitted or null, 67108864 (64 MiB) is used. + */ + @JsonProperty(MAX_REQUEST_SIZE) + @Nullable + public Integer getMaxRequestSize() { + if (maxRequestSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_REQUEST_SIZE, extensionProperties, Integer.class); + } + return maxRequestSize; + } + + @JsonProperty(MAX_REQUEST_SIZE) + public OtlpGrpcMetricExporterModel setMaxRequestSize(Integer maxRequestSize) { + this.maxRequestSize = maxRequestSize; + return this; + } + + /** + * Configure the maximum size of each export response in bytes, after decompression. + * + *

      Value must be positive. + * + *

      If omitted or null, 4194304 (4 MiB) is used. + */ + @JsonProperty(MAX_RESPONSE_SIZE) + @Nullable + public Integer getMaxResponseSize() { + if (maxResponseSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_RESPONSE_SIZE, extensionProperties, Integer.class); + } + return maxResponseSize; + } + + @JsonProperty(MAX_RESPONSE_SIZE) + public OtlpGrpcMetricExporterModel setMaxResponseSize(Integer maxResponseSize) { + this.maxResponseSize = maxResponseSize; + return this; + } + + /** + * Configure max time (in milliseconds) to wait for each export. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 10000 is used. + */ + @JsonProperty(TIMEOUT) + @Nullable + public Integer getTimeout() { + if (timeout == null) { + return ExtensionPropertyUtil.getGraduated(TIMEOUT, extensionProperties, Integer.class); + } + return timeout; + } + + @JsonProperty(TIMEOUT) + public OtlpGrpcMetricExporterModel setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } + + /** + * Configure temporality preference. + * + *

      Values include: + * + *

      * cumulative: Use cumulative aggregation temporality for all instrument types. + * + *

      * delta: Use delta aggregation for all instrument types except up down counter and + * asynchronous up down counter. + * + *

      * low_memory: Use delta aggregation temporality for counter and histogram instrument types. + * Use cumulative aggregation temporality for all other instrument types. + * + *

      If omitted, cumulative is used. + */ + @JsonProperty(TEMPORALITY_PREFERENCE) + @Nullable + public ExporterTemporalityPreferenceModel getTemporalityPreference() { + if (temporalityPreference == null) { + return ExtensionPropertyUtil.getGraduated( + TEMPORALITY_PREFERENCE, extensionProperties, ExporterTemporalityPreferenceModel.class); + } + return temporalityPreference; + } + + @JsonProperty(TEMPORALITY_PREFERENCE) + public OtlpGrpcMetricExporterModel setTemporalityPreference( + ExporterTemporalityPreferenceModel temporalityPreference) { + this.temporalityPreference = temporalityPreference; + return this; + } + + /** + * Configure default histogram aggregation. + * + *

      Values include: + * + *

      * base2_exponential_bucket_histogram: Use base2 exponential histogram as the default + * aggregation for histogram instruments. + * + *

      * explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for + * histogram instruments. + * + *

      If omitted, explicit_bucket_histogram is used. + */ + @JsonProperty(DEFAULT_HISTOGRAM_AGGREGATION) + @Nullable + public ExporterDefaultHistogramAggregationModel getDefaultHistogramAggregation() { + if (defaultHistogramAggregation == null) { + return ExtensionPropertyUtil.getGraduated( + DEFAULT_HISTOGRAM_AGGREGATION, + extensionProperties, + ExporterDefaultHistogramAggregationModel.class); + } + return defaultHistogramAggregation; + } + + @JsonProperty(DEFAULT_HISTOGRAM_AGGREGATION) + public OtlpGrpcMetricExporterModel setDefaultHistogramAggregation( + ExporterDefaultHistogramAggregationModel defaultHistogramAggregation) { + this.defaultHistogramAggregation = defaultHistogramAggregation; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public OtlpGrpcMetricExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "OtlpGrpcMetricExporterModel{" + + "endpoint=" + + endpoint + + ", tls=" + + tls + + ", headers=" + + headers + + ", headersList=" + + headersList + + ", compression=" + + compression + + ", maxRequestSize=" + + maxRequestSize + + ", maxResponseSize=" + + maxResponseSize + + ", timeout=" + + timeout + + ", temporalityPreference=" + + temporalityPreference + + ", defaultHistogramAggregation=" + + defaultHistogramAggregation + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getEndpoint() == null) ? 0 : this.getEndpoint().hashCode(); + h *= 1000003; + h ^= (this.getTls() == null) ? 0 : this.getTls().hashCode(); + h *= 1000003; + h ^= (this.headers == null) ? 0 : this.headers.hashCode(); + h *= 1000003; + h ^= (this.getHeadersList() == null) ? 0 : this.getHeadersList().hashCode(); + h *= 1000003; + h ^= (this.getCompression() == null) ? 0 : this.getCompression().hashCode(); + h *= 1000003; + h ^= (this.getMaxRequestSize() == null) ? 0 : this.getMaxRequestSize().hashCode(); + h *= 1000003; + h ^= (this.getMaxResponseSize() == null) ? 0 : this.getMaxResponseSize().hashCode(); + h *= 1000003; + h ^= (this.getTimeout() == null) ? 0 : this.getTimeout().hashCode(); + h *= 1000003; + h ^= (this.getTemporalityPreference() == null) ? 0 : this.getTemporalityPreference().hashCode(); + h *= 1000003; + h ^= + (this.getDefaultHistogramAggregation() == null) + ? 0 + : this.getDefaultHistogramAggregation().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof OtlpGrpcMetricExporterModel) { + OtlpGrpcMetricExporterModel that = (OtlpGrpcMetricExporterModel) o; + return (this.getEndpoint() == null + ? that.getEndpoint() == null + : this.getEndpoint().equals(that.getEndpoint())) + && (this.getTls() == null ? that.getTls() == null : this.getTls().equals(that.getTls())) + && (this.headers == null ? that.headers == null : this.headers.equals(that.headers)) + && (this.getHeadersList() == null + ? that.getHeadersList() == null + : this.getHeadersList().equals(that.getHeadersList())) + && (this.getCompression() == null + ? that.getCompression() == null + : this.getCompression().equals(that.getCompression())) + && (this.getMaxRequestSize() == null + ? that.getMaxRequestSize() == null + : this.getMaxRequestSize().equals(that.getMaxRequestSize())) + && (this.getMaxResponseSize() == null + ? that.getMaxResponseSize() == null + : this.getMaxResponseSize().equals(that.getMaxResponseSize())) + && (this.getTimeout() == null + ? that.getTimeout() == null + : this.getTimeout().equals(that.getTimeout())) + && (this.getTemporalityPreference() == null + ? that.getTemporalityPreference() == null + : this.getTemporalityPreference().equals(that.getTemporalityPreference())) + && (this.getDefaultHistogramAggregation() == null + ? that.getDefaultHistogramAggregation() == null + : this.getDefaultHistogramAggregation().equals(that.getDefaultHistogramAggregation())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpEncodingModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpEncodingModel.java new file mode 100644 index 00000000000..ae7b872ba1c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpEncodingModel.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum OtlpHttpEncodingModel { + PROTOBUF("protobuf"), + JSON("json"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (OtlpHttpEncodingModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + OtlpHttpEncodingModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static OtlpHttpEncodingModel fromValue(String value) { + OtlpHttpEncodingModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpExporterModel.java new file mode 100644 index 00000000000..52a1bd3a3dc --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpExporterModel.java @@ -0,0 +1,394 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.COMPRESSION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.ENCODING; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.ENDPOINT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.HEADERS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.HEADERS_LIST; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.MAX_REQUEST_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.MAX_RESPONSE_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel.TLS; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ENDPOINT, + TLS, + HEADERS, + HEADERS_LIST, + COMPRESSION, + MAX_REQUEST_SIZE, + MAX_RESPONSE_SIZE, + TIMEOUT, + ENCODING +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class OtlpHttpExporterModel { + + static final String ENDPOINT = "endpoint"; + static final String TLS = "tls"; + static final String HEADERS = "headers"; + static final String HEADERS_LIST = "headers_list"; + static final String COMPRESSION = "compression"; + static final String MAX_REQUEST_SIZE = "max_request_size"; + static final String MAX_RESPONSE_SIZE = "max_response_size"; + static final String TIMEOUT = "timeout"; + static final String ENCODING = "encoding"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ENDPOINT, String.class); + STABLE_PROPERTIES.put(TLS, HttpTlsModel.class); + STABLE_PROPERTIES.put(HEADERS_LIST, String.class); + STABLE_PROPERTIES.put(COMPRESSION, String.class); + STABLE_PROPERTIES.put(MAX_REQUEST_SIZE, Integer.class); + STABLE_PROPERTIES.put(MAX_RESPONSE_SIZE, Integer.class); + STABLE_PROPERTIES.put(TIMEOUT, Integer.class); + STABLE_PROPERTIES.put(ENCODING, OtlpHttpEncodingModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String endpoint; + @Nullable private HttpTlsModel tls; + @Nullable private List headers; + @Nullable private String headersList; + @Nullable private String compression; + @Nullable private Integer maxRequestSize; + @Nullable private Integer maxResponseSize; + @Nullable private Integer timeout; + @Nullable private OtlpHttpEncodingModel encoding; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure endpoint, including the signal specific path. + * + *

      If omitted or null, the http://localhost:4318/v1/{signal} (where signal is 'traces', 'logs', + * or 'metrics') is used. + */ + @JsonProperty(ENDPOINT) + @Nullable + public String getEndpoint() { + if (endpoint == null) { + return ExtensionPropertyUtil.getGraduated(ENDPOINT, extensionProperties, String.class); + } + return endpoint; + } + + @JsonProperty(ENDPOINT) + public OtlpHttpExporterModel setEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * Configure TLS settings for the exporter. + * + *

      If omitted, system default TLS settings are used. + */ + @JsonProperty(TLS) + @Nullable + public HttpTlsModel getTls() { + if (tls == null) { + return ExtensionPropertyUtil.getGraduated(TLS, extensionProperties, HttpTlsModel.class); + } + return tls; + } + + @JsonProperty(TLS) + public OtlpHttpExporterModel setTls(HttpTlsModel tls) { + this.tls = tls; + return this; + } + + /** + * Configure headers. Entries have higher priority than entries from .headers_list. + * + *

      If an entry's .value is null, the entry is ignored. + * + *

      If omitted, no headers are added. + */ + @JsonProperty(HEADERS) + @Nullable + public List getHeaders() { + return headers; + } + + @JsonProperty(HEADERS) + public OtlpHttpExporterModel setHeaders(List headers) { + this.headers = headers; + return this; + } + + /** + * Configure headers. Entries have lower priority than entries from .headers. + * + *

      The value is a list of comma separated key-value pairs matching the format of + * OTEL_EXPORTER_OTLP_HEADERS. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options + * for details. + * + *

      If omitted or null, no headers are added. + */ + @JsonProperty(HEADERS_LIST) + @Nullable + public String getHeadersList() { + if (headersList == null) { + return ExtensionPropertyUtil.getGraduated(HEADERS_LIST, extensionProperties, String.class); + } + return headersList; + } + + @JsonProperty(HEADERS_LIST) + public OtlpHttpExporterModel setHeadersList(String headersList) { + this.headersList = headersList; + return this; + } + + /** + * Configure compression. + * + *

      Known values include: gzip, none. Implementations may support other compression algorithms. + * + *

      If omitted or null, none is used. + */ + @JsonProperty(COMPRESSION) + @Nullable + public String getCompression() { + if (compression == null) { + return ExtensionPropertyUtil.getGraduated(COMPRESSION, extensionProperties, String.class); + } + return compression; + } + + @JsonProperty(COMPRESSION) + public OtlpHttpExporterModel setCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Configure the maximum size of each export request body in bytes, before compression. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity) and is not + * recommended. + * + *

      If omitted or null, 67108864 (64 MiB) is used. + */ + @JsonProperty(MAX_REQUEST_SIZE) + @Nullable + public Integer getMaxRequestSize() { + if (maxRequestSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_REQUEST_SIZE, extensionProperties, Integer.class); + } + return maxRequestSize; + } + + @JsonProperty(MAX_REQUEST_SIZE) + public OtlpHttpExporterModel setMaxRequestSize(Integer maxRequestSize) { + this.maxRequestSize = maxRequestSize; + return this; + } + + /** + * Configure the maximum size of each export response in bytes, after decompression. + * + *

      Value must be positive. + * + *

      If omitted or null, 4194304 (4 MiB) is used. + */ + @JsonProperty(MAX_RESPONSE_SIZE) + @Nullable + public Integer getMaxResponseSize() { + if (maxResponseSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_RESPONSE_SIZE, extensionProperties, Integer.class); + } + return maxResponseSize; + } + + @JsonProperty(MAX_RESPONSE_SIZE) + public OtlpHttpExporterModel setMaxResponseSize(Integer maxResponseSize) { + this.maxResponseSize = maxResponseSize; + return this; + } + + /** + * Configure max time (in milliseconds) to wait for each export. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 10000 is used. + */ + @JsonProperty(TIMEOUT) + @Nullable + public Integer getTimeout() { + if (timeout == null) { + return ExtensionPropertyUtil.getGraduated(TIMEOUT, extensionProperties, Integer.class); + } + return timeout; + } + + @JsonProperty(TIMEOUT) + public OtlpHttpExporterModel setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } + + /** + * Configure the encoding used for messages. + * + *

      Implementations may not support json. + * + *

      Values include: + * + *

      * json: Protobuf JSON encoding. + * + *

      * protobuf: Protobuf binary encoding. + * + *

      If omitted, protobuf is used. + */ + @JsonProperty(ENCODING) + @Nullable + public OtlpHttpEncodingModel getEncoding() { + if (encoding == null) { + return ExtensionPropertyUtil.getGraduated( + ENCODING, extensionProperties, OtlpHttpEncodingModel.class); + } + return encoding; + } + + @JsonProperty(ENCODING) + public OtlpHttpExporterModel setEncoding(OtlpHttpEncodingModel encoding) { + this.encoding = encoding; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public OtlpHttpExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "OtlpHttpExporterModel{" + + "endpoint=" + + endpoint + + ", tls=" + + tls + + ", headers=" + + headers + + ", headersList=" + + headersList + + ", compression=" + + compression + + ", maxRequestSize=" + + maxRequestSize + + ", maxResponseSize=" + + maxResponseSize + + ", timeout=" + + timeout + + ", encoding=" + + encoding + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getEndpoint() == null) ? 0 : this.getEndpoint().hashCode(); + h *= 1000003; + h ^= (this.getTls() == null) ? 0 : this.getTls().hashCode(); + h *= 1000003; + h ^= (this.headers == null) ? 0 : this.headers.hashCode(); + h *= 1000003; + h ^= (this.getHeadersList() == null) ? 0 : this.getHeadersList().hashCode(); + h *= 1000003; + h ^= (this.getCompression() == null) ? 0 : this.getCompression().hashCode(); + h *= 1000003; + h ^= (this.getMaxRequestSize() == null) ? 0 : this.getMaxRequestSize().hashCode(); + h *= 1000003; + h ^= (this.getMaxResponseSize() == null) ? 0 : this.getMaxResponseSize().hashCode(); + h *= 1000003; + h ^= (this.getTimeout() == null) ? 0 : this.getTimeout().hashCode(); + h *= 1000003; + h ^= (this.getEncoding() == null) ? 0 : this.getEncoding().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof OtlpHttpExporterModel) { + OtlpHttpExporterModel that = (OtlpHttpExporterModel) o; + return (this.getEndpoint() == null + ? that.getEndpoint() == null + : this.getEndpoint().equals(that.getEndpoint())) + && (this.getTls() == null ? that.getTls() == null : this.getTls().equals(that.getTls())) + && (this.headers == null ? that.headers == null : this.headers.equals(that.headers)) + && (this.getHeadersList() == null + ? that.getHeadersList() == null + : this.getHeadersList().equals(that.getHeadersList())) + && (this.getCompression() == null + ? that.getCompression() == null + : this.getCompression().equals(that.getCompression())) + && (this.getMaxRequestSize() == null + ? that.getMaxRequestSize() == null + : this.getMaxRequestSize().equals(that.getMaxRequestSize())) + && (this.getMaxResponseSize() == null + ? that.getMaxResponseSize() == null + : this.getMaxResponseSize().equals(that.getMaxResponseSize())) + && (this.getTimeout() == null + ? that.getTimeout() == null + : this.getTimeout().equals(that.getTimeout())) + && (this.getEncoding() == null + ? that.getEncoding() == null + : this.getEncoding().equals(that.getEncoding())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpMetricExporterModel.java new file mode 100644 index 00000000000..948f24b3159 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/OtlpHttpMetricExporterModel.java @@ -0,0 +1,485 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.COMPRESSION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.DEFAULT_HISTOGRAM_AGGREGATION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.ENCODING; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.ENDPOINT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.HEADERS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.HEADERS_LIST; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.MAX_REQUEST_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.MAX_RESPONSE_SIZE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.TEMPORALITY_PREFERENCE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel.TLS; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ENDPOINT, + TLS, + HEADERS, + HEADERS_LIST, + COMPRESSION, + MAX_REQUEST_SIZE, + MAX_RESPONSE_SIZE, + TIMEOUT, + ENCODING, + TEMPORALITY_PREFERENCE, + DEFAULT_HISTOGRAM_AGGREGATION +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class OtlpHttpMetricExporterModel { + + static final String ENDPOINT = "endpoint"; + static final String TLS = "tls"; + static final String HEADERS = "headers"; + static final String HEADERS_LIST = "headers_list"; + static final String COMPRESSION = "compression"; + static final String MAX_REQUEST_SIZE = "max_request_size"; + static final String MAX_RESPONSE_SIZE = "max_response_size"; + static final String TIMEOUT = "timeout"; + static final String ENCODING = "encoding"; + static final String TEMPORALITY_PREFERENCE = "temporality_preference"; + static final String DEFAULT_HISTOGRAM_AGGREGATION = "default_histogram_aggregation"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ENDPOINT, String.class); + STABLE_PROPERTIES.put(TLS, HttpTlsModel.class); + STABLE_PROPERTIES.put(HEADERS_LIST, String.class); + STABLE_PROPERTIES.put(COMPRESSION, String.class); + STABLE_PROPERTIES.put(MAX_REQUEST_SIZE, Integer.class); + STABLE_PROPERTIES.put(MAX_RESPONSE_SIZE, Integer.class); + STABLE_PROPERTIES.put(TIMEOUT, Integer.class); + STABLE_PROPERTIES.put(ENCODING, OtlpHttpEncodingModel.class); + STABLE_PROPERTIES.put(TEMPORALITY_PREFERENCE, ExporterTemporalityPreferenceModel.class); + STABLE_PROPERTIES.put( + DEFAULT_HISTOGRAM_AGGREGATION, ExporterDefaultHistogramAggregationModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String endpoint; + @Nullable private HttpTlsModel tls; + @Nullable private List headers; + @Nullable private String headersList; + @Nullable private String compression; + @Nullable private Integer maxRequestSize; + @Nullable private Integer maxResponseSize; + @Nullable private Integer timeout; + @Nullable private OtlpHttpEncodingModel encoding; + @Nullable private ExporterTemporalityPreferenceModel temporalityPreference; + @Nullable private ExporterDefaultHistogramAggregationModel defaultHistogramAggregation; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure endpoint. + * + *

      If omitted or null, http://localhost:4318/v1/metrics is used. + */ + @JsonProperty(ENDPOINT) + @Nullable + public String getEndpoint() { + if (endpoint == null) { + return ExtensionPropertyUtil.getGraduated(ENDPOINT, extensionProperties, String.class); + } + return endpoint; + } + + @JsonProperty(ENDPOINT) + public OtlpHttpMetricExporterModel setEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * Configure TLS settings for the exporter. + * + *

      If omitted, system default TLS settings are used. + */ + @JsonProperty(TLS) + @Nullable + public HttpTlsModel getTls() { + if (tls == null) { + return ExtensionPropertyUtil.getGraduated(TLS, extensionProperties, HttpTlsModel.class); + } + return tls; + } + + @JsonProperty(TLS) + public OtlpHttpMetricExporterModel setTls(HttpTlsModel tls) { + this.tls = tls; + return this; + } + + /** + * Configure headers. Entries have higher priority than entries from .headers_list. + * + *

      If an entry's .value is null, the entry is ignored. + * + *

      If omitted, no headers are added. + */ + @JsonProperty(HEADERS) + @Nullable + public List getHeaders() { + return headers; + } + + @JsonProperty(HEADERS) + public OtlpHttpMetricExporterModel setHeaders(List headers) { + this.headers = headers; + return this; + } + + /** + * Configure headers. Entries have lower priority than entries from .headers. + * + *

      The value is a list of comma separated key-value pairs matching the format of + * OTEL_EXPORTER_OTLP_HEADERS. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/exporter.md#configuration-options + * for details. + * + *

      If omitted or null, no headers are added. + */ + @JsonProperty(HEADERS_LIST) + @Nullable + public String getHeadersList() { + if (headersList == null) { + return ExtensionPropertyUtil.getGraduated(HEADERS_LIST, extensionProperties, String.class); + } + return headersList; + } + + @JsonProperty(HEADERS_LIST) + public OtlpHttpMetricExporterModel setHeadersList(String headersList) { + this.headersList = headersList; + return this; + } + + /** + * Configure compression. + * + *

      Known values include: gzip, none. Implementations may support other compression algorithms. + * + *

      If omitted or null, none is used. + */ + @JsonProperty(COMPRESSION) + @Nullable + public String getCompression() { + if (compression == null) { + return ExtensionPropertyUtil.getGraduated(COMPRESSION, extensionProperties, String.class); + } + return compression; + } + + @JsonProperty(COMPRESSION) + public OtlpHttpMetricExporterModel setCompression(String compression) { + this.compression = compression; + return this; + } + + /** + * Configure the maximum size of each export request body in bytes, before compression. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity) and is not + * recommended. + * + *

      If omitted or null, 67108864 (64 MiB) is used. + */ + @JsonProperty(MAX_REQUEST_SIZE) + @Nullable + public Integer getMaxRequestSize() { + if (maxRequestSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_REQUEST_SIZE, extensionProperties, Integer.class); + } + return maxRequestSize; + } + + @JsonProperty(MAX_REQUEST_SIZE) + public OtlpHttpMetricExporterModel setMaxRequestSize(Integer maxRequestSize) { + this.maxRequestSize = maxRequestSize; + return this; + } + + /** + * Configure the maximum size of each export response in bytes, after decompression. + * + *

      Value must be positive. + * + *

      If omitted or null, 4194304 (4 MiB) is used. + */ + @JsonProperty(MAX_RESPONSE_SIZE) + @Nullable + public Integer getMaxResponseSize() { + if (maxResponseSize == null) { + return ExtensionPropertyUtil.getGraduated( + MAX_RESPONSE_SIZE, extensionProperties, Integer.class); + } + return maxResponseSize; + } + + @JsonProperty(MAX_RESPONSE_SIZE) + public OtlpHttpMetricExporterModel setMaxResponseSize(Integer maxResponseSize) { + this.maxResponseSize = maxResponseSize; + return this; + } + + /** + * Configure max time (in milliseconds) to wait for each export. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 10000 is used. + */ + @JsonProperty(TIMEOUT) + @Nullable + public Integer getTimeout() { + if (timeout == null) { + return ExtensionPropertyUtil.getGraduated(TIMEOUT, extensionProperties, Integer.class); + } + return timeout; + } + + @JsonProperty(TIMEOUT) + public OtlpHttpMetricExporterModel setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } + + /** + * Configure the encoding used for messages. + * + *

      Implementations may not support json. + * + *

      Values include: + * + *

      * json: Protobuf JSON encoding. + * + *

      * protobuf: Protobuf binary encoding. + * + *

      If omitted, protobuf is used. + */ + @JsonProperty(ENCODING) + @Nullable + public OtlpHttpEncodingModel getEncoding() { + if (encoding == null) { + return ExtensionPropertyUtil.getGraduated( + ENCODING, extensionProperties, OtlpHttpEncodingModel.class); + } + return encoding; + } + + @JsonProperty(ENCODING) + public OtlpHttpMetricExporterModel setEncoding(OtlpHttpEncodingModel encoding) { + this.encoding = encoding; + return this; + } + + /** + * Configure temporality preference. + * + *

      Values include: + * + *

      * cumulative: Use cumulative aggregation temporality for all instrument types. + * + *

      * delta: Use delta aggregation for all instrument types except up down counter and + * asynchronous up down counter. + * + *

      * low_memory: Use delta aggregation temporality for counter and histogram instrument types. + * Use cumulative aggregation temporality for all other instrument types. + * + *

      If omitted, cumulative is used. + */ + @JsonProperty(TEMPORALITY_PREFERENCE) + @Nullable + public ExporterTemporalityPreferenceModel getTemporalityPreference() { + if (temporalityPreference == null) { + return ExtensionPropertyUtil.getGraduated( + TEMPORALITY_PREFERENCE, extensionProperties, ExporterTemporalityPreferenceModel.class); + } + return temporalityPreference; + } + + @JsonProperty(TEMPORALITY_PREFERENCE) + public OtlpHttpMetricExporterModel setTemporalityPreference( + ExporterTemporalityPreferenceModel temporalityPreference) { + this.temporalityPreference = temporalityPreference; + return this; + } + + /** + * Configure default histogram aggregation. + * + *

      Values include: + * + *

      * base2_exponential_bucket_histogram: Use base2 exponential histogram as the default + * aggregation for histogram instruments. + * + *

      * explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for + * histogram instruments. + * + *

      If omitted, explicit_bucket_histogram is used. + */ + @JsonProperty(DEFAULT_HISTOGRAM_AGGREGATION) + @Nullable + public ExporterDefaultHistogramAggregationModel getDefaultHistogramAggregation() { + if (defaultHistogramAggregation == null) { + return ExtensionPropertyUtil.getGraduated( + DEFAULT_HISTOGRAM_AGGREGATION, + extensionProperties, + ExporterDefaultHistogramAggregationModel.class); + } + return defaultHistogramAggregation; + } + + @JsonProperty(DEFAULT_HISTOGRAM_AGGREGATION) + public OtlpHttpMetricExporterModel setDefaultHistogramAggregation( + ExporterDefaultHistogramAggregationModel defaultHistogramAggregation) { + this.defaultHistogramAggregation = defaultHistogramAggregation; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public OtlpHttpMetricExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "OtlpHttpMetricExporterModel{" + + "endpoint=" + + endpoint + + ", tls=" + + tls + + ", headers=" + + headers + + ", headersList=" + + headersList + + ", compression=" + + compression + + ", maxRequestSize=" + + maxRequestSize + + ", maxResponseSize=" + + maxResponseSize + + ", timeout=" + + timeout + + ", encoding=" + + encoding + + ", temporalityPreference=" + + temporalityPreference + + ", defaultHistogramAggregation=" + + defaultHistogramAggregation + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getEndpoint() == null) ? 0 : this.getEndpoint().hashCode(); + h *= 1000003; + h ^= (this.getTls() == null) ? 0 : this.getTls().hashCode(); + h *= 1000003; + h ^= (this.headers == null) ? 0 : this.headers.hashCode(); + h *= 1000003; + h ^= (this.getHeadersList() == null) ? 0 : this.getHeadersList().hashCode(); + h *= 1000003; + h ^= (this.getCompression() == null) ? 0 : this.getCompression().hashCode(); + h *= 1000003; + h ^= (this.getMaxRequestSize() == null) ? 0 : this.getMaxRequestSize().hashCode(); + h *= 1000003; + h ^= (this.getMaxResponseSize() == null) ? 0 : this.getMaxResponseSize().hashCode(); + h *= 1000003; + h ^= (this.getTimeout() == null) ? 0 : this.getTimeout().hashCode(); + h *= 1000003; + h ^= (this.getEncoding() == null) ? 0 : this.getEncoding().hashCode(); + h *= 1000003; + h ^= (this.getTemporalityPreference() == null) ? 0 : this.getTemporalityPreference().hashCode(); + h *= 1000003; + h ^= + (this.getDefaultHistogramAggregation() == null) + ? 0 + : this.getDefaultHistogramAggregation().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof OtlpHttpMetricExporterModel) { + OtlpHttpMetricExporterModel that = (OtlpHttpMetricExporterModel) o; + return (this.getEndpoint() == null + ? that.getEndpoint() == null + : this.getEndpoint().equals(that.getEndpoint())) + && (this.getTls() == null ? that.getTls() == null : this.getTls().equals(that.getTls())) + && (this.headers == null ? that.headers == null : this.headers.equals(that.headers)) + && (this.getHeadersList() == null + ? that.getHeadersList() == null + : this.getHeadersList().equals(that.getHeadersList())) + && (this.getCompression() == null + ? that.getCompression() == null + : this.getCompression().equals(that.getCompression())) + && (this.getMaxRequestSize() == null + ? that.getMaxRequestSize() == null + : this.getMaxRequestSize().equals(that.getMaxRequestSize())) + && (this.getMaxResponseSize() == null + ? that.getMaxResponseSize() == null + : this.getMaxResponseSize().equals(that.getMaxResponseSize())) + && (this.getTimeout() == null + ? that.getTimeout() == null + : this.getTimeout().equals(that.getTimeout())) + && (this.getEncoding() == null + ? that.getEncoding() == null + : this.getEncoding().equals(that.getEncoding())) + && (this.getTemporalityPreference() == null + ? that.getTemporalityPreference() == null + : this.getTemporalityPreference().equals(that.getTemporalityPreference())) + && (this.getDefaultHistogramAggregation() == null + ? that.getDefaultHistogramAggregation() == null + : this.getDefaultHistogramAggregation().equals(that.getDefaultHistogramAggregation())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ParentBasedSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ParentBasedSamplerModel.java new file mode 100644 index 00000000000..a975c142b14 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ParentBasedSamplerModel.java @@ -0,0 +1,252 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel.LOCAL_PARENT_NOT_SAMPLED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel.LOCAL_PARENT_SAMPLED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel.REMOTE_PARENT_NOT_SAMPLED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel.REMOTE_PARENT_SAMPLED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel.ROOT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ROOT, + REMOTE_PARENT_SAMPLED, + REMOTE_PARENT_NOT_SAMPLED, + LOCAL_PARENT_SAMPLED, + LOCAL_PARENT_NOT_SAMPLED +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ParentBasedSamplerModel { + + static final String ROOT = "root"; + static final String REMOTE_PARENT_SAMPLED = "remote_parent_sampled"; + static final String REMOTE_PARENT_NOT_SAMPLED = "remote_parent_not_sampled"; + static final String LOCAL_PARENT_SAMPLED = "local_parent_sampled"; + static final String LOCAL_PARENT_NOT_SAMPLED = "local_parent_not_sampled"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ROOT, SamplerModel.class); + STABLE_PROPERTIES.put(REMOTE_PARENT_SAMPLED, SamplerModel.class); + STABLE_PROPERTIES.put(REMOTE_PARENT_NOT_SAMPLED, SamplerModel.class); + STABLE_PROPERTIES.put(LOCAL_PARENT_SAMPLED, SamplerModel.class); + STABLE_PROPERTIES.put(LOCAL_PARENT_NOT_SAMPLED, SamplerModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private SamplerModel root; + @Nullable private SamplerModel remoteParentSampled; + @Nullable private SamplerModel remoteParentNotSampled; + @Nullable private SamplerModel localParentSampled; + @Nullable private SamplerModel localParentNotSampled; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure root sampler. + * + *

      If omitted, always_on is used. + */ + @JsonProperty(ROOT) + @Nullable + public SamplerModel getRoot() { + if (root == null) { + return ExtensionPropertyUtil.getGraduated(ROOT, extensionProperties, SamplerModel.class); + } + return root; + } + + @JsonProperty(ROOT) + public ParentBasedSamplerModel setRoot(SamplerModel root) { + this.root = root; + return this; + } + + /** + * Configure remote_parent_sampled sampler. + * + *

      If omitted, always_on is used. + */ + @JsonProperty(REMOTE_PARENT_SAMPLED) + @Nullable + public SamplerModel getRemoteParentSampled() { + if (remoteParentSampled == null) { + return ExtensionPropertyUtil.getGraduated( + REMOTE_PARENT_SAMPLED, extensionProperties, SamplerModel.class); + } + return remoteParentSampled; + } + + @JsonProperty(REMOTE_PARENT_SAMPLED) + public ParentBasedSamplerModel setRemoteParentSampled(SamplerModel remoteParentSampled) { + this.remoteParentSampled = remoteParentSampled; + return this; + } + + /** + * Configure remote_parent_not_sampled sampler. + * + *

      If omitted, always_off is used. + */ + @JsonProperty(REMOTE_PARENT_NOT_SAMPLED) + @Nullable + public SamplerModel getRemoteParentNotSampled() { + if (remoteParentNotSampled == null) { + return ExtensionPropertyUtil.getGraduated( + REMOTE_PARENT_NOT_SAMPLED, extensionProperties, SamplerModel.class); + } + return remoteParentNotSampled; + } + + @JsonProperty(REMOTE_PARENT_NOT_SAMPLED) + public ParentBasedSamplerModel setRemoteParentNotSampled(SamplerModel remoteParentNotSampled) { + this.remoteParentNotSampled = remoteParentNotSampled; + return this; + } + + /** + * Configure local_parent_sampled sampler. + * + *

      If omitted, always_on is used. + */ + @JsonProperty(LOCAL_PARENT_SAMPLED) + @Nullable + public SamplerModel getLocalParentSampled() { + if (localParentSampled == null) { + return ExtensionPropertyUtil.getGraduated( + LOCAL_PARENT_SAMPLED, extensionProperties, SamplerModel.class); + } + return localParentSampled; + } + + @JsonProperty(LOCAL_PARENT_SAMPLED) + public ParentBasedSamplerModel setLocalParentSampled(SamplerModel localParentSampled) { + this.localParentSampled = localParentSampled; + return this; + } + + /** + * Configure local_parent_not_sampled sampler. + * + *

      If omitted, always_off is used. + */ + @JsonProperty(LOCAL_PARENT_NOT_SAMPLED) + @Nullable + public SamplerModel getLocalParentNotSampled() { + if (localParentNotSampled == null) { + return ExtensionPropertyUtil.getGraduated( + LOCAL_PARENT_NOT_SAMPLED, extensionProperties, SamplerModel.class); + } + return localParentNotSampled; + } + + @JsonProperty(LOCAL_PARENT_NOT_SAMPLED) + public ParentBasedSamplerModel setLocalParentNotSampled(SamplerModel localParentNotSampled) { + this.localParentNotSampled = localParentNotSampled; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ParentBasedSamplerModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ParentBasedSamplerModel{" + + "root=" + + root + + ", remoteParentSampled=" + + remoteParentSampled + + ", remoteParentNotSampled=" + + remoteParentNotSampled + + ", localParentSampled=" + + localParentSampled + + ", localParentNotSampled=" + + localParentNotSampled + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getRoot() == null) ? 0 : this.getRoot().hashCode(); + h *= 1000003; + h ^= (this.getRemoteParentSampled() == null) ? 0 : this.getRemoteParentSampled().hashCode(); + h *= 1000003; + h ^= + (this.getRemoteParentNotSampled() == null) + ? 0 + : this.getRemoteParentNotSampled().hashCode(); + h *= 1000003; + h ^= (this.getLocalParentSampled() == null) ? 0 : this.getLocalParentSampled().hashCode(); + h *= 1000003; + h ^= (this.getLocalParentNotSampled() == null) ? 0 : this.getLocalParentNotSampled().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ParentBasedSamplerModel) { + ParentBasedSamplerModel that = (ParentBasedSamplerModel) o; + return (this.getRoot() == null + ? that.getRoot() == null + : this.getRoot().equals(that.getRoot())) + && (this.getRemoteParentSampled() == null + ? that.getRemoteParentSampled() == null + : this.getRemoteParentSampled().equals(that.getRemoteParentSampled())) + && (this.getRemoteParentNotSampled() == null + ? that.getRemoteParentNotSampled() == null + : this.getRemoteParentNotSampled().equals(that.getRemoteParentNotSampled())) + && (this.getLocalParentSampled() == null + ? that.getLocalParentSampled() == null + : this.getLocalParentSampled().equals(that.getLocalParentSampled())) + && (this.getLocalParentNotSampled() == null + ? that.getLocalParentNotSampled() == null + : this.getLocalParentNotSampled().equals(that.getLocalParentNotSampled())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PeriodicMetricReaderModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PeriodicMetricReaderModel.java new file mode 100644 index 00000000000..6fc666fbdfb --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PeriodicMetricReaderModel.java @@ -0,0 +1,242 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel.CARDINALITY_LIMITS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel.EXPORTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel.INTERVAL; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel.PRODUCERS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel.TIMEOUT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PeriodicMetricReaderModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({INTERVAL, TIMEOUT, EXPORTER, PRODUCERS, CARDINALITY_LIMITS}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class PeriodicMetricReaderModel { + + static final String INTERVAL = "interval"; + static final String TIMEOUT = "timeout"; + static final String EXPORTER = "exporter"; + static final String PRODUCERS = "producers"; + static final String CARDINALITY_LIMITS = "cardinality_limits"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(INTERVAL, Integer.class); + STABLE_PROPERTIES.put(TIMEOUT, Integer.class); + STABLE_PROPERTIES.put(EXPORTER, PushMetricExporterModel.class); + STABLE_PROPERTIES.put(CARDINALITY_LIMITS, CardinalityLimitsModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer interval; + @Nullable private Integer timeout; + @Nullable private PushMetricExporterModel exporter; + @Nullable private List producers; + @Nullable private CardinalityLimitsModel cardinalityLimits; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure delay interval (in milliseconds) between start of two consecutive exports. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 60000 is used. + */ + @JsonProperty(INTERVAL) + @Nullable + public Integer getInterval() { + if (interval == null) { + return ExtensionPropertyUtil.getGraduated(INTERVAL, extensionProperties, Integer.class); + } + return interval; + } + + @JsonProperty(INTERVAL) + public PeriodicMetricReaderModel setInterval(Integer interval) { + this.interval = interval; + return this; + } + + /** + * Configure maximum allowed time (in milliseconds) to export data. + * + *

      Value must be non-negative. A value of 0 indicates no limit (infinity). + * + *

      If omitted or null, 30000 is used. + */ + @JsonProperty(TIMEOUT) + @Nullable + public Integer getTimeout() { + if (timeout == null) { + return ExtensionPropertyUtil.getGraduated(TIMEOUT, extensionProperties, Integer.class); + } + return timeout; + } + + @JsonProperty(TIMEOUT) + public PeriodicMetricReaderModel setTimeout(Integer timeout) { + this.timeout = timeout; + return this; + } + + /** + * Configure exporter. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(EXPORTER) + @Nullable + public PushMetricExporterModel getExporter() { + if (exporter == null) { + return ExtensionPropertyUtil.getGraduated( + EXPORTER, extensionProperties, PushMetricExporterModel.class); + } + return exporter; + } + + @JsonProperty(EXPORTER) + public PeriodicMetricReaderModel setExporter(PushMetricExporterModel exporter) { + this.exporter = exporter; + return this; + } + + /** + * Configure metric producers. + * + *

      If omitted, no metric producers are added. + */ + @JsonProperty(PRODUCERS) + @Nullable + public List getProducers() { + return producers; + } + + @JsonProperty(PRODUCERS) + public PeriodicMetricReaderModel setProducers(List producers) { + this.producers = producers; + return this; + } + + /** + * Configure cardinality limits. + * + *

      If omitted, default values as described in CardinalityLimits are used. + */ + @JsonProperty(CARDINALITY_LIMITS) + @Nullable + public CardinalityLimitsModel getCardinalityLimits() { + if (cardinalityLimits == null) { + return ExtensionPropertyUtil.getGraduated( + CARDINALITY_LIMITS, extensionProperties, CardinalityLimitsModel.class); + } + return cardinalityLimits; + } + + @JsonProperty(CARDINALITY_LIMITS) + public PeriodicMetricReaderModel setCardinalityLimits(CardinalityLimitsModel cardinalityLimits) { + this.cardinalityLimits = cardinalityLimits; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public PeriodicMetricReaderModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "PeriodicMetricReaderModel{" + + "interval=" + + interval + + ", timeout=" + + timeout + + ", exporter=" + + exporter + + ", producers=" + + producers + + ", cardinalityLimits=" + + cardinalityLimits + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getInterval() == null) ? 0 : this.getInterval().hashCode(); + h *= 1000003; + h ^= (this.getTimeout() == null) ? 0 : this.getTimeout().hashCode(); + h *= 1000003; + h ^= (this.getExporter() == null) ? 0 : this.getExporter().hashCode(); + h *= 1000003; + h ^= (this.producers == null) ? 0 : this.producers.hashCode(); + h *= 1000003; + h ^= (this.getCardinalityLimits() == null) ? 0 : this.getCardinalityLimits().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof PeriodicMetricReaderModel) { + PeriodicMetricReaderModel that = (PeriodicMetricReaderModel) o; + return (this.getInterval() == null + ? that.getInterval() == null + : this.getInterval().equals(that.getInterval())) + && (this.getTimeout() == null + ? that.getTimeout() == null + : this.getTimeout().equals(that.getTimeout())) + && (this.getExporter() == null + ? that.getExporter() == null + : this.getExporter().equals(that.getExporter())) + && (this.producers == null + ? that.producers == null + : this.producers.equals(that.producers)) + && (this.getCardinalityLimits() == null + ? that.getCardinalityLimits() == null + : this.getCardinalityLimits().equals(that.getCardinalityLimits())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PropagatorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PropagatorModel.java new file mode 100644 index 00000000000..db6eb366279 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PropagatorModel.java @@ -0,0 +1,156 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PropagatorModel.COMPOSITE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PropagatorModel.COMPOSITE_LIST; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({COMPOSITE, COMPOSITE_LIST}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class PropagatorModel { + + static final String COMPOSITE = "composite"; + static final String COMPOSITE_LIST = "composite_list"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(COMPOSITE_LIST, String.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private List composite; + @Nullable private String compositeList; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure the propagators in the composite text map propagator. Entries from .composite_list + * are appended to the list here with duplicates filtered out. + * + *

      Built-in propagator keys include: tracecontext, baggage, b3, b3multi. Known third party keys + * include: xray. + * + *

      If omitted, and .composite_list is omitted or null, a noop propagator is used. + */ + @JsonProperty(COMPOSITE) + @Nullable + public List getComposite() { + return composite; + } + + @JsonProperty(COMPOSITE) + public PropagatorModel setComposite(List composite) { + this.composite = composite; + return this; + } + + /** + * Configure the propagators in the composite text map propagator. Entries are appended to + * .composite with duplicates filtered out. + * + *

      The value is a comma separated list of propagator identifiers matching the format of + * OTEL_PROPAGATORS. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration + * for details. + * + *

      Built-in propagator identifiers include: tracecontext, baggage, b3, b3multi. Known third + * party identifiers include: xray. + * + *

      If omitted or null, and .composite is omitted or null, a noop propagator is used. + */ + @JsonProperty(COMPOSITE_LIST) + @Nullable + public String getCompositeList() { + if (compositeList == null) { + return ExtensionPropertyUtil.getGraduated(COMPOSITE_LIST, extensionProperties, String.class); + } + return compositeList; + } + + @JsonProperty(COMPOSITE_LIST) + public PropagatorModel setCompositeList(String compositeList) { + this.compositeList = compositeList; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public PropagatorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "PropagatorModel{" + + "composite=" + + composite + + ", compositeList=" + + compositeList + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.composite == null) ? 0 : this.composite.hashCode(); + h *= 1000003; + h ^= (this.getCompositeList() == null) ? 0 : this.getCompositeList().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof PropagatorModel) { + PropagatorModel that = (PropagatorModel) o; + return (this.composite == null + ? that.composite == null + : this.composite.equals(that.composite)) + && (this.getCompositeList() == null + ? that.getCompositeList() == null + : this.getCompositeList().equals(that.getCompositeList())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PullMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PullMetricExporterModel.java new file mode 100644 index 00000000000..ab697788645 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PullMetricExporterModel.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PullMetricExporterModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class PullMetricExporterModel { + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + private Map extensionProperties = new LinkedHashMap(); + + @JsonAnyGetter + public Map getExtensionProperties() { + return extensionProperties; + } + + @JsonAnySetter + public PullMetricExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + Collections.emptyMap(), + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "PullMetricExporterModel{" + "extensionProperties=" + extensionProperties + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof PullMetricExporterModel) { + PullMetricExporterModel that = (PullMetricExporterModel) o; + return (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PullMetricReaderModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PullMetricReaderModel.java new file mode 100644 index 00000000000..47be9870a1d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PullMetricReaderModel.java @@ -0,0 +1,176 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricReaderModel.CARDINALITY_LIMITS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricReaderModel.EXPORTER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricReaderModel.PRODUCERS; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({EXPORTER, PRODUCERS, CARDINALITY_LIMITS}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class PullMetricReaderModel { + + static final String EXPORTER = "exporter"; + static final String PRODUCERS = "producers"; + static final String CARDINALITY_LIMITS = "cardinality_limits"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(EXPORTER, PullMetricExporterModel.class); + STABLE_PROPERTIES.put(CARDINALITY_LIMITS, CardinalityLimitsModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private PullMetricExporterModel exporter; + @Nullable private List producers; + @Nullable private CardinalityLimitsModel cardinalityLimits; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure exporter. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(EXPORTER) + @Nullable + public PullMetricExporterModel getExporter() { + if (exporter == null) { + return ExtensionPropertyUtil.getGraduated( + EXPORTER, extensionProperties, PullMetricExporterModel.class); + } + return exporter; + } + + @JsonProperty(EXPORTER) + public PullMetricReaderModel setExporter(PullMetricExporterModel exporter) { + this.exporter = exporter; + return this; + } + + /** + * Configure metric producers. + * + *

      If omitted, no metric producers are added. + */ + @JsonProperty(PRODUCERS) + @Nullable + public List getProducers() { + return producers; + } + + @JsonProperty(PRODUCERS) + public PullMetricReaderModel setProducers(List producers) { + this.producers = producers; + return this; + } + + /** + * Configure cardinality limits. + * + *

      If omitted, default values as described in CardinalityLimits are used. + */ + @JsonProperty(CARDINALITY_LIMITS) + @Nullable + public CardinalityLimitsModel getCardinalityLimits() { + if (cardinalityLimits == null) { + return ExtensionPropertyUtil.getGraduated( + CARDINALITY_LIMITS, extensionProperties, CardinalityLimitsModel.class); + } + return cardinalityLimits; + } + + @JsonProperty(CARDINALITY_LIMITS) + public PullMetricReaderModel setCardinalityLimits(CardinalityLimitsModel cardinalityLimits) { + this.cardinalityLimits = cardinalityLimits; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public PullMetricReaderModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "PullMetricReaderModel{" + + "exporter=" + + exporter + + ", producers=" + + producers + + ", cardinalityLimits=" + + cardinalityLimits + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getExporter() == null) ? 0 : this.getExporter().hashCode(); + h *= 1000003; + h ^= (this.producers == null) ? 0 : this.producers.hashCode(); + h *= 1000003; + h ^= (this.getCardinalityLimits() == null) ? 0 : this.getCardinalityLimits().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof PullMetricReaderModel) { + PullMetricReaderModel that = (PullMetricReaderModel) o; + return (this.getExporter() == null + ? that.getExporter() == null + : this.getExporter().equals(that.getExporter())) + && (this.producers == null + ? that.producers == null + : this.producers.equals(that.producers)) + && (this.getCardinalityLimits() == null + ? that.getCardinalityLimits() == null + : this.getCardinalityLimits().equals(that.getCardinalityLimits())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PushMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PushMetricExporterModel.java new file mode 100644 index 00000000000..e0eeca4abd5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/PushMetricExporterModel.java @@ -0,0 +1,180 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel.CONSOLE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel.OTLP_GRPC; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel.OTLP_HTTP; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PushMetricExporterModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({OTLP_HTTP, OTLP_GRPC, CONSOLE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class PushMetricExporterModel { + + static final String OTLP_HTTP = "otlp_http"; + static final String OTLP_GRPC = "otlp_grpc"; + static final String CONSOLE = "console"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(OTLP_HTTP, OtlpHttpMetricExporterModel.class); + STABLE_PROPERTIES.put(OTLP_GRPC, OtlpGrpcMetricExporterModel.class); + STABLE_PROPERTIES.put(CONSOLE, ConsoleMetricExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private OtlpHttpMetricExporterModel otlpHttp; + @Nullable private OtlpGrpcMetricExporterModel otlpGrpc; + @Nullable private ConsoleMetricExporterModel console; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure exporter to be OTLP with HTTP transport. + * + *

      If omitted, ignore. + */ + @JsonProperty(OTLP_HTTP) + @Nullable + public OtlpHttpMetricExporterModel getOtlpHttp() { + if (otlpHttp == null) { + return ExtensionPropertyUtil.getGraduated( + OTLP_HTTP, extensionProperties, OtlpHttpMetricExporterModel.class); + } + return otlpHttp; + } + + @JsonProperty(OTLP_HTTP) + public PushMetricExporterModel setOtlpHttp(OtlpHttpMetricExporterModel otlpHttp) { + this.otlpHttp = otlpHttp; + return this; + } + + /** + * Configure exporter to be OTLP with gRPC transport. + * + *

      If omitted, ignore. + */ + @JsonProperty(OTLP_GRPC) + @Nullable + public OtlpGrpcMetricExporterModel getOtlpGrpc() { + if (otlpGrpc == null) { + return ExtensionPropertyUtil.getGraduated( + OTLP_GRPC, extensionProperties, OtlpGrpcMetricExporterModel.class); + } + return otlpGrpc; + } + + @JsonProperty(OTLP_GRPC) + public PushMetricExporterModel setOtlpGrpc(OtlpGrpcMetricExporterModel otlpGrpc) { + this.otlpGrpc = otlpGrpc; + return this; + } + + /** + * Configure exporter to be console. + * + *

      If omitted, ignore. + */ + @JsonProperty(CONSOLE) + @Nullable + public ConsoleMetricExporterModel getConsole() { + if (console == null) { + return ExtensionPropertyUtil.getGraduated( + CONSOLE, extensionProperties, ConsoleMetricExporterModel.class); + } + return console; + } + + @JsonProperty(CONSOLE) + public PushMetricExporterModel setConsole(ConsoleMetricExporterModel console) { + this.console = console; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public PushMetricExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "PushMetricExporterModel{" + + "otlpHttp=" + + otlpHttp + + ", otlpGrpc=" + + otlpGrpc + + ", console=" + + console + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getOtlpHttp() == null) ? 0 : this.getOtlpHttp().hashCode(); + h *= 1000003; + h ^= (this.getOtlpGrpc() == null) ? 0 : this.getOtlpGrpc().hashCode(); + h *= 1000003; + h ^= (this.getConsole() == null) ? 0 : this.getConsole().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof PushMetricExporterModel) { + PushMetricExporterModel that = (PushMetricExporterModel) o; + return (this.getOtlpHttp() == null + ? that.getOtlpHttp() == null + : this.getOtlpHttp().equals(that.getOtlpHttp())) + && (this.getOtlpGrpc() == null + ? that.getOtlpGrpc() == null + : this.getOtlpGrpc().equals(that.getOtlpGrpc())) + && (this.getConsole() == null + ? that.getConsole() == null + : this.getConsole().equals(that.getConsole())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/RandomIdGeneratorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/RandomIdGeneratorModel.java new file mode 100644 index 00000000000..db908c42caf --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/RandomIdGeneratorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class RandomIdGeneratorModel { + + @Override + public String toString() { + return "RandomIdGeneratorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof RandomIdGeneratorModel) { + RandomIdGeneratorModel that = (RandomIdGeneratorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ResourceModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ResourceModel.java new file mode 100644 index 00000000000..e7e7ec561a6 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ResourceModel.java @@ -0,0 +1,181 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel.ATTRIBUTES; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel.ATTRIBUTES_LIST; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel.SCHEMA_URL; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ResourceModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ATTRIBUTES, SCHEMA_URL, ATTRIBUTES_LIST}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ResourceModel { + + static final String ATTRIBUTES = "attributes"; + static final String SCHEMA_URL = "schema_url"; + static final String ATTRIBUTES_LIST = "attributes_list"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(SCHEMA_URL, String.class); + STABLE_PROPERTIES.put(ATTRIBUTES_LIST, String.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private List attributes; + @Nullable private String schemaUrl; + @Nullable private String attributesList; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure resource attributes. Entries have higher priority than entries from + * .resource.attributes_list. + * + *

      If omitted, no resource attributes are added. + */ + @JsonProperty(ATTRIBUTES) + @Nullable + public List getAttributes() { + return attributes; + } + + @JsonProperty(ATTRIBUTES) + public ResourceModel setAttributes(List attributes) { + this.attributes = attributes; + return this; + } + + /** + * Configure resource schema URL. + * + *

      If omitted or null, no schema URL is used. + */ + @JsonProperty(SCHEMA_URL) + @Nullable + public String getSchemaUrl() { + if (schemaUrl == null) { + return ExtensionPropertyUtil.getGraduated(SCHEMA_URL, extensionProperties, String.class); + } + return schemaUrl; + } + + @JsonProperty(SCHEMA_URL) + public ResourceModel setSchemaUrl(String schemaUrl) { + this.schemaUrl = schemaUrl; + return this; + } + + /** + * Configure resource attributes. Entries have lower priority than entries from + * .resource.attributes. + * + *

      The value is a list of comma separated key-value pairs matching the format of + * OTEL_RESOURCE_ATTRIBUTES. See + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md#general-sdk-configuration + * for details. + * + *

      If omitted or null, no resource attributes are added. + */ + @JsonProperty(ATTRIBUTES_LIST) + @Nullable + public String getAttributesList() { + if (attributesList == null) { + return ExtensionPropertyUtil.getGraduated(ATTRIBUTES_LIST, extensionProperties, String.class); + } + return attributesList; + } + + @JsonProperty(ATTRIBUTES_LIST) + public ResourceModel setAttributesList(String attributesList) { + this.attributesList = attributesList; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ResourceModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ResourceModel{" + + "attributes=" + + attributes + + ", schemaUrl=" + + schemaUrl + + ", attributesList=" + + attributesList + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.attributes == null) ? 0 : this.attributes.hashCode(); + h *= 1000003; + h ^= (this.getSchemaUrl() == null) ? 0 : this.getSchemaUrl().hashCode(); + h *= 1000003; + h ^= (this.getAttributesList() == null) ? 0 : this.getAttributesList().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ResourceModel) { + ResourceModel that = (ResourceModel) o; + return (this.attributes == null + ? that.attributes == null + : this.attributes.equals(that.attributes)) + && (this.getSchemaUrl() == null + ? that.getSchemaUrl() == null + : this.getSchemaUrl().equals(that.getSchemaUrl())) + && (this.getAttributesList() == null + ? that.getAttributesList() == null + : this.getAttributesList().equals(that.getAttributesList())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SamplerModel.java new file mode 100644 index 00000000000..2d73d1a5848 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SamplerModel.java @@ -0,0 +1,244 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel.ALWAYS_OFF; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel.ALWAYS_ON; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel.ALWAYS_RECORD; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel.PARENT_BASED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel.TRACE_ID_RATIO_BASED; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.SamplerModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ALWAYS_OFF, ALWAYS_ON, ALWAYS_RECORD, PARENT_BASED, TRACE_ID_RATIO_BASED}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SamplerModel { + + static final String ALWAYS_OFF = "always_off"; + static final String ALWAYS_ON = "always_on"; + static final String ALWAYS_RECORD = "always_record"; + static final String PARENT_BASED = "parent_based"; + static final String TRACE_ID_RATIO_BASED = "trace_id_ratio_based"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ALWAYS_OFF, AlwaysOffSamplerModel.class); + STABLE_PROPERTIES.put(ALWAYS_ON, AlwaysOnSamplerModel.class); + STABLE_PROPERTIES.put(ALWAYS_RECORD, AlwaysRecordSamplerModel.class); + STABLE_PROPERTIES.put(PARENT_BASED, ParentBasedSamplerModel.class); + STABLE_PROPERTIES.put(TRACE_ID_RATIO_BASED, TraceIdRatioBasedSamplerModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private AlwaysOffSamplerModel alwaysOff; + @Nullable private AlwaysOnSamplerModel alwaysOn; + @Nullable private AlwaysRecordSamplerModel alwaysRecord; + @Nullable private ParentBasedSamplerModel parentBased; + @Nullable private TraceIdRatioBasedSamplerModel traceIdRatioBased; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure sampler to be always_off. + * + *

      If omitted, ignore. + */ + @JsonProperty(ALWAYS_OFF) + @Nullable + public AlwaysOffSamplerModel getAlwaysOff() { + if (alwaysOff == null) { + return ExtensionPropertyUtil.getGraduated( + ALWAYS_OFF, extensionProperties, AlwaysOffSamplerModel.class); + } + return alwaysOff; + } + + @JsonProperty(ALWAYS_OFF) + public SamplerModel setAlwaysOff(AlwaysOffSamplerModel alwaysOff) { + this.alwaysOff = alwaysOff; + return this; + } + + /** + * Configure sampler to be always_on. + * + *

      If omitted, ignore. + */ + @JsonProperty(ALWAYS_ON) + @Nullable + public AlwaysOnSamplerModel getAlwaysOn() { + if (alwaysOn == null) { + return ExtensionPropertyUtil.getGraduated( + ALWAYS_ON, extensionProperties, AlwaysOnSamplerModel.class); + } + return alwaysOn; + } + + @JsonProperty(ALWAYS_ON) + public SamplerModel setAlwaysOn(AlwaysOnSamplerModel alwaysOn) { + this.alwaysOn = alwaysOn; + return this; + } + + /** + * Configure sampler to be always_record. + * + *

      If omitted, ignore. + */ + @JsonProperty(ALWAYS_RECORD) + @Nullable + public AlwaysRecordSamplerModel getAlwaysRecord() { + if (alwaysRecord == null) { + return ExtensionPropertyUtil.getGraduated( + ALWAYS_RECORD, extensionProperties, AlwaysRecordSamplerModel.class); + } + return alwaysRecord; + } + + @JsonProperty(ALWAYS_RECORD) + public SamplerModel setAlwaysRecord(AlwaysRecordSamplerModel alwaysRecord) { + this.alwaysRecord = alwaysRecord; + return this; + } + + /** + * Configure sampler to be parent_based. + * + *

      If omitted, ignore. + */ + @JsonProperty(PARENT_BASED) + @Nullable + public ParentBasedSamplerModel getParentBased() { + if (parentBased == null) { + return ExtensionPropertyUtil.getGraduated( + PARENT_BASED, extensionProperties, ParentBasedSamplerModel.class); + } + return parentBased; + } + + @JsonProperty(PARENT_BASED) + public SamplerModel setParentBased(ParentBasedSamplerModel parentBased) { + this.parentBased = parentBased; + return this; + } + + /** + * Configure sampler to be trace_id_ratio_based. + * + *

      If omitted, ignore. + */ + @JsonProperty(TRACE_ID_RATIO_BASED) + @Nullable + public TraceIdRatioBasedSamplerModel getTraceIdRatioBased() { + if (traceIdRatioBased == null) { + return ExtensionPropertyUtil.getGraduated( + TRACE_ID_RATIO_BASED, extensionProperties, TraceIdRatioBasedSamplerModel.class); + } + return traceIdRatioBased; + } + + @JsonProperty(TRACE_ID_RATIO_BASED) + public SamplerModel setTraceIdRatioBased(TraceIdRatioBasedSamplerModel traceIdRatioBased) { + this.traceIdRatioBased = traceIdRatioBased; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public SamplerModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "SamplerModel{" + + "alwaysOff=" + + alwaysOff + + ", alwaysOn=" + + alwaysOn + + ", alwaysRecord=" + + alwaysRecord + + ", parentBased=" + + parentBased + + ", traceIdRatioBased=" + + traceIdRatioBased + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getAlwaysOff() == null) ? 0 : this.getAlwaysOff().hashCode(); + h *= 1000003; + h ^= (this.getAlwaysOn() == null) ? 0 : this.getAlwaysOn().hashCode(); + h *= 1000003; + h ^= (this.getAlwaysRecord() == null) ? 0 : this.getAlwaysRecord().hashCode(); + h *= 1000003; + h ^= (this.getParentBased() == null) ? 0 : this.getParentBased().hashCode(); + h *= 1000003; + h ^= (this.getTraceIdRatioBased() == null) ? 0 : this.getTraceIdRatioBased().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SamplerModel) { + SamplerModel that = (SamplerModel) o; + return (this.getAlwaysOff() == null + ? that.getAlwaysOff() == null + : this.getAlwaysOff().equals(that.getAlwaysOff())) + && (this.getAlwaysOn() == null + ? that.getAlwaysOn() == null + : this.getAlwaysOn().equals(that.getAlwaysOn())) + && (this.getAlwaysRecord() == null + ? that.getAlwaysRecord() == null + : this.getAlwaysRecord().equals(that.getAlwaysRecord())) + && (this.getParentBased() == null + ? that.getParentBased() == null + : this.getParentBased().equals(that.getParentBased())) + && (this.getTraceIdRatioBased() == null + ? that.getTraceIdRatioBased() == null + : this.getTraceIdRatioBased().equals(that.getTraceIdRatioBased())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SeverityNumberModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SeverityNumberModel.java new file mode 100644 index 00000000000..0ff2fbd1293 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SeverityNumberModel.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum SeverityNumberModel { + TRACE("trace"), + TRACE_2("trace2"), + TRACE_3("trace3"), + TRACE_4("trace4"), + DEBUG("debug"), + DEBUG_2("debug2"), + DEBUG_3("debug3"), + DEBUG_4("debug4"), + INFO("info"), + INFO_2("info2"), + INFO_3("info3"), + INFO_4("info4"), + WARN("warn"), + WARN_2("warn2"), + WARN_3("warn3"), + WARN_4("warn4"), + ERROR("error"), + ERROR_2("error2"), + ERROR_3("error3"), + ERROR_4("error4"), + FATAL("fatal"), + FATAL_2("fatal2"), + FATAL_3("fatal3"), + FATAL_4("fatal4"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (SeverityNumberModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + SeverityNumberModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static SeverityNumberModel fromValue(String value) { + SeverityNumberModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SimpleLogRecordProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SimpleLogRecordProcessorModel.java new file mode 100644 index 00000000000..a71b8bcf60e --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SimpleLogRecordProcessorModel.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleLogRecordProcessorModel.EXPORTER; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({EXPORTER}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SimpleLogRecordProcessorModel { + + static final String EXPORTER = "exporter"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(EXPORTER, LogRecordExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private LogRecordExporterModel exporter; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure exporter. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(EXPORTER) + @Nullable + public LogRecordExporterModel getExporter() { + if (exporter == null) { + return ExtensionPropertyUtil.getGraduated( + EXPORTER, extensionProperties, LogRecordExporterModel.class); + } + return exporter; + } + + @JsonProperty(EXPORTER) + public SimpleLogRecordProcessorModel setExporter(LogRecordExporterModel exporter) { + this.exporter = exporter; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public SimpleLogRecordProcessorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "SimpleLogRecordProcessorModel{" + + "exporter=" + + exporter + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getExporter() == null) ? 0 : this.getExporter().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SimpleLogRecordProcessorModel) { + SimpleLogRecordProcessorModel that = (SimpleLogRecordProcessorModel) o; + return (this.getExporter() == null + ? that.getExporter() == null + : this.getExporter().equals(that.getExporter())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SimpleSpanProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SimpleSpanProcessorModel.java new file mode 100644 index 00000000000..3680b064c93 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SimpleSpanProcessorModel.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleSpanProcessorModel.EXPORTER; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({EXPORTER}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SimpleSpanProcessorModel { + + static final String EXPORTER = "exporter"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(EXPORTER, SpanExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private SpanExporterModel exporter; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure exporter. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(EXPORTER) + @Nullable + public SpanExporterModel getExporter() { + if (exporter == null) { + return ExtensionPropertyUtil.getGraduated( + EXPORTER, extensionProperties, SpanExporterModel.class); + } + return exporter; + } + + @JsonProperty(EXPORTER) + public SimpleSpanProcessorModel setExporter(SpanExporterModel exporter) { + this.exporter = exporter; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public SimpleSpanProcessorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "SimpleSpanProcessorModel{" + + "exporter=" + + exporter + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getExporter() == null) ? 0 : this.getExporter().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SimpleSpanProcessorModel) { + SimpleSpanProcessorModel that = (SimpleSpanProcessorModel) o; + return (this.getExporter() == null + ? that.getExporter() == null + : this.getExporter().equals(that.getExporter())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanExporterModel.java new file mode 100644 index 00000000000..859fc0da024 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanExporterModel.java @@ -0,0 +1,180 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel.CONSOLE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel.OTLP_GRPC; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel.OTLP_HTTP; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.SpanExporterModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({OTLP_HTTP, OTLP_GRPC, CONSOLE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SpanExporterModel { + + static final String OTLP_HTTP = "otlp_http"; + static final String OTLP_GRPC = "otlp_grpc"; + static final String CONSOLE = "console"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(OTLP_HTTP, OtlpHttpExporterModel.class); + STABLE_PROPERTIES.put(OTLP_GRPC, OtlpGrpcExporterModel.class); + STABLE_PROPERTIES.put(CONSOLE, ConsoleExporterModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private OtlpHttpExporterModel otlpHttp; + @Nullable private OtlpGrpcExporterModel otlpGrpc; + @Nullable private ConsoleExporterModel console; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure exporter to be OTLP with HTTP transport. + * + *

      If omitted, ignore. + */ + @JsonProperty(OTLP_HTTP) + @Nullable + public OtlpHttpExporterModel getOtlpHttp() { + if (otlpHttp == null) { + return ExtensionPropertyUtil.getGraduated( + OTLP_HTTP, extensionProperties, OtlpHttpExporterModel.class); + } + return otlpHttp; + } + + @JsonProperty(OTLP_HTTP) + public SpanExporterModel setOtlpHttp(OtlpHttpExporterModel otlpHttp) { + this.otlpHttp = otlpHttp; + return this; + } + + /** + * Configure exporter to be OTLP with gRPC transport. + * + *

      If omitted, ignore. + */ + @JsonProperty(OTLP_GRPC) + @Nullable + public OtlpGrpcExporterModel getOtlpGrpc() { + if (otlpGrpc == null) { + return ExtensionPropertyUtil.getGraduated( + OTLP_GRPC, extensionProperties, OtlpGrpcExporterModel.class); + } + return otlpGrpc; + } + + @JsonProperty(OTLP_GRPC) + public SpanExporterModel setOtlpGrpc(OtlpGrpcExporterModel otlpGrpc) { + this.otlpGrpc = otlpGrpc; + return this; + } + + /** + * Configure exporter to be console. + * + *

      If omitted, ignore. + */ + @JsonProperty(CONSOLE) + @Nullable + public ConsoleExporterModel getConsole() { + if (console == null) { + return ExtensionPropertyUtil.getGraduated( + CONSOLE, extensionProperties, ConsoleExporterModel.class); + } + return console; + } + + @JsonProperty(CONSOLE) + public SpanExporterModel setConsole(ConsoleExporterModel console) { + this.console = console; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public SpanExporterModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "SpanExporterModel{" + + "otlpHttp=" + + otlpHttp + + ", otlpGrpc=" + + otlpGrpc + + ", console=" + + console + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getOtlpHttp() == null) ? 0 : this.getOtlpHttp().hashCode(); + h *= 1000003; + h ^= (this.getOtlpGrpc() == null) ? 0 : this.getOtlpGrpc().hashCode(); + h *= 1000003; + h ^= (this.getConsole() == null) ? 0 : this.getConsole().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SpanExporterModel) { + SpanExporterModel that = (SpanExporterModel) o; + return (this.getOtlpHttp() == null + ? that.getOtlpHttp() == null + : this.getOtlpHttp().equals(that.getOtlpHttp())) + && (this.getOtlpGrpc() == null + ? that.getOtlpGrpc() == null + : this.getOtlpGrpc().equals(that.getOtlpGrpc())) + && (this.getConsole() == null + ? that.getConsole() == null + : this.getConsole().equals(that.getConsole())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanKindModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanKindModel.java new file mode 100644 index 00000000000..d02369a4c3c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanKindModel.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum SpanKindModel { + INTERNAL("internal"), + SERVER("server"), + CLIENT("client"), + PRODUCER("producer"), + CONSUMER("consumer"); + private final String value; + private static final Map CONSTANTS = new HashMap(); + + static { + for (SpanKindModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + SpanKindModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static SpanKindModel fromValue(String value) { + SpanKindModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanLimitsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanLimitsModel.java new file mode 100644 index 00000000000..dd414a95e66 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanLimitsModel.java @@ -0,0 +1,348 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.ATTRIBUTE_COUNT_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.ATTRIBUTE_VALUE_DEPTH_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.ATTRIBUTE_VALUE_LENGTH_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.EVENT_ATTRIBUTE_COUNT_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.EVENT_COUNT_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.LINK_ATTRIBUTE_COUNT_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel.LINK_COUNT_LIMIT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + ATTRIBUTE_VALUE_LENGTH_LIMIT, + ATTRIBUTE_VALUE_DEPTH_LIMIT, + ATTRIBUTE_COUNT_LIMIT, + EVENT_COUNT_LIMIT, + LINK_COUNT_LIMIT, + EVENT_ATTRIBUTE_COUNT_LIMIT, + LINK_ATTRIBUTE_COUNT_LIMIT +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SpanLimitsModel { + + static final String ATTRIBUTE_VALUE_LENGTH_LIMIT = "attribute_value_length_limit"; + static final String ATTRIBUTE_VALUE_DEPTH_LIMIT = "attribute_value_depth_limit"; + static final String ATTRIBUTE_COUNT_LIMIT = "attribute_count_limit"; + static final String EVENT_COUNT_LIMIT = "event_count_limit"; + static final String LINK_COUNT_LIMIT = "link_count_limit"; + static final String EVENT_ATTRIBUTE_COUNT_LIMIT = "event_attribute_count_limit"; + static final String LINK_ATTRIBUTE_COUNT_LIMIT = "link_attribute_count_limit"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(ATTRIBUTE_VALUE_LENGTH_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_VALUE_DEPTH_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_COUNT_LIMIT, Integer.class); + STABLE_PROPERTIES.put(EVENT_COUNT_LIMIT, Integer.class); + STABLE_PROPERTIES.put(LINK_COUNT_LIMIT, Integer.class); + STABLE_PROPERTIES.put(EVENT_ATTRIBUTE_COUNT_LIMIT, Integer.class); + STABLE_PROPERTIES.put(LINK_ATTRIBUTE_COUNT_LIMIT, Integer.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Integer attributeValueLengthLimit; + @Nullable private Integer attributeValueDepthLimit; + @Nullable private Integer attributeCountLimit; + @Nullable private Integer eventCountLimit; + @Nullable private Integer linkCountLimit; + @Nullable private Integer eventAttributeCountLimit; + @Nullable private Integer linkAttributeCountLimit; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure max attribute value size. Overrides .attribute_limits.attribute_value_length_limit. + * + *

      Value must be non-negative. + * + *

      If omitted or null, there is no limit. + */ + @JsonProperty(ATTRIBUTE_VALUE_LENGTH_LIMIT) + @Nullable + public Integer getAttributeValueLengthLimit() { + if (attributeValueLengthLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_VALUE_LENGTH_LIMIT, extensionProperties, Integer.class); + } + return attributeValueLengthLimit; + } + + @JsonProperty(ATTRIBUTE_VALUE_LENGTH_LIMIT) + public SpanLimitsModel setAttributeValueLengthLimit(Integer attributeValueLengthLimit) { + this.attributeValueLengthLimit = attributeValueLengthLimit; + return this; + } + + /** + * Configure the maximum attribute value depth for nested array and map values. Overrides + * .attribute_limits.attribute_value_depth_limit. + * + *

      Depth starts at 1 for the top-level attribute value and increments when descending into + * array elements or map values. + * + *

      Array or map values deeper than the limit are replaced with an empty value. + * + *

      Value must be positive. + * + *

      If omitted or null, 64 is used. + */ + @JsonProperty(ATTRIBUTE_VALUE_DEPTH_LIMIT) + @Nullable + public Integer getAttributeValueDepthLimit() { + if (attributeValueDepthLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_VALUE_DEPTH_LIMIT, extensionProperties, Integer.class); + } + return attributeValueDepthLimit; + } + + @JsonProperty(ATTRIBUTE_VALUE_DEPTH_LIMIT) + public SpanLimitsModel setAttributeValueDepthLimit(Integer attributeValueDepthLimit) { + this.attributeValueDepthLimit = attributeValueDepthLimit; + return this; + } + + /** + * Configure max attribute count. Overrides .attribute_limits.attribute_count_limit. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(ATTRIBUTE_COUNT_LIMIT) + @Nullable + public Integer getAttributeCountLimit() { + if (attributeCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_COUNT_LIMIT, extensionProperties, Integer.class); + } + return attributeCountLimit; + } + + @JsonProperty(ATTRIBUTE_COUNT_LIMIT) + public SpanLimitsModel setAttributeCountLimit(Integer attributeCountLimit) { + this.attributeCountLimit = attributeCountLimit; + return this; + } + + /** + * Configure max span event count. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(EVENT_COUNT_LIMIT) + @Nullable + public Integer getEventCountLimit() { + if (eventCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + EVENT_COUNT_LIMIT, extensionProperties, Integer.class); + } + return eventCountLimit; + } + + @JsonProperty(EVENT_COUNT_LIMIT) + public SpanLimitsModel setEventCountLimit(Integer eventCountLimit) { + this.eventCountLimit = eventCountLimit; + return this; + } + + /** + * Configure max span link count. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(LINK_COUNT_LIMIT) + @Nullable + public Integer getLinkCountLimit() { + if (linkCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + LINK_COUNT_LIMIT, extensionProperties, Integer.class); + } + return linkCountLimit; + } + + @JsonProperty(LINK_COUNT_LIMIT) + public SpanLimitsModel setLinkCountLimit(Integer linkCountLimit) { + this.linkCountLimit = linkCountLimit; + return this; + } + + /** + * Configure max attributes per span event. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(EVENT_ATTRIBUTE_COUNT_LIMIT) + @Nullable + public Integer getEventAttributeCountLimit() { + if (eventAttributeCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + EVENT_ATTRIBUTE_COUNT_LIMIT, extensionProperties, Integer.class); + } + return eventAttributeCountLimit; + } + + @JsonProperty(EVENT_ATTRIBUTE_COUNT_LIMIT) + public SpanLimitsModel setEventAttributeCountLimit(Integer eventAttributeCountLimit) { + this.eventAttributeCountLimit = eventAttributeCountLimit; + return this; + } + + /** + * Configure max attributes per span link. + * + *

      Value must be non-negative. + * + *

      If omitted or null, 128 is used. + */ + @JsonProperty(LINK_ATTRIBUTE_COUNT_LIMIT) + @Nullable + public Integer getLinkAttributeCountLimit() { + if (linkAttributeCountLimit == null) { + return ExtensionPropertyUtil.getGraduated( + LINK_ATTRIBUTE_COUNT_LIMIT, extensionProperties, Integer.class); + } + return linkAttributeCountLimit; + } + + @JsonProperty(LINK_ATTRIBUTE_COUNT_LIMIT) + public SpanLimitsModel setLinkAttributeCountLimit(Integer linkAttributeCountLimit) { + this.linkAttributeCountLimit = linkAttributeCountLimit; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public SpanLimitsModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "SpanLimitsModel{" + + "attributeValueLengthLimit=" + + attributeValueLengthLimit + + ", attributeValueDepthLimit=" + + attributeValueDepthLimit + + ", attributeCountLimit=" + + attributeCountLimit + + ", eventCountLimit=" + + eventCountLimit + + ", linkCountLimit=" + + linkCountLimit + + ", eventAttributeCountLimit=" + + eventAttributeCountLimit + + ", linkAttributeCountLimit=" + + linkAttributeCountLimit + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= + (this.getAttributeValueLengthLimit() == null) + ? 0 + : this.getAttributeValueLengthLimit().hashCode(); + h *= 1000003; + h ^= + (this.getAttributeValueDepthLimit() == null) + ? 0 + : this.getAttributeValueDepthLimit().hashCode(); + h *= 1000003; + h ^= (this.getAttributeCountLimit() == null) ? 0 : this.getAttributeCountLimit().hashCode(); + h *= 1000003; + h ^= (this.getEventCountLimit() == null) ? 0 : this.getEventCountLimit().hashCode(); + h *= 1000003; + h ^= (this.getLinkCountLimit() == null) ? 0 : this.getLinkCountLimit().hashCode(); + h *= 1000003; + h ^= + (this.getEventAttributeCountLimit() == null) + ? 0 + : this.getEventAttributeCountLimit().hashCode(); + h *= 1000003; + h ^= + (this.getLinkAttributeCountLimit() == null) + ? 0 + : this.getLinkAttributeCountLimit().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SpanLimitsModel) { + SpanLimitsModel that = (SpanLimitsModel) o; + return (this.getAttributeValueLengthLimit() == null + ? that.getAttributeValueLengthLimit() == null + : this.getAttributeValueLengthLimit().equals(that.getAttributeValueLengthLimit())) + && (this.getAttributeValueDepthLimit() == null + ? that.getAttributeValueDepthLimit() == null + : this.getAttributeValueDepthLimit().equals(that.getAttributeValueDepthLimit())) + && (this.getAttributeCountLimit() == null + ? that.getAttributeCountLimit() == null + : this.getAttributeCountLimit().equals(that.getAttributeCountLimit())) + && (this.getEventCountLimit() == null + ? that.getEventCountLimit() == null + : this.getEventCountLimit().equals(that.getEventCountLimit())) + && (this.getLinkCountLimit() == null + ? that.getLinkCountLimit() == null + : this.getLinkCountLimit().equals(that.getLinkCountLimit())) + && (this.getEventAttributeCountLimit() == null + ? that.getEventAttributeCountLimit() == null + : this.getEventAttributeCountLimit().equals(that.getEventAttributeCountLimit())) + && (this.getLinkAttributeCountLimit() == null + ? that.getLinkAttributeCountLimit() == null + : this.getLinkAttributeCountLimit().equals(that.getLinkAttributeCountLimit())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanProcessorModel.java new file mode 100644 index 00000000000..398a32e4cd5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SpanProcessorModel.java @@ -0,0 +1,148 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel.BATCH; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel.SIMPLE; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({BATCH, SIMPLE}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SpanProcessorModel { + + static final String BATCH = "batch"; + static final String SIMPLE = "simple"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(BATCH, BatchSpanProcessorModel.class); + STABLE_PROPERTIES.put(SIMPLE, SimpleSpanProcessorModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private BatchSpanProcessorModel batch; + @Nullable private SimpleSpanProcessorModel simple; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure a batch span processor. + * + *

      If omitted, ignore. + */ + @JsonProperty(BATCH) + @Nullable + public BatchSpanProcessorModel getBatch() { + if (batch == null) { + return ExtensionPropertyUtil.getGraduated( + BATCH, extensionProperties, BatchSpanProcessorModel.class); + } + return batch; + } + + @JsonProperty(BATCH) + public SpanProcessorModel setBatch(BatchSpanProcessorModel batch) { + this.batch = batch; + return this; + } + + /** + * Configure a simple span processor. + * + *

      If omitted, ignore. + */ + @JsonProperty(SIMPLE) + @Nullable + public SimpleSpanProcessorModel getSimple() { + if (simple == null) { + return ExtensionPropertyUtil.getGraduated( + SIMPLE, extensionProperties, SimpleSpanProcessorModel.class); + } + return simple; + } + + @JsonProperty(SIMPLE) + public SpanProcessorModel setSimple(SimpleSpanProcessorModel simple) { + this.simple = simple; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public SpanProcessorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "SpanProcessorModel{" + + "batch=" + + batch + + ", simple=" + + simple + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getBatch() == null) ? 0 : this.getBatch().hashCode(); + h *= 1000003; + h ^= (this.getSimple() == null) ? 0 : this.getSimple().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SpanProcessorModel) { + SpanProcessorModel that = (SpanProcessorModel) o; + return (this.getBatch() == null + ? that.getBatch() == null + : this.getBatch().equals(that.getBatch())) + && (this.getSimple() == null + ? that.getSimple() == null + : this.getSimple().equals(that.getSimple())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SumAggregationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SumAggregationModel.java new file mode 100644 index 00000000000..93c6e60b792 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/SumAggregationModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class SumAggregationModel { + + @Override + public String toString() { + return "SumAggregationModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof SumAggregationModel) { + SumAggregationModel that = (SumAggregationModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TextMapPropagatorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TextMapPropagatorModel.java new file mode 100644 index 00000000000..dd0c20a357f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TextMapPropagatorModel.java @@ -0,0 +1,209 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel.BAGGAGE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel.B_3; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel.B_3_MULTI; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel.TRACECONTEXT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({TRACECONTEXT, BAGGAGE, B_3, B_3_MULTI}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class TextMapPropagatorModel { + + static final String TRACECONTEXT = "tracecontext"; + static final String BAGGAGE = "baggage"; + static final String B_3 = "b3"; + static final String B_3_MULTI = "b3multi"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(TRACECONTEXT, TraceContextPropagatorModel.class); + STABLE_PROPERTIES.put(BAGGAGE, BaggagePropagatorModel.class); + STABLE_PROPERTIES.put(B_3, B3PropagatorModel.class); + STABLE_PROPERTIES.put(B_3_MULTI, B3MultiPropagatorModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = true; + + @Nullable private TraceContextPropagatorModel tracecontext; + @Nullable private BaggagePropagatorModel baggage; + @Nullable private B3PropagatorModel b3; + @Nullable private B3MultiPropagatorModel b3multi; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Include the w3c trace context propagator. + * + *

      If omitted, ignore. + */ + @JsonProperty(TRACECONTEXT) + @Nullable + public TraceContextPropagatorModel getTracecontext() { + if (tracecontext == null) { + return ExtensionPropertyUtil.getGraduated( + TRACECONTEXT, extensionProperties, TraceContextPropagatorModel.class); + } + return tracecontext; + } + + @JsonProperty(TRACECONTEXT) + public TextMapPropagatorModel setTracecontext(TraceContextPropagatorModel tracecontext) { + this.tracecontext = tracecontext; + return this; + } + + /** + * Include the w3c baggage propagator. + * + *

      If omitted, ignore. + */ + @JsonProperty(BAGGAGE) + @Nullable + public BaggagePropagatorModel getBaggage() { + if (baggage == null) { + return ExtensionPropertyUtil.getGraduated( + BAGGAGE, extensionProperties, BaggagePropagatorModel.class); + } + return baggage; + } + + @JsonProperty(BAGGAGE) + public TextMapPropagatorModel setBaggage(BaggagePropagatorModel baggage) { + this.baggage = baggage; + return this; + } + + /** + * Include the zipkin b3 propagator. + * + *

      If omitted, ignore. + */ + @JsonProperty(B_3) + @Nullable + public B3PropagatorModel getB3() { + if (b3 == null) { + return ExtensionPropertyUtil.getGraduated(B_3, extensionProperties, B3PropagatorModel.class); + } + return b3; + } + + @JsonProperty(B_3) + public TextMapPropagatorModel setB3(B3PropagatorModel b3) { + this.b3 = b3; + return this; + } + + /** + * Include the zipkin b3 multi propagator. + * + *

      If omitted, ignore. + */ + @JsonProperty(B_3_MULTI) + @Nullable + public B3MultiPropagatorModel getB3multi() { + if (b3multi == null) { + return ExtensionPropertyUtil.getGraduated( + B_3_MULTI, extensionProperties, B3MultiPropagatorModel.class); + } + return b3multi; + } + + @JsonProperty(B_3_MULTI) + public TextMapPropagatorModel setB3multi(B3MultiPropagatorModel b3multi) { + this.b3multi = b3multi; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public TextMapPropagatorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "TextMapPropagatorModel{" + + "tracecontext=" + + tracecontext + + ", baggage=" + + baggage + + ", b3=" + + b3 + + ", b3multi=" + + b3multi + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getTracecontext() == null) ? 0 : this.getTracecontext().hashCode(); + h *= 1000003; + h ^= (this.getBaggage() == null) ? 0 : this.getBaggage().hashCode(); + h *= 1000003; + h ^= (this.getB3() == null) ? 0 : this.getB3().hashCode(); + h *= 1000003; + h ^= (this.getB3multi() == null) ? 0 : this.getB3multi().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof TextMapPropagatorModel) { + TextMapPropagatorModel that = (TextMapPropagatorModel) o; + return (this.getTracecontext() == null + ? that.getTracecontext() == null + : this.getTracecontext().equals(that.getTracecontext())) + && (this.getBaggage() == null + ? that.getBaggage() == null + : this.getBaggage().equals(that.getBaggage())) + && (this.getB3() == null ? that.getB3() == null : this.getB3().equals(that.getB3())) + && (this.getB3multi() == null + ? that.getB3multi() == null + : this.getB3multi().equals(that.getB3multi())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TraceContextPropagatorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TraceContextPropagatorModel.java new file mode 100644 index 00000000000..08094e0c57c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TraceContextPropagatorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class TraceContextPropagatorModel { + + @Override + public String toString() { + return "TraceContextPropagatorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof TraceContextPropagatorModel) { + TraceContextPropagatorModel that = (TraceContextPropagatorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TraceIdRatioBasedSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TraceIdRatioBasedSamplerModel.java new file mode 100644 index 00000000000..cf15908486b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TraceIdRatioBasedSamplerModel.java @@ -0,0 +1,115 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TraceIdRatioBasedSamplerModel.RATIO; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({RATIO}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class TraceIdRatioBasedSamplerModel { + + static final String RATIO = "ratio"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(RATIO, Double.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private Double ratio; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure trace_id_ratio. + * + *

      If omitted or null, 1.0 is used. + */ + @JsonProperty(RATIO) + @Nullable + public Double getRatio() { + if (ratio == null) { + return ExtensionPropertyUtil.getGraduated(RATIO, extensionProperties, Double.class); + } + return ratio; + } + + @JsonProperty(RATIO) + public TraceIdRatioBasedSamplerModel setRatio(Double ratio) { + this.ratio = ratio; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public TraceIdRatioBasedSamplerModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "TraceIdRatioBasedSamplerModel{" + + "ratio=" + + ratio + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getRatio() == null) ? 0 : this.getRatio().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof TraceIdRatioBasedSamplerModel) { + TraceIdRatioBasedSamplerModel that = (TraceIdRatioBasedSamplerModel) o; + return (this.getRatio() == null + ? that.getRatio() == null + : this.getRatio().equals(that.getRatio())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TracerProviderModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TracerProviderModel.java new file mode 100644 index 00000000000..a7b361e90da --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/TracerProviderModel.java @@ -0,0 +1,206 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel.ID_GENERATOR; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel.LIMITS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel.PROCESSORS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel.SAMPLER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.TracerProviderModelAccessor.EXPERIMENTAL_PROPERTIES; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({PROCESSORS, LIMITS, SAMPLER, ID_GENERATOR}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class TracerProviderModel { + + static final String PROCESSORS = "processors"; + static final String LIMITS = "limits"; + static final String SAMPLER = "sampler"; + static final String ID_GENERATOR = "id_generator"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(LIMITS, SpanLimitsModel.class); + STABLE_PROPERTIES.put(SAMPLER, SamplerModel.class); + STABLE_PROPERTIES.put(ID_GENERATOR, IdGeneratorModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private List processors; + @Nullable private SpanLimitsModel limits; + @Nullable private SamplerModel sampler; + @Nullable private IdGeneratorModel idGenerator; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure span processors. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(PROCESSORS) + @Nullable + public List getProcessors() { + return processors; + } + + @JsonProperty(PROCESSORS) + public TracerProviderModel setProcessors(List processors) { + this.processors = processors; + return this; + } + + /** + * Configure span limits. See also attribute_limits. + * + *

      If omitted, default values as described in SpanLimits are used. + */ + @JsonProperty(LIMITS) + @Nullable + public SpanLimitsModel getLimits() { + if (limits == null) { + return ExtensionPropertyUtil.getGraduated(LIMITS, extensionProperties, SpanLimitsModel.class); + } + return limits; + } + + @JsonProperty(LIMITS) + public TracerProviderModel setLimits(SpanLimitsModel limits) { + this.limits = limits; + return this; + } + + /** + * Configure the sampler. + * + *

      If omitted, parent based sampler with a root of always_on is used. + */ + @JsonProperty(SAMPLER) + @Nullable + public SamplerModel getSampler() { + if (sampler == null) { + return ExtensionPropertyUtil.getGraduated(SAMPLER, extensionProperties, SamplerModel.class); + } + return sampler; + } + + @JsonProperty(SAMPLER) + public TracerProviderModel setSampler(SamplerModel sampler) { + this.sampler = sampler; + return this; + } + + /** + * Configure the trace and span ID generator. + * + *

      If omitted, RandomIdGenerator is used. + */ + @JsonProperty(ID_GENERATOR) + @Nullable + public IdGeneratorModel getIdGenerator() { + if (idGenerator == null) { + return ExtensionPropertyUtil.getGraduated( + ID_GENERATOR, extensionProperties, IdGeneratorModel.class); + } + return idGenerator; + } + + @JsonProperty(ID_GENERATOR) + public TracerProviderModel setIdGenerator(IdGeneratorModel idGenerator) { + this.idGenerator = idGenerator; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public TracerProviderModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + EXPERIMENTAL_PROPERTIES, + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "TracerProviderModel{" + + "processors=" + + processors + + ", limits=" + + limits + + ", sampler=" + + sampler + + ", idGenerator=" + + idGenerator + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.processors == null) ? 0 : this.processors.hashCode(); + h *= 1000003; + h ^= (this.getLimits() == null) ? 0 : this.getLimits().hashCode(); + h *= 1000003; + h ^= (this.getSampler() == null) ? 0 : this.getSampler().hashCode(); + h *= 1000003; + h ^= (this.getIdGenerator() == null) ? 0 : this.getIdGenerator().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof TracerProviderModel) { + TracerProviderModel that = (TracerProviderModel) o; + return (this.processors == null + ? that.processors == null + : this.processors.equals(that.processors)) + && (this.getLimits() == null + ? that.getLimits() == null + : this.getLimits().equals(that.getLimits())) + && (this.getSampler() == null + ? that.getSampler() == null + : this.getSampler().equals(that.getSampler())) + && (this.getIdGenerator() == null + ? that.getIdGenerator() == null + : this.getIdGenerator().equals(that.getIdGenerator())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewModel.java new file mode 100644 index 00000000000..5123c2e8c96 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewModel.java @@ -0,0 +1,150 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewModel.SELECTOR; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewModel.STREAM; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({SELECTOR, STREAM}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ViewModel { + + static final String SELECTOR = "selector"; + static final String STREAM = "stream"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(SELECTOR, ViewSelectorModel.class); + STABLE_PROPERTIES.put(STREAM, ViewStreamModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private ViewSelectorModel selector; + @Nullable private ViewStreamModel stream; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure view selector. + * + *

      Selection criteria is additive as described in + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#instrument-selection-criteria. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(SELECTOR) + @Nullable + public ViewSelectorModel getSelector() { + if (selector == null) { + return ExtensionPropertyUtil.getGraduated( + SELECTOR, extensionProperties, ViewSelectorModel.class); + } + return selector; + } + + @JsonProperty(SELECTOR) + public ViewModel setSelector(ViewSelectorModel selector) { + this.selector = selector; + return this; + } + + /** + * Configure view stream. + * + *

      Property is required and must be non-null. + */ + @JsonProperty(STREAM) + @Nullable + public ViewStreamModel getStream() { + if (stream == null) { + return ExtensionPropertyUtil.getGraduated(STREAM, extensionProperties, ViewStreamModel.class); + } + return stream; + } + + @JsonProperty(STREAM) + public ViewModel setStream(ViewStreamModel stream) { + this.stream = stream; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ViewModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ViewModel{" + + "selector=" + + selector + + ", stream=" + + stream + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getSelector() == null) ? 0 : this.getSelector().hashCode(); + h *= 1000003; + h ^= (this.getStream() == null) ? 0 : this.getStream().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ViewModel) { + ViewModel that = (ViewModel) o; + return (this.getSelector() == null + ? that.getSelector() == null + : this.getSelector().equals(that.getSelector())) + && (this.getStream() == null + ? that.getStream() == null + : this.getStream().equals(that.getStream())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewSelectorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewSelectorModel.java new file mode 100644 index 00000000000..8d3c01b5b1f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewSelectorModel.java @@ -0,0 +1,295 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel.INSTRUMENT_NAME; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel.INSTRUMENT_TYPE; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel.METER_NAME; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel.METER_SCHEMA_URL; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel.METER_VERSION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel.UNIT; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + INSTRUMENT_NAME, + INSTRUMENT_TYPE, + UNIT, + METER_NAME, + METER_VERSION, + METER_SCHEMA_URL +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ViewSelectorModel { + + static final String INSTRUMENT_NAME = "instrument_name"; + static final String INSTRUMENT_TYPE = "instrument_type"; + static final String UNIT = "unit"; + static final String METER_NAME = "meter_name"; + static final String METER_VERSION = "meter_version"; + static final String METER_SCHEMA_URL = "meter_schema_url"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(INSTRUMENT_NAME, String.class); + STABLE_PROPERTIES.put(INSTRUMENT_TYPE, InstrumentTypeModel.class); + STABLE_PROPERTIES.put(UNIT, String.class); + STABLE_PROPERTIES.put(METER_NAME, String.class); + STABLE_PROPERTIES.put(METER_VERSION, String.class); + STABLE_PROPERTIES.put(METER_SCHEMA_URL, String.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String instrumentName; + @Nullable private InstrumentTypeModel instrumentType; + @Nullable private String unit; + @Nullable private String meterName; + @Nullable private String meterVersion; + @Nullable private String meterSchemaUrl; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure instrument name selection criteria. + * + *

      If omitted or null, all instrument names match. + */ + @JsonProperty(INSTRUMENT_NAME) + @Nullable + public String getInstrumentName() { + if (instrumentName == null) { + return ExtensionPropertyUtil.getGraduated(INSTRUMENT_NAME, extensionProperties, String.class); + } + return instrumentName; + } + + @JsonProperty(INSTRUMENT_NAME) + public ViewSelectorModel setInstrumentName(String instrumentName) { + this.instrumentName = instrumentName; + return this; + } + + /** + * Configure instrument type selection criteria. + * + *

      Values include: + * + *

      * counter: Synchronous counter instruments. + * + *

      * gauge: Synchronous gauge instruments. + * + *

      * histogram: Synchronous histogram instruments. + * + *

      * observable_counter: Asynchronous counter instruments. + * + *

      * observable_gauge: Asynchronous gauge instruments. + * + *

      * observable_up_down_counter: Asynchronous up down counter instruments. + * + *

      * up_down_counter: Synchronous up down counter instruments. + * + *

      If omitted, all instrument types match. + */ + @JsonProperty(INSTRUMENT_TYPE) + @Nullable + public InstrumentTypeModel getInstrumentType() { + if (instrumentType == null) { + return ExtensionPropertyUtil.getGraduated( + INSTRUMENT_TYPE, extensionProperties, InstrumentTypeModel.class); + } + return instrumentType; + } + + @JsonProperty(INSTRUMENT_TYPE) + public ViewSelectorModel setInstrumentType(InstrumentTypeModel instrumentType) { + this.instrumentType = instrumentType; + return this; + } + + /** + * Configure the instrument unit selection criteria. + * + *

      If omitted or null, all instrument units match. + */ + @JsonProperty(UNIT) + @Nullable + public String getUnit() { + if (unit == null) { + return ExtensionPropertyUtil.getGraduated(UNIT, extensionProperties, String.class); + } + return unit; + } + + @JsonProperty(UNIT) + public ViewSelectorModel setUnit(String unit) { + this.unit = unit; + return this; + } + + /** + * Configure meter name selection criteria. + * + *

      If omitted or null, all meter names match. + */ + @JsonProperty(METER_NAME) + @Nullable + public String getMeterName() { + if (meterName == null) { + return ExtensionPropertyUtil.getGraduated(METER_NAME, extensionProperties, String.class); + } + return meterName; + } + + @JsonProperty(METER_NAME) + public ViewSelectorModel setMeterName(String meterName) { + this.meterName = meterName; + return this; + } + + /** + * Configure meter version selection criteria. + * + *

      If omitted or null, all meter versions match. + */ + @JsonProperty(METER_VERSION) + @Nullable + public String getMeterVersion() { + if (meterVersion == null) { + return ExtensionPropertyUtil.getGraduated(METER_VERSION, extensionProperties, String.class); + } + return meterVersion; + } + + @JsonProperty(METER_VERSION) + public ViewSelectorModel setMeterVersion(String meterVersion) { + this.meterVersion = meterVersion; + return this; + } + + /** + * Configure meter schema url selection criteria. + * + *

      If omitted or null, all meter schema URLs match. + */ + @JsonProperty(METER_SCHEMA_URL) + @Nullable + public String getMeterSchemaUrl() { + if (meterSchemaUrl == null) { + return ExtensionPropertyUtil.getGraduated( + METER_SCHEMA_URL, extensionProperties, String.class); + } + return meterSchemaUrl; + } + + @JsonProperty(METER_SCHEMA_URL) + public ViewSelectorModel setMeterSchemaUrl(String meterSchemaUrl) { + this.meterSchemaUrl = meterSchemaUrl; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ViewSelectorModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ViewSelectorModel{" + + "instrumentName=" + + instrumentName + + ", instrumentType=" + + instrumentType + + ", unit=" + + unit + + ", meterName=" + + meterName + + ", meterVersion=" + + meterVersion + + ", meterSchemaUrl=" + + meterSchemaUrl + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getInstrumentName() == null) ? 0 : this.getInstrumentName().hashCode(); + h *= 1000003; + h ^= (this.getInstrumentType() == null) ? 0 : this.getInstrumentType().hashCode(); + h *= 1000003; + h ^= (this.getUnit() == null) ? 0 : this.getUnit().hashCode(); + h *= 1000003; + h ^= (this.getMeterName() == null) ? 0 : this.getMeterName().hashCode(); + h *= 1000003; + h ^= (this.getMeterVersion() == null) ? 0 : this.getMeterVersion().hashCode(); + h *= 1000003; + h ^= (this.getMeterSchemaUrl() == null) ? 0 : this.getMeterSchemaUrl().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ViewSelectorModel) { + ViewSelectorModel that = (ViewSelectorModel) o; + return (this.getInstrumentName() == null + ? that.getInstrumentName() == null + : this.getInstrumentName().equals(that.getInstrumentName())) + && (this.getInstrumentType() == null + ? that.getInstrumentType() == null + : this.getInstrumentType().equals(that.getInstrumentType())) + && (this.getUnit() == null + ? that.getUnit() == null + : this.getUnit().equals(that.getUnit())) + && (this.getMeterName() == null + ? that.getMeterName() == null + : this.getMeterName().equals(that.getMeterName())) + && (this.getMeterVersion() == null + ? that.getMeterVersion() == null + : this.getMeterVersion().equals(that.getMeterVersion())) + && (this.getMeterSchemaUrl() == null + ? that.getMeterSchemaUrl() == null + : this.getMeterSchemaUrl().equals(that.getMeterSchemaUrl())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewStreamModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewStreamModel.java new file mode 100644 index 00000000000..c42fab5c3a9 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ViewStreamModel.java @@ -0,0 +1,245 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel.AGGREGATION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel.AGGREGATION_CARDINALITY_LIMIT; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel.ATTRIBUTE_KEYS; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel.DESCRIPTION; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel.NAME; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({NAME, DESCRIPTION, AGGREGATION, AGGREGATION_CARDINALITY_LIMIT, ATTRIBUTE_KEYS}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ViewStreamModel { + + static final String NAME = "name"; + static final String DESCRIPTION = "description"; + static final String AGGREGATION = "aggregation"; + static final String AGGREGATION_CARDINALITY_LIMIT = "aggregation_cardinality_limit"; + static final String ATTRIBUTE_KEYS = "attribute_keys"; + + private static final Map> STABLE_PROPERTIES; + + static { + STABLE_PROPERTIES = new HashMap<>(); + STABLE_PROPERTIES.put(NAME, String.class); + STABLE_PROPERTIES.put(DESCRIPTION, String.class); + STABLE_PROPERTIES.put(AGGREGATION, AggregationModel.class); + STABLE_PROPERTIES.put(AGGREGATION_CARDINALITY_LIMIT, Integer.class); + STABLE_PROPERTIES.put(ATTRIBUTE_KEYS, IncludeExcludeModel.class); + } + + private static final boolean ALLOWS_ADDITIONAL_PROPERTIES = false; + + @Nullable private String name; + @Nullable private String description; + @Nullable private AggregationModel aggregation; + @Nullable private Integer aggregationCardinalityLimit; + @Nullable private IncludeExcludeModel attributeKeys; + private Map extensionProperties = new LinkedHashMap(); + + /** + * Configure metric name of the resulting stream(s). + * + *

      If omitted or null, the instrument's original name is used. + */ + @JsonProperty(NAME) + @Nullable + public String getName() { + if (name == null) { + return ExtensionPropertyUtil.getGraduated(NAME, extensionProperties, String.class); + } + return name; + } + + @JsonProperty(NAME) + public ViewStreamModel setName(String name) { + this.name = name; + return this; + } + + /** + * Configure metric description of the resulting stream(s). + * + *

      If omitted or null, the instrument's origin description is used. + */ + @JsonProperty(DESCRIPTION) + @Nullable + public String getDescription() { + if (description == null) { + return ExtensionPropertyUtil.getGraduated(DESCRIPTION, extensionProperties, String.class); + } + return description; + } + + @JsonProperty(DESCRIPTION) + public ViewStreamModel setDescription(String description) { + this.description = description; + return this; + } + + /** + * Configure aggregation of the resulting stream(s). + * + *

      If omitted, default is used. + */ + @JsonProperty(AGGREGATION) + @Nullable + public AggregationModel getAggregation() { + if (aggregation == null) { + return ExtensionPropertyUtil.getGraduated( + AGGREGATION, extensionProperties, AggregationModel.class); + } + return aggregation; + } + + @JsonProperty(AGGREGATION) + public ViewStreamModel setAggregation(AggregationModel aggregation) { + this.aggregation = aggregation; + return this; + } + + /** + * Configure the aggregation cardinality limit. + * + *

      If omitted or null, the metric reader's default cardinality limit is used. + */ + @JsonProperty(AGGREGATION_CARDINALITY_LIMIT) + @Nullable + public Integer getAggregationCardinalityLimit() { + if (aggregationCardinalityLimit == null) { + return ExtensionPropertyUtil.getGraduated( + AGGREGATION_CARDINALITY_LIMIT, extensionProperties, Integer.class); + } + return aggregationCardinalityLimit; + } + + @JsonProperty(AGGREGATION_CARDINALITY_LIMIT) + public ViewStreamModel setAggregationCardinalityLimit(Integer aggregationCardinalityLimit) { + this.aggregationCardinalityLimit = aggregationCardinalityLimit; + return this; + } + + /** + * Configure attribute keys retained in the resulting stream(s). + * + *

      If omitted, all attribute keys are retained. + */ + @JsonProperty(ATTRIBUTE_KEYS) + @Nullable + public IncludeExcludeModel getAttributeKeys() { + if (attributeKeys == null) { + return ExtensionPropertyUtil.getGraduated( + ATTRIBUTE_KEYS, extensionProperties, IncludeExcludeModel.class); + } + return attributeKeys; + } + + @JsonProperty(ATTRIBUTE_KEYS) + public ViewStreamModel setAttributeKeys(IncludeExcludeModel attributeKeys) { + this.attributeKeys = attributeKeys; + return this; + } + + @JsonAnyGetter + public Map getExtensionProperties() { + return ExtensionPropertyUtil.filterSerializable(extensionProperties, STABLE_PROPERTIES); + } + + @JsonAnySetter + public ViewStreamModel setExtensionProperty(String name, @Nullable Object value) { + ExtensionPropertyUtil.handleAnySetter( + name, + value, + extensionProperties, + Collections.emptyMap(), + STABLE_PROPERTIES, + ALLOWS_ADDITIONAL_PROPERTIES); + return this; + } + + @Override + public String toString() { + return "ViewStreamModel{" + + "name=" + + name + + ", description=" + + description + + ", aggregation=" + + aggregation + + ", aggregationCardinalityLimit=" + + aggregationCardinalityLimit + + ", attributeKeys=" + + attributeKeys + + ", extensionProperties=" + + extensionProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.getName() == null) ? 0 : this.getName().hashCode(); + h *= 1000003; + h ^= (this.getDescription() == null) ? 0 : this.getDescription().hashCode(); + h *= 1000003; + h ^= (this.getAggregation() == null) ? 0 : this.getAggregation().hashCode(); + h *= 1000003; + h ^= + (this.getAggregationCardinalityLimit() == null) + ? 0 + : this.getAggregationCardinalityLimit().hashCode(); + h *= 1000003; + h ^= (this.getAttributeKeys() == null) ? 0 : this.getAttributeKeys().hashCode(); + h *= 1000003; + h ^= (this.getExtensionProperties() == null) ? 0 : this.getExtensionProperties().hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ViewStreamModel) { + ViewStreamModel that = (ViewStreamModel) o; + return (this.getName() == null + ? that.getName() == null + : this.getName().equals(that.getName())) + && (this.getDescription() == null + ? that.getDescription() == null + : this.getDescription().equals(that.getDescription())) + && (this.getAggregation() == null + ? that.getAggregation() == null + : this.getAggregation().equals(that.getAggregation())) + && (this.getAggregationCardinalityLimit() == null + ? that.getAggregationCardinalityLimit() == null + : this.getAggregationCardinalityLimit().equals(that.getAggregationCardinalityLimit())) + && (this.getAttributeKeys() == null + ? that.getAttributeKeys() == null + : this.getAttributeKeys().equals(that.getAttributeKeys())) + && (this.getExtensionProperties() == null + ? that.getExtensionProperties() == null + : this.getExtensionProperties().equals(that.getExtensionProperties())); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalCodeInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalCodeInstrumentationModel.java new file mode 100644 index 00000000000..a03fb268c00 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalCodeInstrumentationModel.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"semconv"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalCodeInstrumentationModel { + + @Nullable private ExperimentalSemconvConfigModel semconv; + + /** + * Configure code semantic convention version and migration behavior. + * + *

      This property takes precedence over the + * .instrumentation/development.general.stability_opt_in_list setting. + * + *

      See code semantic conventions: + * https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/ + * + *

      If omitted, uses the general stability_opt_in_list setting, or instrumentations continue + * emitting their default semantic convention version if not set. + */ + @JsonProperty("semconv") + @Nullable + public ExperimentalSemconvConfigModel getSemconv() { + return semconv; + } + + @JsonProperty("semconv") + public ExperimentalCodeInstrumentationModel setSemconv(ExperimentalSemconvConfigModel semconv) { + this.semconv = semconv; + return this; + } + + @Override + public String toString() { + return "ExperimentalCodeInstrumentationModel{" + "semconv=" + semconv + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.semconv == null) ? 0 : this.semconv.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalCodeInstrumentationModel) { + ExperimentalCodeInstrumentationModel that = (ExperimentalCodeInstrumentationModel) o; + return (this.semconv == null ? that.semconv == null : this.semconv.equals(that.semconv)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableAlwaysOffSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableAlwaysOffSamplerModel.java new file mode 100644 index 00000000000..7f17846dc69 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableAlwaysOffSamplerModel.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableAlwaysOffSamplerModel { + + @Override + public String toString() { + return "ExperimentalComposableAlwaysOffSamplerModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableAlwaysOffSamplerModel) { + ExperimentalComposableAlwaysOffSamplerModel that = + (ExperimentalComposableAlwaysOffSamplerModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableAlwaysOnSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableAlwaysOnSamplerModel.java new file mode 100644 index 00000000000..116cc0e819f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableAlwaysOnSamplerModel.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableAlwaysOnSamplerModel { + + @Override + public String toString() { + return "ExperimentalComposableAlwaysOnSamplerModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableAlwaysOnSamplerModel) { + ExperimentalComposableAlwaysOnSamplerModel that = + (ExperimentalComposableAlwaysOnSamplerModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableParentThresholdSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableParentThresholdSamplerModel.java new file mode 100644 index 00000000000..93890d0acf8 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableParentThresholdSamplerModel.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"root"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableParentThresholdSamplerModel { + + @Nullable private ExperimentalComposableSamplerModel root; + + /** + * Sampler to use when there is no parent. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("root") + @Nullable + public ExperimentalComposableSamplerModel getRoot() { + return root; + } + + @JsonProperty("root") + public ExperimentalComposableParentThresholdSamplerModel setRoot( + ExperimentalComposableSamplerModel root) { + this.root = root; + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableParentThresholdSamplerModel{" + "root=" + root + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.root == null) ? 0 : this.root.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableParentThresholdSamplerModel) { + ExperimentalComposableParentThresholdSamplerModel that = + (ExperimentalComposableParentThresholdSamplerModel) o; + return (this.root == null ? that.root == null : this.root.equals(that.root)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableProbabilitySamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableProbabilitySamplerModel.java new file mode 100644 index 00000000000..e4b0ae9807f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableProbabilitySamplerModel.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"ratio"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableProbabilitySamplerModel { + + @Nullable private Double ratio; + + /** + * Configure ratio. + * + *

      If omitted or null, 1.0 is used. + */ + @JsonProperty("ratio") + @Nullable + public Double getRatio() { + return ratio; + } + + @JsonProperty("ratio") + public ExperimentalComposableProbabilitySamplerModel setRatio(Double ratio) { + this.ratio = ratio; + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableProbabilitySamplerModel{" + "ratio=" + ratio + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.ratio == null) ? 0 : this.ratio.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableProbabilitySamplerModel) { + ExperimentalComposableProbabilitySamplerModel that = + (ExperimentalComposableProbabilitySamplerModel) o; + return (this.ratio == null ? that.ratio == null : this.ratio.equals(that.ratio)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerModel.java new file mode 100644 index 00000000000..6a65e390396 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerModel.java @@ -0,0 +1,72 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"rules"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableRuleBasedSamplerModel { + + @Nullable private List rules; + + /** + * The rules for the sampler, matched in order. + * + *

      Each rule can have multiple match conditions. All conditions must match for the rule to + * match. + * + *

      If no conditions are specified, the rule matches all spans that reach it. + * + *

      If no rules match, the span is not sampled. + * + *

      If omitted, no span is sampled. + */ + @JsonProperty("rules") + @Nullable + public List getRules() { + return rules; + } + + @JsonProperty("rules") + public ExperimentalComposableRuleBasedSamplerModel setRules( + List rules) { + this.rules = rules; + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableRuleBasedSamplerModel{" + "rules=" + rules + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.rules == null) ? 0 : this.rules.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableRuleBasedSamplerModel) { + ExperimentalComposableRuleBasedSamplerModel that = + (ExperimentalComposableRuleBasedSamplerModel) o; + return (this.rules == null ? that.rules == null : this.rules.equals(that.rules)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel.java new file mode 100644 index 00000000000..12bd51dc30b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel.java @@ -0,0 +1,130 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"key", "included", "excluded"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel { + + @Nullable private String key; + @Nullable private List included; + @Nullable private List excluded; + + /** + * The attribute key to match against. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("key") + @Nullable + public String getKey() { + return key; + } + + @JsonProperty("key") + public ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel setKey(String key) { + this.key = key; + return this; + } + + /** + * Configure list of value patterns to include. + * + *

      Matching is case-sensitive. Values are evaluated to match as follows: + * + *

      * If the value exactly matches. + * + *

      * If the value matches the wildcard pattern, where '?' matches any single character and '*' + * matches any number of characters including none. + * + *

      If omitted, all values are included. + */ + @JsonProperty("included") + @Nullable + public List getIncluded() { + return included; + } + + @JsonProperty("included") + public ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel setIncluded( + List included) { + this.included = included; + return this; + } + + /** + * Configure list of value patterns to exclude. Applies after .included (i.e. excluded has higher + * priority than included). + * + *

      Matching is case-sensitive. Values are evaluated to match as follows: + * + *

      * If the value exactly matches. + * + *

      * If the value matches the wildcard pattern, where '?' matches any single character and '*' + * matches any number of characters including none. + * + *

      If omitted, .included attributes are included. + */ + @JsonProperty("excluded") + @Nullable + public List getExcluded() { + return excluded; + } + + @JsonProperty("excluded") + public ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel setExcluded( + List excluded) { + this.excluded = excluded; + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel{" + + "key=" + + key + + ", included=" + + included + + ", excluded=" + + excluded + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.key == null) ? 0 : this.key.hashCode(); + h *= 1000003; + h ^= (this.included == null) ? 0 : this.included.hashCode(); + h *= 1000003; + h ^= (this.excluded == null) ? 0 : this.excluded.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel) { + ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel that = + (ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel) o; + return (this.key == null ? that.key == null : this.key.equals(that.key)) + && (this.included == null ? that.included == null : this.included.equals(that.included)) + && (this.excluded == null ? that.excluded == null : this.excluded.equals(that.excluded)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel.java new file mode 100644 index 00000000000..b3afff2ca01 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel.java @@ -0,0 +1,92 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"key", "values"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel { + + @Nullable private String key; + @Nullable private List values; + + /** + * The attribute key to match against. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("key") + @Nullable + public String getKey() { + return key; + } + + @JsonProperty("key") + public ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel setKey(String key) { + this.key = key; + return this; + } + + /** + * The attribute values to match against. If the attribute's value matches any of these, it + * matches. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("values") + @Nullable + public List getValues() { + return values; + } + + @JsonProperty("values") + public ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel setValues( + List values) { + this.values = values; + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel{" + + "key=" + + key + + ", values=" + + values + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.key == null) ? 0 : this.key.hashCode(); + h *= 1000003; + h ^= (this.values == null) ? 0 : this.values.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel) { + ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel that = + (ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel) o; + return (this.key == null ? that.key == null : this.key.equals(that.key)) + && (this.values == null ? that.values == null : this.values.equals(that.values)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleModel.java new file mode 100644 index 00000000000..23d02f9bfe4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableRuleBasedSamplerRuleModel.java @@ -0,0 +1,206 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanKindModel; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"attribute_values", "attribute_patterns", "span_kinds", "parent", "sampler"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableRuleBasedSamplerRuleModel { + + @Nullable private ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel attributeValues; + + @Nullable + private ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel attributePatterns; + + @Nullable private List spanKinds; + @Nullable private List parent; + @Nullable private ExperimentalComposableSamplerModel sampler; + + /** + * Values to match against a single attribute. Non-string attributes are matched using their + * string representation: + * + *

      for example, a value of "404" would match the http.response.status_code 404. For array + * attributes, if any + * + *

      item matches, it is considered a match. + * + *

      If omitted, ignore. + */ + @JsonProperty("attribute_values") + @Nullable + public ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel getAttributeValues() { + return attributeValues; + } + + @JsonProperty("attribute_values") + public ExperimentalComposableRuleBasedSamplerRuleModel setAttributeValues( + ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel attributeValues) { + this.attributeValues = attributeValues; + return this; + } + + /** + * Patterns to match against a single attribute. Non-string attributes are matched using their + * string representation: + * + *

      for example, a pattern of "4*" would match any http.response.status_code in 400-499. For + * array attributes, if any + * + *

      item matches, it is considered a match. + * + *

      If omitted, ignore. + */ + @JsonProperty("attribute_patterns") + @Nullable + public ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel getAttributePatterns() { + return attributePatterns; + } + + @JsonProperty("attribute_patterns") + public ExperimentalComposableRuleBasedSamplerRuleModel setAttributePatterns( + ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel attributePatterns) { + this.attributePatterns = attributePatterns; + return this; + } + + /** + * The span kinds to match. If the span's kind matches any of these, it matches. + * + *

      Values include: + * + *

      * client: client, a client span. + * + *

      * consumer: consumer, a consumer span. + * + *

      * internal: internal, an internal span. + * + *

      * producer: producer, a producer span. + * + *

      * server: server, a server span. + * + *

      If omitted, ignore. + */ + @JsonProperty("span_kinds") + @Nullable + public List getSpanKinds() { + return spanKinds; + } + + @JsonProperty("span_kinds") + public ExperimentalComposableRuleBasedSamplerRuleModel setSpanKinds( + List spanKinds) { + this.spanKinds = spanKinds; + return this; + } + + /** + * The parent span types to match. + * + *

      Values include: + * + *

      * local: local, a local parent. + * + *

      * none: none, no parent, i.e., the trace root. + * + *

      * remote: remote, a remote parent. + * + *

      If omitted, ignore. + */ + @JsonProperty("parent") + @Nullable + public List getParent() { + return parent; + } + + @JsonProperty("parent") + public ExperimentalComposableRuleBasedSamplerRuleModel setParent( + List parent) { + this.parent = parent; + return this; + } + + /** + * The sampler to use for matching spans. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("sampler") + @Nullable + public ExperimentalComposableSamplerModel getSampler() { + return sampler; + } + + @JsonProperty("sampler") + public ExperimentalComposableRuleBasedSamplerRuleModel setSampler( + ExperimentalComposableSamplerModel sampler) { + this.sampler = sampler; + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableRuleBasedSamplerRuleModel{" + + "attributeValues=" + + attributeValues + + ", attributePatterns=" + + attributePatterns + + ", spanKinds=" + + spanKinds + + ", parent=" + + parent + + ", sampler=" + + sampler + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.attributeValues == null) ? 0 : this.attributeValues.hashCode(); + h *= 1000003; + h ^= (this.attributePatterns == null) ? 0 : this.attributePatterns.hashCode(); + h *= 1000003; + h ^= (this.spanKinds == null) ? 0 : this.spanKinds.hashCode(); + h *= 1000003; + h ^= (this.parent == null) ? 0 : this.parent.hashCode(); + h *= 1000003; + h ^= (this.sampler == null) ? 0 : this.sampler.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableRuleBasedSamplerRuleModel) { + ExperimentalComposableRuleBasedSamplerRuleModel that = + (ExperimentalComposableRuleBasedSamplerRuleModel) o; + return (this.attributeValues == null + ? that.attributeValues == null + : this.attributeValues.equals(that.attributeValues)) + && (this.attributePatterns == null + ? that.attributePatterns == null + : this.attributePatterns.equals(that.attributePatterns)) + && (this.spanKinds == null + ? that.spanKinds == null + : this.spanKinds.equals(that.spanKinds)) + && (this.parent == null ? that.parent == null : this.parent.equals(that.parent)) + && (this.sampler == null ? that.sampler == null : this.sampler.equals(that.sampler)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableSamplerModel.java new file mode 100644 index 00000000000..e6e70d8c86c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableSamplerModel.java @@ -0,0 +1,195 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"always_off", "always_on", "parent_threshold", "probability", "rule_based"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableSamplerModel { + + @Nullable private ExperimentalComposableAlwaysOffSamplerModel alwaysOff; + @Nullable private ExperimentalComposableAlwaysOnSamplerModel alwaysOn; + @Nullable private ExperimentalComposableParentThresholdSamplerModel parentThreshold; + @Nullable private ExperimentalComposableProbabilitySamplerModel probability; + @Nullable private ExperimentalComposableRuleBasedSamplerModel ruleBased; + private Map additionalProperties = + new LinkedHashMap(); + + /** + * Configure sampler to be always_off. + * + *

      If omitted, ignore. + */ + @JsonProperty("always_off") + @Nullable + public ExperimentalComposableAlwaysOffSamplerModel getAlwaysOff() { + return alwaysOff; + } + + @JsonProperty("always_off") + public ExperimentalComposableSamplerModel setAlwaysOff( + ExperimentalComposableAlwaysOffSamplerModel alwaysOff) { + this.alwaysOff = alwaysOff; + return this; + } + + /** + * Configure sampler to be always_on. + * + *

      If omitted, ignore. + */ + @JsonProperty("always_on") + @Nullable + public ExperimentalComposableAlwaysOnSamplerModel getAlwaysOn() { + return alwaysOn; + } + + @JsonProperty("always_on") + public ExperimentalComposableSamplerModel setAlwaysOn( + ExperimentalComposableAlwaysOnSamplerModel alwaysOn) { + this.alwaysOn = alwaysOn; + return this; + } + + /** + * Configure sampler to be parent_threshold. + * + *

      If omitted, ignore. + */ + @JsonProperty("parent_threshold") + @Nullable + public ExperimentalComposableParentThresholdSamplerModel getParentThreshold() { + return parentThreshold; + } + + @JsonProperty("parent_threshold") + public ExperimentalComposableSamplerModel setParentThreshold( + ExperimentalComposableParentThresholdSamplerModel parentThreshold) { + this.parentThreshold = parentThreshold; + return this; + } + + /** + * Configure sampler to be probability. + * + *

      If omitted, ignore. + */ + @JsonProperty("probability") + @Nullable + public ExperimentalComposableProbabilitySamplerModel getProbability() { + return probability; + } + + @JsonProperty("probability") + public ExperimentalComposableSamplerModel setProbability( + ExperimentalComposableProbabilitySamplerModel probability) { + this.probability = probability; + return this; + } + + /** + * Configure sampler to be rule_based. + * + *

      If omitted, ignore. + */ + @JsonProperty("rule_based") + @Nullable + public ExperimentalComposableRuleBasedSamplerModel getRuleBased() { + return ruleBased; + } + + @JsonProperty("rule_based") + public ExperimentalComposableSamplerModel setRuleBased( + ExperimentalComposableRuleBasedSamplerModel ruleBased) { + this.ruleBased = ruleBased; + return this; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public ExperimentalComposableSamplerModel setAdditionalProperty( + String name, ExperimentalComposableSamplerPropertyModel value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableSamplerModel{" + + "alwaysOff=" + + alwaysOff + + ", alwaysOn=" + + alwaysOn + + ", parentThreshold=" + + parentThreshold + + ", probability=" + + probability + + ", ruleBased=" + + ruleBased + + ", additionalProperties=" + + additionalProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.alwaysOff == null) ? 0 : this.alwaysOff.hashCode(); + h *= 1000003; + h ^= (this.alwaysOn == null) ? 0 : this.alwaysOn.hashCode(); + h *= 1000003; + h ^= (this.parentThreshold == null) ? 0 : this.parentThreshold.hashCode(); + h *= 1000003; + h ^= (this.probability == null) ? 0 : this.probability.hashCode(); + h *= 1000003; + h ^= (this.ruleBased == null) ? 0 : this.ruleBased.hashCode(); + h *= 1000003; + h ^= (this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableSamplerModel) { + ExperimentalComposableSamplerModel that = (ExperimentalComposableSamplerModel) o; + return (this.alwaysOff == null + ? that.alwaysOff == null + : this.alwaysOff.equals(that.alwaysOff)) + && (this.alwaysOn == null ? that.alwaysOn == null : this.alwaysOn.equals(that.alwaysOn)) + && (this.parentThreshold == null + ? that.parentThreshold == null + : this.parentThreshold.equals(that.parentThreshold)) + && (this.probability == null + ? that.probability == null + : this.probability.equals(that.probability)) + && (this.ruleBased == null + ? that.ruleBased == null + : this.ruleBased.equals(that.ruleBased)) + && (this.additionalProperties == null + ? that.additionalProperties == null + : this.additionalProperties.equals(that.additionalProperties)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableSamplerPropertyModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableSamplerPropertyModel.java new file mode 100644 index 00000000000..c80e3297ec0 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalComposableSamplerPropertyModel.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalComposableSamplerPropertyModel { + + private Map additionalProperties = new LinkedHashMap(); + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public ExperimentalComposableSamplerPropertyModel setAdditionalProperty( + String name, Object value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public String toString() { + return "ExperimentalComposableSamplerPropertyModel{" + + "additionalProperties=" + + additionalProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalComposableSamplerPropertyModel) { + ExperimentalComposableSamplerPropertyModel that = + (ExperimentalComposableSamplerPropertyModel) o; + return (this.additionalProperties == null + ? that.additionalProperties == null + : this.additionalProperties.equals(that.additionalProperties)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalContainerResourceDetectorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalContainerResourceDetectorModel.java new file mode 100644 index 00000000000..45bfa381afc --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalContainerResourceDetectorModel.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalContainerResourceDetectorModel { + + @Override + public String toString() { + return "ExperimentalContainerResourceDetectorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalContainerResourceDetectorModel) { + ExperimentalContainerResourceDetectorModel that = + (ExperimentalContainerResourceDetectorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalDbInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalDbInstrumentationModel.java new file mode 100644 index 00000000000..09fd22f139c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalDbInstrumentationModel.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"semconv"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalDbInstrumentationModel { + + @Nullable private ExperimentalSemconvConfigModel semconv; + + /** + * Configure database semantic convention version and migration behavior. + * + *

      This property takes precedence over the + * .instrumentation/development.general.stability_opt_in_list setting. + * + *

      See database migration: https://opentelemetry.io/docs/specs/semconv/database/ + * + *

      If omitted, uses the general stability_opt_in_list setting, or instrumentations continue + * emitting their default semantic convention version if not set. + */ + @JsonProperty("semconv") + @Nullable + public ExperimentalSemconvConfigModel getSemconv() { + return semconv; + } + + @JsonProperty("semconv") + public ExperimentalDbInstrumentationModel setSemconv(ExperimentalSemconvConfigModel semconv) { + this.semconv = semconv; + return this; + } + + @Override + public String toString() { + return "ExperimentalDbInstrumentationModel{" + "semconv=" + semconv + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.semconv == null) ? 0 : this.semconv.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalDbInstrumentationModel) { + ExperimentalDbInstrumentationModel that = (ExperimentalDbInstrumentationModel) o; + return (this.semconv == null ? that.semconv == null : this.semconv.equals(that.semconv)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalEventToSpanEventBridgeLogRecordProcessorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalEventToSpanEventBridgeLogRecordProcessorModel.java new file mode 100644 index 00000000000..23a9ff340c1 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalEventToSpanEventBridgeLogRecordProcessorModel.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalEventToSpanEventBridgeLogRecordProcessorModel { + + @Override + public String toString() { + return "ExperimentalEventToSpanEventBridgeLogRecordProcessorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalEventToSpanEventBridgeLogRecordProcessorModel) { + ExperimentalEventToSpanEventBridgeLogRecordProcessorModel that = + (ExperimentalEventToSpanEventBridgeLogRecordProcessorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalGenAiInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalGenAiInstrumentationModel.java new file mode 100644 index 00000000000..d5603953e82 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalGenAiInstrumentationModel.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"semconv"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalGenAiInstrumentationModel { + + @Nullable private ExperimentalSemconvConfigModel semconv; + + /** + * Configure GenAI semantic convention version and migration behavior. + * + *

      This property takes precedence over the + * .instrumentation/development.general.stability_opt_in_list setting. + * + *

      See GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/ + * + *

      If omitted, uses the general stability_opt_in_list setting, or instrumentations continue + * emitting their default semantic convention version if not set. + */ + @JsonProperty("semconv") + @Nullable + public ExperimentalSemconvConfigModel getSemconv() { + return semconv; + } + + @JsonProperty("semconv") + public ExperimentalGenAiInstrumentationModel setSemconv(ExperimentalSemconvConfigModel semconv) { + this.semconv = semconv; + return this; + } + + @Override + public String toString() { + return "ExperimentalGenAiInstrumentationModel{" + "semconv=" + semconv + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.semconv == null) ? 0 : this.semconv.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalGenAiInstrumentationModel) { + ExperimentalGenAiInstrumentationModel that = (ExperimentalGenAiInstrumentationModel) o; + return (this.semconv == null ? that.semconv == null : this.semconv.equals(that.semconv)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalGeneralInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalGeneralInstrumentationModel.java new file mode 100644 index 00000000000..5d16b9e3eca --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalGeneralInstrumentationModel.java @@ -0,0 +1,307 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "http", + "code", + "db", + "gen_ai", + "messaging", + "rpc", + "sanitization", + "stability_opt_in_list" +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalGeneralInstrumentationModel { + + @Nullable private ExperimentalHttpInstrumentationModel http; + @Nullable private ExperimentalCodeInstrumentationModel code; + @Nullable private ExperimentalDbInstrumentationModel db; + @Nullable private ExperimentalGenAiInstrumentationModel genAi; + @Nullable private ExperimentalMessagingInstrumentationModel messaging; + @Nullable private ExperimentalRpcInstrumentationModel rpc; + @Nullable private ExperimentalSanitizationModel sanitization; + @Nullable private String stabilityOptInList; + + /** + * Configure instrumentations following the http semantic conventions. + * + *

      See http semantic conventions: https://opentelemetry.io/docs/specs/semconv/http/ + * + *

      If omitted, defaults as described in ExperimentalHttpInstrumentation are used. + */ + @JsonProperty("http") + @Nullable + public ExperimentalHttpInstrumentationModel getHttp() { + return http; + } + + @JsonProperty("http") + public ExperimentalGeneralInstrumentationModel setHttp( + ExperimentalHttpInstrumentationModel http) { + this.http = http; + return this; + } + + /** + * Configure instrumentations following the code semantic conventions. + * + *

      See code semantic conventions: + * https://opentelemetry.io/docs/specs/semconv/registry/attributes/code/ + * + *

      If omitted, defaults as described in ExperimentalCodeInstrumentation are used. + */ + @JsonProperty("code") + @Nullable + public ExperimentalCodeInstrumentationModel getCode() { + return code; + } + + @JsonProperty("code") + public ExperimentalGeneralInstrumentationModel setCode( + ExperimentalCodeInstrumentationModel code) { + this.code = code; + return this; + } + + /** + * Configure instrumentations following the database semantic conventions. + * + *

      See database semantic conventions: https://opentelemetry.io/docs/specs/semconv/database/ + * + *

      If omitted, defaults as described in ExperimentalDbInstrumentation are used. + */ + @JsonProperty("db") + @Nullable + public ExperimentalDbInstrumentationModel getDb() { + return db; + } + + @JsonProperty("db") + public ExperimentalGeneralInstrumentationModel setDb(ExperimentalDbInstrumentationModel db) { + this.db = db; + return this; + } + + /** + * Configure instrumentations following the GenAI semantic conventions. + * + *

      See GenAI semantic conventions: https://opentelemetry.io/docs/specs/semconv/gen-ai/ + * + *

      If omitted, defaults as described in ExperimentalGenAiInstrumentation are used. + */ + @JsonProperty("gen_ai") + @Nullable + public ExperimentalGenAiInstrumentationModel getGenAi() { + return genAi; + } + + @JsonProperty("gen_ai") + public ExperimentalGeneralInstrumentationModel setGenAi( + ExperimentalGenAiInstrumentationModel genAi) { + this.genAi = genAi; + return this; + } + + /** + * Configure instrumentations following the messaging semantic conventions. + * + *

      See messaging semantic conventions: https://opentelemetry.io/docs/specs/semconv/messaging/ + * + *

      If omitted, defaults as described in ExperimentalMessagingInstrumentation are used. + */ + @JsonProperty("messaging") + @Nullable + public ExperimentalMessagingInstrumentationModel getMessaging() { + return messaging; + } + + @JsonProperty("messaging") + public ExperimentalGeneralInstrumentationModel setMessaging( + ExperimentalMessagingInstrumentationModel messaging) { + this.messaging = messaging; + return this; + } + + /** + * Configure instrumentations following the RPC semantic conventions. + * + *

      See RPC semantic conventions: https://opentelemetry.io/docs/specs/semconv/rpc/ + * + *

      If omitted, defaults as described in ExperimentalRpcInstrumentation are used. + */ + @JsonProperty("rpc") + @Nullable + public ExperimentalRpcInstrumentationModel getRpc() { + return rpc; + } + + @JsonProperty("rpc") + public ExperimentalGeneralInstrumentationModel setRpc(ExperimentalRpcInstrumentationModel rpc) { + this.rpc = rpc; + return this; + } + + /** + * Configure general sanitization options. + * + *

      If omitted, defaults as described in ExperimentalSanitization are used. + */ + @JsonProperty("sanitization") + @Nullable + public ExperimentalSanitizationModel getSanitization() { + return sanitization; + } + + @JsonProperty("sanitization") + public ExperimentalGeneralInstrumentationModel setSanitization( + ExperimentalSanitizationModel sanitization) { + this.sanitization = sanitization; + return this; + } + + /** + * Configure semantic convention stability opt-in as a comma-separated list. + * + *

      This property follows the format and semantics of the OTEL_SEMCONV_STABILITY_OPT_IN + * environment variable. + * + *

      Controls the emission of stable vs. experimental semantic conventions for instrumentation. + * + *

      This setting is only intended for migrating from experimental to stable semantic + * conventions. + * + *

      Known values include: + * + *

      - http: Emit stable HTTP and networking conventions only + * + *

      - http/dup: Emit both old and stable HTTP and networking conventions (for phased migration) + * + *

      - database: Emit stable database conventions only + * + *

      - database/dup: Emit both old and stable database conventions (for phased migration) + * + *

      - rpc: Emit stable RPC conventions only + * + *

      - rpc/dup: Emit both experimental and stable RPC conventions (for phased migration) + * + *

      - messaging: Emit stable messaging conventions only + * + *

      - messaging/dup: Emit both old and stable messaging conventions (for phased migration) + * + *

      - code: Emit stable code conventions only + * + *

      - code/dup: Emit both old and stable code conventions (for phased migration) + * + *

      Multiple values can be specified as a comma-separated list (e.g., "http,database/dup"). + * + *

      Additional signal types may be supported in future versions. + * + *

      Domain-specific semconv properties (e.g., .instrumentation/development.general.db.semconv) + * take precedence over this general setting. + * + *

      See: + * + *

      - HTTP migration: https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/ + * + *

      - Database migration: https://opentelemetry.io/docs/specs/semconv/database/ + * + *

      - RPC: https://opentelemetry.io/docs/specs/semconv/rpc/ + * + *

      - Messaging: https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/ + * + *

      If omitted or null, no opt-in is configured and instrumentations continue emitting their + * default semantic convention version. + */ + @JsonProperty("stability_opt_in_list") + @Nullable + public String getStabilityOptInList() { + return stabilityOptInList; + } + + @JsonProperty("stability_opt_in_list") + public ExperimentalGeneralInstrumentationModel setStabilityOptInList(String stabilityOptInList) { + this.stabilityOptInList = stabilityOptInList; + return this; + } + + @Override + public String toString() { + return "ExperimentalGeneralInstrumentationModel{" + + "http=" + + http + + ", code=" + + code + + ", db=" + + db + + ", genAi=" + + genAi + + ", messaging=" + + messaging + + ", rpc=" + + rpc + + ", sanitization=" + + sanitization + + ", stabilityOptInList=" + + stabilityOptInList + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.http == null) ? 0 : this.http.hashCode(); + h *= 1000003; + h ^= (this.code == null) ? 0 : this.code.hashCode(); + h *= 1000003; + h ^= (this.db == null) ? 0 : this.db.hashCode(); + h *= 1000003; + h ^= (this.genAi == null) ? 0 : this.genAi.hashCode(); + h *= 1000003; + h ^= (this.messaging == null) ? 0 : this.messaging.hashCode(); + h *= 1000003; + h ^= (this.rpc == null) ? 0 : this.rpc.hashCode(); + h *= 1000003; + h ^= (this.sanitization == null) ? 0 : this.sanitization.hashCode(); + h *= 1000003; + h ^= (this.stabilityOptInList == null) ? 0 : this.stabilityOptInList.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalGeneralInstrumentationModel) { + ExperimentalGeneralInstrumentationModel that = (ExperimentalGeneralInstrumentationModel) o; + return (this.http == null ? that.http == null : this.http.equals(that.http)) + && (this.code == null ? that.code == null : this.code.equals(that.code)) + && (this.db == null ? that.db == null : this.db.equals(that.db)) + && (this.genAi == null ? that.genAi == null : this.genAi.equals(that.genAi)) + && (this.messaging == null + ? that.messaging == null + : this.messaging.equals(that.messaging)) + && (this.rpc == null ? that.rpc == null : this.rpc.equals(that.rpc)) + && (this.sanitization == null + ? that.sanitization == null + : this.sanitization.equals(that.sanitization)) + && (this.stabilityOptInList == null + ? that.stabilityOptInList == null + : this.stabilityOptInList.equals(that.stabilityOptInList)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHostResourceDetectorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHostResourceDetectorModel.java new file mode 100644 index 00000000000..f0f096458ff --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHostResourceDetectorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalHostResourceDetectorModel { + + @Override + public String toString() { + return "ExperimentalHostResourceDetectorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalHostResourceDetectorModel) { + ExperimentalHostResourceDetectorModel that = (ExperimentalHostResourceDetectorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpClientInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpClientInstrumentationModel.java new file mode 100644 index 00000000000..dfc48a76d35 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpClientInstrumentationModel.java @@ -0,0 +1,127 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"request_captured_headers", "response_captured_headers", "known_methods"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalHttpClientInstrumentationModel { + + @Nullable private List requestCapturedHeaders; + @Nullable private List responseCapturedHeaders; + @Nullable private List knownMethods; + + /** + * Configure headers to capture for outbound http requests. + * + *

      If omitted, no outbound request headers are captured. + */ + @JsonProperty("request_captured_headers") + @Nullable + public List getRequestCapturedHeaders() { + return requestCapturedHeaders; + } + + @JsonProperty("request_captured_headers") + public ExperimentalHttpClientInstrumentationModel setRequestCapturedHeaders( + List requestCapturedHeaders) { + this.requestCapturedHeaders = requestCapturedHeaders; + return this; + } + + /** + * Configure headers to capture for inbound http responses. + * + *

      If omitted, no inbound response headers are captured. + */ + @JsonProperty("response_captured_headers") + @Nullable + public List getResponseCapturedHeaders() { + return responseCapturedHeaders; + } + + @JsonProperty("response_captured_headers") + public ExperimentalHttpClientInstrumentationModel setResponseCapturedHeaders( + List responseCapturedHeaders) { + this.responseCapturedHeaders = responseCapturedHeaders; + return this; + } + + /** + * Override the default list of known HTTP methods. + * + *

      Known methods are case-sensitive. + * + *

      This is a full override of the default known methods, not a list of known methods in + * addition to the defaults. + * + *

      If omitted, HTTP methods GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH are + * known. + */ + @JsonProperty("known_methods") + @Nullable + public List getKnownMethods() { + return knownMethods; + } + + @JsonProperty("known_methods") + public ExperimentalHttpClientInstrumentationModel setKnownMethods(List knownMethods) { + this.knownMethods = knownMethods; + return this; + } + + @Override + public String toString() { + return "ExperimentalHttpClientInstrumentationModel{" + + "requestCapturedHeaders=" + + requestCapturedHeaders + + ", responseCapturedHeaders=" + + responseCapturedHeaders + + ", knownMethods=" + + knownMethods + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.requestCapturedHeaders == null) ? 0 : this.requestCapturedHeaders.hashCode(); + h *= 1000003; + h ^= (this.responseCapturedHeaders == null) ? 0 : this.responseCapturedHeaders.hashCode(); + h *= 1000003; + h ^= (this.knownMethods == null) ? 0 : this.knownMethods.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalHttpClientInstrumentationModel) { + ExperimentalHttpClientInstrumentationModel that = + (ExperimentalHttpClientInstrumentationModel) o; + return (this.requestCapturedHeaders == null + ? that.requestCapturedHeaders == null + : this.requestCapturedHeaders.equals(that.requestCapturedHeaders)) + && (this.responseCapturedHeaders == null + ? that.responseCapturedHeaders == null + : this.responseCapturedHeaders.equals(that.responseCapturedHeaders)) + && (this.knownMethods == null + ? that.knownMethods == null + : this.knownMethods.equals(that.knownMethods)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpInstrumentationModel.java new file mode 100644 index 00000000000..dea07c85ea5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpInstrumentationModel.java @@ -0,0 +1,120 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"semconv", "client", "server"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalHttpInstrumentationModel { + + @Nullable private ExperimentalSemconvConfigModel semconv; + @Nullable private ExperimentalHttpClientInstrumentationModel client; + @Nullable private ExperimentalHttpServerInstrumentationModel server; + + /** + * Configure HTTP semantic convention version and migration behavior. + * + *

      This property takes precedence over the + * .instrumentation/development.general.stability_opt_in_list setting. + * + *

      See HTTP migration: + * https://opentelemetry.io/docs/specs/semconv/non-normative/http-migration/ + * + *

      If omitted, uses the general stability_opt_in_list setting, or instrumentations continue + * emitting their default semantic convention version if not set. + */ + @JsonProperty("semconv") + @Nullable + public ExperimentalSemconvConfigModel getSemconv() { + return semconv; + } + + @JsonProperty("semconv") + public ExperimentalHttpInstrumentationModel setSemconv(ExperimentalSemconvConfigModel semconv) { + this.semconv = semconv; + return this; + } + + /** + * Configure instrumentations following the http client semantic conventions. + * + *

      If omitted, defaults as described in ExperimentalHttpClientInstrumentation are used. + */ + @JsonProperty("client") + @Nullable + public ExperimentalHttpClientInstrumentationModel getClient() { + return client; + } + + @JsonProperty("client") + public ExperimentalHttpInstrumentationModel setClient( + ExperimentalHttpClientInstrumentationModel client) { + this.client = client; + return this; + } + + /** + * Configure instrumentations following the http server semantic conventions. + * + *

      If omitted, defaults as described in ExperimentalHttpServerInstrumentation are used. + */ + @JsonProperty("server") + @Nullable + public ExperimentalHttpServerInstrumentationModel getServer() { + return server; + } + + @JsonProperty("server") + public ExperimentalHttpInstrumentationModel setServer( + ExperimentalHttpServerInstrumentationModel server) { + this.server = server; + return this; + } + + @Override + public String toString() { + return "ExperimentalHttpInstrumentationModel{" + + "semconv=" + + semconv + + ", client=" + + client + + ", server=" + + server + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.semconv == null) ? 0 : this.semconv.hashCode(); + h *= 1000003; + h ^= (this.client == null) ? 0 : this.client.hashCode(); + h *= 1000003; + h ^= (this.server == null) ? 0 : this.server.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalHttpInstrumentationModel) { + ExperimentalHttpInstrumentationModel that = (ExperimentalHttpInstrumentationModel) o; + return (this.semconv == null ? that.semconv == null : this.semconv.equals(that.semconv)) + && (this.client == null ? that.client == null : this.client.equals(that.client)) + && (this.server == null ? that.server == null : this.server.equals(that.server)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpServerInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpServerInstrumentationModel.java new file mode 100644 index 00000000000..36164fcc600 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalHttpServerInstrumentationModel.java @@ -0,0 +1,127 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"request_captured_headers", "response_captured_headers", "known_methods"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalHttpServerInstrumentationModel { + + @Nullable private List requestCapturedHeaders; + @Nullable private List responseCapturedHeaders; + @Nullable private List knownMethods; + + /** + * Configure headers to capture for inbound http requests. + * + *

      If omitted, no request headers are captured. + */ + @JsonProperty("request_captured_headers") + @Nullable + public List getRequestCapturedHeaders() { + return requestCapturedHeaders; + } + + @JsonProperty("request_captured_headers") + public ExperimentalHttpServerInstrumentationModel setRequestCapturedHeaders( + List requestCapturedHeaders) { + this.requestCapturedHeaders = requestCapturedHeaders; + return this; + } + + /** + * Configure headers to capture for outbound http responses. + * + *

      If omitted, no response headers are captures. + */ + @JsonProperty("response_captured_headers") + @Nullable + public List getResponseCapturedHeaders() { + return responseCapturedHeaders; + } + + @JsonProperty("response_captured_headers") + public ExperimentalHttpServerInstrumentationModel setResponseCapturedHeaders( + List responseCapturedHeaders) { + this.responseCapturedHeaders = responseCapturedHeaders; + return this; + } + + /** + * Override the default list of known HTTP methods. + * + *

      Known methods are case-sensitive. + * + *

      This is a full override of the default known methods, not a list of known methods in + * addition to the defaults. + * + *

      If omitted, HTTP methods GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH are + * known. + */ + @JsonProperty("known_methods") + @Nullable + public List getKnownMethods() { + return knownMethods; + } + + @JsonProperty("known_methods") + public ExperimentalHttpServerInstrumentationModel setKnownMethods(List knownMethods) { + this.knownMethods = knownMethods; + return this; + } + + @Override + public String toString() { + return "ExperimentalHttpServerInstrumentationModel{" + + "requestCapturedHeaders=" + + requestCapturedHeaders + + ", responseCapturedHeaders=" + + responseCapturedHeaders + + ", knownMethods=" + + knownMethods + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.requestCapturedHeaders == null) ? 0 : this.requestCapturedHeaders.hashCode(); + h *= 1000003; + h ^= (this.responseCapturedHeaders == null) ? 0 : this.responseCapturedHeaders.hashCode(); + h *= 1000003; + h ^= (this.knownMethods == null) ? 0 : this.knownMethods.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalHttpServerInstrumentationModel) { + ExperimentalHttpServerInstrumentationModel that = + (ExperimentalHttpServerInstrumentationModel) o; + return (this.requestCapturedHeaders == null + ? that.requestCapturedHeaders == null + : this.requestCapturedHeaders.equals(that.requestCapturedHeaders)) + && (this.responseCapturedHeaders == null + ? that.responseCapturedHeaders == null + : this.responseCapturedHeaders.equals(that.responseCapturedHeaders)) + && (this.knownMethods == null + ? that.knownMethods == null + : this.knownMethods.equals(that.knownMethods)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalInstrumentationModel.java new file mode 100644 index 00000000000..1a99ea408e9 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalInstrumentationModel.java @@ -0,0 +1,365 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "general", "cpp", "dotnet", "erlang", "go", "java", "js", "php", "python", "ruby", "rust", "swift" +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalInstrumentationModel { + + @Nullable private ExperimentalGeneralInstrumentationModel general; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel cpp; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel dotnet; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel erlang; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel go; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel java; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel js; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel php; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel python; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel ruby; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel rust; + @Nullable private ExperimentalLanguageSpecificInstrumentationModel swift; + + /** + * Configure general SemConv options that may apply to multiple languages and instrumentations. + * + *

      Instrumentation may merge general config options with the language specific configuration at + * .instrumentation.. + * + *

      If omitted, default values as described in ExperimentalGeneralInstrumentation are used. + */ + @JsonProperty("general") + @Nullable + public ExperimentalGeneralInstrumentationModel getGeneral() { + return general; + } + + @JsonProperty("general") + public ExperimentalInstrumentationModel setGeneral( + ExperimentalGeneralInstrumentationModel general) { + this.general = general; + return this; + } + + /** + * Configure C++ language-specific instrumentation libraries. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("cpp") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getCpp() { + return cpp; + } + + @JsonProperty("cpp") + public ExperimentalInstrumentationModel setCpp( + ExperimentalLanguageSpecificInstrumentationModel cpp) { + this.cpp = cpp; + return this; + } + + /** + * Configure .NET language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("dotnet") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getDotnet() { + return dotnet; + } + + @JsonProperty("dotnet") + public ExperimentalInstrumentationModel setDotnet( + ExperimentalLanguageSpecificInstrumentationModel dotnet) { + this.dotnet = dotnet; + return this; + } + + /** + * Configure Erlang language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("erlang") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getErlang() { + return erlang; + } + + @JsonProperty("erlang") + public ExperimentalInstrumentationModel setErlang( + ExperimentalLanguageSpecificInstrumentationModel erlang) { + this.erlang = erlang; + return this; + } + + /** + * Configure Go language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("go") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getGo() { + return go; + } + + @JsonProperty("go") + public ExperimentalInstrumentationModel setGo( + ExperimentalLanguageSpecificInstrumentationModel go) { + this.go = go; + return this; + } + + /** + * Configure Java language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("java") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getJava() { + return java; + } + + @JsonProperty("java") + public ExperimentalInstrumentationModel setJava( + ExperimentalLanguageSpecificInstrumentationModel java) { + this.java = java; + return this; + } + + /** + * Configure JavaScript language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("js") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getJs() { + return js; + } + + @JsonProperty("js") + public ExperimentalInstrumentationModel setJs( + ExperimentalLanguageSpecificInstrumentationModel js) { + this.js = js; + return this; + } + + /** + * Configure PHP language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("php") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getPhp() { + return php; + } + + @JsonProperty("php") + public ExperimentalInstrumentationModel setPhp( + ExperimentalLanguageSpecificInstrumentationModel php) { + this.php = php; + return this; + } + + /** + * Configure Python language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("python") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getPython() { + return python; + } + + @JsonProperty("python") + public ExperimentalInstrumentationModel setPython( + ExperimentalLanguageSpecificInstrumentationModel python) { + this.python = python; + return this; + } + + /** + * Configure Ruby language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("ruby") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getRuby() { + return ruby; + } + + @JsonProperty("ruby") + public ExperimentalInstrumentationModel setRuby( + ExperimentalLanguageSpecificInstrumentationModel ruby) { + this.ruby = ruby; + return this; + } + + /** + * Configure Rust language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("rust") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getRust() { + return rust; + } + + @JsonProperty("rust") + public ExperimentalInstrumentationModel setRust( + ExperimentalLanguageSpecificInstrumentationModel rust) { + this.rust = rust; + return this; + } + + /** + * Configure Swift language-specific instrumentation libraries. + * + *

      Each entry's key identifies a particular instrumentation library. The corresponding value + * configures it. + * + *

      If omitted, instrumentation defaults are used. + */ + @JsonProperty("swift") + @Nullable + public ExperimentalLanguageSpecificInstrumentationModel getSwift() { + return swift; + } + + @JsonProperty("swift") + public ExperimentalInstrumentationModel setSwift( + ExperimentalLanguageSpecificInstrumentationModel swift) { + this.swift = swift; + return this; + } + + @Override + public String toString() { + return "ExperimentalInstrumentationModel{" + + "general=" + + general + + ", cpp=" + + cpp + + ", dotnet=" + + dotnet + + ", erlang=" + + erlang + + ", go=" + + go + + ", java=" + + java + + ", js=" + + js + + ", php=" + + php + + ", python=" + + python + + ", ruby=" + + ruby + + ", rust=" + + rust + + ", swift=" + + swift + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.general == null) ? 0 : this.general.hashCode(); + h *= 1000003; + h ^= (this.cpp == null) ? 0 : this.cpp.hashCode(); + h *= 1000003; + h ^= (this.dotnet == null) ? 0 : this.dotnet.hashCode(); + h *= 1000003; + h ^= (this.erlang == null) ? 0 : this.erlang.hashCode(); + h *= 1000003; + h ^= (this.go == null) ? 0 : this.go.hashCode(); + h *= 1000003; + h ^= (this.java == null) ? 0 : this.java.hashCode(); + h *= 1000003; + h ^= (this.js == null) ? 0 : this.js.hashCode(); + h *= 1000003; + h ^= (this.php == null) ? 0 : this.php.hashCode(); + h *= 1000003; + h ^= (this.python == null) ? 0 : this.python.hashCode(); + h *= 1000003; + h ^= (this.ruby == null) ? 0 : this.ruby.hashCode(); + h *= 1000003; + h ^= (this.rust == null) ? 0 : this.rust.hashCode(); + h *= 1000003; + h ^= (this.swift == null) ? 0 : this.swift.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalInstrumentationModel) { + ExperimentalInstrumentationModel that = (ExperimentalInstrumentationModel) o; + return (this.general == null ? that.general == null : this.general.equals(that.general)) + && (this.cpp == null ? that.cpp == null : this.cpp.equals(that.cpp)) + && (this.dotnet == null ? that.dotnet == null : this.dotnet.equals(that.dotnet)) + && (this.erlang == null ? that.erlang == null : this.erlang.equals(that.erlang)) + && (this.go == null ? that.go == null : this.go.equals(that.go)) + && (this.java == null ? that.java == null : this.java.equals(that.java)) + && (this.js == null ? that.js == null : this.js.equals(that.js)) + && (this.php == null ? that.php == null : this.php.equals(that.php)) + && (this.python == null ? that.python == null : this.python.equals(that.python)) + && (this.ruby == null ? that.ruby == null : this.ruby.equals(that.ruby)) + && (this.rust == null ? that.rust == null : this.rust.equals(that.rust)) + && (this.swift == null ? that.swift == null : this.swift.equals(that.swift)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalJaegerRemoteSamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalJaegerRemoteSamplerModel.java new file mode 100644 index 00000000000..5994dd46453 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalJaegerRemoteSamplerModel.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"endpoint", "interval", "initial_sampler"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalJaegerRemoteSamplerModel { + + @Nullable private String endpoint; + @Nullable private Integer interval; + @Nullable private SamplerModel initialSampler; + + /** + * Configure the endpoint of the jaeger remote sampling service. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("endpoint") + @Nullable + public String getEndpoint() { + return endpoint; + } + + @JsonProperty("endpoint") + public ExperimentalJaegerRemoteSamplerModel setEndpoint(String endpoint) { + this.endpoint = endpoint; + return this; + } + + /** + * Configure the polling interval (in milliseconds) to fetch from the remote sampling service. + * + *

      If omitted or null, 60000 is used. + */ + @JsonProperty("interval") + @Nullable + public Integer getInterval() { + return interval; + } + + @JsonProperty("interval") + public ExperimentalJaegerRemoteSamplerModel setInterval(Integer interval) { + this.interval = interval; + return this; + } + + /** + * Configure the initial sampler used before first configuration is fetched. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("initial_sampler") + @Nullable + public SamplerModel getInitialSampler() { + return initialSampler; + } + + @JsonProperty("initial_sampler") + public ExperimentalJaegerRemoteSamplerModel setInitialSampler(SamplerModel initialSampler) { + this.initialSampler = initialSampler; + return this; + } + + @Override + public String toString() { + return "ExperimentalJaegerRemoteSamplerModel{" + + "endpoint=" + + endpoint + + ", interval=" + + interval + + ", initialSampler=" + + initialSampler + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.endpoint == null) ? 0 : this.endpoint.hashCode(); + h *= 1000003; + h ^= (this.interval == null) ? 0 : this.interval.hashCode(); + h *= 1000003; + h ^= (this.initialSampler == null) ? 0 : this.initialSampler.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalJaegerRemoteSamplerModel) { + ExperimentalJaegerRemoteSamplerModel that = (ExperimentalJaegerRemoteSamplerModel) o; + return (this.endpoint == null ? that.endpoint == null : this.endpoint.equals(that.endpoint)) + && (this.interval == null ? that.interval == null : this.interval.equals(that.interval)) + && (this.initialSampler == null + ? that.initialSampler == null + : this.initialSampler.equals(that.initialSampler)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLanguageSpecificInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLanguageSpecificInstrumentationModel.java new file mode 100644 index 00000000000..e7f6b75f5c4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLanguageSpecificInstrumentationModel.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalLanguageSpecificInstrumentationModel { + + private Map + additionalProperties = + new LinkedHashMap(); + + @JsonAnyGetter + public Map + getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public ExperimentalLanguageSpecificInstrumentationModel setAdditionalProperty( + String name, ExperimentalLanguageSpecificInstrumentationPropertyModel value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public String toString() { + return "ExperimentalLanguageSpecificInstrumentationModel{" + + "additionalProperties=" + + additionalProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalLanguageSpecificInstrumentationModel) { + ExperimentalLanguageSpecificInstrumentationModel that = + (ExperimentalLanguageSpecificInstrumentationModel) o; + return (this.additionalProperties == null + ? that.additionalProperties == null + : this.additionalProperties.equals(that.additionalProperties)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLanguageSpecificInstrumentationPropertyModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLanguageSpecificInstrumentationPropertyModel.java new file mode 100644 index 00000000000..88fec9d6309 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLanguageSpecificInstrumentationPropertyModel.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalLanguageSpecificInstrumentationPropertyModel { + + private Map additionalProperties = new LinkedHashMap(); + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public ExperimentalLanguageSpecificInstrumentationPropertyModel setAdditionalProperty( + String name, Object value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public String toString() { + return "ExperimentalLanguageSpecificInstrumentationPropertyModel{" + + "additionalProperties=" + + additionalProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalLanguageSpecificInstrumentationPropertyModel) { + ExperimentalLanguageSpecificInstrumentationPropertyModel that = + (ExperimentalLanguageSpecificInstrumentationPropertyModel) o; + return (this.additionalProperties == null + ? that.additionalProperties == null + : this.additionalProperties.equals(that.additionalProperties)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerConfigModel.java new file mode 100644 index 00000000000..9e472b34fd4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerConfigModel.java @@ -0,0 +1,173 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SeverityNumberModel; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"enabled", "minimum_severity", "trace_based"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalLoggerConfigModel { + + @Nullable private Boolean enabled; + @Nullable private SeverityNumberModel minimumSeverity; + @Nullable private Boolean traceBased; + + /** + * Configure if the logger is enabled or not. + * + *

      If omitted or null, true is used. + */ + @JsonProperty("enabled") + @Nullable + public Boolean getEnabled() { + return enabled; + } + + @JsonProperty("enabled") + public ExperimentalLoggerConfigModel setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Configure severity filtering. + * + *

      Log records with an non-zero (i.e. unspecified) severity number which is less than + * minimum_severity are not processed. + * + *

      Values include: + * + *

      * debug: debug, severity number 5. + * + *

      * debug2: debug2, severity number 6. + * + *

      * debug3: debug3, severity number 7. + * + *

      * debug4: debug4, severity number 8. + * + *

      * error: error, severity number 17. + * + *

      * error2: error2, severity number 18. + * + *

      * error3: error3, severity number 19. + * + *

      * error4: error4, severity number 20. + * + *

      * fatal: fatal, severity number 21. + * + *

      * fatal2: fatal2, severity number 22. + * + *

      * fatal3: fatal3, severity number 23. + * + *

      * fatal4: fatal4, severity number 24. + * + *

      * info: info, severity number 9. + * + *

      * info2: info2, severity number 10. + * + *

      * info3: info3, severity number 11. + * + *

      * info4: info4, severity number 12. + * + *

      * trace: trace, severity number 1. + * + *

      * trace2: trace2, severity number 2. + * + *

      * trace3: trace3, severity number 3. + * + *

      * trace4: trace4, severity number 4. + * + *

      * warn: warn, severity number 13. + * + *

      * warn2: warn2, severity number 14. + * + *

      * warn3: warn3, severity number 15. + * + *

      * warn4: warn4, severity number 16. + * + *

      If omitted, severity filtering is not applied. + */ + @JsonProperty("minimum_severity") + @Nullable + public SeverityNumberModel getMinimumSeverity() { + return minimumSeverity; + } + + @JsonProperty("minimum_severity") + public ExperimentalLoggerConfigModel setMinimumSeverity(SeverityNumberModel minimumSeverity) { + this.minimumSeverity = minimumSeverity; + return this; + } + + /** + * Configure trace based filtering. + * + *

      If true, log records associated with unsampled trace contexts traces are not processed. If + * false, or if a log record is not associated with a trace context, trace based filtering is not + * applied. + * + *

      If omitted or null, trace based filtering is not applied. + */ + @JsonProperty("trace_based") + @Nullable + public Boolean getTraceBased() { + return traceBased; + } + + @JsonProperty("trace_based") + public ExperimentalLoggerConfigModel setTraceBased(Boolean traceBased) { + this.traceBased = traceBased; + return this; + } + + @Override + public String toString() { + return "ExperimentalLoggerConfigModel{" + + "enabled=" + + enabled + + ", minimumSeverity=" + + minimumSeverity + + ", traceBased=" + + traceBased + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.enabled == null) ? 0 : this.enabled.hashCode(); + h *= 1000003; + h ^= (this.minimumSeverity == null) ? 0 : this.minimumSeverity.hashCode(); + h *= 1000003; + h ^= (this.traceBased == null) ? 0 : this.traceBased.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalLoggerConfigModel) { + ExperimentalLoggerConfigModel that = (ExperimentalLoggerConfigModel) o; + return (this.enabled == null ? that.enabled == null : this.enabled.equals(that.enabled)) + && (this.minimumSeverity == null + ? that.minimumSeverity == null + : this.minimumSeverity.equals(that.minimumSeverity)) + && (this.traceBased == null + ? that.traceBased == null + : this.traceBased.equals(that.traceBased)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerConfiguratorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerConfiguratorModel.java new file mode 100644 index 00000000000..30ba1a471a1 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerConfiguratorModel.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"default_config", "loggers"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalLoggerConfiguratorModel { + + @Nullable private ExperimentalLoggerConfigModel defaultConfig; + @Nullable private List loggers; + + /** + * Configure the default logger config used there is no matching entry in + * .logger_configurator/development.loggers. + * + *

      If omitted, unmatched .loggers use default values as described in ExperimentalLoggerConfig. + */ + @JsonProperty("default_config") + @Nullable + public ExperimentalLoggerConfigModel getDefaultConfig() { + return defaultConfig; + } + + @JsonProperty("default_config") + public ExperimentalLoggerConfiguratorModel setDefaultConfig( + ExperimentalLoggerConfigModel defaultConfig) { + this.defaultConfig = defaultConfig; + return this; + } + + /** + * Configure loggers. + * + *

      If omitted, all loggers use .default_config. + */ + @JsonProperty("loggers") + @Nullable + public List getLoggers() { + return loggers; + } + + @JsonProperty("loggers") + public ExperimentalLoggerConfiguratorModel setLoggers( + List loggers) { + this.loggers = loggers; + return this; + } + + @Override + public String toString() { + return "ExperimentalLoggerConfiguratorModel{" + + "defaultConfig=" + + defaultConfig + + ", loggers=" + + loggers + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.defaultConfig == null) ? 0 : this.defaultConfig.hashCode(); + h *= 1000003; + h ^= (this.loggers == null) ? 0 : this.loggers.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalLoggerConfiguratorModel) { + ExperimentalLoggerConfiguratorModel that = (ExperimentalLoggerConfiguratorModel) o; + return (this.defaultConfig == null + ? that.defaultConfig == null + : this.defaultConfig.equals(that.defaultConfig)) + && (this.loggers == null ? that.loggers == null : this.loggers.equals(that.loggers)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerMatcherAndConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerMatcherAndConfigModel.java new file mode 100644 index 00000000000..7c03f308ba2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalLoggerMatcherAndConfigModel.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"name", "config"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalLoggerMatcherAndConfigModel { + + @Nullable private String name; + @Nullable private ExperimentalLoggerConfigModel config; + + /** + * Configure logger names to match. Matching is case-sensitive, evaluated as follows: + * + *

      * If the logger name exactly matches. + * + *

      * If the logger name matches the wildcard pattern, where '?' matches any single character + * and '*' matches any number of characters including none. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("name") + @Nullable + public String getName() { + return name; + } + + @JsonProperty("name") + public ExperimentalLoggerMatcherAndConfigModel setName(String name) { + this.name = name; + return this; + } + + /** + * The logger config. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("config") + @Nullable + public ExperimentalLoggerConfigModel getConfig() { + return config; + } + + @JsonProperty("config") + public ExperimentalLoggerMatcherAndConfigModel setConfig(ExperimentalLoggerConfigModel config) { + this.config = config; + return this; + } + + @Override + public String toString() { + return "ExperimentalLoggerMatcherAndConfigModel{" + "name=" + name + ", config=" + config + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.name == null) ? 0 : this.name.hashCode(); + h *= 1000003; + h ^= (this.config == null) ? 0 : this.config.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalLoggerMatcherAndConfigModel) { + ExperimentalLoggerMatcherAndConfigModel that = (ExperimentalLoggerMatcherAndConfigModel) o; + return (this.name == null ? that.name == null : this.name.equals(that.name)) + && (this.config == null ? that.config == null : this.config.equals(that.config)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMessagingInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMessagingInstrumentationModel.java new file mode 100644 index 00000000000..772b993c649 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMessagingInstrumentationModel.java @@ -0,0 +1,70 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"semconv"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalMessagingInstrumentationModel { + + @Nullable private ExperimentalSemconvConfigModel semconv; + + /** + * Configure messaging semantic convention version and migration behavior. + * + *

      This property takes precedence over the + * .instrumentation/development.general.stability_opt_in_list setting. + * + *

      See messaging semantic conventions: https://opentelemetry.io/docs/specs/semconv/messaging/ + * + *

      If omitted, uses the general stability_opt_in_list setting, or instrumentations continue + * emitting their default semantic convention version if not set. + */ + @JsonProperty("semconv") + @Nullable + public ExperimentalSemconvConfigModel getSemconv() { + return semconv; + } + + @JsonProperty("semconv") + public ExperimentalMessagingInstrumentationModel setSemconv( + ExperimentalSemconvConfigModel semconv) { + this.semconv = semconv; + return this; + } + + @Override + public String toString() { + return "ExperimentalMessagingInstrumentationModel{" + "semconv=" + semconv + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.semconv == null) ? 0 : this.semconv.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalMessagingInstrumentationModel) { + ExperimentalMessagingInstrumentationModel that = + (ExperimentalMessagingInstrumentationModel) o; + return (this.semconv == null ? that.semconv == null : this.semconv.equals(that.semconv)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterConfigModel.java new file mode 100644 index 00000000000..85225e1ccad --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterConfigModel.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"enabled"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalMeterConfigModel { + + @Nullable private Boolean enabled; + + /** + * Configure if the meter is enabled or not. + * + *

      If omitted, true is used. + */ + @JsonProperty("enabled") + @Nullable + public Boolean getEnabled() { + return enabled; + } + + @JsonProperty("enabled") + public ExperimentalMeterConfigModel setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + @Override + public String toString() { + return "ExperimentalMeterConfigModel{" + "enabled=" + enabled + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.enabled == null) ? 0 : this.enabled.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalMeterConfigModel) { + ExperimentalMeterConfigModel that = (ExperimentalMeterConfigModel) o; + return (this.enabled == null ? that.enabled == null : this.enabled.equals(that.enabled)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterConfiguratorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterConfiguratorModel.java new file mode 100644 index 00000000000..8596033a7e3 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterConfiguratorModel.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"default_config", "meters"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalMeterConfiguratorModel { + + @Nullable private ExperimentalMeterConfigModel defaultConfig; + @Nullable private List meters; + + /** + * Configure the default meter config used there is no matching entry in + * .meter_configurator/development.meters. + * + *

      If omitted, unmatched .meters use default values as described in ExperimentalMeterConfig. + */ + @JsonProperty("default_config") + @Nullable + public ExperimentalMeterConfigModel getDefaultConfig() { + return defaultConfig; + } + + @JsonProperty("default_config") + public ExperimentalMeterConfiguratorModel setDefaultConfig( + ExperimentalMeterConfigModel defaultConfig) { + this.defaultConfig = defaultConfig; + return this; + } + + /** + * Configure meters. + * + *

      If omitted, all meters used .default_config. + */ + @JsonProperty("meters") + @Nullable + public List getMeters() { + return meters; + } + + @JsonProperty("meters") + public ExperimentalMeterConfiguratorModel setMeters( + List meters) { + this.meters = meters; + return this; + } + + @Override + public String toString() { + return "ExperimentalMeterConfiguratorModel{" + + "defaultConfig=" + + defaultConfig + + ", meters=" + + meters + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.defaultConfig == null) ? 0 : this.defaultConfig.hashCode(); + h *= 1000003; + h ^= (this.meters == null) ? 0 : this.meters.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalMeterConfiguratorModel) { + ExperimentalMeterConfiguratorModel that = (ExperimentalMeterConfiguratorModel) o; + return (this.defaultConfig == null + ? that.defaultConfig == null + : this.defaultConfig.equals(that.defaultConfig)) + && (this.meters == null ? that.meters == null : this.meters.equals(that.meters)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterMatcherAndConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterMatcherAndConfigModel.java new file mode 100644 index 00000000000..1ee5bda2aac --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalMeterMatcherAndConfigModel.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"name", "config"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalMeterMatcherAndConfigModel { + + @Nullable private String name; + @Nullable private ExperimentalMeterConfigModel config; + + /** + * Configure meter names to match. Matching is case-sensitive, evaluated as follows: + * + *

      * If the meter name exactly matches. + * + *

      * If the meter name matches the wildcard pattern, where '?' matches any single character and + * '*' matches any number of characters including none. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("name") + @Nullable + public String getName() { + return name; + } + + @JsonProperty("name") + public ExperimentalMeterMatcherAndConfigModel setName(String name) { + this.name = name; + return this; + } + + /** + * The meter config. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("config") + @Nullable + public ExperimentalMeterConfigModel getConfig() { + return config; + } + + @JsonProperty("config") + public ExperimentalMeterMatcherAndConfigModel setConfig(ExperimentalMeterConfigModel config) { + this.config = config; + return this; + } + + @Override + public String toString() { + return "ExperimentalMeterMatcherAndConfigModel{" + "name=" + name + ", config=" + config + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.name == null) ? 0 : this.name.hashCode(); + h *= 1000003; + h ^= (this.config == null) ? 0 : this.config.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalMeterMatcherAndConfigModel) { + ExperimentalMeterMatcherAndConfigModel that = (ExperimentalMeterMatcherAndConfigModel) o; + return (this.name == null ? that.name == null : this.name.equals(that.name)) + && (this.config == null ? that.config == null : this.config.equals(that.config)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalOtlpFileExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalOtlpFileExporterModel.java new file mode 100644 index 00000000000..e0abf689f05 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalOtlpFileExporterModel.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"output_stream"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalOtlpFileExporterModel { + + @Nullable private String outputStream; + + /** + * Configure output stream. + * + *

      Values include stdout, or scheme+destination. For example: file:///path/to/file.jsonl. + * + *

      If omitted or null, stdout is used. + */ + @JsonProperty("output_stream") + @Nullable + public String getOutputStream() { + return outputStream; + } + + @JsonProperty("output_stream") + public ExperimentalOtlpFileExporterModel setOutputStream(String outputStream) { + this.outputStream = outputStream; + return this; + } + + @Override + public String toString() { + return "ExperimentalOtlpFileExporterModel{" + "outputStream=" + outputStream + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.outputStream == null) ? 0 : this.outputStream.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalOtlpFileExporterModel) { + ExperimentalOtlpFileExporterModel that = (ExperimentalOtlpFileExporterModel) o; + return (this.outputStream == null + ? that.outputStream == null + : this.outputStream.equals(that.outputStream)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalOtlpFileMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalOtlpFileMetricExporterModel.java new file mode 100644 index 00000000000..9a4f9de891d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalOtlpFileMetricExporterModel.java @@ -0,0 +1,144 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExporterDefaultHistogramAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExporterTemporalityPreferenceModel; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"output_stream", "temporality_preference", "default_histogram_aggregation"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalOtlpFileMetricExporterModel { + + @Nullable private String outputStream; + @Nullable private ExporterTemporalityPreferenceModel temporalityPreference; + @Nullable private ExporterDefaultHistogramAggregationModel defaultHistogramAggregation; + + /** + * Configure output stream. + * + *

      Values include stdout, or scheme+destination. For example: file:///path/to/file.jsonl. + * + *

      If omitted or null, stdout is used. + */ + @JsonProperty("output_stream") + @Nullable + public String getOutputStream() { + return outputStream; + } + + @JsonProperty("output_stream") + public ExperimentalOtlpFileMetricExporterModel setOutputStream(String outputStream) { + this.outputStream = outputStream; + return this; + } + + /** + * Configure temporality preference. + * + *

      Values include: + * + *

      * cumulative: Use cumulative aggregation temporality for all instrument types. + * + *

      * delta: Use delta aggregation for all instrument types except up down counter and + * asynchronous up down counter. + * + *

      * low_memory: Use delta aggregation temporality for counter and histogram instrument types. + * Use cumulative aggregation temporality for all other instrument types. + * + *

      If omitted, cumulative is used. + */ + @JsonProperty("temporality_preference") + @Nullable + public ExporterTemporalityPreferenceModel getTemporalityPreference() { + return temporalityPreference; + } + + @JsonProperty("temporality_preference") + public ExperimentalOtlpFileMetricExporterModel setTemporalityPreference( + ExporterTemporalityPreferenceModel temporalityPreference) { + this.temporalityPreference = temporalityPreference; + return this; + } + + /** + * Configure default histogram aggregation. + * + *

      Values include: + * + *

      * base2_exponential_bucket_histogram: Use base2 exponential histogram as the default + * aggregation for histogram instruments. + * + *

      * explicit_bucket_histogram: Use explicit bucket histogram as the default aggregation for + * histogram instruments. + * + *

      If omitted, explicit_bucket_histogram is used. + */ + @JsonProperty("default_histogram_aggregation") + @Nullable + public ExporterDefaultHistogramAggregationModel getDefaultHistogramAggregation() { + return defaultHistogramAggregation; + } + + @JsonProperty("default_histogram_aggregation") + public ExperimentalOtlpFileMetricExporterModel setDefaultHistogramAggregation( + ExporterDefaultHistogramAggregationModel defaultHistogramAggregation) { + this.defaultHistogramAggregation = defaultHistogramAggregation; + return this; + } + + @Override + public String toString() { + return "ExperimentalOtlpFileMetricExporterModel{" + + "outputStream=" + + outputStream + + ", temporalityPreference=" + + temporalityPreference + + ", defaultHistogramAggregation=" + + defaultHistogramAggregation + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.outputStream == null) ? 0 : this.outputStream.hashCode(); + h *= 1000003; + h ^= (this.temporalityPreference == null) ? 0 : this.temporalityPreference.hashCode(); + h *= 1000003; + h ^= + (this.defaultHistogramAggregation == null) + ? 0 + : this.defaultHistogramAggregation.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalOtlpFileMetricExporterModel) { + ExperimentalOtlpFileMetricExporterModel that = (ExperimentalOtlpFileMetricExporterModel) o; + return (this.outputStream == null + ? that.outputStream == null + : this.outputStream.equals(that.outputStream)) + && (this.temporalityPreference == null + ? that.temporalityPreference == null + : this.temporalityPreference.equals(that.temporalityPreference)) + && (this.defaultHistogramAggregation == null + ? that.defaultHistogramAggregation == null + : this.defaultHistogramAggregation.equals(that.defaultHistogramAggregation)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalProbabilitySamplerModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalProbabilitySamplerModel.java new file mode 100644 index 00000000000..5ee299171e5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalProbabilitySamplerModel.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"ratio"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalProbabilitySamplerModel { + + @Nullable private Double ratio; + + /** + * Configure ratio. + * + *

      If omitted or null, 1.0 is used. + */ + @JsonProperty("ratio") + @Nullable + public Double getRatio() { + return ratio; + } + + @JsonProperty("ratio") + public ExperimentalProbabilitySamplerModel setRatio(Double ratio) { + this.ratio = ratio; + return this; + } + + @Override + public String toString() { + return "ExperimentalProbabilitySamplerModel{" + "ratio=" + ratio + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.ratio == null) ? 0 : this.ratio.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalProbabilitySamplerModel) { + ExperimentalProbabilitySamplerModel that = (ExperimentalProbabilitySamplerModel) o; + return (this.ratio == null ? that.ratio == null : this.ratio.equals(that.ratio)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalProcessResourceDetectorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalProcessResourceDetectorModel.java new file mode 100644 index 00000000000..3807471f7bb --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalProcessResourceDetectorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalProcessResourceDetectorModel { + + @Override + public String toString() { + return "ExperimentalProcessResourceDetectorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalProcessResourceDetectorModel) { + ExperimentalProcessResourceDetectorModel that = (ExperimentalProcessResourceDetectorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalPrometheusMetricExporterModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalPrometheusMetricExporterModel.java new file mode 100644 index 00000000000..3f930020e2e --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalPrometheusMetricExporterModel.java @@ -0,0 +1,219 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({ + "host", + "port", + "scope_info_enabled", + "target_info_enabled/development", + "resource_constant_labels", + "translation_strategy" +}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalPrometheusMetricExporterModel { + + @Nullable private String host; + @Nullable private Integer port; + @Nullable private Boolean scopeInfoEnabled; + @Nullable private Boolean targetInfoEnabledDevelopment; + @Nullable private IncludeExcludeModel resourceConstantLabels; + @Nullable private ExperimentalPrometheusTranslationStrategyModel translationStrategy; + + /** + * Configure host. + * + *

      If omitted or null, localhost is used. + */ + @JsonProperty("host") + @Nullable + public String getHost() { + return host; + } + + @JsonProperty("host") + public ExperimentalPrometheusMetricExporterModel setHost(String host) { + this.host = host; + return this; + } + + /** + * Configure port. + * + *

      If omitted or null, 9464 is used. + */ + @JsonProperty("port") + @Nullable + public Integer getPort() { + return port; + } + + @JsonProperty("port") + public ExperimentalPrometheusMetricExporterModel setPort(Integer port) { + this.port = port; + return this; + } + + /** + * Configure Prometheus Exporter to produce metrics with scope labels. + * + *

      If omitted or null, true is used. + */ + @JsonProperty("scope_info_enabled") + @Nullable + public Boolean getScopeInfoEnabled() { + return scopeInfoEnabled; + } + + @JsonProperty("scope_info_enabled") + public ExperimentalPrometheusMetricExporterModel setScopeInfoEnabled(Boolean scopeInfoEnabled) { + this.scopeInfoEnabled = scopeInfoEnabled; + return this; + } + + /** + * Configure Prometheus Exporter to produce metrics with a target info metric for the resource. + * + *

      If omitted or null, true is used. + */ + @JsonProperty("target_info_enabled/development") + @Nullable + public Boolean getTargetInfoEnabledDevelopment() { + return targetInfoEnabledDevelopment; + } + + @JsonProperty("target_info_enabled/development") + public ExperimentalPrometheusMetricExporterModel setTargetInfoEnabledDevelopment( + Boolean targetInfoEnabledDevelopment) { + this.targetInfoEnabledDevelopment = targetInfoEnabledDevelopment; + return this; + } + + /** + * Configure Prometheus Exporter to add resource attributes as metrics attributes, where the + * resource attribute keys match the patterns. + * + *

      If omitted, no resource attributes are added. + */ + @JsonProperty("resource_constant_labels") + @Nullable + public IncludeExcludeModel getResourceConstantLabels() { + return resourceConstantLabels; + } + + @JsonProperty("resource_constant_labels") + public ExperimentalPrometheusMetricExporterModel setResourceConstantLabels( + IncludeExcludeModel resourceConstantLabels) { + this.resourceConstantLabels = resourceConstantLabels; + return this; + } + + /** + * Configure how metric names are translated to Prometheus metric names. + * + *

      Values include: + * + *

      * no_translation/development: Special character escaping is disabled. Type and unit suffixes + * are disabled. Metric names are unaltered. + * + *

      * no_utf8_escaping_with_suffixes/development: Special character escaping is disabled. Type + * and unit suffixes are enabled. + * + *

      * underscore_escaping_with_suffixes: Special character escaping is enabled. Type and unit + * suffixes are enabled. + * + *

      * underscore_escaping_without_suffixes/development: Special character escaping is enabled. + * Type and unit suffixes are disabled. This represents classic Prometheus metric name + * compatibility. + * + *

      If omitted, underscore_escaping_with_suffixes is used. + */ + @JsonProperty("translation_strategy") + @Nullable + public ExperimentalPrometheusTranslationStrategyModel getTranslationStrategy() { + return translationStrategy; + } + + @JsonProperty("translation_strategy") + public ExperimentalPrometheusMetricExporterModel setTranslationStrategy( + ExperimentalPrometheusTranslationStrategyModel translationStrategy) { + this.translationStrategy = translationStrategy; + return this; + } + + @Override + public String toString() { + return "ExperimentalPrometheusMetricExporterModel{" + + "host=" + + host + + ", port=" + + port + + ", scopeInfoEnabled=" + + scopeInfoEnabled + + ", targetInfoEnabledDevelopment=" + + targetInfoEnabledDevelopment + + ", resourceConstantLabels=" + + resourceConstantLabels + + ", translationStrategy=" + + translationStrategy + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.host == null) ? 0 : this.host.hashCode(); + h *= 1000003; + h ^= (this.port == null) ? 0 : this.port.hashCode(); + h *= 1000003; + h ^= (this.scopeInfoEnabled == null) ? 0 : this.scopeInfoEnabled.hashCode(); + h *= 1000003; + h ^= + (this.targetInfoEnabledDevelopment == null) + ? 0 + : this.targetInfoEnabledDevelopment.hashCode(); + h *= 1000003; + h ^= (this.resourceConstantLabels == null) ? 0 : this.resourceConstantLabels.hashCode(); + h *= 1000003; + h ^= (this.translationStrategy == null) ? 0 : this.translationStrategy.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalPrometheusMetricExporterModel) { + ExperimentalPrometheusMetricExporterModel that = + (ExperimentalPrometheusMetricExporterModel) o; + return (this.host == null ? that.host == null : this.host.equals(that.host)) + && (this.port == null ? that.port == null : this.port.equals(that.port)) + && (this.scopeInfoEnabled == null + ? that.scopeInfoEnabled == null + : this.scopeInfoEnabled.equals(that.scopeInfoEnabled)) + && (this.targetInfoEnabledDevelopment == null + ? that.targetInfoEnabledDevelopment == null + : this.targetInfoEnabledDevelopment.equals(that.targetInfoEnabledDevelopment)) + && (this.resourceConstantLabels == null + ? that.resourceConstantLabels == null + : this.resourceConstantLabels.equals(that.resourceConstantLabels)) + && (this.translationStrategy == null + ? that.translationStrategy == null + : this.translationStrategy.equals(that.translationStrategy)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalPrometheusTranslationStrategyModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalPrometheusTranslationStrategyModel.java new file mode 100644 index 00000000000..f3018034e2d --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalPrometheusTranslationStrategyModel.java @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum ExperimentalPrometheusTranslationStrategyModel { + UNDERSCORE_ESCAPING_WITH_SUFFIXES("underscore_escaping_with_suffixes"), + UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES_DEVELOPMENT( + "underscore_escaping_without_suffixes/development"), + NO_UTF_8_ESCAPING_WITH_SUFFIXES_DEVELOPMENT("no_utf8_escaping_with_suffixes/development"), + NO_TRANSLATION_DEVELOPMENT("no_translation/development"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (ExperimentalPrometheusTranslationStrategyModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + ExperimentalPrometheusTranslationStrategyModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static ExperimentalPrometheusTranslationStrategyModel fromValue(String value) { + ExperimentalPrometheusTranslationStrategyModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectionModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectionModel.java new file mode 100644 index 00000000000..30970fb4f92 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectionModel.java @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"attributes", "detectors"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalResourceDetectionModel { + + @Nullable private IncludeExcludeModel attributes; + @Nullable private List detectors; + + /** + * Configure attributes provided by resource detectors. + * + *

      If omitted, all attributes from resource detectors are added. + */ + @JsonProperty("attributes") + @Nullable + public IncludeExcludeModel getAttributes() { + return attributes; + } + + @JsonProperty("attributes") + public ExperimentalResourceDetectionModel setAttributes(IncludeExcludeModel attributes) { + this.attributes = attributes; + return this; + } + + /** + * Configure resource detectors. + * + *

      Resource detector names are dependent on the SDK language ecosystem. Please consult + * documentation for each respective language. + * + *

      If omitted, no resource detectors are enabled. + */ + @JsonProperty("detectors") + @Nullable + public List getDetectors() { + return detectors; + } + + @JsonProperty("detectors") + public ExperimentalResourceDetectionModel setDetectors( + List detectors) { + this.detectors = detectors; + return this; + } + + @Override + public String toString() { + return "ExperimentalResourceDetectionModel{" + + "attributes=" + + attributes + + ", detectors=" + + detectors + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.attributes == null) ? 0 : this.attributes.hashCode(); + h *= 1000003; + h ^= (this.detectors == null) ? 0 : this.detectors.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalResourceDetectionModel) { + ExperimentalResourceDetectionModel that = (ExperimentalResourceDetectionModel) o; + return (this.attributes == null + ? that.attributes == null + : this.attributes.equals(that.attributes)) + && (this.detectors == null + ? that.detectors == null + : this.detectors.equals(that.detectors)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectorModel.java new file mode 100644 index 00000000000..3697c8aef6f --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectorModel.java @@ -0,0 +1,165 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"container", "host", "process", "service"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalResourceDetectorModel { + + @Nullable private ExperimentalContainerResourceDetectorModel container; + @Nullable private ExperimentalHostResourceDetectorModel host; + @Nullable private ExperimentalProcessResourceDetectorModel process; + @Nullable private ExperimentalServiceResourceDetectorModel service; + private Map additionalProperties = + new LinkedHashMap(); + + /** + * Enable the container resource detector, which populates container.* attributes. + * + *

      If omitted, ignore. + */ + @JsonProperty("container") + @Nullable + public ExperimentalContainerResourceDetectorModel getContainer() { + return container; + } + + @JsonProperty("container") + public ExperimentalResourceDetectorModel setContainer( + ExperimentalContainerResourceDetectorModel container) { + this.container = container; + return this; + } + + /** + * Enable the host resource detector, which populates host.* and os.* attributes. + * + *

      If omitted, ignore. + */ + @JsonProperty("host") + @Nullable + public ExperimentalHostResourceDetectorModel getHost() { + return host; + } + + @JsonProperty("host") + public ExperimentalResourceDetectorModel setHost(ExperimentalHostResourceDetectorModel host) { + this.host = host; + return this; + } + + /** + * Enable the process resource detector, which populates process.* attributes. + * + *

      If omitted, ignore. + */ + @JsonProperty("process") + @Nullable + public ExperimentalProcessResourceDetectorModel getProcess() { + return process; + } + + @JsonProperty("process") + public ExperimentalResourceDetectorModel setProcess( + ExperimentalProcessResourceDetectorModel process) { + this.process = process; + return this; + } + + /** + * Enable the service detector, which populates service.name based on the OTEL_SERVICE_NAME + * environment variable and service.instance.id. + * + *

      If omitted, ignore. + */ + @JsonProperty("service") + @Nullable + public ExperimentalServiceResourceDetectorModel getService() { + return service; + } + + @JsonProperty("service") + public ExperimentalResourceDetectorModel setService( + ExperimentalServiceResourceDetectorModel service) { + this.service = service; + return this; + } + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public ExperimentalResourceDetectorModel setAdditionalProperty( + String name, ExperimentalResourceDetectorPropertyModel value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public String toString() { + return "ExperimentalResourceDetectorModel{" + + "container=" + + container + + ", host=" + + host + + ", process=" + + process + + ", service=" + + service + + ", additionalProperties=" + + additionalProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.container == null) ? 0 : this.container.hashCode(); + h *= 1000003; + h ^= (this.host == null) ? 0 : this.host.hashCode(); + h *= 1000003; + h ^= (this.process == null) ? 0 : this.process.hashCode(); + h *= 1000003; + h ^= (this.service == null) ? 0 : this.service.hashCode(); + h *= 1000003; + h ^= (this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalResourceDetectorModel) { + ExperimentalResourceDetectorModel that = (ExperimentalResourceDetectorModel) o; + return (this.container == null + ? that.container == null + : this.container.equals(that.container)) + && (this.host == null ? that.host == null : this.host.equals(that.host)) + && (this.process == null ? that.process == null : this.process.equals(that.process)) + && (this.service == null ? that.service == null : this.service.equals(that.service)) + && (this.additionalProperties == null + ? that.additionalProperties == null + : this.additionalProperties.equals(that.additionalProperties)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectorPropertyModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectorPropertyModel.java new file mode 100644 index 00000000000..5bd48b5ee85 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalResourceDetectorPropertyModel.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.LinkedHashMap; +import java.util.Map; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalResourceDetectorPropertyModel { + + private Map additionalProperties = new LinkedHashMap(); + + @JsonAnyGetter + public Map getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public ExperimentalResourceDetectorPropertyModel setAdditionalProperty( + String name, Object value) { + this.additionalProperties.put(name, value); + return this; + } + + @Override + public String toString() { + return "ExperimentalResourceDetectorPropertyModel{" + + "additionalProperties=" + + additionalProperties + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.additionalProperties == null) ? 0 : this.additionalProperties.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalResourceDetectorPropertyModel) { + ExperimentalResourceDetectorPropertyModel that = + (ExperimentalResourceDetectorPropertyModel) o; + return (this.additionalProperties == null + ? that.additionalProperties == null + : this.additionalProperties.equals(that.additionalProperties)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalRpcInstrumentationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalRpcInstrumentationModel.java new file mode 100644 index 00000000000..06a66cdb645 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalRpcInstrumentationModel.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"semconv"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalRpcInstrumentationModel { + + @Nullable private ExperimentalSemconvConfigModel semconv; + + /** + * Configure RPC semantic convention version and migration behavior. + * + *

      This property takes precedence over the + * .instrumentation/development.general.stability_opt_in_list setting. + * + *

      See RPC semantic conventions: https://opentelemetry.io/docs/specs/semconv/rpc/ + * + *

      If omitted, uses the general stability_opt_in_list setting, or instrumentations continue + * emitting their default semantic convention version if not set. + */ + @JsonProperty("semconv") + @Nullable + public ExperimentalSemconvConfigModel getSemconv() { + return semconv; + } + + @JsonProperty("semconv") + public ExperimentalRpcInstrumentationModel setSemconv(ExperimentalSemconvConfigModel semconv) { + this.semconv = semconv; + return this; + } + + @Override + public String toString() { + return "ExperimentalRpcInstrumentationModel{" + "semconv=" + semconv + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.semconv == null) ? 0 : this.semconv.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalRpcInstrumentationModel) { + ExperimentalRpcInstrumentationModel that = (ExperimentalRpcInstrumentationModel) o; + return (this.semconv == null ? that.semconv == null : this.semconv.equals(that.semconv)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSanitizationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSanitizationModel.java new file mode 100644 index 00000000000..31d7da6dd4b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSanitizationModel.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"url"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalSanitizationModel { + + @Nullable private ExperimentalUrlSanitizationModel url; + + /** + * Configure URL sanitization options. + * + *

      If omitted, defaults as described in ExperimentalUrlSanitization are used. + */ + @JsonProperty("url") + @Nullable + public ExperimentalUrlSanitizationModel getUrl() { + return url; + } + + @JsonProperty("url") + public ExperimentalSanitizationModel setUrl(ExperimentalUrlSanitizationModel url) { + this.url = url; + return this; + } + + @Override + public String toString() { + return "ExperimentalSanitizationModel{" + "url=" + url + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.url == null) ? 0 : this.url.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalSanitizationModel) { + ExperimentalSanitizationModel that = (ExperimentalSanitizationModel) o; + return (this.url == null ? that.url == null : this.url.equals(that.url)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSemconvConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSemconvConfigModel.java new file mode 100644 index 00000000000..2fed4d28ed5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSemconvConfigModel.java @@ -0,0 +1,123 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"version", "experimental", "dual_emit"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalSemconvConfigModel { + + @Nullable private Integer version; + @Nullable private Boolean experimental; + @Nullable private Boolean dualEmit; + + /** + * The target semantic convention version for this domain (e.g., 1). + * + *

      If omitted or null, the latest stable version is used, or if no stable version is available + * and .experimental is true then the latest experimental version is used. + */ + @JsonProperty("version") + @Nullable + public Integer getVersion() { + return version; + } + + @JsonProperty("version") + public ExperimentalSemconvConfigModel setVersion(Integer version) { + this.version = version; + return this; + } + + /** + * Use latest experimental semantic conventions (before stable is available or to enable + * experimental features on top of stable conventions). + * + *

      If omitted or null, false is used. + */ + @JsonProperty("experimental") + @Nullable + public Boolean getExperimental() { + return experimental; + } + + @JsonProperty("experimental") + public ExperimentalSemconvConfigModel setExperimental(Boolean experimental) { + this.experimental = experimental; + return this; + } + + /** + * When true, also emit the previous major version alongside the target version. + * + *

      For version=1, the previous version refers to the pre-stable conventions that the + * instrumentation emitted before the first stable semantic convention version was defined. + * + *

      For version=2 and above, the previous version is the prior stable major version (e.g., + * version=2, dual_emit=true emits both v2 and v1). + * + *

      Enables dual-emit for phased migration between versions. + * + *

      If omitted or null, false is used. + */ + @JsonProperty("dual_emit") + @Nullable + public Boolean getDualEmit() { + return dualEmit; + } + + @JsonProperty("dual_emit") + public ExperimentalSemconvConfigModel setDualEmit(Boolean dualEmit) { + this.dualEmit = dualEmit; + return this; + } + + @Override + public String toString() { + return "ExperimentalSemconvConfigModel{" + + "version=" + + version + + ", experimental=" + + experimental + + ", dualEmit=" + + dualEmit + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.version == null) ? 0 : this.version.hashCode(); + h *= 1000003; + h ^= (this.experimental == null) ? 0 : this.experimental.hashCode(); + h *= 1000003; + h ^= (this.dualEmit == null) ? 0 : this.dualEmit.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalSemconvConfigModel) { + ExperimentalSemconvConfigModel that = (ExperimentalSemconvConfigModel) o; + return (this.version == null ? that.version == null : this.version.equals(that.version)) + && (this.experimental == null + ? that.experimental == null + : this.experimental.equals(that.experimental)) + && (this.dualEmit == null ? that.dualEmit == null : this.dualEmit.equals(that.dualEmit)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalServiceResourceDetectorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalServiceResourceDetectorModel.java new file mode 100644 index 00000000000..26305c126d8 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalServiceResourceDetectorModel.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalServiceResourceDetectorModel { + + @Override + public String toString() { + return "ExperimentalServiceResourceDetectorModel{}"; + } + + @Override + public int hashCode() { + int h = 1; + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalServiceResourceDetectorModel) { + ExperimentalServiceResourceDetectorModel that = (ExperimentalServiceResourceDetectorModel) o; + return true; + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSpanParentModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSpanParentModel.java new file mode 100644 index 00000000000..5ae4f3e3a08 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalSpanParentModel.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum ExperimentalSpanParentModel { + NONE("none"), + REMOTE("remote"), + LOCAL("local"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (ExperimentalSpanParentModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + ExperimentalSpanParentModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static ExperimentalSpanParentModel fromValue(String value) { + ExperimentalSpanParentModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerConfigModel.java new file mode 100644 index 00000000000..4aa579aa2c5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerConfigModel.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"enabled"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalTracerConfigModel { + + @Nullable private Boolean enabled; + + /** + * Configure if the tracer is enabled or not. + * + *

      If omitted, true is used. + */ + @JsonProperty("enabled") + @Nullable + public Boolean getEnabled() { + return enabled; + } + + @JsonProperty("enabled") + public ExperimentalTracerConfigModel setEnabled(Boolean enabled) { + this.enabled = enabled; + return this; + } + + @Override + public String toString() { + return "ExperimentalTracerConfigModel{" + "enabled=" + enabled + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.enabled == null) ? 0 : this.enabled.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalTracerConfigModel) { + ExperimentalTracerConfigModel that = (ExperimentalTracerConfigModel) o; + return (this.enabled == null ? that.enabled == null : this.enabled.equals(that.enabled)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerConfiguratorModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerConfiguratorModel.java new file mode 100644 index 00000000000..f155fd6c243 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerConfiguratorModel.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"default_config", "tracers"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalTracerConfiguratorModel { + + @Nullable private ExperimentalTracerConfigModel defaultConfig; + @Nullable private List tracers; + + /** + * Configure the default tracer config used there is no matching entry in + * .tracer_configurator/development.tracers. + * + *

      If omitted, unmatched .tracers use default values as described in ExperimentalTracerConfig. + */ + @JsonProperty("default_config") + @Nullable + public ExperimentalTracerConfigModel getDefaultConfig() { + return defaultConfig; + } + + @JsonProperty("default_config") + public ExperimentalTracerConfiguratorModel setDefaultConfig( + ExperimentalTracerConfigModel defaultConfig) { + this.defaultConfig = defaultConfig; + return this; + } + + /** + * Configure tracers. + * + *

      If omitted, all tracers use .default_config. + */ + @JsonProperty("tracers") + @Nullable + public List getTracers() { + return tracers; + } + + @JsonProperty("tracers") + public ExperimentalTracerConfiguratorModel setTracers( + List tracers) { + this.tracers = tracers; + return this; + } + + @Override + public String toString() { + return "ExperimentalTracerConfiguratorModel{" + + "defaultConfig=" + + defaultConfig + + ", tracers=" + + tracers + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.defaultConfig == null) ? 0 : this.defaultConfig.hashCode(); + h *= 1000003; + h ^= (this.tracers == null) ? 0 : this.tracers.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalTracerConfiguratorModel) { + ExperimentalTracerConfiguratorModel that = (ExperimentalTracerConfiguratorModel) o; + return (this.defaultConfig == null + ? that.defaultConfig == null + : this.defaultConfig.equals(that.defaultConfig)) + && (this.tracers == null ? that.tracers == null : this.tracers.equals(that.tracers)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerMatcherAndConfigModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerMatcherAndConfigModel.java new file mode 100644 index 00000000000..7fa58d39252 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalTracerMatcherAndConfigModel.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"name", "config"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalTracerMatcherAndConfigModel { + + @Nullable private String name; + @Nullable private ExperimentalTracerConfigModel config; + + /** + * Configure tracer names to match. Matching is case-sensitive, evaluated as follows: + * + *

      * If the tracer name exactly matches. + * + *

      * If the tracer name matches the wildcard pattern, where '?' matches any single character + * and '*' matches any number of characters including none. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("name") + @Nullable + public String getName() { + return name; + } + + @JsonProperty("name") + public ExperimentalTracerMatcherAndConfigModel setName(String name) { + this.name = name; + return this; + } + + /** + * The tracer config. + * + *

      Property is required and must be non-null. + */ + @JsonProperty("config") + @Nullable + public ExperimentalTracerConfigModel getConfig() { + return config; + } + + @JsonProperty("config") + public ExperimentalTracerMatcherAndConfigModel setConfig(ExperimentalTracerConfigModel config) { + this.config = config; + return this; + } + + @Override + public String toString() { + return "ExperimentalTracerMatcherAndConfigModel{" + "name=" + name + ", config=" + config + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.name == null) ? 0 : this.name.hashCode(); + h *= 1000003; + h ^= (this.config == null) ? 0 : this.config.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalTracerMatcherAndConfigModel) { + ExperimentalTracerMatcherAndConfigModel that = (ExperimentalTracerMatcherAndConfigModel) o; + return (this.name == null ? that.name == null : this.name.equals(that.name)) + && (this.config == null ? that.config == null : this.config.equals(that.config)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalUrlSanitizationModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalUrlSanitizationModel.java new file mode 100644 index 00000000000..26c766d07e1 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalUrlSanitizationModel.java @@ -0,0 +1,79 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import java.util.List; +import javax.annotation.Generated; +import javax.annotation.Nullable; + +@JsonInclude(JsonInclude.Include.NON_NULL) +@JsonPropertyOrder({"sensitive_query_parameters"}) +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public class ExperimentalUrlSanitizationModel { + + @Nullable private List sensitiveQueryParameters; + + /** + * List of query parameter names whose values should be redacted from URLs. + * + *

      Query parameter names are case-sensitive. + * + *

      This is a full override of the default sensitive query parameter keys, it is not a list of + * keys in addition to the defaults. + * + *

      Set to an empty array to disable query parameter redaction. + * + *

      If omitted, the default sensitive query parameter list as defined by the url semantic + * conventions + * (https://github.com/open-telemetry/semantic-conventions/blob/main/docs/registry/attributes/url.md) + * is used. + */ + @JsonProperty("sensitive_query_parameters") + @Nullable + public List getSensitiveQueryParameters() { + return sensitiveQueryParameters; + } + + @JsonProperty("sensitive_query_parameters") + public ExperimentalUrlSanitizationModel setSensitiveQueryParameters( + List sensitiveQueryParameters) { + this.sensitiveQueryParameters = sensitiveQueryParameters; + return this; + } + + @Override + public String toString() { + return "ExperimentalUrlSanitizationModel{" + + "sensitiveQueryParameters=" + + sensitiveQueryParameters + + "}"; + } + + @Override + public int hashCode() { + int h = 1; + h *= 1000003; + h ^= (this.sensitiveQueryParameters == null) ? 0 : this.sensitiveQueryParameters.hashCode(); + return h; + } + + @Override + public boolean equals(@Nullable Object o) { + if (o == this) { + return true; + } + if (o instanceof ExperimentalUrlSanitizationModel) { + ExperimentalUrlSanitizationModel that = (ExperimentalUrlSanitizationModel) o; + return (this.sensitiveQueryParameters == null + ? that.sensitiveQueryParameters == null + : this.sensitiveQueryParameters.equals(that.sensitiveQueryParameters)); + } + return false; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalViewMatchingModeModel.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalViewMatchingModeModel.java new file mode 100644 index 00000000000..cd7107a6284 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExperimentalViewMatchingModeModel.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Generated; + +@Generated("io.opentelemetry.gradle.DeclarativeConfigPojoGenerator") +public enum ExperimentalViewMatchingModeModel { + INDEPENDENT("independent"), + COMPOSABLE("composable"); + private final String value; + private static final Map CONSTANTS = + new HashMap(); + + static { + for (ExperimentalViewMatchingModeModel c : values()) { + CONSTANTS.put(c.value, c); + } + } + + ExperimentalViewMatchingModeModel(String value) { + this.value = value; + } + + @Override + public String toString() { + return this.value; + } + + @JsonValue + public String value() { + return this.value; + } + + @JsonCreator + public static ExperimentalViewMatchingModeModel fromValue(String value) { + ExperimentalViewMatchingModeModel constant = CONSTANTS.get(value); + if (constant == null) { + throw new IllegalArgumentException(value); + } else { + return constant; + } + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExtensionPropertyUtil.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExtensionPropertyUtil.java new file mode 100644 index 00000000000..80d972e2a9c --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ExtensionPropertyUtil.java @@ -0,0 +1,137 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal.DeclarativeConfigurationMapperUtil; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * Shared {@code @JsonAnySetter} logic for generated stable model classes. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class ExtensionPropertyUtil { + + private static final String DEV_SUFFIX = "/development"; + private static final Logger LOGGER = Logger.getLogger(ExtensionPropertyUtil.class.getName()); + + private ExtensionPropertyUtil() {} + + /** + * Routes a single {@code @JsonAnySetter} call into {@code extensionProperties}. Known + * experimental keys are type-converted for parse-time checking. Keys of the form {@code + * {stableName}/development} for a known stable property are graduated: a warning is logged and + * the value is converted to the stable type but stored under the original {@code /development} + * key so serialization round-trips. Unknown keys are stored raw on open types or + * warned-and-dropped on closed types. + */ + public static void handleAnySetter( + String name, + @Nullable Object value, + Map extensionProperties, + Map> experimentalPropertyTypes, + Map> stablePropertyTypes, + boolean allowsAdditionalProperties) { + + if (name.endsWith(DEV_SUFFIX)) { + String candidate = name.substring(0, name.length() - DEV_SUFFIX.length()); + Class stableType = stablePropertyTypes.get(candidate); + if (stableType != null) { + LOGGER.warning( + "Property '" + name + "' has been stabilized. Use '" + candidate + "' instead."); + extensionProperties.put( + name, + value == null ? null : DeclarativeConfigurationMapperUtil.convert(value, stableType)); + return; + } + } + + Class experimentalType = experimentalPropertyTypes.get(name); + if (experimentalType != null) { + extensionProperties.put( + name, + value == null + ? null + : DeclarativeConfigurationMapperUtil.convert(value, experimentalType)); + return; + } + + if (allowsAdditionalProperties) { + extensionProperties.put(name, value); + return; + } + + LOGGER.warning("Unknown property '" + name + "' is not recognized and will be ignored."); + } + + /** + * Returns the extension property value for {@code key}, cast to {@code type}. + * + *

      Values are guaranteed to be the correct type at store time: {@link #handleAnySetter} + * converts known experimental properties via the configured mapper before storing, and the + * generated accessor builders enforce the type at the call site. A {@link ClassCastException} + * here indicates a contract violation (e.g. writing directly to the extension properties map with + * the wrong type). + * + *

      Tolerates a null {@code extensionProperties} map (returning null) even though the generated + * field is always initialized: generated equals/hashCode call through the getters that call this + * method, and EqualsVerifier's null-safety check reflectively nulls every field, including {@code + * extensionProperties}, to prove equals/hashCode never throw. + */ + @Nullable + public static T get( + String key, @Nullable Map extensionProperties, Class type) { + Object raw = extensionProperties == null ? null : extensionProperties.get(key); + return raw == null ? null : type.cast(raw); + } + + /** + * Looks up a graduated value stored by {@link #handleAnySetter} under {@code stableKey + + * "/development"}. + */ + @Nullable + public static T getGraduated( + String stableKey, @Nullable Map extensionProperties, Class type) { + return get(stableKey + DEV_SUFFIX, extensionProperties, type); + } + + /** + * Returns {@code extensionProperties} minus graduated entries (keys of the form {@code + * X/development} where {@code X} is in {@code stableProperties}). Used by {@code @JsonAnyGetter} + * to avoid emitting graduated values twice: once under the stable {@code @JsonProperty} key via + * the getter's {@link #getGraduated} fallback, and once under {@code /development} via the raw + * map. + * + *

      Tolerates a null {@code extensionProperties} map, returning an empty map; see {@link #get} + * for why. + */ + public static Map filterSerializable( + @Nullable Map extensionProperties, Map> stableProperties) { + if (extensionProperties == null) { + return Collections.emptyMap(); + } + if (stableProperties.isEmpty() || extensionProperties.isEmpty()) { + return extensionProperties; + } + Map filtered = null; + for (String key : extensionProperties.keySet()) { + if (key.endsWith(DEV_SUFFIX) + && stableProperties.containsKey(key.substring(0, key.length() - DEV_SUFFIX.length()))) { + if (filtered == null) { + filtered = new LinkedHashMap<>(extensionProperties); + } + filtered.remove(key); + } + } + return filtered != null ? filtered : extensionProperties; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LogRecordExporterModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LogRecordExporterModelAccessor.java new file mode 100644 index 00000000000..ffaaba900f2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LogRecordExporterModelAccessor.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link LogRecordExporterModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class LogRecordExporterModelAccessor { + + private LogRecordExporterModelAccessor() {} + + static final String OTLP_FILE = "otlp_file/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(OTLP_FILE, ExperimentalOtlpFileExporterModel.class); + } + + @Nullable + public static ExperimentalOtlpFileExporterModel getOtlpFile(LogRecordExporterModel model) { + return ExtensionPropertyUtil.get( + OTLP_FILE, model.getExtensionProperties(), ExperimentalOtlpFileExporterModel.class); + } + + public static LogRecordExporterModel setOtlpFile( + LogRecordExporterModel model, ExperimentalOtlpFileExporterModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(OTLP_FILE, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LogRecordProcessorModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LogRecordProcessorModelAccessor.java new file mode 100644 index 00000000000..3a51edd52a9 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LogRecordProcessorModelAccessor.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link LogRecordProcessorModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class LogRecordProcessorModelAccessor { + + private LogRecordProcessorModelAccessor() {} + + static final String EVENT_TO_SPAN_EVENT_BRIDGE = "event_to_span_event_bridge/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put( + EVENT_TO_SPAN_EVENT_BRIDGE, + ExperimentalEventToSpanEventBridgeLogRecordProcessorModel.class); + } + + @Nullable + public static ExperimentalEventToSpanEventBridgeLogRecordProcessorModel getEventToSpanEventBridge( + LogRecordProcessorModel model) { + return ExtensionPropertyUtil.get( + EVENT_TO_SPAN_EVENT_BRIDGE, + model.getExtensionProperties(), + ExperimentalEventToSpanEventBridgeLogRecordProcessorModel.class); + } + + public static LogRecordProcessorModel setEventToSpanEventBridge( + LogRecordProcessorModel model, + ExperimentalEventToSpanEventBridgeLogRecordProcessorModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(EVENT_TO_SPAN_EVENT_BRIDGE, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LoggerProviderModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LoggerProviderModelAccessor.java new file mode 100644 index 00000000000..fb1ab084ec8 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/LoggerProviderModelAccessor.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link LoggerProviderModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class LoggerProviderModelAccessor { + + private LoggerProviderModelAccessor() {} + + static final String LOGGER_CONFIGURATOR = "logger_configurator/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(LOGGER_CONFIGURATOR, ExperimentalLoggerConfiguratorModel.class); + } + + @Nullable + public static ExperimentalLoggerConfiguratorModel getLoggerConfigurator( + LoggerProviderModel model) { + return ExtensionPropertyUtil.get( + LOGGER_CONFIGURATOR, + model.getExtensionProperties(), + ExperimentalLoggerConfiguratorModel.class); + } + + public static LoggerProviderModel setLoggerConfigurator( + LoggerProviderModel model, ExperimentalLoggerConfiguratorModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(LOGGER_CONFIGURATOR, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/MeterProviderModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/MeterProviderModelAccessor.java new file mode 100644 index 00000000000..6a7dade4ea2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/MeterProviderModelAccessor.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link MeterProviderModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class MeterProviderModelAccessor { + + private MeterProviderModelAccessor() {} + + static final String METER_CONFIGURATOR = "meter_configurator/development"; + static final String VIEW_MATCHING_MODE = "view_matching_mode/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(METER_CONFIGURATOR, ExperimentalMeterConfiguratorModel.class); + EXPERIMENTAL_PROPERTIES.put(VIEW_MATCHING_MODE, ExperimentalViewMatchingModeModel.class); + } + + @Nullable + public static ExperimentalMeterConfiguratorModel getMeterConfigurator(MeterProviderModel model) { + return ExtensionPropertyUtil.get( + METER_CONFIGURATOR, + model.getExtensionProperties(), + ExperimentalMeterConfiguratorModel.class); + } + + public static MeterProviderModel setMeterConfigurator( + MeterProviderModel model, ExperimentalMeterConfiguratorModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(METER_CONFIGURATOR, value); + return model; + } + + @Nullable + public static ExperimentalViewMatchingModeModel getViewMatchingMode(MeterProviderModel model) { + return ExtensionPropertyUtil.get( + VIEW_MATCHING_MODE, + model.getExtensionProperties(), + ExperimentalViewMatchingModeModel.class); + } + + public static MeterProviderModel setViewMatchingMode( + MeterProviderModel model, ExperimentalViewMatchingModeModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(VIEW_MATCHING_MODE, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/OpenTelemetryConfigurationModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/OpenTelemetryConfigurationModelAccessor.java new file mode 100644 index 00000000000..3bf18bf9911 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/OpenTelemetryConfigurationModelAccessor.java @@ -0,0 +1,48 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link OpenTelemetryConfigurationModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class OpenTelemetryConfigurationModelAccessor { + + private OpenTelemetryConfigurationModelAccessor() {} + + static final String INSTRUMENTATION = "instrumentation/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(INSTRUMENTATION, ExperimentalInstrumentationModel.class); + } + + @Nullable + public static ExperimentalInstrumentationModel getInstrumentation( + OpenTelemetryConfigurationModel model) { + return ExtensionPropertyUtil.get( + INSTRUMENTATION, model.getExtensionProperties(), ExperimentalInstrumentationModel.class); + } + + public static OpenTelemetryConfigurationModel setInstrumentation( + OpenTelemetryConfigurationModel model, ExperimentalInstrumentationModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(INSTRUMENTATION, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PeriodicMetricReaderModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PeriodicMetricReaderModelAccessor.java new file mode 100644 index 00000000000..10a3689c2a1 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PeriodicMetricReaderModelAccessor.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link PeriodicMetricReaderModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class PeriodicMetricReaderModelAccessor { + + private PeriodicMetricReaderModelAccessor() {} + + static final String MAX_EXPORT_BATCH_SIZE = "max_export_batch_size/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(MAX_EXPORT_BATCH_SIZE, Integer.class); + } + + @Nullable + public static Integer getMaxExportBatchSize(PeriodicMetricReaderModel model) { + return ExtensionPropertyUtil.get( + MAX_EXPORT_BATCH_SIZE, model.getExtensionProperties(), Integer.class); + } + + public static PeriodicMetricReaderModel setMaxExportBatchSize( + PeriodicMetricReaderModel model, Integer value) { + requireNonNull(value, "value"); + model.setExtensionProperty(MAX_EXPORT_BATCH_SIZE, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PullMetricExporterModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PullMetricExporterModelAccessor.java new file mode 100644 index 00000000000..d05cb79f4ef --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PullMetricExporterModelAccessor.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricExporterModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link PullMetricExporterModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class PullMetricExporterModelAccessor { + + private PullMetricExporterModelAccessor() {} + + static final String PROMETHEUS = "prometheus/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(PROMETHEUS, ExperimentalPrometheusMetricExporterModel.class); + } + + @Nullable + public static ExperimentalPrometheusMetricExporterModel getPrometheus( + PullMetricExporterModel model) { + return ExtensionPropertyUtil.get( + PROMETHEUS, + model.getExtensionProperties(), + ExperimentalPrometheusMetricExporterModel.class); + } + + public static PullMetricExporterModel setPrometheus( + PullMetricExporterModel model, ExperimentalPrometheusMetricExporterModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(PROMETHEUS, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PushMetricExporterModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PushMetricExporterModelAccessor.java new file mode 100644 index 00000000000..a33c1fd19bb --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/PushMetricExporterModelAccessor.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link PushMetricExporterModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class PushMetricExporterModelAccessor { + + private PushMetricExporterModelAccessor() {} + + static final String OTLP_FILE = "otlp_file/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(OTLP_FILE, ExperimentalOtlpFileMetricExporterModel.class); + } + + @Nullable + public static ExperimentalOtlpFileMetricExporterModel getOtlpFile(PushMetricExporterModel model) { + return ExtensionPropertyUtil.get( + OTLP_FILE, model.getExtensionProperties(), ExperimentalOtlpFileMetricExporterModel.class); + } + + public static PushMetricExporterModel setOtlpFile( + PushMetricExporterModel model, ExperimentalOtlpFileMetricExporterModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(OTLP_FILE, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ResourceModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ResourceModelAccessor.java new file mode 100644 index 00000000000..b22381f81c7 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/ResourceModelAccessor.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link ResourceModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class ResourceModelAccessor { + + private ResourceModelAccessor() {} + + static final String DETECTION = "detection/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(DETECTION, ExperimentalResourceDetectionModel.class); + } + + @Nullable + public static ExperimentalResourceDetectionModel getDetection(ResourceModel model) { + return ExtensionPropertyUtil.get( + DETECTION, model.getExtensionProperties(), ExperimentalResourceDetectionModel.class); + } + + public static ResourceModel setDetection( + ResourceModel model, ExperimentalResourceDetectionModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(DETECTION, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/SamplerModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/SamplerModelAccessor.java new file mode 100644 index 00000000000..adaa205927b --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/SamplerModelAccessor.java @@ -0,0 +1,77 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link SamplerModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class SamplerModelAccessor { + + private SamplerModelAccessor() {} + + static final String COMPOSITE = "composite/development"; + static final String JAEGER_REMOTE = "jaeger_remote/development"; + static final String PROBABILITY = "probability/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(COMPOSITE, ExperimentalComposableSamplerModel.class); + EXPERIMENTAL_PROPERTIES.put(JAEGER_REMOTE, ExperimentalJaegerRemoteSamplerModel.class); + EXPERIMENTAL_PROPERTIES.put(PROBABILITY, ExperimentalProbabilitySamplerModel.class); + } + + @Nullable + public static ExperimentalComposableSamplerModel getComposite(SamplerModel model) { + return ExtensionPropertyUtil.get( + COMPOSITE, model.getExtensionProperties(), ExperimentalComposableSamplerModel.class); + } + + public static SamplerModel setComposite( + SamplerModel model, ExperimentalComposableSamplerModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(COMPOSITE, value); + return model; + } + + @Nullable + public static ExperimentalJaegerRemoteSamplerModel getJaegerRemote(SamplerModel model) { + return ExtensionPropertyUtil.get( + JAEGER_REMOTE, model.getExtensionProperties(), ExperimentalJaegerRemoteSamplerModel.class); + } + + public static SamplerModel setJaegerRemote( + SamplerModel model, ExperimentalJaegerRemoteSamplerModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(JAEGER_REMOTE, value); + return model; + } + + @Nullable + public static ExperimentalProbabilitySamplerModel getProbability(SamplerModel model) { + return ExtensionPropertyUtil.get( + PROBABILITY, model.getExtensionProperties(), ExperimentalProbabilitySamplerModel.class); + } + + public static SamplerModel setProbability( + SamplerModel model, ExperimentalProbabilitySamplerModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(PROBABILITY, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/SpanExporterModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/SpanExporterModelAccessor.java new file mode 100644 index 00000000000..f87acc69406 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/SpanExporterModelAccessor.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link SpanExporterModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class SpanExporterModelAccessor { + + private SpanExporterModelAccessor() {} + + static final String OTLP_FILE = "otlp_file/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(OTLP_FILE, ExperimentalOtlpFileExporterModel.class); + } + + @Nullable + public static ExperimentalOtlpFileExporterModel getOtlpFile(SpanExporterModel model) { + return ExtensionPropertyUtil.get( + OTLP_FILE, model.getExtensionProperties(), ExperimentalOtlpFileExporterModel.class); + } + + public static SpanExporterModel setOtlpFile( + SpanExporterModel model, ExperimentalOtlpFileExporterModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(OTLP_FILE, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/TracerProviderModelAccessor.java b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/TracerProviderModelAccessor.java new file mode 100644 index 00000000000..691213fcce5 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/internal/TracerProviderModelAccessor.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Provides typed access to experimental properties on {@link TracerProviderModel}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class TracerProviderModelAccessor { + + private TracerProviderModelAccessor() {} + + static final String TRACER_CONFIGURATOR = "tracer_configurator/development"; + + public static final Map> EXPERIMENTAL_PROPERTIES; + + static { + EXPERIMENTAL_PROPERTIES = new HashMap<>(); + EXPERIMENTAL_PROPERTIES.put(TRACER_CONFIGURATOR, ExperimentalTracerConfiguratorModel.class); + } + + @Nullable + public static ExperimentalTracerConfiguratorModel getTracerConfigurator( + TracerProviderModel model) { + return ExtensionPropertyUtil.get( + TRACER_CONFIGURATOR, + model.getExtensionProperties(), + ExperimentalTracerConfiguratorModel.class); + } + + public static TracerProviderModel setTracerConfigurator( + TracerProviderModel model, ExperimentalTracerConfiguratorModel value) { + requireNonNull(value, "value"); + model.setExtensionProperty(TRACER_CONFIGURATOR, value); + return model; + } +} diff --git a/sdk-extensions/declarative-config/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/sdk-extensions/declarative-config/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..ab573c38938 --- /dev/null +++ b/sdk-extensions/declarative-config/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,3 @@ +io.opentelemetry.sdk.autoconfigure.declarativeconfig.EntitiesEnvResourceDetector +io.opentelemetry.sdk.autoconfigure.declarativeconfig.ServiceResourceDetector + diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AggregationFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AggregationFactoryTest.java new file mode 100644 index 00000000000..a83a8c94e75 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AggregationFactoryTest.java @@ -0,0 +1,143 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.Base2ExponentialBucketHistogramAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.DropAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExplicitBucketHistogramAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LastValueAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SumAggregationModel; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions; +import io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions; +import java.util.Arrays; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class AggregationFactoryTest { + + @ParameterizedTest + @MethodSource("createTestCases") + void create(AggregationModel model, Aggregation expectedResult) { + Aggregation aggregation = + AggregationFactory.getInstance().create(model, mock(DeclarativeConfigContext.class)); + assertThat(aggregation.toString()).isEqualTo(expectedResult.toString()); + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet("default", new AggregationModel(), Aggregation.defaultAggregation()), + Arguments.argumentSet( + "drop", new AggregationModel().setDrop(new DropAggregationModel()), Aggregation.drop()), + Arguments.argumentSet( + "sum", new AggregationModel().setSum(new SumAggregationModel()), Aggregation.sum()), + Arguments.argumentSet( + "last_Value", + new AggregationModel().setLastValue(new LastValueAggregationModel()), + Aggregation.lastValue()), + Arguments.argumentSet( + "base2_exponential_bucket_histogram defaults", + new AggregationModel() + .setBase2ExponentialBucketHistogram( + new Base2ExponentialBucketHistogramAggregationModel()), + Aggregation.base2ExponentialBucketHistogram()), + Arguments.argumentSet( + "base2_exponential_bucket_histogram with options", + new AggregationModel() + .setBase2ExponentialBucketHistogram( + new Base2ExponentialBucketHistogramAggregationModel() + .setMaxSize(2) + .setMaxScale(2)), + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(2) + .setMaxScale(2) + .build())), + Arguments.argumentSet( + "explicit_bucket_histogram null boundaries", + new AggregationModel() + .setExplicitBucketHistogram( + new ExplicitBucketHistogramAggregationModel().setBoundaries(null)), + Aggregation.explicitBucketHistogram()), + Arguments.argumentSet( + "explicit_bucket_histogram with boundaries", + new AggregationModel() + .setExplicitBucketHistogram( + new ExplicitBucketHistogramAggregationModel() + .setBoundaries(Arrays.asList(1.0, 2.0))), + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, 2.0)) + .build())), + Arguments.argumentSet( + "explicit_bucket_histogram record_min_max true", + new AggregationModel() + .setExplicitBucketHistogram( + new ExplicitBucketHistogramAggregationModel() + .setBoundaries(Arrays.asList(1.0, 2.0)) + .setRecordMinMax(true)), + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, 2.0)) + .setRecordMinMax(true) + .build())), + Arguments.argumentSet( + "explicit_bucket_histogram record_min_max false", + new AggregationModel() + .setExplicitBucketHistogram( + new ExplicitBucketHistogramAggregationModel() + .setBoundaries(Arrays.asList(1.0, 2.0)) + .setRecordMinMax(false)), + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, 2.0)) + .setRecordMinMax(false) + .build())), + Arguments.argumentSet( + "explicit_bucket_histogram null boundaries record_min_max false", + new AggregationModel() + .setExplicitBucketHistogram( + new ExplicitBucketHistogramAggregationModel() + .setBoundaries(null) + .setRecordMinMax(false)), + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder().setRecordMinMax(false).build())), + Arguments.argumentSet( + "base2_exponential_bucket_histogram record_min_max true", + new AggregationModel() + .setBase2ExponentialBucketHistogram( + new Base2ExponentialBucketHistogramAggregationModel() + .setMaxSize(2) + .setMaxScale(2) + .setRecordMinMax(true)), + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(2) + .setMaxScale(2) + .setRecordMinMax(true) + .build())), + Arguments.argumentSet( + "base2_exponential_bucket_histogram record_min_max false", + new AggregationModel() + .setBase2ExponentialBucketHistogram( + new Base2ExponentialBucketHistogramAggregationModel() + .setMaxSize(2) + .setMaxScale(2) + .setRecordMinMax(false)), + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(2) + .setMaxScale(2) + .setRecordMinMax(false) + .build()))); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java new file mode 100644 index 00000000000..edc06c3a161 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/AttributeListFactoryTest.java @@ -0,0 +1,153 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeTypeModel; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class AttributeListFactoryTest { + + @ParameterizedTest + @MethodSource("invalidAttributes") + void create_InvalidAttributes(List model, String expectedMessage) { + assertThatThrownBy(() -> + AttributeListFactory.getInstance().create(model, mock(DeclarativeConfigContext.class))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining(expectedMessage); + } + + private static Stream invalidAttributes() { + return Stream.of( + Arguments.argumentSet( + "wrong type string", + Collections.singletonList( + new AttributeNameValueModel().setName("key").setValue(new Object())), + "Error processing attribute with name \"key\": value did not match type STRING"), + Arguments.argumentSet( + "wrong type int list", + Collections.singletonList( + new AttributeNameValueModel() + .setName("key") + .setType(AttributeTypeModel.INT) + .setValue(Arrays.asList(1L, 1))), + "Error processing attribute with name \"key\": value did not match type INT"), + Arguments.argumentSet( + "wrong type int boolean", + Collections.singletonList( + new AttributeNameValueModel() + .setName("key") + .setType(AttributeTypeModel.INT) + .setValue(true)), + "Error processing attribute with name \"key\": value did not match type INT")); + } + + @Test + void create_NullValueIgnored() { + assertThat( + AttributeListFactory.getInstance() + .create( + Arrays.asList( + new AttributeNameValueModel().setName("key"), + new AttributeNameValueModel() + .setName("key2") + .setType(AttributeTypeModel.INT), + new AttributeNameValueModel().setName("other").setValue("v")), + mock(DeclarativeConfigContext.class))) + .isEqualTo(Attributes.of(stringKey("other"), "v")); + } + + @Test + void create() { + Attributes expectedAttributes = + Attributes.builder() + .put("service.name", "my-service") + .put("strKey", "val") + .put("longKey", 1L) + .put("intKey", 2) + .put("doubleKey", 1.0d) + .put("floatKey", 2.0f) + .put("boolKey", true) + .put("strArrKey", "val1", "val2") + .put("longArrKey", 1L, 2L) + .put("intArrKey", 1, 2) + .put("doubleArrKey", 1.0d, 2.0d) + .put("floatArrKey", 1.0f, 2.0f) + .put("boolArrKey", true, false) + .build(); + assertThat( + AttributeListFactory.getInstance() + .create( + Arrays.asList( + new AttributeNameValueModel() + .setName("service.name") + .setValue("my-service"), + new AttributeNameValueModel() + .setName("strKey") + .setValue("val") + .setType(AttributeTypeModel.STRING), + new AttributeNameValueModel() + .setName("longKey") + .setValue(1L) + .setType(AttributeTypeModel.INT), + new AttributeNameValueModel() + .setName("intKey") + .setValue(2) + .setType(AttributeTypeModel.INT), + new AttributeNameValueModel() + .setName("doubleKey") + .setValue(1.0d) + .setType(AttributeTypeModel.DOUBLE), + new AttributeNameValueModel() + .setName("floatKey") + .setValue(2.0f) + .setType(AttributeTypeModel.DOUBLE), + new AttributeNameValueModel() + .setName("boolKey") + .setValue(true) + .setType(AttributeTypeModel.BOOL), + new AttributeNameValueModel() + .setName("strArrKey") + .setValue(Arrays.asList("val1", "val2")) + .setType(AttributeTypeModel.STRING_ARRAY), + new AttributeNameValueModel() + .setName("longArrKey") + .setValue(Arrays.asList(1L, 2L)) + .setType(AttributeTypeModel.INT_ARRAY), + new AttributeNameValueModel() + .setName("intArrKey") + .setValue(Arrays.asList(1, 2)) + .setType(AttributeTypeModel.INT_ARRAY), + new AttributeNameValueModel() + .setName("doubleArrKey") + .setValue(Arrays.asList(1.0d, 2.0d)) + .setType(AttributeTypeModel.DOUBLE_ARRAY), + new AttributeNameValueModel() + .setName("floatArrKey") + .setValue(Arrays.asList(1.0f, 2.0f)) + .setType(AttributeTypeModel.DOUBLE_ARRAY), + new AttributeNameValueModel() + .setName("boolArrKey") + .setValue(Arrays.asList(true, false)) + .setType(AttributeTypeModel.BOOL_ARRAY)), + mock(DeclarativeConfigContext.class))) + .isEqualTo(expectedAttributes); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/CardinalityLimitsFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/CardinalityLimitsFactoryTest.java new file mode 100644 index 00000000000..3c0eef46b9f --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/CardinalityLimitsFactoryTest.java @@ -0,0 +1,81 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class CardinalityLimitsFactoryTest { + + @ParameterizedTest + @MethodSource("createTestCases") + void create(CardinalityLimitsModel model, CardinalityLimitSelector expectedResult) { + CardinalityLimitSelector cardinalityLimitSelector = + CardinalityLimitsFactory.getInstance().create(model, mock(DeclarativeConfigContext.class)); + + for (InstrumentType instrumentType : InstrumentType.values()) { + assertThat(cardinalityLimitSelector.getCardinalityLimit(instrumentType)) + .describedAs(instrumentType.toString()) + .isEqualTo(expectedResult.getCardinalityLimit(instrumentType)); + } + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "defaults", + new CardinalityLimitsModel(), + CardinalityLimitSelector.defaultCardinalityLimitSelector()), + Arguments.argumentSet( + "default and counter", + new CardinalityLimitsModel().setDefault(10).setCounter(1), + (CardinalityLimitSelector) + instrumentType -> { + if (instrumentType == InstrumentType.COUNTER) { + return 1; + } + return 10; + }), + Arguments.argumentSet( + "all instrument types", + new CardinalityLimitsModel() + .setCounter(1) + .setUpDownCounter(2) + .setHistogram(3) + .setObservableCounter(4) + .setObservableUpDownCounter(5) + .setObservableGauge(6) + .setGauge(7), + (CardinalityLimitSelector) + instrumentType -> { + switch (instrumentType) { + case COUNTER: + return 1; + case UP_DOWN_COUNTER: + return 2; + case HISTOGRAM: + return 3; + case OBSERVABLE_COUNTER: + return 4; + case OBSERVABLE_UP_DOWN_COUNTER: + return 5; + case OBSERVABLE_GAUGE: + return 6; + case GAUGE: + return 7; + } + return 2000; + })); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactoryTest.java new file mode 100644 index 00000000000..358492d4441 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ComposableRuleBasedSamplerFactoryTest.java @@ -0,0 +1,606 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.api.trace.SpanKind.CLIENT; +import static io.opentelemetry.api.trace.SpanKind.CONSUMER; +import static io.opentelemetry.api.trace.SpanKind.INTERNAL; +import static io.opentelemetry.api.trace.SpanKind.PRODUCER; +import static io.opentelemetry.api.trace.SpanKind.SERVER; +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.ComposableRuleBasedSamplerFactory.DeclarativeConfigSamplingPredicate.toSpanParent; +import static java.util.Collections.emptyList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.ComposableRuleBasedSamplerFactory.AttributeMatcher; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.ComposableRuleBasedSamplerFactory.DeclarativeConfigSamplingPredicate; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanKindModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableAlwaysOffSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableAlwaysOnSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableProbabilitySamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerRuleModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalSpanParentModel; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.ComposableSampler; +import io.opentelemetry.sdk.trace.IdGenerator; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ComposableRuleBasedSamplerFactoryTest { + + private final DeclarativeConfigContext context = + new DeclarativeConfigContext(ComponentLoader.forClassLoader(getClass().getClassLoader())); + + @ParameterizedTest + @MethodSource("createTestCases") + void create(ExperimentalComposableRuleBasedSamplerModel model, ComposableSampler expectedResult) { + ComposableSampler composableSampler = + ComposableRuleBasedSamplerFactory.getInstance().create(model, context); + assertThat(composableSampler.toString()).isEqualTo(expectedResult.toString()); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void createInvalid(ExperimentalComposableRuleBasedSamplerModel model, String expectedMessage) { + assertThatThrownBy(() -> ComposableRuleBasedSamplerFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + private static Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "attribute_patterns included empty", + new ExperimentalComposableRuleBasedSamplerModel() + .setRules( + Collections.singletonList( + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributePatterns( + new ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel() + .setKey("http.path") + .setIncluded(Collections.emptyList()) + .setExcluded(null)) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOn( + new ExperimentalComposableAlwaysOnSamplerModel())))), + "included must not be empty"), + Arguments.argumentSet( + "attribute_patterns excluded empty", + new ExperimentalComposableRuleBasedSamplerModel() + .setRules( + Collections.singletonList( + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributePatterns( + new ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel() + .setKey("http.path") + .setIncluded(null) + .setExcluded(Collections.emptyList())) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOn( + new ExperimentalComposableAlwaysOnSamplerModel())))), + "excluded must not be empty"), + Arguments.argumentSet( + "attribute_values null values", + new ExperimentalComposableRuleBasedSamplerModel() + .setRules( + Collections.singletonList( + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributeValues( + new ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel() + .setKey("http.route") + .setValues(null)) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOn( + new ExperimentalComposableAlwaysOnSamplerModel())))), + ".values is required and must be non-empty"), + Arguments.argumentSet( + "attribute_values empty values", + new ExperimentalComposableRuleBasedSamplerModel() + .setRules( + Collections.singletonList( + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributeValues( + new ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel() + .setKey("http.route") + .setValues(Collections.emptyList())) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOn( + new ExperimentalComposableAlwaysOnSamplerModel())))), + ".values is required and must be non-empty")); + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "empty model", + new ExperimentalComposableRuleBasedSamplerModel(), + ComposableSampler.ruleBasedBuilder().build()), + // https://github.com/open-telemetry/opentelemetry-java/issues/8337 + Arguments.argumentSet( + "attribute_patterns included only", + new ExperimentalComposableRuleBasedSamplerModel() + .setRules( + Collections.singletonList( + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributePatterns( + new ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel() + .setKey("http.path") + .setIncluded(Collections.singletonList("/internal/*"))) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOn( + new ExperimentalComposableAlwaysOnSamplerModel())))), + ComposableSampler.ruleBasedBuilder() + .add( + new DeclarativeConfigSamplingPredicate( + null, + new AttributeMatcher( + "http.path", + IncludeExcludePredicate.createPatternMatching( + Collections.singletonList("/internal/*"), null)), + null, + null), + ComposableSampler.alwaysOn()) + .build()), + Arguments.argumentSet( + "full example", + new ExperimentalComposableRuleBasedSamplerModel() + .setRules( + Arrays.asList( + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributeValues( + new ExperimentalComposableRuleBasedSamplerRuleAttributeValuesModel() + .setKey("http.route") + .setValues(Arrays.asList("/healthz", "/livez"))) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOff( + new ExperimentalComposableAlwaysOffSamplerModel())), + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setAttributePatterns( + new ExperimentalComposableRuleBasedSamplerRuleAttributePatternsModel() + .setKey("http.path") + .setIncluded(Collections.singletonList("/internal/*")) + .setExcluded(Collections.singletonList("/internal/special/*"))) + .setSampler( + new ExperimentalComposableSamplerModel() + .setAlwaysOn(new ExperimentalComposableAlwaysOnSamplerModel())), + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setParent(Collections.singletonList(ExperimentalSpanParentModel.NONE)) + .setSpanKinds(Collections.singletonList(SpanKindModel.CLIENT)) + .setSampler( + new ExperimentalComposableSamplerModel() + .setProbability( + new ExperimentalComposableProbabilitySamplerModel() + .setRatio(0.05))), + new ExperimentalComposableRuleBasedSamplerRuleModel() + .setSampler( + new ExperimentalComposableSamplerModel() + .setProbability( + new ExperimentalComposableProbabilitySamplerModel() + .setRatio(0.05))))), + ComposableSampler.ruleBasedBuilder() + .add( + new DeclarativeConfigSamplingPredicate( + new AttributeMatcher( + "http.route", + IncludeExcludePredicate.createExactMatching( + Arrays.asList("/healthz", "/livez"), null)), + null, + null, + null), + ComposableSampler.alwaysOff()) + .add( + new DeclarativeConfigSamplingPredicate( + null, + new AttributeMatcher( + "http.path", + IncludeExcludePredicate.createPatternMatching( + Collections.singletonList("/internal/*"), + Collections.singletonList("/internal/special/*"))), + null, + null), + ComposableSampler.alwaysOn()) + .add( + new DeclarativeConfigSamplingPredicate( + null, + null, + Collections.singleton(ExperimentalSpanParentModel.NONE), + Collections.singleton(CLIENT)), + ComposableSampler.probability(0.05)) + .add( + new DeclarativeConfigSamplingPredicate(null, null, null, null), + ComposableSampler.probability(0.05)) + .build())); + } + + private static final Context noParent = Context.current(); + private static final Context localParent = + Context.root() + .with( + Span.wrap( + SpanContext.create( + IdGenerator.random().generateTraceId(), + IdGenerator.random().generateSpanId(), + TraceFlags.getDefault(), + TraceState.getDefault()))); + private static final Context remoteParent = + Context.root() + .with( + Span.wrap( + SpanContext.createFromRemoteParent( + IdGenerator.random().generateTraceId(), + IdGenerator.random().generateSpanId(), + TraceFlags.getDefault(), + TraceState.getDefault()))); + private static final String sn = "name"; + private static final SpanKind sk = CLIENT; + private static final AttributeKey HTTP_ROUTE = AttributeKey.stringKey("http.route"); + private static final AttributeKey HTTP_PATH = AttributeKey.stringKey("http.path"); + private static final AttributeKey SERVER_PORT = AttributeKey.longKey("server.port"); + private static final AttributeKey> STRING_ARRAY = + AttributeKey.stringArrayKey("test.string_array"); + private static final AttributeKey> LONG_ARRAY = + AttributeKey.longArrayKey("test.long_array"); + + @ParameterizedTest + @MethodSource("declarativeConfigSamplingPredicateArgs") + void declarativeConfigSamplingPredicate( + DeclarativeConfigSamplingPredicate predicate, + Context context, + SpanKind spanKind, + Attributes attributes, + boolean expectedResult) { + assertThat(predicate.matches(context, sn, spanKind, attributes, emptyList())) + .isEqualTo(expectedResult); + } + + @SuppressWarnings("unused") + private static Stream declarativeConfigSamplingPredicateArgs() { + DeclarativeConfigSamplingPredicate matchAll = + new DeclarativeConfigSamplingPredicate(null, null, null, null); + DeclarativeConfigSamplingPredicate valuesMatcher = + new DeclarativeConfigSamplingPredicate( + new AttributeMatcher( + "http.route", + IncludeExcludePredicate.createExactMatching( + Arrays.asList("/healthz", "/livez"), null)), + null, + null, + null); + DeclarativeConfigSamplingPredicate patternsMatcher = + new DeclarativeConfigSamplingPredicate( + null, + new AttributeMatcher( + "http.path", + IncludeExcludePredicate.createPatternMatching( + Collections.singletonList("/internal/*"), + Collections.singletonList("/internal/special/*"))), + null, + null); + DeclarativeConfigSamplingPredicate parentMatcher = + new DeclarativeConfigSamplingPredicate( + null, null, Collections.singleton(ExperimentalSpanParentModel.NONE), null); + DeclarativeConfigSamplingPredicate spanKindMatcher = + new DeclarativeConfigSamplingPredicate(null, null, null, Collections.singleton(CLIENT)); + DeclarativeConfigSamplingPredicate numberValuesMatcher = + new DeclarativeConfigSamplingPredicate( + new AttributeMatcher( + "server.port", + IncludeExcludePredicate.createExactMatching( + Collections.singletonList("8081"), null)), + null, + null, + null); + DeclarativeConfigSamplingPredicate numberPatternsMatcher = + new DeclarativeConfigSamplingPredicate( + null, + new AttributeMatcher( + "server.port", + IncludeExcludePredicate.createPatternMatching( + Collections.singletonList("808*"), null)), + null, + null); + DeclarativeConfigSamplingPredicate multiMatcher = + new DeclarativeConfigSamplingPredicate( + new AttributeMatcher( + "http.route", + IncludeExcludePredicate.createExactMatching( + Arrays.asList("/healthz", "/livez"), null)), + new AttributeMatcher( + "http.path", + IncludeExcludePredicate.createPatternMatching( + Collections.singletonList("/internal/*"), + Collections.singletonList("/internal/special/*"))), + Collections.singleton(ExperimentalSpanParentModel.NONE), + Collections.singleton(CLIENT)); + DeclarativeConfigSamplingPredicate arrayValuesMatcher = + new DeclarativeConfigSamplingPredicate( + new AttributeMatcher( + "test.string_array", + IncludeExcludePredicate.createExactMatching( + Arrays.asList("/healthz", "/livez"), null)), + null, + null, + null); + DeclarativeConfigSamplingPredicate arrayPatternsMatcher = + new DeclarativeConfigSamplingPredicate( + null, + new AttributeMatcher( + "test.string_array", + IncludeExcludePredicate.createPatternMatching( + Collections.singletonList("/internal/*"), + Collections.singletonList("/internal/special/*"))), + null, + null); + DeclarativeConfigSamplingPredicate arrayNumberValuesMatcher = + new DeclarativeConfigSamplingPredicate( + new AttributeMatcher( + "test.long_array", + IncludeExcludePredicate.createExactMatching( + Collections.singletonList("8081"), null)), + null, + null, + null); + + return Stream.of( + Arguments.argumentSet( + "matchAll no parent empty", matchAll, noParent, sk, Attributes.empty(), true), + Arguments.argumentSet( + "matchAll no parent route", + matchAll, + noParent, + sk, + Attributes.of(HTTP_ROUTE, "/healthz"), + true), + Arguments.argumentSet( + "matchAll no parent path", + matchAll, + noParent, + sk, + Attributes.of(HTTP_PATH, "/internal/admin/users"), + true), + Arguments.argumentSet( + "matchAll no parent server kind", matchAll, noParent, SERVER, Attributes.empty(), true), + Arguments.argumentSet( + "matchAll remote parent", matchAll, remoteParent, sk, Attributes.empty(), true), + Arguments.argumentSet( + "valuesMatcher healthz", + valuesMatcher, + noParent, + sk, + Attributes.of(HTTP_ROUTE, "/healthz"), + true), + Arguments.argumentSet( + "valuesMatcher livez", + valuesMatcher, + noParent, + sk, + Attributes.of(HTTP_ROUTE, "/livez"), + true), + Arguments.argumentSet( + "valuesMatcher foo no match", + valuesMatcher, + noParent, + sk, + Attributes.of(HTTP_ROUTE, "/foo"), + false), + Arguments.argumentSet( + "valuesMatcher empty no match", valuesMatcher, noParent, sk, Attributes.empty(), false), + Arguments.argumentSet( + "patternsMatcher internal admin", + patternsMatcher, + noParent, + sk, + Attributes.of(HTTP_PATH, "/internal/admin/users"), + true), + Arguments.argumentSet( + "patternsMatcher internal management", + patternsMatcher, + noParent, + sk, + Attributes.of(HTTP_PATH, "/internal/management/config"), + true), + Arguments.argumentSet( + "patternsMatcher users no match", + patternsMatcher, + noParent, + sk, + Attributes.of(HTTP_PATH, "/users/profile/123"), + false), + Arguments.argumentSet( + "patternsMatcher internal special excluded", + patternsMatcher, + noParent, + sk, + Attributes.of(HTTP_PATH, "/internal/special/foo"), + false), + Arguments.argumentSet( + "parentMatcher no parent", parentMatcher, noParent, sk, Attributes.empty(), true), + Arguments.argumentSet( + "parentMatcher local parent no match", + parentMatcher, + localParent, + sk, + Attributes.empty(), + false), + Arguments.argumentSet( + "parentMatcher remote parent no match", + parentMatcher, + remoteParent, + sk, + Attributes.empty(), + false), + Arguments.argumentSet( + "spanKindMatcher CLIENT", spanKindMatcher, noParent, CLIENT, Attributes.empty(), true), + Arguments.argumentSet( + "spanKindMatcher SERVER no match", + spanKindMatcher, + noParent, + SERVER, + Attributes.empty(), + false), + Arguments.argumentSet( + "spanKindMatcher INTERNAL no match", + spanKindMatcher, + noParent, + INTERNAL, + Attributes.empty(), + false), + Arguments.argumentSet( + "spanKindMatcher PRODUCER no match", + spanKindMatcher, + noParent, + PRODUCER, + Attributes.empty(), + false), + Arguments.argumentSet( + "spanKindMatcher CONSUMER no match", + spanKindMatcher, + noParent, + CONSUMER, + Attributes.empty(), + false), + Arguments.argumentSet( + "numberValuesMatcher matching port", + numberValuesMatcher, + noParent, + sk, + Attributes.of(SERVER_PORT, 8081L), + true), + Arguments.argumentSet( + "numberValuesMatcher non matching port", + numberValuesMatcher, + noParent, + sk, + Attributes.of(SERVER_PORT, 8080L), + false), + Arguments.argumentSet( + "numberValuesMatcher empty no match", + numberValuesMatcher, + noParent, + sk, + Attributes.empty(), + false), + Arguments.argumentSet( + "numberPatternsMatcher matching port", + numberPatternsMatcher, + noParent, + sk, + Attributes.of(SERVER_PORT, 8081L), + true), + Arguments.argumentSet( + "numberPatternsMatcher non matching port", + numberPatternsMatcher, + noParent, + sk, + Attributes.of(SERVER_PORT, 9090L), + false), + Arguments.argumentSet( + "arrayValuesMatcher with matching element", + arrayValuesMatcher, + noParent, + sk, + Attributes.of(STRING_ARRAY, Arrays.asList("/foo", "/healthz")), + true), + Arguments.argumentSet( + "arrayValuesMatcher without matching element", + arrayValuesMatcher, + noParent, + sk, + Attributes.of(STRING_ARRAY, Arrays.asList("/foo", "/bar")), + false), + Arguments.argumentSet( + "arrayPatternsMatcher with matching element", + arrayPatternsMatcher, + noParent, + sk, + Attributes.of(STRING_ARRAY, Arrays.asList("/users/profile", "/internal/admin")), + true), + Arguments.argumentSet( + "arrayPatternsMatcher excluded element no match", + arrayPatternsMatcher, + noParent, + sk, + Attributes.of(STRING_ARRAY, Arrays.asList("/users/profile", "/internal/special/foo")), + false), + Arguments.argumentSet( + "arrayNumberValuesMatcher with matching element", + arrayNumberValuesMatcher, + noParent, + sk, + Attributes.of(LONG_ARRAY, Arrays.asList(8080L, 8081L)), + true), + Arguments.argumentSet( + "multiMatcher all conditions match", + multiMatcher, + noParent, + CLIENT, + Attributes.of(HTTP_ROUTE, "/livez", HTTP_PATH, "/internal/admin/users"), + true), + Arguments.argumentSet( + "multiMatcher missing path no match", + multiMatcher, + noParent, + CLIENT, + Attributes.of(HTTP_ROUTE, "/livez"), + false), + Arguments.argumentSet( + "multiMatcher missing route no match", + multiMatcher, + noParent, + CLIENT, + Attributes.of(HTTP_PATH, "/internal/admin/users"), + false), + Arguments.argumentSet( + "multiMatcher wrong kind no match", + multiMatcher, + noParent, + SERVER, + Attributes.of(HTTP_ROUTE, "/livez", HTTP_PATH, "/internal/admin/users"), + false), + Arguments.argumentSet( + "multiMatcher local parent no match", + multiMatcher, + localParent, + CLIENT, + Attributes.of(HTTP_ROUTE, "/livez", HTTP_PATH, "/internal/admin/users"), + false)); + } + + @Test + void toSpanParent_Valid() { + assertThat(toSpanParent(SpanContext.getInvalid())).isEqualTo(ExperimentalSpanParentModel.NONE); + assertThat(toSpanParent(Span.fromContext(localParent).getSpanContext())) + .isEqualTo(ExperimentalSpanParentModel.LOCAL); + assertThat(toSpanParent(Span.fromContext(remoteParent).getSpanContext())) + .isEqualTo(ExperimentalSpanParentModel.REMOTE); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java new file mode 100644 index 00000000000..e2a8fe47f1b --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigContextTest.java @@ -0,0 +1,391 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class DeclarativeConfigContextTest { + + private final ComponentLoader componentLoader = + spy(ComponentLoader.forClassLoader(getClass().getClassLoader())); + private final DeclarativeConfigContext context = new DeclarativeConfigContext(componentLoader); + + @Test + @SuppressWarnings("deprecation") + void componentProvidersCached() { + // First loadComponent call should load providers + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "nonexistent", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("No component provider detected"); + + // Second loadComponent call should use cached providers, not reload + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "another", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("No component provider detected"); + + // Verify spiHelper.load() was only called once + verify(componentLoader, times(1)).load(ComponentProvider.class); + verify(componentLoader, times(1)) + .load(io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider.class); + } + + @Test + void componentConfigForwardsTypeIntrospection() { + AtomicReference received = new AtomicReference<>(); + ComponentProvider provider = + new ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public Object create(DeclarativeConfigProperties config) { + received.set(config); + return Resource.empty(); + } + }; + doReturn(Collections.singletonList(provider)) + .when(componentLoader) + .load(ComponentProvider.class); + + Map properties = new HashMap<>(); + properties.put("str_key", "value"); + properties.put("bool_key", true); + properties.put("int_key", 1); + properties.put("double_key", 1.5); + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "test", YamlDeclarativeConfigProperties.create(properties, componentLoader))); + + DeclarativeConfigProperties config = received.get(); + assertThat(config).isNotNull(); + assertThat(config.isString("str_key")).isTrue(); + assertThat(config.isBoolean("bool_key")).isTrue(); + assertThat(config.isInt("int_key")).isTrue(); + assertThat(config.isLong("int_key")).isTrue(); + assertThat(config.isDouble("double_key")).isTrue(); + assertThat(config.isString("int_key")).isFalse(); + } + + @Test + @SuppressWarnings("deprecation") + void legacyComponentProviderLoaded() { + Resource expectedResource = Resource.builder().put("source", "legacy").build(); + io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider legacyProvider = + new io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "legacy-test"; + } + + @Override + public Object create( + io.opentelemetry.api.incubator.config.DeclarativeConfigProperties config) { + assertThat(config).isInstanceOf(LegacyYamlDeclarativeConfigProperties.class); + return expectedResource; + } + }; + + doReturn(Collections.singletonList(legacyProvider)) + .when(componentLoader) + .load(io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider.class); + + Resource resource = + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "legacy-test", + YamlDeclarativeConfigProperties.create(Collections.emptyMap(), componentLoader))); + + assertThat(resource).isSameAs(expectedResource); + } + + @Test + @SuppressWarnings("deprecation") + void legacyComponentProviderConflictWhenModernProviderExists() { + Resource modernResource = Resource.builder().put("source", "modern").build(); + Resource legacyResource = Resource.builder().put("source", "legacy").build(); + + ComponentProvider modernProvider = + new ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "duplicate-test"; + } + + @Override + public Object create(DeclarativeConfigProperties config) { + return modernResource; + } + }; + + io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider legacyProvider = + new io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "duplicate-test"; + } + + @Override + public Object create( + io.opentelemetry.api.incubator.config.DeclarativeConfigProperties config) { + return legacyResource; + } + }; + + doReturn(Collections.singletonList(modernProvider)) + .when(componentLoader) + .load(ComponentProvider.class); + doReturn(Collections.singletonList(legacyProvider)) + .when(componentLoader) + .load(io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider.class); + + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "duplicate-test", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("Component provider conflict. Multiple providers detected for"); + } + + @Test + @SuppressWarnings("deprecation") + void legacyComponentProviderConflictWhenMultipleLegacyProvidersExist() { + Resource legacyResource1 = Resource.builder().put("source", "legacy1").build(); + Resource legacyResource2 = Resource.builder().put("source", "legacy2").build(); + + io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider legacyProvider1 = + new io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "duplicate-legacy"; + } + + @Override + public Object create( + io.opentelemetry.api.incubator.config.DeclarativeConfigProperties config) { + return legacyResource1; + } + }; + + io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider legacyProvider2 = + new io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "duplicate-legacy"; + } + + @Override + public Object create( + io.opentelemetry.api.incubator.config.DeclarativeConfigProperties config) { + return legacyResource2; + } + }; + + doReturn(Arrays.asList(legacyProvider1, legacyProvider2)) + .when(componentLoader) + .load(io.opentelemetry.sdk.autoconfigure.spi.internal.ComponentProvider.class); + + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "duplicate-legacy", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("Component provider conflict. Multiple providers detected for"); + } + + @Test + void componentProviderUnexpectedComponentType() { + ComponentProvider provider = + new ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "bad-type"; + } + + @Override + public Object create(DeclarativeConfigProperties config) { + return "not-a-resource"; + } + }; + + doReturn(Collections.singletonList(provider)) + .when(componentLoader) + .load(ComponentProvider.class); + + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "bad-type", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageStartingWith( + "Error configuring io.opentelemetry.sdk.resources.Resource with name \"bad-type\"") + .hasCauseInstanceOf(DeclarativeConfigException.class) + .hasRootCauseMessage( + "Error configuring io.opentelemetry.sdk.resources.Resource with name \"bad-type\". Component provider " + + provider.getClass().getName() + + " returned an unexpected component type: java.lang.String"); + } + + @Test + void componentProviderThrowsExceptionWrapped() { + ComponentProvider provider = + new ComponentProvider() { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "throws-error"; + } + + @Override + public Object create(DeclarativeConfigProperties config) { + throw new IllegalStateException("initialization failure"); + } + }; + + doReturn(Collections.singletonList(provider)) + .when(componentLoader) + .load(ComponentProvider.class); + + assertThatThrownBy(() -> + context.loadComponent( + Resource.class, + ConfigKeyValue.of( + "throws-error", + YamlDeclarativeConfigProperties.create( + Collections.emptyMap(), componentLoader)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageStartingWith( + "Error configuring io.opentelemetry.sdk.resources.Resource with name \"throws-error\"") + .hasCauseInstanceOf(IllegalStateException.class); + } + + @Test + void setInternalTelemetry_nullWhenConfigProviderNull() { + AtomicReference meterProviderRef = new AtomicReference<>(); + AtomicReference versionRef = new AtomicReference<>(); + + context.setInternalTelemetry(supplier -> meterProviderRef.set(supplier.get()), versionRef::set); + + assertThat(meterProviderRef.get()).isSameAs(MeterProvider.noop()); + assertThat(versionRef.get()).isNull(); + } + + @Test + void setInternalTelemetry_legacy() { + ConfigProvider configProvider = mock(ConfigProvider.class); + DeclarativeConfigProperties otelSdkProps = mock(DeclarativeConfigProperties.class); + when(configProvider.getInstrumentationConfig("otel_sdk")).thenReturn(otelSdkProps); + when(otelSdkProps.getString("internal_telemetry_version")).thenReturn("legacy"); + + DeclarativeConfigContext ctx = new DeclarativeConfigContext(componentLoader); + ctx.setConfigProvider(configProvider); + + AtomicReference versionRef = new AtomicReference<>(); + ctx.setInternalTelemetry(supplier -> {}, versionRef::set); + + assertThat(versionRef.get()).isEqualTo(InternalTelemetryVersion.LEGACY); + } + + @Test + void setInternalTelemetry_invalid() { + ConfigProvider configProvider = mock(ConfigProvider.class); + DeclarativeConfigProperties otelSdkProps = mock(DeclarativeConfigProperties.class); + when(configProvider.getInstrumentationConfig("otel_sdk")).thenReturn(otelSdkProps); + when(otelSdkProps.getString("internal_telemetry_version")).thenReturn("invalid_ver"); + + DeclarativeConfigContext ctx = new DeclarativeConfigContext(componentLoader); + ctx.setConfigProvider(configProvider); + + assertThatThrownBy(() -> ctx.setInternalTelemetry(supplier -> {}, version -> {})) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("Invalid sdk telemetry version: invalid_ver"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationBuilderTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationBuilderTest.java new file mode 100644 index 00000000000..01c212cd046 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationBuilderTest.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import org.junit.jupiter.api.Test; + +class DeclarativeConfigurationBuilderTest { + + @Test + void spanExporterCustomizer_Single() { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + + builder.addSpanExporterCustomizer( + SpanExporter.class, (exporter, properties) -> mock(SpanExporter.class)); + + assertThat(builder.getSpanExporterCustomizers()).hasSize(1); + } + + @Test + void spanExporterCustomizer_Multiple_Compose() { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + + builder.addSpanExporterCustomizer( + SpanExporter.class, (exporter, properties) -> mock(SpanExporter.class)); + builder.addSpanExporterCustomizer( + SpanExporter.class, (exporter, properties) -> mock(SpanExporter.class)); + + assertThat(builder.getSpanExporterCustomizers()).hasSize(2); + } + + @Test + void metricExporterCustomizer_Single() { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + + builder.addMetricExporterCustomizer( + MetricExporter.class, (exporter, properties) -> mock(MetricExporter.class)); + + assertThat(builder.getMetricExporterCustomizers()).hasSize(1); + } + + @Test + void metricExporterCustomizer_Multiple_Compose() { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + + builder.addMetricExporterCustomizer( + MetricExporter.class, (exporter, properties) -> mock(MetricExporter.class)); + builder.addMetricExporterCustomizer( + MetricExporter.class, (exporter, properties) -> mock(MetricExporter.class)); + + assertThat(builder.getMetricExporterCustomizers()).hasSize(2); + } + + @Test + void logRecordExporterCustomizer_Single() { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + + builder.addLogRecordExporterCustomizer( + LogRecordExporter.class, (exporter, properties) -> mock(LogRecordExporter.class)); + + assertThat(builder.getLogRecordExporterCustomizers()).hasSize(1); + } + + @Test + void logRecordExporterCustomizer_Multiple_Compose() { + DeclarativeConfigurationBuilder builder = new DeclarativeConfigurationBuilder(); + + builder.addLogRecordExporterCustomizer( + LogRecordExporter.class, (exporter, properties) -> mock(LogRecordExporter.class)); + builder.addLogRecordExporterCustomizer( + LogRecordExporter.class, (exporter, properties) -> mock(LogRecordExporter.class)); + + assertThat(builder.getLogRecordExporterCustomizers()).hasSize(2); + } + + @Test + void customizer_ClosesOriginalWhenReplaced() throws Exception { + SpanExporter original = mock(SpanExporter.class); + SpanExporter replacement = mock(SpanExporter.class); + DeclarativeConfigProperties props = mock(DeclarativeConfigProperties.class); + + DeclarativeConfigurationBuilder.Customizer customizer = + new DeclarativeConfigurationBuilder.Customizer<>( + SpanExporter.class, (exporter, properties) -> replacement); + + SpanExporter result = customizer.maybeCustomize(original, "test", props); + + assertThat(result).isSameAs(replacement); + verify(original).close(); + } + + @Test + void customizer_DoesNotCloseWhenSameInstance() throws Exception { + SpanExporter exporter = mock(SpanExporter.class); + DeclarativeConfigProperties props = mock(DeclarativeConfigProperties.class); + + DeclarativeConfigurationBuilder.Customizer customizer = + new DeclarativeConfigurationBuilder.Customizer<>(SpanExporter.class, (e, properties) -> e); + + SpanExporter result = customizer.maybeCustomize(exporter, "test", props); + + assertThat(result).isSameAs(exporter); + verify(exporter, never()).close(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java new file mode 100644 index 00000000000..089ce2132dd --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationCreateTest.java @@ -0,0 +1,215 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigTestUtil.createTempFileWithContent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.trace.samplers.ParentBasedSamplerBuilder; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.event.Level; + +class DeclarativeConfigurationCreateTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + @RegisterExtension + LogCapturer logCapturer = + LogCapturer.create().captureForLogger(DeclarativeConfiguration.class.getName(), Level.TRACE); + + /** + * Verify each example in open-telemetry/opentelemetry-configuration/examples + * can pass {@link DeclarativeConfiguration#parseAndCreate(InputStream)}. + */ + @ParameterizedTest + @MethodSource("exampleFiles") + @SuppressLogger(ParentBasedSamplerBuilder.class) + @SuppressLogger(ResourceBuilder.class) + void parseAndCreate_Examples(File example, @TempDir Path tempDir) + throws IOException, CertificateEncodingException { + // Write certificates to temp files + String certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + String clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + String clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + + // Rewrite references to cert files in examples + String exampleContent = + new String(Files.readAllBytes(example.toPath()), StandardCharsets.UTF_8); + String rewrittenExampleContent = + exampleContent + .replaceAll( + "ca_file: .*\n", + "ca_file: " + certificatePath.replace("\\", "\\\\") + System.lineSeparator()) + .replaceAll( + "key_file: .*\n", + "key_file: " + clientKeyPath.replace("\\", "\\\\") + System.lineSeparator()) + .replaceAll( + "cert_file: .*\n", + "cert_file: " + + clientCertificatePath.replace("\\", "\\\\") + + System.lineSeparator()) + // Snippets write to file:///var/log/*.jsonl, which is not writable in tests. The + // value can be the last line of the file, so the line terminator is not matched. + .replaceAll( + "output_stream: file:.*", + "output_stream: " + tempDir.resolve("output.jsonl").toUri()) + // A snippet references a custom id generator named my_custom_id_generator. Replace with + // one named test, which we provide via SPI + .replace("my_custom_id_generator", "test"); + InputStream is = + new ByteArrayInputStream(rewrittenExampleContent.getBytes(StandardCharsets.UTF_8)); + + // Verify that file can be parsed and interpreted without error + assertThatCode(() -> cleanup.addCloseable(DeclarativeConfiguration.parseAndCreate(is).getSdk())) + .as("Example file: " + example.getName()) + .doesNotThrowAnyException(); + } + + private static Stream exampleFiles() { + File configRepoRoot = new File(System.getenv("CONFIG_REPO_ROOT")); + File examplesDir = new File(configRepoRoot + "/examples/"); + File snippetsDir = new File(configRepoRoot + "/snippets/"); + List examples = new ArrayList<>(); + examples.addAll(Arrays.asList(Objects.requireNonNull(examplesDir.listFiles()))); + examples.addAll(Arrays.asList(Objects.requireNonNull(snippetsDir.listFiles()))); + + return examples.stream().map(file -> Arguments.argumentSet(file.getName(), file)); + } + + @Test + void parseAndCreate_Exception_CleansUpPartials() { + // Trigger an exception after some components have been configured by adding a valid batch + // exporter with OTLP exporter, following by invalid batch exporter which references invalid + // exporter "foo". + String yaml = + "file_format: \"1.2\"\n" + + "logger_provider:\n" + + " processors:\n" + + " - batch:\n" + + " exporter:\n" + + " otlp_http: {}\n" + + " - batch:\n" + + " exporter:\n" + + " foo: {}\n"; + + assertThatThrownBy(() -> + DeclarativeConfiguration.parseAndCreate( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage( + "No component provider detected for io.opentelemetry.sdk.logs.export.LogRecordExporter with name \"foo\"."); + logCapturer.assertContains( + "Error encountered interpreting model. Closing partially configured components."); + logCapturer.assertContains( + "Closing io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter"); + logCapturer.assertContains("Closing io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor"); + } + + @Test + void parseAndCreate_EmptyComponentProviderConfig() { + String yaml = + "file_format: \"1.2\"\n" + + "logger_provider:\n" + + " processors:\n" + + " - test:\n" + + "tracer_provider:\n" + + " processors:\n" + + " - test:\n"; + + assertThatCode(() -> + DeclarativeConfiguration.parseAndCreate( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)))) + .doesNotThrowAnyException(); + } + + @Test + void create_ModelCustomizer() { + OpenTelemetryConfigurationModel model = new OpenTelemetryConfigurationModel(); + model.setFileFormat("1.2"); + model.setTracerProvider( + new TracerProviderModel() + .setProcessors( + Collections.singletonList( + new SpanProcessorModel().setExtensionProperty("test", null)))); + ExtendedOpenTelemetrySdk sdk = + DeclarativeConfiguration.create( + model, + // customizer is TestDeclarativeConfigurationCustomizerProvider + ComponentLoader.forClassLoader( + DeclarativeConfigurationCreateTest.class.getClassLoader())) + .getSdk(); + String sdkStr = sdk.toString(); + assertThat(sdkStr).contains("color=\"blue\""); + assertThat(sdkStr).contains("foo=\"bar\""); + assertThat(sdkStr).contains("service.name=\"unknown_service:java\""); + assertThat(sdkStr).contains("telemetry.sdk.language=\"java\""); + assertThat(sdkStr).contains("telemetry.sdk.name=\"opentelemetry\""); + assertThat(sdkStr).contains("telemetry.sdk.version=\""); + } + + @Test + @SuppressLogger(DeclarativeConfiguration.class) + void callAutoConfigureListeners_exceptionIsCaught() { + DeclarativeConfigContext context = mock(DeclarativeConfigContext.class); + when(context.getListeners()) + .thenReturn( + Collections.singleton(sdk -> { + throw new RuntimeException("Test exception from AutoConfigureListener"); + })); + + assertThatCode(() -> + DeclarativeConfiguration.callAutoConfigureListeners( + context, OpenTelemetrySdk.builder().build())) + .doesNotThrowAnyException(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java new file mode 100644 index 00000000000..1e78c2d466e --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/DeclarativeConfigurationParseTest.java @@ -0,0 +1,579 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TraceIdRatioBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.AbstractMap; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class DeclarativeConfigurationParseTest { + + @Test + void parse_BadInputStream() { + assertThatThrownBy(() -> + DeclarativeConfiguration.parseAndCreate( + new ByteArrayInputStream("foo".getBytes(StandardCharsets.UTF_8)))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage("Unable to parse configuration input stream"); + } + + @Test + void parse_nullValuesParsedToEmptyObjects() { + String objectPlaceholderString = + "file_format: \"1.2\"\n" + + "tracer_provider:\n" + + " processors:\n" + + " - batch:\n" + + " exporter:\n" + + " console: {}\n" + + "meter_provider:\n" + + " views:\n" + + " - selector:\n" + + " instrument_type: histogram\n" + + " stream:\n" + + " aggregation:\n" + + " drop: {}\n"; + OpenTelemetryConfigurationModel objectPlaceholderModel = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(objectPlaceholderString.getBytes(StandardCharsets.UTF_8))); + + String noOjbectPlaceholderString = + "file_format: \"1.2\"\n" + + "tracer_provider:\n" + + " processors:\n" + + " - batch:\n" + + " exporter:\n" + + " console:\n" + + "meter_provider:\n" + + " views:\n" + + " - selector:\n" + + " instrument_type: histogram\n" + + " stream:\n" + + " aggregation:\n" + + " drop:\n"; + OpenTelemetryConfigurationModel noObjectPlaceholderModel = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(noOjbectPlaceholderString.getBytes(StandardCharsets.UTF_8))); + + SpanExporterModel exporter = + noObjectPlaceholderModel + .getTracerProvider() + .getProcessors() + .get(0) + .getBatch() + .getExporter(); + assertThat(exporter.getConsole()).isNotNull(); + assertThat(exporter.getOtlpHttp()).isNull(); + + AggregationModel aggregation = + noObjectPlaceholderModel.getMeterProvider().getViews().get(0).getStream().getAggregation(); + assertThat(aggregation.getDrop()).isNotNull(); + assertThat(aggregation.getSum()).isNull(); + + assertThat(objectPlaceholderModel).isEqualTo(noObjectPlaceholderModel); + } + + @Test + void parse_nullBoxedPrimitivesParsedToNull() { + String yaml = + "file_format:\n" // String + + "disabled:\n" // Boolean + + "attribute_limits:\n" + + " attribute_value_length_limit:\n" // Integer + + "tracer_provider:\n" + + " sampler:\n" + + " trace_id_ratio_based:\n" + + " ratio:\n"; // Double + + OpenTelemetryConfigurationModel model = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))); + + assertThat(model.getFileFormat()).isNull(); + assertThat(model.getDisabled()).isNull(); + assertThat(model.getAttributeLimits().getAttributeValueLengthLimit()).isNull(); + assertThat(model.getTracerProvider().getSampler().getTraceIdRatioBased().getRatio()).isNull(); + + assertThat(model) + .isEqualTo( + new OpenTelemetryConfigurationModel() + .setAttributeLimits(new AttributeLimitsModel()) + .setTracerProvider( + new TracerProviderModel() + .setSampler( + new SamplerModel() + .setTraceIdRatioBased(new TraceIdRatioBasedSamplerModel())))); + } + + @Test + void parse_quotedInput() { + String yaml = + "resource:\n" + + " attributes:\n" + + " - name: single_quote\n" + + " value: '\"single\"'\n" + + " - name: double_quote\n" + + " value: \"\\\"double\\\"\""; + + OpenTelemetryConfigurationModel model = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8))); + + Assertions.assertNotNull(model.getResource()); + assertThat(model.getResource().getAttributes()) + .containsExactly( + new AttributeNameValueModel().setName("single_quote").setValue("\"single\""), + new AttributeNameValueModel().setName("double_quote").setValue("\"double\"")); + } + + @ParameterizedTest + @MethodSource("coreSchemaValuesArgs") + void coreSchemaValues(String rawYaml, Object expectedYamlResult) { + Object yaml = + DeclarativeConfiguration.loadYaml( + new ByteArrayInputStream(rawYaml.getBytes(StandardCharsets.UTF_8)), + Collections.emptyMap(), + Collections.emptyMap()); + assertThat(yaml).isEqualTo(expectedYamlResult); + } + + @SuppressWarnings("unchecked") + private static Stream coreSchemaValuesArgs() { + return Stream.of( + Arguments.argumentSet("octal with o", "key1: 0o123\n", mapOf(entry("key1", 83))), + Arguments.argumentSet("octal without o", "key1: 0123\n", mapOf(entry("key1", 123))), + Arguments.argumentSet( + "unquoted hex string", "key1: 0xdeadbeef\n", mapOf(entry("key1", 3735928559L))), + Arguments.argumentSet( + "quoted hex string", "key1: \"0xdeadbeef\"\n", mapOf(entry("key1", "0xdeadbeef")))); + } + + @ParameterizedTest + @MethodSource("envVarSubstitutionArgs") + void envSubstituteAndLoadYaml(String rawYaml, Object expectedYamlResult) { + Map environmentVariables = new HashMap<>(); + environmentVariables.put("FOO", "BAR"); + environmentVariables.put("STR_1", "value1"); + environmentVariables.put("STR_2", "value2"); + environmentVariables.put("VALUE_WITH_ESCAPE", "value$$"); + environmentVariables.put("EMPTY_STR", ""); + environmentVariables.put("BOOL", "true"); + environmentVariables.put("INT", "1"); + environmentVariables.put("FLOAT", "1.1"); + environmentVariables.put("HEX", "0xdeadbeef"); + + Object yaml = + DeclarativeConfiguration.loadYaml( + new ByteArrayInputStream(rawYaml.getBytes(StandardCharsets.UTF_8)), + environmentVariables, + Collections.emptyMap()); + assertThat(yaml).isEqualTo(expectedYamlResult); + } + + @SuppressWarnings("unchecked") + private static Stream envVarSubstitutionArgs() { + return Stream.of( + Arguments.argumentSet("STR_1 string", "key1: ${STR_1}\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet("BOOL boolean", "key1: ${BOOL}\n", mapOf(entry("key1", true))), + Arguments.argumentSet("INT integer", "key1: ${INT}\n", mapOf(entry("key1", 1))), + Arguments.argumentSet("FLOAT float", "key1: ${FLOAT}\n", mapOf(entry("key1", 1.1))), + Arguments.argumentSet("HEX hex", "key1: ${HEX}\n", mapOf(entry("key1", 3735928559L))), + Arguments.argumentSet( + "STR_1 with literal key2", + "key1: ${STR_1}\n" + "key2: value2\n", + mapOf(entry("key1", "value1"), entry("key2", "value2"))), + Arguments.argumentSet( + "STR_1 concatenated with literal", + "key1: ${STR_1} value1\n" + "key2: value2\n", + mapOf(entry("key1", "value1 value1"), entry("key2", "value2"))), + Arguments.argumentSet( + "default string", "key1: ${NOT_SET:-value1}\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet( + "default boolean", "key1: ${NOT_SET:-true}\n", mapOf(entry("key1", true))), + Arguments.argumentSet("default integer", "key1: ${NOT_SET:-1}\n", mapOf(entry("key1", 1))), + Arguments.argumentSet( + "default float", "key1: ${NOT_SET:-1.1}\n", mapOf(entry("key1", 1.1))), + Arguments.argumentSet( + "default hex", "key1: ${NOT_SET:-0xdeadbeef}\n", mapOf(entry("key1", 3735928559L))), + Arguments.argumentSet( + "default concatenated with literal", + "key1: ${NOT_SET:-value1} value2\n" + "key2: value2\n", + mapOf(entry("key1", "value1 value2"), entry("key2", "value2"))), + Arguments.argumentSet( + "two vars concatenated", + "key1: ${STR_1}${STR_2}\n", + mapOf(entry("key1", "value1value2"))), + Arguments.argumentSet( + "two vars with space", + "key1: ${STR_1} ${STR_2}\n", + mapOf(entry("key1", "value1 value2"))), + Arguments.argumentSet( + "two vars with default", + "key1: ${STR_1} ${NOT_SET:-default} ${STR_2}\n", + mapOf(entry("key1", "value1 default value2"))), + Arguments.argumentSet("empty var null", "key1: ${EMPTY_STR}\n", mapOf(entry("key1", null))), + Arguments.argumentSet("undefined var null", "key1: ${STR_3}\n", mapOf(entry("key1", null))), + Arguments.argumentSet( + "set and undefined vars", "key1: ${STR_1} ${STR_3}\n", mapOf(entry("key1", "value1 "))), + // Environment variable keys must match pattern: [a-zA-Z_]+[a-zA-Z0-9_]* + Arguments.argumentSet( + "invalid var syntax literal", "key1: ${VAR&}\n", mapOf(entry("key1", "${VAR&}"))), + // Environment variable substitution only takes place in scalar values of maps + Arguments.argumentSet( + "var in map key not substituted", + "${STR_1}: value1\n", + mapOf(entry("${STR_1}", "value1"))), + Arguments.argumentSet( + "var in nested map key not substituted", + "key1:\n ${STR_1}: value1\n", + mapOf(entry("key1", mapOf(entry("${STR_1}", "value1"))))), + Arguments.argumentSet( + "var in list not substituted", + "key1:\n - ${STR_1}\n", + mapOf(entry("key1", Collections.singletonList("${STR_1}")))), + Arguments.argumentSet( + "double-quoted hex string", "key1: \"${HEX}\"\n", mapOf(entry("key1", "0xdeadbeef"))), + Arguments.argumentSet( + "double-quoted string", "key1: \"${STR_1}\"\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet( + "double-quoted empty string", "key1: \"${EMPTY_STR}\"\n", mapOf(entry("key1", ""))), + Arguments.argumentSet( + "double-quoted boolean string", "key1: \"${BOOL}\"\n", mapOf(entry("key1", "true"))), + Arguments.argumentSet( + "double-quoted integer string", "key1: \"${INT}\"\n", mapOf(entry("key1", "1"))), + Arguments.argumentSet( + "double-quoted float string", "key1: \"${FLOAT}\"\n", mapOf(entry("key1", "1.1"))), + Arguments.argumentSet( + "double-quoted multiple vars", + "key1: \"${HEX} ${BOOL} ${INT}\"\n", + mapOf(entry("key1", "0xdeadbeef true 1"))), + Arguments.argumentSet( + "single-quoted hex string", "key1: '${HEX}'\n", mapOf(entry("key1", "0xdeadbeef"))), + Arguments.argumentSet( + "single-quoted string", "key1: '${STR_1}'\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet( + "single-quoted empty string", "key1: '${EMPTY_STR}'\n", mapOf(entry("key1", ""))), + Arguments.argumentSet( + "single-quoted boolean string", "key1: '${BOOL}'\n", mapOf(entry("key1", "true"))), + Arguments.argumentSet( + "single-quoted integer string", "key1: '${INT}'\n", mapOf(entry("key1", "1"))), + Arguments.argumentSet( + "single-quoted float string", "key1: '${FLOAT}'\n", mapOf(entry("key1", "1.1"))), + Arguments.argumentSet( + "single-quoted multiple vars", + "key1: '${HEX} ${BOOL} ${INT}'\n", + mapOf(entry("key1", "0xdeadbeef true 1"))), + Arguments.argumentSet("FOO var", "key1: ${FOO}\n", mapOf(entry("key1", "BAR"))), + Arguments.argumentSet( + "double-dollar escape", "key1: $${FOO}\n", mapOf(entry("key1", "${FOO}"))), + Arguments.argumentSet("triple-dollar", "key1: $$${FOO}\n", mapOf(entry("key1", "$BAR"))), + Arguments.argumentSet( + "quad-dollar escape", "key1: $$$${FOO}\n", mapOf(entry("key1", "$${FOO}"))), + Arguments.argumentSet( + "double-dollar in middle", "key1: a $$ b\n", mapOf(entry("key1", "a $ b"))), + Arguments.argumentSet("double-dollar prefix", "key1: $$ b\n", mapOf(entry("key1", "$ b"))), + Arguments.argumentSet("double-dollar suffix", "key1: a $$\n", mapOf(entry("key1", "a $"))), + Arguments.argumentSet( + "single dollar literal", "key1: a $ b\n", mapOf(entry("key1", "a $ b"))), + Arguments.argumentSet("escape var", "key1: $${STR_1}\n", mapOf(entry("key1", "${STR_1}"))), + Arguments.argumentSet( + "escape two vars", + "key1: $${STR_1}$${STR_1}\n", + mapOf(entry("key1", "${STR_1}${STR_1}"))), + Arguments.argumentSet( + "escape var with dollar", "key1: $${STR_1}$$\n", mapOf(entry("key1", "${STR_1}$"))), + Arguments.argumentSet( + "triple-dollar var", "key1: $$${STR_1}\n", mapOf(entry("key1", "$value1"))), + Arguments.argumentSet( + "double-quoted escape var", "key1: \"$${STR_1}\"\n", mapOf(entry("key1", "${STR_1}"))), + Arguments.argumentSet( + "escape var then real var", + "key1: $${STR_1} ${STR_2}\n", + mapOf(entry("key1", "${STR_1} value2"))), + Arguments.argumentSet( + "two escape vars", + "key1: $${STR_1} $${STR_2}\n", + mapOf(entry("key1", "${STR_1} ${STR_2}"))), + Arguments.argumentSet( + "escape default", + "key1: $${NOT_SET:-value1}\n", + mapOf(entry("key1", "${NOT_SET:-value1}"))), + Arguments.argumentSet( + "escape var with fallback", + "key1: $${STR_1:-fallback}\n", + mapOf(entry("key1", "${STR_1:-fallback}"))), + Arguments.argumentSet( + "escape var with nested default", + "key1: $${STR_1:-${STR_1}}\n", + mapOf(entry("key1", "${STR_1:-value1}"))), + Arguments.argumentSet( + "nested var in default", + "key1: ${NOT_SET:-${FALLBACK}}\n", + mapOf(entry("key1", "${FALLBACK}"))), + Arguments.argumentSet( + "escape in default", + "key1: ${NOT_SET:-$${FALLBACK}}\n", + mapOf(entry("key1", "${NOT_SET:-${FALLBACK}}"))), + Arguments.argumentSet( + "value with escape", "key1: ${VALUE_WITH_ESCAPE}\n", mapOf(entry("key1", "value$$")))); + } + + private static Map.Entry entry(K key, @Nullable V value) { + return new AbstractMap.SimpleEntry<>(key, value); + } + + @SuppressWarnings("unchecked") + private static Map mapOf(Map.Entry... entries) { + Map result = new HashMap<>(); + for (Map.Entry entry : entries) { + result.put(entry.getKey(), entry.getValue()); + } + return result; + } + + @ParameterizedTest + @MethodSource("sysPropertySubstitutionArgs") + void sysPropertySubstituteAndLoadYaml(String rawYaml, Object expectedYamlResult) { + Map systemProperties = new HashMap<>(); + systemProperties.put("foo.bar", "BAR"); + systemProperties.put("str.1", "value1"); + systemProperties.put("str.2", "value2"); + systemProperties.put("value.with.escape", "value$$"); + systemProperties.put("empty.str", ""); + systemProperties.put("bool.prop", "true"); + systemProperties.put("int.prop", "1"); + systemProperties.put("float.prop", "1.1"); + systemProperties.put("hex.prop", "0xdeadbeef"); + + Object yaml = + DeclarativeConfiguration.loadYaml( + new ByteArrayInputStream(rawYaml.getBytes(StandardCharsets.UTF_8)), + Collections.emptyMap(), + systemProperties); + assertThat(yaml).isEqualTo(expectedYamlResult); + } + + @SuppressWarnings("unchecked") + private static Stream sysPropertySubstitutionArgs() { + return Stream.of( + Arguments.argumentSet( + "sys str.1 string", "key1: ${sys:str.1}\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet( + "sys bool.prop boolean", "key1: ${sys:bool.prop}\n", mapOf(entry("key1", true))), + Arguments.argumentSet( + "sys int.prop integer", "key1: ${sys:int.prop}\n", mapOf(entry("key1", 1))), + Arguments.argumentSet( + "sys float.prop float", "key1: ${sys:float.prop}\n", mapOf(entry("key1", 1.1))), + Arguments.argumentSet( + "sys hex.prop hex", "key1: ${sys:hex.prop}\n", mapOf(entry("key1", 3735928559L))), + Arguments.argumentSet( + "sys default string", "key1: ${sys:not.set:-value1}\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet( + "sys default boolean", "key1: ${sys:not.set:-true}\n", mapOf(entry("key1", true))), + Arguments.argumentSet( + "sys default integer", "key1: ${sys:not.set:-1}\n", mapOf(entry("key1", 1))), + Arguments.argumentSet( + "sys two props concatenated", + "key1: ${sys:str.1}${sys:str.2}\n", + mapOf(entry("key1", "value1value2"))), + Arguments.argumentSet( + "sys two props with space", + "key1: ${sys:str.1} ${sys:str.2}\n", + mapOf(entry("key1", "value1 value2"))), + Arguments.argumentSet( + "sys two props with default", + "key1: ${sys:str.1} ${sys:not.set:-default} ${sys:str.2}\n", + mapOf(entry("key1", "value1 default value2"))), + Arguments.argumentSet( + "sys empty.str null", "key1: ${sys:empty.str}\n", mapOf(entry("key1", null))), + Arguments.argumentSet( + "sys undefined null", "key1: ${sys:str.3}\n", mapOf(entry("key1", null))), + Arguments.argumentSet( + "sys set and undefined", + "key1: ${sys:str.1} ${sys:str.3}\n", + mapOf(entry("key1", "value1 "))), + Arguments.argumentSet( + "sys double-quoted hex string", + "key1: \"${sys:hex.prop}\"\n", + mapOf(entry("key1", "0xdeadbeef"))), + Arguments.argumentSet( + "sys double-quoted string", "key1: \"${sys:str.1}\"\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet( + "sys single-quoted string", "key1: '${sys:str.1}'\n", mapOf(entry("key1", "value1"))), + Arguments.argumentSet("sys foo.bar", "key1: ${sys:foo.bar}\n", mapOf(entry("key1", "BAR"))), + Arguments.argumentSet( + "sys double-dollar escape", + "key1: $${sys:foo.bar}\n", + mapOf(entry("key1", "${sys:foo.bar}"))), + Arguments.argumentSet( + "sys triple-dollar", "key1: $$${sys:foo.bar}\n", mapOf(entry("key1", "$BAR"))), + Arguments.argumentSet( + "sys quad-dollar escape", + "key1: $$$${sys:foo.bar}\n", + mapOf(entry("key1", "$${sys:foo.bar}"))), + Arguments.argumentSet( + "sys value with escape", + "key1: ${sys:value.with.escape}\n", + mapOf(entry("key1", "value$$")))); + } + + @Test + void read_WithEnvironmentVariables() { + String yaml = + "file_format: \"1.2\"\n" + + "tracer_provider:\n" + + " processors:\n" + + " - batch:\n" + + " exporter:\n" + + " otlp_http:\n" + + " endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}\n" + + " - batch:\n" + + " exporter:\n" + + " otlp_http:\n" + + " endpoint: ${UNSET_ENV_VAR}\n"; + Map envVars = new HashMap<>(); + envVars.put("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector:4317"); + OpenTelemetryConfigurationModel model = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)), + envVars, + Collections.emptyMap()); + assertThat(model) + .isEqualTo( + new OpenTelemetryConfigurationModel() + .setFileFormat("1.2") + .setTracerProvider( + new TracerProviderModel() + .setProcessors( + Arrays.asList( + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel() + .setOtlpHttp( + new OtlpHttpExporterModel() + .setEndpoint( + "http://collector:4317")))), + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel()))))))); + } + + @Test + void read_WithSystemProperties() { + String yaml = + "file_format: \"1.2\"\n" + + "tracer_provider:\n" + + " processors:\n" + + " - batch:\n" + + " exporter:\n" + + " otlp_http:\n" + + " endpoint: ${sys:otel.exporter.otlp.endpoint}\n" + + " - batch:\n" + + " exporter:\n" + + " otlp_http:\n" + + " endpoint: ${sys:unset.sys.prop}\n"; + Map sysProps = new HashMap<>(); + sysProps.put("otel.exporter.otlp.endpoint", "http://collector:4318"); + OpenTelemetryConfigurationModel model = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)), + Collections.emptyMap(), + sysProps); + assertThat(model) + .isEqualTo( + new OpenTelemetryConfigurationModel() + .setFileFormat("1.2") + .setTracerProvider( + new TracerProviderModel() + .setProcessors( + Arrays.asList( + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel() + .setOtlpHttp( + new OtlpHttpExporterModel() + .setEndpoint( + "http://collector:4318")))), + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel()))))))); + } + + @Test + void read_WithMixedEnvVarsAndSystemProperties() { + String yaml = + "file_format: \"1.2\"\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: ${SERVICE_NAME}\n" + + " - name: service.version\n" + + " value: ${sys:app.version}\n" + + " - name: deployment.environment\n" + + " value: ${env:DEPLOYMENT_ENV:-production}\n"; + Map envVars = new HashMap<>(); + envVars.put("SERVICE_NAME", "my-service"); + Map sysProps = new HashMap<>(); + sysProps.put("app.version", "1.2.3"); + OpenTelemetryConfigurationModel model = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(yaml.getBytes(StandardCharsets.UTF_8)), envVars, sysProps); + assertThat(model) + .isEqualTo( + new OpenTelemetryConfigurationModel() + .setFileFormat("1.2") + .setResource( + new ResourceModel() + .setAttributes( + Arrays.asList( + new AttributeNameValueModel() + .setName("service.name") + .setValue("my-service"), + new AttributeNameValueModel() + .setName("service.version") + .setValue("1.2.3"), + new AttributeNameValueModel() + .setName("deployment.environment") + .setValue("production"))))); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/EntitiesEnvResourceDetectorTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/EntitiesEnvResourceDetectorTest.java new file mode 100644 index 00000000000..1a89dd20072 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/EntitiesEnvResourceDetectorTest.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.ClearSystemProperty; +import org.junitpioneer.jupiter.SetSystemProperty; + +class EntitiesEnvResourceDetectorTest { + + @Test + void getTypeAndName() { + EntitiesEnvResourceDetector detector = new EntitiesEnvResourceDetector(); + + assertThat(detector.getType()).isEqualTo(Resource.class); + assertThat(detector.getName()).isEqualTo("env"); + } + + @Test + @SetSystemProperty( + key = "otel.entities", + value = "process{process.pid=1234}[process.executable.name=java]@http://schema") + void create_SystemPropertySet() { + Resource resource = + new EntitiesEnvResourceDetector().create(DeclarativeConfigProperties.empty()); + + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder("process", Attributes.of(stringKey("process.pid"), "1234")) + .setSchemaUrl("http://schema") + .setDescription(Attributes.of(stringKey("process.executable.name"), "java")) + .build()); + } + + @Test + @ClearSystemProperty(key = "otel.entities") + void create_NoSystemProperty() { + assertThat(new EntitiesEnvResourceDetector().create(DeclarativeConfigProperties.empty())) + .isEqualTo(Resource.empty()); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExemplarFilterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExemplarFilterFactoryTest.java new file mode 100644 index 00000000000..ba34dd72017 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExemplarFilterFactoryTest.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExemplarFilterModel; +import io.opentelemetry.sdk.metrics.ExemplarFilter; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ExemplarFilterFactoryTest { + + @ParameterizedTest + @MethodSource("createTestCases") + void create(ExemplarFilterModel model, ExemplarFilter expectedResult) { + ExemplarFilter exemplarFilter = + ExemplarFilterFactory.getInstance().create(model, mock(DeclarativeConfigContext.class)); + assertThat(exemplarFilter.toString()).isEqualTo(expectedResult.toString()); + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "always_on", ExemplarFilterModel.ALWAYS_ON, ExemplarFilter.alwaysOn()), + Arguments.argumentSet( + "always_off", ExemplarFilterModel.ALWAYS_OFF, ExemplarFilter.alwaysOff()), + Arguments.argumentSet( + "trace_based", ExemplarFilterModel.TRACE_BASED, ExemplarFilter.traceBased())); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExtensionPropertyUtilTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExtensionPropertyUtilTest.java new file mode 100644 index 00000000000..078b3fd08e7 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ExtensionPropertyUtilTest.java @@ -0,0 +1,202 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExtensionPropertyUtil; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.slf4j.event.Level; + +class ExtensionPropertyUtilTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @RegisterExtension + LogCapturer logs = + LogCapturer.create().captureForLogger(ExtensionPropertyUtil.class.getName(), Level.TRACE); + + @Test + void handleAnySetter_knownExperimentalKey_convertsAndStores() { + Map props = new LinkedHashMap<>(); + Map> experimentalTypes = new HashMap<>(); + experimentalTypes.put("composite/development", ExperimentalComposableSamplerModel.class); + + ExtensionPropertyUtil.handleAnySetter( + "composite/development", + new LinkedHashMap<>(), + props, + experimentalTypes, + Collections.emptyMap(), + false); + + assertThat(props.get("composite/development")) + .isInstanceOf(ExperimentalComposableSamplerModel.class); + } + + @Test + void handleAnySetter_knownExperimentalKey_nullValue_storesNull() { + Map props = new LinkedHashMap<>(); + Map> experimentalTypes = new HashMap<>(); + experimentalTypes.put("composite/development", ExperimentalComposableSamplerModel.class); + + ExtensionPropertyUtil.handleAnySetter( + "composite/development", null, props, experimentalTypes, Collections.emptyMap(), false); + + assertThat(props).containsEntry("composite/development", null); + } + + @Test + void handleAnySetter_graduatedKey_storesUnderDevelopmentKey_andWarns() { + Map props = new LinkedHashMap<>(); + Map> stableTypes = new HashMap<>(); + stableTypes.put("limits", LogRecordLimitsModel.class); + + ExtensionPropertyUtil.handleAnySetter( + "limits/development", + new LinkedHashMap<>(), + props, + Collections.emptyMap(), + stableTypes, + false); + + assertThat(props).doesNotContainKey("limits"); + assertThat(props.get("limits/development")).isInstanceOf(LogRecordLimitsModel.class); + logs.assertContains("Property 'limits/development' has been stabilized. Use 'limits' instead."); + } + + @Test + void handleAnySetter_unknownKey_openType_stores() { + Map props = new LinkedHashMap<>(); + + ExtensionPropertyUtil.handleAnySetter( + "custom_exporter", + "config_value", + props, + Collections.emptyMap(), + Collections.emptyMap(), + true); + + assertThat(props).containsEntry("custom_exporter", "config_value"); + } + + @Test + void handleAnySetter_unknownKey_closedType_doesNotStore_andWarns() { + Map props = new LinkedHashMap<>(); + + ExtensionPropertyUtil.handleAnySetter( + "unknown_key", "value", props, Collections.emptyMap(), Collections.emptyMap(), false); + + assertThat(props).isEmpty(); + logs.assertContains("Unknown property 'unknown_key' is not recognized and will be ignored."); + } + + @Test + void get_absentKey_returnsNull() { + assertThat( + ExtensionPropertyUtil.get("missing", new LinkedHashMap<>(), LogRecordLimitsModel.class)) + .isNull(); + } + + @Test + void get_presentKey_returnsTypedValue() { + Map props = new LinkedHashMap<>(); + LogRecordLimitsModel limits = new LogRecordLimitsModel(); + props.put("limits", limits); + + assertThat(ExtensionPropertyUtil.get("limits", props, LogRecordLimitsModel.class)) + .isSameAs(limits); + } + + @Test + void stableGetter_returnsGraduatedValue_fromExtensionPropertiesFallback() { + LoggerProviderModel model = new LoggerProviderModel(); + model.setExtensionProperty("limits/development", new LinkedHashMap<>()); + + assertThat(model.getLimits()).isNotNull().isInstanceOf(LogRecordLimitsModel.class); + } + + @Test + void graduatedValue_isEqualToDirectlySetValue() { + LogRecordLimitsModel limits = new LogRecordLimitsModel(); + + LoggerProviderModel viaStableSetter = new LoggerProviderModel().setLimits(limits); + LoggerProviderModel viaGraduatedKey = new LoggerProviderModel(); + viaGraduatedKey.setExtensionProperty("limits/development", limits); + + assertThat(viaStableSetter.getLimits()).isEqualTo(viaGraduatedKey.getLimits()); + assertThat(viaStableSetter).isEqualTo(viaGraduatedKey); + assertThat(viaStableSetter.hashCode()).isEqualTo(viaGraduatedKey.hashCode()); + } + + @Test + void filterSerializable_noStableProperties_returnsInputUnchanged() { + Map props = new LinkedHashMap<>(); + props.put("anything/development", "x"); + assertThat(ExtensionPropertyUtil.filterSerializable(props, Collections.emptyMap())) + .isSameAs(props); + } + + @Test + void filterSerializable_noMatchingGraduatedKeys_returnsInputUnchanged() { + Map props = new LinkedHashMap<>(); + props.put("composite/development", "x"); + Map> stableProperties = new HashMap<>(); + stableProperties.put("limits", LogRecordLimitsModel.class); + + assertThat(ExtensionPropertyUtil.filterSerializable(props, stableProperties)).isSameAs(props); + } + + @Test + void filterSerializable_dropsGraduatedKeys_preservesOthers() { + Map props = new LinkedHashMap<>(); + props.put("limits/development", "graduated"); + props.put("composite/development", "still-experimental"); + props.put("custom_key", "open-schema-extension"); + Map> stableProperties = new HashMap<>(); + stableProperties.put("limits", LogRecordLimitsModel.class); + + Map filtered = + ExtensionPropertyUtil.filterSerializable(props, stableProperties); + + assertThat(filtered) + .doesNotContainKey("limits/development") + .containsEntry("composite/development", "still-experimental") + .containsEntry("custom_key", "open-schema-extension"); + assertThat(props).containsKey("limits/development"); + } + + @Test + void stableModel_roundTripsGraduatedKey_emitsStableKeyOnly() throws Exception { + String json = "{\"limits/development\":{}}"; + LoggerProviderModel model = mapper.readValue(json, LoggerProviderModel.class); + + assertThat(model.getLimits()).isNotNull().isInstanceOf(LogRecordLimitsModel.class); + + String reserialized = mapper.writeValueAsString(model); + assertThat(reserialized).contains("\"limits\":").doesNotContain("limits/development"); + } + + @Test + void stableModel_roundTripsNonGraduatedDevelopmentKey_verbatim() throws Exception { + String json = "{\"composite/development\":{}}"; + SamplerModel model = mapper.readValue(json, SamplerModel.class); + + String reserialized = mapper.writeValueAsString(model); + assertThat(reserialized).contains("composite/development"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/FileConfigTestUtil.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/FileConfigTestUtil.java new file mode 100644 index 00000000000..1e8bcb64171 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/FileConfigTestUtil.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +final class FileConfigTestUtil { + + private FileConfigTestUtil() {} + + static String createTempFileWithContent(Path dir, String filename, byte[] content) + throws IOException { + Path path = dir.resolve(filename); + Files.write(path, content); + return path.toString(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IdGeneratorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IdGeneratorFactoryTest.java new file mode 100644 index 00000000000..2180d42a4ed --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IdGeneratorFactoryTest.java @@ -0,0 +1,74 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.IdGeneratorComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IdGeneratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.RandomIdGeneratorModel; +import io.opentelemetry.sdk.trace.IdGenerator; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class IdGeneratorFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(IdGeneratorFactoryTest.class.getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create(IdGeneratorModel model, IdGenerator expectedIdGenerator) { + IdGenerator idGenerator = IdGeneratorFactory.getInstance().create(model, context); + assertThat(idGenerator.toString()).isEqualTo(expectedIdGenerator.toString()); + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "random id generator", + new IdGeneratorModel().setRandom(new RandomIdGeneratorModel()), + IdGenerator.random()), + Arguments.argumentSet( + "SPI id generator", + new IdGeneratorModel().setExtensionProperty("test", null), + IdGeneratorComponentProvider.TestIdGenerator.create())); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(IdGeneratorModel model, String expectedMessage) { + assertThatThrownBy(() -> IdGeneratorFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + private static Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "unknown SPI id generator", + new IdGeneratorModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value")), + "No component provider detected for io.opentelemetry.sdk.trace.IdGenerator with name \"unknown_key\".")); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IncludeExcludeFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IncludeExcludeFactoryTest.java new file mode 100644 index 00000000000..6d6a01d7f9c --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/IncludeExcludeFactoryTest.java @@ -0,0 +1,79 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import java.util.Arrays; +import java.util.Collections; +import java.util.function.Predicate; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class IncludeExcludeFactoryTest { + + private final DeclarativeConfigContext context = + new DeclarativeConfigContext(ComponentLoader.forClassLoader(getClass().getClassLoader())); + + @ParameterizedTest + @MethodSource("createArguments") + void create(IncludeExcludeModel model, Predicate expectedPredicate) { + Predicate predicate = IncludeExcludeFactory.getInstance().create(model, context); + assertThat(predicate.toString()).isEqualTo(expectedPredicate.toString()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "both null", + new IncludeExcludeModel().setIncluded(null).setExcluded(null), + IncludeExcludePredicate.createPatternMatching(null, null)), + Arguments.argumentSet( + "included present excluded null", + new IncludeExcludeModel().setIncluded(Arrays.asList("foo", "bar")).setExcluded(null), + IncludeExcludePredicate.createPatternMatching(Arrays.asList("foo", "bar"), null)), + Arguments.argumentSet( + "included null excluded present", + new IncludeExcludeModel() + .setIncluded(null) + .setExcluded(Collections.singletonList("baz")), + IncludeExcludePredicate.createPatternMatching(null, Collections.singletonList("baz"))), + Arguments.argumentSet( + "both present", + new IncludeExcludeModel() + .setIncluded(Arrays.asList("foo", "bar")) + .setExcluded(Collections.singletonList("baz")), + IncludeExcludePredicate.createPatternMatching( + Arrays.asList("foo", "bar"), Collections.singletonList("baz")))); + } + + @ParameterizedTest + @MethodSource("createInvalidArguments") + void createInvalid(IncludeExcludeModel model, String expectedMessage) { + assertThatThrownBy(() -> IncludeExcludeFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + private static Stream createInvalidArguments() { + return Stream.of( + Arguments.argumentSet( + "included empty", + new IncludeExcludeModel().setIncluded(Collections.emptyList()).setExcluded(null), + "included must not be empty"), + Arguments.argumentSet( + "excluded empty", + new IncludeExcludeModel().setIncluded(null).setExcluded(Collections.emptyList()), + "excluded must not be empty")); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java new file mode 100644 index 00000000000..dbb2338d4c1 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/InstrumentSelectorFactoryTest.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.InstrumentTypeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.InstrumentType; +import org.junit.jupiter.api.Test; + +class InstrumentSelectorFactoryTest { + + @Test + void create_Defaults() { + assertThatThrownBy(() -> + InstrumentSelectorFactory.getInstance() + .create(new ViewSelectorModel(), mock(DeclarativeConfigContext.class))) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage("Invalid selector"); + } + + @Test + void create() { + assertThat( + InstrumentSelectorFactory.getInstance() + .create( + new ViewSelectorModel() + .setInstrumentName("instrument-name") + .setInstrumentType(InstrumentTypeModel.COUNTER) + .setUnit("ms") + .setMeterName("meter-name") + .setMeterSchemaUrl("https://opentelemetry.io/schemas/1.16.0") + .setMeterVersion("1.0.0"), + mock(DeclarativeConfigContext.class))) + .isEqualTo( + InstrumentSelector.builder() + .setName("instrument-name") + .setType(InstrumentType.COUNTER) + .setUnit("ms") + .setMeterName("meter-name") + .setMeterSchemaUrl("https://opentelemetry.io/schemas/1.16.0") + .setMeterVersion("1.0.0") + .build()); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LegacyYamlDeclarativeConfigPropertiesTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LegacyYamlDeclarativeConfigPropertiesTest.java new file mode 100644 index 00000000000..f086a767c8b --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LegacyYamlDeclarativeConfigPropertiesTest.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.common.ComponentLoader; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") +class LegacyYamlDeclarativeConfigPropertiesTest { + + @Test + void delegation() { + DeclarativeConfigProperties delegate = mock(DeclarativeConfigProperties.class); + DeclarativeConfigProperties child = mock(DeclarativeConfigProperties.class); + ComponentLoader componentLoader = mock(ComponentLoader.class); + + when(delegate.getString("str")).thenReturn("hello"); + when(delegate.getBoolean("bool")).thenReturn(true); + when(delegate.getInt("int")).thenReturn(42); + when(delegate.getLong("long")).thenReturn(100L); + when(delegate.getDouble("double")).thenReturn(3.14); + + when(delegate.isString("str")).thenReturn(true); + when(delegate.isBoolean("bool")).thenReturn(true); + when(delegate.isInt("int")).thenReturn(true); + when(delegate.isLong("long")).thenReturn(true); + when(delegate.isDouble("double")).thenReturn(true); + + when(delegate.getScalarList("list", String.class)) + .thenReturn(Collections.singletonList("item")); + when(delegate.getStructured("child")).thenReturn(child); + when(delegate.getStructured("missing")).thenReturn(null); + + when(delegate.getStructuredList("children")).thenReturn(Collections.singletonList(child)); + when(delegate.getStructuredList("missing_list")).thenReturn(null); + + when(delegate.getPropertyKeys()).thenReturn(Collections.singleton("str")); + when(delegate.getComponentLoader()).thenReturn(componentLoader); + when(delegate.toString()).thenReturn("mockDelegate"); + + LegacyYamlDeclarativeConfigProperties properties = + new LegacyYamlDeclarativeConfigProperties(delegate); + + assertThat(properties.getString("str")).isEqualTo("hello"); + assertThat(properties.getBoolean("bool")).isTrue(); + assertThat(properties.getInt("int")).isEqualTo(42); + assertThat(properties.getLong("long")).isEqualTo(100L); + assertThat(properties.getDouble("double")).isEqualTo(3.14); + + assertThat(properties.isString("str")).isTrue(); + assertThat(properties.isBoolean("bool")).isTrue(); + assertThat(properties.isInt("int")).isTrue(); + assertThat(properties.isLong("long")).isTrue(); + assertThat(properties.isDouble("double")).isTrue(); + + assertThat(properties.getScalarList("list", String.class)).containsExactly("item"); + + io.opentelemetry.api.incubator.config.DeclarativeConfigProperties structured = + properties.getStructured("child"); + assertThat(structured).isInstanceOf(LegacyYamlDeclarativeConfigProperties.class); + assertThat(properties.getStructured("missing")).isNull(); + + List structuredList = + properties.getStructuredList("children"); + assertThat(structuredList).hasSize(1); + assertThat(structuredList.get(0)).isInstanceOf(LegacyYamlDeclarativeConfigProperties.class); + assertThat(properties.getStructuredList("missing_list")).isNull(); + + assertThat(properties.getPropertyKeys()).containsExactly("str"); + assertThat(properties.getComponentLoader()).isSameAs(componentLoader); + assertThat(properties.toString()) + .isEqualTo("LegacyYamlDeclarativeConfigProperties{mockDelegate}"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogLimitsFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogLimitsFactoryTest.java new file mode 100644 index 00000000000..1f28ea78696 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogLimitsFactoryTest.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel; +import io.opentelemetry.sdk.logs.LogLimits; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class LogLimitsFactoryTest { + + @ParameterizedTest + @MethodSource("createArguments") + void create(LogRecordLimitsAndAttributeLimits model, LogLimits expectedLogLimits) { + assertThat(LogLimitsFactory.getInstance().create(model, mock(DeclarativeConfigContext.class))) + .isEqualTo(expectedLogLimits); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "null limits", + LogRecordLimitsAndAttributeLimits.create(null, null), + LogLimits.builder().build()), + Arguments.argumentSet( + "empty models", + LogRecordLimitsAndAttributeLimits.create( + new AttributeLimitsModel(), new LogRecordLimitsModel()), + LogLimits.builder().build()), + Arguments.argumentSet( + "attribute limits only", + LogRecordLimitsAndAttributeLimits.create( + new AttributeLimitsModel() + .setAttributeValueLengthLimit(1) + .setAttributeCountLimit(2), + new LogRecordLimitsModel()), + LogLimits.builder().setMaxAttributeValueLength(1).setMaxNumberOfAttributes(2).build()), + Arguments.argumentSet( + "log record limits override attribute limits", + LogRecordLimitsAndAttributeLimits.create( + new AttributeLimitsModel() + .setAttributeValueLengthLimit(1) + .setAttributeCountLimit(2), + new LogRecordLimitsModel() + .setAttributeValueLengthLimit(3) + .setAttributeCountLimit(4)), + LogLimits.builder().setMaxAttributeValueLength(3).setMaxNumberOfAttributes(4).build())); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java new file mode 100644 index 00000000000..83c4bc5f69e --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordExporterFactoryTest.java @@ -0,0 +1,294 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigTestUtil.createTempFileWithContent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.logging.SystemOutLogRecordExporter; +import io.opentelemetry.exporter.logging.otlp.internal.logs.OtlpStdoutLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.logs.OtlpGrpcLogRecordExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.LogRecordExporterComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ConsoleExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.HttpTlsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.NameStringValuePairModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalOtlpFileExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LogRecordExporterModelAccessor; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.io.IOException; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class LogRecordExporterFactoryTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(LogRecordExporterFactoryTest.class.getClassLoader())); + + private String certificatePath; + private String clientKeyPath; + private String clientCertificatePath; + + @BeforeAll + void setupTls(@TempDir Path tempDir) throws CertificateEncodingException, IOException { + certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + } + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create(LogRecordExporterModel model, LogRecordExporter expectedExporter) { + cleanup.addCloseable(expectedExporter); + LogRecordExporter exporter = LogRecordExporterFactory.getInstance().create(model, context); + cleanup.addCloseable(exporter); + assertThat(exporter.toString()).isEqualTo(expectedExporter.toString()); + } + + Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "otlp_http default", + new LogRecordExporterModel().setOtlpHttp(new OtlpHttpExporterModel()), + OtlpHttpLogRecordExporter.getDefault().toBuilder().setComponentLoader(context).build()), + Arguments.argumentSet( + "otlp_http with options", + new LogRecordExporterModel() + .setOtlpHttp( + new OtlpHttpExporterModel() + .setEndpoint("http://example:4318/v1/logs") + .setHeaders( + Arrays.asList( + new NameStringValuePairModel().setName("key1").setValue("value1"), + new NameStringValuePairModel().setName("key2").setValue("value2"))) + .setCompression("gzip") + .setTimeout(15_000) + .setMaxRequestSize(1234) + .setTls( + new HttpTlsModel() + .setCaFile(certificatePath) + .setKeyFile(clientKeyPath) + .setCertFile(clientCertificatePath))), + OtlpHttpLogRecordExporter.builder() + .setEndpoint("http://example:4318/v1/logs") + .addHeader("key1", "value1") + .addHeader("key2", "value2") + .setTimeout(Duration.ofSeconds(15)) + .setCompression("gzip") + .setMaxRequestBodySize(1234) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_http max_request_size 0", + new LogRecordExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel().setMaxRequestSize(0)), + OtlpHttpLogRecordExporter.getDefault().toBuilder() + .setMaxRequestBodySize(Long.MAX_VALUE) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_grpc default", + new LogRecordExporterModel().setOtlpGrpc(new OtlpGrpcExporterModel()), + OtlpGrpcLogRecordExporter.getDefault().toBuilder().setComponentLoader(context).build()), + Arguments.argumentSet( + "otlp_grpc with options", + new LogRecordExporterModel() + .setOtlpGrpc( + new OtlpGrpcExporterModel() + .setEndpoint("http://example:4317") + .setHeaders( + Arrays.asList( + new NameStringValuePairModel().setName("key1").setValue("value1"), + new NameStringValuePairModel().setName("key2").setValue("value2"))) + .setCompression("gzip") + .setTimeout(15_000) + .setMaxRequestSize(1234) + .setTls( + new GrpcTlsModel() + .setCaFile(certificatePath) + .setKeyFile(clientKeyPath) + .setCertFile(clientCertificatePath))), + OtlpGrpcLogRecordExporter.builder() + .setEndpoint("http://example:4317") + .addHeader("key1", "value1") + .addHeader("key2", "value2") + .setTimeout(Duration.ofSeconds(15)) + .setCompression("gzip") + .setMaxRequestMessageSize(1234) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_grpc max_request_size 0", + new LogRecordExporterModel() + .setOtlpGrpc(new OtlpGrpcExporterModel().setMaxRequestSize(0)), + OtlpGrpcLogRecordExporter.getDefault().toBuilder() + .setMaxRequestMessageSize(Long.MAX_VALUE) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_file/development", + LogRecordExporterModelAccessor.setOtlpFile( + new LogRecordExporterModel(), new ExperimentalOtlpFileExporterModel()), + OtlpStdoutLogRecordExporter.builder().build())); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(LogRecordExporterModel model, String expectedMessage) { + assertThatThrownBy(() -> LogRecordExporterFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "unknown component provider", + new LogRecordExporterModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value1")), + "No component provider detected for io.opentelemetry.sdk.logs.export.LogRecordExporter with name \"unknown_key\"."), + Arguments.argumentSet( + "otlp_http negative max_request_size", + new LogRecordExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel().setMaxRequestSize(-1)), + "Error configuring io.opentelemetry.sdk.logs.export.LogRecordExporter with name \"otlp_http\""), + Arguments.argumentSet( + "otlp_grpc negative max_request_size", + new LogRecordExporterModel() + .setOtlpGrpc(new OtlpGrpcExporterModel().setMaxRequestSize(-1)), + "Error configuring io.opentelemetry.sdk.logs.export.LogRecordExporter with name \"otlp_grpc\"")); + } + + @Test + void create_SpiExporter_Valid() { + LogRecordExporter logRecordExporter = + LogRecordExporterFactory.getInstance() + .create( + new LogRecordExporterModel() + .setExtensionProperty("test", Collections.singletonMap("key1", "value1")), + context); + assertThat(logRecordExporter) + .isInstanceOf(LogRecordExporterComponentProvider.TestLogRecordExporter.class); + assertThat( + ((LogRecordExporterComponentProvider.TestLogRecordExporter) logRecordExporter) + .config.getString("key1")) + .isEqualTo("value1"); + } + + @Test + void create_Customizer() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addLogRecordExporterCustomizer( + LogRecordExporter.class, (exporter, properties) -> SystemOutLogRecordExporter.create()); + + LogRecordExporter result = + LogRecordExporterFactory.getInstance() + .create(new LogRecordExporterModel().setConsole(new ConsoleExporterModel()), context); + cleanup.addCloseable(result); + + assertThat(result).isInstanceOf(SystemOutLogRecordExporter.class); + } + + @Test + void create_Customizer_TypeSafe() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addLogRecordExporterCustomizer( + OtlpGrpcLogRecordExporter.class, + (exporter, properties) -> + exporter.toBuilder().setTimeout(Duration.ofSeconds(42)).build()); + + LogRecordExporter result = + LogRecordExporterFactory.getInstance() + .create(new LogRecordExporterModel().setOtlpGrpc(new OtlpGrpcExporterModel()), context); + cleanup.addCloseable(result); + + assertThat(result).isInstanceOf(OtlpGrpcLogRecordExporter.class); + assertThat(result.toString()).contains("timeoutNanos=42000000000"); + } + + @Test + void create_Customizer_TypeMismatch() { + AtomicInteger callCount = new AtomicInteger(0); + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addLogRecordExporterCustomizer( + OtlpGrpcLogRecordExporter.class, + (exporter, properties) -> { + callCount.incrementAndGet(); + return exporter; + }); + + LogRecordExporter result = + LogRecordExporterFactory.getInstance() + .create(new LogRecordExporterModel().setConsole(new ConsoleExporterModel()), context); + cleanup.addCloseable(result); + + assertThat(callCount.get()).isEqualTo(0); + } + + @Test + void create_Customizer_ReturnsNull() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addLogRecordExporterCustomizer(LogRecordExporter.class, (exporter, properties) -> null); + + assertThatThrownBy(() -> + LogRecordExporterFactory.getInstance() + .create( + new LogRecordExporterModel().setConsole(new ConsoleExporterModel()), context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("Customizer returned null for LogRecordExporter: console"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordProcessorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordProcessorFactoryTest.java new file mode 100644 index 00000000000..40d0cc93d4a --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LogRecordProcessorFactoryTest.java @@ -0,0 +1,131 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.LogRecordProcessorComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalEventToSpanEventBridgeLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LogRecordProcessorModelAccessor; +import io.opentelemetry.sdk.extension.incubator.logs.EventToSpanEventBridge; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import java.time.Duration; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class LogRecordProcessorFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(LogRecordProcessorFactoryTest.class.getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create(LogRecordProcessorModel model, LogRecordProcessor expectedProcessor) { + cleanup.addCloseable(expectedProcessor); + LogRecordProcessor processor = LogRecordProcessorFactory.getInstance().create(model, context); + cleanup.addCloseable(processor); + assertThat(processor.toString()).isEqualTo(expectedProcessor.toString()); + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "batch otlp_http defaults", + new LogRecordProcessorModel() + .setBatch( + new BatchLogRecordProcessorModel() + .setExporter( + new LogRecordExporterModel().setOtlpHttp(new OtlpHttpExporterModel()))), + BatchLogRecordProcessor.builder( + OtlpHttpLogRecordExporter.builder().setComponentLoader(context).build()) + .build()), + Arguments.argumentSet( + "batch otlp_http with options", + new LogRecordProcessorModel() + .setBatch( + new BatchLogRecordProcessorModel() + .setExporter( + new LogRecordExporterModel().setOtlpHttp(new OtlpHttpExporterModel())) + .setScheduleDelay(1) + .setMaxExportBatchSize(2) + .setExportTimeout(3)), + BatchLogRecordProcessor.builder( + OtlpHttpLogRecordExporter.builder().setComponentLoader(context).build()) + .setScheduleDelay(Duration.ofMillis(1)) + .setMaxExportBatchSize(2) + .setExporterTimeout(Duration.ofMillis(3)) + .build()), + Arguments.argumentSet( + "simple otlp_http", + new LogRecordProcessorModel() + .setSimple( + new SimpleLogRecordProcessorModel() + .setExporter( + new LogRecordExporterModel().setOtlpHttp(new OtlpHttpExporterModel()))), + SimpleLogRecordProcessor.create( + OtlpHttpLogRecordExporter.builder().setComponentLoader(context).build())), + Arguments.argumentSet( + "event_to_span_event_bridge/development", + LogRecordProcessorModelAccessor.setEventToSpanEventBridge( + new LogRecordProcessorModel(), + new ExperimentalEventToSpanEventBridgeLogRecordProcessorModel()), + EventToSpanEventBridge.create()), + Arguments.argumentSet( + "spi test processor", + new LogRecordProcessorModel().setExtensionProperty("test", null), + LogRecordProcessorComponentProvider.TestLogRecordProcessor.create())); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(LogRecordProcessorModel model, String expectedMessage) { + assertThatThrownBy(() -> LogRecordProcessorFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + private static Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "batch missing exporter", + new LogRecordProcessorModel().setBatch(new BatchLogRecordProcessorModel()), + "batch log record processor exporter is required but is null"), + Arguments.argumentSet( + "simple missing exporter", + new LogRecordProcessorModel().setSimple(new SimpleLogRecordProcessorModel()), + "simple log record processor exporter is required but is null"), + Arguments.argumentSet( + "unknown component provider", + new LogRecordProcessorModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value1")), + "No component provider detected for io.opentelemetry.sdk.logs.LogRecordProcessor with name \"unknown_key\".")); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java new file mode 100644 index 00000000000..1a27625e7ec --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/LoggerProviderFactoryTest.java @@ -0,0 +1,167 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil.setLoggerConfigurator; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SeverityNumberModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLoggerConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLoggerConfiguratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalLoggerMatcherAndConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.LoggerProviderModelAccessor; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class LoggerProviderFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(LoggerProviderFactoryTest.class.getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createArguments") + void create(LoggerProviderAndAttributeLimits model, SdkLoggerProvider expectedProvider) { + List closeables = new ArrayList<>(); + cleanup.addCloseable(expectedProvider); + + SdkLoggerProvider provider = LoggerProviderFactory.getInstance().create(model, context).build(); + cleanup.addCloseable(provider); + cleanup.addCloseables(closeables); + + assertThat(provider.toString()).isEqualTo(expectedProvider.toString()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "null limits", + LoggerProviderAndAttributeLimits.create(null, null), + SdkLoggerProvider.builder().build()), + Arguments.argumentSet( + "empty models", + LoggerProviderAndAttributeLimits.create( + new AttributeLimitsModel(), new LoggerProviderModel()), + SdkLoggerProvider.builder().build()), + Arguments.argumentSet( + "full configuration", + LoggerProviderAndAttributeLimits.create( + new AttributeLimitsModel(), + LoggerProviderModelAccessor.setLoggerConfigurator( + new LoggerProviderModel() + .setLimits( + new LogRecordLimitsModel() + .setAttributeCountLimit(1) + .setAttributeValueLengthLimit(2)) + .setProcessors( + Collections.singletonList( + new LogRecordProcessorModel() + .setBatch( + new BatchLogRecordProcessorModel() + .setExporter( + new LogRecordExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel()))))), + new ExperimentalLoggerConfiguratorModel() + .setDefaultConfig(new ExperimentalLoggerConfigModel().setEnabled(false)) + .setLoggers( + Collections.singletonList( + new ExperimentalLoggerMatcherAndConfigModel() + .setName("foo") + .setConfig( + new ExperimentalLoggerConfigModel() + .setEnabled(true) + .setTraceBased(true) + .setMinimumSeverity(SeverityNumberModel.INFO)))))), + setLoggerConfigurator( + SdkLoggerProvider.builder(), + ScopeConfigurator.builder() + .setDefault(LoggerConfig.disabled()) + .addCondition( + ScopeConfiguratorBuilder.nameMatchesGlob("foo"), + LoggerConfig.builder() + .setEnabled(true) + .setTraceBased(true) + .setMinimumSeverity(Severity.INFO) + .build()) + .build()) + .setLogLimits(() -> + LogLimits.builder() + .setMaxNumberOfAttributes(1) + .setMaxAttributeValueLength(2) + .build()) + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + OtlpHttpLogRecordExporter.builder().setComponentLoader(context).build()) + .build()) + .build())); + } + + @ParameterizedTest + @MethodSource("severityNumberArguments") + void severityNumber(SeverityNumberModel model, Severity expectedSeverity) { + assertThat(LoggerProviderFactory.severityNumberToSeverity(model)).isEqualTo(expectedSeverity); + } + + private static Stream severityNumberArguments() { + return Stream.of( + Arguments.argumentSet("TRACE", SeverityNumberModel.TRACE, Severity.TRACE), + Arguments.argumentSet("TRACE_2", SeverityNumberModel.TRACE_2, Severity.TRACE2), + Arguments.argumentSet("TRACE_3", SeverityNumberModel.TRACE_3, Severity.TRACE3), + Arguments.argumentSet("TRACE_4", SeverityNumberModel.TRACE_4, Severity.TRACE4), + Arguments.argumentSet("DEBUG", SeverityNumberModel.DEBUG, Severity.DEBUG), + Arguments.argumentSet("DEBUG_2", SeverityNumberModel.DEBUG_2, Severity.DEBUG2), + Arguments.argumentSet("DEBUG_3", SeverityNumberModel.DEBUG_3, Severity.DEBUG3), + Arguments.argumentSet("DEBUG_4", SeverityNumberModel.DEBUG_4, Severity.DEBUG4), + Arguments.argumentSet("INFO", SeverityNumberModel.INFO, Severity.INFO), + Arguments.argumentSet("INFO_2", SeverityNumberModel.INFO_2, Severity.INFO2), + Arguments.argumentSet("INFO_3", SeverityNumberModel.INFO_3, Severity.INFO3), + Arguments.argumentSet("INFO_4", SeverityNumberModel.INFO_4, Severity.INFO4), + Arguments.argumentSet("WARN", SeverityNumberModel.WARN, Severity.WARN), + Arguments.argumentSet("WARN_2", SeverityNumberModel.WARN_2, Severity.WARN2), + Arguments.argumentSet("WARN_3", SeverityNumberModel.WARN_3, Severity.WARN3), + Arguments.argumentSet("WARN_4", SeverityNumberModel.WARN_4, Severity.WARN4), + Arguments.argumentSet("ERROR", SeverityNumberModel.ERROR, Severity.ERROR), + Arguments.argumentSet("ERROR_2", SeverityNumberModel.ERROR_2, Severity.ERROR2), + Arguments.argumentSet("ERROR_3", SeverityNumberModel.ERROR_3, Severity.ERROR3), + Arguments.argumentSet("ERROR_4", SeverityNumberModel.ERROR_4, Severity.ERROR4), + Arguments.argumentSet("FATAL", SeverityNumberModel.FATAL, Severity.FATAL), + Arguments.argumentSet("FATAL_2", SeverityNumberModel.FATAL_2, Severity.FATAL2), + Arguments.argumentSet("FATAL_3", SeverityNumberModel.FATAL_3, Severity.FATAL3), + Arguments.argumentSet("FATAL_4", SeverityNumberModel.FATAL_4, Severity.FATAL4)); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactoryTest.java new file mode 100644 index 00000000000..584bdfa22f4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MeterProviderFactoryTest.java @@ -0,0 +1,125 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil.setMeterConfigurator; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExemplarFilterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalMeterConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalMeterConfiguratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalMeterMatcherAndConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.MeterProviderModelAccessor; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.metrics.ExemplarFilter; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class MeterProviderFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(MeterProviderFactoryTest.class.getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createArguments") + void create(MeterProviderModel model, SdkMeterProvider expectedProvider) { + List closeables = new ArrayList<>(); + cleanup.addCloseable(expectedProvider); + + SdkMeterProvider provider = MeterProviderFactory.getInstance().create(model, context).build(); + cleanup.addCloseable(provider); + cleanup.addCloseables(closeables); + + assertThat(provider.toString()).isEqualTo(expectedProvider.toString()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "defaults", new MeterProviderModel(), SdkMeterProvider.builder().build()), + Arguments.argumentSet( + "with reader view and meter configurator", + MeterProviderModelAccessor.setMeterConfigurator( + new MeterProviderModel() + .setReaders( + Collections.singletonList( + new MetricReaderModel() + .setPeriodic( + new PeriodicMetricReaderModel() + .setExporter( + new PushMetricExporterModel() + .setOtlpHttp( + new OtlpHttpMetricExporterModel()))))) + .setViews( + Collections.singletonList( + new ViewModel() + .setSelector( + new ViewSelectorModel() + .setInstrumentName("instrument-name")) + .setStream( + new ViewStreamModel() + .setName("stream-name") + .setAttributeKeys(null)))), + new ExperimentalMeterConfiguratorModel() + .setDefaultConfig(new ExperimentalMeterConfigModel().setEnabled(false)) + .setMeters( + Collections.singletonList( + new ExperimentalMeterMatcherAndConfigModel() + .setName("foo") + .setConfig( + new ExperimentalMeterConfigModel().setEnabled(true))))) + .setExemplarFilter(ExemplarFilterModel.ALWAYS_ON), + setMeterConfigurator( + SdkMeterProvider.builder(), + ScopeConfigurator.builder() + .setDefault(MeterConfig.disabled()) + .addCondition( + ScopeConfiguratorBuilder.nameMatchesGlob("foo"), MeterConfig.enabled()) + .build()) + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader( + PeriodicMetricReader.builder( + OtlpHttpMetricExporter.builder().setComponentLoader(context).build()) + .build()) + .registerView( + InstrumentSelector.builder().setName("instrument-name").build(), + View.builder().setName("stream-name").build()) + .build())); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java new file mode 100644 index 00000000000..9697a3e2397 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricExporterFactoryTest.java @@ -0,0 +1,331 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigTestUtil.createTempFileWithContent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.logging.LoggingMetricExporter; +import io.opentelemetry.exporter.logging.otlp.internal.metrics.OtlpStdoutMetricExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.metrics.OtlpGrpcMetricExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.MetricExporterComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ConsoleMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExporterDefaultHistogramAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExporterTemporalityPreferenceModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.HttpTlsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.NameStringValuePairModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalOtlpFileMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PushMetricExporterModelAccessor; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.io.IOException; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class MetricExporterFactoryTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(MetricExporterFactoryTest.class.getClassLoader())); + + private String certificatePath; + private String clientKeyPath; + private String clientCertificatePath; + + @BeforeAll + void setupTls(@TempDir Path tempDir) throws CertificateEncodingException, IOException { + certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + } + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create(PushMetricExporterModel model, MetricExporter expectedExporter) { + cleanup.addCloseable(expectedExporter); + MetricExporter exporter = MetricExporterFactory.getInstance().create(model, context); + cleanup.addCloseable(exporter); + assertThat(exporter.toString()).isEqualTo(expectedExporter.toString()); + } + + Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "otlp_http default", + new PushMetricExporterModel().setOtlpHttp(new OtlpHttpMetricExporterModel()), + OtlpHttpMetricExporter.getDefault().toBuilder().setComponentLoader(context).build()), + Arguments.argumentSet( + "otlp_http with options", + new PushMetricExporterModel() + .setOtlpHttp( + new OtlpHttpMetricExporterModel() + .setEndpoint("http://example:4318/v1/metrics") + .setHeaders( + Arrays.asList( + new NameStringValuePairModel().setName("key1").setValue("value1"), + new NameStringValuePairModel().setName("key2").setValue("value2"))) + .setCompression("gzip") + .setTimeout(15_000) + .setMaxRequestSize(1234) + .setTls( + new HttpTlsModel() + .setCaFile(certificatePath) + .setKeyFile(clientKeyPath) + .setCertFile(clientCertificatePath)) + .setTemporalityPreference(ExporterTemporalityPreferenceModel.DELTA) + .setDefaultHistogramAggregation( + ExporterDefaultHistogramAggregationModel + .BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM)), + OtlpHttpMetricExporter.builder() + .setEndpoint("http://example:4318/v1/metrics") + .addHeader("key1", "value1") + .addHeader("key2", "value2") + .setTimeout(Duration.ofSeconds(15)) + .setCompression("gzip") + .setMaxRequestBodySize(1234) + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with( + InstrumentType.HISTOGRAM, + Aggregation.base2ExponentialBucketHistogram())) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_http max_request_size 0", + new PushMetricExporterModel() + .setOtlpHttp(new OtlpHttpMetricExporterModel().setMaxRequestSize(0)), + OtlpHttpMetricExporter.getDefault().toBuilder() + .setMaxRequestBodySize(Long.MAX_VALUE) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_grpc default", + new PushMetricExporterModel().setOtlpGrpc(new OtlpGrpcMetricExporterModel()), + OtlpGrpcMetricExporter.getDefault().toBuilder().setComponentLoader(context).build()), + Arguments.argumentSet( + "otlp_grpc with options", + new PushMetricExporterModel() + .setOtlpGrpc( + new OtlpGrpcMetricExporterModel() + .setEndpoint("http://example:4317") + .setHeaders( + Arrays.asList( + new NameStringValuePairModel().setName("key1").setValue("value1"), + new NameStringValuePairModel().setName("key2").setValue("value2"))) + .setCompression("gzip") + .setTimeout(15_000) + .setMaxRequestSize(1234) + .setTls( + new GrpcTlsModel() + .setCaFile(certificatePath) + .setKeyFile(clientKeyPath) + .setCertFile(clientCertificatePath)) + .setTemporalityPreference(ExporterTemporalityPreferenceModel.DELTA) + .setDefaultHistogramAggregation( + ExporterDefaultHistogramAggregationModel + .BASE_2_EXPONENTIAL_BUCKET_HISTOGRAM)), + OtlpGrpcMetricExporter.builder() + .setEndpoint("http://example:4317") + .addHeader("key1", "value1") + .addHeader("key2", "value2") + .setTimeout(Duration.ofSeconds(15)) + .setCompression("gzip") + .setMaxRequestMessageSize(1234) + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with( + InstrumentType.HISTOGRAM, + Aggregation.base2ExponentialBucketHistogram())) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_grpc max_request_size 0", + new PushMetricExporterModel() + .setOtlpGrpc(new OtlpGrpcMetricExporterModel().setMaxRequestSize(0)), + OtlpGrpcMetricExporter.getDefault().toBuilder() + .setMaxRequestMessageSize(Long.MAX_VALUE) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "console", + new PushMetricExporterModel().setConsole(new ConsoleMetricExporterModel()), + LoggingMetricExporter.create()), + Arguments.argumentSet( + "otlp_file/development", + PushMetricExporterModelAccessor.setOtlpFile( + new PushMetricExporterModel(), new ExperimentalOtlpFileMetricExporterModel()), + OtlpStdoutMetricExporter.builder().build())); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(PushMetricExporterModel model, String expectedMessage) { + assertThatThrownBy(() -> MetricExporterFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "unknown component provider", + new PushMetricExporterModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value1")), + "No component provider detected for io.opentelemetry.sdk.metrics.export.MetricExporter with name \"unknown_key\"."), + Arguments.argumentSet( + "otlp_http negative max_request_size", + new PushMetricExporterModel() + .setOtlpHttp(new OtlpHttpMetricExporterModel().setMaxRequestSize(-1)), + "Error configuring io.opentelemetry.sdk.metrics.export.MetricExporter with name \"otlp_http\""), + Arguments.argumentSet( + "otlp_grpc negative max_request_size", + new PushMetricExporterModel() + .setOtlpGrpc(new OtlpGrpcMetricExporterModel().setMaxRequestSize(-1)), + "Error configuring io.opentelemetry.sdk.metrics.export.MetricExporter with name \"otlp_grpc\"")); + } + + @Test + void create_SpiExporter_Valid() { + MetricExporter metricExporter = + MetricExporterFactory.getInstance() + .create( + new PushMetricExporterModel() + .setExtensionProperty("test", Collections.singletonMap("key1", "value1")), + context); + assertThat(metricExporter) + .isInstanceOf(MetricExporterComponentProvider.TestMetricExporter.class); + assertThat( + ((MetricExporterComponentProvider.TestMetricExporter) metricExporter) + .config.getString("key1")) + .isEqualTo("value1"); + } + + @Test + void create_Customizer() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addMetricExporterCustomizer( + MetricExporter.class, (exporter, properties) -> LoggingMetricExporter.create()); + + MetricExporter result = + MetricExporterFactory.getInstance() + .create( + new PushMetricExporterModel().setConsole(new ConsoleMetricExporterModel()), + context); + cleanup.addCloseable(result); + + assertThat(result).isInstanceOf(LoggingMetricExporter.class); + } + + @Test + void create_Customizer_TypeSafe() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addMetricExporterCustomizer( + OtlpGrpcMetricExporter.class, + (exporter, properties) -> + exporter.toBuilder().setTimeout(Duration.ofSeconds(42)).build()); + + MetricExporter result = + MetricExporterFactory.getInstance() + .create( + new PushMetricExporterModel().setOtlpGrpc(new OtlpGrpcMetricExporterModel()), + context); + cleanup.addCloseable(result); + + assertThat(result).isInstanceOf(OtlpGrpcMetricExporter.class); + assertThat(result.toString()).contains("timeoutNanos=42000000000"); + } + + @Test + void create_Customizer_TypeMismatch() { + AtomicInteger callCount = new AtomicInteger(0); + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addMetricExporterCustomizer( + OtlpGrpcMetricExporter.class, + (exporter, properties) -> { + callCount.incrementAndGet(); + return exporter; + }); + + MetricExporter result = + MetricExporterFactory.getInstance() + .create( + new PushMetricExporterModel().setConsole(new ConsoleMetricExporterModel()), + context); + cleanup.addCloseable(result); + + assertThat(callCount.get()).isEqualTo(0); + } + + @Test + void create_Customizer_ReturnsNull() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addMetricExporterCustomizer(MetricExporter.class, (exporter, properties) -> null); + + assertThatThrownBy(() -> + MetricExporterFactory.getInstance() + .create( + new PushMetricExporterModel().setConsole(new ConsoleMetricExporterModel()), + context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("Customizer returned null for MetricExporter: console"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderFactoryTest.java new file mode 100644 index 00000000000..42302cb2942 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/MetricReaderFactoryTest.java @@ -0,0 +1,257 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.prometheus.PrometheusHttpServer; +import io.opentelemetry.exporter.prometheus.TranslationStrategy; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.CardinalityLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PullMetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalPrometheusMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalPrometheusTranslationStrategyModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PeriodicMetricReaderModelAccessor; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.PullMetricExporterModelAccessor; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import java.io.IOException; +import java.net.ServerSocket; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class MetricReaderFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + spy( + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(MetricReaderFactoryTest.class.getClassLoader()))); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + clearInvocations(context); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create( + MetricReaderModel model, + MetricReader expectedReader, + Integer expectedDefaultCardinalityLimit, + boolean verifyLoadComponent) { + cleanup.addCloseable(expectedReader); + MetricReaderAndCardinalityLimits readerAndCardinalityLimits = + MetricReaderFactory.getInstance().create(model, context); + MetricReader reader = readerAndCardinalityLimits.getMetricReader(); + cleanup.addCloseable(reader); + + assertThat(reader.toString()).isEqualTo(expectedReader.toString()); + if (expectedDefaultCardinalityLimit == null) { + assertThat(readerAndCardinalityLimits.getCardinalityLimitsSelector()).isNull(); + } else { + assertThat( + readerAndCardinalityLimits + .getCardinalityLimitsSelector() + .getCardinalityLimit(InstrumentType.COUNTER)) + .isEqualTo(expectedDefaultCardinalityLimit); + } + if (verifyLoadComponent) { + verify(context).loadComponent(eq(MetricReader.class), any(ConfigKeyValue.class)); + } + } + + /** + * Find a random unused port. There's a small race if another process takes it before we + * initialize. Consider adding retries to this test if it flakes, presumably it never will on CI + * since there's no prometheus there blocking the well-known port. + */ + static Stream createTestCases() throws IOException { + List testCases = + new ArrayList<>( + Arrays.asList( + Arguments.argumentSet( + "periodic defaults", + new MetricReaderModel() + .setPeriodic( + new PeriodicMetricReaderModel() + .setExporter( + new PushMetricExporterModel() + .setOtlpHttp(new OtlpHttpMetricExporterModel()))), + PeriodicMetricReader.builder( + OtlpHttpMetricExporter.builder().setComponentLoader(context).build()) + .build(), + null, + false), + Arguments.argumentSet( + "periodic configured", + new MetricReaderModel() + .setPeriodic( + PeriodicMetricReaderModelAccessor.setMaxExportBatchSize( + new PeriodicMetricReaderModel() + .setExporter( + new PushMetricExporterModel() + .setOtlpHttp(new OtlpHttpMetricExporterModel())) + .setInterval(1) + .setCardinalityLimits( + new CardinalityLimitsModel().setDefault(100)), + 200)), + PeriodicMetricReader.builder( + OtlpHttpMetricExporter.builder().setComponentLoader(context).build()) + .setInterval(Duration.ofMillis(1)) + .setMaxExportBatchSize(200) + .build(), + 100, + false))); + + int prom1Port = randomAvailablePort(); + PrometheusHttpServer prom1Expected = PrometheusHttpServer.builder().setPort(prom1Port).build(); + // Close immediately to release the port before MetricReaderFactory creates a server on it + prom1Expected.close(); + testCases.add( + Arguments.argumentSet( + "pull prometheus defaults", + new MetricReaderModel() + .setPull( + new PullMetricReaderModel() + .setExporter( + PullMetricExporterModelAccessor.setPrometheus( + new PullMetricExporterModel(), + new ExperimentalPrometheusMetricExporterModel() + .setPort(prom1Port)))), + prom1Expected, + null, + true)); + + int prom2Port = randomAvailablePort(); + PrometheusHttpServer prom2Expected = + PrometheusHttpServer.builder() + .setHost("localhost") + .setPort(prom2Port) + .setOtelScopeLabelsEnabled(false) + .setTargetInfoMetricEnabled(false) + .setTranslationStrategy(TranslationStrategy.UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES) + .setAllowedResourceAttributesFilter( + IncludeExcludePredicate.createPatternMatching( + singletonList("foo"), singletonList("bar"))) + .build(); + prom2Expected.close(); + // Close immediately to release the port before MetricReaderFactory creates a server on it + testCases.add( + Arguments.argumentSet( + "pull prometheus configured", + new MetricReaderModel() + .setPull( + new PullMetricReaderModel() + .setCardinalityLimits(new CardinalityLimitsModel().setDefault(100)) + .setExporter( + PullMetricExporterModelAccessor.setPrometheus( + new PullMetricExporterModel(), + new ExperimentalPrometheusMetricExporterModel() + .setHost("localhost") + .setPort(prom2Port) + .setResourceConstantLabels( + new IncludeExcludeModel() + .setIncluded(singletonList("foo")) + .setExcluded(singletonList("bar"))) + .setScopeInfoEnabled(false) + .setTargetInfoEnabledDevelopment(false) + .setTranslationStrategy( + ExperimentalPrometheusTranslationStrategyModel + .UNDERSCORE_ESCAPING_WITHOUT_SUFFIXES_DEVELOPMENT)))), + prom2Expected, + 100, + true)); + + int prom3Port = randomAvailablePort(); + PrometheusHttpServer prom3Expected = + PrometheusHttpServer.builder() + .setPort(prom3Port) + .setTranslationStrategy(TranslationStrategy.NO_TRANSLATION) + .build(); + prom3Expected.close(); + // Close immediately to release the port before MetricReaderFactory creates a server on it + testCases.add( + Arguments.argumentSet( + "pull prometheus no translation", + new MetricReaderModel() + .setPull( + new PullMetricReaderModel() + .setExporter( + PullMetricExporterModelAccessor.setPrometheus( + new PullMetricExporterModel(), + new ExperimentalPrometheusMetricExporterModel() + .setHost("localhost") + .setPort(prom3Port) + .setTranslationStrategy( + ExperimentalPrometheusTranslationStrategyModel + .NO_TRANSLATION_DEVELOPMENT)))), + prom3Expected, + null, + true)); + + return testCases.stream(); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(MetricReaderModel model, String expectedMessage) { + assertThatThrownBy(() -> MetricReaderFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + static Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "null periodic reader exporter", + new MetricReaderModel().setPeriodic(new PeriodicMetricReaderModel()), + "periodic metric reader exporter is required but is null"), + Arguments.argumentSet( + "null pull reader", + new MetricReaderModel().setPull(new PullMetricReaderModel()), + "pull metric reader exporter is required but is null"), + Arguments.argumentSet( + "null pull reader exporter", + new MetricReaderModel() + .setPull(new PullMetricReaderModel().setExporter(new PullMetricExporterModel())), + "metric reader must have exactly one entry but has 0")); + } + + private static int randomAvailablePort() throws IOException { + try (ServerSocket socket = new ServerSocket(0)) { + return socket.getLocalPort(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java new file mode 100644 index 00000000000..c9cfb2186cd --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/OpenTelemetryConfigurationFactoryTest.java @@ -0,0 +1,408 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.trace.samplers.Sampler.alwaysOn; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.exporter.otlp.http.logs.OtlpHttpLogRecordExporter; +import io.opentelemetry.exporter.otlp.http.metrics.OtlpHttpMetricExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.extension.trace.propagation.B3Propagator; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysOnSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.LoggerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MeterProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.MetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PeriodicMetricReaderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PushMetricExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleLogRecordProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewSelectorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectionModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ResourceModelAccessor; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.internal.OpenTelemetrySdkBuilderUtil; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SpanLimits; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import java.io.Closeable; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.slf4j.event.Level; + +class OpenTelemetryConfigurationFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + @RegisterExtension + LogCapturer logCapturer = + LogCapturer.create() + .captureForLogger(OpenTelemetryConfigurationFactory.class.getName(), Level.WARN); + + private final DeclarativeConfigContext context = + new DeclarativeConfigContext(ComponentLoader.forClassLoader(getClass().getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("fileFormatArgs") + @SuppressLogger(OpenTelemetryConfigurationFactory.class) + void create_FileFormat(String fileFormat, boolean isValid) { + OpenTelemetryConfigurationModel model = + new OpenTelemetryConfigurationModel().setFileFormat(fileFormat); + + if (isValid) { + assertThatCode(() -> OpenTelemetryConfigurationFactory.getInstance().create(model, context)) + .doesNotThrowAnyException(); + } else { + assertThatThrownBy( + () -> OpenTelemetryConfigurationFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageMatching( + "Unsupported file format '.+'\\. Supported formats include 0\\.4, 1\\.\\*"); + } + } + + private static Stream fileFormatArgs() { + return Stream.of( + Arguments.argumentSet("null invalid", null, false), + Arguments.argumentSet("0.3 invalid", "0.3", false), + Arguments.argumentSet("a0.4 invalid", "a0.4", false), + Arguments.argumentSet("0.4a invalid", "0.4a", false), + Arguments.argumentSet("foo invalid", "foo", false), + Arguments.argumentSet("1.0-rc.a invalid", "1.0-rc.a", false), + Arguments.argumentSet("1.0.0 invalid", "1.0.0", false), + Arguments.argumentSet("1.0.3 invalid", "1.0.3", false), + Arguments.argumentSet("1.0.0-rc.3 invalid", "1.0.0-rc.3", false), + Arguments.argumentSet("1.1.0 invalid", "1.1.0", false), + Arguments.argumentSet("1.a invalid", "1.a", false), + Arguments.argumentSet("0.4 valid", "0.4", true), + Arguments.argumentSet("1.0-rc.1 valid", "1.0-rc.1", true), + Arguments.argumentSet("1.0-rc.2 valid", "1.0-rc.2", true), + Arguments.argumentSet("1.0-rc.3 valid", "1.0-rc.3", true), + Arguments.argumentSet("1.0 valid", "1.0", true), + Arguments.argumentSet("1.1 valid", "1.1", true), + Arguments.argumentSet("1.2 valid", "1.2", true), + Arguments.argumentSet("1.12 valid", "1.12", true)); + } + + @Test + @SuppressLogger(OpenTelemetryConfigurationFactory.class) + void create_FileFormatVersionMismatch_LogsWarning() { + OpenTelemetryConfigurationModel model = + new OpenTelemetryConfigurationModel().setFileFormat("1.0-rc.3"); + + ExtendedOpenTelemetrySdk sdk = + OpenTelemetryConfigurationFactory.getInstance().create(model, context).getSdk(); + cleanup.addCloseable(sdk); + + logCapturer.assertContains( + "Configuration file_format '1.0-rc.3' does not exactly match expected version '1.2'"); + } + + @Test + void create_FileFormatExactMatch_NoWarning() { + OpenTelemetryConfigurationModel model = + new OpenTelemetryConfigurationModel().setFileFormat("1.2"); + + ExtendedOpenTelemetrySdk sdk = + OpenTelemetryConfigurationFactory.getInstance().create(model, context).getSdk(); + cleanup.addCloseable(sdk); + + assertThat(logCapturer.size()).isEqualTo(0); + } + + @Test + void create_Defaults() { + List closeables = new ArrayList<>(); + OpenTelemetryConfigurationModel model = + new OpenTelemetryConfigurationModel().setFileFormat("1.2"); + OpenTelemetrySdk expectedSdk = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder(), + SdkConfigProvider.create(DeclarativeConfiguration.toConfigProperties(model))) + .build(); + cleanup.addCloseable(expectedSdk); + + ExtendedOpenTelemetrySdk sdk = + OpenTelemetryConfigurationFactory.getInstance().create(model, context).getSdk(); + cleanup.addCloseable(sdk); + cleanup.addCloseables(closeables); + + assertThat(sdk).hasToString(expectedSdk.toString()); + } + + @Test + void create_Disabled() { + List closeables = new ArrayList<>(); + OpenTelemetryConfigurationModel model = + new OpenTelemetryConfigurationModel() + .setFileFormat("1.2") + .setDisabled(true) + // Logger provider configuration should be ignored since SDK is disabled + .setLoggerProvider( + new LoggerProviderModel() + .setProcessors( + Collections.singletonList( + new LogRecordProcessorModel() + .setSimple( + new SimpleLogRecordProcessorModel() + .setExporter( + new LogRecordExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel())))))); + OpenTelemetrySdk expectedSdk = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder(), + SdkConfigProvider.create(DeclarativeConfiguration.toConfigProperties(model))) + .build(); + cleanup.addCloseable(expectedSdk); + + ExtendedOpenTelemetrySdk sdk = + OpenTelemetryConfigurationFactory.getInstance().create(model, context).getSdk(); + cleanup.addCloseable(sdk); + cleanup.addCloseables(closeables); + + assertThat(sdk).hasToString(expectedSdk.toString()); + } + + @Test + void create_Configured() throws NoSuchFieldException { + List closeables = new ArrayList<>(); + Resource expectedResource = + Resource.getDefault().toBuilder() + .put("service.name", "my-service") + .put("key", "val") + // resource attributes from resource ComponentProviders + .put("color", "red") + .put("shape", "square") + .put("order", "second") + .build(); + + OpenTelemetryConfigurationModel model = + new OpenTelemetryConfigurationModel() + .setFileFormat("1.2") + .setPropagator( + new PropagatorModel().setCompositeList("tracecontext,baggage,b3multi,b3")) + .setResource( + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setDetectors( + Arrays.asList( + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("order_first", null), + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("order_second", null), + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("shape_color", null)))) + .setAttributes( + Arrays.asList( + new AttributeNameValueModel() + .setName("service.name") + .setValue("my-service"), + new AttributeNameValueModel().setName("key").setValue("val")))) + .setLoggerProvider( + new LoggerProviderModel() + .setLimits( + new LogRecordLimitsModel() + .setAttributeValueLengthLimit(1) + .setAttributeCountLimit(2)) + .setProcessors( + Collections.singletonList( + new LogRecordProcessorModel() + .setBatch( + new BatchLogRecordProcessorModel() + .setExporter( + new LogRecordExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel())))))) + .setTracerProvider( + new TracerProviderModel() + .setLimits( + new SpanLimitsModel() + .setAttributeCountLimit(1) + .setAttributeValueLengthLimit(2) + .setEventCountLimit(3) + .setLinkCountLimit(4) + .setEventAttributeCountLimit(5) + .setLinkAttributeCountLimit(6)) + .setSampler(new SamplerModel().setAlwaysOn(new AlwaysOnSamplerModel())) + .setProcessors( + Collections.singletonList( + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel())))))) + .setMeterProvider( + new MeterProviderModel() + .setReaders( + Collections.singletonList( + new MetricReaderModel() + .setPeriodic( + new PeriodicMetricReaderModel() + .setExporter( + new PushMetricExporterModel() + .setOtlpHttp(new OtlpHttpMetricExporterModel()))))) + .setViews( + Collections.singletonList( + new ViewModel() + .setSelector( + new ViewSelectorModel().setInstrumentName("instrument-name")) + .setStream( + new ViewStreamModel() + .setName("stream-name") + .setAttributeKeys(null))))); + + OpenTelemetrySdk expectedSdk = + OpenTelemetrySdkBuilderUtil.setConfigProvider( + OpenTelemetrySdk.builder() + .setPropagators( + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + W3CBaggagePropagator.getInstance(), + B3Propagator.injectingMultiHeaders(), + B3Propagator.injectingSingleHeader()))) + .setLoggerProvider( + SdkLoggerProvider.builder() + .setResource(expectedResource) + .setLogLimits(() -> + LogLimits.builder() + .setMaxAttributeValueLength(1) + .setMaxNumberOfAttributes(2) + .build()) + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + OtlpHttpLogRecordExporter.builder() + .setComponentLoader(context) + .build()) + .build()) + .build()) + .setTracerProvider( + SdkTracerProvider.builder() + .setResource(expectedResource) + .setSpanLimits( + SpanLimits.builder() + .setMaxNumberOfAttributes(1) + .setMaxAttributeValueLength(2) + .setMaxNumberOfEvents(3) + .setMaxNumberOfLinks(4) + .setMaxNumberOfAttributesPerEvent(5) + .setMaxNumberOfAttributesPerLink(6) + .build()) + .setSampler(alwaysOn()) + .addSpanProcessor( + BatchSpanProcessor.builder( + OtlpHttpSpanExporter.builder() + .setComponentLoader(context) + .build()) + .build()) + .build()) + .setMeterProvider( + SdkMeterProvider.builder() + .setResource(expectedResource) + .registerMetricReader( + PeriodicMetricReader.builder( + OtlpHttpMetricExporter.builder() + .setComponentLoader(context) + .build()) + .build()) + .registerView( + InstrumentSelector.builder().setName("instrument-name").build(), + View.builder().setName("stream-name").build()) + .build()), + SdkConfigProvider.create(DeclarativeConfiguration.toConfigProperties(model))) + .build(); + + cleanup.addCloseable(expectedSdk); + + ExtendedOpenTelemetrySdk sdk = + OpenTelemetryConfigurationFactory.getInstance().create(model, context).getSdk(); + cleanup.addCloseable(sdk); + cleanup.addCloseables(closeables); + + assertThat(sdk).hasToString(expectedSdk.toString()); + + // test that the meter provider is wired through to the tracer and logger providers + Field field = SdkMeterProvider.class.getDeclaredField("sharedState"); + field.setAccessible(true); + + // Lazily initialized + assertThat(sdk) + .extracting("loggerProvider") + .extracting("delegate") + .extracting("sharedState") + .extracting("logRecordProcessor") + .extracting("worker") + .extracting("logProcessorInstrumentation") + .extracting("processedLogs") + .isNull(); + + // Lazily initialized + assertThat(sdk) + .extracting("tracerProvider") + .extracting("delegate") + .extracting("sharedState") + .extracting("activeSpanProcessor") + .extracting("worker") + .extracting("spanProcessorInstrumentation") + .extracting("processedSpans") + .isNull(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java new file mode 100644 index 00000000000..3b23fd94a88 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/PropagatorFactoryTest.java @@ -0,0 +1,132 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.extension.trace.propagation.B3Propagator; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.TextMapPropagatorComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.B3MultiPropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.B3PropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BaggagePropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.PropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TextMapPropagatorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TraceContextPropagatorModel; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class PropagatorFactoryTest { + + private final DeclarativeConfigContext context = + new DeclarativeConfigContext(ComponentLoader.forClassLoader(getClass().getClassLoader())); + + @ParameterizedTest + @MethodSource("createArguments") + void create(PropagatorModel model, ContextPropagators expectedPropagators) { + ContextPropagators propagators = PropagatorFactory.getInstance().create(model, context); + + assertThat(propagators.toString()).isEqualTo(expectedPropagators.toString()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "structured list", + new PropagatorModel() + .setComposite( + Arrays.asList( + new TextMapPropagatorModel() + .setTracecontext(new TraceContextPropagatorModel()), + new TextMapPropagatorModel().setBaggage(new BaggagePropagatorModel()), + new TextMapPropagatorModel().setB3multi(new B3MultiPropagatorModel()), + new TextMapPropagatorModel().setB3(new B3PropagatorModel()))), + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + W3CBaggagePropagator.getInstance(), + B3Propagator.injectingMultiHeaders(), + B3Propagator.injectingSingleHeader()))), + Arguments.argumentSet( + "string list", + new PropagatorModel().setCompositeList("tracecontext,baggage,b3multi,b3 ,none"), + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + W3CBaggagePropagator.getInstance(), + B3Propagator.injectingMultiHeaders(), + B3Propagator.injectingSingleHeader()))), + Arguments.argumentSet( + "structured list and string list", + new PropagatorModel() + .setComposite( + Arrays.asList( + new TextMapPropagatorModel() + .setTracecontext(new TraceContextPropagatorModel()), + new TextMapPropagatorModel().setBaggage(new BaggagePropagatorModel()))) + .setCompositeList("b3multi,b3"), + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + W3CBaggagePropagator.getInstance(), + B3Propagator.injectingMultiHeaders(), + B3Propagator.injectingSingleHeader()))), + Arguments.argumentSet( + "structured list and string list with overlap", + new PropagatorModel() + .setComposite( + Arrays.asList( + new TextMapPropagatorModel() + .setTracecontext(new TraceContextPropagatorModel()), + new TextMapPropagatorModel().setBaggage(new BaggagePropagatorModel()))) + .setCompositeList("tracecontext,b3multi,b3"), + ContextPropagators.create( + TextMapPropagator.composite( + W3CTraceContextPropagator.getInstance(), + W3CBaggagePropagator.getInstance(), + B3Propagator.injectingMultiHeaders(), + B3Propagator.injectingSingleHeader()))), + Arguments.argumentSet( + "spi structured list", + new PropagatorModel() + .setComposite( + Collections.singletonList( + new TextMapPropagatorModel().setExtensionProperty("test", null))), + ContextPropagators.create( + TextMapPropagator.composite( + new TextMapPropagatorComponentProvider.TestTextMapPropagator( + DeclarativeConfigProperties.empty())))), + Arguments.argumentSet( + "spi string list", + new PropagatorModel().setCompositeList("test"), + ContextPropagators.create( + TextMapPropagator.composite( + new TextMapPropagatorComponentProvider.TestTextMapPropagator( + DeclarativeConfigProperties.empty()))))); + } + + @Test + void create_SpiPropagator_Unknown() { + assertThatThrownBy(() -> + PropagatorFactory.getInstance() + .create(new PropagatorModel().setCompositeList("foo"), context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage( + "No component provider detected for io.opentelemetry.context.propagation.TextMapPropagator with name \"foo\"."); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java new file mode 100644 index 00000000000..ea75b676b41 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ResourceFactoryTest.java @@ -0,0 +1,356 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectionModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalResourceDetectorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ResourceModelAccessor; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ResourceFactoryTest { + + private final DeclarativeConfigContext context = + new DeclarativeConfigContext(ComponentLoader.forClassLoader(getClass().getClassLoader())); + + @ParameterizedTest + @MethodSource("createArgs") + void create(ResourceModel model, Resource expectedResource) { + assertThat(ResourceFactory.getInstance().create(model, context)).isEqualTo(expectedResource); + } + + private static Stream createArgs() { + return Stream.of( + Arguments.argumentSet( + "with attributes", + new ResourceModel() + .setAttributes( + Arrays.asList( + new AttributeNameValueModel() + .setName("service.name") + .setValue("my-service"), + new AttributeNameValueModel().setName("key").setValue("val"), + new AttributeNameValueModel().setName("shape").setValue("circle"))), + Resource.getDefault().toBuilder() + .put("shape", "circle") + .put("service.name", "my-service") + .put("key", "val") + .build()), + Arguments.argumentSet( + "with schema url", + new ResourceModel().setSchemaUrl("http://foo"), + Resource.getDefault().toBuilder().setSchemaUrl("http://foo").build()), + Arguments.argumentSet( + "with attributes list", + new ResourceModel().setAttributesList("key1=val1,key2=val2"), + Resource.getDefault().toBuilder().put("key1", "val1").put("key2", "val2").build())); + } + + @ParameterizedTest + @MethodSource("createWithDetectorsArgs") + void createWithDetectors( + @Nullable List included, @Nullable List excluded, Resource expectedResource) { + ResourceModel resourceModel = + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setDetectors( + Arrays.asList( + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("order_first", null), + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("order_second", null), + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("shape_color", null))) + .setAttributes( + new IncludeExcludeModel().setIncluded(included).setExcluded(excluded))); + Resource resource = ResourceFactory.getInstance().create(resourceModel, context); + assertThat(resource).isEqualTo(expectedResource); + } + + private static Stream createWithDetectorsArgs() { + return Stream.of( + Arguments.argumentSet( + "no filters", + null, + null, + Resource.getDefault().toBuilder() + .put("color", "red") + .put("shape", "square") + .put("order", "second") + .build()), + Arguments.argumentSet( + "include color", + Collections.singletonList("color"), + null, + Resource.getDefault().toBuilder().put("color", "red").build()), + Arguments.argumentSet( + "include color shape", + Arrays.asList("color", "shape"), + null, + Resource.getDefault().toBuilder().put("color", "red").put("shape", "square").build()), + Arguments.argumentSet( + "exclude color", + null, + Collections.singletonList("color"), + Resource.getDefault().toBuilder() + .put("shape", "square") + .put("order", "second") + .build()), + Arguments.argumentSet( + "exclude color shape", + null, + Arrays.asList("color", "shape"), + Resource.getDefault().toBuilder().put("order", "second").build()), + Arguments.argumentSet( + "include and exclude same", + Collections.singletonList("color"), + Collections.singletonList("color"), + Resource.getDefault().toBuilder().build()), + Arguments.argumentSet( + "include color shape exclude color", + Arrays.asList("color", "shape"), + Collections.singletonList("color"), + Resource.getDefault().toBuilder().put("shape", "square").build()), + Arguments.argumentSet( + "include c* glob", + Collections.singletonList("c*"), + null, + Resource.getDefault().toBuilder().put("color", "red").build()), + Arguments.argumentSet( + "include c?lor glob", + Collections.singletonList("c?lor"), + null, + Resource.getDefault().toBuilder().put("color", "red").build()), + Arguments.argumentSet( + "exclude c* glob", + null, + Collections.singletonList("c*"), + Resource.getDefault().toBuilder() + .put("shape", "square") + .put("order", "second") + .build()), + Arguments.argumentSet( + "exclude c?lor glob", + null, + Collections.singletonList("c?lor"), + Resource.getDefault().toBuilder() + .put("shape", "square") + .put("order", "second") + .build()), + Arguments.argumentSet( + "include *o* exclude order", + Collections.singletonList("*o*"), + Collections.singletonList("order"), + Resource.getDefault().toBuilder().put("color", "red").build()), + Arguments.argumentSet( + "exclude order", + null, + Collections.singletonList("order"), + Resource.getDefault().toBuilder().put("color", "red").put("shape", "square").build())); + } + + @ParameterizedTest + @MethodSource("entityFilteringCases") + @SuppressLogger(ResourceBuilder.class) + void entityFiltering( + @Nullable List included, + @Nullable List excluded, + Attributes expectedId, + Attributes expectedDescription) { + Entity host = + Entity.builder( + "host", + Attributes.builder().put("host.id", "H1").put("host.region", "west").build()) + .setDescription( + Attributes.builder().put("host.name", "machine").put("host.type", "vm").build()) + .build(); + ResourceModel model = entityDetectorModel(); + ResourceModelAccessor.getDetection(model) + .setAttributes(new IncludeExcludeModel().setIncluded(included).setExcluded(excluded)); + Resource resource = + ResourceFactory.getInstance() + .create( + model, + entityDetectorContext(EntityUtil.createResource(Collections.singletonList(host)))); + + if (!expectedId.equals(host.getId())) { + assertThat(EntityUtil.getEntities(resource)).isEmpty(); + } else { + assertThat(EntityUtil.getEntities(resource)) + .singleElement() + .satisfies(filtered -> { + assertThat(filtered.getId()).isEqualTo(expectedId); + assertThat(filtered.getDescription()).isEqualTo(expectedDescription); + }); + } + assertThat(resource.getAttributes()) + .isEqualTo( + Resource.getDefault().getAttributes().toBuilder() + .putAll(expectedId) + .putAll(expectedDescription) + .build()); + } + + static Stream entityFilteringCases() { + return Stream.of( + Arguments.argumentSet( + "exclude description", + null, + Collections.singletonList("host.name"), + Attributes.builder().put("host.id", "H1").put("host.region", "west").build(), + Attributes.of(AttributeKey.stringKey("host.type"), "vm")), + Arguments.argumentSet( + "exclude one identifying attribute key", + null, + Collections.singletonList("host.id"), + Attributes.of(AttributeKey.stringKey("host.region"), "west"), + Attributes.builder().put("host.name", "machine").put("host.type", "vm").build())); + } + + @ParameterizedTest + @MethodSource("explicitEntityOverrideCases") + @SuppressLogger(ResourceBuilder.class) + void explicitAttributesOverrideEntities(boolean useAttributeList) { + Entity service = + Entity.builder("service", Attributes.of(AttributeKey.stringKey("service.name"), "detected")) + .setDescription(Attributes.of(AttributeKey.stringKey("service.version"), "1.0")) + .build(); + ResourceModel model = entityDetectorModel(); + if (useAttributeList) { + model.setAttributesList("service.name=configured"); + } else { + model.setAttributes( + Collections.singletonList( + new AttributeNameValueModel().setName("service.name").setValue("configured"))); + } + Resource resource = + ResourceFactory.getInstance() + .create( + model, + entityDetectorContext( + EntityUtil.createResource(Collections.singletonList(service)))); + assertThat(EntityUtil.getEntities(resource)).isEmpty(); + assertThat(resource) + .isEqualTo( + Resource.getDefault().toBuilder() + .put("service.name", "configured") + .put("service.version", "1.0") + .build()); + } + + static Stream explicitEntityOverrideCases() { + return Stream.of( + Arguments.argumentSet("explicit attribute list", true), + Arguments.argumentSet("explicit attributes", false)); + } + + private static ResourceModel entityDetectorModel() { + return ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setDetectors( + Collections.singletonList( + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("entity", null)))); + } + + private static DeclarativeConfigContext entityDetectorContext(Resource resource) { + ComponentProvider provider = mock(ComponentProvider.class); + when(provider.getType()).thenAnswer(unused -> Resource.class); + when(provider.getName()).thenReturn("entity"); + when(provider.create(any())).thenReturn(resource); + ComponentLoader loader = mock(ComponentLoader.class); + when(loader.load(ComponentProvider.class)).thenReturn(Collections.singletonList(provider)); + return new DeclarativeConfigContext(loader); + } + + @ParameterizedTest + @MethodSource("createInvalidDetectorsArgs") + void createWithDetectors_Invalid(ResourceModel model, String expectedMessage) { + assertThatThrownBy(() -> ResourceFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + private static Stream createInvalidDetectorsArgs() { + return Stream.of( + Arguments.argumentSet( + "unknown detector", + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setDetectors( + Collections.singletonList( + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("foo", null)))), + "No component provider detected for io.opentelemetry.sdk.resources.Resource with name \"foo\"."), + Arguments.argumentSet( + "detector multiple entries", + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setDetectors( + Collections.singletonList( + new ExperimentalResourceDetectorModel() + .setAdditionalProperty("foo", null) + .setAdditionalProperty("bar", null)))), + "resource detector must have exactly one entry but has 2: [foo,bar]"), + Arguments.argumentSet( + "detector no entries", + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setDetectors( + Collections.singletonList(new ExperimentalResourceDetectorModel()))), + "resource detector must have exactly one entry but has 0"), + Arguments.argumentSet( + "included empty list", + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setAttributes( + new IncludeExcludeModel() + .setIncluded(Collections.emptyList()) + .setExcluded(null))), + "included must not be empty"), + Arguments.argumentSet( + "excluded empty list", + ResourceModelAccessor.setDetection( + new ResourceModel(), + new ExperimentalResourceDetectionModel() + .setAttributes( + new IncludeExcludeModel() + .setIncluded(null) + .setExcluded(Collections.emptyList()))), + "excluded must not be empty")); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SamplerFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SamplerFactoryTest.java new file mode 100644 index 00000000000..453ea879773 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SamplerFactoryTest.java @@ -0,0 +1,250 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.SamplerComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysOffSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysOnSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysRecordSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ParentBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TraceIdRatioBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableAlwaysOffSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableAlwaysOnSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableParentThresholdSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableProbabilitySamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableRuleBasedSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalJaegerRemoteSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.SamplerModelAccessor; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.AlwaysRecordSampler; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.ComposableSampler; +import io.opentelemetry.sdk.extension.incubator.trace.samplers.CompositeSampler; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSampler; +import io.opentelemetry.sdk.trace.samplers.ParentBasedSamplerBuilder; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.io.Closeable; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +// Suppress logs from JaegerRemoteSampler +@SuppressLogger( + loggerName = "io.opentelemetry.sdk.extension.trace.jaeger.sampler.OkHttpGrpcService") +@SuppressLogger(ParentBasedSamplerBuilder.class) +@SuppressLogger(JaegerRemoteSampler.class) +class SamplerFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private final DeclarativeConfigContext context = + new DeclarativeConfigContext(ComponentLoader.forClassLoader(getClass().getClassLoader())); + + @ParameterizedTest + @MethodSource("createArguments") + void create(@Nullable SamplerModel model, Sampler expectedSampler) { + // // All samplers are Closeable - ensure these get cleaned up + cleanup.addCloseable(expectedSampler); + + List closeables = new ArrayList<>(); + Sampler sampler = SamplerFactory.getInstance().create(model, context); + cleanup.addCloseables(closeables); + + assertThat(sampler.getDescription()).isEqualTo(expectedSampler.getDescription()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "always_on", + new SamplerModel().setAlwaysOn(new AlwaysOnSamplerModel()), + Sampler.alwaysOn()), + Arguments.argumentSet( + "always_off", + new SamplerModel().setAlwaysOff(new AlwaysOffSamplerModel()), + Sampler.alwaysOff()), + Arguments.argumentSet( + "trace_id_ratio_based default", + new SamplerModel().setTraceIdRatioBased(new TraceIdRatioBasedSamplerModel()), + Sampler.traceIdRatioBased(1.0d)), + Arguments.argumentSet( + "trace_id_ratio_based with ratio", + new SamplerModel() + .setTraceIdRatioBased(new TraceIdRatioBasedSamplerModel().setRatio(0.5d)), + Sampler.traceIdRatioBased(0.5)), + Arguments.argumentSet( + "parent_based default", + new SamplerModel().setParentBased(new ParentBasedSamplerModel()), + Sampler.parentBased(Sampler.alwaysOn())), + Arguments.argumentSet( + "parent_based with options", + new SamplerModel() + .setParentBased( + new ParentBasedSamplerModel() + .setRoot( + new SamplerModel() + .setTraceIdRatioBased( + new TraceIdRatioBasedSamplerModel().setRatio(0.1d))) + .setRemoteParentSampled( + new SamplerModel() + .setTraceIdRatioBased( + new TraceIdRatioBasedSamplerModel().setRatio(0.2d))) + .setRemoteParentNotSampled( + new SamplerModel() + .setTraceIdRatioBased( + new TraceIdRatioBasedSamplerModel().setRatio(0.3d))) + .setLocalParentSampled( + new SamplerModel() + .setTraceIdRatioBased( + new TraceIdRatioBasedSamplerModel().setRatio(0.4d))) + .setLocalParentNotSampled( + new SamplerModel() + .setTraceIdRatioBased( + new TraceIdRatioBasedSamplerModel().setRatio(0.5d)))), + Sampler.parentBasedBuilder(Sampler.traceIdRatioBased(0.1d)) + .setRemoteParentSampled(Sampler.traceIdRatioBased(0.2d)) + .setRemoteParentNotSampled(Sampler.traceIdRatioBased(0.3d)) + .setLocalParentSampled(Sampler.traceIdRatioBased(0.4d)) + .setLocalParentNotSampled(Sampler.traceIdRatioBased(0.5d)) + .build()), + Arguments.argumentSet( + "always_record", + new SamplerModel() + .setAlwaysRecord( + new AlwaysRecordSamplerModel() + .setRoot( + new SamplerModel() + .setTraceIdRatioBased( + new TraceIdRatioBasedSamplerModel().setRatio(0.1d)))), + AlwaysRecordSampler.create(Sampler.traceIdRatioBased(0.1d))), + Arguments.argumentSet( + "jaeger_remote", + SamplerModelAccessor.setJaegerRemote( + new SamplerModel(), + new ExperimentalJaegerRemoteSamplerModel() + .setEndpoint("http://jaeger-remote-endpoint") + .setInterval(10_000) + .setInitialSampler( + new SamplerModel().setAlwaysOff(new AlwaysOffSamplerModel()))), + JaegerRemoteSampler.builder() + .setEndpoint("http://jaeger-remote-endpoint") + .setPollingInterval(Duration.ofSeconds(10)) + .setInitialSampler(Sampler.alwaysOff()) + .build()), + Arguments.argumentSet( + "composite/development always_on", + SamplerModelAccessor.setComposite( + new SamplerModel(), + new ExperimentalComposableSamplerModel() + .setAlwaysOn(new ExperimentalComposableAlwaysOnSamplerModel())), + CompositeSampler.wrap(ComposableSampler.alwaysOn())), + Arguments.argumentSet( + "composite/development always_off", + SamplerModelAccessor.setComposite( + new SamplerModel(), + new ExperimentalComposableSamplerModel() + .setAlwaysOff(new ExperimentalComposableAlwaysOffSamplerModel())), + CompositeSampler.wrap(ComposableSampler.alwaysOff())), + Arguments.argumentSet( + "composite/development probability", + SamplerModelAccessor.setComposite( + new SamplerModel(), + new ExperimentalComposableSamplerModel() + .setProbability( + new ExperimentalComposableProbabilitySamplerModel().setRatio(0.5))), + CompositeSampler.wrap(ComposableSampler.probability(0.5))), + Arguments.argumentSet( + "composite/development rule_based", + SamplerModelAccessor.setComposite( + new SamplerModel(), + new ExperimentalComposableSamplerModel() + .setRuleBased(new ExperimentalComposableRuleBasedSamplerModel())), + CompositeSampler.wrap(ComposableSampler.ruleBasedBuilder().build())), + Arguments.argumentSet( + "composite/development parent_threshold", + SamplerModelAccessor.setComposite( + new SamplerModel(), + new ExperimentalComposableSamplerModel() + .setParentThreshold( + new ExperimentalComposableParentThresholdSamplerModel() + .setRoot( + new ExperimentalComposableSamplerModel() + .setAlwaysOn( + new ExperimentalComposableAlwaysOnSamplerModel())))), + CompositeSampler.wrap( + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn())))); + } + + @ParameterizedTest + @MethodSource("createInvalidArguments") + void createInvalid(SamplerModel model, String expectedMessage) { + assertThatThrownBy(() -> SamplerFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .extracting(throwable -> throwable.getCause() == null ? throwable : throwable.getCause()) + .extracting(Throwable::getMessage) + .isEqualTo(expectedMessage); + } + + private static Stream createInvalidArguments() { + return Stream.of( + Arguments.argumentSet( + "jaeger_remote missing endpoint", + SamplerModelAccessor.setJaegerRemote( + new SamplerModel(), new ExperimentalJaegerRemoteSamplerModel()), + "jaeger remote sampler endpoint is required"), + Arguments.argumentSet( + "jaeger_remote missing initialSampler", + SamplerModelAccessor.setJaegerRemote( + new SamplerModel(), + new ExperimentalJaegerRemoteSamplerModel() + .setEndpoint("http://jaeger-remote-endpoint")), + "jaeger remote sampler initial_sampler is required"), + Arguments.argumentSet( + "parent_threshold missing root", + SamplerModelAccessor.setComposite( + new SamplerModel(), + new ExperimentalComposableSamplerModel() + .setParentThreshold(new ExperimentalComposableParentThresholdSamplerModel())), + "parent threshold sampler root is required but is null"), + Arguments.argumentSet( + "always_record missing root", + new SamplerModel().setAlwaysRecord(new AlwaysRecordSamplerModel()), + "always_record sampler .root is required"), + Arguments.argumentSet( + "unknown component provider", + new SamplerModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value1")), + "No component provider detected for io.opentelemetry.sdk.trace.samplers.Sampler with name \"unknown_key\".")); + } + + @Test + void create_SpiExporter_Valid() { + Sampler sampler = + SamplerFactory.getInstance() + .create( + new SamplerModel() + .setExtensionProperty("test", Collections.singletonMap("key1", "value1")), + context); + assertThat(sampler).isInstanceOf(SamplerComponentProvider.TestSampler.class); + assertThat(((SamplerComponentProvider.TestSampler) sampler).config.getString("key1")) + .isEqualTo("value1"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ServiceResourceDetectorTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ServiceResourceDetectorTest.java new file mode 100644 index 00000000000..9d144f62454 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ServiceResourceDetectorTest.java @@ -0,0 +1,71 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.Objects; +import java.util.UUID; +import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.ClearSystemProperty; +import org.junitpioneer.jupiter.SetSystemProperty; + +class ServiceResourceDetectorTest { + + @Test + void getTypeAndName() { + ServiceResourceDetector detector = new ServiceResourceDetector(); + + assertThat(detector.getType()).isEqualTo(Resource.class); + assertThat(detector.getName()).isEqualTo("service"); + } + + @Test + @SetSystemProperty(key = "otel.service.name", value = "test") + void create_SystemPropertySet() { + Resource resource = new ServiceResourceDetector().create(DeclarativeConfigProperties.empty()); + Attributes attributes = resource.getAttributes(); + assertThat(attributes.get(AttributeKey.stringKey("service.name"))).isEqualTo("test"); + String serviceInstanceId = + Objects.requireNonNull(attributes.get(AttributeKey.stringKey("service.instance.id"))); + assertThatCode(() -> UUID.fromString(serviceInstanceId)).doesNotThrowAnyException(); + assertThat(EntityUtil.getEntities(resource)) + .containsExactlyInAnyOrder( + Entity.builder("service", Attributes.of(AttributeKey.stringKey("service.name"), "test")) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build(), + Entity.builder( + "service.instance", + Attributes.of(AttributeKey.stringKey("service.instance.id"), serviceInstanceId)) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build()); + } + + @Test + @ClearSystemProperty(key = "otel.service.name") + void create_NoSystemProperty() { + Resource resource = new ServiceResourceDetector().create(DeclarativeConfigProperties.empty()); + Attributes attributes = resource.getAttributes(); + assertThat(attributes.get(AttributeKey.stringKey("service.name"))).isNull(); + String serviceInstanceId = + Objects.requireNonNull(attributes.get(AttributeKey.stringKey("service.instance.id"))); + assertThatCode(() -> UUID.fromString(serviceInstanceId)).doesNotThrowAnyException(); + assertThat(EntityUtil.getEntities(resource)) + .containsExactly( + Entity.builder( + "service.instance", + Attributes.of(AttributeKey.stringKey("service.instance.id"), serviceInstanceId)) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build()); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java new file mode 100644 index 00000000000..f3ede6961c2 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanExporterFactoryTest.java @@ -0,0 +1,297 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.autoconfigure.declarativeconfig.FileConfigTestUtil.createTempFileWithContent; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.logging.LoggingSpanExporter; +import io.opentelemetry.exporter.logging.otlp.internal.traces.OtlpStdoutSpanExporter; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.SpanExporterComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ConsoleExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.GrpcTlsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.HttpTlsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.NameStringValuePairModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpGrpcExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalOtlpFileExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.SpanExporterModelAccessor; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSampler; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.io.IOException; +import java.nio.file.Path; +import java.security.cert.CertificateEncodingException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +@SuppressLogger(JaegerRemoteSampler.class) +class SpanExporterFactoryTest { + + @RegisterExtension + static final SelfSignedCertificateExtension serverTls = new SelfSignedCertificateExtension(); + + @RegisterExtension + static final SelfSignedCertificateExtension clientTls = new SelfSignedCertificateExtension(); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(SpanExporterFactoryTest.class.getClassLoader())); + + private String certificatePath; + private String clientKeyPath; + private String clientCertificatePath; + + @BeforeAll + void setupTls(@TempDir Path tempDir) throws CertificateEncodingException, IOException { + certificatePath = + createTempFileWithContent( + tempDir, "certificate.cert", serverTls.certificate().getEncoded()); + clientKeyPath = + createTempFileWithContent(tempDir, "clientKey.key", clientTls.privateKey().getEncoded()); + clientCertificatePath = + createTempFileWithContent( + tempDir, "clientCertificate.cert", clientTls.certificate().getEncoded()); + } + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create(SpanExporterModel model, SpanExporter expectedExporter) { + cleanup.addCloseable(expectedExporter); + SpanExporter exporter = SpanExporterFactory.getInstance().create(model, context); + cleanup.addCloseable(exporter); + assertThat(exporter.toString()).isEqualTo(expectedExporter.toString()); + } + + Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "otlp_http default", + new SpanExporterModel().setOtlpHttp(new OtlpHttpExporterModel()), + OtlpHttpSpanExporter.getDefault().toBuilder().setComponentLoader(context).build()), + Arguments.argumentSet( + "otlp_http with options", + new SpanExporterModel() + .setOtlpHttp( + new OtlpHttpExporterModel() + .setEndpoint("http://example:4318/v1/traces") + .setHeaders( + Arrays.asList( + new NameStringValuePairModel().setName("key1").setValue("value1"), + new NameStringValuePairModel().setName("key2").setValue("value2"))) + .setCompression("gzip") + .setTimeout(15_000) + .setMaxRequestSize(1234) + .setTls( + new HttpTlsModel() + .setCaFile(certificatePath) + .setKeyFile(clientKeyPath) + .setCertFile(clientCertificatePath))), + OtlpHttpSpanExporter.builder() + .setEndpoint("http://example:4318/v1/traces") + .addHeader("key1", "value1") + .addHeader("key2", "value2") + .setTimeout(Duration.ofSeconds(15)) + .setCompression("gzip") + .setMaxRequestBodySize(1234) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_http max_request_size 0", + new SpanExporterModel().setOtlpHttp(new OtlpHttpExporterModel().setMaxRequestSize(0)), + OtlpHttpSpanExporter.getDefault().toBuilder() + .setMaxRequestBodySize(Long.MAX_VALUE) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_grpc default", + new SpanExporterModel().setOtlpGrpc(new OtlpGrpcExporterModel()), + OtlpGrpcSpanExporter.getDefault().toBuilder().setComponentLoader(context).build()), + Arguments.argumentSet( + "otlp_grpc with options", + new SpanExporterModel() + .setOtlpGrpc( + new OtlpGrpcExporterModel() + .setEndpoint("http://example:4317") + .setHeaders( + Arrays.asList( + new NameStringValuePairModel().setName("key1").setValue("value1"), + new NameStringValuePairModel().setName("key2").setValue("value2"))) + .setCompression("gzip") + .setTimeout(15_000) + .setMaxRequestSize(1234) + .setTls( + new GrpcTlsModel() + .setCaFile(certificatePath) + .setKeyFile(clientKeyPath) + .setCertFile(clientCertificatePath))), + OtlpGrpcSpanExporter.builder() + .setEndpoint("http://example:4317") + .addHeader("key1", "value1") + .addHeader("key2", "value2") + .setTimeout(Duration.ofSeconds(15)) + .setCompression("gzip") + .setMaxRequestMessageSize(1234) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "otlp_grpc max_request_size 0", + new SpanExporterModel().setOtlpGrpc(new OtlpGrpcExporterModel().setMaxRequestSize(0)), + OtlpGrpcSpanExporter.getDefault().toBuilder() + .setMaxRequestMessageSize(Long.MAX_VALUE) + .setComponentLoader(context) + .build()), + Arguments.argumentSet( + "console", + new SpanExporterModel().setConsole(new ConsoleExporterModel()), + LoggingSpanExporter.create()), + Arguments.argumentSet( + "otlp_file/development", + SpanExporterModelAccessor.setOtlpFile( + new SpanExporterModel(), new ExperimentalOtlpFileExporterModel()), + OtlpStdoutSpanExporter.builder().build())); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(SpanExporterModel model, String expectedMessage) { + assertThatThrownBy(() -> SpanExporterFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "unknown component provider", + new SpanExporterModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value1")), + "No component provider detected for io.opentelemetry.sdk.trace.export.SpanExporter with name \"unknown_key\"."), + Arguments.argumentSet( + "otlp_http negative max_request_size", + new SpanExporterModel().setOtlpHttp(new OtlpHttpExporterModel().setMaxRequestSize(-1)), + "Error configuring io.opentelemetry.sdk.trace.export.SpanExporter with name \"otlp_http\""), + Arguments.argumentSet( + "otlp_grpc negative max_request_size", + new SpanExporterModel().setOtlpGrpc(new OtlpGrpcExporterModel().setMaxRequestSize(-1)), + "Error configuring io.opentelemetry.sdk.trace.export.SpanExporter with name \"otlp_grpc\"")); + } + + @Test + void create_SpiExporter_Valid() { + SpanExporter spanExporter = + SpanExporterFactory.getInstance() + .create( + new SpanExporterModel() + .setExtensionProperty("test", Collections.singletonMap("key1", "value1")), + context); + assertThat(spanExporter).isInstanceOf(SpanExporterComponentProvider.TestSpanExporter.class); + assertThat( + ((SpanExporterComponentProvider.TestSpanExporter) spanExporter) + .config.getString("key1")) + .isEqualTo("value1"); + } + + @Test + void create_Customizer() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addSpanExporterCustomizer( + SpanExporter.class, + (exporter, properties) -> + SpanExporter.composite(exporter, LoggingSpanExporter.create())); + + SpanExporter result = + SpanExporterFactory.getInstance() + .create(new SpanExporterModel().setConsole(new ConsoleExporterModel()), context); + cleanup.addCloseable(result); + + assertThat(result.toString()).contains("LoggingSpanExporter"); + } + + @Test + void create_Customizer_TypeSafe() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addSpanExporterCustomizer( + OtlpGrpcSpanExporter.class, + (exporter, properties) -> + exporter.toBuilder().setTimeout(Duration.ofSeconds(42)).build()); + + SpanExporter result = + SpanExporterFactory.getInstance() + .create(new SpanExporterModel().setOtlpGrpc(new OtlpGrpcExporterModel()), context); + cleanup.addCloseable(result); + + assertThat(result).isInstanceOf(OtlpGrpcSpanExporter.class); + assertThat(result.toString()).contains("timeoutNanos=42000000000"); + } + + @Test + void create_Customizer_TypeMismatch() { + AtomicInteger callCount = new AtomicInteger(0); + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addSpanExporterCustomizer( + OtlpGrpcSpanExporter.class, + (exporter, properties) -> { + callCount.incrementAndGet(); + return exporter; + }); + + SpanExporter result = + SpanExporterFactory.getInstance() + .create(new SpanExporterModel().setConsole(new ConsoleExporterModel()), context); + cleanup.addCloseable(result); + + assertThat(callCount.get()).isEqualTo(0); + } + + @Test + void create_Customizer_ReturnsNull() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + context + .getBuilder() + .addSpanExporterCustomizer(SpanExporter.class, (exporter, properties) -> null); + + assertThatThrownBy(() -> + SpanExporterFactory.getInstance() + .create(new SpanExporterModel().setConsole(new ConsoleExporterModel()), context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessageContaining("Customizer returned null for SpanExporter: console"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsFactoryTest.java new file mode 100644 index 00000000000..87ee51e44f6 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanLimitsFactoryTest.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel; +import io.opentelemetry.sdk.trace.SpanLimits; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class SpanLimitsFactoryTest { + + @ParameterizedTest + @MethodSource("createArguments") + void create(SpanLimitsAndAttributeLimits model, SpanLimits expectedSpanLimits) { + assertThat(SpanLimitsFactory.getInstance().create(model, mock(DeclarativeConfigContext.class))) + .isEqualTo(expectedSpanLimits); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "null limits", + SpanLimitsAndAttributeLimits.create(null, null), + SpanLimits.getDefault()), + Arguments.argumentSet( + "empty models", + SpanLimitsAndAttributeLimits.create(new AttributeLimitsModel(), new SpanLimitsModel()), + SpanLimits.getDefault()), + Arguments.argumentSet( + "attribute limits only", + SpanLimitsAndAttributeLimits.create( + new AttributeLimitsModel() + .setAttributeCountLimit(1) + .setAttributeValueLengthLimit(2), + new SpanLimitsModel()), + SpanLimits.builder().setMaxNumberOfAttributes(1).setMaxAttributeValueLength(2).build()), + Arguments.argumentSet( + "span limits override attribute limits", + SpanLimitsAndAttributeLimits.create( + new AttributeLimitsModel() + .setAttributeCountLimit(1) + .setAttributeValueLengthLimit(2), + new SpanLimitsModel() + .setAttributeCountLimit(3) + .setAttributeValueLengthLimit(4) + .setEventCountLimit(5) + .setLinkCountLimit(6) + .setEventAttributeCountLimit(7) + .setLinkAttributeCountLimit(8)), + SpanLimits.builder() + .setMaxNumberOfAttributes(3) + .setMaxAttributeValueLength(4) + .setMaxNumberOfEvents(5) + .setMaxNumberOfLinks(6) + .setMaxNumberOfAttributesPerEvent(7) + .setMaxNumberOfAttributesPerLink(8) + .build())); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanProcessorFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanProcessorFactoryTest.java new file mode 100644 index 00000000000..ca37ee23a89 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/SpanProcessorFactoryTest.java @@ -0,0 +1,134 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.SpanProcessorComponentProvider; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SimpleSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.trace.SpanProcessor; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import java.time.Duration; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class SpanProcessorFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(SpanProcessorFactoryTest.class.getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createTestCases") + void create(SpanProcessorModel model, SpanProcessor expectedProcessor) { + cleanup.addCloseable(expectedProcessor); + SpanProcessor processor = SpanProcessorFactory.getInstance().create(model, context); + cleanup.addCloseable(processor); + assertThat(processor.toString()).isEqualTo(expectedProcessor.toString()); + } + + private static Stream createTestCases() { + return Stream.of( + Arguments.argumentSet( + "batch default", + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel().setOtlpHttp(new OtlpHttpExporterModel()))), + BatchSpanProcessor.builder( + OtlpHttpSpanExporter.builder().setComponentLoader(context).build()) + .build()), + Arguments.argumentSet( + "batch with options", + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel().setOtlpHttp(new OtlpHttpExporterModel())) + .setScheduleDelay(1) + .setMaxExportBatchSize(2) + .setExportTimeout(3)), + BatchSpanProcessor.builder( + OtlpHttpSpanExporter.builder().setComponentLoader(context).build()) + .setScheduleDelay(Duration.ofMillis(1)) + .setMaxExportBatchSize(2) + .setExporterTimeout(Duration.ofMillis(3)) + .build()), + Arguments.argumentSet( + "simple", + new SpanProcessorModel() + .setSimple( + new SimpleSpanProcessorModel() + .setExporter( + new SpanExporterModel().setOtlpHttp(new OtlpHttpExporterModel()))), + SimpleSpanProcessor.create( + OtlpHttpSpanExporter.builder().setComponentLoader(context).build()))); + } + + @ParameterizedTest + @MethodSource("createInvalidTestCases") + void create_Invalid(SpanProcessorModel model, String expectedMessage) { + assertThatThrownBy(() -> SpanProcessorFactory.getInstance().create(model, context)) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage(expectedMessage); + } + + private static Stream createInvalidTestCases() { + return Stream.of( + Arguments.argumentSet( + "batch missing exporter", + new SpanProcessorModel().setBatch(new BatchSpanProcessorModel()), + "batch span processor exporter is required but is null"), + Arguments.argumentSet( + "simple missing exporter", + new SpanProcessorModel().setSimple(new SimpleSpanProcessorModel()), + "simple span processor exporter is required but is null"), + Arguments.argumentSet( + "unknown component provider", + new SpanProcessorModel() + .setExtensionProperty("unknown_key", Collections.singletonMap("key1", "value1")), + "No component provider detected for io.opentelemetry.sdk.trace.SpanProcessor with name \"unknown_key\".")); + } + + @Test + void create_SpiProcessor_Valid() { + SpanProcessor spanProcessor = + SpanProcessorFactory.getInstance() + .create( + new SpanProcessorModel() + .setExtensionProperty("test", Collections.singletonMap("key1", "value1")), + context); + assertThat(spanProcessor).isInstanceOf(SpanProcessorComponentProvider.TestSpanProcessor.class); + assertThat( + ((SpanProcessorComponentProvider.TestSpanProcessor) spanProcessor) + .config.getString("key1")) + .isEqualTo("value1"); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java new file mode 100644 index 00000000000..d633fbb9da4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TestDeclarativeConfigurationCustomizerProvider.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeNameValueModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeTypeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ResourceModel; +import java.util.ArrayList; +import java.util.List; + +public class TestDeclarativeConfigurationCustomizerProvider + implements DeclarativeConfigurationCustomizerProvider { + + @Override + public void customize(DeclarativeConfigurationCustomizer customizer) { + customizer.addModelCustomizer(model -> { + ResourceModel resource = model.getResource(); + if (resource == null) { + resource = new ResourceModel(); + model.setResource(resource); + } + List attributes = resource.getAttributes(); + if (attributes == null) { + attributes = new ArrayList<>(); + resource.setAttributes(attributes); + } + attributes.add( + new AttributeNameValueModel() + .setName("foo") + .setType(AttributeTypeModel.STRING) + .setValue("bar")); + attributes.add( + new AttributeNameValueModel() + .setName("color") + .setType(AttributeTypeModel.STRING) + .setValue("blue")); + return model; + }); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactoryTest.java new file mode 100644 index 00000000000..d3b9e1d3900 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/TracerProviderFactoryTest.java @@ -0,0 +1,143 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.trace.samplers.Sampler.alwaysOn; + +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.otlp.http.trace.OtlpHttpSpanExporter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AlwaysOnSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AttributeLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.BatchSpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OtlpHttpExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanExporterModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanLimitsModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.SpanProcessorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.TracerProviderModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalTracerConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalTracerConfiguratorModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalTracerMatcherAndConfigModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.TracerProviderModelAccessor; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.SpanLimits; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.internal.TracerConfig; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class TracerProviderFactoryTest { + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + private static final DeclarativeConfigContext context = + new DeclarativeConfigContext( + ComponentLoader.forClassLoader(TracerProviderFactoryTest.class.getClassLoader())); + + @BeforeEach + void setup() { + context.setBuilder(new DeclarativeConfigurationBuilder()); + } + + @ParameterizedTest + @MethodSource("createArguments") + void create(TracerProviderAndAttributeLimits model, SdkTracerProvider expectedProvider) { + List closeables = new ArrayList<>(); + cleanup.addCloseable(expectedProvider); + + SdkTracerProvider provider = TracerProviderFactory.getInstance().create(model, context).build(); + cleanup.addCloseable(provider); + cleanup.addCloseables(closeables); + + assertThat(provider.toString()).isEqualTo(expectedProvider.toString()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "null limits", + TracerProviderAndAttributeLimits.create(null, null), + SdkTracerProvider.builder().build()), + Arguments.argumentSet( + "empty models", + TracerProviderAndAttributeLimits.create( + new AttributeLimitsModel(), new TracerProviderModel()), + SdkTracerProvider.builder().build()), + Arguments.argumentSet( + "full configuration", + TracerProviderAndAttributeLimits.create( + new AttributeLimitsModel(), + TracerProviderModelAccessor.setTracerConfigurator( + new TracerProviderModel() + .setLimits( + new SpanLimitsModel() + .setAttributeCountLimit(1) + .setAttributeValueLengthLimit(2) + .setEventCountLimit(3) + .setLinkCountLimit(4) + .setEventAttributeCountLimit(5) + .setLinkAttributeCountLimit(6)) + .setSampler(new SamplerModel().setAlwaysOn(new AlwaysOnSamplerModel())) + .setProcessors( + Collections.singletonList( + new SpanProcessorModel() + .setBatch( + new BatchSpanProcessorModel() + .setExporter( + new SpanExporterModel() + .setOtlpHttp(new OtlpHttpExporterModel()))))), + new ExperimentalTracerConfiguratorModel() + .setDefaultConfig(new ExperimentalTracerConfigModel().setEnabled(false)) + .setTracers( + Collections.singletonList( + new ExperimentalTracerMatcherAndConfigModel() + .setName("foo") + .setConfig( + new ExperimentalTracerConfigModel().setEnabled(true)))))), + addTracerConfigurator( + SdkTracerProvider.builder(), + ScopeConfigurator.builder() + .setDefault(TracerConfig.disabled()) + .addCondition( + ScopeConfiguratorBuilder.nameMatchesGlob("foo"), TracerConfig.enabled()) + .build()) + .setSpanLimits( + SpanLimits.builder() + .setMaxNumberOfAttributes(1) + .setMaxAttributeValueLength(2) + .setMaxNumberOfEvents(3) + .setMaxNumberOfLinks(4) + .setMaxNumberOfAttributesPerEvent(5) + .setMaxNumberOfAttributesPerLink(6) + .build()) + .setSampler(alwaysOn()) + .addSpanProcessor( + BatchSpanProcessor.builder( + OtlpHttpSpanExporter.builder().setComponentLoader(context).build()) + .build()) + .build())); + } + + private static SdkTracerProviderBuilder addTracerConfigurator( + SdkTracerProviderBuilder builder, ScopeConfigurator tracerConfigurator) { + SdkTracerProviderUtil.setTracerConfigurator(builder, tracerConfigurator); + return builder; + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ViewFactoryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ViewFactoryTest.java new file mode 100644 index 00000000000..90d6a514957 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/ViewFactoryTest.java @@ -0,0 +1,82 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.AggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ExplicitBucketHistogramAggregationModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.IncludeExcludeModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.ViewStreamModel; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions; +import io.opentelemetry.sdk.metrics.View; +import java.util.Arrays; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ViewFactoryTest { + + @ParameterizedTest + @MethodSource("createArguments") + void create(ViewStreamModel model, View expectedView) { + View view = ViewFactory.getInstance().create(model, mock(DeclarativeConfigContext.class)); + assertThat(view.toString()).isEqualTo(expectedView.toString()); + } + + private static Stream createArguments() { + return Stream.of( + Arguments.argumentSet( + "defaults", new ViewStreamModel().setAttributeKeys(null), View.builder().build()), + // https://github.com/open-telemetry/opentelemetry-java/issues/8337 + Arguments.argumentSet( + "included only no excluded", + new ViewStreamModel() + .setAttributeKeys( + new IncludeExcludeModel() + .setIncluded( + Arrays.asList( + "url.full", "http.request.method", "http.response.status_code"))), + View.builder() + .setAttributeFilter( + IncludeExcludePredicate.createPatternMatching( + Arrays.asList( + "url.full", "http.request.method", "http.response.status_code"), + null)) + .build()), + Arguments.argumentSet( + "full configuration", + new ViewStreamModel() + .setName("name") + .setDescription("description") + .setAttributeKeys( + new IncludeExcludeModel() + .setIncluded(Arrays.asList("foo", "bar")) + .setExcluded(Collections.singletonList("baz"))) + .setAggregation( + new AggregationModel() + .setExplicitBucketHistogram( + new ExplicitBucketHistogramAggregationModel() + .setBoundaries(Arrays.asList(1.0, 2.0)))), + View.builder() + .setName("name") + .setDescription("description") + .setAttributeFilter( + IncludeExcludePredicate.createPatternMatching( + Arrays.asList("foo", "bar"), Collections.singletonList("baz"))) + .setAggregation( + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, 2.0)) + .build())) + .build())); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java new file mode 100644 index 00000000000..170b1bd0b2b --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/YamlDeclarativeConfigPropertiesTest.java @@ -0,0 +1,383 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig; + +import static io.opentelemetry.api.config.DeclarativeConfigProperties.empty; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableSet; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +@SuppressLogger(YamlDeclarativeConfigProperties.class) +class YamlDeclarativeConfigPropertiesTest { + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(YamlDeclarativeConfigProperties.class); + + private static final String extendedSchema = + "file_format: \"1.2\"\n" + + "disabled: false\n" + + "\n" + + "resource:\n" + + " attributes:\n" + + " - name: service.name\n" + + " value: \"unknown_service\"\n" + + "\n" + + "other:\n" + + " str_key: str_value\n" + + " int_key: 1\n" + + " float_key: 1.1\n" + + " bool_key: true\n" + + " null_key:\n" + + " str_list_key: [val1, val2]\n" + + " int_list_key: [1, 2]\n" + + " float_list_key: [1.1, 2.2]\n" + + " bool_list_key: [true, false]\n" + + " mixed_list_key: [val1, 1, 1.1, true]\n" + + " map_key:\n" + + " str_key1: str_value1\n" + + " int_key1: 2\n" + + " map_key1:\n" + + " str_key2: str_value2\n" + + " int_key2: 3\n" + + " list_key:\n" + + " - str_key1: str_value1\n" + + " int_key1: 2\n" + + " map_key1:\n" + + " str_key2: str_value2\n" + + " int_key2: 3\n" + + " - str_key1: str_value1\n" + + " int_key1: 2"; + + private DeclarativeConfigProperties structuredConfigProps; + + @BeforeEach + void setup() { + OpenTelemetryConfigurationModel configuration = + DeclarativeConfiguration.parse( + new ByteArrayInputStream(extendedSchema.getBytes(StandardCharsets.UTF_8))); + structuredConfigProps = DeclarativeConfiguration.toConfigProperties(configuration); + } + + @Test + void configurationSchema() { + // Validate can read declarative configuration schema properties + assertThat(structuredConfigProps.getString("file_format")).isEqualTo("1.2"); + DeclarativeConfigProperties resourceProps = structuredConfigProps.getStructured("resource"); + assertThat(resourceProps).isNotNull(); + List resourceAttributesList = + resourceProps.getStructuredList("attributes"); + assertThat(resourceAttributesList) + .isNotNull() + .satisfiesExactly(attributeEntry -> { + assertThat(attributeEntry.getString("name")).isEqualTo("service.name"); + assertThat(attributeEntry.getString("value")).isEqualTo("unknown_service"); + }); + } + + @Test + void additionalProperties() { + assertThat(structuredConfigProps.getPropertyKeys()) + .isEqualTo(ImmutableSet.of("file_format", "disabled", "resource", "other")); + + // Validate can read properties not part of configuration schema + // .other + DeclarativeConfigProperties otherProps = structuredConfigProps.getStructured("other"); + assertThat(otherProps).isNotNull(); + assertThat(otherProps.getPropertyKeys()) + .isEqualTo( + ImmutableSet.of( + "str_key", + "int_key", + "float_key", + "bool_key", + "null_key", + "str_list_key", + "int_list_key", + "float_list_key", + "bool_list_key", + "mixed_list_key", + "map_key", + "list_key")); + assertThat(otherProps.getString("str_key")).isEqualTo("str_value"); + assertThat(otherProps.getInt("int_key")).isEqualTo(1); + assertThat(otherProps.getLong("int_key")).isEqualTo(1); + assertThat(otherProps.getDouble("float_key")).isEqualTo(1.1); + assertThat(otherProps.getString("null_key")).isNull(); + assertThat(otherProps.getInt("null_key")).isNull(); + assertThat(otherProps.getLong("null_key")).isNull(); + assertThat(otherProps.getBoolean("null_key")).isNull(); + assertThat(otherProps.getScalarList("str_list_key", String.class)) + .isEqualTo(Arrays.asList("val1", "val2")); + assertThat(otherProps.getScalarList("int_list_key", Long.class)) + .isEqualTo(Arrays.asList(1L, 2L)); + assertThat(otherProps.getScalarList("float_list_key", Double.class)) + .isEqualTo(Arrays.asList(1.1d, 2.2d)); + assertThat(otherProps.getScalarList("bool_list_key", Boolean.class)) + .isEqualTo(Arrays.asList(true, false)); + // If reading a scalar list which is mixed, entries which are not aligned with + // the requested + // type are filtered out + assertThat(otherProps.getScalarList("mixed_list_key", String.class)) + .isEqualTo(Collections.singletonList("val1")); + assertThat(otherProps.getScalarList("mixed_list_key", Long.class)) + .isEqualTo(Collections.singletonList(1L)); + assertThat(otherProps.getScalarList("mixed_list_key", Double.class)) + .isEqualTo(Collections.singletonList(1.1d)); + assertThat(otherProps.getScalarList("mixed_list_key", Boolean.class)) + .isEqualTo(Collections.singletonList(true)); + + // .other.map_key + DeclarativeConfigProperties otherMapKeyProps = otherProps.getStructured("map_key"); + assertThat(otherMapKeyProps).isNotNull(); + assertThat(otherMapKeyProps.getPropertyKeys()) + .isEqualTo(ImmutableSet.of("str_key1", "int_key1", "map_key1")); + assertThat(otherMapKeyProps.getString("str_key1")).isEqualTo("str_value1"); + assertThat(otherMapKeyProps.getInt("int_key1")).isEqualTo(2); + // other.map_key.map_key1 + DeclarativeConfigProperties otherMapKeyMapKey1Props = + otherMapKeyProps.getStructured("map_key1"); + assertThat(otherMapKeyMapKey1Props).isNotNull(); + assertThat(otherMapKeyMapKey1Props.getPropertyKeys()) + .isEqualTo(ImmutableSet.of("str_key2", "int_key2")); + assertThat(otherMapKeyMapKey1Props.getString("str_key2")).isEqualTo("str_value2"); + assertThat(otherMapKeyMapKey1Props.getInt("int_key2")).isEqualTo(3); + + // .other.list_key + List listKey = otherProps.getStructuredList("list_key"); + assertThat(listKey).hasSize(2); + DeclarativeConfigProperties listKeyProps1 = listKey.get(0); + assertThat(listKeyProps1.getPropertyKeys()) + .isEqualTo(ImmutableSet.of("str_key1", "int_key1", "map_key1")); + assertThat(listKeyProps1.getString("str_key1")).isEqualTo("str_value1"); + assertThat(listKeyProps1.getInt("int_key1")).isEqualTo(2); + // .other.list_key[0] + DeclarativeConfigProperties listKeyProps1MapKeyProps = listKeyProps1.getStructured("map_key1"); + assertThat(listKeyProps1MapKeyProps).isNotNull(); + assertThat(listKeyProps1MapKeyProps.getPropertyKeys()) + .isEqualTo(ImmutableSet.of("str_key2", "int_key2")); + assertThat(listKeyProps1MapKeyProps.getString("str_key2")).isEqualTo("str_value2"); + assertThat(listKeyProps1MapKeyProps.getInt("int_key2")).isEqualTo(3); + // .other.list_key[1] + DeclarativeConfigProperties listKeyProps2 = listKey.get(1); + assertThat(listKeyProps2.getPropertyKeys()).isEqualTo(ImmutableSet.of("str_key1", "int_key1")); + assertThat(listKeyProps2.getString("str_key1")).isEqualTo("str_value1"); + assertThat(listKeyProps2.getInt("int_key1")).isEqualTo(2); + } + + @Test + void treeWalking() { + // Validate common pattern of walking down tree path which is not defined + // Access string at .foo.bar.baz without null checking and without exception. + assertThat( + structuredConfigProps + .get("foo") // short for getStructured("foo", empty()) + .getStructured("bar", empty()) + .getString("baz")) + .isNull(); + } + + @Test + void defaults() { + assertThat(structuredConfigProps.getString("foo", "bar")).isEqualTo("bar"); + assertThat(structuredConfigProps.getInt("foo", 1)).isEqualTo(1); + assertThat(structuredConfigProps.getLong("foo", 1)).isEqualTo(1); + assertThat(structuredConfigProps.getDouble("foo", 1.1)).isEqualTo(1.1); + assertThat(structuredConfigProps.getBoolean("foo", true)).isTrue(); + assertThat( + structuredConfigProps.getScalarList( + "foo", String.class, Collections.singletonList("bar"))) + .isEqualTo(Collections.singletonList("bar")); + assertThat(structuredConfigProps.getStructured("foo", empty())).isEqualTo(empty()); + assertThat(structuredConfigProps.getStructuredList("foo", Collections.emptyList())) + .isEqualTo(Collections.emptyList()); + + DeclarativeConfigProperties otherProps = structuredConfigProps.getStructured("other"); + assertThat(otherProps).isNotNull(); + assertThat(otherProps.getString("str_key", "defaultStr")).isEqualTo("str_value"); + assertThat(otherProps.getInt("int_key", 99)).isEqualTo(1); + assertThat(otherProps.getLong("int_key", 99L)).isEqualTo(1L); + assertThat(otherProps.getDouble("float_key", 9.99)).isEqualTo(1.1); + assertThat(otherProps.getBoolean("bool_key", false)).isTrue(); + assertThat(otherProps.getScalarList("str_list_key", String.class, Collections.emptyList())) + .isEqualTo(Arrays.asList("val1", "val2")); + assertThat(otherProps.getStructured("map_key", empty())) + .isEqualTo(otherProps.getStructured("map_key")); + assertThat(otherProps.get("map_key")).isEqualTo(otherProps.getStructured("map_key")); + assertThat(otherProps.getStructuredList("list_key", Collections.emptyList())) + .isEqualTo(otherProps.getStructuredList("list_key")); + } + + @Test + void missingKeys() { + assertThat(structuredConfigProps.getString("foo")).isNull(); + assertThat(structuredConfigProps.getInt("foo")).isNull(); + assertThat(structuredConfigProps.getLong("foo")).isNull(); + assertThat(structuredConfigProps.getDouble("foo")).isNull(); + assertThat(structuredConfigProps.getBoolean("foo")).isNull(); + assertThat(structuredConfigProps.getScalarList("foo", String.class)).isNull(); + assertThat(structuredConfigProps.getStructured("foo")).isNull(); + assertThat(structuredConfigProps.getStructuredList("foo")).isNull(); + } + + @Test + void wrongType() { + DeclarativeConfigProperties otherProps = structuredConfigProps.getStructured("other"); + assertThat(otherProps).isNotNull(); + + assertThat(otherProps.getString("int_key")).isNull(); + assertThat(otherProps.getInt("str_key")).isNull(); + assertThat(otherProps.getLong("str_key")).isNull(); + assertThat(otherProps.getDouble("str_key")).isNull(); + assertThat(otherProps.getBoolean("str_key")).isNull(); + assertThat(otherProps.getScalarList("str_key", String.class)).isNull(); + assertThat(otherProps.getScalarList("str_list_key", Long.class)).isNull(); + assertThat(otherProps.getScalarList("str_list_key", Boolean.class)).isNull(); + assertThat(otherProps.getScalarList("str_list_key", Double.class)).isNull(); + assertThat(otherProps.getStructured("str_key")).isNull(); + assertThat(otherProps.getStructuredList("str_key")).isNull(); + assertThat(otherProps.getStructured("str_list_key")).isNull(); + assertThat(otherProps.getStructuredList("map_key")).isNull(); + + assertWarning("Ignoring value for key [int_key] because it is Integer instead of String: 1"); + assertWarning( + "Ignoring value for key [str_key] because it is String instead of Long: str_value"); + assertWarning( + "Ignoring value for key [str_key] because it is String instead of Double: str_value"); + assertWarning( + "Ignoring value for key [str_key] because it is String instead of Boolean: str_value"); + assertWarning( + "Ignoring value for key [str_list_key] because it is String instead of Long: val1"); + } + + @Test + void wrongTypeWithDefault() { + DeclarativeConfigProperties otherProps = structuredConfigProps.getStructured("other"); + assertThat(otherProps).isNotNull(); + + assertThat(otherProps.getString("int_key", "default")).isEqualTo("default"); + assertThat(otherProps.getInt("str_key", 100)).isEqualTo(100); + assertThat(otherProps.getLong("str_key", 100L)).isEqualTo(100L); + assertThat(otherProps.getDouble("str_key", 1.1)).isEqualTo(1.1); + assertThat(otherProps.getBoolean("str_key", true)).isTrue(); + assertThat( + otherProps.getScalarList("str_key", String.class, Collections.singletonList("default"))) + .isEqualTo(Collections.singletonList("default")); + assertThat(otherProps.getStructured("str_key", empty())).isEqualTo(empty()); + assertThat(otherProps.getStructuredList("str_key", Collections.emptyList())) + .isEqualTo(Collections.emptyList()); + } + + @Test + void typeIntrospection() { + DeclarativeConfigProperties otherProps = structuredConfigProps.getStructured("other"); + assertThat(otherProps).isNotNull(); + + assertThat(otherProps.isString("str_key")).isTrue(); + assertThat(otherProps.isBoolean("bool_key")).isTrue(); + assertThat(otherProps.isInt("int_key")).isTrue(); + assertThat(otherProps.isDouble("float_key")).isTrue(); + + // getInt and getLong accept each other's types, so the predicates do too + assertThat(otherProps.isLong("int_key")).isTrue(); + + assertThat(otherProps.isString("int_key")).isFalse(); + assertThat(otherProps.isBoolean("str_key")).isFalse(); + assertThat(otherProps.isInt("str_key")).isFalse(); + assertThat(otherProps.isLong("str_key")).isFalse(); + assertThat(otherProps.isDouble("str_key")).isFalse(); + + // null-valued, non-scalar, and unconfigured keys are all false + assertThat(otherProps.isString("null_key")).isFalse(); + assertThat(otherProps.isString("str_list_key")).isFalse(); + assertThat(otherProps.isString("map_key")).isFalse(); + assertThat(otherProps.isString("foo")).isFalse(); + + // the reason these exist: asking never reports a type mismatch + assertThat(logs.getEvents()).isEmpty(); + } + + @Test + void typeIntrospectionAgreesWithGetters() { + DeclarativeConfigProperties otherProps = structuredConfigProps.getStructured("other"); + assertThat(otherProps).isNotNull(); + + for (String key : Arrays.asList("str_key", "int_key", "float_key", "bool_key", "null_key")) { + assertThat(otherProps.isString(key)).isEqualTo(otherProps.getString(key) != null); + assertThat(otherProps.isBoolean(key)).isEqualTo(otherProps.getBoolean(key) != null); + assertThat(otherProps.isInt(key)).isEqualTo(otherProps.getInt(key) != null); + assertThat(otherProps.isLong(key)).isEqualTo(otherProps.getLong(key) != null); + assertThat(otherProps.isDouble(key)).isEqualTo(otherProps.getDouble(key) != null); + } + } + + @Test + void typeIntrospectionAcceptsGetterConversions() { + // YAML parsing yields Integer and Double, so build the Long and Float cases directly + Map properties = new HashMap<>(); + properties.put("long_key", 5L); + properties.put("float_key", 1.5f); + DeclarativeConfigProperties props = + YamlDeclarativeConfigProperties.create( + properties, ComponentLoader.forClassLoader(getClass().getClassLoader())); + + assertThat(props.isInt("long_key")).isTrue(); + assertThat(props.isLong("long_key")).isTrue(); + assertThat(props.isDouble("float_key")).isTrue(); + assertThat(props.isDouble("long_key")).isFalse(); + assertThat(props.isLong("float_key")).isFalse(); + assertThat(logs.getEvents()).isEmpty(); + } + + private void assertWarning(String message) { + logs.assertContains( + e -> + String.format(e.getMessage().replaceAll("\\{\\d}", "%s"), e.getArgumentArray()) + .contains(message), + message); + } + + @Test + void emptyProperties() { + assertThat(empty().getString("foo")).isNull(); + assertThat(empty().getInt("foo")).isNull(); + assertThat(empty().getLong("foo")).isNull(); + assertThat(empty().getDouble("foo")).isNull(); + assertThat(empty().getBoolean("foo")).isNull(); + assertThat(empty().getScalarList("foo", String.class)).isNull(); + assertThat(empty().getStructured("foo")).isNull(); + assertThat(empty().getStructuredList("foo")).isNull(); + assertThat(empty().getString("foo", "bar")).isEqualTo("bar"); + assertThat(empty().getInt("foo", 1)).isEqualTo(1); + assertThat(empty().getLong("foo", 1)).isEqualTo(1); + assertThat(empty().getDouble("foo", 1.1)).isEqualTo(1.1); + assertThat(empty().getBoolean("foo", true)).isTrue(); + assertThat(empty().getScalarList("foo", String.class, Collections.singletonList("bar"))) + .isEqualTo(Collections.singletonList("bar")); + assertThat(empty().getStructured("foo", empty())).isEqualTo(empty()); + assertThat(empty().getStructuredList("foo", Collections.emptyList())) + .isEqualTo(Collections.emptyList()); + assertThat(empty().isString("foo")).isFalse(); + assertThat(empty().isBoolean("foo")).isFalse(); + assertThat(empty().isInt("foo")).isFalse(); + assertThat(empty().isLong("foo")).isFalse(); + assertThat(empty().isDouble("foo")).isFalse(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/IdGeneratorComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/IdGeneratorComponentProvider.java new file mode 100644 index 00000000000..458727bfc59 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/IdGeneratorComponentProvider.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.trace.IdGenerator; + +public class IdGeneratorComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return IdGenerator.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public IdGenerator create(DeclarativeConfigProperties config) { + return TestIdGenerator.create(); + } + + public static class TestIdGenerator implements IdGenerator { + + private TestIdGenerator() {} + + public static TestIdGenerator create() { + return new TestIdGenerator(); + } + + @Override + public String generateSpanId() { + return "00000000"; + } + + @Override + public String generateTraceId() { + return "0000000000000000"; + } + + @Override + public String toString() { + return "TestIdGenerator{}"; + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/LogRecordExporterComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/LogRecordExporterComponentProvider.java new file mode 100644 index 00000000000..c7deabcc836 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/LogRecordExporterComponentProvider.java @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.Collection; + +public class LogRecordExporterComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return LogRecordExporter.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public LogRecordExporter create(DeclarativeConfigProperties config) { + return new TestLogRecordExporter(config); + } + + public static class TestLogRecordExporter implements LogRecordExporter { + + public final DeclarativeConfigProperties config; + + private TestLogRecordExporter(DeclarativeConfigProperties config) { + this.config = config; + } + + @Override + public CompletableResultCode export(Collection logs) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/LogRecordProcessorComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/LogRecordProcessorComponentProvider.java new file mode 100644 index 00000000000..a0738de69d6 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/LogRecordProcessorComponentProvider.java @@ -0,0 +1,56 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.ReadWriteLogRecord; + +public class LogRecordProcessorComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return LogRecordProcessor.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public LogRecordProcessor create(DeclarativeConfigProperties config) { + return new TestLogRecordProcessor(config); + } + + public static class TestLogRecordProcessor implements LogRecordProcessor { + + public final DeclarativeConfigProperties config; + + private TestLogRecordProcessor(DeclarativeConfigProperties config) { + this.config = config; + } + + public static TestLogRecordProcessor create() { + return new TestLogRecordProcessor(null); + } + + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) {} + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public String toString() { + return "TestLogRecordProcessor{}"; + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/MetricExporterComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/MetricExporterComponentProvider.java new file mode 100644 index 00000000000..d189d24b2d4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/MetricExporterComponentProvider.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.Collection; + +public class MetricExporterComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return MetricExporter.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public MetricExporter create(DeclarativeConfigProperties config) { + return new TestMetricExporter(config); + } + + public static class TestMetricExporter implements MetricExporter { + + public final DeclarativeConfigProperties config; + + private TestMetricExporter(DeclarativeConfigProperties config) { + this.config = config; + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporalitySelector.alwaysCumulative() + .getAggregationTemporality(instrumentType); + } + + @Override + public CompletableResultCode export(Collection metrics) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceComponentProvider.java new file mode 100644 index 00000000000..6c62ce74925 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceComponentProvider.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class ResourceComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "shape_color"; + } + + @Override + public Resource create(DeclarativeConfigProperties config) { + return Resource.builder().put("shape", "square").put("color", "red").build(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceFirstComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceFirstComponentProvider.java new file mode 100644 index 00000000000..7d5ffe15357 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceFirstComponentProvider.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class ResourceFirstComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "order_first"; + } + + @Override + public Resource create(DeclarativeConfigProperties config) { + return Resource.builder().put("order", "first").build(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceSecondComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceSecondComponentProvider.java new file mode 100644 index 00000000000..bb3d8d9d703 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/ResourceSecondComponentProvider.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.resources.Resource; + +public class ResourceSecondComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return Resource.class; + } + + @Override + public String getName() { + return "order_second"; + } + + @Override + public Resource create(DeclarativeConfigProperties config) { + return Resource.builder().put("order", "second").build(); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SamplerComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SamplerComponentProvider.java new file mode 100644 index 00000000000..e82263217e4 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SamplerComponentProvider.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.List; + +public class SamplerComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return Sampler.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public Sampler create(DeclarativeConfigProperties config) { + return new TestSampler(config); + } + + public static class TestSampler implements Sampler { + + public final DeclarativeConfigProperties config; + + private TestSampler(DeclarativeConfigProperties config) { + this.config = config; + } + + @Override + public SamplingResult shouldSample( + Context parentContext, + String traceId, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return SamplingResult.recordOnly(); + } + + @Override + public String getDescription() { + return "test"; + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SpanExporterComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SpanExporterComponentProvider.java new file mode 100644 index 00000000000..47b393acd74 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SpanExporterComponentProvider.java @@ -0,0 +1,54 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.util.Collection; + +public class SpanExporterComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return SpanExporter.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public SpanExporter create(DeclarativeConfigProperties config) { + return new TestSpanExporter(config); + } + + public static class TestSpanExporter implements SpanExporter { + + public final DeclarativeConfigProperties config; + + private TestSpanExporter(DeclarativeConfigProperties config) { + this.config = config; + } + + @Override + public CompletableResultCode export(Collection spans) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SpanProcessorComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SpanProcessorComponentProvider.java new file mode 100644 index 00000000000..62cc0e90eb8 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/SpanProcessorComponentProvider.java @@ -0,0 +1,61 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; + +public class SpanProcessorComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return SpanProcessor.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public SpanProcessor create(DeclarativeConfigProperties config) { + return new TestSpanProcessor(config); + } + + public static class TestSpanProcessor implements SpanProcessor { + + public final DeclarativeConfigProperties config; + + private TestSpanProcessor(DeclarativeConfigProperties config) { + this.config = config; + } + + @Override + public void onStart(Context parentContext, ReadWriteSpan span) {} + + @Override + public boolean isStartRequired() { + return true; + } + + @Override + public void onEnd(ReadableSpan span) {} + + @Override + public boolean isEndRequired() { + return true; + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/TextMapPropagatorComponentProvider.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/TextMapPropagatorComponentProvider.java new file mode 100644 index 00000000000..15365cc7c02 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/component/TextMapPropagatorComponentProvider.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.component; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.propagation.TextMapGetter; +import io.opentelemetry.context.propagation.TextMapPropagator; +import io.opentelemetry.context.propagation.TextMapSetter; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import java.util.Collection; +import java.util.Collections; +import javax.annotation.Nullable; + +public class TextMapPropagatorComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return TextMapPropagator.class; + } + + @Override + public String getName() { + return "test"; + } + + @Override + public TextMapPropagator create(DeclarativeConfigProperties config) { + return new TestTextMapPropagator(config); + } + + public static class TestTextMapPropagator implements TextMapPropagator { + + public final DeclarativeConfigProperties config; + + public TestTextMapPropagator(DeclarativeConfigProperties config) { + this.config = config; + } + + @Override + public Collection fields() { + return Collections.emptyList(); + } + + @Override + public void inject(Context context, @Nullable C carrier, TextMapSetter setter) {} + + @Override + public Context extract(Context context, @Nullable C carrier, TextMapGetter getter) { + return context; + } + + @Override + public String toString() { + return "TestTextMapPropagator{}"; + } + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigProviderLoaderTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigProviderLoaderTest.java new file mode 100644 index 00000000000..19e12424531 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/internal/DeclarativeConfigProviderLoaderTest.java @@ -0,0 +1,128 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.common.ComponentLoader; +import java.util.Arrays; +import java.util.Collections; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junitpioneer.jupiter.ClearSystemProperty; + +@ClearSystemProperty( + key = + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.internal.DeclarativeConfigProviderLoaderTest$TestSpi") +class DeclarativeConfigProviderLoaderTest { + + private static final TestSpi FIRST = new FirstProvider(); + private static final TestSpi SECOND = new SecondProvider(); + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(DeclarativeConfigProviderLoader.class); + + private final ComponentLoader loader = mock(ComponentLoader.class); + + @Test + void cachesSelectedProviders() { + assertThat(DeclarativeConfigProviderLoader.getMapper()) + .isSameAs(DeclarativeConfigProviderLoader.getMapper()); + assertThat(DeclarativeConfigProviderLoader.getYamlParser()) + .isSameAs(DeclarativeConfigProviderLoader.getYamlParser()); + } + + @Test + void retriesFailedResolutionAndCachesSuccess() { + AtomicReference ref = new AtomicReference<>(); + when(loader.load(TestSpi.class)) + .thenThrow(new IllegalStateException("lookup failed")) + .thenReturn(Collections.singletonList(FIRST)); + + assertThatThrownBy(() -> + DeclarativeConfigProviderLoader.resolveProvider(ref, TestSpi.class, loader, "missing")) + .isInstanceOf(IllegalStateException.class); + assertThat(ref.get()).isNull(); + assertThat( + DeclarativeConfigProviderLoader.resolveProvider(ref, TestSpi.class, loader, "missing")) + .isSameAs(FIRST); + assertThat( + DeclarativeConfigProviderLoader.resolveProvider(ref, TestSpi.class, loader, "missing")) + .isSameAs(FIRST); + verify(loader, times(2)).load(TestSpi.class); + } + + @Test + void rejectsMissingProvider() { + when(loader.load(TestSpi.class)).thenReturn(Collections.emptyList()); + + assertThatThrownBy(() -> + DeclarativeConfigProviderLoader.resolveProvider( + new AtomicReference<>(), TestSpi.class, loader, "missing")) + .isInstanceOf(DeclarativeConfigException.class) + .hasMessage("missing"); + } + + @Test + void selectsSingleProvider() { + when(loader.load(TestSpi.class)).thenReturn(Collections.singletonList(FIRST)); + + assertThat( + DeclarativeConfigProviderLoader.resolveProvider( + new AtomicReference<>(), TestSpi.class, loader, "missing")) + .isSameAs(FIRST); + } + + @Test + void selectsFirstProviderAndWarns() { + when(loader.load(TestSpi.class)).thenReturn(Arrays.asList(FIRST, SECOND)); + + assertThat( + DeclarativeConfigProviderLoader.resolveProvider( + new AtomicReference<>(), TestSpi.class, loader, "missing")) + .isSameAs(FIRST); + logs.assertContains( + event -> event.getMessage().startsWith("Multiple {0} providers found."), + "Expected multiple-provider warning"); + } + + @Test + void selectsConfiguredProvider() { + System.setProperty(TestSpi.class.getName(), SECOND.getClass().getName()); + when(loader.load(TestSpi.class)).thenReturn(Arrays.asList(FIRST, SECOND)); + + assertThat( + DeclarativeConfigProviderLoader.resolveProvider( + new AtomicReference<>(), TestSpi.class, loader, "missing")) + .isSameAs(SECOND); + } + + @Test + void rejectsUnknownConfiguredProvider() { + System.setProperty(TestSpi.class.getName(), "missing.Provider"); + when(loader.load(TestSpi.class)).thenReturn(Arrays.asList(FIRST, SECOND)); + + assertThatThrownBy(() -> + DeclarativeConfigProviderLoader.resolveProvider( + new AtomicReference<>(), TestSpi.class, loader, "missing")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing.Provider"); + } + + private interface TestSpi {} + + private static final class FirstProvider implements TestSpi {} + + private static final class SecondProvider implements TestSpi {} +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelEqualsHashCodeTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelEqualsHashCodeTest.java new file mode 100644 index 00000000000..22d6401bddb --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelEqualsHashCodeTest.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import com.google.common.reflect.ClassPath; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableAlwaysOffSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableParentThresholdSamplerModel; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerModel; +import java.io.IOException; +import java.util.Comparator; +import java.util.stream.Stream; +import nl.jqno.equalsverifier.EqualsVerifier; +import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * Verifies the {@code equals}/{@code hashCode} contract for every generated model POJO. The models + * and their {@code equals}/{@code hashCode} implementations are generated by {@code + * io.opentelemetry.gradle.DeclarativeConfigPojoGenerator}, so this test guards the generator output + * rather than any hand-written code. + */ +class ModelEqualsHashCodeTest { + + // Experimental (unstable) models live in the MODEL_PACKAGE.internal sub-package, so the class + // scan below is recursive to cover both stable and experimental POJOs. + private static final String MODEL_PACKAGE = + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.model"; + + @ParameterizedTest + @MethodSource("modelClasses") + void equalsHashCode(Class modelClass) { + EqualsVerifier.forClass(modelClass) + // Generated POJOs are mutable (non-final fields) and non-final with an instanceof-based + // equals, neither of which EqualsVerifier accepts by default. + .suppress(Warning.NONFINAL_FIELDS, Warning.STRICT_INHERITANCE) + // Several models hold "oneOf" sub-models that are empty (e.g. ConsoleExporterModel), whose + // equals is instanceof-only. EqualsVerifier can't produce two unequal instances of such a + // type, so it can't prove the enclosing field is significant. The full equals/hashCode + // contract is still verified. + .suppress(Warning.ALL_FIELDS_SHOULD_BE_USED) + // Break the self-referential sampler graphs (e.g. parent-based and jaeger-remote samplers + // contain a nested SamplerModel; composable parent-threshold samplers contain a root + // sampler). Prefab values only need to be unequal to each other. + .withPrefabValues( + SamplerModel.class, + new SamplerModel(), + new SamplerModel().setAlwaysOn(new AlwaysOnSamplerModel())) + .withPrefabValues( + ExperimentalComposableSamplerModel.class, + new ExperimentalComposableSamplerModel(), + new ExperimentalComposableSamplerModel() + .setAlwaysOff(new ExperimentalComposableAlwaysOffSamplerModel())) + .withPrefabValues( + ExperimentalComposableParentThresholdSamplerModel.class, + new ExperimentalComposableParentThresholdSamplerModel(), + new ExperimentalComposableParentThresholdSamplerModel() + .setRoot(new ExperimentalComposableSamplerModel())) + .verify(); + } + + static Stream modelClasses() throws IOException { + return ClassPath.from(ModelEqualsHashCodeTest.class.getClassLoader()) + .getTopLevelClassesRecursive(MODEL_PACKAGE) + .stream() + .map(ClassPath.ClassInfo::load) + // All generated types (both classes and enums) carry the "Model" suffix. Enums have a + // correct-by-construction equals/hashCode (identity), so only non-enum Model classes need + // EqualsVerifier coverage. + .filter(clazz -> clazz.getSimpleName().endsWith("Model") && !clazz.isEnum()) + .sorted(Comparator.comparing(Class::getSimpleName)) + .map(clazz -> Arguments.argumentSet(clazz.getSimpleName(), clazz)); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelJacksonRoundTripTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelJacksonRoundTripTest.java new file mode 100644 index 00000000000..c66dabc1292 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelJacksonRoundTripTest.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.fasterxml.jackson.databind.ObjectMapper; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.internal.ExperimentalComposableSamplerPropertyModel; +import org.junit.jupiter.api.Test; + +/** + * Locks in the Jackson binding of the generated models. Uses a plain {@link ObjectMapper} to + * exercise the generated annotations directly, not the production mapper's configuration. + */ +class ModelJacksonRoundTripTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void deserializesThroughBuilderWithSnakeCaseNames() throws Exception { + // @JsonProperty is on the getter and setX, not the field, so Jackson binds through the + // builder using the snake_case name. + BatchSpanProcessorModel model = new BatchSpanProcessorModel().setScheduleDelay(5000); + + String json = mapper.writeValueAsString(model); + assertThat(json).isEqualTo("{\"schedule_delay\":5000}"); + + assertThat(mapper.readValue(json, BatchSpanProcessorModel.class)).isEqualTo(model); + } + + @Test + void additionalPropertiesFlattenAndRoundTrip() throws Exception { + // additionalProperties contents flatten to top-level keys via @JsonAnyGetter/@JsonAnySetter + // rather than serializing under an "additionalProperties" key. + ExperimentalComposableSamplerPropertyModel model = + new ExperimentalComposableSamplerPropertyModel().setAdditionalProperty("foo", "bar"); + + String json = mapper.writeValueAsString(model); + assertThat(json).isEqualTo("{\"foo\":\"bar\"}"); + + assertThat(mapper.readValue(json, ExperimentalComposableSamplerPropertyModel.class)) + .isEqualTo(model); + } +} diff --git a/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java new file mode 100644 index 00000000000..3f2476f2ed1 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/java/io/opentelemetry/sdk/autoconfigure/declarativeconfig/model/ModelPackageBoundaryTest.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.autoconfigure.declarativeconfig.model; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.reflect.ClassPath; +import java.io.IOException; +import java.util.List; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; + +/** + * Guards the experimental/stable package boundary for the generated model types. + * + *

      Experimental (unstable) model types must live in {@code MODEL_PACKAGE.internal} and stable + * model types in {@code MODEL_PACKAGE}. The generator routes types whose name starts with {@code + * Experimental} to the internal sub-package. {@code *ModelAccessor} classes also live in {@code + * MODEL_PACKAGE.internal}; they provide typed access to experimental properties on stable classes + * and are exempt from the {@code Experimental} prefix requirement. This test fails if a schema + * update or rename ever breaks the invariant — e.g. leaking a mutable experimental type into + * the stable public API. + */ +class ModelPackageBoundaryTest { + + private static final String MODEL_PACKAGE = + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.model"; + private static final String INTERNAL_PACKAGE = MODEL_PACKAGE + ".internal"; + private static final String EXPERIMENTAL_PREFIX = "Experimental"; + + @Test + void experimentalTypesAreExactlyTheInternalPackage() throws IOException { + List> generated = + ClassPath.from(ModelPackageBoundaryTest.class.getClassLoader()) + .getTopLevelClassesRecursive(MODEL_PACKAGE) + .stream() + .map(ClassPath.ClassInfo::load) + // The model package also holds the hand-written tests; exclude them. + .filter(clazz -> !clazz.getSimpleName().endsWith("Test")) + .collect(Collectors.toList()); + + // Guard against a vacuous pass if the scan finds nothing (e.g. wrong package or classpath). + assertThat(generated).isNotEmpty(); + assertThat(generated) + .filteredOn(clazz -> clazz.getPackage().getName().equals(INTERNAL_PACKAGE)) + .isNotEmpty(); + + assertThat(generated) + .allSatisfy(clazz -> { + boolean inInternal = clazz.getPackage().getName().equals(INTERNAL_PACKAGE); + boolean experimental = clazz.getSimpleName().startsWith(EXPERIMENTAL_PREFIX); + // Internal utility classes are exempt from the Experimental prefix requirement. + boolean isInfrastructure = + clazz.getSimpleName().endsWith("Accessor") + || clazz.getSimpleName().equals("ModelMapper") + || clazz.getSimpleName().equals("ExtensionPropertyUtil"); + assertThat(experimental || isInfrastructure) + .as( + "%s: experimental types (name starts with %s) and internal infrastructure " + + "classes must live in %s, all other types in %s", + clazz.getName(), EXPERIMENTAL_PREFIX, INTERNAL_PACKAGE, MODEL_PACKAGE) + .isEqualTo(inInternal); + }); + } +} diff --git a/sdk-extensions/declarative-config/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider b/sdk-extensions/declarative-config/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider new file mode 100644 index 00000000000..a8b8bd75636 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider @@ -0,0 +1 @@ +io.opentelemetry.sdk.autoconfigure.declarativeconfig.TestDeclarativeConfigurationCustomizerProvider diff --git a/sdk-extensions/declarative-config/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/sdk-extensions/declarative-config/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..98cdcb2e199 --- /dev/null +++ b/sdk-extensions/declarative-config/src/test/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,12 @@ +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.MetricExporterComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.SpanExporterComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.LogRecordExporterComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.TextMapPropagatorComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.SamplerComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.SpanProcessorComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.LogRecordProcessorComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.ResourceComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.ResourceFirstComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.ResourceSecondComponentProvider +io.opentelemetry.sdk.autoconfigure.declarativeconfig.component.IdGeneratorComponentProvider + diff --git a/sdk-extensions/incubator/README.md b/sdk-extensions/incubator/README.md new file mode 100644 index 00000000000..cf5d34fb5d5 --- /dev/null +++ b/sdk-extensions/incubator/README.md @@ -0,0 +1,8 @@ +# OpenTelemetry Incubator + +This artifact contains experimental code related to the trace and metric SDKs. + +## Declarative Configuration + +> [!WARNING] +> Relocated to [opentelemetry-sdk-extensions-declarative-config](../declarative-config) diff --git a/sdk-extensions/incubator/build.gradle.kts b/sdk-extensions/incubator/build.gradle.kts new file mode 100644 index 00000000000..d9423fdecd7 --- /dev/null +++ b/sdk-extensions/incubator/build.gradle.kts @@ -0,0 +1,31 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +// SDK modules that are still being developed. + +description = "OpenTelemetry SDK Incubator" +otelJava.moduleName.set("io.opentelemetry.sdk.extension.incubator") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator", "io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider", +)) + +dependencies { + api(project(":sdk:all")) + + annotationProcessor("com.google.auto.value:auto-value") + + compileOnly(project(":api:incubator")) + + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + + testImplementation(project(":sdk:testing")) + testImplementation(project(":sdk-extensions:autoconfigure")) + testImplementation("edu.berkeley.cs.jqf:jqf-fuzz") + testImplementation("com.google.guava:guava-testlib") +} diff --git a/sdk-extensions/autoconfigure/gradle.properties b/sdk-extensions/incubator/gradle.properties similarity index 100% rename from sdk-extensions/autoconfigure/gradle.properties rename to sdk-extensions/incubator/gradle.properties diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridge.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridge.java new file mode 100644 index 00000000000..7e646499a27 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridge.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.logs; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.ReadWriteLogRecord; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.concurrent.TimeUnit; + +/** + * A {@link LogRecordProcessor} which bridges events (i.e. log records with a non-empty {@code + * event.name}) as span events on the current span. + * + *

      A log record is bridged to a span event if and only if all of the following conditions are + * met: + * + *

        + *
      • The log record has a non-empty event name. + *
      • The log record has a valid trace ID and span ID. + *
      • The resolved context contains a current span whose {@link Span#isRecording()} is {@code + * true}. + *
      • The log record's trace ID and span ID equal those of the current span in the resolved + * context. + *
      + * + *

      When bridged, a span event is added with: + * + *

        + *
      • Name set to the log record's event name. + *
      • Timestamp set to the log record's timestamp if set; otherwise, the observed timestamp. + *
      • All log record attributes copied to the span event attributes. + *
      + * + *

      Bridging does NOT prevent the log record from continuing through the normal log processing + * pipeline. + */ +public final class EventToSpanEventBridge implements LogRecordProcessor { + + private EventToSpanEventBridge() {} + + /** Create a new instance. */ + public static EventToSpanEventBridge create() { + return new EventToSpanEventBridge(); + } + + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) { + LogRecordData logRecordData = logRecord.toLogRecordData(); + String eventName = logRecordData.getEventName(); + if (eventName == null || eventName.isEmpty()) { + return; + } + SpanContext logSpanContext = logRecordData.getSpanContext(); + if (!logSpanContext.isValid()) { + return; + } + Span currentSpan = Span.fromContext(context); + if (!currentSpan.isRecording()) { + return; + } + SpanContext currentSpanContext = currentSpan.getSpanContext(); + if (!currentSpanContext.getTraceId().equals(logSpanContext.getTraceId()) + || !currentSpanContext.getSpanId().equals(logSpanContext.getSpanId())) { + return; + } + long timestampNanos = logRecordData.getTimestampEpochNanos(); + if (timestampNanos == 0) { + timestampNanos = logRecordData.getObservedTimestampEpochNanos(); + } + currentSpan.addEvent( + eventName, logRecordData.getAttributes(), timestampNanos, TimeUnit.NANOSECONDS); + } + + @Override + public String toString() { + return "EventToSpanEventBridge{}"; + } +} diff --git a/sdk-extensions/tracing-incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java similarity index 95% rename from sdk-extensions/tracing-incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java rename to sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java index 8fd7b68ce34..e76d469a8ff 100644 --- a/sdk-extensions/tracing-incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessor.java @@ -37,9 +37,8 @@ public final class LeakDetectingSpanProcessor implements SpanProcessor { * garbage collected. */ public static LeakDetectingSpanProcessor create() { - return new LeakDetectingSpanProcessor( - (message, throwable) -> - logger.log(Level.WARNING, "Span garbage collected before being ended.", throwable)); + return new LeakDetectingSpanProcessor((message, throwable) -> + logger.log(Level.WARNING, "Span garbage collected before being ended.", throwable)); } // Visible for testing @@ -87,6 +86,7 @@ private static PendingSpans create(BiConsumer reporter) { thread.setName("weak-ref-cleaner-leakingspandetector"); thread.setPriority(Thread.MIN_PRIORITY); thread.setDaemon(true); + thread.setContextClassLoader(null); thread.start(); return pendingSpans; } diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/OnEndSpanProcessor.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/OnEndSpanProcessor.java new file mode 100644 index 00000000000..41296ebd603 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/OnEndSpanProcessor.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; + +/** A SpanProcessor implementation that is only capable of processing spans when they end. */ +public final class OnEndSpanProcessor implements SpanProcessor { + private final OnEnd onEnd; + + private OnEndSpanProcessor(OnEnd onEnd) { + this.onEnd = onEnd; + } + + public static SpanProcessor create(OnEnd onEnd) { + return new OnEndSpanProcessor(onEnd); + } + + @Override + public void onEnd(ReadableSpan span) { + onEnd.apply(span); + } + + @Override + public boolean isEndRequired() { + return true; + } + + @Override + public void onStart(Context parentContext, ReadWriteSpan span) { + // nop + } + + @Override + public boolean isStartRequired() { + return false; + } + + /** Callback invoked when a span ends. */ + @FunctionalInterface + public interface OnEnd { + void apply(ReadableSpan span); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessor.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessor.java new file mode 100644 index 00000000000..a291a14acc2 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessor.java @@ -0,0 +1,51 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; + +/** A SpanProcessor that only handles onStart(). */ +public final class OnStartSpanProcessor implements SpanProcessor { + + private final OnStart onStart; + + private OnStartSpanProcessor(OnStart onStart) { + this.onStart = onStart; + } + + public static SpanProcessor create(OnStart onStart) { + return new OnStartSpanProcessor(onStart); + } + + @Override + public void onStart(Context parentContext, ReadWriteSpan span) { + onStart.apply(parentContext, span); + } + + @Override + public boolean isStartRequired() { + return true; + } + + @Override + public void onEnd(ReadableSpan span) { + // nop + } + + @Override + public boolean isEndRequired() { + return false; + } + + /** Callback invoked when a span starts. */ + @FunctionalInterface + public interface OnStart { + void apply(Context context, ReadWriteSpan span); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/AlwaysRecordSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/AlwaysRecordSampler.java new file mode 100644 index 00000000000..a9f6905bc78 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/AlwaysRecordSampler.java @@ -0,0 +1,95 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * This sampler will return the sampling result of the provided {@link #rootSampler}, unless the + * sampling result contains the sampling decision {@link SamplingDecision#DROP}, in which case, a + * new sampling result will be returned that is functionally equivalent to the original, except that + * it contains the sampling decision {@link SamplingDecision#RECORD_ONLY}. This ensures that all + * spans are recorded, with no change to sampling. + * + *

      An intended use case of this sampler is to provide a means of sending all spans to a processor + * without having an impact on the sampling rate. This may be desirable if a user wishes to count or + * otherwise measure all spans produced in a service, without incurring the cost of 100% sampling. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +@Immutable +public final class AlwaysRecordSampler implements Sampler { + + private final Sampler rootSampler; + + public static AlwaysRecordSampler create(Sampler rootSampler) { + return new AlwaysRecordSampler(rootSampler); + } + + private AlwaysRecordSampler(Sampler rootSampler) { + this.rootSampler = rootSampler; + } + + @Override + public SamplingResult shouldSample( + Context parentContext, + String traceId, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + SamplingResult result = + rootSampler.shouldSample(parentContext, traceId, name, spanKind, attributes, parentLinks); + if (result.getDecision() != SamplingDecision.DROP) { + return result; + } + + return new RecordOnlyDelegateSamplingResult(result); + } + + @Override + public String getDescription() { + return "AlwaysRecordSampler{" + rootSampler.getDescription() + "}"; + } + + private static class RecordOnlyDelegateSamplingResult implements SamplingResult { + private final SamplingResult delegate; + + private RecordOnlyDelegateSamplingResult(SamplingResult delegate) { + this.delegate = delegate; + } + + @Override + public SamplingDecision getDecision() { + return SamplingDecision.RECORD_ONLY; + } + + @Override + public Attributes getAttributes() { + return delegate.getAttributes(); + } + + @Override + public TraceState getUpdatedTraceState(TraceState parentTraceState) { + return delegate.getUpdatedTraceState(parentTraceState); + } + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOffSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOffSampler.java new file mode 100644 index 00000000000..e2d587fa56d --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOffSampler.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.NON_SAMPLING_INTENT; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +enum ComposableAlwaysOffSampler implements ComposableSampler { + INSTANCE; + + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return NON_SAMPLING_INTENT; + } + + @Override + public String getDescription() { + return "ComposableAlwaysOffSampler"; + } + + @Override + public String toString() { + return getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOnSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOnSampler.java new file mode 100644 index 00000000000..c85b499d8a0 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOnSampler.java @@ -0,0 +1,43 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +enum ComposableAlwaysOnSampler implements ComposableSampler { + INSTANCE; + + private static final SamplingIntent INTENT = + SamplingIntent.create( + ImmutableSamplingIntent.MIN_THRESHOLD, + /* adjustedCountReliable= */ true, + Attributes.empty(), + ImmutableSamplingIntent.NO_TRACE_STATE_UPDATE); + + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return INTENT; + } + + @Override + public String getDescription() { + return "ComposableAlwaysOnSampler"; + } + + @Override + public String toString() { + return getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAnnotatingSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAnnotatingSampler.java new file mode 100644 index 00000000000..e88913c194d --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAnnotatingSampler.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +final class ComposableAnnotatingSampler implements ComposableSampler { + private final ComposableSampler delegate; + private final Attributes attributes; + private final String description; + + ComposableAnnotatingSampler(ComposableSampler delegate, Attributes attributes) { + this.delegate = delegate; + this.attributes = attributes; + + this.description = + "ComposableAnnotatingSampler{" + delegate.getDescription() + "," + attributes + "}"; + } + + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + SamplingIntent intent = + delegate.getSamplingIntent(parentContext, name, spanKind, attributes, parentLinks); + return SamplingIntent.create( + intent.getThreshold(), + intent.isAdjustedCountReliable(), + intent.getAttributes().toBuilder().putAll(this.attributes).build(), + intent.getTraceStateUpdater()); + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableParentThresholdSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableParentThresholdSampler.java new file mode 100644 index 00000000000..7d5da47535a --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableParentThresholdSampler.java @@ -0,0 +1,71 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_THRESHOLD; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.MIN_THRESHOLD; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.NO_TRACE_STATE_UPDATE; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.isValidThreshold; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +final class ComposableParentThresholdSampler implements ComposableSampler { + + private final ComposableSampler rootSampler; + private final String description; + + ComposableParentThresholdSampler(ComposableSampler rootSampler) { + this.rootSampler = rootSampler; + this.description = "ComposableParentThresholdSampler{rootSampler=" + rootSampler + "}"; + } + + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + SpanContext parentSpanContext = Span.fromContext(parentContext).getSpanContext(); + if (!parentSpanContext.isValid()) { + return rootSampler.getSamplingIntent(parentContext, name, spanKind, attributes, parentLinks); + } + + boolean parentSampled = parentSpanContext.getTraceFlags().isSampled(); + OtelTraceState otTraceState = OtelTraceState.parse(parentSpanContext.getTraceState()); + long parentThreshold = otTraceState.getThreshold(); + if (isValidThreshold(parentThreshold) + && (!parentSampled + || parentThreshold + <= otTraceState.getRandomValueOrFromTraceId(parentSpanContext.getTraceId()))) { + return ImmutableSamplingIntent.create( + parentThreshold, + /* adjustedCountReliable= */ true, + Attributes.empty(), + NO_TRACE_STATE_UPDATE); + } + + long threshold = parentSampled ? MIN_THRESHOLD : INVALID_THRESHOLD; + return ImmutableSamplingIntent.create( + threshold, /* adjustedCountReliable= */ false, Attributes.empty(), NO_TRACE_STATE_UPDATE); + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return this.getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableProbabilitySampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableProbabilitySampler.java new file mode 100644 index 00000000000..32734b9b414 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableProbabilitySampler.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +final class ComposableProbabilitySampler implements ComposableSampler { + private static long calculateThreshold(double ratio) { + return ImmutableSamplingIntent.MAX_THRESHOLD + - Math.round(ratio * (double) ImmutableSamplingIntent.MAX_THRESHOLD); + } + + private final SamplingIntent intent; + private final String description; + + ComposableProbabilitySampler(double ratio) { + long threshold = calculateThreshold(ratio); + String thresholdStr; + if (threshold == ImmutableSamplingIntent.MAX_THRESHOLD) { + thresholdStr = "max"; + + // Same as ComposableAlwaysOffSampler, notably the threshold is not considered reliable. + // The spec mentions returning an instance of ComposableAlwaysOffSampler in this case but + // it seems clearer if the description of the sampler matches the user's request. + this.intent = + SamplingIntent.create( + ImmutableSamplingIntent.INVALID_THRESHOLD, + /* adjustedCountReliable= */ false, + Attributes.empty(), + ImmutableSamplingIntent.NO_TRACE_STATE_UPDATE); + } else { + StringBuilder sb = new StringBuilder(); + OtelTraceState.serializeTh(threshold, sb); + thresholdStr = sb.toString(); + + this.intent = + SamplingIntent.create( + threshold, + /* adjustedCountReliable= */ true, + Attributes.empty(), + ImmutableSamplingIntent.NO_TRACE_STATE_UPDATE); + } + this.description = + "ComposableProbabilitySampler{threshold=" + thresholdStr + ", ratio=" + ratio + "}"; + } + + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return intent; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return this.getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSampler.java new file mode 100644 index 00000000000..c6225da041c --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSampler.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.NON_SAMPLING_INTENT; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +final class ComposableRuleBasedSampler implements ComposableSampler { + + private final SamplingRule[] rules; + private final String description; + + ComposableRuleBasedSampler(List rules) { + this.rules = rules.toArray(new SamplingRule[0]); + + StringBuilder description = new StringBuilder("ComposableRuleBasedSampler{["); + if (this.rules.length > 0) { + for (SamplingRule rule : this.rules) { + description.append('('); + description.append(rule.predicate().toString()); + description.append(':'); + description.append(rule.sampler().getDescription()); + description.append(')'); + description.append(','); + } + // Remove trailing comma + description.setLength(description.length() - 1); + } + description.append("]}"); + this.description = description.toString(); + } + + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + for (SamplingRule rule : rules) { + if (rule.predicate().matches(parentContext, name, spanKind, attributes, parentLinks)) { + return rule.sampler() + .getSamplingIntent(parentContext, name, spanKind, attributes, parentLinks); + } + } + return NON_SAMPLING_INTENT; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return this.getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSamplerBuilder.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSamplerBuilder.java new file mode 100644 index 00000000000..1dd70d246bf --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSamplerBuilder.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import java.util.ArrayList; +import java.util.List; + +/** A builder for a composable rule-based sampler. */ +public final class ComposableRuleBasedSamplerBuilder { + private final List rules = new ArrayList<>(); + + ComposableRuleBasedSamplerBuilder() {} + + /** + * Adds a rule to use the given {@link ComposableSampler} if the {@link SamplingPredicate} + * matches. + */ + public ComposableRuleBasedSamplerBuilder add( + SamplingPredicate predicate, ComposableSampler sampler) { + rules.add(ImmutableSamplingRule.create(predicate, sampler)); + return this; + } + + /** Returns a {@link ComposableSampler} with the rules in this builder. */ + public ComposableSampler build() { + return new ComposableRuleBasedSampler(rules); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableSampler.java new file mode 100644 index 00000000000..09b16e323a5 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableSampler.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +/** A sampler that can be composed to make a final sampling decision. */ +public interface ComposableSampler { + /** Returns a {@link ComposableSampler} that does not sample any span. */ + static ComposableSampler alwaysOff() { + return ComposableAlwaysOffSampler.INSTANCE; + } + + /** Returns a {@link ComposableSampler} that samples all spans. */ + static ComposableSampler alwaysOn() { + return ComposableAlwaysOnSampler.INSTANCE; + } + + /** Returns a {@link ComposableSampler} that samples each span with a fixed ratio. */ + static ComposableSampler probability(double ratio) { + return new ComposableProbabilitySampler(ratio); + } + + /** + * Returns a {@link ComposableSampler} that respects the sampling decision of the parent span or + * falls back to the given sampler if it is a root span. + */ + static ComposableSampler parentThreshold(ComposableSampler rootSampler) { + return new ComposableParentThresholdSampler(rootSampler); + } + + /** + * Returns a {@link ComposableRuleBasedSamplerBuilder} to create a composable rule-based sampler. + * Rules will be tested in order, and the first to match will have its {@link ComposableSampler} + * used for a sampling decision. If no rule matches, the span will be dropped. + */ + static ComposableRuleBasedSamplerBuilder ruleBasedBuilder() { + return new ComposableRuleBasedSamplerBuilder(); + } + + /** + * Returns a {@link ComposableSampler} that adds the given {@link Attributes} to all sampled + * spans. + */ + static ComposableSampler annotating(ComposableSampler sampler, Attributes attributes) { + return new ComposableAnnotatingSampler(sampler, attributes); + } + + /** Returns the {@link SamplingIntent} to use to make a sampling decision. */ + SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks); + + /** Returns a description of the sampler implementation. */ + String getDescription(); +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/CompositeSampler.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/CompositeSampler.java new file mode 100644 index 00000000000..8f3f28dc705 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/CompositeSampler.java @@ -0,0 +1,116 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_THRESHOLD; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.isValidThreshold; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.OtelTraceState.OTEL_TRACE_STATE_KEY; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.internal.RandomSupplier; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.List; + +/** + * A sampler that uses a {@link ComposableSampler} to make its sampling decisions while handlign + * tracestate. + */ +public final class CompositeSampler implements Sampler { + /** + * Returns a new composite {@link Sampler} that delegates to the given {@link ComposableSampler}. + */ + public static Sampler wrap(ComposableSampler delegate) { + return new CompositeSampler(delegate); + } + + private final ComposableSampler delegate; + + private CompositeSampler(ComposableSampler delegate) { + this.delegate = delegate; + } + + @Override + public SamplingResult shouldSample( + Context parentContext, + String traceId, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + TraceState traceState = Span.fromContext(parentContext).getSpanContext().getTraceState(); + OtelTraceState otelTraceState = OtelTraceState.parse(traceState); + + SamplingIntent intent = + delegate.getSamplingIntent(parentContext, name, spanKind, attributes, parentLinks); + + boolean adjustedCountReliable = false; + boolean sampled = false; + if (isValidThreshold(intent.getThreshold())) { + adjustedCountReliable = intent.isAdjustedCountReliable(); + long randomValue; + if (adjustedCountReliable) { + randomValue = otelTraceState.getRandomValueOrFromTraceId(traceId); + } else { + randomValue = RandomSupplier.platformDefault().get().nextLong() & 0x00FFFFFFFFFFFFFFL; + } + sampled = intent.getThreshold() <= randomValue; + } + + SamplingDecision decision = + sampled ? SamplingDecision.RECORD_AND_SAMPLE : SamplingDecision.DROP; + if (sampled && adjustedCountReliable) { + otelTraceState = + new OtelTraceState( + otelTraceState.getRandomValue(), intent.getThreshold(), otelTraceState.getRest()); + } else { + otelTraceState = + new OtelTraceState( + otelTraceState.getRandomValue(), INVALID_THRESHOLD, otelTraceState.getRest()); + } + + String serializedState = otelTraceState.serialize(); + return new SamplingResult() { + @Override + public SamplingDecision getDecision() { + return decision; + } + + @Override + public Attributes getAttributes() { + return intent.getAttributes(); + } + + @Override + public TraceState getUpdatedTraceState(TraceState parentTraceState) { + TraceState newTraceState = intent.getTraceStateUpdater().apply(traceState, decision); + if (!serializedState.isEmpty()) { + newTraceState = + newTraceState.toBuilder().put(OTEL_TRACE_STATE_KEY, serializedState).build(); + } else if (newTraceState.get(OTEL_TRACE_STATE_KEY) != null) { + newTraceState = newTraceState.toBuilder().remove(OTEL_TRACE_STATE_KEY).build(); + } + return newTraceState; + } + }; + } + + @Override + public String getDescription() { + return delegate.getDescription(); + } + + @Override + public String toString() { + return this.getDescription(); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ImmutableSamplingIntent.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ImmutableSamplingIntent.java new file mode 100644 index 00000000000..d1194891fa6 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ImmutableSamplingIntent.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import java.util.function.BiFunction; + +@AutoValue +abstract class ImmutableSamplingIntent implements SamplingIntent { + private static final int RANDOM_VALUE_BITS = 56; + + static final long INVALID_THRESHOLD = -1; + static final long INVALID_RANDOM_VALUE = -1; + static final long MIN_THRESHOLD = 0; + static final long MAX_THRESHOLD = 1L << RANDOM_VALUE_BITS; + static final long MAX_RANDOM_VALUE = MAX_THRESHOLD - 1; + + static final BiFunction NO_TRACE_STATE_UPDATE = + (traceState, decision) -> traceState; + + static final SamplingIntent NON_SAMPLING_INTENT = + create( + ImmutableSamplingIntent.INVALID_THRESHOLD, + /* adjustedCountReliable= */ false, + Attributes.empty(), + NO_TRACE_STATE_UPDATE); + + static boolean isValidThreshold(long threshold) { + return threshold >= MIN_THRESHOLD && threshold <= MAX_THRESHOLD; + } + + static boolean isValidRandomValue(long randomValue) { + return randomValue >= 0 && randomValue <= MAX_RANDOM_VALUE; + } + + static ImmutableSamplingIntent create( + long threshold, + boolean adjustedCountReliable, + Attributes attributes, + BiFunction traceStateUpdater) { + return new AutoValue_ImmutableSamplingIntent( + threshold, adjustedCountReliable, attributes, traceStateUpdater); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ImmutableSamplingRule.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ImmutableSamplingRule.java new file mode 100644 index 00000000000..2d7e11267e3 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ImmutableSamplingRule.java @@ -0,0 +1,16 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import com.google.auto.value.AutoValue; + +@AutoValue +abstract class ImmutableSamplingRule implements SamplingRule { + static final ImmutableSamplingRule create( + SamplingPredicate predicate, ComposableSampler sampler) { + return new AutoValue_ImmutableSamplingRule(predicate, sampler); + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceState.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceState.java new file mode 100644 index 00000000000..9e568461145 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceState.java @@ -0,0 +1,208 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_RANDOM_VALUE; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_THRESHOLD; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.MAX_RANDOM_VALUE; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.MAX_THRESHOLD; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.isValidRandomValue; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.isValidThreshold; + +import io.opentelemetry.api.impl.Base16EncodingUtils; +import io.opentelemetry.api.impl.TemporaryBuffers; +import io.opentelemetry.api.trace.TraceState; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +// https://opentelemetry.io/docs/specs/otel/trace/tracestate-handling/ +final class OtelTraceState { + + private static final OtelTraceState EMPTY = + new OtelTraceState(INVALID_RANDOM_VALUE, INVALID_THRESHOLD, Collections.emptyList()); + + private static final int MAX_OTEL_TRACE_STATE_LENGTH = 256; + // visible for testing + static final int MAX_VALUE_LENGTH = 14; // 56 bits, 4 bits per hex digit + + static final String OTEL_TRACE_STATE_KEY = "ot"; + + static OtelTraceState parse(TraceState traceState) { + String ot = traceState.get(OTEL_TRACE_STATE_KEY); + if (ot == null || ot.isEmpty() || ot.length() > MAX_OTEL_TRACE_STATE_LENGTH) { + return EMPTY; + } + + long threshold = INVALID_THRESHOLD; + long randomValue = INVALID_RANDOM_VALUE; + + List rest = Collections.emptyList(); + int idx = 0; + while (idx < ot.length()) { + int delimIdx = ot.indexOf(';', idx); + String member = delimIdx != -1 ? ot.substring(idx, delimIdx) : ot.substring(idx); + if (member.startsWith("th:")) { + threshold = parseTh(member.substring("th:".length())); + } else if (member.startsWith("rv:")) { + randomValue = parseRv(member.substring("rv:".length())); + } else { + if (rest.isEmpty()) { + rest = new ArrayList<>(); + } + rest.add(member); + } + + if (delimIdx == -1) { + break; + } + idx = delimIdx + 1; + } + + return new OtelTraceState(randomValue, threshold, rest); + } + + private static long parseTh(String th) { + if (th.isEmpty() + || th.length() > MAX_VALUE_LENGTH + || !Base16EncodingUtils.isValidBase16String(th)) { + return INVALID_THRESHOLD; + } + + // Fast path for very common all sampling case + if (th.equals("0")) { + return 0; + } + + return Base16EncodingUtils.longFromBase16String(new PaddedValue(th), 0); + } + + private static long parseRv(String rv) { + if (rv.length() != MAX_VALUE_LENGTH || !Base16EncodingUtils.isValidBase16String(rv)) { + return INVALID_RANDOM_VALUE; + } + + return Base16EncodingUtils.longFromBase16String(new PaddedValue(rv), 0); + } + + static void serializeTh(long threshold, StringBuilder sb) { + if (threshold == 0) { + sb.append('0'); + return; + } + // We only need 56 bits, but we can live with one extra byte being encoded. + char[] buf = TemporaryBuffers.chars(16); + Base16EncodingUtils.longToBase16String(threshold, buf, 0); + int startIdx = 2; + int endIdx = 16; + for (; endIdx > startIdx; endIdx--) { + if (buf[endIdx - 1] != '0') { + break; + } + } + sb.append(buf, startIdx, endIdx - startIdx); + } + + private static void serializeRv(long randomValue, StringBuilder sb) { + // We only need 56 bits, but we can live with one extra byte being encoded. + char[] buf = TemporaryBuffers.chars(16); + Base16EncodingUtils.longToBase16String(randomValue, buf, 0); + int startIdx = 2; + int endIdx = 16; + sb.append(buf, startIdx, endIdx - startIdx); + } + + private final long randomValue; + private final long threshold; + private final List rest; + + OtelTraceState(long randomValue, long threshold, List rest) { + this.randomValue = randomValue; + this.threshold = threshold; + this.rest = rest; + } + + long getRandomValue() { + return randomValue; + } + + /** + * Returns the explicit randomness value if present, otherwise the randomness derived from the + * last 56 bits of the trace ID. + */ + long getRandomValueOrFromTraceId(String traceId) { + if (isValidRandomValue(randomValue)) { + return randomValue; + } + return Base16EncodingUtils.longFromBase16String(traceId, 16) & MAX_RANDOM_VALUE; + } + + long getThreshold() { + return threshold; + } + + List getRest() { + return rest; + } + + String serialize() { + if ((!isValidThreshold(threshold) || threshold == MAX_THRESHOLD) + && !isValidRandomValue(randomValue) + && rest.isEmpty()) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + if (isValidThreshold(threshold) && threshold != MAX_THRESHOLD) { + sb.append("th:"); + serializeTh(threshold, sb); + sb.append(';'); + } + if (isValidRandomValue(randomValue)) { + sb.append("rv:"); + serializeRv(randomValue, sb); + sb.append(';'); + } + for (String member : rest) { + sb.append(member); + sb.append(';'); + } + + // Trim trailing semicolon + sb.setLength(sb.length() - 1); + return sb.toString(); + } + + private static class PaddedValue implements CharSequence { + private final String value; + + PaddedValue(String value) { + this.value = value; + } + + @Override + public int length() { + return 16; + } + + @Override + public char charAt(int index) { + if (index < 2) { + return '0'; + } + index -= 2; + if (index < value.length()) { + return value.charAt(index); + } + return '0'; + } + + @Override + public CharSequence subSequence(int start, int end) { + throw new UnsupportedOperationException(); + } + } +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingIntent.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingIntent.java new file mode 100644 index 00000000000..798dc44c259 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingIntent.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import java.util.function.BiFunction; + +/** Information to make a sampling decision. */ +public interface SamplingIntent { + + /** Returns a {@link SamplingIntent} with the given data. */ + static SamplingIntent create( + long threshold, + boolean adjustedCountReliable, + Attributes attributes, + BiFunction traceStateUpdater) { + return ImmutableSamplingIntent.create( + threshold, adjustedCountReliable, attributes, traceStateUpdater); + } + + /** + * Returns the sampling threshold value. A lower threshold increases the likelihood of sampling. + */ + long getThreshold(); + + /** + * The threshold provided by the SamplingIntent can always be used to determine the sampling + * decision. However, in certain situations it cannot be used to calculate the adjusted count + * (reciprocal of sampling probability, used by Span-to-Metrics estimation) reliably, because a + * non-consistent-probability sampling decision might have affected the threshold value. + * + * @return true if and only if the threshold can be reliably used for adjusted count calculation + */ + boolean isAdjustedCountReliable(); + + /** Returns any attributes to add to the span to record the sampling result. */ + Attributes getAttributes(); + + /** + * Returns a function to apply to the parent tracestate and final sampling decision to possibly + * update the tracestate of the span. The function must not modify the OpenTelemetry {@code ot} + * entry of the tracestate. + */ + BiFunction getTraceStateUpdater(); +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingPredicate.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingPredicate.java new file mode 100644 index 00000000000..e79bfd39a78 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingPredicate.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import java.util.List; + +/** + * A predicate for a composable sampler, indicating whether a set of sampling arguments matches. + * + *

      While this can be implemented with lambda expressions, it is recommended to implement {@link + * Object#toString()} as well with an explanation of the predicate for rendering in {@link + * io.opentelemetry.sdk.trace.samplers.Sampler#getDescription()}. + */ +@FunctionalInterface +public interface SamplingPredicate { + /** Returns whether this {@link SamplingPredicate} matches the given sampling arguments. */ + boolean matches( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks); +} diff --git a/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingRule.java b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingRule.java new file mode 100644 index 00000000000..66c4a1f6bf4 --- /dev/null +++ b/sdk-extensions/incubator/src/main/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/SamplingRule.java @@ -0,0 +1,16 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +/** A rule which returns a {@link ComposableSampler} to use when a predicate matches. */ +interface SamplingRule { + + /** The {@link SamplingPredicate} which indicates whether to use {@link #sampler()}. */ + SamplingPredicate predicate(); + + /** The {@link ComposableSampler} to use when the rule matches. */ + ComposableSampler sampler(); +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/OnEndSpanProcessorPublicAccessTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/OnEndSpanProcessorPublicAccessTest.java new file mode 100644 index 00000000000..618ad068ae7 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/OnEndSpanProcessorPublicAccessTest.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.extension.incubator.trace.OnEndSpanProcessor; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +// Lives outside the trace package to verify OnEndSpanProcessor.create() is callable by users. +class OnEndSpanProcessorPublicAccessTest { + + @Test + void createFromOutsidePackage() { + List endedSpans = new ArrayList<>(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(OnEndSpanProcessor.create(endedSpans::add)) + .build(); + + tracerProvider.get("test").spanBuilder("span").startSpan().end(); + + assertThat(endedSpans).hasSize(1); + assertThat(endedSpans.get(0).getName()).isEqualTo("span"); + tracerProvider.close(); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java new file mode 100644 index 00000000000..4dde80170e5 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/logs/EventToSpanEventBridgeTest.java @@ -0,0 +1,234 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.logs; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.IdGenerator; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.time.Instant; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class EventToSpanEventBridgeTest { + + private final InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); + private final SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .setSampler(onlyServerSpans()) + .addSpanProcessor(SimpleSpanProcessor.create(spanExporter)) + .build(); + private final TestClock testClock = TestClock.create(); + private final SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .setClock(testClock) + .addLogRecordProcessor(EventToSpanEventBridge.create()) + .build(); + private final Tracer tracer = tracerProvider.get("tracer"); + private final Logger logger = loggerProvider.get("event-logger"); + + private static Sampler onlyServerSpans() { + return new Sampler() { + @Override + public SamplingResult shouldSample( + Context parentContext, + String traceId, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return SpanKind.SERVER.equals(spanKind) + ? SamplingResult.recordAndSample() + : SamplingResult.drop(); + } + + @Override + public String getDescription() { + return "description"; + } + }; + } + + @Test + void withRecordingSpan_bridgesEventWithAttributes() { + Span span = tracer.spanBuilder("span").setSpanKind(SpanKind.SERVER).startSpan(); + try (Scope unused = span.makeCurrent()) { + logger + .logRecordBuilder() + .setEventName("my.event-name") + .setTimestamp(100, TimeUnit.NANOSECONDS) + .setSeverity(Severity.DEBUG) + .setAttribute(AttributeKey.stringKey("color"), "red") + .setAttribute(AttributeKey.stringKey("shape"), "square") + .emit(); + } finally { + span.end(); + } + + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactly(spanData -> + assertThat(spanData) + .hasName("span") + .hasEventsSatisfyingExactly(spanEvent -> + spanEvent + .hasName("my.event-name") + .hasTimestamp(100, TimeUnit.NANOSECONDS) + .hasAttributes( + Attributes.of( + stringKey("color"), "red", + stringKey("shape"), "square")))); + } + + @Test + void timestamp_fallsBackToObservedTimestamp() { + // Set observed time to 1ms = 1_000_000 ns via the test clock + testClock.setTime(Instant.ofEpochMilli(1)); + + Span span = tracer.spanBuilder("span").setSpanKind(SpanKind.SERVER).startSpan(); + try (Scope unused = span.makeCurrent()) { + // No explicit timestamp β€” SDK sets observedTimestamp from the clock + logger.logRecordBuilder().setEventName("my.event-name").emit(); + } finally { + span.end(); + } + + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactly(spanData -> + assertThat(spanData) + .hasName("span") + .hasEventsSatisfyingExactly( + // observedTimestamp is 1ms = 1_000_000 ns + spanEvent -> + spanEvent + .hasName("my.event-name") + .hasTimestamp(1_000_000, TimeUnit.NANOSECONDS))); + } + + @Test + void nonRecordingSpan_doesNotBridgeEvent() { + // INTERNAL kind is dropped by the sampler, producing a non-recording span + Span span = tracer.spanBuilder("span").setSpanKind(SpanKind.INTERNAL).startSpan(); + try (Scope unused = span.makeCurrent()) { + logger + .logRecordBuilder() + .setEventName("my.event-name") + .setTimestamp(100, TimeUnit.NANOSECONDS) + .emit(); + } finally { + span.end(); + } + + assertThat(spanExporter.getFinishedSpanItems()) + .allSatisfy(spanData -> assertThat(spanData.getEvents()).isEmpty()); + } + + @Test + void differentSpanContext_doesNotBridgeEvent() { + Span span = tracer.spanBuilder("span").setSpanKind(SpanKind.SERVER).startSpan(); + try (Scope unused = span.makeCurrent()) { + // Override the log's context to reference a different span + logger + .logRecordBuilder() + .setEventName("my.event-name") + .setContext( + Span.wrap( + SpanContext.create( + IdGenerator.random().generateTraceId(), + IdGenerator.random().generateSpanId(), + TraceFlags.getDefault(), + TraceState.getDefault())) + .storeInContext(Context.current())) + .setTimestamp(100, TimeUnit.NANOSECONDS) + .emit(); + } finally { + span.end(); + } + + assertThat(spanExporter.getFinishedSpanItems()) + .allSatisfy(spanData -> assertThat(spanData.getEvents()).isEmpty()); + } + + @Test + void noCurrentSpan_doesNotBridgeEvent() { + logger + .logRecordBuilder() + .setEventName("my.event-name") + .setTimestamp(100, TimeUnit.NANOSECONDS) + .emit(); + + assertThat(spanExporter.getFinishedSpanItems()).isEmpty(); + } + + @Test + void noEventName_doesNotBridgeEvent() { + Span span = tracer.spanBuilder("span").setSpanKind(SpanKind.SERVER).startSpan(); + try (Scope unused = span.makeCurrent()) { + // Emit a plain log record (no event name) + logger.logRecordBuilder().setTimestamp(100, TimeUnit.NANOSECONDS).emit(); + } finally { + span.end(); + } + + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactly(spanData -> + assertThat(spanData) + .hasName("span") + .hasEventsSatisfying(events -> assertThat(events).isEmpty())); + } + + @Test + void usesContextParameter_notAmbientContext() { + // span1: NOT made current β€” its context is passed explicitly to the log record builder + Span span1 = tracer.spanBuilder("span1").setSpanKind(SpanKind.SERVER).startSpan(); + // span2: the ambient current span during emission + Span span2 = tracer.spanBuilder("span2").setSpanKind(SpanKind.SERVER).startSpan(); + try (Scope unused = span2.makeCurrent()) { + logger + .logRecordBuilder() + .setEventName("my.event-name") + .setTimestamp(100, TimeUnit.NANOSECONDS) + // The context passed to onEmit contains span1, not the ambient span2 + .setContext(span1.storeInContext(Context.root())) + .emit(); + } finally { + span1.end(); + span2.end(); + } + + // The bridge MUST use the context parameter (span1), not the ambient context (span2). + assertThat(spanExporter.getFinishedSpanItems()) + .satisfiesExactlyInAnyOrder( + spanData -> + assertThat(spanData) + .hasName("span1") + .hasEventsSatisfyingExactly(event -> event.hasName("my.event-name")), + spanData -> + assertThat(spanData) + .hasName("span2") + .hasEventsSatisfying(events -> assertThat(events).isEmpty())); + } +} diff --git a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java similarity index 80% rename from sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java rename to sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java index 27ef612e2a3..fc340ba5240 100644 --- a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/LeakDetectingSpanProcessorTest.java @@ -41,18 +41,16 @@ void garbageCollectedUnendedSpan() { await() .atMost(Duration.ofSeconds(30)) - .untilAsserted( - () -> { - System.gc(); - assertThat(logs) - .singleElement() - .satisfies( - callerStackTrace -> - assertThat(callerStackTrace.getMessage()) - .matches( - "Span garbage collected before being ended\\. " - + "Thread: \\[.*\\] started span : .*")); - }); + .untilAsserted(() -> { + System.gc(); + assertThat(logs) + .singleElement() + .satisfies(callerStackTrace -> + assertThat(callerStackTrace.getMessage()) + .matches( + "Span garbage collected before being ended\\. " + + "Thread: \\[.*\\] started span : .*")); + }); } @Test diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnEndSpanProcessorTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnEndSpanProcessorTest.java new file mode 100644 index 00000000000..426b68e8131 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnEndSpanProcessorTest.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class OnEndSpanProcessorTest { + + @Test + void endOnly() { + AtomicReference seenSpan = new AtomicReference<>(); + ReadWriteSpan inputSpan = mock(ReadWriteSpan.class); + + SpanProcessor processor = OnEndSpanProcessor.create(seenSpan::set); + + assertThat(processor.isStartRequired()).isFalse(); + assertThat(processor.isEndRequired()).isTrue(); + processor.onEnd(inputSpan); + assertThat(seenSpan.get()).isSameAs(inputSpan); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java new file mode 100644 index 00000000000..9b4dd4feae0 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/OnStartSpanProcessorTest.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class OnStartSpanProcessorTest { + + @Test + void startOnly() { + AtomicReference seenContext = new AtomicReference<>(); + AtomicReference seenSpan = new AtomicReference<>(); + Context context = mock(Context.class); + ReadWriteSpan inputSpan = mock(ReadWriteSpan.class); + + SpanProcessor processor = + OnStartSpanProcessor.create((ctx, span) -> { + seenContext.set(ctx); + seenSpan.set(span); + }); + + assertThat(processor.isStartRequired()).isTrue(); + assertThat(processor.isEndRequired()).isFalse(); + processor.onStart(context, inputSpan); + assertThat(seenContext.get()).isSameAs(context); + assertThat(seenSpan.get()).isSameAs(inputSpan); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/AlwaysRecordSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/AlwaysRecordSamplerTest.java new file mode 100644 index 00000000000..3f362946a23 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/AlwaysRecordSamplerTest.java @@ -0,0 +1,115 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +// Includes work from: +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** Unit tests for {@link AlwaysRecordSampler}. */ +class AlwaysRecordSamplerTest { + + // Mocks + private Sampler mockSampler; + + private AlwaysRecordSampler sampler; + + @BeforeEach + void setUpSamplers() { + mockSampler = mock(Sampler.class); + sampler = AlwaysRecordSampler.create(mockSampler); + } + + @Test + void getDescription() { + when(mockSampler.getDescription()).thenReturn("mockDescription"); + assertThat(sampler.getDescription()).isEqualTo("AlwaysRecordSampler{mockDescription}"); + } + + private static Stream expectedSamplingDecisionArgs() { + return Stream.of( + Arguments.argumentSet( + "RECORD_AND_SAMPLE", + SamplingDecision.RECORD_AND_SAMPLE, + SamplingDecision.RECORD_AND_SAMPLE), + Arguments.argumentSet( + "RECORD_ONLY", SamplingDecision.RECORD_ONLY, SamplingDecision.RECORD_ONLY), + Arguments.argumentSet( + "DROP becomes RECORD_ONLY", SamplingDecision.DROP, SamplingDecision.RECORD_ONLY)); + } + + @ParameterizedTest + @MethodSource("expectedSamplingDecisionArgs") + void shouldSampleReturnsExpectedDecision( + SamplingDecision rootDecision, SamplingDecision expectedDecision) { + SamplingResult rootResult = buildRootSamplingResult(rootDecision); + when(mockSampler.shouldSample(any(), anyString(), anyString(), any(), any(), any())) + .thenReturn(rootResult); + SamplingResult actualResult = + sampler.shouldSample( + Context.current(), + TraceId.fromLongs(1, 2), + "name", + SpanKind.CLIENT, + Attributes.empty(), + Collections.emptyList()); + + if (rootDecision.equals(expectedDecision)) { + assertThat(actualResult).isEqualTo(rootResult); + assertThat(actualResult.getDecision()).isEqualTo(rootDecision); + } else { + assertThat(actualResult).isNotEqualTo(rootResult); + assertThat(actualResult.getDecision()).isEqualTo(expectedDecision); + } + + assertThat(actualResult.getAttributes()).isEqualTo(rootResult.getAttributes()); + TraceState traceState = TraceState.builder().build(); + assertThat(actualResult.getUpdatedTraceState(traceState)) + .isEqualTo(rootResult.getUpdatedTraceState(traceState)); + } + + private static SamplingResult buildRootSamplingResult(SamplingDecision samplingDecision) { + return new SamplingResult() { + @Override + public SamplingDecision getDecision() { + return samplingDecision; + } + + @Override + public Attributes getAttributes() { + return Attributes.of(AttributeKey.stringKey("key"), samplingDecision.name()); + } + + @Override + public TraceState getUpdatedTraceState(TraceState parentTraceState) { + return TraceState.builder().put("key", samplingDecision.name()).build(); + } + }; + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOffSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOffSamplerTest.java new file mode 100644 index 00000000000..a43871b1eb0 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOffSamplerTest.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.TestUtil.traceIdGenerator; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.Collections; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; + +class ComposableAlwaysOffSamplerTest { + @Test + void testDescription() { + assertThat(ComposableSampler.alwaysOff().getDescription()) + .isEqualTo("ComposableAlwaysOffSampler"); + assertThat(ComposableSampler.alwaysOff()).hasToString("ComposableAlwaysOffSampler"); + } + + @Test + void testThreshold() { + assertThat( + ComposableSampler.alwaysOff() + .getSamplingIntent( + Context.root(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()) + .getThreshold()) + .isEqualTo(-1); + } + + @Test + void sampling() { + Supplier generator = traceIdGenerator(); + Sampler sampler = CompositeSampler.wrap(ComposableSampler.alwaysOff()); + int numSampled = 0; + for (int i = 0; i < 10000; i++) { + SamplingResult result = + sampler.shouldSample( + Context.root(), + generator.get(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + if (result.getDecision() == SamplingDecision.RECORD_AND_SAMPLE) { + numSampled++; + } + } + assertThat(numSampled).isZero(); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOnSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOnSamplerTest.java new file mode 100644 index 00000000000..8104d68c86d --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAlwaysOnSamplerTest.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.TestUtil.traceIdGenerator; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.Collections; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; + +class ComposableAlwaysOnSamplerTest { + @Test + void testDescription() { + assertThat(ComposableSampler.alwaysOn().getDescription()) + .isEqualTo("ComposableAlwaysOnSampler"); + assertThat(ComposableSampler.alwaysOn()).hasToString("ComposableAlwaysOnSampler"); + } + + @Test + void testThreshold() { + assertThat( + ComposableSampler.alwaysOn() + .getSamplingIntent( + Context.root(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()) + .getThreshold()) + .isEqualTo(0); + } + + @Test + void sampling() { + Supplier generator = traceIdGenerator(); + Sampler sampler = CompositeSampler.wrap(ComposableSampler.alwaysOn()); + int numSampled = 0; + for (int i = 0; i < 10000; i++) { + SamplingResult result = + sampler.shouldSample( + Context.root(), + generator.get(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + if (result.getDecision() == SamplingDecision.RECORD_AND_SAMPLE) { + numSampled++; + } + } + assertThat(numSampled).isEqualTo(10000); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAnnotatingSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAnnotatingSamplerTest.java new file mode 100644 index 00000000000..6c961c2c141 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableAnnotatingSamplerTest.java @@ -0,0 +1,97 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.context.Context; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class ComposableAnnotatingSamplerTest { + + private static final Attributes ATTRIBUTES = + Attributes.of( + AttributeKey.stringKey("http.route"), "/bear", AttributeKey.longKey("size"), 100L); + + @Test + void testDescription() { + assertThat( + ComposableSampler.annotating(ComposableSampler.alwaysOn(), Attributes.empty()) + .getDescription()) + .isEqualTo("ComposableAnnotatingSampler{ComposableAlwaysOnSampler,{}}"); + assertThat( + ComposableSampler.annotating(ComposableSampler.alwaysOn(), ATTRIBUTES).getDescription()) + .isEqualTo( + "ComposableAnnotatingSampler{ComposableAlwaysOnSampler,{http.route=\"/bear\", size=100}}"); + } + + @Test + void descriptionInComposedSampler() { + // The annotating sampler must override toString() so that samplers composing it (which build + // their description by concatenating the nested sampler) surface its real description instead + // of an Object hash. + String description = + ComposableSampler.parentThreshold( + ComposableSampler.annotating(ComposableSampler.alwaysOn(), Attributes.empty())) + .getDescription(); + assertThat(description) + .isEqualTo( + "ComposableParentThresholdSampler{rootSampler=ComposableAnnotatingSampler{ComposableAlwaysOnSampler,{}}}"); + assertThat(description).doesNotContain("@"); + } + + @Test + void setsAttributes() { + SamplingIntent intent = + ComposableSampler.annotating(ComposableSampler.alwaysOn(), ATTRIBUTES) + .getSamplingIntent( + Context.root(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isEqualTo(0); + assertThat(intent.getAttributes()).isEqualTo(ATTRIBUTES); + } + + @Test + void mergesAttributes() { + // Easiest way to have a SamplingIntent with attributes is to use annotating sampler itself. + // This effectively creates a "test coverage dependency" where we know it's ok since we verify + // the base case in setsAttributes(). + ComposableSampler baseSampler = + ComposableSampler.annotating( + ComposableSampler.alwaysOn(), + Attributes.of( + AttributeKey.stringKey("http.route"), + "/cat", + AttributeKey.stringKey("type"), + "mammal")); + + SamplingIntent intent = + ComposableSampler.annotating(baseSampler, ATTRIBUTES) + .getSamplingIntent( + Context.root(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isEqualTo(0); + assertThat(intent.getAttributes()) + .isEqualTo( + Attributes.of( + AttributeKey.stringKey("http.route"), + "/bear", + AttributeKey.longKey("size"), + 100L, + AttributeKey.stringKey("type"), + "mammal")); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableParentThresholdSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableParentThresholdSamplerTest.java new file mode 100644 index 00000000000..ac635c7c299 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableParentThresholdSamplerTest.java @@ -0,0 +1,172 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +public class ComposableParentThresholdSamplerTest { + @Test + void testDescription() { + assertThat(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()).getDescription()) + .isEqualTo("ComposableParentThresholdSampler{rootSampler=ComposableAlwaysOnSampler}"); + assertThat(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn())) + .hasToString("ComposableParentThresholdSampler{rootSampler=ComposableAlwaysOnSampler}"); + } + + @Test + void rootSpan() { + assertThat( + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()) + .getThreshold()) + .isEqualTo(0); + } + + @Test + void parentWithThreshold() { + SpanContext parentSpanContext = + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getSampled(), + TraceState.builder() + .put("ot", new OtelTraceState(10, 10, Collections.emptyList()).serialize()) + .build()); + SamplingIntent intent = + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root().with(Span.wrap(parentSpanContext)), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isEqualTo(10); + assertThat(intent.isAdjustedCountReliable()).isTrue(); + } + + @Test + void parentWithInconsistentThresholdSampled() { + // Sampled even though rv < th, so the threshold is erased and the sampled flag is used. + SpanContext parentSpanContext = + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getSampled(), + TraceState.builder() + .put("ot", new OtelTraceState(1, 10, Collections.emptyList()).serialize()) + .build()); + SamplingIntent intent = + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root().with(Span.wrap(parentSpanContext)), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isZero(); + assertThat(intent.isAdjustedCountReliable()).isFalse(); + } + + @Test + void parentWithInconsistentThresholdSampledTraceIdRandomness() { + // No rv, so randomness comes from the trace ID, which is 2 here. + SpanContext parentSpanContext = + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getSampled(), + TraceState.builder().put("ot", "th:8").build()); + SamplingIntent intent = + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root().with(Span.wrap(parentSpanContext)), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isZero(); + assertThat(intent.isAdjustedCountReliable()).isFalse(); + } + + @Test + void parentWithThresholdNotSampled() { + SpanContext parentSpanContext = + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getDefault(), + TraceState.builder() + .put("ot", new OtelTraceState(1, 10, Collections.emptyList()).serialize()) + .build()); + SamplingIntent intent = + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root().with(Span.wrap(parentSpanContext)), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isEqualTo(10); + assertThat(intent.isAdjustedCountReliable()).isTrue(); + } + + @Test + void parentWithoutThresholdSampled() { + SpanContext parentSpanContext = + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getSampled(), + TraceState.getDefault()); + SamplingIntent intent = + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root().with(Span.wrap(parentSpanContext)), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isZero(); + assertThat(intent.isAdjustedCountReliable()).isFalse(); + } + + @Test + void parentWithoutThresholdNotSampled() { + SpanContext parentSpanContext = + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getDefault(), + TraceState.getDefault()); + SamplingIntent intent = + ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()) + .getSamplingIntent( + Context.root().with(Span.wrap(parentSpanContext)), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + assertThat(intent.getThreshold()).isEqualTo(-1); + assertThat(intent.isAdjustedCountReliable()).isFalse(); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableProbabilitySamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableProbabilitySamplerTest.java new file mode 100644 index 00000000000..77db6b0f575 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableProbabilitySamplerTest.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.TestUtil.traceIdGenerator; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.Collections; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class ComposableProbabilitySamplerTest { + @Test + void testDescription() { + assertThat(ComposableSampler.probability(1.0).getDescription()) + .isEqualTo("ComposableProbabilitySampler{threshold=0, ratio=1.0}"); + assertThat(ComposableSampler.probability(1.0)) + .hasToString("ComposableProbabilitySampler{threshold=0, ratio=1.0}"); + + assertThat(ComposableSampler.probability(0.5).getDescription()) + .isEqualTo("ComposableProbabilitySampler{threshold=8, ratio=0.5}"); + assertThat(ComposableSampler.probability(0.25).getDescription()) + .isEqualTo("ComposableProbabilitySampler{threshold=c, ratio=0.25}"); + assertThat(ComposableSampler.probability(1e-300).getDescription()) + .isEqualTo("ComposableProbabilitySampler{threshold=max, ratio=1.0E-300}"); + assertThat(ComposableSampler.probability(0).getDescription()) + .isEqualTo("ComposableProbabilitySampler{threshold=max, ratio=0.0}"); + } + + @ParameterizedTest + @CsvSource({ + "1.0, 0", + "0.5, 36028797018963968", + "0.25, 54043195528445952", + "0.125, 63050394783186944", + "0.0, 72057594037927936", + "0.45, 39631676720860364", + "0.2, 57646075230342348", + "0.13, 62690106812997304", + "0.05, 68454714336031539", + }) + void sampling(double ratio, long threshold) { + Supplier generator = traceIdGenerator(); + Sampler sampler = CompositeSampler.wrap(ComposableSampler.probability(ratio)); + int numSampled = 0; + for (int i = 0; i < 10000; i++) { + SamplingResult result = + sampler.shouldSample( + Context.root(), + generator.get(), + "span", + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()); + if (result.getDecision() == SamplingDecision.RECORD_AND_SAMPLE) { + numSampled++; + OtelTraceState otTraceState = + OtelTraceState.parse(result.getUpdatedTraceState(TraceState.getDefault())); + assertThat(otTraceState.getThreshold()).isEqualTo(threshold); + assertThat(otTraceState.getRandomValue()).isEqualTo(-1); + } + } + int expectedNumSampled = (int) Math.round(10000 * ratio); + // NB: It would be better to calculate a standard deviation based on the numbers. + // But our random seed in TestUtil conveniently allows the test to pass so don't bother. + assertThat(Math.abs(numSampled - expectedNumSampled)).isLessThan(50); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSamplerTest.java new file mode 100644 index 00000000000..da695806fd4 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/ComposableRuleBasedSamplerTest.java @@ -0,0 +1,169 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +class ComposableRuleBasedSamplerTest { + + private static final AttributeKey HTTP_ROUTE = AttributeKey.stringKey("http.route"); + + private static final class AttributePredicate implements SamplingPredicate { + + private final AttributeKey key; + private final T value; + private final String description; + + private AttributePredicate(AttributeKey key, T value) { + this.key = key; + this.value = value; + this.description = key.getKey() + "=" + value; + } + + @Override + public boolean matches( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return value.equals(attributes.get(key)); + } + + @Override + public String toString() { + return description; + } + } + + private enum IsRootPredicate implements SamplingPredicate { + INSTANCE; + + @Override + public boolean matches( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return !Span.fromContext(parentContext).getSpanContext().isValid(); + } + + @Override + public String toString() { + return "isRoot"; + } + } + + @Test + void testDescription() { + assertThat(ComposableSampler.ruleBasedBuilder().build().getDescription()) + .isEqualTo("ComposableRuleBasedSampler{[]}"); + assertThat( + ComposableSampler.ruleBasedBuilder() + .add(new AttributePredicate<>(HTTP_ROUTE, "/health"), ComposableSampler.alwaysOff()) + .build() + .getDescription()) + .isEqualTo("ComposableRuleBasedSampler{[(http.route=/health:ComposableAlwaysOffSampler)]}"); + assertThat( + ComposableSampler.ruleBasedBuilder() + .add(new AttributePredicate<>(HTTP_ROUTE, "/health"), ComposableSampler.alwaysOff()) + .add(IsRootPredicate.INSTANCE, ComposableSampler.alwaysOn()) + .build() + .getDescription()) + .isEqualTo( + "ComposableRuleBasedSampler{[(http.route=/health:ComposableAlwaysOffSampler),(isRoot:ComposableAlwaysOnSampler)]}"); + } + + @Test + void noRules() { + Sampler sampler = CompositeSampler.wrap(ComposableSampler.ruleBasedBuilder().build()); + assertThat( + sampler + .shouldSample( + Context.root(), + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()) + .getDecision()) + .isEqualTo(SamplingDecision.DROP); + } + + @Test + void rules() { + Sampler sampler = + CompositeSampler.wrap( + ComposableSampler.ruleBasedBuilder() + .add(new AttributePredicate<>(HTTP_ROUTE, "/check"), ComposableSampler.alwaysOff()) + .add(IsRootPredicate.INSTANCE, ComposableSampler.alwaysOn()) + .build()); + + // root health check + assertThat( + sampler + .shouldSample( + Context.root(), + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + SpanKind.SERVER, + Attributes.of(HTTP_ROUTE, "/check"), + Collections.emptyList()) + .getDecision()) + .isEqualTo(SamplingDecision.DROP); + + // root + assertThat( + sampler + .shouldSample( + Context.root(), + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()) + .getDecision()) + .isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + + // no match + assertThat( + sampler + .shouldSample( + Context.root() + .with( + Span.wrap( + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(2), + TraceFlags.getSampled(), + TraceState.getDefault()))), + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + SpanKind.SERVER, + Attributes.empty(), + Collections.emptyList()) + .getDecision()) + .isEqualTo(SamplingDecision.DROP); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/CompositeSamplerTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/CompositeSamplerTest.java new file mode 100644 index 00000000000..82bc79b6551 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/CompositeSamplerTest.java @@ -0,0 +1,395 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_RANDOM_VALUE; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_THRESHOLD; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.isValidRandomValue; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.isValidThreshold; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.trace.data.LinkData; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.util.Collections; +import java.util.List; +import java.util.Locale; +import java.util.OptionalLong; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class CompositeSamplerTest { + private static class Input { + private static final String traceId = "00112233445566778800000000000000"; + private static final String spanId = "0123456789abcdef"; + private static final String name = "name"; + private static final SpanKind spanKind = SpanKind.SERVER; + private static final Attributes attributes = Attributes.empty(); + private static final List parentLinks = Collections.emptyList(); + private boolean parentSampled = true; + + private OptionalLong parentThreshold = OptionalLong.empty(); + private OptionalLong parentRandomValue = OptionalLong.empty(); + + void setParentSampled(boolean parentSampled) { + this.parentSampled = parentSampled; + } + + void setParentThreshold(long parentThreshold) { + assertThat(parentThreshold).isBetween(0L, 0xffffffffffffffL); + this.parentThreshold = OptionalLong.of(parentThreshold); + } + + void setParentRandomValue(long parentRandomValue) { + assertThat(parentRandomValue).isBetween(0L, 0xffffffffffffffL); + this.parentRandomValue = OptionalLong.of(parentRandomValue); + } + + Context getParentContext() { + return createParentContext( + traceId, spanId, parentThreshold, parentRandomValue, parentSampled); + } + + static String getTraceId() { + return traceId; + } + + static String getName() { + return name; + } + + static SpanKind getSpanKind() { + return spanKind; + } + + static Attributes getAttributes() { + return attributes; + } + + static List getParentLinks() { + return parentLinks; + } + } + + private static class Output { + + private final SamplingResult samplingResult; + private final Context parentContext; + + Output(SamplingResult samplingResult, Context parentContext) { + this.samplingResult = samplingResult; + this.parentContext = parentContext; + } + + OptionalLong getThreshold() { + Span parentSpan = Span.fromContext(parentContext); + OtelTraceState otelTraceState = + OtelTraceState.parse( + samplingResult.getUpdatedTraceState(parentSpan.getSpanContext().getTraceState())); + return isValidThreshold(otelTraceState.getThreshold()) + ? OptionalLong.of(otelTraceState.getThreshold()) + : OptionalLong.empty(); + } + + OptionalLong getRandomValue() { + Span parentSpan = Span.fromContext(parentContext); + OtelTraceState otelTraceState = + OtelTraceState.parse( + samplingResult.getUpdatedTraceState(parentSpan.getSpanContext().getTraceState())); + return isValidRandomValue(otelTraceState.getRandomValue()) + ? OptionalLong.of(otelTraceState.getRandomValue()) + : OptionalLong.empty(); + } + } + + private static TraceState createTraceState(OptionalLong threshold, OptionalLong randomValue) { + long t = threshold.orElse(INVALID_THRESHOLD); + long rv = randomValue.orElse(INVALID_RANDOM_VALUE); + OtelTraceState state = new OtelTraceState(rv, t, Collections.emptyList()); + return TraceState.builder().put("ot", state.serialize()).build(); + } + + private static Context createParentContext( + String traceId, + String spanId, + OptionalLong threshold, + OptionalLong randomValue, + boolean sampled) { + TraceState parentTraceState = createTraceState(threshold, randomValue); + TraceFlags traceFlags = sampled ? TraceFlags.getSampled() : TraceFlags.getDefault(); + SpanContext parentSpanContext = + SpanContext.create(traceId, spanId, traceFlags, parentTraceState); + Span parentSpan = Span.wrap(parentSpanContext); + return parentSpan.storeInContext(Context.root()); + } + + private static Output sample(Input input, Sampler sampler) { + Context parentContext = input.getParentContext(); + SamplingResult samplingResult = + sampler.shouldSample( + parentContext, + Input.getTraceId(), + Input.getName(), + Input.getSpanKind(), + Input.getAttributes(), + Input.getParentLinks()); + return new Output(samplingResult, parentContext); + } + + @Test + void description() { + assertThat( + CompositeSampler.wrap(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn())) + .getDescription()) + .isEqualTo("ComposableParentThresholdSampler{rootSampler=ComposableAlwaysOnSampler}"); + assertThat( + CompositeSampler.wrap(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn()))) + .hasToString("ComposableParentThresholdSampler{rootSampler=ComposableAlwaysOnSampler}"); + } + + @Test + void testMinThresholdWithoutParentRandomValue() { + Input input = new Input(); + + Sampler sampler = CompositeSampler.wrap(ComposableSampler.alwaysOn()); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + assertThat(output.getThreshold()).hasValue(0); + assertThat(output.getRandomValue()).isNotPresent(); + } + + @Test + void testMinThresholdWithParentRandomValue() { + long parentRandomValue = 0x7f99aa40c02744L; + + Input input = new Input(); + input.setParentRandomValue(parentRandomValue); + + Sampler sampler = CompositeSampler.wrap(ComposableSampler.alwaysOn()); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + assertThat(output.getThreshold()).hasValue(0); + assertThat(output.getRandomValue()).hasValue(parentRandomValue); + } + + @Test + void testMaxThreshold() { + Input input = new Input(); + + Sampler sampler = CompositeSampler.wrap(ComposableSampler.probability(0.0)); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.DROP); + assertThat(output.getThreshold()).isNotPresent(); + assertThat(output.getRandomValue()).isNotPresent(); + } + + @Test + void testParentBasedInConsistentMode() { + long parentRandomValue = 0x7f99aa40c02744L; + + Input input = new Input(); + input.setParentRandomValue(parentRandomValue); + input.setParentThreshold(parentRandomValue); + input.setParentSampled(false); // should be ignored + + Sampler sampler = + CompositeSampler.wrap(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn())); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + assertThat(output.getThreshold()).hasValue(parentRandomValue); + assertThat(output.getRandomValue()).hasValue(parentRandomValue); + } + + @Test + void testParentBasedInLegacyMode() { + // No parent threshold present + Input input = new Input(); + + Sampler sampler = + CompositeSampler.wrap(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn())); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + assertThat(output.getThreshold()).isNotPresent(); + assertThat(output.getRandomValue()).isNotPresent(); + } + + @Test + void testHalfThresholdNotSampled() { + Input input = new Input(); + input.setParentRandomValue(0x7FFFFFFFFFFFFFL); + + Sampler sampler = CompositeSampler.wrap(ComposableSampler.probability(0.5)); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.DROP); + assertThat(output.getThreshold()).isNotPresent(); + assertThat(output.getRandomValue()).hasValue(0x7FFFFFFFFFFFFFL); + } + + @Test + void testHalfThresholdSampled() { + Input input = new Input(); + input.setParentRandomValue(0x80000000000000L); + + Sampler sampler = CompositeSampler.wrap(ComposableSampler.probability(0.5)); + + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + assertThat(output.getThreshold()).hasValue(0x80000000000000L); + assertThat(output.getRandomValue()).hasValue(0x80000000000000L); + } + + @Test + void testParentViolatingInvariant() { + + Input input = new Input(); + input.setParentThreshold(0x80000000000000L); + input.setParentRandomValue(0x80000000000000L); + input.setParentSampled(false); + + Sampler sampler = CompositeSampler.wrap(ComposableSampler.probability(1.0)); + Output output = sample(input, sampler); + + assertThat(output.samplingResult.getDecision()).isEqualTo(SamplingDecision.RECORD_AND_SAMPLE); + assertThat(output.getThreshold()).hasValue(0x0L); + assertThat(output.getRandomValue()).hasValue(0x80000000000000L); + } + + // The trace ID used here has randomness 0, so th:8 is inconsistent with a sampled flag. + @ParameterizedTest + @MethodSource("parentThresholdTraceStateCases") + void parentThresholdTraceState( + boolean parentSampled, + TraceState parentTraceState, + SamplingDecision expectedDecision, + TraceState expectedTraceState) { + TraceFlags traceFlags = parentSampled ? TraceFlags.getSampled() : TraceFlags.getDefault(); + Context parentContext = + Span.wrap( + SpanContext.create( + Input.getTraceId(), "0123456789abcdef", traceFlags, parentTraceState)) + .storeInContext(Context.root()); + + Sampler sampler = + CompositeSampler.wrap(ComposableSampler.parentThreshold(ComposableSampler.alwaysOn())); + SamplingResult result = + sampler.shouldSample( + parentContext, + Input.getTraceId(), + Input.getName(), + Input.getSpanKind(), + Input.getAttributes(), + Input.getParentLinks()); + + assertThat(result.getDecision()).isEqualTo(expectedDecision); + assertThat(result.getUpdatedTraceState(parentTraceState).asMap()) + .isEqualTo(expectedTraceState.asMap()); + } + + private static Stream parentThresholdTraceStateCases() { + return Stream.of( + Arguments.argumentSet( + "dropped, only th", + false, + TraceState.builder().put("ot", "th:f").build(), + SamplingDecision.DROP, + TraceState.getDefault()), + Arguments.argumentSet( + "dropped, other vendor", + false, + TraceState.builder().put("ot", "th:8").put("vendor", "x").build(), + SamplingDecision.DROP, + TraceState.builder().put("vendor", "x").build()), + Arguments.argumentSet( + "dropped, keeps rv", + false, + TraceState.builder().put("ot", "th:8;rv:7fffffffffffff").build(), + SamplingDecision.DROP, + TraceState.builder().put("ot", "rv:7fffffffffffff").build()), + Arguments.argumentSet( + "sampled, consistent", + true, + TraceState.builder().put("ot", "th:8;rv:80000000000000").build(), + SamplingDecision.RECORD_AND_SAMPLE, + TraceState.builder().put("ot", "th:8;rv:80000000000000").build()), + Arguments.argumentSet( + "sampled, inconsistent with trace ID", + true, + TraceState.builder().put("ot", "th:8").build(), + SamplingDecision.RECORD_AND_SAMPLE, + TraceState.getDefault()), + Arguments.argumentSet( + "sampled, inconsistent with rv", + true, + TraceState.builder().put("ot", "th:8;rv:7fffffffffffff").build(), + SamplingDecision.RECORD_AND_SAMPLE, + TraceState.builder().put("ot", "rv:7fffffffffffff").build())); + } + + @ParameterizedTest + @MethodSource("traceStateUpdaterCases") + void traceStateUpdaterReceivesDecision(long threshold, SamplingDecision expectedDecision) { + ComposableSampler delegate = + new ComposableSampler() { + @Override + public SamplingIntent getSamplingIntent( + Context parentContext, + String name, + SpanKind spanKind, + Attributes attributes, + List parentLinks) { + return SamplingIntent.create( + threshold, + /* adjustedCountReliable= */ true, + Attributes.empty(), + (traceState, decision) -> + traceState.toBuilder() + .put("decision", decision.name().toLowerCase(Locale.ROOT)) + .build()); + } + + @Override + public String getDescription() { + return "DecisionRecordingSampler"; + } + }; + + Output output = sample(new Input(), CompositeSampler.wrap(delegate)); + + assertThat(output.samplingResult.getDecision()).isEqualTo(expectedDecision); + assertThat(output.samplingResult.getUpdatedTraceState(TraceState.getDefault()).get("decision")) + .isEqualTo(expectedDecision.name().toLowerCase(Locale.ROOT)); + } + + private static Stream traceStateUpdaterCases() { + return Stream.of( + Arguments.argumentSet("sampled", 0L, SamplingDecision.RECORD_AND_SAMPLE), + Arguments.argumentSet("dropped", INVALID_THRESHOLD, SamplingDecision.DROP)); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceStateFuzzTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceStateFuzzTest.java new file mode 100644 index 00000000000..c563ddfc3f1 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceStateFuzzTest.java @@ -0,0 +1,115 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.pholser.junit.quickcheck.generator.InRange; +import edu.berkeley.cs.jqf.fuzz.Fuzz; +import edu.berkeley.cs.jqf.fuzz.JQF; +import edu.berkeley.cs.jqf.fuzz.junit.GuidedFuzzing; +import edu.berkeley.cs.jqf.fuzz.random.NoGuidance; +import io.opentelemetry.api.trace.TraceState; +import java.util.Collections; +import org.junit.jupiter.api.Test; +import org.junit.runner.Result; +import org.junit.runner.RunWith; + +@SuppressWarnings("SystemOut") +class OtelTraceStateFuzzTest { + + @RunWith(JQF.class) + public static class TestCases { + @Fuzz + public void roundTripRandomValues(long rv, long th) { + OtelTraceState input = new OtelTraceState(rv, th, Collections.emptyList()); + OtelTraceState output = + OtelTraceState.parse(TraceState.builder().put("ot", input.serialize()).build()); + assertState(output, rv, th); + } + + @Fuzz + public void roundTripValidValues( + @InRange(minLong = 0, maxLong = ImmutableSamplingIntent.MAX_RANDOM_VALUE) long rv, + @InRange(minLong = 0, maxLong = ImmutableSamplingIntent.MAX_THRESHOLD) long th) { + OtelTraceState input = new OtelTraceState(rv, th, Collections.emptyList()); + OtelTraceState output = + OtelTraceState.parse(TraceState.builder().put("ot", input.serialize()).build()); + assertState(output, rv, th); + } + + private static void assertState(OtelTraceState state, long rv, long th) { + boolean hasRv = false; + boolean hasTh = false; + if (rv >= 0 && rv <= ImmutableSamplingIntent.MAX_RANDOM_VALUE) { + assertThat(state.getRandomValue()).isEqualTo(rv); + hasRv = true; + } else { + assertThat(state.getRandomValue()).isEqualTo(ImmutableSamplingIntent.INVALID_RANDOM_VALUE); + } + if (th >= 0 && th <= ImmutableSamplingIntent.MAX_THRESHOLD) { + assertThat(state.getThreshold()).isEqualTo(th); + hasTh = state.getThreshold() != ImmutableSamplingIntent.MAX_THRESHOLD; + } else { + assertThat(state.getThreshold()).isEqualTo(ImmutableSamplingIntent.INVALID_THRESHOLD); + } + String[] parts = state.serialize().split(";"); + String thStr = null; + String rvStr = null; + if (hasRv && hasTh) { + assertThat(parts).hasSize(2); + thStr = parts[0]; + rvStr = parts[1]; + } else if (hasRv) { + assertThat(parts).hasSize(1); + rvStr = parts[0]; + } else if (hasTh) { + assertThat(parts).hasSize(1); + thStr = parts[0]; + } + + if (hasRv) { + assertThat(rvStr).startsWith("rv:"); + rvStr = rvStr.substring("rv:".length()); + assertThat(rvStr).hasSize(OtelTraceState.MAX_VALUE_LENGTH); + assertThat(rvStr).isHexadecimal(); + } + + if (hasTh) { + assertThat(thStr).startsWith("th:"); + thStr = thStr.substring("th:".length()); + assertThat(thStr).hasSizeBetween(1, OtelTraceState.MAX_VALUE_LENGTH); + assertThat(thStr).isHexadecimal(); + if (th == 0) { + assertThat(thStr).isEqualTo("0"); + } else { + // No trailing zeros + assertThat(thStr).doesNotMatch("[^0]0+$"); + } + } + } + } + + // driver methods to avoid having to use the vintage junit engine, and to enable increasing the + // number of iterations: + + @Test + void roundTripFuzzing() { + Result result = runTestCase("roundTripRandomValues"); + assertThat(result.wasSuccessful()).isTrue(); + } + + @Test + void roundTripValidValues() { + Result result = runTestCase("roundTripValidValues"); + assertThat(result.wasSuccessful()).isTrue(); + } + + private static Result runTestCase(String testCaseName) { + return GuidedFuzzing.run( + TestCases.class, testCaseName, new NoGuidance(10000, System.out), System.out); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceStateTest.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceStateTest.java new file mode 100644 index 00000000000..0d655141481 --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/OtelTraceStateTest.java @@ -0,0 +1,103 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.INVALID_RANDOM_VALUE; +import static io.opentelemetry.sdk.extension.incubator.trace.samplers.ImmutableSamplingIntent.MAX_THRESHOLD; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.trace.TraceState; +import java.util.Collections; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; + +class OtelTraceStateTest { + + private static String getXString(int len) { + return Stream.generate(() -> "X").limit(len).collect(Collectors.joining()); + } + + @ParameterizedTest + @CsvSource({ + "'', ''", + "a, a", + "#, #", + ";, ''", + "a;, a", + "a;b;, a;b", + "animal:bear;food:pizza, animal:bear;food:pizza", + "rv:1234567890abcd, rv:1234567890abcd", + "rv:01020304050607, rv:01020304050607", + "rv:1234567890abcde, ''", + "th:1234567890abcd, th:1234567890abcd", + "th:1234567890abcd, th:1234567890abcd", + "th:10000000000000, th:1", + "th:1234500000000, th:12345", + "th:0, th:0", + "th:100000000000000, ''", + "th:1234567890abcde, ''", + "th:, ''", + "th:x, ''", + "th:100000000000000, ''", + "th:10000000000000, th:1", + "th:1000000000000, th:1", + "th:100000000000, th:1", + "th:10000000000, th:1", + "th:1000000000, th:1", + "th:100000000, th:1", + "th:10000000, th:1", + "th:1000000, th:1", + "th:100000, th:1", + "th:10000, th:1", + "th:1000, th:1", + "th:100, th:1", + "th:10, th:1", + "th:1, th:1", + "th:10000000000001, th:10000000000001", + "th:10000000000010, th:1000000000001", + "rv:x, ''", + "rv:xxxxxxxxxxxxxx, ''", + "rv:100000000000000, ''", + "rv:10000000000000, rv:10000000000000", + "rv:1000000000000, ''", + }) + void roundTrip(String input, String output) { + String result = OtelTraceState.parse(TraceState.builder().put("ot", input).build()).serialize(); + assertThat(result).isEqualTo(output); + } + + @Test + void notTooLong() { + String input = "a:" + getXString(214) + ";rv:1234567890abcd;th:1234567890abcd;x:3"; + String result = OtelTraceState.parse(TraceState.builder().put("ot", input).build()).serialize(); + assertThat(result) + .isEqualTo("th:1234567890abcd;rv:1234567890abcd;a:" + getXString(214) + ";x:3"); + } + + @Test + void tooLong() { + String input = "a:" + getXString(215) + ";rv:1234567890abcd;th:1234567890abcd;x:3"; + String result = OtelTraceState.parse(TraceState.builder().put("ot", input).build()).serialize(); + assertThat(result).isEmpty(); + } + + @Test + void missing() { + String result = OtelTraceState.parse(TraceState.getDefault()).serialize(); + assertThat(result).isEmpty(); + } + + @Test + void emptyMaxThreshold() { + String result = + new OtelTraceState(INVALID_RANDOM_VALUE, MAX_THRESHOLD, Collections.emptyList()) + .serialize(); + assertThat(result).isEmpty(); + } +} diff --git a/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/TestUtil.java b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/TestUtil.java new file mode 100644 index 00000000000..37bdd131dab --- /dev/null +++ b/sdk-extensions/incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/samplers/TestUtil.java @@ -0,0 +1,28 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.incubator.trace.samplers; + +import io.opentelemetry.api.trace.TraceId; +import java.util.Random; +import java.util.function.Supplier; + +final class TestUtil { + + static Supplier traceIdGenerator() { + // Generate a fixed set of random trace IDs for reliable sampling tests. + Random random = new Random(0xabcd1234L); + return () -> { + long a = random.nextLong(); + long b; + do { + b = random.nextLong(); + } while (b == 0); + return TraceId.fromLongs(a, b); + }; + } + + private TestUtil() {} +} diff --git a/sdk-extensions/jaeger-remote-sampler/README.md b/sdk-extensions/jaeger-remote-sampler/README.md index e4c632116d5..76a1f8f088c 100644 --- a/sdk-extensions/jaeger-remote-sampler/README.md +++ b/sdk-extensions/jaeger-remote-sampler/README.md @@ -1,8 +1,6 @@ # Jaeger Remote Sampler -[![Javadocs][javadoc-image]][javadoc-url] - -This module implements [Jaeger remote sampler](https://www.jaegertracing.io/docs/latest/sampling/#collector-sampling-configuration). +This module implements [Jaeger remote sampler](https://www.jaegertracing.io/docs/latest/sampling/#remote-sampling). The sampler configuration is received from collector's gRPC endpoint. ### Example @@ -18,6 +16,3 @@ return SdkTracerProvider.builder() .setSampler(sampler) .build(); ``` - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-jaeger-remote-sampler.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-jaeger-remote-sampler diff --git a/sdk-extensions/jaeger-remote-sampler/build.gradle.kts b/sdk-extensions/jaeger-remote-sampler/build.gradle.kts index 270de3c1463..ca200b2d936 100644 --- a/sdk-extensions/jaeger-remote-sampler/build.gradle.kts +++ b/sdk-extensions/jaeger-remote-sampler/build.gradle.kts @@ -9,18 +9,24 @@ plugins { description = "OpenTelemetry - Jaeger Remote sampler" otelJava.moduleName.set("io.opentelemetry.sdk.extension.trace.jaeger") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.sdk.autoconfigure.declarativeconfig", "io.opentelemetry.sdk.autoconfigure.spi")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider", + "io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider", +)) dependencies { api(project(":sdk:all")) + compileOnly(project(":api:incubator")) compileOnly(project(":sdk-extensions:autoconfigure")) + compileOnly(project(":sdk-extensions:declarative-config")) implementation(project(":sdk:all")) + implementation(project(":exporters:common")) + implementation(project(":exporters:sender:okhttp")) - // TODO(anuraaga): otlp-common has a lot of code not specific to OTLP now. As it's just internal - // code, this mysterious dependency is possibly still OK but we may need a rename or splitting. - implementation(project(":exporters:otlp:common")) - - implementation("com.squareup.okhttp3:okhttp") + annotationProcessor("com.google.auto.value:auto-value") compileOnly("io.grpc:grpc-api") compileOnly("io.grpc:grpc-protobuf") @@ -28,29 +34,50 @@ dependencies { testImplementation(project(":sdk:testing")) testImplementation(project(":sdk-extensions:autoconfigure")) - testImplementation("com.google.protobuf:protobuf-java-util") + testImplementation("com.google.guava:guava") + testImplementation("com.google.protobuf:protobuf-java") testImplementation("com.linecorp.armeria:armeria-junit5") + testImplementation("com.linecorp.armeria:armeria-grpc") testImplementation("com.linecorp.armeria:armeria-grpc-protocol") - testImplementation("org.testcontainers:junit-jupiter") + testImplementation("org.testcontainers:testcontainers-junit-jupiter") } testing { suites { - val testGrpcNetty by registering(JvmTestSuite::class) { + register("testGrpcNetty") { dependencies { implementation(project(":sdk:testing")) - implementation("com.google.protobuf:protobuf-java-util") + implementation(project(":exporters:common")) + implementation(project(":exporters:sender:grpc-managed-channel")) + implementation("com.google.protobuf:protobuf-java") implementation("com.linecorp.armeria:armeria-junit5") implementation("com.linecorp.armeria:armeria-grpc-protocol") - implementation("org.testcontainers:junit-jupiter") + implementation("org.testcontainers:testcontainers-junit-jupiter") implementation("io.grpc:grpc-netty") implementation("io.grpc:grpc-stub") - implementation(project(":exporters:otlp:common")) + } + targets { + all { + testTask { + systemProperty( + "io.opentelemetry.sdk.common.export.GrpcSenderProvider", + "io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSenderProvider" + ) + } + } } } } } +afterEvaluate { + // Classpath when compiling testGrpcNetty, we add dependency management directly + // since it doesn't follow Gradle conventions of naming / properties. + dependencies { + add("testGrpcNettyCompileProtoPath", platform(project(":dependencyManagement"))) + } +} + tasks { check { dependsOn(testing.suites) @@ -59,13 +86,7 @@ tasks { wire { custom { - customHandlerClass = "io.opentelemetry.gradle.ProtoFieldsWireHandler" - } -} - -sourceSets { - main { - java.srcDir("$buildDir/generated/source/wire") + schemaHandlerFactoryClass = "io.opentelemetry.gradle.ProtoFieldsWireHandlerFactory" } } @@ -76,4 +97,9 @@ tasks { compilerArgs.add("-Xlint:-serial") } } + + checkstyleMain { + // overrides the default which includes generated proto sources + source = fileTree("src/main/java") + } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcService.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcService.java deleted file mode 100644 index 1a75796a14f..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcService.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import com.google.common.util.concurrent.Futures; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import io.opentelemetry.exporter.internal.grpc.ManagedChannelUtil; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -final class DefaultGrpcService - implements GrpcService { - - private static final Logger logger = Logger.getLogger(DefaultGrpcService.class.getName()); - - private final String type; - private final ManagedChannel managedChannel; - private final MarshalerServiceStub stub; - private final long timeoutNanos; - - /** Creates a new {@link DefaultGrpcService}. */ - DefaultGrpcService( - String type, - ManagedChannel channel, - MarshalerServiceStub stub, - long timeoutNanos) { - this.type = type; - this.managedChannel = channel; - this.timeoutNanos = timeoutNanos; - this.stub = stub; - } - - @Override - public ResUnMarshalerT execute( - ReqMarshalerT exportRequest, ResUnMarshalerT responseUnmarshaller) { - MarshalerServiceStub stub = this.stub; - if (timeoutNanos > 0) { - stub = stub.withDeadlineAfter(timeoutNanos, TimeUnit.NANOSECONDS); - } - - try { - return Futures.getUnchecked(stub.export(exportRequest)); - } catch (Throwable t) { - Status status = Status.fromThrowable(t); - - if (status.getCode().equals(Status.Code.UNIMPLEMENTED)) { - logger.log( - Level.SEVERE, - "Failed to execute " - + type - + "s. Server responded with UNIMPLEMENTED. " - + "Full error message: " - + status.getDescription()); - } else if (status.getCode().equals(Status.Code.UNAVAILABLE)) { - logger.log( - Level.SEVERE, - "Failed to execute " - + type - + "s. Server is UNAVAILABLE. " - + "Make sure your service is running and reachable from this network. " - + "Full error message:" - + status.getDescription()); - } else { - logger.log( - Level.WARNING, - "Failed to execute " - + type - + "s. Server responded with gRPC status code " - + status.getCode().value() - + ". Error message: " - + status.getDescription()); - } - } - - return responseUnmarshaller; - } - - @Override - public CompletableResultCode shutdown() { - if (managedChannel.isTerminated()) { - return CompletableResultCode.ofSuccess(); - } - return ManagedChannelUtil.shutdownChannel(managedChannel); - } -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcServiceBuilder.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcServiceBuilder.java deleted file mode 100644 index 17e3eeae6e8..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcServiceBuilder.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import static io.grpc.Metadata.ASCII_STRING_MARSHALLER; -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static io.opentelemetry.exporter.internal.grpc.ManagedChannelUtil.toServiceConfig; -import static java.util.Objects.requireNonNull; - -import io.grpc.Codec; -import io.grpc.ManagedChannel; -import io.grpc.ManagedChannelBuilder; -import io.grpc.Metadata; -import io.grpc.stub.MetadataUtils; -import io.opentelemetry.exporter.internal.ExporterBuilderUtil; -import io.opentelemetry.exporter.internal.grpc.ManagedChannelUtil; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporterBuilder; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import java.util.function.Function; -import javax.annotation.Nullable; -import javax.net.ssl.SSLException; - -final class DefaultGrpcServiceBuilder - implements GrpcServiceBuilder { - - private final String type; - private final Function> stubFactory; - private final String grpcServiceName; - - @Nullable private ManagedChannel channel; - private long timeoutNanos; - private URI endpoint; - private boolean compressionEnabled = false; - @Nullable private Metadata metadata; - @Nullable private byte[] trustedCertificatesPem; - @Nullable private byte[] privateKeyPem; - @Nullable private byte[] certificatePem; - @Nullable private RetryPolicy retryPolicy; - - /** Creates a new {@link OkHttpGrpcExporterBuilder}. */ - // Visible for testing - DefaultGrpcServiceBuilder( - String type, - Function> stubFactory, - long defaultTimeoutSecs, - URI defaultEndpoint, - String grpcServiceName) { - this.type = type; - this.stubFactory = stubFactory; - this.grpcServiceName = grpcServiceName; - timeoutNanos = TimeUnit.SECONDS.toNanos(defaultTimeoutSecs); - endpoint = defaultEndpoint; - } - - @Override - public DefaultGrpcServiceBuilder setChannel(ManagedChannel channel) { - requireNonNull(channel, "channel"); - this.channel = channel; - return this; - } - - @Override - public DefaultGrpcServiceBuilder setTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - timeoutNanos = unit.toNanos(timeout); - return this; - } - - @Override - public DefaultGrpcServiceBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - checkArgument(!timeout.isNegative(), "timeout must be non-negative"); - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - @Override - public DefaultGrpcServiceBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - this.endpoint = ExporterBuilderUtil.validateEndpoint(endpoint); - return this; - } - - @Override - public DefaultGrpcServiceBuilder setCompression(String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - this.compressionEnabled = true; - return this; - } - - @Override - public DefaultGrpcServiceBuilder setTrustedCertificates( - byte[] trustedCertificatesPem) { - requireNonNull(trustedCertificatesPem, "trustedCertificatesPem"); - this.trustedCertificatesPem = trustedCertificatesPem; - return this; - } - - @Override - public GrpcServiceBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { - this.privateKeyPem = privateKeyPem; - this.certificatePem = certificatePem; - return this; - } - - @Override - public DefaultGrpcServiceBuilder addHeader(String key, String value) { - requireNonNull(key, "key"); - requireNonNull(value, "value"); - if (metadata == null) { - metadata = new Metadata(); - } - metadata.put(Metadata.Key.of(key, ASCII_STRING_MARSHALLER), value); - return this; - } - - @Override - public DefaultGrpcServiceBuilder addRetryPolicy(RetryPolicy retryPolicy) { - requireNonNull(retryPolicy, "retryPolicy"); - this.retryPolicy = retryPolicy; - return this; - } - - @Override - public GrpcService build() { - ManagedChannel channel = this.channel; - if (channel == null) { - ManagedChannelBuilder managedChannelBuilder = - ManagedChannelBuilder.forTarget(endpoint.getAuthority()); - - if (endpoint.getScheme().equals("https")) { - managedChannelBuilder.useTransportSecurity(); - } else { - managedChannelBuilder.usePlaintext(); - } - - if (metadata != null) { - managedChannelBuilder.intercept(MetadataUtils.newAttachHeadersInterceptor(metadata)); - } - - if (trustedCertificatesPem != null) { - try { - ManagedChannelUtil.setClientKeysAndTrustedCertificatesPem( - managedChannelBuilder, privateKeyPem, certificatePem, trustedCertificatesPem); - } catch (SSLException e) { - throw new IllegalStateException( - "Could not set trusted certificates for gRPC TLS connection, are they valid " - + "X.509 in PEM format?", - e); - } - } - - if (retryPolicy != null) { - managedChannelBuilder.defaultServiceConfig(toServiceConfig(grpcServiceName, retryPolicy)); - } - - channel = managedChannelBuilder.build(); - } - - Codec codec = compressionEnabled ? new Codec.Gzip() : Codec.Identity.NONE; - MarshalerServiceStub stub = - stubFactory.apply(channel).withCompression(codec.getMessageEncoding()); - return new DefaultGrpcService<>(type, channel, stub, timeoutNanos); - } -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcService.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcService.java deleted file mode 100644 index 95ab116a445..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcService.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.grpc.GrpcExporterBuilder; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.sdk.common.CompletableResultCode; -import java.net.URI; -import java.util.function.Function; -import java.util.function.Supplier; - -interface GrpcService { - - /** Returns a new {@link GrpcExporterBuilder}. */ - static - GrpcServiceBuilder builder( - String type, - long defaultTimeoutSecs, - URI defaultEndpoint, - Supplier< - Function>> - stubFactory, - String grpcServiceName, - String grpcEndpointPath) { - return GrpcServiceUtil.serviceBuilder( - type, defaultTimeoutSecs, defaultEndpoint, stubFactory, grpcServiceName, grpcEndpointPath); - } - - /** - * Exports the {@code exportRequest} which is a request {@link Marshaler} for {@code numItems} - * items. - */ - ResUnMarshalerT execute(ReqMarshalerT request, ResUnMarshalerT response); - - /** Shuts the exporter down. */ - CompletableResultCode shutdown(); -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcServiceBuilder.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcServiceBuilder.java deleted file mode 100644 index a977c1d2e71..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcServiceBuilder.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -interface GrpcServiceBuilder { - GrpcServiceBuilder setChannel(ManagedChannel channel); - - GrpcServiceBuilder setTimeout(long timeout, TimeUnit unit); - - GrpcServiceBuilder setTimeout(Duration timeout); - - GrpcServiceBuilder setEndpoint(String endpoint); - - GrpcServiceBuilder setCompression(String compressionMethod); - - GrpcServiceBuilder setTrustedCertificates( - byte[] trustedCertificatesPem); - - GrpcServiceBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem); - - GrpcServiceBuilder addHeader(String key, String value); - - GrpcServiceBuilder addRetryPolicy(RetryPolicy retryPolicy); - - GrpcService build(); -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcServiceUtil.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcServiceUtil.java deleted file mode 100644 index 4d7fe4f0139..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/GrpcServiceUtil.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import java.net.URI; -import java.util.function.Function; -import java.util.function.Supplier; - -final class GrpcServiceUtil { - - private static final boolean USE_OKHTTP; - - static { - boolean useOkhttp = true; - // Use the OkHttp exporter unless grpc-stub is on the classpath. - try { - Class.forName("io.grpc.stub.AbstractStub"); - useOkhttp = false; - } catch (ClassNotFoundException e) { - // Fall through - } - USE_OKHTTP = useOkhttp; - } - - static - GrpcServiceBuilder serviceBuilder( - String type, - long defaultTimeoutSecs, - URI defaultEndpoint, - Supplier< - Function>> - stubFactory, - String grpcServiceName, - String grpcEndpointPath) { - if (USE_OKHTTP) { - return new OkHttpGrpcServiceBuilder<>( - type, grpcEndpointPath, defaultTimeoutSecs, defaultEndpoint); - } else { - return new DefaultGrpcServiceBuilder<>( - type, stubFactory.get(), defaultTimeoutSecs, defaultEndpoint, grpcServiceName); - } - } - - private GrpcServiceUtil() {} -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/ImmutableGrpcSenderConfig.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/ImmutableGrpcSenderConfig.java new file mode 100644 index 00000000000..cba172e97f2 --- /dev/null +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/ImmutableGrpcSenderConfig.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.trace.jaeger.sampler; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.exporter.internal.grpc.ExtendedGrpcSenderConfig; +import io.opentelemetry.sdk.common.export.Compressor; +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +@AutoValue +abstract class ImmutableGrpcSenderConfig implements ExtendedGrpcSenderConfig { + + @SuppressWarnings("TooManyParameters") + static ImmutableGrpcSenderConfig create( + URI endpoint, + String fullMethodName, + @Nullable Compressor compressor, + Duration timeoutNanos, + Duration connectTimeoutNanos, + Supplier>> headersSupplier, + @Nullable RetryPolicy retryPolicy, + @Nullable SSLContext sslContext, + @Nullable X509TrustManager trustManager, + @Nullable ExecutorService executorService, + @Nullable Object managedChannel, + long maxResponseBodySize) { + return new AutoValue_ImmutableGrpcSenderConfig( + endpoint, + fullMethodName, + compressor, + timeoutNanos, + connectTimeoutNanos, + headersSupplier, + retryPolicy, + sslContext, + trustManager, + executorService, + managedChannel, + maxResponseBodySize); + } + + @Override + public abstract long getMaxResponseBodySize(); +} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSampler.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSampler.java index 7f175c51132..9b6cfa0dd84 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSampler.java +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSampler.java @@ -6,48 +6,65 @@ package io.opentelemetry.sdk.extension.trace.jaeger.sampler; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.internal.GuardedBy; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.GrpcResponse; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.samplers.Sampler; import io.opentelemetry.sdk.trace.samplers.SamplingResult; -import java.io.Closeable; +import java.io.IOException; +import java.net.URI; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; /** Remote sampler that gets sampling configuration from remote Jaeger server. */ -public final class JaegerRemoteSampler implements Sampler, Closeable { +public final class JaegerRemoteSampler implements Sampler { private static final Logger logger = Logger.getLogger(JaegerRemoteSampler.class.getName()); private static final String WORKER_THREAD_NAME = JaegerRemoteSampler.class.getSimpleName() + "_WorkerThread"; + private static final String TYPE = "remoteSampling"; private final String serviceName; - private final ScheduledExecutorService pollExecutor; private final ScheduledFuture pollFuture; private volatile Sampler sampler; - private final GrpcService< - SamplingStrategyParametersMarshaler, SamplingStrategyResponseUnMarshaler> - delegate; + private final AtomicBoolean isShutdown = new AtomicBoolean(); + + private final GrpcSender grpcSender; + private final URI endpoint; + private final int pollingIntervalMs; + private final Object lock = new Object(); + + @GuardedBy("lock") + @Nullable + private SamplingStrategyResponse lastStrategyResponse; JaegerRemoteSampler( - GrpcService - delegate, + GrpcSender grpcSender, + URI endpoint, @Nullable String serviceName, int pollingIntervalMs, Sampler initialSampler) { this.serviceName = serviceName != null ? serviceName : ""; - this.delegate = delegate; + this.grpcSender = grpcSender; + this.endpoint = endpoint; + this.pollingIntervalMs = pollingIntervalMs; this.sampler = initialSampler; pollExecutor = Executors.newScheduledThreadPool(1, new DaemonThreadFactory(WORKER_THREAD_NAME)); pollFuture = @@ -67,21 +84,91 @@ public SamplingResult shouldSample( } private void getAndUpdateSampler() { + SamplingStrategyParametersMarshaler marshaler = + SamplingStrategyParametersMarshaler.create(this.serviceName); try { - SamplingStrategyResponseUnMarshaler samplingStrategyResponseUnMarshaler = - delegate.execute( - SamplingStrategyParametersMarshaler.create(this.serviceName), - new SamplingStrategyResponseUnMarshaler()); - SamplingStrategyResponse response = samplingStrategyResponseUnMarshaler.get(); - if (response != null) { - this.sampler = updateSampler(response); - } - } catch (Throwable e) { // keep the timer thread alive + MessageWriter messageWriter = marshaler.toBinaryMessageWriter(); + grpcSender.send(messageWriter, this::onResponse, this::onError); + } catch (Throwable e) { // Catch all to ensure scheduled task continues logger.log(Level.WARNING, "Failed to update sampler", e); } } - private static Sampler updateSampler(SamplingStrategyResponse response) { + private void onResponse(GrpcResponse grpcResponse) { + GrpcStatusCode statusCode = grpcResponse.getStatusCode(); + + if (statusCode == GrpcStatusCode.OK) { + if (isShutdown.get()) { + return; + } + try { + SamplingStrategyResponse strategyResponse = + SamplingStrategyResponseUnMarshaler.read(grpcResponse.getResponseMessage()); + synchronized (lock) { + // Keep the current sampler when the strategy hasn't changed, so stateful samplers such + // as RateLimitingSampler don't lose their state on every poll. + if (strategyResponse.equals(lastStrategyResponse)) { + return; + } + sampler = updateSampler(strategyResponse); + lastStrategyResponse = strategyResponse; + } + } catch (IOException e) { + logger.log(Level.WARNING, "Failed to unmarshal strategy response", e); + } + return; + } + + switch (statusCode) { + case UNIMPLEMENTED: + logger.log( + levelOnFailure(Level.SEVERE), + "Failed to execute " + + TYPE + + "s. Server responded with UNIMPLEMENTED. " + + "Full error message: " + + grpcResponse.getStatusDescription()); + break; + case UNAVAILABLE: + logger.log( + levelOnFailure(Level.SEVERE), + "Failed to execute " + + TYPE + + "s. Server is UNAVAILABLE. " + + "Make sure your service is running and reachable from this network. " + + "Full error message: " + + grpcResponse.getStatusDescription()); + break; + default: + logger.log( + levelOnFailure(Level.WARNING), + "Failed to execute " + + TYPE + + "s. Server responded with gRPC status code " + + statusCode.name() + + ". Error message: " + + grpcResponse.getStatusDescription()); + break; + } + } + + private void onError(Throwable e) { + logger.log( + levelOnFailure(Level.SEVERE), + "Failed to execute " + TYPE + "s. The request could not be executed.", + e); + if (logger.isLoggable(Level.FINEST)) { + logger.log(Level.FINEST, "Failed to execute " + TYPE + "s. Details follow:", e); + } + } + + // Failures after shutdown are typically caused by in-flight requests being cancelled by + // shutdown() and are not actionable, so demote them to FINE. + private Level levelOnFailure(Level defaultLevel) { + return isShutdown.get() ? Level.FINE : defaultLevel; + } + + private static Sampler updateSampler(SamplingStrategyResponse response) throws IOException { SamplingStrategyResponse.PerOperationSamplingStrategies operationSampling = response.perOperationSamplingStrategies; if (operationSampling.strategies.size() > 0) { @@ -98,14 +185,20 @@ private static Sampler updateSampler(SamplingStrategyResponse response) { return Sampler.parentBased( new RateLimitingSampler(response.rateLimitingSamplingStrategy.maxTracesPerSecond)); case UNRECOGNIZED: - throw new AssertionError("unrecognized sampler type"); + throw new IOException("unrecognized sampler type"); } - throw new AssertionError("unrecognized sampler type"); + throw new IOException("unrecognized sampler type"); } @Override public String getDescription() { - return String.format("JaegerRemoteSampler{%s}", this.sampler); + return "JaegerRemoteSampler{sampler=" + + this.sampler + + ", endpoint=" + + this.endpoint + + ", pollingIntervalMs=" + + this.pollingIntervalMs + + "}"; } @Override @@ -122,10 +215,26 @@ public static JaegerRemoteSamplerBuilder builder() { return new JaegerRemoteSamplerBuilder(); } + /** + * Shuts down the sampler, cancelling the polling task and shutting down the gRPC sender. + * + * @since 1.65.0 + */ @Override - public void close() { + @SuppressWarnings("Interruption") + public CompletableResultCode shutdown() { + if (isShutdown.getAndSet(true)) { + return CompletableResultCode.ofSuccess(); + } + pollFuture.cancel(true); pollExecutor.shutdownNow(); - delegate.shutdown(); + return grpcSender.shutdown(); + } + + @Override + @Deprecated + public void close() { + shutdown(); } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerBuilder.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerBuilder.java index f290c40e630..c6b2783e1a2 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerBuilder.java +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerBuilder.java @@ -9,33 +9,53 @@ import io.grpc.ManagedChannel; import io.opentelemetry.api.internal.Utils; +import io.opentelemetry.common.ComponentLoader; +import io.opentelemetry.exporter.internal.EndpointUtil; +import io.opentelemetry.exporter.internal.SenderUtil; +import io.opentelemetry.exporter.internal.TlsConfigHelper; +import io.opentelemetry.sdk.common.export.GrpcSender; +import io.opentelemetry.sdk.common.export.GrpcSenderProvider; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.net.URI; import java.time.Duration; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import javax.annotation.Nullable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; /** A builder for {@link JaegerRemoteSampler}. */ public final class JaegerRemoteSamplerBuilder { private static final String GRPC_SERVICE_NAME = "jaeger.api_v2.SamplingManager"; - // Visible for testing - static final String GRPC_ENDPOINT_PATH = "/" + GRPC_SERVICE_NAME + "/GetSamplingStrategy"; + private static final String GRPC_FULL_METHOD_NAME = + GRPC_SERVICE_NAME + "/" + "GetSamplingStrategy"; private static final String DEFAULT_ENDPOINT_URL = "http://localhost:14250"; private static final URI DEFAULT_ENDPOINT = URI.create(DEFAULT_ENDPOINT_URL); private static final int DEFAULT_POLLING_INTERVAL_MILLIS = 60000; private static final Sampler INITIAL_SAMPLER = Sampler.parentBased(Sampler.traceIdRatioBased(0.001)); + private static final Duration DEFAULT_TIMEOUT = Duration.ofSeconds(10); + private static final long DEFAULT_MAX_RESPONSE_BODY_SIZE = 4 * 1024L * 1024L; - @Nullable private String serviceName; + private URI endpoint = DEFAULT_ENDPOINT; private Sampler initialSampler = INITIAL_SAMPLER; private int pollingIntervalMillis = DEFAULT_POLLING_INTERVAL_MILLIS; - private static final long DEFAULT_TIMEOUT_SECS = 10; + private final TlsConfigHelper tlsConfigHelper = new TlsConfigHelper(); + private Supplier> headerSupplier = Collections::emptyMap; + private long maxResponseBodySize = DEFAULT_MAX_RESPONSE_BODY_SIZE; + + @Nullable private String serviceName; + + // Use Object type since gRPC may not be on the classpath. + @Nullable private Object grpcChannel; - private final GrpcServiceBuilder< - SamplingStrategyParametersMarshaler, SamplingStrategyResponseUnMarshaler> - delegate; + JaegerRemoteSamplerBuilder() {} /** * Sets the service name to be used by this exporter. Required. @@ -54,14 +74,47 @@ public JaegerRemoteSamplerBuilder setServiceName(String serviceName) { */ public JaegerRemoteSamplerBuilder setEndpoint(String endpoint) { requireNonNull(endpoint, "endpoint"); - delegate.setEndpoint(endpoint); + this.endpoint = EndpointUtil.validateEndpoint(endpoint); return this; } /** Sets trusted certificate. */ public JaegerRemoteSamplerBuilder setTrustedCertificates(byte[] trustedCertificatesPem) { requireNonNull(trustedCertificatesPem, "trustedCertificatesPem"); - delegate.setTrustedCertificates(trustedCertificatesPem); + tlsConfigHelper.setTrustManagerFromCerts(trustedCertificatesPem); + return this; + } + + /** + * Sets the client key and the certificate chain to use for verifying client when TLS is enabled. + * The key must be PKCS8, and both must be in PEM format. + * + * @since 1.24.0 + */ + public JaegerRemoteSamplerBuilder setClientTls(byte[] privateKeyPem, byte[] certificatePem) { + requireNonNull(privateKeyPem, "privateKeyPem"); + requireNonNull(certificatePem, "certificatePem"); + tlsConfigHelper.setKeyManagerFromCerts(privateKeyPem, certificatePem); + return this; + } + + /** + * Sets the "bring-your-own" SSLContext for use with TLS. Users should call this _or_ set raw + * certificate bytes, but not both. + */ + public JaegerRemoteSamplerBuilder setSslContext( + SSLContext sslContext, X509TrustManager trustManager) { + tlsConfigHelper.setSslContext(sslContext, trustManager); + return this; + } + + /** + * Set the supplier of headers to add to requests. Applicable only if {@link + * JaegerRemoteSamplerBuilder#setChannel(ManagedChannel)} is not used to set channel. + */ + // TODO(jack-berg): Make public + JaegerRemoteSamplerBuilder setHeaders(Supplier> headerSupplier) { + this.headerSupplier = headerSupplier; return this; } @@ -95,6 +148,18 @@ public JaegerRemoteSamplerBuilder setInitialSampler(Sampler initialSampler) { return this; } + /** + * Sets the maximum number of bytes to read from a sampling strategy response body. If unset, + * defaults to 4 MiB. Must be positive. + * + * @since 1.61.0 + */ + public JaegerRemoteSamplerBuilder setMaxSamplingStrategyResponseBodySize(long bytes) { + Utils.checkArgument(bytes > 0, "maxSamplingStrategyResponseBodySize must be positive"); + this.maxResponseBodySize = bytes; + return this; + } + /** * Sets the managed channel to use when communicating with the backend. Takes precedence over * {@link #setEndpoint(String)} if both are called. @@ -105,7 +170,7 @@ public JaegerRemoteSamplerBuilder setInitialSampler(Sampler initialSampler) { @Deprecated public JaegerRemoteSamplerBuilder setChannel(ManagedChannel channel) { requireNonNull(channel, "channel"); - delegate.setChannel(channel); + this.grpcChannel = channel; return this; } @@ -115,24 +180,37 @@ public JaegerRemoteSamplerBuilder setChannel(ManagedChannel channel) { * @return the remote sampler instance. */ public JaegerRemoteSampler build() { + GrpcSender grpcSender = resolveGrpcSender(); return new JaegerRemoteSampler( - delegate.build(), serviceName, pollingIntervalMillis, initialSampler); - } - - JaegerRemoteSamplerBuilder() { - delegate = - GrpcService.builder( - "remoteSampling", - DEFAULT_TIMEOUT_SECS, - DEFAULT_ENDPOINT, - () -> MarshallerRemoteSamplerServiceGrpc::newFutureStub, - GRPC_SERVICE_NAME, - GRPC_ENDPOINT_PATH); + grpcSender, endpoint, serviceName, pollingIntervalMillis, initialSampler); } - // Visible for testing - GrpcServiceBuilder - getDelegate() { - return delegate; + private GrpcSender resolveGrpcSender() { + ComponentLoader componentLoader = + ComponentLoader.forClassLoader(JaegerRemoteSamplerBuilder.class.getClassLoader()); + GrpcSenderProvider grpcSenderProvider = SenderUtil.resolveGrpcSenderProvider(componentLoader); + Supplier>> headerSupplier = + () -> { + Map> result = new HashMap<>(); + Map supplierResult = this.headerSupplier.get(); + supplierResult.forEach((key, value) -> result.put(key, Collections.singletonList(value))); + return result; + }; + + ImmutableGrpcSenderConfig grpcSenderConfig = + ImmutableGrpcSenderConfig.create( + endpoint, + GRPC_FULL_METHOD_NAME, + null, + DEFAULT_TIMEOUT, + DEFAULT_TIMEOUT, + headerSupplier, + null, + tlsConfigHelper.getSslContext(), + tlsConfigHelper.getTrustManager(), + null, + grpcChannel, + maxResponseBodySize); + return grpcSenderProvider.createSender(grpcSenderConfig); } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProvider.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProvider.java index 70f2314a669..67069cf9397 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProvider.java +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProvider.java @@ -10,16 +10,22 @@ import io.opentelemetry.sdk.trace.samplers.Sampler; import java.util.Map; import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +/** Autoconfiguration provider for the {@code jaeger_remote} sampler. */ public class JaegerRemoteSamplerProvider implements ConfigurableSamplerProvider { + private static final Logger LOGGER = + Logger.getLogger(JaegerRemoteSamplerProvider.class.getName()); + // visible for testing static final String ATTRIBUTE_PROPERTY = "otel.resource.attributes"; static final String SERVICE_NAME_PROPERTY = "otel.service.name"; static final String SAMPLER_ARG_PROPERTY = "otel.traces.sampler.arg"; - + static final String RESOURCE_ATTRIBUTE_SERVICE_NAME_PROPERTY = "service.name"; private static final String ENDPOINT_KEY = "endpoint"; - private static final String POLLING_INTERVAL = "pollingInterval"; + private static final String POLLING_INTERVAL = "pollingIntervalMs"; private static final String INITIAL_SAMPLING_RATE = "initialSamplingRate"; @Override @@ -29,7 +35,7 @@ public Sampler createSampler(ConfigProperties config) { String serviceName = config.getString(SERVICE_NAME_PROPERTY); if (serviceName == null) { Map resourceAttributes = config.getMap(ATTRIBUTE_PROPERTY); - serviceName = resourceAttributes.get(SERVICE_NAME_PROPERTY); + serviceName = resourceAttributes.get(RESOURCE_ATTRIBUTE_SERVICE_NAME_PROPERTY); } if (serviceName != null) { builder.setServiceName(serviceName); @@ -43,9 +49,23 @@ public Sampler createSampler(ConfigProperties config) { builder.setEndpoint(endpoint); } String pollingInterval = params.get(POLLING_INTERVAL); + // Previously, we mistakenly read from pollingInterval. For backwards compatibility, check + // pollingInterval and log warning if set. + if (pollingInterval == null) { + pollingInterval = params.get("pollingInterval"); + if (pollingInterval != null) { + LOGGER.log( + Level.WARNING, + SAMPLER_ARG_PROPERTY + + " contains deprecated \"pollingInterval\" property. Please use \"" + + POLLING_INTERVAL + + "\" instead."); + } + } if (pollingInterval != null) { builder.setPollingInterval(Integer.valueOf(pollingInterval), TimeUnit.MILLISECONDS); } + String initialSamplingRate = params.get(INITIAL_SAMPLING_RATE); if (initialSamplingRate != null) { builder.setInitialSampler( diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/MarshallerRemoteSamplerServiceGrpc.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/MarshallerRemoteSamplerServiceGrpc.java deleted file mode 100644 index cfec3ff6cdd..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/MarshallerRemoteSamplerServiceGrpc.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import static io.grpc.MethodDescriptor.generateFullMethodName; - -import com.google.common.util.concurrent.ListenableFuture; -import io.grpc.CallOptions; -import io.grpc.Channel; -import io.grpc.MethodDescriptor; -import io.grpc.stub.ClientCalls; -import io.opentelemetry.exporter.internal.grpc.MarshalerInputStream; -import io.opentelemetry.exporter.internal.grpc.MarshalerServiceStub; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -class MarshallerRemoteSamplerServiceGrpc { - - private static final String SERVICE_NAME = "jaeger.api_v2.SamplingManager"; - - private static final MethodDescriptor.Marshaller - REQUEST_MARSHALLER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(SamplingStrategyParametersMarshaler value) { - return new MarshalerInputStream(value); - } - - @Override - public SamplingStrategyParametersMarshaler parse(InputStream stream) { - throw new UnsupportedOperationException("Only for serializing"); - } - }; - - private static final MethodDescriptor.Marshaller - RESPONSE_MARSHALLER = - new MethodDescriptor.Marshaller() { - @Override - public InputStream stream(SamplingStrategyResponseUnMarshaler value) { - throw new UnsupportedOperationException("Only for parsing"); - } - - @Override - public SamplingStrategyResponseUnMarshaler parse(InputStream stream) { - SamplingStrategyResponseUnMarshaler unmarshaller = - new SamplingStrategyResponseUnMarshaler(); - try { - unmarshaller.read(readAllBytes(stream)); - } catch (IOException e) { - // could not parse response - throw new IllegalStateException( - "could not parse jaeger remote sampling response", e); - } - return unmarshaller; - } - }; - - private static final MethodDescriptor< - SamplingStrategyParametersMarshaler, SamplingStrategyResponseUnMarshaler> - getPostSpansMethod = - MethodDescriptor - . - newBuilder() - .setType(MethodDescriptor.MethodType.UNARY) - .setFullMethodName(generateFullMethodName(SERVICE_NAME, "GetSamplingStrategy")) - .setRequestMarshaller(REQUEST_MARSHALLER) - .setResponseMarshaller(RESPONSE_MARSHALLER) - .build(); - - static SamplingManagerFutureStub newFutureStub(Channel channel) { - return SamplingManagerFutureStub.newStub(SamplingManagerFutureStub::new, channel); - } - - static final class SamplingManagerFutureStub - extends MarshalerServiceStub< - SamplingStrategyParametersMarshaler, - SamplingStrategyResponseUnMarshaler, - SamplingManagerFutureStub> { - - private SamplingManagerFutureStub(Channel channel, CallOptions callOptions) { - super(channel, callOptions); - } - - @Override - protected SamplingManagerFutureStub build(Channel channel, CallOptions callOptions) { - return new SamplingManagerFutureStub(channel, callOptions); - } - - @Override - public ListenableFuture export( - SamplingStrategyParametersMarshaler request) { - return ClientCalls.futureUnaryCall( - getChannel().newCall(getPostSpansMethod, getCallOptions()), request); - } - } - - private static byte[] readAllBytes(InputStream inputStream) throws IOException { - int bufLen = 4 * 0x400; // 4KB - byte[] buf = new byte[bufLen]; - int readLen; - IOException exception = null; - - try { - try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { - while ((readLen = inputStream.read(buf, 0, bufLen)) != -1) { - outputStream.write(buf, 0, readLen); - } - return outputStream.toByteArray(); - } - } catch (IOException e) { - exception = e; - throw e; - } finally { - if (exception == null) { - inputStream.close(); - } else { - try { - inputStream.close(); - } catch (IOException e) { - exception.addSuppressed(e); - } - } - } - } - - private MarshallerRemoteSamplerServiceGrpc() {} -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcService.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcService.java deleted file mode 100644 index beeb58bab17..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcService.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import io.opentelemetry.exporter.internal.grpc.GrpcRequestBody; -import io.opentelemetry.exporter.internal.grpc.GrpcStatusUtil; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.retry.RetryUtil; -import io.opentelemetry.sdk.common.CompletableResultCode; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; -import okhttp3.Headers; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; -import okhttp3.Response; -import okio.Buffer; -import okio.GzipSource; -import okio.Okio; - -final class OkHttpGrpcService - implements GrpcService { - - private static final String GRPC_STATUS = "grpc-status"; - private static final String GRPC_MESSAGE = "grpc-message"; - - private static final Logger logger = Logger.getLogger(OkHttpGrpcService.class.getName()); - - private final String type; - private final OkHttpClient client; - private final String endpoint; - private final Headers headers; - private final boolean compressionEnabled; - - /** Creates a new {@link OkHttpGrpcService}. */ - OkHttpGrpcService( - String type, - OkHttpClient client, - String endpoint, - Headers headers, - boolean compressionEnabled) { - this.type = type; - this.client = client; - this.endpoint = endpoint; - this.headers = headers; - this.compressionEnabled = compressionEnabled; - } - - @Override - public ResUnMarshalerT execute( - ReqMarshalerT exportRequest, ResUnMarshalerT responseUnmarshaller) { - Request.Builder requestBuilder = new Request.Builder().url(endpoint).headers(headers); - - RequestBody requestBody = new GrpcRequestBody(exportRequest, compressionEnabled); - requestBuilder.post(requestBody); - - try { - Response response = client.newCall(requestBuilder.build()).execute(); - - byte[] bodyBytes = new byte[0]; - try { - bodyBytes = response.body().bytes(); - } catch (IOException ignored) { - // It's unlikely a transport exception would actually be useful in debugging. There may - // be gRPC status information available handled below though, so ignore this exception - // and continue through gRPC error handling logic. In the worst case we will record the - // HTTP error. - } - - String status = grpcStatus(response); - if ("0".equals(status)) { - if (bodyBytes.length > 5) { - ByteArrayInputStream bodyStream = new ByteArrayInputStream(bodyBytes); - bodyStream.skip(5); - if (bodyBytes[0] == '1') { - Buffer buffer = new Buffer(); - buffer.readFrom(bodyStream); - GzipSource gzipSource = new GzipSource(buffer); - bodyBytes = Okio.buffer(gzipSource).getBuffer().readByteArray(); - } else { - bodyBytes = Arrays.copyOfRange(bodyBytes, 5, bodyBytes.length); - } - responseUnmarshaller.read(bodyBytes); - return responseUnmarshaller; - } - return responseUnmarshaller; - } - - // handle non OK status codes - String codeMessage = - status != null ? "gRPC status code " + status : "HTTP status code " + response.code(); - String errorMessage = grpcMessage(response); - - if (GrpcStatusUtil.GRPC_STATUS_UNIMPLEMENTED.equals(status)) { - logger.log( - Level.SEVERE, - "Failed to execute " - + type - + "s. Server responded with UNIMPLEMENTED. " - + "Full error message: " - + errorMessage); - } else if (GrpcStatusUtil.GRPC_STATUS_UNAVAILABLE.equals(status)) { - logger.log( - Level.SEVERE, - "Failed to execute " - + type - + "s. Server is UNAVAILABLE. " - + "Make sure your service is running and reachable from this network. " - + "Full error message:" - + errorMessage); - } else { - logger.log( - Level.WARNING, - "Failed to execute " - + type - + "s. Server responded with " - + codeMessage - + ". Error message: " - + errorMessage); - } - } catch (IOException e) { - logger.log( - Level.SEVERE, - "Failed to execute " - + type - + "s. The request could not be executed. Full error message: " - + e.getMessage()); - } - - return responseUnmarshaller; - } - - @Nullable - private static String grpcStatus(Response response) { - // Status can either be in the headers or trailers depending on error - String grpcStatus = response.header(GRPC_STATUS); - if (grpcStatus == null) { - try { - grpcStatus = response.trailers().get(GRPC_STATUS); - } catch (IOException e) { - // Could not read a status, this generally means the HTTP status is the error. - return null; - } - } - return grpcStatus; - } - - private static String grpcMessage(Response response) { - String message = response.header(GRPC_MESSAGE); - if (message == null) { - try { - message = response.trailers().get(GRPC_MESSAGE); - } catch (IOException e) { - // Fall through - } - } - if (message != null) { - return unescape(message); - } - // Couldn't get message for some reason, use the HTTP status. - return response.message(); - } - - @Override - public CompletableResultCode shutdown() { - client.dispatcher().cancelAll(); - client.dispatcher().executorService().shutdownNow(); - client.connectionPool().evictAll(); - return CompletableResultCode.ofSuccess(); - } - - static boolean isRetryable(Response response) { - // Only retry on gRPC codes which will always come with an HTTP success - if (!response.isSuccessful()) { - return false; - } - - // We don't check trailers for retry since retryable error codes always come with response - // headers, not trailers, in practice. - String grpcStatus = response.header(GRPC_STATUS); - return RetryUtil.retryableGrpcStatusCodes().contains(grpcStatus); - } - - // From grpc-java - - /** Unescape the provided ascii to a unicode {@link String}. */ - private static String unescape(String value) { - for (int i = 0; i < value.length(); i++) { - char c = value.charAt(i); - if (c < ' ' || c >= '~' || (c == '%' && i + 2 < value.length())) { - return doUnescape(value.getBytes(StandardCharsets.US_ASCII)); - } - } - return value; - } - - private static String doUnescape(byte[] value) { - ByteBuffer buf = ByteBuffer.allocate(value.length); - for (int i = 0; i < value.length; ) { - if (value[i] == '%' && i + 2 < value.length) { - try { - buf.put((byte) Integer.parseInt(new String(value, i + 1, 2, StandardCharsets.UTF_8), 16)); - i += 3; - continue; - } catch (NumberFormatException e) { - // ignore, fall through, just push the bytes. - } - } - buf.put(value[i]); - i += 1; - } - return new String(buf.array(), 0, buf.position(), StandardCharsets.UTF_8); - } -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcServiceBuilder.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcServiceBuilder.java deleted file mode 100644 index 25f2774d0f7..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcServiceBuilder.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.grpc.ManagedChannel; -import io.opentelemetry.exporter.internal.ExporterBuilderUtil; -import io.opentelemetry.exporter.internal.TlsUtil; -import io.opentelemetry.exporter.internal.grpc.OkHttpGrpcExporter; -import io.opentelemetry.exporter.internal.marshal.Marshaler; -import io.opentelemetry.exporter.internal.okhttp.OkHttpUtil; -import io.opentelemetry.exporter.internal.retry.RetryInterceptor; -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.time.Duration; -import java.util.Arrays; -import java.util.Collections; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; -import javax.net.ssl.SSLException; -import javax.net.ssl.X509KeyManager; -import javax.net.ssl.X509TrustManager; -import okhttp3.Headers; -import okhttp3.OkHttpClient; -import okhttp3.Protocol; - -final class OkHttpGrpcServiceBuilder< - ReqMarshalerT extends Marshaler, ResUnMarshalerT extends UnMarshaler> - implements GrpcServiceBuilder { - - private final String type; - private final String grpcEndpointPath; - - private long timeoutNanos; - private URI endpoint; - private boolean compressionEnabled = false; - private final Headers.Builder headers = new Headers.Builder(); - @Nullable private byte[] trustedCertificatesPem; - @Nullable private byte[] privateKeyPem; - @Nullable private byte[] certificatePem; - @Nullable private RetryPolicy retryPolicy; - - OkHttpGrpcServiceBuilder( - String type, String grpcEndpointPath, long defaultTimeoutSecs, URI defaultEndpoint) { - this.type = type; - this.grpcEndpointPath = grpcEndpointPath; - timeoutNanos = TimeUnit.SECONDS.toNanos(defaultTimeoutSecs); - endpoint = defaultEndpoint; - } - - @Override - public GrpcServiceBuilder setChannel(ManagedChannel channel) { - throw new UnsupportedOperationException("Only available on DefaultGrpcService"); - } - - @Override - public OkHttpGrpcServiceBuilder setTimeout( - long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - timeoutNanos = unit.toNanos(timeout); - return this; - } - - @Override - public OkHttpGrpcServiceBuilder setTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - checkArgument(!timeout.isNegative(), "timeout must be non-negative"); - return setTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - @Override - public OkHttpGrpcServiceBuilder setEndpoint(String endpoint) { - requireNonNull(endpoint, "endpoint"); - this.endpoint = ExporterBuilderUtil.validateEndpoint(endpoint); - return this; - } - - @Override - public OkHttpGrpcServiceBuilder setCompression( - String compressionMethod) { - requireNonNull(compressionMethod, "compressionMethod"); - checkArgument( - compressionMethod.equals("gzip") || compressionMethod.equals("none"), - "Unsupported compression method. Supported compression methods include: gzip, none."); - this.compressionEnabled = true; - return this; - } - - @Override - public OkHttpGrpcServiceBuilder setTrustedCertificates( - byte[] trustedCertificatesPem) { - requireNonNull(trustedCertificatesPem, "trustedCertificatesPem"); - this.trustedCertificatesPem = trustedCertificatesPem; - return this; - } - - @Override - public GrpcServiceBuilder setClientTls( - byte[] privateKeyPem, byte[] certificatePem) { - requireNonNull(privateKeyPem, "privateKeyPem"); - requireNonNull(certificatePem, "certificatePem"); - this.privateKeyPem = privateKeyPem; - this.certificatePem = certificatePem; - return this; - } - - @Override - public OkHttpGrpcServiceBuilder addHeader( - String key, String value) { - requireNonNull(key, "key"); - requireNonNull(value, "value"); - headers.add(key, value); - return this; - } - - @Override - public OkHttpGrpcServiceBuilder addRetryPolicy( - RetryPolicy retryPolicy) { - requireNonNull(retryPolicy, "retryPolicy"); - this.retryPolicy = retryPolicy; - return this; - } - - @Override - public GrpcService build() { - OkHttpClient.Builder clientBuilder = - new OkHttpClient.Builder().dispatcher(OkHttpUtil.newDispatcher()); - - clientBuilder.callTimeout(Duration.ofNanos(timeoutNanos)); - - if (trustedCertificatesPem != null) { - try { - X509TrustManager trustManager = TlsUtil.trustManager(trustedCertificatesPem); - X509KeyManager keyManager = null; - if (privateKeyPem != null && certificatePem != null) { - keyManager = TlsUtil.keyManager(privateKeyPem, certificatePem); - } - clientBuilder.sslSocketFactory( - TlsUtil.sslSocketFactory(keyManager, trustManager), trustManager); - } catch (SSLException e) { - throw new IllegalStateException( - "Could not set trusted certificates, are they valid X.509 in PEM format?", e); - } - } - - String endpoint = this.endpoint.resolve(grpcEndpointPath).toString(); - if (endpoint.startsWith("http://")) { - clientBuilder.protocols(Collections.singletonList(Protocol.H2_PRIOR_KNOWLEDGE)); - } else { - clientBuilder.protocols(Arrays.asList(Protocol.HTTP_2, Protocol.HTTP_1_1)); - } - - headers.add("te", "trailers"); - if (compressionEnabled) { - headers.add("grpc-encoding", "gzip"); - } - - if (retryPolicy != null) { - clientBuilder.addInterceptor( - new RetryInterceptor(retryPolicy, OkHttpGrpcExporter::isRetryable)); - } - - return new OkHttpGrpcService<>( - type, clientBuilder.build(), endpoint, headers.build(), compressionEnabled); - } -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSampler.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSampler.java index f7ae501957e..e5148526aa2 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSampler.java +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSampler.java @@ -13,12 +13,15 @@ import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.internal.RateLimiter; +import io.opentelemetry.sdk.common.internal.RateLimiter; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.samplers.Sampler; import io.opentelemetry.sdk.trace.samplers.SamplingDecision; import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; import java.util.List; +import java.util.Locale; /** * {@link RateLimitingSampler} sampler uses a leaky bucket rate limiter to ensure that traces are @@ -29,10 +32,10 @@ class RateLimitingSampler implements Sampler { static final AttributeKey SAMPLER_TYPE = stringKey("sampler.type"); static final AttributeKey SAMPLER_PARAM = doubleKey("sampler.param"); - private final double maxTracesPerSecond; private final RateLimiter rateLimiter; private final SamplingResult onSamplingResult; private final SamplingResult offSamplingResult; + private final String description; /** * Creates rate limiting sampler. @@ -40,13 +43,13 @@ class RateLimitingSampler implements Sampler { * @param maxTracesPerSecond the maximum number of sampled traces per second. */ RateLimitingSampler(int maxTracesPerSecond) { - this.maxTracesPerSecond = maxTracesPerSecond; double maxBalance = maxTracesPerSecond < 1.0 ? 1.0 : maxTracesPerSecond; this.rateLimiter = new RateLimiter(maxTracesPerSecond, maxBalance, Clock.getDefault()); Attributes attributes = Attributes.of(SAMPLER_TYPE, TYPE, SAMPLER_PARAM, (double) maxTracesPerSecond); this.onSamplingResult = SamplingResult.create(SamplingDecision.RECORD_AND_SAMPLE, attributes); this.offSamplingResult = SamplingResult.create(SamplingDecision.DROP, attributes); + description = "RateLimitingSampler{" + decimalFormat(maxTracesPerSecond) + "}"; } @Override @@ -62,11 +65,19 @@ public SamplingResult shouldSample( @Override public String getDescription() { - return String.format("RateLimitingSampler{%.2f}", maxTracesPerSecond); + return description; } @Override public String toString() { return getDescription(); } + + private static String decimalFormat(double value) { + DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.ROOT); + decimalFormatSymbols.setDecimalSeparator('.'); + + DecimalFormat decimalFormat = new DecimalFormat("0.00", decimalFormatSymbols); + return decimalFormat.format(value); + } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponse.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponse.java index 7f1d5fc2281..05bd072192f 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponse.java +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponse.java @@ -8,8 +8,9 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; +import javax.annotation.Nullable; -class SamplingStrategyResponse { +final class SamplingStrategyResponse { enum SamplingStrategyType { PROBABILISTIC, @@ -17,13 +18,27 @@ enum SamplingStrategyType { UNRECOGNIZED, } - static class RateLimitingSamplingStrategy { + static final class RateLimitingSamplingStrategy { final int maxTracesPerSecond; private RateLimitingSamplingStrategy(Builder builder) { this.maxTracesPerSecond = builder.maxTracesPerSecond; } + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof RateLimitingSamplingStrategy)) { + return false; + } + RateLimitingSamplingStrategy that = (RateLimitingSamplingStrategy) o; + return maxTracesPerSecond == that.maxTracesPerSecond; + } + + @Override + public int hashCode() { + return Integer.hashCode(maxTracesPerSecond); + } + static class Builder { private int maxTracesPerSecond; @@ -38,13 +53,27 @@ RateLimitingSamplingStrategy build() { } } - static class ProbabilisticSamplingStrategy { + static final class ProbabilisticSamplingStrategy { final double samplingRate; ProbabilisticSamplingStrategy(Builder builder) { this.samplingRate = builder.samplingRate; } + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof ProbabilisticSamplingStrategy)) { + return false; + } + ProbabilisticSamplingStrategy that = (ProbabilisticSamplingStrategy) o; + return Double.doubleToLongBits(samplingRate) == Double.doubleToLongBits(that.samplingRate); + } + + @Override + public int hashCode() { + return Double.hashCode(samplingRate); + } + static class Builder { private double samplingRate; @@ -59,7 +88,7 @@ ProbabilisticSamplingStrategy build() { } } - static class PerOperationSamplingStrategies { + static final class PerOperationSamplingStrategies { final double defaultSamplingProbability; final double defaultLowerBoundTracesPerSecond; final double defaultUpperBoundTracesPerSecond; @@ -72,6 +101,30 @@ private PerOperationSamplingStrategies(Builder builder) { this.strategies = Collections.unmodifiableList(builder.strategies); } + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof PerOperationSamplingStrategies)) { + return false; + } + PerOperationSamplingStrategies that = (PerOperationSamplingStrategies) o; + return Double.doubleToLongBits(defaultSamplingProbability) + == Double.doubleToLongBits(that.defaultSamplingProbability) + && Double.doubleToLongBits(defaultLowerBoundTracesPerSecond) + == Double.doubleToLongBits(that.defaultLowerBoundTracesPerSecond) + && Double.doubleToLongBits(defaultUpperBoundTracesPerSecond) + == Double.doubleToLongBits(that.defaultUpperBoundTracesPerSecond) + && strategies.equals(that.strategies); + } + + @Override + public int hashCode() { + int result = Double.hashCode(defaultSamplingProbability); + result = 31 * result + Double.hashCode(defaultLowerBoundTracesPerSecond); + result = 31 * result + Double.hashCode(defaultUpperBoundTracesPerSecond); + result = 31 * result + strategies.hashCode(); + return result; + } + static class Builder { private double defaultSamplingProbability; private double defaultLowerBoundTracesPerSecond; @@ -104,7 +157,7 @@ PerOperationSamplingStrategies build() { } } - static class OperationSamplingStrategy { + static final class OperationSamplingStrategy { final String operation; final ProbabilisticSamplingStrategy probabilisticSamplingStrategy; @@ -113,6 +166,21 @@ private OperationSamplingStrategy(Builder builder) { this.probabilisticSamplingStrategy = builder.probabilisticSamplingStrategy; } + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof OperationSamplingStrategy)) { + return false; + } + OperationSamplingStrategy that = (OperationSamplingStrategy) o; + return operation.equals(that.operation) + && probabilisticSamplingStrategy.equals(that.probabilisticSamplingStrategy); + } + + @Override + public int hashCode() { + return 31 * operation.hashCode() + probabilisticSamplingStrategy.hashCode(); + } + static class Builder { private String operation = ""; private ProbabilisticSamplingStrategy probabilisticSamplingStrategy = @@ -147,6 +215,27 @@ private SamplingStrategyResponse(Builder builder) { this.perOperationSamplingStrategies = builder.perOperationSamplingStrategies; } + @Override + public boolean equals(@Nullable Object o) { + if (!(o instanceof SamplingStrategyResponse)) { + return false; + } + SamplingStrategyResponse that = (SamplingStrategyResponse) o; + return strategyType == that.strategyType + && rateLimitingSamplingStrategy.equals(that.rateLimitingSamplingStrategy) + && probabilisticSamplingStrategy.equals(that.probabilisticSamplingStrategy) + && perOperationSamplingStrategies.equals(that.perOperationSamplingStrategies); + } + + @Override + public int hashCode() { + int result = strategyType.hashCode(); + result = 31 * result + rateLimitingSamplingStrategy.hashCode(); + result = 31 * result + probabilisticSamplingStrategy.hashCode(); + result = 31 * result + perOperationSamplingStrategies.hashCode(); + return result; + } + static class Builder { private SamplingStrategyType samplingStrategyType = SamplingStrategyType.UNRECOGNIZED; private RateLimitingSamplingStrategy rateLimitingSamplingStrategy = diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseUnMarshaler.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseUnMarshaler.java index 454b1f916cc..f662d130c7c 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseUnMarshaler.java +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseUnMarshaler.java @@ -7,27 +7,16 @@ import io.opentelemetry.exporter.internal.marshal.CodedInputStream; import java.io.IOException; -import javax.annotation.Nullable; -class SamplingStrategyResponseUnMarshaler extends UnMarshaler { +class SamplingStrategyResponseUnMarshaler { - @Nullable private SamplingStrategyResponse samplingStrategyResponse; + private SamplingStrategyResponseUnMarshaler() {} - @Nullable - public SamplingStrategyResponse get() { - return samplingStrategyResponse; - } - - @Override - public void read(byte[] payload) throws IOException { + static SamplingStrategyResponse read(byte[] payload) throws IOException { SamplingStrategyResponse.Builder responseBuilder = new SamplingStrategyResponse.Builder(); - try { - CodedInputStream codedInputStream = CodedInputStream.newInstance(payload); - parseResponse(responseBuilder, codedInputStream); - samplingStrategyResponse = responseBuilder.build(); - } catch (IOException ex) { - // use null message - } + CodedInputStream codedInputStream = CodedInputStream.newInstance(payload); + parseResponse(responseBuilder, codedInputStream); + return responseBuilder.build(); } private static void parseResponse( @@ -47,8 +36,9 @@ private static void parseResponse( responseBuilder.setProbabilisticSamplingStrategy(parseProbabilistic(input, length)); break; case 26: - input.readRawVarint32(); // skip length - responseBuilder.setRateLimitingSamplingStrategy(parseRateLimiting(input)); + int rateLimitingLength = input.readRawVarint32(); + responseBuilder.setRateLimitingSamplingStrategy( + parseRateLimiting(input, rateLimitingLength)); break; case 34: input.readRawVarint32(); // skip length @@ -106,9 +96,13 @@ private static SamplingStrategyResponse.ProbabilisticSamplingStrategy parseProba } private static SamplingStrategyResponse.RateLimitingSamplingStrategy parseRateLimiting( - CodedInputStream input) throws IOException { + CodedInputStream input, int length) throws IOException { SamplingStrategyResponse.RateLimitingSamplingStrategy.Builder builder = new SamplingStrategyResponse.RateLimitingSamplingStrategy.Builder(); + if (length == 0) { + // Default rate limiting strategy. + return builder.setMaxTracesPerSecond(0).build(); + } boolean done = false; while (!done) { int tag = input.readTag(); diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/UnMarshaler.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/UnMarshaler.java deleted file mode 100644 index 89b3c2496d4..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/UnMarshaler.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import java.io.IOException; - -/** - * UnMarshaler from protobuf wire format to SDK data type. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -abstract class UnMarshaler { - - abstract void read(byte[] payload) throws IOException; -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/internal/JaegerRemoteSamplerComponentProvider.java b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/internal/JaegerRemoteSamplerComponentProvider.java new file mode 100644 index 00000000000..c998cf4be6e --- /dev/null +++ b/sdk-extensions/jaeger-remote-sampler/src/main/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/internal/JaegerRemoteSamplerComponentProvider.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.trace.jaeger.sampler.internal; + +import io.opentelemetry.api.config.DeclarativeConfigException; +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSampler; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.JaegerRemoteSamplerBuilder; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.time.Duration; + +/** + * File configuration SPI implementation for {@link JaegerRemoteSampler}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class JaegerRemoteSamplerComponentProvider implements ComponentProvider { + @Override + public Class getType() { + return Sampler.class; + } + + @Override + public String getName() { + return "jaeger_remote/development"; + } + + @Override + public Sampler create(DeclarativeConfigProperties config) { + JaegerRemoteSamplerBuilder builder = JaegerRemoteSampler.builder(); + + String endpoint = config.getString("endpoint"); + if (endpoint == null) { + throw new DeclarativeConfigException("jaeger remote sampler endpoint is required"); + } + builder.setEndpoint(endpoint); + + DeclarativeConfigProperties initialSamplerModel = config.getStructured("initial_sampler"); + if (initialSamplerModel == null) { + throw new DeclarativeConfigException("jaeger remote sampler initial_sampler is required"); + } + builder.setInitialSampler(DeclarativeConfiguration.createSampler(initialSamplerModel)); + + Long pollingIntervalMs = config.getLong("interval"); + if (pollingIntervalMs != null) { + builder.setPollingInterval(Duration.ofMillis(pollingIntervalMs)); + } + + return builder.build(); + } +} diff --git a/sdk-extensions/jaeger-remote-sampler/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider b/sdk-extensions/jaeger-remote-sampler/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider new file mode 100644 index 00000000000..d4a81bc8438 --- /dev/null +++ b/sdk-extensions/jaeger-remote-sampler/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.declarativeconfig.ComponentProvider @@ -0,0 +1,2 @@ +io.opentelemetry.sdk.extension.trace.jaeger.sampler.internal.JaegerRemoteSamplerComponentProvider + diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java index b0e04b2f874..15ed44e3c76 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerIntegrationTest.java @@ -34,8 +34,8 @@ class JaegerRemoteSamplerIntegrationTest { private static final String SERVICE_NAME_DEFAULT_STRATEGY = "foobar"; @Container - public static GenericContainer jaegerContainer = - new GenericContainer<>("ghcr.io/open-telemetry/opentelemetry-java/jaeger:1.32") + public static final GenericContainer jaegerContainer = + new GenericContainer<>("jaegertracing/all-in-one:1.32") .withCommand("--sampling.strategies-file=/sampling.json") .withExposedPorts(COLLECTOR_PORT, QUERY_PORT, HEALTH_PORT) .waitingFor(Wait.forHttp("/").forPort(HEALTH_PORT)) @@ -91,11 +91,10 @@ void remoteSampling_defaultStrategy() { .build()) { await() .atMost(Duration.ofSeconds(10)) - .untilAsserted( - () -> - assertThat(remoteSampler.getDescription()) - .contains("TraceIdRatioBased") - .contains("0.8")); + .untilAsserted(() -> + assertThat(remoteSampler.getDescription()) + .contains("TraceIdRatioBased") + .contains("0.8")); } } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java index d4dc82e8885..edf14a7d9a6 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerProviderTest.java @@ -10,6 +10,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; import io.opentelemetry.sdk.autoconfigure.spi.traces.ConfigurableSamplerProvider; import io.opentelemetry.sdk.trace.samplers.Sampler; @@ -17,6 +18,7 @@ import java.util.ServiceLoader; import org.junit.jupiter.api.Test; +@SuppressLogger(JaegerRemoteSampler.class) public class JaegerRemoteSamplerProviderTest { @Test @@ -33,7 +35,7 @@ void serviceProvider() { .thenReturn("test_service"); HashMap samplerArgs = new HashMap<>(); samplerArgs.put("endpoint", "http://localhost:9999"); - samplerArgs.put("pollingInterval", "99"); + samplerArgs.put("pollingIntervalMs", "99"); double samplingRate = 0.33; samplerArgs.put("initialSamplingRate", String.valueOf(samplingRate)); when(mockConfig.getMap(JaegerRemoteSamplerProvider.SAMPLER_ARG_PROPERTY)) @@ -42,41 +44,40 @@ void serviceProvider() { Sampler sampler = Sampler.parentBased(Sampler.traceIdRatioBased(samplingRate)); assertThat(samplerProviders) .singleElement(type(JaegerRemoteSamplerProvider.class)) - .satisfies( - provider -> { - try (JaegerRemoteSampler s = - (JaegerRemoteSampler) provider.createSampler(mockConfig)) { - assertThat(s) - .extracting("sampler", type(Sampler.class)) - .asString() - .isEqualTo(sampler.toString()); - assertThat(s).extracting("serviceName").isEqualTo("test_service"); - assertThat(s) - .extracting("delegate") - .extracting("endpoint") - .isEqualTo( - "http://localhost:9999/jaeger.api_v2.SamplingManager/GetSamplingStrategy"); - } - }); + .satisfies(provider -> { + try (JaegerRemoteSampler s = (JaegerRemoteSampler) provider.createSampler(mockConfig)) { + assertThat(s) + .extracting("sampler", type(Sampler.class)) + .asString() + .isEqualTo(sampler.toString()); + assertThat(s).extracting("serviceName").isEqualTo("test_service"); + assertThat(s) + .extracting("grpcSender") + .extracting("url") + .satisfies(url -> + assertThat(url.toString()) + .isEqualTo( + "http://localhost:9999/jaeger.api_v2.SamplingManager/GetSamplingStrategy")); + } + }); } @Test void serviceNameInAttributeProperties() { ConfigProperties mockConfig = mock(ConfigProperties.class); HashMap attributeProperties = new HashMap<>(); - attributeProperties.put(JaegerRemoteSamplerProvider.SERVICE_NAME_PROPERTY, "test_service2"); + attributeProperties.put( + JaegerRemoteSamplerProvider.RESOURCE_ATTRIBUTE_SERVICE_NAME_PROPERTY, "test_service2"); when(mockConfig.getMap(JaegerRemoteSamplerProvider.ATTRIBUTE_PROPERTY)) .thenReturn(attributeProperties); ServiceLoader samplerProviders = ServiceLoader.load(ConfigurableSamplerProvider.class); assertThat(samplerProviders) .singleElement(type(JaegerRemoteSamplerProvider.class)) - .satisfies( - provider -> { - try (JaegerRemoteSampler s = - (JaegerRemoteSampler) provider.createSampler(mockConfig)) { - assertThat(s).extracting("serviceName").isEqualTo("test_service2"); - } - }); + .satisfies(provider -> { + try (JaegerRemoteSampler s = (JaegerRemoteSampler) provider.createSampler(mockConfig)) { + assertThat(s).extracting("serviceName").isEqualTo("test_service2"); + } + }); } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java index 4ea64d8e370..4a3075c1cf3 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerTest.java @@ -6,39 +6,61 @@ package io.opentelemetry.sdk.extension.trace.jaeger.sampler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; +import static org.junit.jupiter.api.Named.named; +import static org.junit.jupiter.params.provider.Arguments.arguments; +import com.linecorp.armeria.common.TlsKeyPair; import com.linecorp.armeria.common.grpc.protocol.ArmeriaStatusException; import com.linecorp.armeria.server.ServerBuilder; -import com.linecorp.armeria.server.ServiceRequestContext; -import com.linecorp.armeria.server.grpc.protocol.AbstractUnaryGrpcService; +import com.linecorp.armeria.server.grpc.GrpcService; import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; import com.linecorp.armeria.testing.junit5.server.ServerExtension; import io.github.netmikey.logunit.api.LogCapturer; +import io.grpc.stub.StreamObserver; +import io.netty.handler.ssl.ClientAuth; +import io.opentelemetry.exporter.internal.TlsUtil; +import io.opentelemetry.exporter.sender.okhttp.internal.OkHttpGrpcSender; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling; import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling.RateLimitingSamplingStrategy; +import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling.SamplingStrategyParameters; import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling.SamplingStrategyType; +import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.SamplingManagerGrpc; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.io.IOException; -import java.lang.reflect.Field; import java.nio.file.Files; import java.time.Duration; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CompletionStage; +import java.util.Collections; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Stream; import javax.annotation.Nullable; +import javax.net.ssl.KeyManager; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509KeyManager; +import javax.net.ssl.X509TrustManager; import org.awaitility.core.ThrowingRunnable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.junit.jupiter.params.support.ParameterDeclarations; import org.slf4j.event.Level; import org.slf4j.event.LoggingEvent; -@SuppressLogger(OkHttpGrpcService.class) +@SuppressLogger(JaegerRemoteSampler.class) class JaegerRemoteSamplerTest { private static final String SERVICE_NAME = "my-service"; @@ -50,54 +72,72 @@ class JaegerRemoteSamplerTest { private static final ConcurrentLinkedQueue responses = new ConcurrentLinkedQueue<>(); - private static void addGrpcError(int code, @Nullable String message) { - grpcErrors.add(new ArmeriaStatusException(code, message)); + private static final AtomicInteger requestCount = new AtomicInteger(); + + private static void addGrpcError(GrpcStatusCode code, @Nullable String message) { + grpcErrors.add(new ArmeriaStatusException(code.getValue(), message)); } @RegisterExtension - LogCapturer logs = LogCapturer.create().captureForType(OkHttpGrpcService.class, Level.TRACE); + LogCapturer logs = LogCapturer.create().captureForType(JaegerRemoteSampler.class, Level.TRACE); @Order(1) @RegisterExtension static final SelfSignedCertificateExtension certificate = new SelfSignedCertificateExtension(); + @RegisterExtension @Order(2) + static final SelfSignedCertificateExtension clientCertificate = + new SelfSignedCertificateExtension(); + + @Order(3) @RegisterExtension static final ServerExtension server = new ServerExtension() { @Override protected void configure(ServerBuilder sb) { sb.service( - JaegerRemoteSamplerBuilder.GRPC_ENDPOINT_PATH, - new AbstractUnaryGrpcService() { - @Override - protected CompletionStage handleMessage( - ServiceRequestContext ctx, byte[] message) { - - ArmeriaStatusException grpcError = grpcErrors.peek(); - if (grpcError != null) { - throw grpcError; - } - - Sampling.SamplingStrategyResponse response = responses.poll(); - // use default - if (response == null) { - response = - Sampling.SamplingStrategyResponse.newBuilder() - .setStrategyType(SamplingStrategyType.RATE_LIMITING) - .setRateLimitingSampling( - RateLimitingSamplingStrategy.newBuilder() - .setMaxTracesPerSecond(RATE) - .build()) - .build(); - } - - return CompletableFuture.completedFuture(response.toByteArray()); - } - }); + GrpcService.builder() + .addService( + new SamplingManagerGrpc.SamplingManagerImplBase() { + @Override + public void getSamplingStrategy( + SamplingStrategyParameters request, + StreamObserver< + io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2 + .Sampling.SamplingStrategyResponse> + responseObserver) { + requestCount.incrementAndGet(); + ArmeriaStatusException grpcError = grpcErrors.poll(); + if (grpcError != null) { + responseObserver.onError(grpcError); + return; + } + Sampling.SamplingStrategyResponse response = responses.poll(); + // use default + if (response == null) { + response = + Sampling.SamplingStrategyResponse.newBuilder() + .setStrategyType(SamplingStrategyType.RATE_LIMITING) + .setRateLimitingSampling( + RateLimitingSamplingStrategy.newBuilder() + .setMaxTracesPerSecond(RATE) + .build()) + .build(); + } + responseObserver.onNext(response); + responseObserver.onCompleted(); + } + }) + .autoCompression(true) + .build()); sb.http(0); sb.https(0); - sb.tls(certificate.certificateFile(), certificate.privateKeyFile()); + sb.tls(TlsKeyPair.of(certificate.privateKey(), certificate.certificate())); + sb.tlsCustomizer(ssl -> { + ssl.clientAuth(ClientAuth.OPTIONAL); + ssl.trustManager(clientCertificate.certificate()); + }); } }; @@ -105,6 +145,7 @@ protected CompletionStage handleMessage( public void before() { grpcErrors.clear(); responses.clear(); + requestCount.set(0); } @Test @@ -115,6 +156,7 @@ void connectionWorks() { .setPollingInterval(1, TimeUnit.SECONDS) .setServiceName(SERVICE_NAME) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -123,6 +165,22 @@ void connectionWorks() { } } + @Test + void shutdown() { + JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpUri().toString()) + .setPollingInterval(1, TimeUnit.SECONDS) + .setServiceName(SERVICE_NAME) + .build(); + + CompletableResultCode first = sampler.shutdown(); + CompletableResultCode second = sampler.shutdown(); + + assertThat(first.join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(second.isSuccess()).isTrue(); + } + @Test void tlsConnectionWorks() throws IOException { try (JaegerRemoteSampler sampler = @@ -132,6 +190,85 @@ void tlsConnectionWorks() throws IOException { .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) .setServiceName(SERVICE_NAME) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + + await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); + + // verify + assertThat(sampler.getDescription()).contains("RateLimitingSampler{999.00}"); + } + } + + @ParameterizedTest + @ArgumentsSource(ClientPrivateKeyProvider.class) + void clientTlsConnectionWorks(byte[] privateKey) throws IOException { + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpsUri().toString()) + .setPollingInterval(1, TimeUnit.SECONDS) + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) + .setClientTls( + privateKey, Files.readAllBytes(clientCertificate.certificateFile().toPath())) + .setServiceName(SERVICE_NAME) + .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + + await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); + + // verify + assertThat(sampler.getDescription()).contains("RateLimitingSampler{999.00}"); + } + } + + private static class ClientPrivateKeyProvider implements ArgumentsProvider { + @Override + @SuppressWarnings("PrimitiveArrayPassedToVarargsMethod") + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) throws Exception { + return Stream.of( + arguments(named("PEM", Files.readAllBytes(clientCertificate.privateKeyFile().toPath()))), + arguments(named("DER", clientCertificate.privateKey().getEncoded()))); + } + } + + @Test + void tlsViaSslContext() throws Exception { + X509TrustManager trustManager = TlsUtil.trustManager(certificate.certificate().getEncoded()); + + X509KeyManager keyManager = + TlsUtil.keyManager( + clientCertificate.privateKey().getEncoded(), + clientCertificate.certificate().getEncoded()); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(new KeyManager[] {keyManager}, new TrustManager[] {trustManager}, null); + + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpsUri().toString()) + .setPollingInterval(1, TimeUnit.SECONDS) + .setSslContext(sslContext, trustManager) + .setServiceName(SERVICE_NAME) + .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + + await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); + + // verify + assertThat(sampler.getDescription()).contains("RateLimitingSampler{999.00}"); + } + } + + @Test + void gzipResponse() { + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpUri().toString()) + .setPollingInterval(1, TimeUnit.SECONDS) + .setHeaders(() -> Collections.singletonMap("grpc-accept-encoding", "gzip")) + .setServiceName(SERVICE_NAME) + .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -148,8 +285,11 @@ void description() { .setPollingInterval(1, TimeUnit.SECONDS) .setServiceName(SERVICE_NAME) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}") + .contains("endpoint=" + server.httpUri(), "pollingIntervalMs=1000"); // wait until the sampling strategy is retrieved before exiting test method await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -164,7 +304,10 @@ void initialSampler() { .setServiceName(SERVICE_NAME) .setInitialSampler(Sampler.alwaysOn()) .build()) { - assertThat(sampler.getDescription()).startsWith("JaegerRemoteSampler{AlwaysOnSampler}"); + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + + assertThat(sampler.getDescription()) + .startsWith("JaegerRemoteSampler{sampler=AlwaysOnSampler"); } } @@ -176,6 +319,7 @@ void pollingInterval() { .setServiceName(SERVICE_NAME) .setPollingInterval(1, TimeUnit.MILLISECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); // wait until the sampling strategy is retrieved before exiting test method await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -190,12 +334,33 @@ void pollingInterval_duration() { .setServiceName(SERVICE_NAME) .setPollingInterval(Duration.ofMillis(1)) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); // wait until the sampling strategy is retrieved before exiting test method await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); } } + @Test + void emptyResponse() { + Sampling.SamplingStrategyResponse response = + Sampling.SamplingStrategyResponse.newBuilder().build(); + responses.add(response); + + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpUri().toString()) + .setServiceName(SERVICE_NAME) + // Make sure only polls once. + .setPollingInterval(500, TimeUnit.SECONDS) + .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + + // Empty response results in an unmarshaling exception which is handled by logging a warning + await().untilAsserted(() -> logs.assertContains("Failed to unmarshal strategy response")); + } + } + @Test void perOperationSampling() { Sampling.SamplingStrategyResponse response = @@ -234,22 +399,88 @@ void perOperationSampling() { // Make sure only polls once. .setPollingInterval(500, TimeUnit.SECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); + + await() + .untilAsserted(() -> { + assertThat(sampler.getDescription()) + .startsWith( + "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); + assertThat(sampler.getDescription()).contains("bar"); + }); + } + } + + @Test + void perOperationSampling_zeroRateLimiting() { + // maxTracesPerSecond=0 is omitted on the wire, so the rate limiting message has length 0. + Sampling.SamplingStrategyResponse response = + Sampling.SamplingStrategyResponse.newBuilder() + .setStrategyType(SamplingStrategyType.RATE_LIMITING) + .setRateLimitingSampling( + RateLimitingSamplingStrategy.newBuilder().setMaxTracesPerSecond(0).build()) + .setOperationSampling( + Sampling.PerOperationSamplingStrategies.newBuilder() + .setDefaultSamplingProbability(0.55) + .addPerOperationStrategies( + Sampling.OperationSamplingStrategy.newBuilder() + .setOperation("foo") + .setProbabilisticSampling( + Sampling.ProbabilisticSamplingStrategy.newBuilder() + .setSamplingRate(0.90) + .build()) + .build()) + .build()) + .build(); + responses.add(response); + + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpUri().toString()) + .setServiceName(SERVICE_NAME) + // Make sure only polls once. + .setPollingInterval(500, TimeUnit.SECONDS) + .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); await() - .untilAsserted( - () -> { - assertThat(sampler.getDescription()) - .startsWith( - "JaegerRemoteSampler{ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); - assertThat(sampler.getDescription()).contains("bar"); - }); + .untilAsserted(() -> + assertThat(sampler.getDescription()) + .startsWith( + "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}}}")); + } + } + + @Test + void unchangedStrategy_keepsSampler() { + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setEndpoint(server.httpUri().toString()) + .setServiceName(SERVICE_NAME) + .setPollingInterval(50, TimeUnit.MILLISECONDS) + .build()) { + await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); + Sampler initial = sampler.getSampler(); + + // Further polls return the same strategy, so the stateful sampler must be retained. + int polls = requestCount.get(); + await().untilAsserted(() -> assertThat(requestCount.get()).isGreaterThan(polls + 2)); + assertThat(sampler.getSampler()).isSameAs(initial); + + // A changed strategy still replaces the sampler. + responses.add( + Sampling.SamplingStrategyResponse.newBuilder() + .setStrategyType(SamplingStrategyType.RATE_LIMITING) + .setRateLimitingSampling( + RateLimitingSamplingStrategy.newBuilder().setMaxTracesPerSecond(5).build()) + .build()); + await().untilAsserted(() -> assertThat(sampler.getSampler()).isNotSameAs(initial)); } } @Test - @SuppressLogger(OkHttpGrpcService.class) void internal_error_server_response() { - addGrpcError(13, "internal error"); + addGrpcError(GrpcStatusCode.INTERNAL, "internal error"); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() @@ -257,24 +488,23 @@ void internal_error_server_response() { .setServiceName(SERVICE_NAME) .setPollingInterval(50, TimeUnit.MILLISECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = - logs.assertContains(" Server responded with gRPC status code 13"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - }); + .untilAsserted(() -> { + LoggingEvent log = + logs.assertContains(" Server responded with gRPC status code INTERNAL"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + }); } } @Test - @SuppressLogger(OkHttpGrpcService.class) void unavailable_error_server_response() { - addGrpcError(14, "γ‚―γƒžπŸ» resource exhausted"); + addGrpcError(GrpcStatusCode.UNAVAILABLE, "γ‚―γƒžπŸ» resource exhausted"); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() @@ -282,23 +512,22 @@ void unavailable_error_server_response() { .setServiceName(SERVICE_NAME) .setPollingInterval(50, TimeUnit.MILLISECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } @Test - @SuppressLogger(OkHttpGrpcService.class) void unimplemented_error_server_response() { - addGrpcError(12, null); + addGrpcError(GrpcStatusCode.UNIMPLEMENTED, null); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() @@ -306,27 +535,62 @@ void unimplemented_error_server_response() { .setServiceName(SERVICE_NAME) .setPollingInterval(50, TimeUnit.MILLISECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(OkHttpGrpcSender.class); assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } + @Test + void builder_ValidConfig() { + assertThatCode(() -> JaegerRemoteSampler.builder().setEndpoint("http://localhost:4317")) + .doesNotThrowAnyException(); + assertThatCode(() -> JaegerRemoteSampler.builder().setEndpoint("http://localhost")) + .doesNotThrowAnyException(); + assertThatCode(() -> JaegerRemoteSampler.builder().setEndpoint("https://localhost")) + .doesNotThrowAnyException(); + assertThatCode(() -> JaegerRemoteSampler.builder().setEndpoint("http://foo:bar@localhost")) + .doesNotThrowAnyException(); + + assertThatCode(() -> + JaegerRemoteSampler.builder() + .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath()))) + .doesNotThrowAnyException(); + + assertThatCode(() -> + JaegerRemoteSampler.builder() + .setClientTls( + Files.readAllBytes(clientCertificate.privateKeyFile().toPath()), + Files.readAllBytes(clientCertificate.certificateFile().toPath()))) + .doesNotThrowAnyException(); + } + @Test void invalidArguments() { assertThatThrownBy(() -> JaegerRemoteSampler.builder().setServiceName(null)) .isInstanceOf(NullPointerException.class) .hasMessage("serviceName"); + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setEndpoint(null)) .isInstanceOf(NullPointerException.class) .hasMessage("endpoint"); + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setEndpoint("😺://localhost")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid endpoint, must be a URL: 😺://localhost"); + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setEndpoint("localhost")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setEndpoint("gopher://localhost")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); + assertThatThrownBy( () -> JaegerRemoteSampler.builder().setPollingInterval(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) @@ -341,12 +605,17 @@ void invalidArguments() { assertThatThrownBy(() -> JaegerRemoteSampler.builder().setPollingInterval(null)) .isInstanceOf(NullPointerException.class) .hasMessage("interval"); - } - @Test - void usingOkHttp() { - assertThat(JaegerRemoteSampler.builder().getDelegate()) - .isInstanceOf(OkHttpGrpcServiceBuilder.class); + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setTrustedCertificates(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("trustedCertificatesPem"); + + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setClientTls(null, new byte[] {})) + .isInstanceOf(NullPointerException.class) + .hasMessage("privateKeyPem"); + assertThatThrownBy(() -> JaegerRemoteSampler.builder().setClientTls(new byte[] {}, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("certificatePem"); } static ThrowingRunnable samplerIsType( @@ -355,9 +624,7 @@ static ThrowingRunnable samplerIsType( assertThat(sampler.getSampler().getClass().getName()) .isEqualTo("io.opentelemetry.sdk.trace.samplers.ParentBasedSampler"); - Field field = sampler.getSampler().getClass().getDeclaredField("root"); - field.setAccessible(true); - assertThat(field.get(sampler.getSampler()).getClass()).isEqualTo(expected); + assertThat(sampler.getSampler()).extracting("root").isInstanceOf(expected); }; } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcServiceBuilderTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcServiceBuilderTest.java deleted file mode 100644 index eab10fd1a16..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/OkHttpGrpcServiceBuilderTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class OkHttpGrpcServiceBuilderTest { - - private static OkHttpGrpcServiceBuilder< - SamplingStrategyParametersMarshaler, SamplingStrategyResponseUnMarshaler> - exporterBuilder() { - return new OkHttpGrpcServiceBuilder<>("some", "some", 1, URI.create("htt://localhost:8080")); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void validConfig() { - assertThatCode(() -> exporterBuilder().setTimeout(0, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(0))) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(10, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(10))) - .doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost:4317")) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setEndpoint("https://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setEndpoint("http://foo:bar@localhost")) - .doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().setCompression("gzip")).doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setCompression("none")).doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().addHeader("foo", "bar").addHeader("baz", "qux")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - exporterBuilder().setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().addRetryPolicy(RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - @SuppressWarnings({"PreferJavaTimeOverload", "NullAway"}) - public void invalidConfig() { - assertThatThrownBy(() -> exporterBuilder().setTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> exporterBuilder().setTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> exporterBuilder().setTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> exporterBuilder().addRetryPolicy(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("retryPolicy"); - - assertThatThrownBy(() -> exporterBuilder().addHeader(null, "val")) - .isInstanceOf(NullPointerException.class) - .hasMessage("key"); - assertThatThrownBy(() -> exporterBuilder().addHeader("key", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("value"); - - assertThatThrownBy(() -> exporterBuilder().setTrustedCertificates(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("trustedCertificatesPem"); - - assertThatThrownBy(() -> exporterBuilder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy(() -> exporterBuilder().setEndpoint("😺://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must be a URL: 😺://localhost"); - assertThatThrownBy(() -> exporterBuilder().setEndpoint("localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); - assertThatThrownBy(() -> exporterBuilder().setEndpoint("gopher://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); - - assertThatThrownBy(() -> exporterBuilder().setCompression(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("compressionMethod"); - assertThatThrownBy(() -> exporterBuilder().setCompression("foo")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Unsupported compression method. Supported compression methods include: gzip, none."); - } -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSamplerTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSamplerTest.java index 873e4c5c0b4..a7300f9ccaa 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSamplerTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/RateLimitingSamplerTest.java @@ -17,6 +17,7 @@ import io.opentelemetry.sdk.trace.samplers.SamplingDecision; import io.opentelemetry.sdk.trace.samplers.SamplingResult; import java.util.Collections; +import java.util.Locale; import org.junit.jupiter.api.Test; class RateLimitingSamplerTest { @@ -62,8 +63,14 @@ void sampleOneTrace() { } @Test - void description() { + void descriptionShouldBeLocaleIndependent() { RateLimitingSampler sampler = new RateLimitingSampler(15); + + // PL locale uses ',' as decimal separator + Locale.setDefault(Locale.forLanguageTag("PL")); + assertThat(sampler.getDescription()).isEqualTo("RateLimitingSampler{15.00}"); + + Locale.setDefault(Locale.ENGLISH); assertThat(sampler.getDescription()).isEqualTo("RateLimitingSampler{15.00}"); } } diff --git a/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseTest.java b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseTest.java new file mode 100644 index 00000000000..f9fef1a475a --- /dev/null +++ b/sdk-extensions/jaeger-remote-sampler/src/test/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/SamplingStrategyResponseTest.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.extension.trace.jaeger.sampler; + +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.SamplingStrategyResponse.OperationSamplingStrategy; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.SamplingStrategyResponse.PerOperationSamplingStrategies; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.SamplingStrategyResponse.ProbabilisticSamplingStrategy; +import io.opentelemetry.sdk.extension.trace.jaeger.sampler.SamplingStrategyResponse.RateLimitingSamplingStrategy; +import nl.jqno.equalsverifier.EqualsVerifier; +import nl.jqno.equalsverifier.Warning; +import org.junit.jupiter.api.Test; + +class SamplingStrategyResponseTest { + + @Test + void equalsVerifier() { + // The builders always supply a value, so the fields are never null in practice. + EqualsVerifier.forClass(RateLimitingSamplingStrategy.class).verify(); + EqualsVerifier.forClass(ProbabilisticSamplingStrategy.class).verify(); + EqualsVerifier.forClass(OperationSamplingStrategy.class).suppress(Warning.NULL_FIELDS).verify(); + EqualsVerifier.forClass(PerOperationSamplingStrategies.class) + .suppress(Warning.NULL_FIELDS) + .verify(); + EqualsVerifier.forClass(SamplingStrategyResponse.class).suppress(Warning.NULL_FIELDS).verify(); + } +} diff --git a/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcServiceBuilderTest.java b/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcServiceBuilderTest.java deleted file mode 100644 index dd8d231e03c..00000000000 --- a/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/DefaultGrpcServiceBuilderTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.trace.jaeger.sampler; - -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.exporter.internal.retry.RetryPolicy; -import java.net.URI; -import java.nio.charset.StandardCharsets; -import java.time.Duration; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -class DefaultGrpcServiceBuilderTest { - - private static DefaultGrpcServiceBuilder< - SamplingStrategyParametersMarshaler, SamplingStrategyResponseUnMarshaler> - exporterBuilder() { - return new DefaultGrpcServiceBuilder<>( - "some", null, 10, URI.create("htt://localhost:8080"), "some"); - } - - @Test - @SuppressWarnings("PreferJavaTimeOverload") - void validConfig() { - assertThatCode(() -> exporterBuilder().setTimeout(0, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(0))) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(10, TimeUnit.MILLISECONDS)) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setTimeout(Duration.ofMillis(10))) - .doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost:4317")) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setEndpoint("http://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setEndpoint("https://localhost")) - .doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setEndpoint("http://foo:bar@localhost")) - .doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().setCompression("gzip")).doesNotThrowAnyException(); - assertThatCode(() -> exporterBuilder().setCompression("none")).doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().addHeader("foo", "bar").addHeader("baz", "qux")) - .doesNotThrowAnyException(); - - assertThatCode( - () -> - exporterBuilder().setTrustedCertificates("foobar".getBytes(StandardCharsets.UTF_8))) - .doesNotThrowAnyException(); - - assertThatCode(() -> exporterBuilder().addRetryPolicy(RetryPolicy.getDefault())) - .doesNotThrowAnyException(); - } - - @Test - @SuppressWarnings({"PreferJavaTimeOverload", "NullAway"}) - public void invalidConfig() { - assertThatThrownBy(() -> exporterBuilder().setTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> exporterBuilder().setTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> exporterBuilder().setTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - - assertThatThrownBy(() -> exporterBuilder().addRetryPolicy(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("retryPolicy"); - - assertThatThrownBy(() -> exporterBuilder().addHeader(null, "val")) - .isInstanceOf(NullPointerException.class) - .hasMessage("key"); - assertThatThrownBy(() -> exporterBuilder().addHeader("key", null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("value"); - - assertThatThrownBy(() -> exporterBuilder().setTrustedCertificates(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("trustedCertificatesPem"); - - assertThatThrownBy(() -> exporterBuilder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy(() -> exporterBuilder().setEndpoint("😺://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must be a URL: 😺://localhost"); - assertThatThrownBy(() -> exporterBuilder().setEndpoint("localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: localhost"); - assertThatThrownBy(() -> exporterBuilder().setEndpoint("gopher://localhost")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Invalid endpoint, must start with http:// or https://: gopher://localhost"); - - assertThatThrownBy(() -> exporterBuilder().setCompression(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("compressionMethod"); - assertThatThrownBy(() -> exporterBuilder().setCompression("foo")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage( - "Unsupported compression method. Supported compression methods include: gzip, none."); - - assertThatThrownBy(() -> exporterBuilder().setChannel(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("channel"); - } -} diff --git a/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java b/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java index d0b5f31ec5e..2371c41fb7a 100644 --- a/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java +++ b/sdk-extensions/jaeger-remote-sampler/src/testGrpcNetty/java/io/opentelemetry/sdk/extension/trace/jaeger/sampler/JaegerRemoteSamplerGrpcNettyTest.java @@ -6,7 +6,6 @@ package io.opentelemetry.sdk.extension.trace.jaeger.sampler; import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; import com.linecorp.armeria.common.grpc.protocol.ArmeriaStatusException; @@ -16,14 +15,16 @@ import com.linecorp.armeria.testing.junit5.server.SelfSignedCertificateExtension; import com.linecorp.armeria.testing.junit5.server.ServerExtension; import io.github.netmikey.logunit.api.LogCapturer; +import io.grpc.ManagedChannel; +import io.grpc.ManagedChannelBuilder; +import io.opentelemetry.exporter.sender.grpc.managedchannel.internal.UpstreamGrpcSender; +import io.opentelemetry.internal.testing.CleanupExtension; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.export.GrpcStatusCode; import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling; import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling.RateLimitingSamplingStrategy; import io.opentelemetry.sdk.extension.trace.jaeger.proto.api_v2.Sampling.SamplingStrategyType; import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.io.IOException; -import java.lang.reflect.Field; -import java.nio.file.Files; import java.time.Duration; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; @@ -38,7 +39,8 @@ import org.slf4j.event.Level; import org.slf4j.event.LoggingEvent; -@SuppressLogger(DefaultGrpcService.class) +@SuppressLogger(JaegerRemoteSampler.class) +@SuppressWarnings("deprecation") // Testing deprecated code class JaegerRemoteSamplerGrpcNettyTest { private static final String SERVICE_NAME = "my-service"; @@ -50,12 +52,14 @@ class JaegerRemoteSamplerGrpcNettyTest { private static final ConcurrentLinkedQueue responses = new ConcurrentLinkedQueue<>(); - private static void addGrpcError(int code, @Nullable String message) { - grpcErrors.add(new ArmeriaStatusException(code, message)); + private static void addGrpcError(GrpcStatusCode code, @Nullable String message) { + grpcErrors.add(new ArmeriaStatusException(code.getValue(), message)); } + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + @RegisterExtension - LogCapturer logs = LogCapturer.create().captureForType(DefaultGrpcService.class, Level.TRACE); + LogCapturer logs = LogCapturer.create().captureForType(JaegerRemoteSampler.class, Level.TRACE); @Order(1) @RegisterExtension @@ -68,7 +72,7 @@ private static void addGrpcError(int code, @Nullable String message) { @Override protected void configure(ServerBuilder sb) { sb.service( - JaegerRemoteSamplerBuilder.GRPC_ENDPOINT_PATH, + "/jaeger.api_v2.SamplingManager/GetSamplingStrategy", new AbstractUnaryGrpcService() { @Override protected CompletionStage handleMessage( @@ -96,8 +100,6 @@ protected CompletionStage handleMessage( } }); sb.http(0); - sb.https(0); - sb.tls(certificate.certificateFile(), certificate.privateKeyFile()); } }; @@ -107,31 +109,36 @@ public void before() { responses.clear(); } - @Test - void connectionWorks() { - try (JaegerRemoteSampler sampler = - JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) - .setPollingInterval(1, TimeUnit.SECONDS) - .setServiceName(SERVICE_NAME) - .build()) { - - await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); - - // verify - assertThat(sampler.getDescription()).contains("RateLimitingSampler{999.00}"); - } + private ManagedChannel managedChannel() { + ManagedChannel channel = + ManagedChannelBuilder.forTarget(server.httpUri().getAuthority()).usePlaintext().build(); + cleanup.addCloseable(() -> { + // Graceful shutdown ensures the server has processed all in-flight requests before + // the next test starts, preventing stale requests from consuming errors added to the + // queue by a subsequent test. + channel.shutdown(); + try { + if (!channel.awaitTermination(10, TimeUnit.SECONDS)) { + channel.shutdownNow(); + } + } catch (InterruptedException e) { + channel.shutdownNow(); + Thread.currentThread().interrupt(); + } + }); + return channel; } @Test - void tlsConnectionWorks() throws IOException { + void connectionWorks() { try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpsUri().toString()) + .setChannel(managedChannel()) + .setEndpoint(server.httpUri().toString()) .setPollingInterval(1, TimeUnit.SECONDS) - .setTrustedCertificates(Files.readAllBytes(certificate.certificateFile().toPath())) .setServiceName(SERVICE_NAME) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -144,12 +151,14 @@ void tlsConnectionWorks() throws IOException { void description() { try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setPollingInterval(1, TimeUnit.SECONDS) .setServiceName(SERVICE_NAME) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); + assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); // wait until the sampling strategy is retrieved before exiting test method await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -158,13 +167,18 @@ void description() { @Test void initialSampler() { + ManagedChannel channel = ManagedChannelBuilder.forTarget("example.com").build(); + cleanup.addCloseable(channel::shutdownNow); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint("http://example.com") + .setChannel(channel) .setServiceName(SERVICE_NAME) .setInitialSampler(Sampler.alwaysOn()) .build()) { - assertThat(sampler.getDescription()).startsWith("JaegerRemoteSampler{AlwaysOnSampler}"); + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); + + assertThat(sampler.getDescription()) + .startsWith("JaegerRemoteSampler{sampler=AlwaysOnSampler"); } } @@ -172,10 +186,11 @@ void initialSampler() { void pollingInterval() { try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setServiceName(SERVICE_NAME) .setPollingInterval(1, TimeUnit.MILLISECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); // wait until the sampling strategy is retrieved before exiting test method await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); @@ -186,16 +201,37 @@ void pollingInterval() { void pollingInterval_duration() { try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setServiceName(SERVICE_NAME) .setPollingInterval(Duration.ofMillis(1)) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); // wait until the sampling strategy is retrieved before exiting test method await().untilAsserted(samplerIsType(sampler, RateLimitingSampler.class)); } } + @Test + void emptyResponse() { + Sampling.SamplingStrategyResponse response = + Sampling.SamplingStrategyResponse.newBuilder().build(); + responses.add(response); + + try (JaegerRemoteSampler sampler = + JaegerRemoteSampler.builder() + .setChannel(managedChannel()) + .setServiceName(SERVICE_NAME) + // Make sure only polls once. + .setPollingInterval(500, TimeUnit.SECONDS) + .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); + + // Empty response results in an unmarshaling exception which is handled by logging a warning + await().untilAsserted(() -> logs.assertContains("Failed to unmarshal strategy response")); + } + } + @Test void perOperationSampling() { Sampling.SamplingStrategyResponse response = @@ -229,132 +265,102 @@ void perOperationSampling() { try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setServiceName(SERVICE_NAME) // Make sure only polls once. .setPollingInterval(500, TimeUnit.SECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); await() - .untilAsserted( - () -> { - assertThat(sampler.getDescription()) - .startsWith( - "JaegerRemoteSampler{ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); - assertThat(sampler.getDescription()).contains("bar"); - }); + .untilAsserted(() -> { + assertThat(sampler.getDescription()) + .startsWith( + "JaegerRemoteSampler{sampler=ParentBased{root:PerOperationSampler{default=TraceIdRatioBased{0.550000}, perOperation={foo=TraceIdRatioBased{0.900000}, bar=TraceIdRatioBased{0.700000}}}"); + assertThat(sampler.getDescription()).contains("bar"); + }); } } @Test void internal_error_server_response() { - addGrpcError(13, "internal error"); + addGrpcError(GrpcStatusCode.INTERNAL, "internal error"); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setServiceName(SERVICE_NAME) - .setPollingInterval(50, TimeUnit.MILLISECONDS) + // Make sure only polls once. + .setPollingInterval(500, TimeUnit.SECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = - logs.assertContains(" Server responded with gRPC status code 13"); - assertThat(log.getLevel()).isEqualTo(Level.WARN); - }); + .untilAsserted(() -> { + LoggingEvent log = + logs.assertContains(" Server responded with gRPC status code INTERNAL"); + assertThat(log.getLevel()).isEqualTo(Level.WARN); + }); } } @Test void unavailable_error_server_response() { - addGrpcError(14, "γ‚―γƒžπŸ» resource exhausted"); + addGrpcError(GrpcStatusCode.UNAVAILABLE, "γ‚―γƒžπŸ» resource exhausted"); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setServiceName(SERVICE_NAME) - .setPollingInterval(50, TimeUnit.MILLISECONDS) + // Make sure only polls once. + .setPollingInterval(500, TimeUnit.SECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server is UNAVAILABLE"); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } @Test void unimplemented_error_server_response() { - addGrpcError(12, null); + addGrpcError(GrpcStatusCode.UNIMPLEMENTED, null); try (JaegerRemoteSampler sampler = JaegerRemoteSampler.builder() - .setEndpoint(server.httpUri().toString()) + .setChannel(managedChannel()) .setServiceName(SERVICE_NAME) - .setPollingInterval(50, TimeUnit.MILLISECONDS) + // Make sure only polls once. + .setPollingInterval(500, TimeUnit.SECONDS) .build()) { + assertThat(sampler).extracting("grpcSender").isInstanceOf(UpstreamGrpcSender.class); assertThat(sampler.getDescription()) - .startsWith("JaegerRemoteSampler{ParentBased{root:TraceIdRatioBased{0.001000}"); + .startsWith("JaegerRemoteSampler{sampler=ParentBased{root:TraceIdRatioBased{0.001000}"); await() - .untilAsserted( - () -> { - LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); - assertThat(log.getLevel()).isEqualTo(Level.ERROR); - }); + .untilAsserted(() -> { + LoggingEvent log = logs.assertContains("Server responded with UNIMPLEMENTED."); + assertThat(log.getLevel()).isEqualTo(Level.ERROR); + }); } } - @Test - void invalidArguments() { - assertThatThrownBy(() -> JaegerRemoteSampler.builder().setServiceName(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("serviceName"); - assertThatThrownBy(() -> JaegerRemoteSampler.builder().setEndpoint(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("endpoint"); - assertThatThrownBy( - () -> JaegerRemoteSampler.builder().setPollingInterval(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("polling interval must be positive"); - assertThatThrownBy(() -> JaegerRemoteSampler.builder().setPollingInterval(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy( - () -> JaegerRemoteSampler.builder().setPollingInterval(Duration.ofMillis(-1))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("polling interval must be positive"); - assertThatThrownBy(() -> JaegerRemoteSampler.builder().setPollingInterval(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("interval"); - } - - @Test - void usingGrpc() { - assertThat(JaegerRemoteSampler.builder().getDelegate()) - .isInstanceOf(DefaultGrpcServiceBuilder.class); - } - static ThrowingRunnable samplerIsType( JaegerRemoteSampler sampler, Class expected) { return () -> { assertThat(sampler.getSampler().getClass().getName()) .isEqualTo("io.opentelemetry.sdk.trace.samplers.ParentBasedSampler"); - - Field field = sampler.getSampler().getClass().getDeclaredField("root"); - field.setAccessible(true); - assertThat(field.get(sampler.getSampler()).getClass()).isEqualTo(expected); + assertThat(sampler.getSampler()).extracting("root").isInstanceOf(expected); }; } } diff --git a/sdk-extensions/jfr-events/README.md b/sdk-extensions/jfr-events/README.md deleted file mode 100644 index c039bc6c1c1..00000000000 --- a/sdk-extensions/jfr-events/README.md +++ /dev/null @@ -1,23 +0,0 @@ -# OpenTelemetry SDK Extension Java Flight Recorder (JFR) Events - -[![Javadocs][javadoc-image]][javadoc-url] - -Create JFR events that can be recorded and viewed in Java Mission Control (JMC). -* Creates Open Telemetry Tracing/Span events for spans - * The thread and stracktrace will be of the thead ending the span which might be different than the thread creating the span. - * Has the fields - * Operation Name - * Trace ID - * Parent Span ID - * Span ID -* Creates Open Telemetry Tracing/Scope events for scopes - * Thread will match the thread the scope was active in and the stacktrace will be when scope was closed - * Multiple scopes might be collected for a single span - * Has the fields - * Trace ID - * Span ID -* Supports the Open Source version of JFR in Java 11. - * Might support back port to OpenJDK 8, but not tested and classes are built with JDK 11 bytecode. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-jfr-events.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-jfr-events diff --git a/sdk-extensions/jfr-events/build.gradle.kts b/sdk-extensions/jfr-events/build.gradle.kts deleted file mode 100644 index c45dc715b03..00000000000 --- a/sdk-extensions/jfr-events/build.gradle.kts +++ /dev/null @@ -1,30 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") -} - -description = "OpenTelemetry SDK Extension JFR" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.jfr") - -dependencies { - implementation(project(":api:all")) - implementation(project(":sdk:all")) -} - -tasks { - withType(JavaCompile::class) { - options.release.set(11) - } - - test { - val testJavaVersion: String? by project - if (testJavaVersion == "8") { - enabled = false - } - - // Disabled due to https://bugs.openjdk.java.net/browse/JDK-8245283 - configure { - enabled = false - } - } -} diff --git a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/JfrContextStorageWrapper.java b/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/JfrContextStorageWrapper.java deleted file mode 100644 index b9d587dda01..00000000000 --- a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/JfrContextStorageWrapper.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.jfr; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.ContextStorage; -import io.opentelemetry.context.Scope; -import javax.annotation.Nullable; - -public final class JfrContextStorageWrapper implements ContextStorage { - - private final ContextStorage wrapped; - - public JfrContextStorageWrapper(ContextStorage wrapped) { - this.wrapped = wrapped; - } - - @Override - public Scope attach(Context toAttach) { - Scope scope = wrapped.attach(toAttach); - ScopeEvent event = new ScopeEvent(Span.fromContext(toAttach).getSpanContext()); - event.begin(); - return () -> { - if (event.shouldCommit()) { - event.commit(); - } - scope.close(); - }; - } - - @Override - @Nullable - public Context current() { - return wrapped.current(); - } -} diff --git a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/JfrSpanProcessor.java b/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/JfrSpanProcessor.java deleted file mode 100644 index e3e9e914c36..00000000000 --- a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/JfrSpanProcessor.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.jfr; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.internal.shaded.WeakConcurrentMap; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.ReadWriteSpan; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.SpanProcessor; - -/** - * Span processor to create new JFR events for the Span as they are started, and commit on end. - * - *

      NOTE: The JfrSpanProcessor measures the timing of spans, avoid if possible to wrap it with any - * other SpanProcessor which may affect timings. When possible, register it first before any other - * processors to allow the most accurate measurements. - */ -public final class JfrSpanProcessor implements SpanProcessor { - - private final WeakConcurrentMap spanEvents = - new WeakConcurrentMap.WithInlinedExpunction<>(); - - private volatile boolean closed; - - @Override - public void onStart(Context parentContext, ReadWriteSpan span) { - if (closed) { - return; - } - if (span.getSpanContext().isValid()) { - SpanEvent event = new SpanEvent(span.toSpanData()); - event.begin(); - spanEvents.put(span.getSpanContext(), event); - } - } - - @Override - public boolean isStartRequired() { - return true; - } - - @Override - public void onEnd(ReadableSpan rs) { - SpanEvent event = spanEvents.remove(rs.getSpanContext()); - if (!closed && event != null && event.shouldCommit()) { - event.commit(); - } - } - - @Override - public boolean isEndRequired() { - return true; - } - - @Override - public CompletableResultCode shutdown() { - closed = true; - return CompletableResultCode.ofSuccess(); - } -} diff --git a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/ScopeEvent.java b/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/ScopeEvent.java deleted file mode 100644 index cf40bb4e103..00000000000 --- a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/ScopeEvent.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.jfr; - -import io.opentelemetry.api.trace.SpanContext; -import jdk.jfr.Category; -import jdk.jfr.Description; -import jdk.jfr.Event; -import jdk.jfr.Label; -import jdk.jfr.Name; - -@Name("io.opentelemetry.context.Scope") -@Label("Scope") -@Category("Open Telemetry Tracing") -@Description( - "Open Telemetry trace event corresponding to the span currently " - + "in scope/active on this thread.") -class ScopeEvent extends Event { - - private final String traceId; - private final String spanId; - - ScopeEvent(SpanContext spanContext) { - this.traceId = spanContext.getTraceId(); - this.spanId = spanContext.getSpanId(); - } - - @Label("Trace Id") - public String getTraceId() { - return traceId; - } - - @Label("Span Id") - public String getSpanId() { - return spanId; - } -} diff --git a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/SpanEvent.java b/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/SpanEvent.java deleted file mode 100644 index 1e239b92937..00000000000 --- a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/SpanEvent.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.jfr; - -import io.opentelemetry.sdk.trace.data.SpanData; -import jdk.jfr.Category; -import jdk.jfr.Description; -import jdk.jfr.Event; -import jdk.jfr.Label; -import jdk.jfr.Name; - -@Label("Span") -@Name("io.opentelemetry.trace.Span") -@Category("Open Telemetry Tracing") -@Description("Open Telemetry trace event corresponding to a span.") -class SpanEvent extends Event { - - private final String operationName; - private final String traceId; - private final String spanId; - private final String parentId; - - SpanEvent(SpanData spanData) { - this.operationName = spanData.getName(); - this.traceId = spanData.getTraceId(); - this.spanId = spanData.getSpanId(); - this.parentId = spanData.getParentSpanId(); - } - - @Label("Operation Name") - public String getOperationName() { - return operationName; - } - - @Label("Trace Id") - public String getTraceId() { - return traceId; - } - - @Label("Span Id") - public String getSpanId() { - return spanId; - } - - @Label("Parent Id") - public String getParentId() { - return parentId; - } -} diff --git a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/package-info.java b/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/package-info.java deleted file mode 100644 index ac7889ff0e5..00000000000 --- a/sdk-extensions/jfr-events/src/main/java/io/opentelemetry/sdk/extension/jfr/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * Capture Spans and Scopes as events in JFR recordings. - * - * @see io.opentelemetry.sdk.extension.jfr.JfrSpanProcessor - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.extension.jfr; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/jfr-events/src/test/java/io/opentelemetry/sdk/extension/jfr/JfrSpanProcessorTest.java b/sdk-extensions/jfr-events/src/test/java/io/opentelemetry/sdk/extension/jfr/JfrSpanProcessorTest.java deleted file mode 100644 index 530d2977259..00000000000 --- a/sdk-extensions/jfr-events/src/test/java/io/opentelemetry/sdk/extension/jfr/JfrSpanProcessorTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.jfr; - -import static org.junit.jupiter.api.Assertions.assertEquals; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.context.ContextStorage; -import io.opentelemetry.context.Scope; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import jdk.jfr.Recording; -import jdk.jfr.consumer.RecordedEvent; -import jdk.jfr.consumer.RecordingFile; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class JfrSpanProcessorTest { - - private static final String OPERATION_NAME = "Test Span"; - - private SdkTracerProvider sdkTracerProvider; - private Tracer tracer; - - @BeforeEach - void setUp() { - sdkTracerProvider = - SdkTracerProvider.builder().addSpanProcessor(new JfrSpanProcessor()).build(); - tracer = sdkTracerProvider.get("JfrSpanProcessorTest"); - } - - @AfterEach - void tearDown() { - sdkTracerProvider.shutdown(); - } - - static { - ContextStorage.addWrapper(JfrContextStorageWrapper::new); - } - - /** - * Test basic single span. - * - * @throws java.io.IOException on io error - */ - @Test - public void basicSpan() throws IOException { - Path output = Files.createTempFile("test-basic-span", ".jfr"); - - try { - Recording recording = new Recording(); - recording.start(); - Span span; - - try (recording) { - - span = tracer.spanBuilder(OPERATION_NAME).setNoParent().startSpan(); - span.end(); - - recording.dump(output); - } - - List events = RecordingFile.readAllEvents(output); - assertEquals(1, events.size()); - events.stream() - .forEach( - e -> { - assertEquals(span.getSpanContext().getTraceId(), e.getValue("traceId")); - assertEquals(span.getSpanContext().getSpanId(), e.getValue("spanId")); - assertEquals(OPERATION_NAME, e.getValue("operationName")); - }); - - } finally { - Files.delete(output); - } - } - - /** - * Test basic single span with a scope. - * - * @throws java.io.IOException on io error - * @throws java.lang.InterruptedException interrupted sleep - */ - @Test - public void basicSpanWithScope() throws IOException, InterruptedException { - Path output = Files.createTempFile("test-basic-span-with-scope", ".jfr"); - - try { - Recording recording = new Recording(); - recording.start(); - Span span; - - try (recording) { - span = tracer.spanBuilder(OPERATION_NAME).setNoParent().startSpan(); - try (Scope s = span.makeCurrent()) { - Thread.sleep(10); - } - span.end(); - - recording.dump(output); - } - - List events = RecordingFile.readAllEvents(output); - assertEquals(2, events.size()); - events.stream() - .forEach( - e -> { - assertEquals(span.getSpanContext().getTraceId(), e.getValue("traceId")); - assertEquals(span.getSpanContext().getSpanId(), e.getValue("spanId")); - if ("Span".equals(e.getEventType().getLabel())) { - assertEquals(OPERATION_NAME, e.getValue("operationName")); - } - }); - - } finally { - Files.delete(output); - } - } -} diff --git a/sdk-extensions/metric-incubator/README.md b/sdk-extensions/metric-incubator/README.md deleted file mode 100644 index 36d750ae794..00000000000 --- a/sdk-extensions/metric-incubator/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# OpenTelemetry Metric Incubator - -[![Javadocs][javadoc-image]][javadoc-url] - -This artifact contains experimental code related to metrics. - -## View File Configuration - -Adds support for file based YAML configuration of Metric SDK Views. - -For example, suppose `/Users/user123/view.yaml` has the following content: - -```yaml -- selector: - instrument_name: my-instrument - instrument_type: COUNTER - meter_name: my-meter - meter_version: 1.0.0 - meter_schema_url: http://example.com - view: - name: new-instrument-name - description: new-description - aggregation: histogram - attribute_keys: - - foo - - bar -``` - -The equivalent view configuration would be: - -``` -SdkMeterProvider.builder() - .registerView( - InstrumentSelector.builder() - .setInstrumentName("my-instrument") - .setInstrumentType(InstrumentType.COUNTER) - .setMeterSelector( - MeterSelector.builder() - .setName("my-meter") - .setVersion("1.0.0") - .setSchemaUrl("http://example.com") - .build()) - .build(), - View.builder() - .setName("new-instrument") - .setDescription("new-description") - .setAggregation(Aggregation.histogram()) - .filterAttributes(key -> new HashSet<>(Arrays.asList("foo", "bar")).contains(key)) - .build()); -``` - -If using [autoconfigure](../autoconfigure) with this artifact on your classpath, it will automatically load a list of view config files specified via environment variable or system property: - -| System property | Environment variable | Purpose | -|---------------------------------------|---------------------------------------|------------------------------------------------------| -| otel.experimental.metrics.view-config | OTEL_EXPERIMENTAL_METRICS_VIEW_CONFIG | List of files containing view configuration YAML [1] | - -**[1]** In addition to absolute paths, resources on the classpath packaged with a jar can be loaded. -For example, `otel.experimental.metrics.view-config=classpath:/my-view.yaml` loads the -resource `/my-view.yaml`. - -If not using autoconfigure, a file can be used to configure views as follows: - -``` -SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); -try (FileInputStream fileInputStream = new FileInputStream("/Users/user123/view.yaml")) { - ViewConfig.registerViews(builder, fileInputStream); -} -``` - -Notes on usage: - -- Many view configurations can live in one file. The YAML is parsed as an array of view - configurations. -- At least one selection field is required, but including all is not necessary. Any omitted fields - will result in the default from `InstrumentSelector` being used. -- At least one view field is required, but including all is not required. Any omitted fields will - result in the default from `View` being used. -- Advanced selection criteria, like regular expressions, is not yet supported. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-metric-incubator - -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-metric-incubator diff --git a/sdk-extensions/metric-incubator/build.gradle.kts b/sdk-extensions/metric-incubator/build.gradle.kts deleted file mode 100644 index 2c9ef7fe96c..00000000000 --- a/sdk-extensions/metric-incubator/build.gradle.kts +++ /dev/null @@ -1,21 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") -} - -description = "OpenTelemetry SDK Metric Incubator" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.metric.incubator") - -dependencies { - implementation(project(":sdk:metrics")) - implementation(project(":sdk-extensions:autoconfigure-spi")) - - implementation("org.yaml:snakeyaml") - - annotationProcessor("com.google.auto.value:auto-value") - - testImplementation(project(":sdk:testing")) - testImplementation(project(":sdk-extensions:autoconfigure")) - - testImplementation("com.google.guava:guava") -} diff --git a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/SelectorSpecification.java b/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/SelectorSpecification.java deleted file mode 100644 index cd334444ae9..00000000000 --- a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/SelectorSpecification.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.InstrumentType; -import javax.annotation.Nullable; - -@AutoValue -abstract class SelectorSpecification { - - static AutoValue_SelectorSpecification.Builder builder() { - return new AutoValue_SelectorSpecification.Builder(); - } - - @Nullable - abstract String getInstrumentName(); - - @Nullable - abstract InstrumentType getInstrumentType(); - - @Nullable - abstract String getMeterName(); - - @Nullable - abstract String getMeterVersion(); - - @Nullable - abstract String getMeterSchemaUrl(); - - @AutoValue.Builder - interface Builder { - Builder instrumentName(@Nullable String instrumentName); - - Builder instrumentType(@Nullable InstrumentType instrumentType); - - Builder meterName(@Nullable String meterName); - - Builder meterVersion(@Nullable String meterVersion); - - Builder meterSchemaUrl(@Nullable String meterSchemaUrl); - - SelectorSpecification build(); - } -} diff --git a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfig.java b/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfig.java deleted file mode 100644 index a42fcf8cbad..00000000000 --- a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfig.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import static java.util.Objects.requireNonNull; -import static java.util.stream.Collectors.toList; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.InstrumentSelector; -import io.opentelemetry.sdk.metrics.InstrumentSelectorBuilder; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; -import io.opentelemetry.sdk.metrics.View; -import io.opentelemetry.sdk.metrics.ViewBuilder; -import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import javax.annotation.Nullable; -import org.yaml.snakeyaml.Yaml; - -/** - * Enables file based YAML configuration of Metric SDK {@link View}s. - * - *

      For example, a YAML file with the following content: - * - *

      - *   - selector:
      - *       instrument_name: my-instrument
      - *       instrument_type: COUNTER
      - *       meter_name: my-meter
      - *       meter_version: 1.0.0
      - *       meter_schema_url: http://example.com
      - *     view:
      - *       name: new-instrument-name
      - *       description: new-description
      - *       aggregation: histogram
      - *       attribute_keys:
      - *         - foo
      - *         - bar
      - * 
      - * - *

      Is equivalent to the following configuration: - * - *

      {@code
      - * SdkMeterProvider.builder()
      - *     .registerView(
      - *         InstrumentSelector.builder()
      - *             .setInstrumentName("my-instrument")
      - *             .setInstrumentType(InstrumentType.COUNTER)
      - *             .setMeterSelector(
      - *                 MeterSelector.builder()
      - *                     .setName("my-meter")
      - *                     .setVersion("1.0.0")
      - *                     .setSchemaUrl("http://example.com")
      - *                     .build())
      - *             .build(),
      - *         View.builder()
      - *             .setName("new-instrument")
      - *             .setDescription("new-description")
      - *             .setAggregation(Aggregation.histogram())
      - *             .filterAttributes(key -> new HashSet<>(Arrays.asList("foo", "bar")).contains(key))
      - *             .build());
      - * }
      - */ -public final class ViewConfig { - - private ViewConfig() {} - - /** - * Load the view configuration YAML from the {@code inputStream} and apply it to the {@link - * SdkMeterProviderBuilder}. - * - * @throws ConfigurationException if unable to interpret {@code inputStream} contents - */ - public static void registerViews( - SdkMeterProviderBuilder meterProviderBuilder, InputStream inputStream) { - List viewConfigSpecs = loadViewConfig(inputStream); - - for (ViewConfigSpecification viewConfigSpec : viewConfigSpecs) { - meterProviderBuilder.registerView( - toInstrumentSelector(viewConfigSpec.getSelectorSpecification()), - toView(viewConfigSpec.getViewSpecification())); - } - } - - // Visible for testing - @SuppressWarnings("unchecked") - static List loadViewConfig(InputStream inputStream) { - Yaml yaml = new Yaml(); - try { - List result = new ArrayList<>(); - List> viewConfigs = yaml.load(inputStream); - for (Map viewConfigSpecMap : viewConfigs) { - Map selectorSpecMap = - requireNonNull( - getAsType(viewConfigSpecMap, "selector", Map.class), "selector is required"); - Map viewSpecMap = - requireNonNull(getAsType(viewConfigSpecMap, "view", Map.class), "view is required"); - - InstrumentType instrumentType = - Optional.ofNullable(getAsType(selectorSpecMap, "instrument_type", String.class)) - .map(InstrumentType::valueOf) - .orElse(null); - List attributeKeys = - Optional.ofNullable( - ((List) getAsType(viewSpecMap, "attribute_keys", List.class))) - .map(objects -> objects.stream().map(String::valueOf).collect(toList())) - .orElse(null); - - result.add( - ViewConfigSpecification.builder() - .selectorSpecification( - SelectorSpecification.builder() - .instrumentName(getAsType(selectorSpecMap, "instrument_name", String.class)) - .instrumentType(instrumentType) - .meterName(getAsType(selectorSpecMap, "meter_name", String.class)) - .meterVersion(getAsType(selectorSpecMap, "meter_version", String.class)) - .meterSchemaUrl( - getAsType(selectorSpecMap, "meter_schema_url", String.class)) - .build()) - .viewSpecification( - ViewSpecification.builder() - .name(getAsType(viewSpecMap, "name", String.class)) - .description(getAsType(viewSpecMap, "description", String.class)) - .aggregation(getAsType(viewSpecMap, "aggregation", String.class)) - .attributeKeys(attributeKeys) - .build()) - .build()); - } - return result; - } catch (RuntimeException e) { - throw new ConfigurationException("Failed to parse view config", e); - } - } - - @Nullable - @SuppressWarnings("unchecked") - private static T getAsType(Map map, String key, Class type) { - Object value = map.get(key); - if (value != null && !type.isInstance(value)) { - throw new IllegalStateException( - "Expected " - + key - + " to be type " - + type.getName() - + " but was " - + value.getClass().getName()); - } - return (T) value; - } - - // Visible for testing - static View toView(ViewSpecification viewSpec) { - ViewBuilder builder = View.builder(); - String name = viewSpec.getName(); - if (name != null) { - builder.setName(name); - } - String description = viewSpec.getDescription(); - if (description != null) { - builder.setDescription(description); - } - String aggregation = viewSpec.getAggregation(); - if (aggregation != null) { - builder.setAggregation(toAggregation(aggregation)); - } - List attributeKeys = viewSpec.getAttributeKeys(); - if (attributeKeys != null) { - Set keySet = new HashSet<>(attributeKeys); - builder.setAttributeFilter(keySet::contains); - } - return builder.build(); - } - - // Visible for testing - static Aggregation toAggregation(String aggregation) { - try { - return AggregationUtil.forName(aggregation); - } catch (IllegalArgumentException e) { - throw new ConfigurationException("Error creating aggregation", e); - } - } - - // Visible for testing - static InstrumentSelector toInstrumentSelector(SelectorSpecification selectorSpec) { - InstrumentSelectorBuilder builder = InstrumentSelector.builder(); - String instrumentName = selectorSpec.getInstrumentName(); - if (instrumentName != null) { - builder.setName(instrumentName); - } - InstrumentType instrumentType = selectorSpec.getInstrumentType(); - if (instrumentType != null) { - builder.setType(instrumentType); - } - - String meterName = selectorSpec.getMeterName(); - if (meterName != null) { - builder.setMeterName(meterName); - } - String meterVersion = selectorSpec.getMeterVersion(); - if (meterVersion != null) { - builder.setMeterVersion(meterVersion); - } - String meterSchemaUrl = selectorSpec.getMeterSchemaUrl(); - if (meterSchemaUrl != null) { - builder.setMeterSchemaUrl(meterSchemaUrl); - } - - return builder.build(); - } -} diff --git a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfigCustomizer.java b/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfigCustomizer.java deleted file mode 100644 index 7d8303a4f29..00000000000 --- a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfigCustomizer.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; -import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -/** SPI implementation for loading view configuration YAML. */ -public final class ViewConfigCustomizer implements AutoConfigurationCustomizerProvider { - - @Override - public void customize(AutoConfigurationCustomizer autoConfiguration) { - autoConfiguration.addMeterProviderCustomizer(ViewConfigCustomizer::customizeMeterProvider); - } - - // Visible for testing - static SdkMeterProviderBuilder customizeMeterProvider( - SdkMeterProviderBuilder meterProviderBuilder, ConfigProperties configProperties) { - List configFileLocations = - configProperties.getList("otel.experimental.metrics.view.config"); - for (String configFileLocation : configFileLocations) { - if (configFileLocation.startsWith("classpath:")) { - String classpathLocation = configFileLocation.substring("classpath:".length()); - try (InputStream inputStream = - ViewConfigCustomizer.class.getResourceAsStream(classpathLocation)) { - if (inputStream == null) { - throw new ConfigurationException( - "Resource " - + classpathLocation - + " not found on classpath of classloader " - + ViewConfigCustomizer.class.getClassLoader().getClass().getName()); - } - ViewConfig.registerViews(meterProviderBuilder, inputStream); - } catch (IOException e) { - throw new ConfigurationException( - "An error occurred reading view config resource on classpath: " + classpathLocation, - e); - } - } else { - try (FileInputStream fileInputStream = new FileInputStream(configFileLocation)) { - ViewConfig.registerViews(meterProviderBuilder, fileInputStream); - } catch (FileNotFoundException e) { - throw new ConfigurationException("View config file not found: " + configFileLocation, e); - } catch (IOException e) { - throw new ConfigurationException( - "An error occurred reading view config file: " + configFileLocation, e); - } - } - } - return meterProviderBuilder; - } -} diff --git a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfigSpecification.java b/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfigSpecification.java deleted file mode 100644 index aad1e67ce3b..00000000000 --- a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewConfigSpecification.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import com.google.auto.value.AutoValue; - -@AutoValue -abstract class ViewConfigSpecification { - - static AutoValue_ViewConfigSpecification.Builder builder() { - return new AutoValue_ViewConfigSpecification.Builder(); - } - - abstract SelectorSpecification getSelectorSpecification(); - - abstract ViewSpecification getViewSpecification(); - - @AutoValue.Builder - interface Builder { - Builder selectorSpecification(SelectorSpecification selectorSpecification); - - Builder viewSpecification(ViewSpecification viewSpecification); - - ViewConfigSpecification build(); - } -} diff --git a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewSpecification.java b/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewSpecification.java deleted file mode 100644 index 6495a4a4885..00000000000 --- a/sdk-extensions/metric-incubator/src/main/java/io/opentelemetry/sdk/viewconfig/ViewSpecification.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import com.google.auto.value.AutoValue; -import java.util.List; -import javax.annotation.Nullable; - -@AutoValue -abstract class ViewSpecification { - - static AutoValue_ViewSpecification.Builder builder() { - return new AutoValue_ViewSpecification.Builder(); - } - - @Nullable - abstract String getName(); - - @Nullable - abstract String getDescription(); - - @Nullable - abstract String getAggregation(); - - @Nullable - abstract List getAttributeKeys(); - - @AutoValue.Builder - interface Builder { - Builder name(@Nullable String name); - - Builder description(@Nullable String description); - - Builder aggregation(@Nullable String aggregation); - - Builder attributeKeys(@Nullable List attributeKeys); - - ViewSpecification build(); - } -} diff --git a/sdk-extensions/metric-incubator/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider b/sdk-extensions/metric-incubator/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider deleted file mode 100644 index e33fbf08e10..00000000000 --- a/sdk-extensions/metric-incubator/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider +++ /dev/null @@ -1 +0,0 @@ -io.opentelemetry.sdk.viewconfig.ViewConfigCustomizer \ No newline at end of file diff --git a/sdk-extensions/metric-incubator/src/test/java/io/opentelemetry/sdk/viewconfig/ViewConfigCustomizerTest.java b/sdk-extensions/metric-incubator/src/test/java/io/opentelemetry/sdk/viewconfig/ViewConfigCustomizerTest.java deleted file mode 100644 index 49e5472f564..00000000000 --- a/sdk-extensions/metric-incubator/src/test/java/io/opentelemetry/sdk/viewconfig/ViewConfigCustomizerTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import java.util.Arrays; -import java.util.UUID; -import org.junit.jupiter.api.Test; - -class ViewConfigCustomizerTest { - - @Test - void customizeMeterProvider_Spi() { - InMemoryMetricReader reader = InMemoryMetricReader.create(); - AutoConfiguredOpenTelemetrySdk.builder() - .setResultAsGlobal(false) - .addPropertiesSupplier( - () -> { - return ImmutableMap.of( - "otel.traces.exporter", - "none", - "otel.metrics.exporter", - "none", - "otel.experimental.metrics.view.config", - "classpath:/view-config-customizer-test.yaml"); - }) - .addMeterProviderCustomizer( - (meterProviderBuilder, configProperties) -> - meterProviderBuilder.registerMetricReader(reader)) - .build() - .getOpenTelemetrySdk() - .getSdkMeterProvider() - .get("test-meter") - .counterBuilder("counter") - .buildWithCallback( - callback -> { - // Attributes with keys baz and qux should be filtered out - callback.record( - 1, - Attributes.builder() - .put("foo", "val") - .put("bar", "val") - .put("baz", "val") - .put("qux", "val") - .build()); - }); - - assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes( - attributeEntry("foo", "val"), - attributeEntry("bar", "val"))))); - } - - @Test - void customizeMeterProvider_MultipleFiles() { - ConfigProperties properties = - withConfigFileLocations( - "classpath:/view-config-customizer-test.yaml", "classpath:/full-config.yaml"); - - assertThatCode( - () -> - ViewConfigCustomizer.customizeMeterProvider(SdkMeterProvider.builder(), properties)) - .doesNotThrowAnyException(); - } - - @Test - void customizeMeterProvider_AbsolutePath() { - ConfigProperties properties = - withConfigFileLocations( - ViewConfigTest.class.getResource("/view-config-customizer-test.yaml").getFile()); - - assertThatCode( - () -> - ViewConfigCustomizer.customizeMeterProvider(SdkMeterProvider.builder(), properties)) - .doesNotThrowAnyException(); - } - - @Test - void customizeMeterProvider_Invalid() { - assertThatThrownBy( - () -> - ViewConfigCustomizer.customizeMeterProvider( - SdkMeterProvider.builder(), - withConfigFileLocations("classpath:" + UUID.randomUUID()))) - .hasMessageMatching("Resource .* not found on classpath of classloader .*"); - assertThatThrownBy( - () -> - ViewConfigCustomizer.customizeMeterProvider( - SdkMeterProvider.builder(), withConfigFileLocations("/" + UUID.randomUUID()))) - .hasMessageContaining("View config file not found:"); - assertThatThrownBy( - () -> - ViewConfigCustomizer.customizeMeterProvider( - SdkMeterProvider.builder(), - withConfigFileLocations("classpath:/empty-selector-config.yaml"))) - .hasMessageContaining("Failed to parse view config") - .hasRootCauseMessage("selector is required"); - } - - private static ConfigProperties withConfigFileLocations(String... fileLocations) { - ConfigProperties properties = mock(ConfigProperties.class); - when(properties.getList("otel.experimental.metrics.view.config")) - .thenReturn(Arrays.asList(fileLocations)); - return properties; - } -} diff --git a/sdk-extensions/metric-incubator/src/test/java/io/opentelemetry/sdk/viewconfig/ViewConfigTest.java b/sdk-extensions/metric-incubator/src/test/java/io/opentelemetry/sdk/viewconfig/ViewConfigTest.java deleted file mode 100644 index dbbd92ddf6d..00000000000 --- a/sdk-extensions/metric-incubator/src/test/java/io/opentelemetry/sdk/viewconfig/ViewConfigTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.viewconfig; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.assertj.core.api.Assertions.as; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.autoconfigure.spi.ConfigurationException; -import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.InstrumentSelector; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; -import io.opentelemetry.sdk.metrics.View; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; -import io.opentelemetry.sdk.metrics.internal.view.ViewRegistryBuilder; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.net.URL; -import java.util.Arrays; -import java.util.List; -import java.util.function.Consumer; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.jupiter.api.Test; - -class ViewConfigTest { - - @Test - void registerViews_FullConfig() { - SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); - - ViewConfig.registerViews(builder, resourceFileInputStream("full-config.yaml")); - - assertThat(builder) - .extracting( - "viewRegistryBuilder", as(InstanceOfAssertFactories.type(ViewRegistryBuilder.class))) - .extracting("orderedViews", as(InstanceOfAssertFactories.list(Object.class))) - .hasSize(2); - } - - @Test - void loadViewConfig_FullConfig() { - List viewConfigSpecs = - ViewConfig.loadViewConfig(resourceFileInputStream("full-config.yaml")); - - assertThat(viewConfigSpecs) - .satisfiesExactly( - viewConfigSpec -> { - SelectorSpecification selectorSpec = viewConfigSpec.getSelectorSpecification(); - assertThat(selectorSpec.getInstrumentName()).isEqualTo("name1"); - assertThat(selectorSpec.getInstrumentType()).isEqualTo(InstrumentType.COUNTER); - assertThat(selectorSpec.getMeterName()).isEqualTo("meterName1"); - assertThat(selectorSpec.getMeterVersion()).isEqualTo("1.0.0"); - assertThat(selectorSpec.getMeterSchemaUrl()).isEqualTo("http://example1.com"); - ViewSpecification viewSpec = viewConfigSpec.getViewSpecification(); - assertThat(viewSpec.getName()).isEqualTo("name1"); - assertThat(viewSpec.getDescription()).isEqualTo("description1"); - assertThat(viewSpec.getAggregation()).isEqualTo("sum"); - assertThat(viewSpec.getAttributeKeys()).containsExactly("foo", "bar"); - }, - viewConfigSpec -> { - SelectorSpecification selectorSpec = viewConfigSpec.getSelectorSpecification(); - assertThat(selectorSpec.getInstrumentName()).isEqualTo("name2"); - assertThat(selectorSpec.getInstrumentType()).isEqualTo(InstrumentType.COUNTER); - assertThat(selectorSpec.getMeterName()).isEqualTo("meterName2"); - assertThat(selectorSpec.getMeterVersion()).isEqualTo("2.0.0"); - assertThat(selectorSpec.getMeterSchemaUrl()).isEqualTo("http://example2.com"); - ViewSpecification viewSpec = viewConfigSpec.getViewSpecification(); - assertThat(viewSpec.getName()).isEqualTo("name2"); - assertThat(viewSpec.getDescription()).isEqualTo("description2"); - assertThat(viewSpec.getAggregation()).isEqualTo("last_value"); - assertThat(viewSpec.getAttributeKeys()).containsExactly("baz", "qux"); - }); - } - - @Test - void loadViewConfig_Invalid() { - assertThatThrownBy( - () -> ViewConfig.loadViewConfig(resourceFileInputStream("empty-view-config.yaml"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Failed to parse view config") - .hasRootCauseMessage("view is required"); - assertThatThrownBy( - () -> ViewConfig.loadViewConfig(resourceFileInputStream("empty-selector-config.yaml"))) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Failed to parse view config") - .hasRootCauseMessage("selector is required"); - } - - @Test - void toView_Empty() { - View view = ViewConfig.toView(ViewSpecification.builder().build()); - assertThat(view).isEqualTo(View.builder().build()); - } - - @Test - void toView() { - View view = - ViewConfig.toView( - ViewSpecification.builder() - .name("name") - .description("description") - .aggregation("sum") - .attributeKeys(Arrays.asList("foo", "bar")) - .build()); - assertThat(view.getName()).isEqualTo("name"); - assertThat(view.getDescription()).isEqualTo("description"); - assertThat(view.getAggregation()).isEqualTo(Aggregation.sum()); - assertThat(view) - .extracting( - "attributesProcessor", as(InstanceOfAssertFactories.type(AttributesProcessor.class))) - .satisfies( - attributesProcessor -> { - assertThat( - attributesProcessor.process( - Attributes.builder() - .put("foo", "val") - .put("bar", "val") - .put("baz", "val") - .build(), - Context.current())) - .containsEntry("foo", "val") - .containsEntry("bar", "val") - .satisfies( - (Consumer) - attributes -> - assertThat(attributes.get(AttributeKey.stringKey("baz"))).isBlank()); - }); - } - - @Test - void toAggregation() { - assertThatThrownBy(() -> ViewConfig.toAggregation("foo")) - .isInstanceOf(ConfigurationException.class) - .hasMessageContaining("Error creating aggregation"); - } - - @Test - void toInstrumentSelector() { - InstrumentSelector selector = - ViewConfig.toInstrumentSelector( - SelectorSpecification.builder() - .instrumentName("name") - .instrumentType(InstrumentType.COUNTER) - .meterName("meterName") - .meterVersion("meterVersion") - .meterSchemaUrl("http://example.com") - .build()); - - assertThat(selector.getInstrumentName()).isEqualTo("name"); - assertThat(selector.getInstrumentType()).isEqualTo(InstrumentType.COUNTER); - assertThat(selector.getMeterName()).isEqualTo("meterName"); - assertThat(selector.getMeterVersion()).isEqualTo("meterVersion"); - assertThat(selector.getMeterSchemaUrl()).isEqualTo("http://example.com"); - } - - private static InputStream resourceFileInputStream(String resourceFileName) { - URL resourceUrl = ViewConfigTest.class.getResource("/" + resourceFileName); - if (resourceUrl == null) { - throw new IllegalStateException("Could not find resource file: " + resourceFileName); - } - String path = resourceUrl.getFile(); - try { - return new FileInputStream(path); - } catch (FileNotFoundException e) { - throw new IllegalStateException("File not found: " + path, e); - } - } -} diff --git a/sdk-extensions/metric-incubator/src/test/resources/empty-selector-config.yaml b/sdk-extensions/metric-incubator/src/test/resources/empty-selector-config.yaml deleted file mode 100644 index 657a53c0f87..00000000000 --- a/sdk-extensions/metric-incubator/src/test/resources/empty-selector-config.yaml +++ /dev/null @@ -1,5 +0,0 @@ -- selector: - view: - name: name1 - description: description1 - aggregation: sum diff --git a/sdk-extensions/metric-incubator/src/test/resources/empty-view-config.yaml b/sdk-extensions/metric-incubator/src/test/resources/empty-view-config.yaml deleted file mode 100644 index 57c527ed3eb..00000000000 --- a/sdk-extensions/metric-incubator/src/test/resources/empty-view-config.yaml +++ /dev/null @@ -1,7 +0,0 @@ -- selector: - instrument_name: name1 - instrument_type: COUNTER - meter_name: meterName1 - meter_version: 1.0.0 - meter_schema_url: http://example1.com - view: diff --git a/sdk-extensions/metric-incubator/src/test/resources/full-config.yaml b/sdk-extensions/metric-incubator/src/test/resources/full-config.yaml deleted file mode 100644 index 1f0245d8c56..00000000000 --- a/sdk-extensions/metric-incubator/src/test/resources/full-config.yaml +++ /dev/null @@ -1,26 +0,0 @@ -- selector: - instrument_name: name1 - instrument_type: COUNTER - meter_name: meterName1 - meter_version: 1.0.0 - meter_schema_url: http://example1.com - view: - name: name1 - description: description1 - aggregation: sum - attribute_keys: - - foo - - bar -- selector: - instrument_name: name2 - instrument_type: COUNTER - meter_name: meterName2 - meter_version: 2.0.0 - meter_schema_url: http://example2.com - view: - name: name2 - description: description2 - aggregation: last_value - attribute_keys: - - baz - - qux diff --git a/sdk-extensions/metric-incubator/src/test/resources/view-config-customizer-test.yaml b/sdk-extensions/metric-incubator/src/test/resources/view-config-customizer-test.yaml deleted file mode 100644 index afa6514b62b..00000000000 --- a/sdk-extensions/metric-incubator/src/test/resources/view-config-customizer-test.yaml +++ /dev/null @@ -1,6 +0,0 @@ -- selector: - instrument_type: OBSERVABLE_COUNTER - view: - attribute_keys: - - foo - - bar \ No newline at end of file diff --git a/sdk-extensions/resources/README.md b/sdk-extensions/resources/README.md deleted file mode 100644 index 1e4b493c15c..00000000000 --- a/sdk-extensions/resources/README.md +++ /dev/null @@ -1,48 +0,0 @@ -# OpenTelemetry Resource Providers - -[![Javadocs][javadoc-image]][javadoc-url] - -This package includes some standard `ResourceProvider`s for filling in attributes related to -common environments. Currently the resources provide the following semantic conventions - -## Populated attributes - -### Operating System - -Provider: `io.opentelemetry.sdk.extension.resources.OsResource` - -Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/semantic_conventions/os.md - -Implemented attributes: -- `os.name` -- `os.description` - -### Process - -Implementation: `io.opentelemetry.sdk.extension.resources.ProcessResource` - -Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/semantic_conventions/process.md#process - -Implemented attributes: -- `process.pid` -- `process.executable.path` (note, we assume the `java` binary is located in the `bin` subfolder of `JAVA_HOME`) -- `process.command_line` (note this includes all system properties and arguments when running) - -### Java Runtime - -Implementation: `io.opentelemetry.sdk.extension.resources.ProcessRuntimeResource` - -Specification: https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/resource/semantic_conventions/process.md#process-runtimes - -Implemented attributes: -- `process.runtime.name` -- `process.runtime.version` -- `process.runtime.description` - -## Platforms - -This package currently does not run on Android. It has been verified on OpenJDK and should work on -other server JVM distributions but if you find any issues please let us know. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-resources.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-resources diff --git a/sdk-extensions/resources/build.gradle.kts b/sdk-extensions/resources/build.gradle.kts deleted file mode 100644 index 51db76b723e..00000000000 --- a/sdk-extensions/resources/build.gradle.kts +++ /dev/null @@ -1,66 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry SDK Resource Providers" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.resources") - -val mrJarVersions = listOf(11) - -dependencies { - api(project(":sdk:common")) - - implementation(project(":semconv")) - - compileOnly(project(":sdk-extensions:autoconfigure")) - - compileOnly("org.codehaus.mojo:animal-sniffer-annotations") -} - -for (version in mrJarVersions) { - sourceSets { - create("java$version") { - java { - setSrcDirs(listOf("src/main/java$version")) - } - } - } - - tasks { - named("compileJava${version}Java") { - sourceCompatibility = "$version" - targetCompatibility = "$version" - options.release.set(version) - } - } - - configurations { - named("java${version}Implementation") { - extendsFrom(configurations["implementation"]) - } - named("java${version}CompileOnly") { - extendsFrom(configurations["compileOnly"]) - } - } - - dependencies { - // Common to reference classes in main sourceset from Java 9 one (e.g., to return a common interface) - add("java${version}Implementation", files(sourceSets.main.get().output.classesDirs)) - } -} - -tasks { - withType(Jar::class) { - for (version in mrJarVersions) { - into("META-INF/versions/$version") { - from(sourceSets["java$version"].output) - } - } - manifest.attributes( - "Multi-Release" to "true" - ) - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ContainerResource.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ContainerResource.java deleted file mode 100644 index 123477e6ad3..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ContainerResource.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.OtelEncodingUtils; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Objects; -import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; - -/** Factory for {@link Resource} retrieving Container ID information. */ -public final class ContainerResource { - - private static final Logger logger = Logger.getLogger(ContainerResource.class.getName()); - private static final String UNIQUE_HOST_NAME_FILE_NAME = "/proc/self/cgroup"; - private static final Resource INSTANCE = buildSingleton(UNIQUE_HOST_NAME_FILE_NAME); - - @IgnoreJRERequirement - private static Resource buildSingleton(String uniqueHostNameFileName) { - // can't initialize this statically without running afoul of animalSniffer on paths - return buildResource(Paths.get(uniqueHostNameFileName)); - } - - // package private for testing - static Resource buildResource(Path path) { - String containerId = extractContainerId(path); - - if (containerId == null || containerId.isEmpty()) { - return Resource.empty(); - } else { - return Resource.create(Attributes.of(ResourceAttributes.CONTAINER_ID, containerId)); - } - } - - /** Returns resource with container information. */ - public static Resource get() { - return INSTANCE; - } - - /** - * Each line of cgroup file looks like "14:name=systemd:/docker/.../... A hex string is expected - * inside the last section separated by '/' Each segment of the '/' can contain metadata separated - * by either '.' (at beginning) or '-' (at end) - * - * @return containerId - */ - @IgnoreJRERequirement - @Nullable - private static String extractContainerId(Path cgroupFilePath) { - if (!Files.exists(cgroupFilePath) || !Files.isReadable(cgroupFilePath)) { - return null; - } - try (Stream lines = Files.lines(cgroupFilePath)) { - Optional value = - lines - .filter(line -> !line.isEmpty()) - .map(ContainerResource::getIdFromLine) - .filter(Objects::nonNull) - .findFirst(); - if (value.isPresent()) { - return value.get(); - } - } catch (IOException e) { - logger.log(Level.WARNING, "Unable to read file: " + e.getMessage()); - } - return null; - } - - @Nullable - private static String getIdFromLine(String line) { - // This cgroup output line should have the container id in it - int lastSlashIdx = line.lastIndexOf('/'); - if (lastSlashIdx < 0) { - return null; - } - - String lastSection = line.substring(lastSlashIdx + 1); - int startIdx = lastSection.lastIndexOf('-'); - int endIdx = lastSection.lastIndexOf('.'); - - String containerId = - lastSection.substring( - startIdx == -1 ? 0 : startIdx + 1, endIdx == -1 ? lastSection.length() : endIdx); - if (OtelEncodingUtils.isValidBase16String(containerId) && !containerId.isEmpty()) { - return containerId; - } else { - return null; - } - } - - private ContainerResource() {} -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ContainerResourceProvider.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ContainerResourceProvider.java deleted file mode 100644 index 1146737777f..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ContainerResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link ResourceProvider}. */ -public class ContainerResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return ContainerResource.get(); - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/HostResource.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/HostResource.java deleted file mode 100644 index e3ecf76416b..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/HostResource.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.net.InetAddress; -import java.net.UnknownHostException; - -/** Factory for a {@link Resource} which provides information about the host info. */ -public final class HostResource { - - private static final Resource INSTANCE = buildResource(); - - /** Returns a {@link Resource} which provides information about host. */ - public static Resource get() { - return INSTANCE; - } - - // Visible for testing - static Resource buildResource() { - AttributesBuilder attributes = Attributes.builder(); - try { - attributes.put(ResourceAttributes.HOST_NAME, InetAddress.getLocalHost().getHostName()); - } catch (UnknownHostException e) { - // Ignore - } - String hostArch = null; - try { - hostArch = System.getProperty("os.arch"); - } catch (SecurityException t) { - // Ignore - } - if (hostArch != null) { - attributes.put(ResourceAttributes.HOST_ARCH, hostArch); - } - - return Resource.create(attributes.build(), ResourceAttributes.SCHEMA_URL); - } - - private HostResource() {} -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/HostResourceProvider.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/HostResourceProvider.java deleted file mode 100644 index b49691ba1bc..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/HostResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link HostResource}. */ -public final class HostResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return HostResource.get(); - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/OsResource.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/OsResource.java deleted file mode 100644 index 323988da2da..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/OsResource.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import javax.annotation.Nullable; - -/** Factory of a {@link Resource} which provides information about the current operating system. */ -public final class OsResource { - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a factory for a {@link Resource} which provides information about the current operating - * system. - */ - public static Resource get() { - return INSTANCE; - } - - // Visible for testing - static Resource buildResource() { - - String os; - try { - os = System.getProperty("os.name"); - } catch (SecurityException t) { - // Security manager enabled, can't provide much os information. - return Resource.empty(); - } - - if (os == null) { - return Resource.empty(); - } - - AttributesBuilder attributes = Attributes.builder(); - - String osName = getOs(os); - if (osName != null) { - attributes.put(ResourceAttributes.OS_TYPE, osName); - } - - String version = null; - try { - version = System.getProperty("os.version"); - } catch (SecurityException e) { - // Ignore - } - String osDescription = version != null ? os + ' ' + version : os; - attributes.put(ResourceAttributes.OS_DESCRIPTION, osDescription); - - return Resource.create(attributes.build(), ResourceAttributes.SCHEMA_URL); - } - - @Nullable - private static String getOs(String os) { - os = os.toLowerCase(); - if (os.startsWith("windows")) { - return ResourceAttributes.OsTypeValues.WINDOWS; - } else if (os.startsWith("linux")) { - return ResourceAttributes.OsTypeValues.LINUX; - } else if (os.startsWith("mac")) { - return ResourceAttributes.OsTypeValues.DARWIN; - } else if (os.startsWith("freebsd")) { - return ResourceAttributes.OsTypeValues.FREEBSD; - } else if (os.startsWith("netbsd")) { - return ResourceAttributes.OsTypeValues.NETBSD; - } else if (os.startsWith("openbsd")) { - return ResourceAttributes.OsTypeValues.OPENBSD; - } else if (os.startsWith("dragonflybsd")) { - return ResourceAttributes.OsTypeValues.DRAGONFLYBSD; - } else if (os.startsWith("hp-ux")) { - return ResourceAttributes.OsTypeValues.HPUX; - } else if (os.startsWith("aix")) { - return ResourceAttributes.OsTypeValues.AIX; - } else if (os.startsWith("solaris")) { - return ResourceAttributes.OsTypeValues.SOLARIS; - } else if (os.startsWith("z/os")) { - return ResourceAttributes.OsTypeValues.Z_OS; - } - return null; - } - - private OsResource() {} -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/OsResourceProvider.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/OsResourceProvider.java deleted file mode 100644 index e7e70d8314a..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/OsResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link OsResource}. */ -public final class OsResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return OsResource.get(); - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessPid.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessPid.java deleted file mode 100644 index 43ad8e10f63..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessPid.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import java.lang.management.ManagementFactory; -import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; - -final class ProcessPid { - - private ProcessPid() {} - - @IgnoreJRERequirement - static long getPid() { - // While this is not strictly defined, almost all commonly used JVMs format this as - // pid@hostname. - String runtimeName = ManagementFactory.getRuntimeMXBean().getName(); - int atIndex = runtimeName.indexOf('@'); - if (atIndex >= 0) { - String pidString = runtimeName.substring(0, atIndex); - try { - return Long.parseLong(pidString); - } catch (NumberFormatException ignored) { - // Ignore parse failure. - } - } - return -1; - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessResource.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessResource.java deleted file mode 100644 index 03c3702d41d..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessResource.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.File; -import java.lang.management.ManagementFactory; -import java.lang.management.RuntimeMXBean; -import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; - -/** Factory of a {@link Resource} which provides information about the current running process. */ -public final class ProcessResource { - - private static final Resource INSTANCE = buildResource(); - - /** - * Returns a factory for a {@link Resource} which provides information about the current running - * process. - */ - public static Resource get() { - return INSTANCE; - } - - // Visible for testing - static Resource buildResource() { - try { - return doBuildResource(); - } catch (LinkageError t) { - // Will only happen on Android, where these attributes generally don't make much sense - // anyways. - return Resource.empty(); - } - } - - @IgnoreJRERequirement - private static Resource doBuildResource() { - AttributesBuilder attributes = Attributes.builder(); - - RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); - - long pid = ProcessPid.getPid(); - - if (pid >= 0) { - attributes.put(ResourceAttributes.PROCESS_PID, pid); - } - - String javaHome = null; - String osName = null; - try { - javaHome = System.getProperty("java.home"); - osName = System.getProperty("os.name"); - } catch (SecurityException e) { - // Ignore - } - if (javaHome != null) { - StringBuilder executablePath = new StringBuilder(javaHome); - executablePath - .append(File.pathSeparatorChar) - .append("bin") - .append(File.pathSeparatorChar) - .append("java"); - if (osName != null && osName.toLowerCase().startsWith("windows")) { - executablePath.append(".exe"); - } - - attributes.put(ResourceAttributes.PROCESS_EXECUTABLE_PATH, executablePath.toString()); - - StringBuilder commandLine = new StringBuilder(executablePath); - for (String arg : runtime.getInputArguments()) { - commandLine.append(' ').append(arg); - } - attributes.put(ResourceAttributes.PROCESS_COMMAND_LINE, commandLine.toString()); - } - - return Resource.create(attributes.build(), ResourceAttributes.SCHEMA_URL); - } - - private ProcessResource() {} -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessResourceProvider.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessResourceProvider.java deleted file mode 100644 index 1ed9a4c3f18..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link ProcessResource}. */ -public final class ProcessResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return ProcessResource.get(); - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResource.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResource.java deleted file mode 100644 index 2bd8054b4ce..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResource.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.PROCESS_RUNTIME_DESCRIPTION; -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.PROCESS_RUNTIME_NAME; -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.PROCESS_RUNTIME_VERSION; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; - -/** Factory of a {@link Resource} which provides information about the Java runtime. */ -public final class ProcessRuntimeResource { - - private static final Resource INSTANCE = buildResource(); - - /** Returns a factory for a {@link Resource} which provides information about the Java runtime. */ - public static Resource get() { - return INSTANCE; - } - - // Visible for testing - static Resource buildResource() { - try { - String name = System.getProperty("java.runtime.name"); - String version = System.getProperty("java.runtime.version"); - String description = - System.getProperty("java.vm.vendor") - + " " - + System.getProperty("java.vm.name") - + " " - + System.getProperty("java.vm.version"); - - return Resource.create( - Attributes.of( - PROCESS_RUNTIME_NAME, - name, - PROCESS_RUNTIME_VERSION, - version, - PROCESS_RUNTIME_DESCRIPTION, - description), - ResourceAttributes.SCHEMA_URL); - } catch (SecurityException ignored) { - return Resource.empty(); - } - } - - private ProcessRuntimeResource() {} -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResourceProvider.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResourceProvider.java deleted file mode 100644 index e35155132f4..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResourceProvider.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import io.opentelemetry.sdk.autoconfigure.spi.ConfigProperties; -import io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider; -import io.opentelemetry.sdk.resources.Resource; - -/** {@link ResourceProvider} for automatically configuring {@link ProcessRuntimeResource}. */ -public final class ProcessRuntimeResourceProvider implements ResourceProvider { - @Override - public Resource createResource(ConfigProperties config) { - return ProcessRuntimeResource.get(); - } -} diff --git a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/package-info.java b/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/package-info.java deleted file mode 100644 index 9d134a78cd1..00000000000 --- a/sdk-extensions/resources/src/main/java/io/opentelemetry/sdk/extension/resources/package-info.java +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * {@link io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider} implementations for common - * resource information. - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.extension.resources; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/resources/src/main/java11/io/opentelemetry/sdk/extension/resources/ProcessPid.java b/sdk-extensions/resources/src/main/java11/io/opentelemetry/sdk/extension/resources/ProcessPid.java deleted file mode 100644 index e4da0fc9437..00000000000 --- a/sdk-extensions/resources/src/main/java11/io/opentelemetry/sdk/extension/resources/ProcessPid.java +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import java.lang.management.ManagementFactory; -import org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement; - -final class ProcessPid { - - private ProcessPid() {} - - @IgnoreJRERequirement - static long getPid() { - return ManagementFactory.getRuntimeMXBean().getPid(); - } -} diff --git a/sdk-extensions/resources/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider b/sdk-extensions/resources/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider deleted file mode 100644 index 8ac23c697a4..00000000000 --- a/sdk-extensions/resources/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.ResourceProvider +++ /dev/null @@ -1,5 +0,0 @@ -io.opentelemetry.sdk.extension.resources.ContainerResourceProvider -io.opentelemetry.sdk.extension.resources.HostResourceProvider -io.opentelemetry.sdk.extension.resources.OsResourceProvider -io.opentelemetry.sdk.extension.resources.ProcessResourceProvider -io.opentelemetry.sdk.extension.resources.ProcessRuntimeResourceProvider diff --git a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ContainerResourceTest.java b/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ContainerResourceTest.java deleted file mode 100644 index 2b3de4428b2..00000000000 --- a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ContainerResourceTest.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import static io.opentelemetry.sdk.extension.resources.ContainerResource.buildResource; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.io.TempDir; - -public class ContainerResourceTest { - - // Invalid because ID is not a hex string - private static final String INVALID_CGROUP_LINE_1 = - "13:name=systemd:/podruntime/docker/kubepods/ac679f8a8319c8cf7d38e1adf263bc08d23zzzz"; - - // with suffix - private static final String CGROUP_LINE_1 = - "13:name=systemd:/podruntime/docker/kubepods/ac679f8a8319c8cf7d38e1adf263bc08d23.aaaa"; - private static final String EXPECTED_CGROUP_1 = "ac679f8a8319c8cf7d38e1adf263bc08d23"; - - // with prefix and suffix - private static final String CGROUP_LINE_2 = - "13:name=systemd:/podruntime/docker/kubepods/crio-dc679f8a8319c8cf7d38e1adf263bc08d23.stuff"; - private static final String EXPECTED_CGROUP_2 = "dc679f8a8319c8cf7d38e1adf263bc08d23"; - - // just container id - private static final String CGROUP_LINE_3 = - "13:name=systemd:/pod/d86d75589bf6cc254f3e2cc29debdf85dde404998aa128997a819ff991827356"; - private static final String EXPECTED_CGROUP_3 = - "d86d75589bf6cc254f3e2cc29debdf85dde404998aa128997a819ff991827356"; - - // with prefix - private static final String CGROUP_LINE_4 = - "//\n" - + "1:name=systemd:/podruntime/docker/kubepods/docker-dc579f8a8319c8cf7d38e1adf263bc08d23" - + "2:name=systemd:/podruntime/docker/kubepods/docker-dc579f8a8319c8cf7d38e1adf263bc08d23" - + "3:name=systemd:/podruntime/docker/kubepods/docker-dc579f8a8319c8cf7d38e1adf263bc08d23"; - - private static final String EXPECTED_CGROUP_4 = "dc579f8a8319c8cf7d38e1adf263bc08d23"; - - // with two dashes in prefix - private static final String CGROUP_LINE_5 = - "11:perf_event:/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod4415fd05_2c0f_4533_909b_f2180dca8d7c.slice/cri-containerd-713a77a26fe2a38ebebd5709604a048c3d380db1eb16aa43aca0b2499e54733c.scope"; - private static final String EXPECTED_CGROUP_5 = - "713a77a26fe2a38ebebd5709604a048c3d380db1eb16aa43aca0b2499e54733c"; - - @Test - public void testNegativeCases(@TempDir Path tempFolder) throws IOException { - // invalid containerId (non-hex) - Path cgroup = createCGroup(tempFolder.resolve("cgroup1"), INVALID_CGROUP_LINE_1); - assertThat(buildResource(cgroup)).isEqualTo(Resource.empty()); - - // test invalid file - cgroup = tempFolder.resolve("DoesNotExist"); - assertThat(buildResource(cgroup)).isEqualTo(Resource.empty()); - } - - @Test - public void testContainer(@TempDir Path tempFolder) throws IOException { - Path cgroup = createCGroup(tempFolder.resolve("cgroup1"), CGROUP_LINE_1); - assertThat(getContainerId(buildResource(cgroup))).isEqualTo(EXPECTED_CGROUP_1); - - Path cgroup2 = createCGroup(tempFolder.resolve("cgroup2"), CGROUP_LINE_2); - assertThat(getContainerId(buildResource(cgroup2))).isEqualTo(EXPECTED_CGROUP_2); - - Path cgroup3 = createCGroup(tempFolder.resolve("cgroup3"), CGROUP_LINE_3); - assertThat(getContainerId(buildResource(cgroup3))).isEqualTo(EXPECTED_CGROUP_3); - - Path cgroup4 = createCGroup(tempFolder.resolve("cgroup4"), CGROUP_LINE_4); - assertThat(getContainerId(buildResource(cgroup4))).isEqualTo(EXPECTED_CGROUP_4); - - Path cgroup5 = createCGroup(tempFolder.resolve("cgroup5"), CGROUP_LINE_5); - assertThat(getContainerId(buildResource(cgroup5))).isEqualTo(EXPECTED_CGROUP_5); - } - - private static String getContainerId(Resource resource) { - return resource.getAttribute(ResourceAttributes.CONTAINER_ID); - } - - private static Path createCGroup(Path path, String line) throws IOException { - return Files.write(path, line.getBytes(StandardCharsets.UTF_8)); - } -} diff --git a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/HostResourceTest.java b/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/HostResourceTest.java deleted file mode 100644 index 15bb9dc6db9..00000000000 --- a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/HostResourceTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.condition.EnabledOnJre; -import org.junit.jupiter.api.condition.JRE; -import org.junit.jupiter.api.extension.ExtendWith; - -class HostResourceTest { - @Test - void shouldCreateRuntimeAttributes() { - // when - Resource resource = HostResource.buildResource(); - Attributes attributes = resource.getAttributes(); - - // then - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(attributes.get(ResourceAttributes.HOST_NAME)).isNotBlank(); - assertThat(attributes.get(ResourceAttributes.HOST_ARCH)).isNotBlank(); - } - - @Nested - @TestInstance(TestInstance.Lifecycle.PER_CLASS) - @ExtendWith(SecurityManagerExtension.class) - @EnabledOnJre( - value = {JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_16}, - disabledReason = "Java 17 deprecates security manager for removal") - static class SecurityManagerEnabled { - @Test - void empty() { - Attributes attributes = HostResource.buildResource().getAttributes(); - assertThat(attributes.asMap()).containsOnlyKeys(ResourceAttributes.HOST_NAME); - } - } -} diff --git a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/OsResourceTest.java b/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/OsResourceTest.java deleted file mode 100644 index 4a2c64b88bc..00000000000 --- a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/OsResourceTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.condition.EnabledOnJre; -import org.junit.jupiter.api.condition.JRE; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junitpioneer.jupiter.SetSystemProperty; - -class OsResourceTest { - - @Test - @SetSystemProperty(key = "os.name", value = "Linux 4.11") - void linux() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.LINUX); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "MacOS X 11") - void macos() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.DARWIN); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "Windows 10") - void windows() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.WINDOWS); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "FreeBSD 10") - void freebsd() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.FREEBSD); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "NetBSD 10") - void netbsd() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.NETBSD); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "OpenBSD 10") - void openbsd() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.OPENBSD); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "DragonFlyBSD 10") - void dragonflybsd() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.DRAGONFLYBSD); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "HP-UX 10") - void hpux() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.HPUX); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "AIX 10") - void aix() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.AIX); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "Solaris 10") - void solaris() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.SOLARIS); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "Z/OS 10") - void zos() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)) - .isEqualTo(ResourceAttributes.OsTypeValues.Z_OS); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Test - @SetSystemProperty(key = "os.name", value = "RagOS 10") - void unknown() { - Resource resource = OsResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(resource.getAttribute(ResourceAttributes.OS_TYPE)).isNull(); - assertThat(resource.getAttribute(ResourceAttributes.OS_DESCRIPTION)).isNotEmpty(); - } - - @Nested - @TestInstance(TestInstance.Lifecycle.PER_CLASS) - @ExtendWith(SecurityManagerExtension.class) - @EnabledOnJre( - value = {JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_16}, - disabledReason = "Java 17 deprecates security manager for removal") - static class SecurityManagerEnabled { - @Test - void empty() { - assertThat(OsResource.buildResource()).isEqualTo(Resource.empty()); - } - } -} diff --git a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ProcessResourceTest.java b/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ProcessResourceTest.java deleted file mode 100644 index 073d347634e..00000000000 --- a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ProcessResourceTest.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.condition.EnabledOnJre; -import org.junit.jupiter.api.condition.JRE; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junitpioneer.jupiter.SetSystemProperty; - -class ProcessResourceTest { - - @Test - @SetSystemProperty(key = "os.name", value = "Linux 4.12") - void notWindows() { - Resource resource = ProcessResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - Attributes attributes = resource.getAttributes(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_PID)).isGreaterThan(1); - assertThat(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)) - .contains("java") - .doesNotEndWith(".exe"); - assertThat(attributes.get(ResourceAttributes.PROCESS_COMMAND_LINE)) - .contains(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)); - } - - @Test - @SetSystemProperty(key = "os.name", value = "Windows 10") - void windows() { - Resource resource = ProcessResource.buildResource(); - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - Attributes attributes = resource.getAttributes(); - - assertThat(attributes.get(ResourceAttributes.PROCESS_PID)).isGreaterThan(1); - assertThat(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)) - .contains("java") - .endsWith(".exe"); - assertThat(attributes.get(ResourceAttributes.PROCESS_COMMAND_LINE)) - .contains(attributes.get(ResourceAttributes.PROCESS_EXECUTABLE_PATH)); - } - - @Nested - @TestInstance(TestInstance.Lifecycle.PER_CLASS) - @ExtendWith(SecurityManagerExtension.class) - @EnabledOnJre( - value = {JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_16}, - disabledReason = "Java 17 deprecates security manager for removal") - static class SecurityManagerEnabled { - @Test - void empty() { - Attributes attributes = ProcessResource.buildResource().getAttributes(); - assertThat(attributes.asMap()).containsOnlyKeys(ResourceAttributes.PROCESS_PID); - } - } -} diff --git a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResourceTest.java b/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResourceTest.java deleted file mode 100644 index 290dde44352..00000000000 --- a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/ProcessRuntimeResourceTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; -import org.junit.jupiter.api.Nested; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; -import org.junit.jupiter.api.condition.EnabledOnJre; -import org.junit.jupiter.api.condition.JRE; -import org.junit.jupiter.api.extension.ExtendWith; - -class ProcessRuntimeResourceTest { - @Test - void shouldCreateRuntimeAttributes() { - // when - Resource resource = ProcessRuntimeResource.buildResource(); - Attributes attributes = resource.getAttributes(); - - // then - assertThat(resource.getSchemaUrl()).isEqualTo(ResourceAttributes.SCHEMA_URL); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_NAME)).isNotBlank(); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_VERSION)).isNotBlank(); - assertThat(attributes.get(ResourceAttributes.PROCESS_RUNTIME_DESCRIPTION)).isNotBlank(); - } - - @Nested - @TestInstance(TestInstance.Lifecycle.PER_CLASS) - @ExtendWith(SecurityManagerExtension.class) - @EnabledOnJre( - value = {JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_16}, - disabledReason = "Java 17 deprecates security manager for removal") - static class SecurityManagerEnabled { - @Test - void empty() { - assertThat(ProcessRuntimeResource.buildResource()).isEqualTo(Resource.empty()); - } - } -} diff --git a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/SecurityManagerExtension.java b/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/SecurityManagerExtension.java deleted file mode 100644 index ba3f4e980f6..00000000000 --- a/sdk-extensions/resources/src/test/java/io/opentelemetry/sdk/extension/resources/SecurityManagerExtension.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.resources; - -import java.security.Permission; -import java.util.HashSet; -import java.util.PropertyPermission; -import java.util.Set; -import org.junit.jupiter.api.extension.AfterEachCallback; -import org.junit.jupiter.api.extension.BeforeEachCallback; -import org.junit.jupiter.api.extension.ExtensionContext; - -final class SecurityManagerExtension implements BeforeEachCallback, AfterEachCallback { - - private static final ExtensionContext.Namespace NAMESPACE = - ExtensionContext.Namespace.create(SecurityManagerExtension.class); - - @Override - public void beforeEach(ExtensionContext context) { - context.getStore(NAMESPACE).put(SecurityManager.class, System.getSecurityManager()); - System.setSecurityManager(BlockPropertiesAccess.INSTANCE); - } - - @Override - public void afterEach(ExtensionContext context) { - System.setSecurityManager( - (SecurityManager) context.getStore(NAMESPACE).get(SecurityManager.class)); - } - - private static class BlockPropertiesAccess extends SecurityManager { - - private static final BlockPropertiesAccess INSTANCE = new BlockPropertiesAccess(); - - private static final Set BLOCKED_PROPERTIES = new HashSet<>(); - - static { - BLOCKED_PROPERTIES.add("java.home"); - BLOCKED_PROPERTIES.add("java.runtime.home"); - BLOCKED_PROPERTIES.add("java.runtime.version"); - BLOCKED_PROPERTIES.add("java.vm.name"); - BLOCKED_PROPERTIES.add("java.vm.vendor"); - BLOCKED_PROPERTIES.add("java.vm.version"); - BLOCKED_PROPERTIES.add("os.arch"); - BLOCKED_PROPERTIES.add("os.name"); - BLOCKED_PROPERTIES.add("os.version"); - } - - @Override - public void checkPermission(Permission perm) { - if (perm instanceof PropertyPermission) { - if (BLOCKED_PROPERTIES.contains(perm.getName())) { - throw new SecurityException("Property access not allowed."); - } - } - } - } -} diff --git a/sdk-extensions/tracing-incubator/README.md b/sdk-extensions/tracing-incubator/README.md deleted file mode 100644 index 14071eb1625..00000000000 --- a/sdk-extensions/tracing-incubator/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Tracing Incubator - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-tracing-incubator.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-tracing-incubator diff --git a/sdk-extensions/tracing-incubator/build.gradle.kts b/sdk-extensions/tracing-incubator/build.gradle.kts deleted file mode 100644 index d6b140ff8f8..00000000000 --- a/sdk-extensions/tracing-incubator/build.gradle.kts +++ /dev/null @@ -1,24 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -// SDK modules that are still being developed. - -description = "OpenTelemetry SDK Tracing Incubator" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.trace.incubator") - -dependencies { - api(project(":api:all")) - api(project(":sdk:trace")) - - compileOnly(project(":sdk:trace-shaded-deps")) - - implementation(project(":semconv")) - - annotationProcessor("com.google.auto.value:auto-value") - testImplementation(project(":sdk:testing")) - testImplementation("com.google.guava:guava-testlib") -} diff --git a/sdk-extensions/tracing-incubator/gradle.properties b/sdk-extensions/tracing-incubator/gradle.properties deleted file mode 100644 index 4476ae57e31..00000000000 --- a/sdk-extensions/tracing-incubator/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -otel.release=alpha diff --git a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/BlockingSpanExporter.java b/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/BlockingSpanExporter.java deleted file mode 100644 index 561838baaa5..00000000000 --- a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/BlockingSpanExporter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.incubator.trace; - -import io.opentelemetry.api.internal.GuardedBy; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.Collection; - -public final class BlockingSpanExporter implements SpanExporter { - - final Object monitor = new Object(); - - private enum State { - WAIT_TO_BLOCK, - BLOCKED, - UNBLOCKED - } - - @GuardedBy("monitor") - State state = State.WAIT_TO_BLOCK; - - @Override - public CompletableResultCode export(Collection spanDataList) { - synchronized (monitor) { - while (state != State.UNBLOCKED) { - try { - state = State.BLOCKED; - // Some threads may wait for Blocked State. - monitor.notifyAll(); - monitor.wait(); - } catch (InterruptedException e) { - // Do nothing - } - } - } - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - public void waitUntilIsBlocked() { - synchronized (monitor) { - while (state != State.BLOCKED) { - try { - monitor.wait(); - } catch (InterruptedException e) { - // Do nothing - } - } - } - } - - @Override - public CompletableResultCode shutdown() { - // Do nothing; - return CompletableResultCode.ofSuccess(); - } - - public void unblock() { - synchronized (monitor) { - state = State.UNBLOCKED; - monitor.notifyAll(); - } - } -} diff --git a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/CompletableSpanExporter.java b/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/CompletableSpanExporter.java deleted file mode 100644 index 6acc5618f8a..00000000000 --- a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/CompletableSpanExporter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.incubator.trace; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -public class CompletableSpanExporter implements SpanExporter { - - private final List results = new ArrayList<>(); - - private final List exported = new ArrayList<>(); - - private volatile boolean succeeded; - - List getExported() { - return exported; - } - - void succeed() { - succeeded = true; - results.forEach(CompletableResultCode::succeed); - } - - @Override - public CompletableResultCode export(Collection spans) { - exported.addAll(spans); - if (succeeded) { - return CompletableResultCode.ofSuccess(); - } - CompletableResultCode result = new CompletableResultCode(); - results.add(result); - return result; - } - - @Override - public CompletableResultCode flush() { - if (succeeded) { - return CompletableResultCode.ofSuccess(); - } else { - return CompletableResultCode.ofFailure(); - } - } - - @Override - public CompletableResultCode shutdown() { - return flush(); - } -} diff --git a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/WaitingSpanExporter.java b/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/WaitingSpanExporter.java deleted file mode 100644 index 4acb0ab9880..00000000000 --- a/sdk-extensions/tracing-incubator/src/test/java/io/opentelemetry/sdk/extension/incubator/trace/WaitingSpanExporter.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.incubator.trace; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.export.SpanExporter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import javax.annotation.Nullable; - -public class WaitingSpanExporter implements SpanExporter { - - private final ConcurrentLinkedQueue spanDataList = new ConcurrentLinkedQueue<>(); - private final int numberToWaitFor; - private final CompletableResultCode exportResultCode; - private CountDownLatch countDownLatch; - private int timeout = 10; - public final AtomicBoolean shutDownCalled = new AtomicBoolean(false); - - WaitingSpanExporter(int numberToWaitFor, CompletableResultCode exportResultCode) { - countDownLatch = new CountDownLatch(numberToWaitFor); - this.numberToWaitFor = numberToWaitFor; - this.exportResultCode = exportResultCode; - } - - WaitingSpanExporter(int numberToWaitFor, CompletableResultCode exportResultCode, int timeout) { - this(numberToWaitFor, exportResultCode); - this.timeout = timeout; - } - - List getExported() { - List result = new ArrayList<>(spanDataList); - spanDataList.clear(); - return result; - } - - /** - * Waits until we received numberOfSpans spans to export. Returns the list of exported {@link - * SpanData} objects, otherwise {@code null} if the current thread is interrupted. - * - * @return the list of exported {@link SpanData} objects, otherwise {@code null} if the current - * thread is interrupted. - */ - @Nullable - List waitForExport() { - try { - countDownLatch.await(timeout, TimeUnit.SECONDS); - } catch (InterruptedException e) { - // Preserve the interruption status as per guidance. - Thread.currentThread().interrupt(); - return null; - } - return getExported(); - } - - @Override - public CompletableResultCode export(Collection spans) { - this.spanDataList.addAll(spans); - for (int i = 0; i < spans.size(); i++) { - countDownLatch.countDown(); - } - return exportResultCode; - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - shutDownCalled.set(true); - return CompletableResultCode.ofSuccess(); - } - - public void reset() { - this.countDownLatch = new CountDownLatch(numberToWaitFor); - } -} diff --git a/sdk-extensions/zpages/README.md b/sdk-extensions/zpages/README.md deleted file mode 100644 index 5153cf5ed77..00000000000 --- a/sdk-extensions/zpages/README.md +++ /dev/null @@ -1,76 +0,0 @@ -# OpenTelemetry SDK Extension zPages - -[![Javadocs][javadoc-image]][javadoc-url] - -This module contains code for the OpenTelemetry Java zPages, which are a collection of dynamic HTML -web pages embedded in your app that display stats and trace data. Learn more in [this blog post](https://medium.com/opentelemetry/zpages-in-opentelemetry-2b080a81eb47). - -### Register the zPages - -**Note:** The package `com.sun.net.httpserver` is required to use the default zPages setup. Please make sure your -version of the JDK includes this package. - -To set-up the zPages, simply call `ZPageServer.startHttpServerAndRegisterAllPages(int port)` in your -main function: - -```java -public class MyMainClass { - public static void main(String[] args) throws Exception { - ZPageServer.startHttpServerAndRegisterAllPages(8080); - // ... do work - } -} -``` - -Alternatively, you can call `ZPageServer.registerAllPagesToHttpServer(HttpServer server)` to -register the zPages to a shared server: - -```java -public class MyMainClass { - public static void main(String[] args) throws Exception { - HttpServer server = HttpServer.create(new InetSocketAddress(8000), 10); - ZPageServer.registerAllPagesToHttpServer(server); - server.start(); - // ... do work - } -} -``` - -### Access the zPages - -#### View all available zPages on the `/` index page - -The index page `/` lists all available zPages with a link and description. - -#### View trace spans on the `/tracez` zPage - -The /tracez zPage displays information on running spans, sample span latencies, and sample error -spans. The data is aggregated into a summary-level table: - -![tracez-table](img/tracez-table.png) - -You can click on each of the counts in the table cells to access the corresponding span -details. For example, here are the details of the `ChildSpan` latency sample (row 1, col 4): - -![tracez-details](img/tracez-details.png) - -#### View and update the tracing configuration on the `/traceconfigz` zPage - -The /traceconfigz zPage displays information about the currently active tracing configuration and -provides an interface for users to modify relevant parameters. Here is what the web page looks like: - -![traceconfigz](img/traceconfigz.png) - -## Benchmark Testing - -This module contains two sets of benchmark tests: one for adding spans to an instance of -TracezSpanBuckets and another for retrieving counts and spans with TracezDataAggregator. You can run -the tests yourself with the following commands: - -``` -./gradlew -PjmhIncludeSingleClass=TracezSpanBucketsBenchmark clean :opentelemetry-sdk-extension-zpages:jmh -./gradlew -PjmhIncludeSingleClass=TracezDataAggregatorBenchmark clean :opentelemetry-sdk-extension-zpages:jmh -``` - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-zpages.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-zpages diff --git a/sdk-extensions/zpages/build.gradle.kts b/sdk-extensions/zpages/build.gradle.kts deleted file mode 100644 index 16143f99bb5..00000000000 --- a/sdk-extensions/zpages/build.gradle.kts +++ /dev/null @@ -1,20 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.jmh-conventions") -} - -description = "OpenTelemetry - zPages" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.zpages") - -dependencies { - implementation(project(":api:all")) - implementation(project(":sdk:all")) - - testImplementation(project(":sdk:testing")) - - testImplementation("com.google.guava:guava") - - compileOnly("com.sun.net.httpserver:http") -} diff --git a/sdk-extensions/zpages/gradle.properties b/sdk-extensions/zpages/gradle.properties deleted file mode 100644 index 4476ae57e31..00000000000 --- a/sdk-extensions/zpages/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -otel.release=alpha diff --git a/sdk-extensions/zpages/img/traceconfigz.png b/sdk-extensions/zpages/img/traceconfigz.png deleted file mode 100644 index 0047e1ab8c1..00000000000 Binary files a/sdk-extensions/zpages/img/traceconfigz.png and /dev/null differ diff --git a/sdk-extensions/zpages/img/tracez-details.png b/sdk-extensions/zpages/img/tracez-details.png deleted file mode 100644 index d45a013911e..00000000000 Binary files a/sdk-extensions/zpages/img/tracez-details.png and /dev/null differ diff --git a/sdk-extensions/zpages/img/tracez-table.png b/sdk-extensions/zpages/img/tracez-table.png deleted file mode 100644 index c9605fe38d2..00000000000 Binary files a/sdk-extensions/zpages/img/tracez-table.png and /dev/null differ diff --git a/sdk-extensions/zpages/src/jmh/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregatorBenchmark.java b/sdk-extensions/zpages/src/jmh/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregatorBenchmark.java deleted file mode 100644 index 893bc97e81b..00000000000 --- a/sdk-extensions/zpages/src/jmh/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregatorBenchmark.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Param; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.TearDown; -import org.openjdk.jmh.annotations.Threads; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.Blackhole; - -/** Benchmark class for {@link TracezDataAggregator}. */ -@State(Scope.Benchmark) -public class TracezDataAggregatorBenchmark { - - private static final String runningSpan = "RUNNING_SPAN"; - private static final String latencySpan = "LATENCY_SPAN"; - private static final String errorSpan = "ERROR_SPAN"; - - private SdkTracerProvider tracerProvider; - private TracezDataAggregator dataAggregator; - - @Param({"1", "10", "1000", "1000000"}) - private int numberOfSpans; - - @Setup(Level.Trial) - public final void setup() { - TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - tracerProvider = SdkTracerProvider.builder().addSpanProcessor(spanProcessor).build(); - dataAggregator = new TracezDataAggregator(spanProcessor); - Tracer tracer = tracerProvider.get("TracezDataAggregatorBenchmark"); - - for (int i = 0; i < numberOfSpans; i++) { - tracer.spanBuilder(runningSpan).startSpan(); - tracer.spanBuilder(latencySpan).startSpan().end(); - Span error = tracer.spanBuilder(errorSpan).startSpan(); - error.setStatus(StatusCode.ERROR); - error.end(); - } - } - - @TearDown(Level.Trial) - public final void tearDown() { - tracerProvider.shutdown(); - } - - /** Get span counts with 1 thread. */ - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getCounts_01Thread(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpanCounts()); - blackhole.consume(dataAggregator.getSpanLatencyCounts()); - blackhole.consume(dataAggregator.getErrorSpanCounts()); - } - - /** Get span counts with 5 threads. */ - @Benchmark - @Threads(value = 5) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getCounts_05Threads(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpanCounts()); - blackhole.consume(dataAggregator.getSpanLatencyCounts()); - blackhole.consume(dataAggregator.getErrorSpanCounts()); - } - - /** Get span counts with 10 threads. */ - @Benchmark - @Threads(value = 10) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getCounts_10Threads(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpanCounts()); - blackhole.consume(dataAggregator.getSpanLatencyCounts()); - blackhole.consume(dataAggregator.getErrorSpanCounts()); - } - - /** Get span counts with 20 threads. */ - @Benchmark - @Threads(value = 20) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getCounts_20Threads(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpanCounts()); - blackhole.consume(dataAggregator.getSpanLatencyCounts()); - blackhole.consume(dataAggregator.getErrorSpanCounts()); - } - - /** Get spans with 1 thread. */ - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getSpans_01Thread(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpans(runningSpan)); - blackhole.consume(dataAggregator.getOkSpans(latencySpan, 0, Long.MAX_VALUE)); - blackhole.consume(dataAggregator.getErrorSpans(errorSpan)); - } - - /** Get spans with 5 threads. */ - @Benchmark - @Threads(value = 5) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getSpans_05Threads(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpans(runningSpan)); - blackhole.consume(dataAggregator.getOkSpans(latencySpan, 0, Long.MAX_VALUE)); - blackhole.consume(dataAggregator.getErrorSpans(errorSpan)); - } - - /** Get spans with 10 threads. */ - @Benchmark - @Threads(value = 10) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getSpans_10Threads(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpans(runningSpan)); - blackhole.consume(dataAggregator.getOkSpans(latencySpan, 0, Long.MAX_VALUE)); - blackhole.consume(dataAggregator.getErrorSpans(errorSpan)); - } - - /** Get spans with 20 threads. */ - @Benchmark - @Threads(value = 20) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void getSpans_20Threads(Blackhole blackhole) { - blackhole.consume(dataAggregator.getRunningSpans(runningSpan)); - blackhole.consume(dataAggregator.getOkSpans(latencySpan, 0, Long.MAX_VALUE)); - blackhole.consume(dataAggregator.getErrorSpans(errorSpan)); - } -} diff --git a/sdk-extensions/zpages/src/jmh/java/io/opentelemetry/sdk/extension/zpages/TracezSpanBucketsBenchmark.java b/sdk-extensions/zpages/src/jmh/java/io/opentelemetry/sdk/extension/zpages/TracezSpanBucketsBenchmark.java deleted file mode 100644 index 4108c3a9e6f..00000000000 --- a/sdk-extensions/zpages/src/jmh/java/io/opentelemetry/sdk/extension/zpages/TracezSpanBucketsBenchmark.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Threads; -import org.openjdk.jmh.annotations.Warmup; - -/** Benchmark class for {@link TracezSpanBuckets}. */ -@State(Scope.Benchmark) -public class TracezSpanBucketsBenchmark { - - private static final String spanName = "BENCHMARK_SPAN"; - private static ReadableSpan readableSpan; - private TracezSpanBuckets bucket; - - @Setup(Level.Trial) - public final void setup() { - bucket = new TracezSpanBuckets(); - Tracer tracer = SdkTracerProvider.builder().build().get("TracezZPageBenchmark"); - Span span = tracer.spanBuilder(spanName).startSpan(); - span.end(); - readableSpan = (ReadableSpan) span; - } - - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void addToBucket_01Thread() { - bucket.addToBucket(readableSpan); - } - - @Benchmark - @Threads(value = 5) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void addToBucket_05Threads() { - bucket.addToBucket(readableSpan); - } - - @Benchmark - @Threads(value = 10) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void addToBucket_10Threads() { - bucket.addToBucket(readableSpan); - } - - @Benchmark - @Threads(value = 20) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void addToBucket_20Threads() { - bucket.addToBucket(readableSpan); - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/IndexZPageHandler.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/IndexZPageHandler.java deleted file mode 100644 index 9469c96ee2a..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/IndexZPageHandler.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.List; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -final class IndexZPageHandler extends ZPageHandler { - private static final String INDEX_URL = "/"; - private static final String INDEX_NAME = "Index"; - private static final String INDEX_DESCRITION = "Index page of zPages"; - private static final Logger logger = Logger.getLogger(IndexZPageHandler.class.getName()); - private final List availableHandlers; - - IndexZPageHandler(List availableHandlers) { - this.availableHandlers = availableHandlers; - } - - @Override - public String getUrlPath() { - return INDEX_URL; - } - - @Override - public String getPageName() { - return INDEX_NAME; - } - - @Override - public String getPageDescription() { - return INDEX_DESCRITION; - } - - private static void emitPageLinkAndInfo(PrintStream out, ZPageHandler handler) { - out.print(""); - out.print("

      " + handler.getPageName() + "

      "); - out.print("
      "); - out.print("

      " + handler.getPageDescription() + "

      "); - } - - @Override - public void emitHtml(Map queryMap, OutputStream outputStream) { - // PrintStream for emitting HTML contents - try (PrintStream out = new PrintStream(outputStream, /* autoFlush= */ false, "UTF-8")) { - out.print(""); - out.print(""); - out.print(""); - out.print(""); - out.print( - ""); - out.print( - ""); - out.print( - ""); - out.print("zPages"); - out.print(""); - out.print(""); - out.print(""); - out.print( - ""); - out.print("

      zPages

      "); - out.print( - "

      OpenTelemetry provides in-process web pages that display collected data from" - + " the process that they are attached to. These are called \"zPages\"." - + " They are useful for in-process diagnostics without having to depend on" - + " any backend to examine traces or metrics.

      "); - - out.print( - "

      zPages can be useful during the development time or " - + "when the process to be inspected is known in production.

      "); - for (ZPageHandler handler : this.availableHandlers) { - emitPageLinkAndInfo(out, handler); - } - out.print(""); - out.print(""); - } catch (Throwable t) { - logger.log(Level.WARNING, "error while generating HTML", t); - } - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/LatencyBoundary.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/LatencyBoundary.java deleted file mode 100644 index 63e9e0442d2..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/LatencyBoundary.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import java.util.concurrent.TimeUnit; - -/** - * A class of boundaries for the latency buckets. The completed spans with a status of {@link - * io.opentelemetry.api.trace.Status#OK} are categorized into one of these buckets om the traceZ - * zPage. - */ -// TODO(anuraaga): Consider renaming the enums that don't follow our standard convention for -// constants. -@SuppressWarnings("MemberName") -enum LatencyBoundary { - /** Stores finished successful requests of duration within the interval [0, 10us). */ - ZERO_MICROSx10(0, TimeUnit.MICROSECONDS.toNanos(10)), - - /** Stores finished successful requests of duration within the interval [10us, 100us). */ - MICROSx10_MICROSx100(TimeUnit.MICROSECONDS.toNanos(10), TimeUnit.MICROSECONDS.toNanos(100)), - - /** Stores finished successful requests of duration within the interval [100us, 1ms). */ - MICROSx100_MILLIx1(TimeUnit.MICROSECONDS.toNanos(100), TimeUnit.MILLISECONDS.toNanos(1)), - - /** Stores finished successful requests of duration within the interval [1ms, 10ms). */ - MILLIx1_MILLIx10(TimeUnit.MILLISECONDS.toNanos(1), TimeUnit.MILLISECONDS.toNanos(10)), - - /** Stores finished successful requests of duration within the interval [10ms, 100ms). */ - MILLIx10_MILLIx100(TimeUnit.MILLISECONDS.toNanos(10), TimeUnit.MILLISECONDS.toNanos(100)), - - /** Stores finished successful requests of duration within the interval [100ms, 1sec). */ - MILLIx100_SECONDx1(TimeUnit.MILLISECONDS.toNanos(100), TimeUnit.SECONDS.toNanos(1)), - - /** Stores finished successful requests of duration within the interval [1sec, 10sec). */ - SECONDx1_SECONDx10(TimeUnit.SECONDS.toNanos(1), TimeUnit.SECONDS.toNanos(10)), - - /** Stores finished successful requests of duration within the interval [10sec, 100sec). */ - SECONDx10_SECONDx100(TimeUnit.SECONDS.toNanos(10), TimeUnit.SECONDS.toNanos(100)), - - /** Stores finished successful requests of duration greater than or equal to 100sec. */ - SECONDx100_MAX(TimeUnit.SECONDS.toNanos(100), Long.MAX_VALUE); - - private final long latencyLowerBound; - private final long latencyUpperBound; - - /** - * Constructs a {@code LatencyBoundaries} with the given boundaries and label. - * - * @param latencyLowerBound the latency lower bound of the bucket. - * @param latencyUpperBound the latency upper bound of the bucket. - */ - LatencyBoundary(long latencyLowerBound, long latencyUpperBound) { - this.latencyLowerBound = latencyLowerBound; - this.latencyUpperBound = latencyUpperBound; - } - - /** - * Returns the latency lower bound of the bucket. - * - * @return the latency lower bound of the bucket. - */ - long getLatencyLowerBound() { - return latencyLowerBound; - } - - /** - * Returns the latency upper bound of the bucket. - * - * @return the latency upper bound of the bucket. - */ - long getLatencyUpperBound() { - return latencyUpperBound; - } - - /** - * Returns the LatencyBoundary that the argument falls into. - * - * @param latencyNanos latency in nanoseconds. - * @return the LatencyBoundary that latencyNanos falls into. - */ - static LatencyBoundary getBoundary(long latencyNanos) { - for (LatencyBoundary bucket : LatencyBoundary.values()) { - if (latencyNanos >= bucket.getLatencyLowerBound() - && latencyNanos < bucket.getLatencyUpperBound()) { - return bucket; - } - } - return ZERO_MICROSx10; - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/SpanBucket.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/SpanBucket.java deleted file mode 100644 index 47a4286c10f..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/SpanBucket.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.sdk.trace.ReadableSpan; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReferenceArray; - -final class SpanBucket { - // A power of 2 means Integer.MAX_VALUE % bucketSize = bucketSize - 1, so the index will always - // loop back to 0. - private static final int LATENCY_BUCKET_SIZE = 16; - private static final int ERROR_BUCKET_SIZE = 8; - - private final AtomicReferenceArray spans; - private final AtomicInteger index; - private final int bucketSize; - - SpanBucket(boolean isLatencyBucket) { - bucketSize = isLatencyBucket ? LATENCY_BUCKET_SIZE : ERROR_BUCKET_SIZE; - spans = new AtomicReferenceArray<>(bucketSize); - index = new AtomicInteger(); - } - - void add(ReadableSpan span) { - spans.set(remainder(index.getAndIncrement(), bucketSize), span); - } - - int size() { - for (int i = bucketSize - 1; i >= 0; i--) { - if (spans.get(i) != null) { - return i + 1; - } - } - return 0; - } - - void addTo(List result) { - for (int i = 0; i < bucketSize; i++) { - ReadableSpan span = spans.get(i); - if (span != null) { - result.add(span); - } else { - break; - } - } - } - - private static int remainder(int dividend, int divisor) { - return (int) (Integer.toUnsignedLong(dividend) % Integer.toUnsignedLong(divisor)); - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TraceConfigzZPageHandler.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TraceConfigzZPageHandler.java deleted file mode 100644 index b86f202f213..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TraceConfigzZPageHandler.java +++ /dev/null @@ -1,428 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.sdk.trace.SpanLimits; -import io.opentelemetry.sdk.trace.SpanLimitsBuilder; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; - -final class TraceConfigzZPageHandler extends ZPageHandler { - private static final String TRACE_CONFIGZ_URL = "/traceconfigz"; - private static final String TRACE_CONFIGZ_NAME = "TraceConfigZ"; - private static final String TRACE_CONFIGZ_DESCRIPTION = - "TraceConfigZ displays information about the current active tracing configuration" - + " and allows users to change it"; - private static final String QUERY_STRING_ACTION = "action"; - private static final String QUERY_STRING_ACTION_CHANGE = "change"; - private static final String QUERY_STRING_ACTION_DEFAULT = "default"; - private static final String QUERY_STRING_SAMPLING_PROBABILITY = "samplingprobability"; - private static final String QUERY_STRING_MAX_NUM_OF_ATTRIBUTES = "maxnumofattributes"; - private static final String QUERY_STRING_MAX_NUM_OF_EVENTS = "maxnumofevents"; - private static final String QUERY_STRING_MAX_NUM_OF_LINKS = "maxnumoflinks"; - private static final String QUERY_STRING_MAX_NUM_OF_ATTRIBUTES_PER_EVENT = - "maxnumofattributesperevent"; - private static final String QUERY_STRING_MAX_NUM_OF_ATTRIBUTES_PER_LINK = - "maxnumofattributesperlink"; - // Background color used for zebra striping rows in table - private static final String ZEBRA_STRIPE_COLOR = "#e6e6e6"; - private static final Logger logger = Logger.getLogger(TraceConfigzZPageHandler.class.getName()); - private final TracezTraceConfigSupplier configSupplier; - - TraceConfigzZPageHandler(TracezTraceConfigSupplier configSupplier) { - this.configSupplier = configSupplier; - } - - @Override - public String getUrlPath() { - return TRACE_CONFIGZ_URL; - } - - @Override - public String getPageName() { - return TRACE_CONFIGZ_NAME; - } - - @Override - public String getPageDescription() { - return TRACE_CONFIGZ_DESCRIPTION; - } - - /** - * Emits CSS styles to the {@link PrintStream} {@code out}. Content emitted by this function - * should be enclosed by tag. - * - * @param out the {@link PrintStream} {@code out}. - */ - private static void emitHtmlStyle(PrintStream out) { - out.print(""); - } - - /** - * Emits a row of the change tracing parameter table to the {@link PrintStream} {@code out}. Each - * row corresponds to one tracing parameter. - * - * @param out the {@link PrintStream} {@code out}. - * @param rowName the display name of the corresponding tracing parameter. - * @param paramName the name of the corresponding tracing parameter (this will be used to - * construct the query parameter in URL). - * @param inputPlaceHolder placeholder for the HTML element. - * @param paramDefaultValue the default value of the corresponding tracing parameter. - * @param zebraStripeColor hex code of the color used for zebra striping rows. - * @param zebraStripe boolean indicating if the row is zebra striped. - */ - private static void emitChangeTableRow( - PrintStream out, - String rowName, - String paramName, - String inputPlaceHolder, - String paramDefaultValue, - String zebraStripeColor, - boolean zebraStripe) { - if (zebraStripe) { - out.print(""); - } else { - out.print(""); - } - out.print("Update " + rowName + ""); - out.print( - ""); - out.print("(" + paramDefaultValue + ")"); - out.print(""); - } - - /** - * Emits the change tracing parameter table to the {@link PrintStream} {@code out}. - * - * @param out the {@link PrintStream} {@code out}. - */ - private static void emitChangeTable(PrintStream out) { - out.print(""); - out.print(""); - out.print( - ""); - out.print(""); - emitChangeTableRow( - /* out= */ out, - /* rowName= */ "SamplingProbability to", - /* paramName= */ QUERY_STRING_SAMPLING_PROBABILITY, - /* inputPlaceHolder= */ "[0.0, 1.0]", - /* paramDefaultValue= */ "1.0", - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ false); - emitChangeTableRow( - /* out= */ out, - /* rowName= */ "MaxNumberOfAttributes to", - /* paramName= */ QUERY_STRING_MAX_NUM_OF_ATTRIBUTES, - /* inputPlaceHolder= */ "", - /* paramDefaultValue= */ Integer.toString( - SpanLimits.getDefault().getMaxNumberOfAttributes()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ true); - emitChangeTableRow( - /* out= */ out, - /* rowName= */ "MaxNumberOfEvents to", - /* paramName= */ QUERY_STRING_MAX_NUM_OF_EVENTS, - /* inputPlaceHolder= */ "", - /* paramDefaultValue= */ Integer.toString(SpanLimits.getDefault().getMaxNumberOfEvents()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ false); - emitChangeTableRow( - /* out= */ out, - /* rowName= */ "MaxNumberOfLinks to", - /* paramName= */ QUERY_STRING_MAX_NUM_OF_LINKS, - /* inputPlaceHolder= */ "", - /* paramDefaultValue= */ Integer.toString(SpanLimits.getDefault().getMaxNumberOfLinks()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ true); - emitChangeTableRow( - /* out= */ out, - /* rowName= */ "MaxNumberOfAttributesPerEvent to", - /* paramName= */ QUERY_STRING_MAX_NUM_OF_ATTRIBUTES_PER_EVENT, - /* inputPlaceHolder= */ "", - /* paramDefaultValue= */ Integer.toString( - SpanLimits.getDefault().getMaxNumberOfAttributesPerEvent()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ false); - emitChangeTableRow( - /* out= */ out, - /* rowName= */ "MaxNumberOfAttributesPerLink to", - /* paramName= */ QUERY_STRING_MAX_NUM_OF_ATTRIBUTES_PER_LINK, - /* inputPlaceHolder= */ "", - /* paramDefaultValue= */ Integer.toString( - SpanLimits.getDefault().getMaxNumberOfAttributesPerLink()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ true); - out.print("
      " - + "Update active TraceConfigDefault
      "); - } - - /** - * Emits a row of the active tracing parameter table to the {@link PrintStream} {@code out}. Each - * row corresponds to one tracing parameter. - * - * @param out the {@link PrintStream} {@code out}. - * @param paramName the name of the corresponding tracing parameter. - * @param paramValue the value of the corresponding tracing parameter. - * @param zebraStripeColor hex code of the color used for zebra striping rows. - * @param zebraStripe boolean indicating if the row is zebra striped. - */ - private static void emitActiveTableRow( - PrintStream out, - String paramName, - String paramValue, - String zebraStripeColor, - boolean zebraStripe) { - if (zebraStripe) { - out.print(""); - } else { - out.print(""); - } - out.print("" + paramName + ""); - out.print("" + paramValue + ""); - out.print(""); - } - - /** - * Emits the active tracing parameters table to the {@link PrintStream} {@code out}. - * - * @param out the {@link PrintStream} {@code out}. - */ - private void emitActiveTable(PrintStream out) { - out.print(""); - out.print(""); - out.print(""); - out.print(""); - out.print(""); - emitActiveTableRow( - /* out= */ out, - /* paramName= */ "Sampler", - /* paramValue=*/ configSupplier.getSampler().getDescription(), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ false); - emitActiveTableRow( - /* out= */ out, - /* paramName= */ "MaxNumOfAttributes", - /* paramValue=*/ Integer.toString(configSupplier.get().getMaxNumberOfAttributes()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ true); - emitActiveTableRow( - /* out= */ out, - /* paramName= */ "MaxNumOfEvents", - /* paramValue=*/ Integer.toString(configSupplier.get().getMaxNumberOfEvents()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ false); - emitActiveTableRow( - /* out= */ out, - /* paramName= */ "MaxNumOfLinks", - /* paramValue=*/ Integer.toString(configSupplier.get().getMaxNumberOfLinks()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ true); - emitActiveTableRow( - /* out= */ out, - /* paramName= */ "MaxNumOfAttributesPerEvent", - /* paramValue=*/ Integer.toString(configSupplier.get().getMaxNumberOfAttributesPerEvent()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe= */ false); - emitActiveTableRow( - /* out= */ out, - /* paramName= */ "MaxNumOfAttributesPerLink", - /* paramValue=*/ Integer.toString(configSupplier.get().getMaxNumberOfAttributesPerLink()), - /* zebraStripeColor= */ ZEBRA_STRIPE_COLOR, - /* zebraStripe=*/ true); - out.print("
      NameValue
      "); - } - - /** - * Emits HTML body content to the {@link PrintStream} {@code out}. Content emitted by this - * function should be enclosed by tag. - * - * @param out the {@link PrintStream} {@code out}. - */ - private void emitHtmlBody(PrintStream out) { - out.print( - ""); - out.print("

      Trace Configuration

      "); - out.print("
      "); - out.print( - ""); - emitChangeTable(out); - // Button for submit - out.print(""); - out.print("
      "); - // Button for restore default - out.print("
      "); - out.print( - ""); - out.print(""); - out.print("
      "); - out.print("

      Active Tracing Parameters

      "); - emitActiveTable(out); - } - - @Override - public void emitHtml(Map queryMap, OutputStream outputStream) { - // PrintStream for emitting HTML contents - try (PrintStream out = new PrintStream(outputStream, /* autoFlush= */ false, "UTF-8")) { - out.print(""); - out.print(""); - out.print(""); - out.print(""); - out.print( - ""); - out.print( - ""); - out.print( - ""); - out.print("" + TRACE_CONFIGZ_NAME + ""); - emitHtmlStyle(out); - out.print(""); - out.print(""); - try { - emitHtmlBody(out); - } catch (Throwable t) { - out.print("Error while generating HTML: " + t.toString()); - logger.log(Level.WARNING, "error while generating HTML", t); - } - out.print(""); - out.print(""); - } catch (Throwable t) { - logger.log(Level.WARNING, "error while generating HTML", t); - } - } - - @Override - public boolean processRequest( - String requestMethod, Map queryMap, OutputStream outputStream) { - if (requestMethod.equalsIgnoreCase("POST")) { - try { - applyTraceConfig(queryMap); - } catch (Throwable t) { - try (PrintStream out = new PrintStream(outputStream, /* autoFlush= */ false, "UTF-8")) { - out.print(""); - out.print(""); - out.print(""); - out.print(""); - out.print( - ""); - out.print( - ""); - out.print( - ""); - out.print("" + TRACE_CONFIGZ_NAME + ""); - out.print(""); - out.print(""); - out.print("Error while applying trace config changes: " + t.toString()); - out.print(""); - out.print(""); - logger.log(Level.WARNING, "error while applying trace config changes", t); - } catch (Throwable e) { - logger.log(Level.WARNING, "error while applying trace config changes", e); - return true; - } - return true; - } - } - return false; - } - - /** - * Apply updated trace configuration through the tracerProvider based on query parameters. - * - * @param queryMap the map containing URL query parameters. - * @throws NumberFormatException if one of the {@code double}/{@code integer} valued query string - * does not contain a parsable {@code double}/{@code integer}. - */ - private void applyTraceConfig(Map queryMap) { - String action = queryMap.get(QUERY_STRING_ACTION); - if (action == null) { - return; - } - if (action.equals(QUERY_STRING_ACTION_CHANGE)) { - SpanLimitsBuilder newConfigBuilder = configSupplier.get().toBuilder(); - String samplingProbabilityStr = queryMap.get(QUERY_STRING_SAMPLING_PROBABILITY); - if (samplingProbabilityStr != null) { - try { - double samplingProbability = Double.parseDouble(samplingProbabilityStr); - configSupplier.setSampler(Sampler.traceIdRatioBased(samplingProbability)); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("SamplingProbability must be of the type double", e); - } - } - String maxNumOfAttributesStr = queryMap.get(QUERY_STRING_MAX_NUM_OF_ATTRIBUTES); - if (maxNumOfAttributesStr != null) { - try { - int maxNumOfAttributes = Integer.parseInt(maxNumOfAttributesStr); - newConfigBuilder.setMaxNumberOfAttributes(maxNumOfAttributes); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("MaxNumOfAttributes must be of the type integer", e); - } - } - String maxNumOfEventsStr = queryMap.get(QUERY_STRING_MAX_NUM_OF_EVENTS); - if (maxNumOfEventsStr != null) { - try { - int maxNumOfEvents = Integer.parseInt(maxNumOfEventsStr); - newConfigBuilder.setMaxNumberOfEvents(maxNumOfEvents); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("MaxNumOfEvents must be of the type integer", e); - } - } - String maxNumOfLinksStr = queryMap.get(QUERY_STRING_MAX_NUM_OF_LINKS); - if (maxNumOfLinksStr != null) { - try { - int maxNumOfLinks = Integer.parseInt(maxNumOfLinksStr); - newConfigBuilder.setMaxNumberOfLinks(maxNumOfLinks); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("MaxNumOfLinks must be of the type integer", e); - } - } - String maxNumOfAttributesPerEventStr = - queryMap.get(QUERY_STRING_MAX_NUM_OF_ATTRIBUTES_PER_EVENT); - if (maxNumOfAttributesPerEventStr != null) { - try { - int maxNumOfAttributesPerEvent = Integer.parseInt(maxNumOfAttributesPerEventStr); - newConfigBuilder.setMaxNumberOfAttributesPerEvent(maxNumOfAttributesPerEvent); - } catch (NumberFormatException e) { - throw new IllegalArgumentException( - "MaxNumOfAttributesPerEvent must be of the type integer", e); - } - } - String maxNumOfAttributesPerLinkStr = - queryMap.get(QUERY_STRING_MAX_NUM_OF_ATTRIBUTES_PER_LINK); - if (maxNumOfAttributesPerLinkStr != null) { - try { - int maxNumOfAttributesPerLink = Integer.parseInt(maxNumOfAttributesPerLinkStr); - newConfigBuilder.setMaxNumberOfAttributesPerLink(maxNumOfAttributesPerLink); - } catch (NumberFormatException e) { - throw new IllegalArgumentException( - "MaxNumOfAttributesPerLink must be of the type integer", e); - } - } - configSupplier.setActiveTraceConfig(newConfigBuilder.build()); - } else if (action.equals(QUERY_STRING_ACTION_DEFAULT)) { - SpanLimits defaultConfig = SpanLimits.builder().build(); - configSupplier.setActiveTraceConfig(defaultConfig); - } - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregator.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregator.java deleted file mode 100644 index 4412ff03765..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregator.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import javax.annotation.concurrent.ThreadSafe; - -/** - * A data aggregator for the traceZ zPage. - * - *

      The traceZ data aggregator compiles information about the running spans, span latencies, and - * error spans for the frontend of the zPage. - */ -@ThreadSafe -final class TracezDataAggregator { - private final TracezSpanProcessor spanProcessor; - - /** - * Constructor for {@link TracezDataAggregator}. - * - * @param spanProcessor collects span data. - */ - TracezDataAggregator(TracezSpanProcessor spanProcessor) { - this.spanProcessor = spanProcessor; - } - - /** - * Returns a Set of running and completed span names for {@link TracezDataAggregator}. - * - * @return a Set of {@link String}. - */ - Set getSpanNames() { - Set spanNames = new TreeSet<>(); - Collection allRunningSpans = spanProcessor.getRunningSpans(); - for (ReadableSpan span : allRunningSpans) { - spanNames.add(span.getName()); - } - spanNames.addAll(spanProcessor.getCompletedSpanCache().keySet()); - return spanNames; - } - - /** - * Returns a Map of the running span counts for {@link TracezDataAggregator}. - * - * @return a Map of span counts for each span name. - */ - Map getRunningSpanCounts() { - Collection allRunningSpans = spanProcessor.getRunningSpans(); - Map numSpansPerName = new HashMap<>(); - for (ReadableSpan span : allRunningSpans) { - Integer prevValue = numSpansPerName.get(span.getName()); - numSpansPerName.put(span.getName(), prevValue != null ? prevValue + 1 : 1); - } - return numSpansPerName; - } - - /** - * Returns a List of all running spans with a given span name for {@link TracezDataAggregator}. - * - * @param spanName name to filter returned spans. - * @return a List of {@link SpanData}. - */ - List getRunningSpans(String spanName) { - Collection allRunningSpans = spanProcessor.getRunningSpans(); - List filteredSpans = new ArrayList<>(); - for (ReadableSpan span : allRunningSpans) { - if (span.getName().equals(spanName)) { - filteredSpans.add(span.toSpanData()); - } - } - return filteredSpans; - } - - /** - * Returns a Map of span names to counts for all {@link StatusCode#OK} spans in {@link - * TracezDataAggregator}. - * - * @return a Map of span names to counts, where the counts are further indexed by the latency - * boundaries. - */ - Map> getSpanLatencyCounts() { - Map completedSpanCache = spanProcessor.getCompletedSpanCache(); - Map> numSpansPerName = new HashMap<>(); - for (Map.Entry cacheEntry : completedSpanCache.entrySet()) { - numSpansPerName.put( - cacheEntry.getKey(), cacheEntry.getValue().getLatencyBoundaryToCountMap()); - } - return numSpansPerName; - } - - /** - * Returns a List of all {@link StatusCode#OK} spans with a given span name between [lowerBound, - * upperBound) for {@link TracezDataAggregator}. - * - * @param spanName name to filter returned spans. - * @param lowerBound latency lower bound (inclusive) - * @param upperBound latency upper bound (exclusive) - * @return a List of {@link SpanData}. - */ - List getOkSpans(String spanName, long lowerBound, long upperBound) { - Map completedSpanCache = spanProcessor.getCompletedSpanCache(); - TracezSpanBuckets buckets = completedSpanCache.get(spanName); - if (buckets == null) { - return Collections.emptyList(); - } - Collection allOkSpans = buckets.getOkSpans(); - List filteredSpans = new ArrayList<>(); - for (ReadableSpan span : allOkSpans) { - if (span.getLatencyNanos() >= lowerBound && span.getLatencyNanos() < upperBound) { - filteredSpans.add(span.toSpanData()); - } - } - return Collections.unmodifiableList(filteredSpans); - } - - /** - * Returns a Map of error span counts for {@link TracezDataAggregator}. - * - * @return a Map of error span counts for each span name. - */ - Map getErrorSpanCounts() { - Map completedSpanCache = spanProcessor.getCompletedSpanCache(); - Map numErrorsPerName = new HashMap<>(); - for (Map.Entry cacheEntry : completedSpanCache.entrySet()) { - numErrorsPerName.put(cacheEntry.getKey(), cacheEntry.getValue().getErrorSpans().size()); - } - return numErrorsPerName; - } - - /** - * Returns a List of error spans with a given span name for {@link TracezDataAggregator}. - * - * @param spanName name to filter returned spans. - * @return a List of {@link SpanData}. - */ - List getErrorSpans(String spanName) { - Map completedSpanCache = spanProcessor.getCompletedSpanCache(); - TracezSpanBuckets buckets = completedSpanCache.get(spanName); - if (buckets == null) { - return Collections.emptyList(); - } - Collection allErrorSpans = buckets.getErrorSpans(); - List errorSpans = new ArrayList<>(); - for (ReadableSpan span : allErrorSpans) { - errorSpans.add(span.toSpanData()); - } - return Collections.unmodifiableList(errorSpans); - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezSpanBuckets.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezSpanBuckets.java deleted file mode 100644 index 62ba3f03c41..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezSpanBuckets.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; - -final class TracezSpanBuckets { - private final LatencyBuckets latencyBuckets = new LatencyBuckets(); - private final SpanBucket errors = new SpanBucket(/* isLatencyBucket= */ false); - - void addToBucket(ReadableSpan span) { - StatusData status = span.toSpanData().getStatus(); - if (status.getStatusCode() != StatusCode.ERROR) { - latencyBuckets.get(LatencyBoundary.getBoundary(span.getLatencyNanos())).add(span); - return; - } - errors.add(span); - } - - Map getLatencyBoundaryToCountMap() { - Map latencyCounts = new EnumMap<>(LatencyBoundary.class); - for (LatencyBoundary bucket : LatencyBoundary.values()) { - latencyCounts.put(bucket, latencyBuckets.get(bucket).size()); - } - return latencyCounts; - } - - List getOkSpans() { - List okSpans = new ArrayList<>(); - latencyBuckets.addTo(okSpans); - return okSpans; - } - - List getErrorSpans() { - List errorSpans = new ArrayList<>(); - errors.addTo(errorSpans); - return errorSpans; - } - - List getSpans() { - List spans = new ArrayList<>(); - spans.addAll(getOkSpans()); - spans.addAll(getErrorSpans()); - return spans; - } - - private static class LatencyBuckets { - final SpanBucket zeroToTenMicros = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket tenMicrosToHundredMicros = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket hundredMicrosToOneMilli = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket oneMilliToTenMillis = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket tenMillisToHundredMillis = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket hundredMillisToOneSecond = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket oneSecondToTenSeconds = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket tenSecondsToHundredSeconds = new SpanBucket(/* isLatencyBucket= */ true); - final SpanBucket hundredSecondsToMax = new SpanBucket(/* isLatencyBucket= */ true); - - void addTo(List spans) { - zeroToTenMicros.addTo(spans); - tenMicrosToHundredMicros.addTo(spans); - hundredMicrosToOneMilli.addTo(spans); - oneMilliToTenMillis.addTo(spans); - tenMillisToHundredMillis.addTo(spans); - hundredMillisToOneSecond.addTo(spans); - oneSecondToTenSeconds.addTo(spans); - tenSecondsToHundredSeconds.addTo(spans); - hundredSecondsToMax.addTo(spans); - } - - SpanBucket get(LatencyBoundary boundary) { - switch (boundary) { - case ZERO_MICROSx10: - return zeroToTenMicros; - case MICROSx10_MICROSx100: - return tenMicrosToHundredMicros; - case MICROSx100_MILLIx1: - return hundredMicrosToOneMilli; - case MILLIx1_MILLIx10: - return oneMilliToTenMillis; - case MILLIx10_MILLIx100: - return tenMillisToHundredMillis; - case MILLIx100_SECONDx1: - return hundredMillisToOneSecond; - case SECONDx1_SECONDx10: - return oneSecondToTenSeconds; - case SECONDx10_SECONDx100: - return tenSecondsToHundredSeconds; - case SECONDx100_MAX: - return hundredSecondsToMax; - } - // Can't happen with aligned versions, just pick an arbitrary one to compile. - return hundredSecondsToMax; - } - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezSpanProcessor.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezSpanProcessor.java deleted file mode 100644 index 6efebb9a7da..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezSpanProcessor.java +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.trace.ReadWriteSpan; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.SpanProcessor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import javax.annotation.concurrent.ThreadSafe; - -/** A {@link SpanProcessor} implementation for the traceZ zPage. */ -@ThreadSafe -final class TracezSpanProcessor implements SpanProcessor { - private final ConcurrentMap runningSpanCache; - private final ConcurrentMap completedSpanCache; - private final boolean sampled; - - /** - * Constructor for {@link TracezSpanProcessor}. - * - * @param sampled report only sampled spans. - */ - TracezSpanProcessor(boolean sampled) { - runningSpanCache = new ConcurrentHashMap<>(); - completedSpanCache = new ConcurrentHashMap<>(); - this.sampled = sampled; - } - - @Override - public void onStart(Context parentContext, ReadWriteSpan span) { - runningSpanCache.put(span.getSpanContext().getSpanId(), span); - } - - @Override - public boolean isStartRequired() { - return true; - } - - @Override - public void onEnd(ReadableSpan span) { - runningSpanCache.remove(span.getSpanContext().getSpanId()); - if (!sampled || span.getSpanContext().isSampled()) { - completedSpanCache - .computeIfAbsent(span.getName(), unused -> new TracezSpanBuckets()) - .addToBucket(span); - } - } - - @Override - public boolean isEndRequired() { - return true; - } - - @Override - public CompletableResultCode shutdown() { - // Do nothing. - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode forceFlush() { - // Do nothing. - return CompletableResultCode.ofSuccess(); - } - - /** - * Returns a Collection of all running spans for {@link TracezSpanProcessor}. - * - * @return a Collection of {@link ReadableSpan}. - */ - Collection getRunningSpans() { - return runningSpanCache.values(); - } - - /** - * Returns a Collection of all completed spans for {@link TracezSpanProcessor}. - * - * @return a Collection of {@link ReadableSpan}. - */ - Collection getCompletedSpans() { - Collection completedSpans = new ArrayList<>(); - for (TracezSpanBuckets buckets : completedSpanCache.values()) { - completedSpans.addAll(buckets.getSpans()); - } - return completedSpans; - } - - /** - * Returns the completed span cache for {@link TracezSpanProcessor}. - * - * @return a Map of String to {@link TracezSpanBuckets}. - */ - Map getCompletedSpanCache() { - return completedSpanCache; - } - - /** - * Returns a new Builder for {@link TracezSpanProcessor}. - * - * @return a new {@link TracezSpanProcessor}. - */ - public static Builder builder() { - return new Builder(); - } - - /** Builder class for {@link TracezSpanProcessor}. */ - public static final class Builder { - - private static final boolean DEFAULT_EXPORT_ONLY_SAMPLED = true; - private boolean sampled = DEFAULT_EXPORT_ONLY_SAMPLED; - - private Builder() {} - - /** - * Sets whether only sampled spans should be exported. - * - *

      Default value is {@code true}. - * - * @see Builder#DEFAULT_EXPORT_ONLY_SAMPLED - * @param sampled report only sampled spans. - * @return this. - */ - public Builder setExportOnlySampled(boolean sampled) { - this.sampled = sampled; - return this; - } - - /** - * Returns a new {@link TracezSpanProcessor}. - * - * @return a new {@link TracezSpanProcessor}. - */ - public TracezSpanProcessor build() { - return new TracezSpanProcessor(sampled); - } - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezTraceConfigSupplier.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezTraceConfigSupplier.java deleted file mode 100644 index c83cb5207a5..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezTraceConfigSupplier.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanKind; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.trace.SpanLimits; -import io.opentelemetry.sdk.trace.data.LinkData; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import io.opentelemetry.sdk.trace.samplers.SamplingResult; -import java.util.List; -import java.util.function.Supplier; - -final class TracezTraceConfigSupplier implements Supplier, Sampler { - - private volatile Sampler sampler; - private volatile SpanLimits activeSpanLimits; - - TracezTraceConfigSupplier() { - sampler = Sampler.traceIdRatioBased(1.0); - activeSpanLimits = SpanLimits.getDefault(); - } - - @Override - public SpanLimits get() { - return activeSpanLimits; - } - - Sampler getSampler() { - return sampler; - } - - void setSampler(Sampler sampler) { - this.sampler = sampler; - } - - void setActiveTraceConfig(SpanLimits spanLimits) { - activeSpanLimits = spanLimits; - } - - @Override - public SamplingResult shouldSample( - Context parentContext, - String traceId, - String name, - SpanKind spanKind, - Attributes attributes, - List parentLinks) { - return sampler.shouldSample(parentContext, traceId, name, spanKind, attributes, parentLinks); - } - - @Override - public String getDescription() { - return sampler.getDescription(); - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezZPageHandler.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezZPageHandler.java deleted file mode 100644 index bdb1c5f6c9c..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/TracezZPageHandler.java +++ /dev/null @@ -1,602 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.sdk.trace.data.EventData; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.charset.StandardCharsets; -import java.util.Calendar; -import java.util.Collection; -import java.util.Comparator; -import java.util.Formatter; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.function.BiConsumer; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Collectors; -import javax.annotation.Nullable; - -final class TracezZPageHandler extends ZPageHandler { - private enum SampleType { - RUNNING(0), - LATENCY(1), - ERROR(2), - UNKNOWN(-1); - - private final int value; - - SampleType(int value) { - this.value = value; - } - - static SampleType fromString(String str) { - int value = Integer.parseInt(str); - switch (value) { - case 0: - return RUNNING; - case 1: - return LATENCY; - case 2: - return ERROR; - default: - return UNKNOWN; - } - } - - int getValue() { - return value; - } - } - - private static final String TRACEZ_URL = "/tracez"; - private static final String TRACEZ_NAME = "TraceZ"; - private static final String TRACEZ_DESCRIPTION = - "TraceZ displays information about all the running spans" - + " and all the sampled spans based on latency and errors"; - // Background color used for zebra striping rows of summary table - private static final String ZEBRA_STRIPE_COLOR = "#e6e6e6"; - // Color for sampled traceIds - private static final String SAMPLED_TRACE_ID_COLOR = "#c1272d"; - // Color for not sampled traceIds - private static final String NOT_SAMPLED_TRACE_ID_COLOR = "black"; - // Query string parameter name for span name - private static final String PARAM_SPAN_NAME = "zspanname"; - // Query string parameter name for type to display - // * 0 = running, 1 = latency, 2 = error - private static final String PARAM_SAMPLE_TYPE = "ztype"; - // Query string parameter name for sub-type: - // * for latency based sampled spans [0, 8] corresponds to each latency boundaries - // where 0 corresponds to the first boundary - // * for error based sampled spans [0, 15], 0 means all, otherwise the error code - private static final String PARAM_SAMPLE_SUB_TYPE = "zsubtype"; - // Map from LatencyBoundary to human readable string on the UI - private static final Map LATENCY_BOUNDARIES_STRING_MAP = - buildLatencyBoundaryStringMap(); - private static final Logger logger = Logger.getLogger(TracezZPageHandler.class.getName()); - @Nullable private final TracezDataAggregator dataAggregator; - - /** Constructs a new {@code TracezZPageHandler}. */ - TracezZPageHandler(@Nullable TracezDataAggregator dataAggregator) { - this.dataAggregator = dataAggregator; - } - - @Override - public String getUrlPath() { - return TRACEZ_URL; - } - - @Override - public String getPageName() { - return TRACEZ_NAME; - } - - @Override - public String getPageDescription() { - return TRACEZ_DESCRIPTION; - } - - /** - * Emits CSS Styles to the {@link PrintStream} {@code out}. Content emitted by this function - * should be enclosed by tag. - * - * @param out the {@link PrintStream} {@code out}. - */ - private static void emitHtmlStyle(PrintStream out) { - out.print(""); - } - - /** - * Emits the header of the summary table to the {@link PrintStream} {@code out}. - * - * @param out the {@link PrintStream} {@code out}. - */ - private static void emitSummaryTableHeader(PrintStream out) { - // First row - out.print(""); - out.print("Span Name"); - out.print("Running"); - out.print("Latency Samples"); - out.print("Error Samples"); - out.print(""); - - // Second row - out.print(""); - out.print(""); - out.print(""); - for (LatencyBoundary latencyBoundary : LatencyBoundary.values()) { - out.print( - "[" - + LATENCY_BOUNDARIES_STRING_MAP.get(latencyBoundary) - + "]"); - } - out.print(""); - out.print(""); - } - - /** - * Emits a single cell of the summary table depends on the parameters passed in, to the {@link - * PrintStream} {@code out}. - * - * @param out the {@link PrintStream} {@code out}. - * @param spanName the name of the corresponding span. - * @param numOfSamples the number of samples of the corresponding span. - * @param type the type of the corresponding span (running, latency, error). - * @param subtype the sub-type of the corresponding span (latency [0, 8], error [0, 15]). - */ - private static void emitSummaryTableCell( - PrintStream out, String spanName, int numOfSamples, SampleType type, int subtype) { - // If numOfSamples is greater than 0, emit a link to see detailed span information - // If numOfSamples is smaller than 0, print the text "N/A", otherwise print the text "0" - if (numOfSamples > 0) { - out.print("" + numOfSamples + ""); - } else if (numOfSamples < 0) { - out.print("N/A"); - } else { - out.print("0"); - } - } - - /** - * Emits the summary table of running spans and sampled spans to the {@link PrintStream} {@code - * out}. - * - * @param out the {@link PrintStream} {@code out}. - */ - private void emitSummaryTable(PrintStream out) { - if (dataAggregator == null) { - return; - } - out.print(""); - emitSummaryTableHeader(out); - - Set spanNames = dataAggregator.getSpanNames(); - boolean zebraStripe = false; - - Map runningSpanCounts = dataAggregator.getRunningSpanCounts(); - Map> latencySpanCounts = - dataAggregator.getSpanLatencyCounts(); - Map errorSpanCounts = dataAggregator.getErrorSpanCounts(); - for (String spanName : spanNames) { - if (zebraStripe) { - out.print(""); - } else { - out.print(""); - } - zebraStripe = !zebraStripe; - out.print(""); - - // Running spans column - int numOfRunningSpans = - runningSpanCounts.containsKey(spanName) ? runningSpanCounts.get(spanName) : 0; - // subtype is ignored for running spans - emitSummaryTableCell(out, spanName, numOfRunningSpans, SampleType.RUNNING, 0); - - // Latency based sampled spans column - int subtype = 0; - for (LatencyBoundary latencyBoundary : LatencyBoundary.values()) { - int numOfLatencySamples = - latencySpanCounts.containsKey(spanName) - && latencySpanCounts.get(spanName).containsKey(latencyBoundary) - ? latencySpanCounts.get(spanName).get(latencyBoundary) - : 0; - emitSummaryTableCell(out, spanName, numOfLatencySamples, SampleType.LATENCY, subtype); - subtype += 1; - } - - // Error based sampled spans column - int numOfErrorSamples = - errorSpanCounts.containsKey(spanName) ? errorSpanCounts.get(spanName) : 0; - // subtype 0 means all errors - emitSummaryTableCell(out, spanName, numOfErrorSamples, SampleType.ERROR, 0); - } - out.print("
      " + escapeHtml(spanName) + "
      "); - } - - private static void emitSpanNameAndCount( - PrintStream out, String spanName, int count, SampleType type) { - out.print("

      Span Name: " + escapeHtml(spanName) + "

      "); - String typeString = - type == SampleType.RUNNING - ? "running" - : type == SampleType.LATENCY ? "latency samples" : "error samples"; - out.print("

      Number of " + typeString + ": " + count + "

      "); - } - - private static void emitSpanDetails( - PrintStream out, Formatter formatter, Collection spans) { - out.print(""); - out.print(""); - out.print( - ""); - out.print( - ""); - out.print(""); - out.print(""); - boolean zebraStripe = false; - for (SpanData span : spans) { - zebraStripe = emitSingleSpan(out, formatter, span, zebraStripe); - } - out.print("
      When
      " - + "
      Elapsed(s)
      "); - } - - private static boolean emitSingleSpan( - PrintStream out, Formatter formatter, SpanData span, boolean zebraStripe) { - Calendar calendar = Calendar.getInstance(); - calendar.setTimeInMillis(TimeUnit.NANOSECONDS.toMillis(span.getStartEpochNanos())); - long microsField = TimeUnit.NANOSECONDS.toMicros(span.getStartEpochNanos()); - String elapsedSecondsStr = - span.hasEnded() - ? String.format("%.6f", (span.getEndEpochNanos() - span.getStartEpochNanos()) * 1.0e-9) - : ""; - formatter.format( - "", zebraStripe ? ZEBRA_STRIPE_COLOR : "#fff"); - formatter.format( - "
      "
      -            + "%04d/%02d/%02d-%02d:%02d:%02d.%06d
      ", - calendar.get(Calendar.YEAR), - calendar.get(Calendar.MONTH) + 1, - calendar.get(Calendar.DAY_OF_MONTH), - calendar.get(Calendar.HOUR_OF_DAY), - calendar.get(Calendar.MINUTE), - calendar.get(Calendar.SECOND), - microsField); - formatter.format( - "
      %s
      ", - elapsedSecondsStr); - formatter.format( - "
      "
      -            + "TraceId: %s "
      -            + " | SpanId: %s | ParentSpanId: %s
      ", - span.getSpanContext().isSampled() ? SAMPLED_TRACE_ID_COLOR : NOT_SAMPLED_TRACE_ID_COLOR, - span.getTraceId(), - span.getSpanId(), - span.getParentSpanId()); - out.print(""); - zebraStripe = !zebraStripe; - - int lastEntryDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); - - long lastEpochNanos = span.getStartEpochNanos(); - List timedEvents = - span.getEvents().stream() - .sorted(Comparator.comparingLong(EventData::getEpochNanos)) - .collect(Collectors.toList()); - for (EventData event : timedEvents) { - calendar.setTimeInMillis(TimeUnit.NANOSECONDS.toMillis(event.getEpochNanos())); - formatter.format( - "", zebraStripe ? ZEBRA_STRIPE_COLOR : "#fff"); - emitSingleEvent(out, formatter, event, calendar, lastEntryDayOfYear, lastEpochNanos); - out.print(""); - if (calendar.get(Calendar.DAY_OF_YEAR) != lastEntryDayOfYear) { - lastEntryDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); - } - lastEpochNanos = event.getEpochNanos(); - zebraStripe = !zebraStripe; - } - formatter.format( - "" - + "
      ",
      -        zebraStripe ? ZEBRA_STRIPE_COLOR : "#fff");
      -    StatusData status = span.getStatus();
      -    if (status != null) {
      -      formatter.format("%s | ", escapeHtml(status.toString()));
      -    }
      -    formatter.format("%s
      ", escapeHtml(renderAttributes(span.getAttributes()))); - zebraStripe = !zebraStripe; - return zebraStripe; - } - - private static void emitSingleEvent( - PrintStream out, - Formatter formatter, - EventData event, - Calendar calendar, - int lastEntryDayOfYear, - long lastEpochNanos) { - if (calendar.get(Calendar.DAY_OF_YEAR) == lastEntryDayOfYear) { - out.print("
      ");
      -    } else {
      -      formatter.format(
      -          "
      %04d/%02d/%02d-",
      -          calendar.get(Calendar.YEAR),
      -          calendar.get(Calendar.MONTH) + 1,
      -          calendar.get(Calendar.DAY_OF_MONTH));
      -    }
      -
      -    // Special printing so that durations smaller than one second
      -    // are left padded with blanks instead of '0' characters.
      -    // E.g.,
      -    //        Number                  Printout
      -    //        ---------------------------------
      -    //        0.000534                  .   534
      -    //        1.000534                 1.000534
      -    long deltaMicros = TimeUnit.NANOSECONDS.toMicros(event.getEpochNanos() - lastEpochNanos);
      -    String deltaString;
      -    if (deltaMicros >= 1000000) {
      -      deltaString = String.format("%.6f", (deltaMicros / 1000000.0));
      -    } else {
      -      deltaString = String.format("%1s.%6d", "", deltaMicros);
      -    }
      -
      -    long microsField = TimeUnit.NANOSECONDS.toMicros(event.getEpochNanos());
      -    formatter.format(
      -        "%02d:%02d:%02d.%06d
      " - + "
      %s
      " - + "
      %s
      ", - calendar.get(Calendar.HOUR_OF_DAY), - calendar.get(Calendar.MINUTE), - calendar.get(Calendar.SECOND), - microsField, - deltaString, - escapeHtml(renderEvent(event))); - } - - private static String renderAttributes(Attributes attributes) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append("Attributes:{"); - attributes.forEach( - new BiConsumer, Object>() { - private boolean first = true; - - @Override - public void accept(AttributeKey key, Object value) { - if (first) { - first = false; - } else { - stringBuilder.append(", "); - } - stringBuilder.append(key); - stringBuilder.append("="); - stringBuilder.append(value.toString()); - } - }); - stringBuilder.append("}"); - return stringBuilder.toString(); - } - - private static String renderEvent(EventData event) { - StringBuilder stringBuilder = new StringBuilder(); - stringBuilder.append(event.getName()); - if (!event.getAttributes().isEmpty()) { - stringBuilder.append(" | "); - stringBuilder.append(renderAttributes(event.getAttributes())); - } - return stringBuilder.toString(); - } - - /** - * Emits HTML body content to the {@link PrintStream} {@code out}. Content emitted by this - * function should be enclosed by tag. - * - * @param queryMap the map containing URL query parameters.s - * @param out the {@link PrintStream} {@code out}. - */ - private void emitHtmlBody(Map queryMap, PrintStream out) { - if (dataAggregator == null) { - out.print("OpenTelemetry implementation not available."); - return; - } - out.print( - ""); - out.print("

      TraceZ Summary

      "); - emitSummaryTable(out); - // spanName will be null if the query parameter doesn't exist in the URL - String spanName = queryMap.get(PARAM_SPAN_NAME); - if (spanName != null) { - // Show detailed information for the corresponding span - String typeStr = queryMap.get(PARAM_SAMPLE_TYPE); - if (typeStr != null) { - List spans = null; - SampleType type = SampleType.fromString(typeStr); - switch (type) { - case UNKNOWN: - // Type of unknown is garbage value - return; - case RUNNING: - // Display running span - spans = dataAggregator.getRunningSpans(spanName); - break; - default: - String subtypeStr = queryMap.get(PARAM_SAMPLE_SUB_TYPE); - if (subtypeStr != null) { - int subtype = Integer.parseInt(subtypeStr); - if (type == SampleType.LATENCY) { - if (subtype < 0 || subtype >= LatencyBoundary.values().length) { - // N/A or out-of-bound check for latency based subtype, valid values: [0, 8] - return; - } - // Display latency based span - LatencyBoundary latencyBoundary = LatencyBoundary.values()[subtype]; - spans = - dataAggregator.getOkSpans( - spanName, - latencyBoundary.getLatencyLowerBound(), - latencyBoundary.getLatencyUpperBound()); - } else { - if (subtype < 0 || subtype >= StatusCode.values().length) { - // N/A or out-of-bound cueck for error based subtype, valid values: [0, 15] - return; - } - // Display error based span - spans = dataAggregator.getErrorSpans(spanName); - } - } - } - out.print("

      Span Details

      "); - emitSpanNameAndCount(out, spanName, spans == null ? 0 : spans.size(), type); - - if (spans != null) { - Formatter formatter = new Formatter(out, Locale.US); - spans = - spans.stream() - .sorted(Comparator.comparingLong(SpanData::getStartEpochNanos)) - .collect(Collectors.toList()); - emitSpanDetails(out, formatter, spans); - } - } - } - } - - @Override - public void emitHtml(Map queryMap, OutputStream outputStream) { - // PrintStream for emitting HTML contents - try (PrintStream out = new PrintStream(outputStream, /* autoFlush= */ false, "UTF-8")) { - out.print(""); - out.print(""); - out.print(""); - out.print(""); - out.print( - ""); - out.print( - ""); - out.print( - ""); - out.print("" + TRACEZ_NAME + ""); - emitHtmlStyle(out); - out.print(""); - out.print(""); - try { - emitHtmlBody(queryMap, out); - } catch (Throwable t) { - out.print("Error while generating HTML: " + t.toString()); - logger.log(Level.WARNING, "error while generating HTML", t); - } - out.print(""); - out.print(""); - } catch (Throwable t) { - logger.log(Level.WARNING, "error while generating HTML", t); - } - } - - private static String latencyBoundaryToString(LatencyBoundary latencyBoundary) { - switch (latencyBoundary) { - case ZERO_MICROSx10: - return ">0us"; - case MICROSx10_MICROSx100: - return ">10us"; - case MICROSx100_MILLIx1: - return ">100us"; - case MILLIx1_MILLIx10: - return ">1ms"; - case MILLIx10_MILLIx100: - return ">10ms"; - case MILLIx100_SECONDx1: - return ">100ms"; - case SECONDx1_SECONDx10: - return ">1s"; - case SECONDx10_SECONDx100: - return ">10s"; - case SECONDx100_MAX: - return ">100s"; - } - throw new IllegalArgumentException("No value string available for: " + latencyBoundary); - } - - private static Map buildLatencyBoundaryStringMap() { - Map latencyBoundaryMap = new HashMap<>(); - for (LatencyBoundary latencyBoundary : LatencyBoundary.values()) { - latencyBoundaryMap.put(latencyBoundary, latencyBoundaryToString(latencyBoundary)); - } - return latencyBoundaryMap; - } - - private static String escapeHtml(String html) { - StringBuilder escaped = null; - for (int i = 0; i < html.length(); i++) { - char c = html.charAt(i); - switch (c) { - case '"': - escaped = lazyStringBuilder(escaped, html, i); - escaped.append("""); - break; - case '\'': - escaped = lazyStringBuilder(escaped, html, i); - escaped.append("'"); - break; - case '&': - escaped = lazyStringBuilder(escaped, html, i); - escaped.append("&"); - break; - case '<': - escaped = lazyStringBuilder(escaped, html, i); - escaped.append("<"); - break; - case '>': - escaped = lazyStringBuilder(escaped, html, i); - escaped.append(">"); - break; - default: - if (escaped != null) { - escaped.append(c); - } - } - } - return escaped != null ? escaped.toString() : html; - } - - private static StringBuilder lazyStringBuilder( - @Nullable StringBuilder sb, String str, int currentCharIdx) { - if (sb != null) { - return sb; - } - sb = new StringBuilder(str.length()); - sb.append(str.substring(0, currentCharIdx - 1)); - return sb; - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageHandler.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageHandler.java deleted file mode 100644 index c19fe82c8cd..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageHandler.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import java.io.OutputStream; -import java.util.Map; - -/** - * The main interface for all zPages. All zPages should implement this interface to allow the HTTP - * server implementation to support these pages. - */ -public abstract class ZPageHandler { - - /** - * Returns the URL path that should be used to register this zPage to the HTTP server. - * - * @return the URL path that should be used to register this zPage to the HTTP server. - */ - public abstract String getUrlPath(); - - /** - * Returns the name of the zPage. - * - * @return the name of the zPage. - */ - public abstract String getPageName(); - - /** - * Returns the description of the zPage. - * - * @return the description of the zPage. - */ - public abstract String getPageDescription(); - - /** - * Process requests that require changes (POST/PUT/DELETE). - * - * @param requestMethod the request method HttpHandler received. - * @param queryMap the map of the URL query parameters. - * @return true if theres an error while processing the request. - */ - public boolean processRequest( - String requestMethod, Map queryMap, OutputStream outputStream) { - // base no-op method - return false; - } - - /** - * Emits the generated HTML page to the {@code outputStream}. - * - * @param queryMap the map of the URL query parameters. - * @param outputStream the output for the generated HTML page. - */ - public abstract void emitHtml(Map queryMap, OutputStream outputStream); - - /** Package protected constructor to disallow users to extend this class. */ - ZPageHandler() {} -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageHttpHandler.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageHttpHandler.java deleted file mode 100644 index 1183130070d..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageHttpHandler.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import com.sun.net.httpserver.HttpExchange; -import com.sun.net.httpserver.HttpHandler; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -/** An {@link HttpHandler} that will be used to render HTML pages using any {@code ZPageHandler}. */ -final class ZPageHttpHandler implements HttpHandler { - // Query string parameter name for span name - private static final String PARAM_SPAN_NAME = "zspanname"; - // The corresponding ZPageHandler for the zPage (e.g. TracezZPageHandler) - private final ZPageHandler zpageHandler; - - /** Constructs a new {@code ZPageHttpHandler}. */ - ZPageHttpHandler(ZPageHandler zpageHandler) { - this.zpageHandler = zpageHandler; - } - - /** - * Build a query map from the query string. - * - * @param queryString the query string for buiding the query map. - * @return the query map built based on the query string. - */ - // Visible for testing - static Map parseQueryString(String queryString) { - if (queryString == null) { - return Collections.emptyMap(); - } - Map queryMap = new HashMap(); - Arrays.stream(queryString.split("&")) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .forEach( - param -> { - List keyValuePair = - Arrays.stream(param.split("=")) - .map(String::trim) - .filter(s -> !s.isEmpty()) - .collect(Collectors.toList()); - if (keyValuePair.size() > 1) { - if (keyValuePair.get(0).equals(PARAM_SPAN_NAME)) { - try { - queryMap.put( - keyValuePair.get(0), URLDecoder.decode(keyValuePair.get(1), "UTF-8")); - } catch (UnsupportedEncodingException e) { - // Ignore encoding exception. - } - } else { - queryMap.put(keyValuePair.get(0), keyValuePair.get(1)); - } - } - }); - return Collections.unmodifiableMap(queryMap); - } - - @Override - public final void handle(HttpExchange httpExchange) throws IOException { - try { - String requestMethod = httpExchange.getRequestMethod(); - httpExchange.sendResponseHeaders(200, 0); - if (requestMethod.equalsIgnoreCase("GET")) { - zpageHandler.emitHtml( - parseQueryString(httpExchange.getRequestURI().getRawQuery()), - httpExchange.getResponseBody()); - } else { - String queryString; - try (BufferedReader reader = - new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "utf-8"))) { - // Query strings can only have one line - queryString = reader.readLine(); - } - boolean error = - zpageHandler.processRequest( - requestMethod, parseQueryString(queryString), httpExchange.getResponseBody()); - if (!error) { - zpageHandler.emitHtml(parseQueryString(queryString), httpExchange.getResponseBody()); - } - } - } finally { - httpExchange.close(); - } - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageLogo.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageLogo.java deleted file mode 100644 index a3c0b02c28a..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageLogo.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Base64; -import java.util.logging.Level; -import java.util.logging.Logger; - -final class ZPageLogo { - private static final Logger logger = Logger.getLogger(ZPageLogo.class.getName()); - - private ZPageLogo() {} - - /** - * Get OpenTelemetry logo in base64 encoding. - * - * @return OpenTelemetry logo in base64 encoding. - */ - public static String getLogoBase64() { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - try (InputStream is = ZPageLogo.class.getClassLoader().getResourceAsStream("logo.png")) { - readTo(is, os); - } - } catch (Throwable t) { - logger.log(Level.WARNING, "error while getting OpenTelemetry Logo", t); - return ""; - } - byte[] bytes = os.toByteArray(); - return Base64.getEncoder().encodeToString(bytes); - } - - /** - * Get OpenTelemetry favicon in base64 encoding. - * - * @return OpenTelemetry favicon in base64 encoding. - */ - public static String getFaviconBase64() { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try (InputStream is = ZPageLogo.class.getClassLoader().getResourceAsStream("favicon.png")) { - readTo(is, os); - } catch (Throwable t) { - logger.log(Level.WARNING, "error while getting OpenTelemetry Logo", t); - return ""; - } - byte[] bytes = os.toByteArray(); - return Base64.getEncoder().encodeToString(bytes); - } - - private static void readTo(InputStream is, ByteArrayOutputStream os) throws IOException { - int b; - while ((b = is.read()) != -1) { - os.write(b); - } - } -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageServer.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageServer.java deleted file mode 100644 index 5d04a7fbe45..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageServer.java +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import com.sun.net.httpserver.HttpServer; -import io.opentelemetry.api.internal.GuardedBy; -import io.opentelemetry.sdk.trace.SpanLimits; -import io.opentelemetry.sdk.trace.SpanProcessor; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.util.Arrays; -import java.util.function.Supplier; -import javax.annotation.Nullable; -import javax.annotation.concurrent.ThreadSafe; - -/** - * A collection of HTML pages to display stats and trace data and allow library configuration - * control. To use, add {@linkplain ZPageServer#getSpanProcessor() the z-pages span processor}, - * {@linkplain ZPageServer#getTracezTraceConfigSupplier() the z-pages dynamic trace config} and - * {@linkplain ZPageServer#getTracezSampler() the z-pages dynamic sampler} to a {@link - * io.opentelemetry.sdk.trace.SdkTracerProviderBuilder}. Currently all tracers can only be made - * visible to a singleton {@link ZPageServer}. - * - *

      Example usage with private {@link HttpServer} - * - *

      {@code
      - * public class Main {
      - *   public static void main(String[] args) throws Exception {
      - *     OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
      - *         .setTracerProvider(SdkTracerProvider.builder()
      - *             .addSpanProcessor(ZPageServer.getSpanProcessor())
      - *             .setTraceConfigSupplier(ZPageServer.getTraceConfigSupplier())
      - *             .setSampler(ZPageServer.getSampler())
      - *             .build();
      - *         .build();
      - *
      - *     ZPageServer.startHttpServerAndRegisterAllPages(8000);
      - *     ... // do work
      - *   }
      - * }
      - * }
      - * - *

      Example usage with shared {@link HttpServer} - * - *

      {@code
      - * public class Main {
      - *   public static void main(String[] args) throws Exception {
      - *     OpenTelemetry openTelemetry = OpenTelemetrySdk.builder()
      - *         .setTracerProvider(SdkTracerProvider.builder()
      - *             .addSpanProcessor(ZPageServer.getSpanProcessor())
      - *             .setTraceConfigSupplier(ZPageServer.getTraceConfigSupplier())
      - *             .setSampler(ZPageServer.getSampler())
      - *             .build();
      - *         .build();
      - *
      - *     HttpServer server = HttpServer.create(new InetSocketAddress(8000), 10);
      - *     ZPageServer.registerAllPagesToHttpServer(server);
      - *     server.start();
      - *     ... // do work
      - *   }
      - * }
      - * }
      - */ -@ThreadSafe -public final class ZPageServer { - // The maximum number of queued incoming connections allowed on the HttpServer listening socket. - private static final int HTTPSERVER_BACKLOG = 5; - // Length of time to wait for the HttpServer to stop - private static final int HTTPSERVER_STOP_DELAY = 1; - // Tracez SpanProcessor and DataAggregator for constructing TracezZPageHandler - private static final TracezSpanProcessor tracezSpanProcessor = - TracezSpanProcessor.builder().build(); - private static final TracezTraceConfigSupplier tracezTraceConfigSupplier = - new TracezTraceConfigSupplier(); - private static final TracezDataAggregator tracezDataAggregator = - new TracezDataAggregator(tracezSpanProcessor); - // Handler for /tracez page - private static final ZPageHandler tracezZPageHandler = - new TracezZPageHandler(tracezDataAggregator); - // Handler for /traceconfigz page - private static final ZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(tracezTraceConfigSupplier); - // Handler for index page, **please include all available ZPageHandlers in the constructor** - private static final ZPageHandler indexZPageHandler = - new IndexZPageHandler(Arrays.asList(tracezZPageHandler, traceConfigzZPageHandler)); - - private static final Object mutex = new Object(); - - @GuardedBy("mutex") - @Nullable - private static HttpServer server; - - /** Returns a supplier of {@link SpanLimits} which can be reconfigured using zpages. */ - public static Supplier getTracezTraceConfigSupplier() { - return tracezTraceConfigSupplier; - } - - /** Returns a {@link Sampler} which can be reconfigured using zpages. */ - public static Sampler getTracezSampler() { - return tracezTraceConfigSupplier; - } - - /** - * Returns a {@link SpanProcessor} which will allow processing of spans by {@link ZPageServer}. - */ - public static SpanProcessor getSpanProcessor() { - return tracezSpanProcessor; - } - - /** - * Registers a {@link ZPageHandler} for the index page of zPages. The page displays information - * about all available zPages with links to those zPages. - * - * @param server the {@link HttpServer} for the page to register to. - */ - static void registerIndexZPageHandler(HttpServer server) { - server.createContext(indexZPageHandler.getUrlPath(), new ZPageHttpHandler(indexZPageHandler)); - } - - /** - * Registers a {@link ZPageHandler} for tracing debug to the server. The page displays information - * about all running spans and all sampled spans based on latency and error. - * - *

      It displays a summary table which contains one row for each span name and data about number - * of running and sampled spans. - * - *

      Clicking on a cell in the table with a number that is greater than zero will display - * detailed information about that span. - * - *

      This method will add the TracezSpanProcessor to the tracerProvider, it should only be called - * once. - * - * @param server the {@link HttpServer} for the page to register to. - */ - static void registerTracezZPageHandler(HttpServer server) { - server.createContext(tracezZPageHandler.getUrlPath(), new ZPageHttpHandler(tracezZPageHandler)); - } - - /** - * Registers a {@code ZPageHandler} for tracing config. The page displays information about all - * active configuration and allow changing the active configuration. - * - *

      It displays a change table which allows users to change active configuration. - * - *

      It displays an active value table which displays current active configuration. - * - *

      Refreshing the page will show the updated active configuration. - * - * @param server the {@link HttpServer} for the page to register to. - */ - static void registerTraceConfigzZPageHandler(HttpServer server) { - server.createContext( - traceConfigzZPageHandler.getUrlPath(), new ZPageHttpHandler(traceConfigzZPageHandler)); - } - - /** - * Registers all zPages to the given {@link HttpServer} {@code server}. - * - * @param server the {@link HttpServer} for the page to register to. - */ - public static void registerAllPagesToHttpServer(HttpServer server) { - // For future zPages, register them to the server in here - registerIndexZPageHandler(server); - registerTracezZPageHandler(server); - registerTraceConfigzZPageHandler(server); - } - - /** Method for stopping the {@link HttpServer} {@code server}. */ - private static void stop() { - synchronized (mutex) { - if (server == null) { - return; - } - server.stop(HTTPSERVER_STOP_DELAY); - server = null; - } - } - - /** - * Starts a private {@link HttpServer} and registers all zPages to it. When the JVM shuts down the - * server is stopped. - * - *

      Users can only call this function once per process. - * - * @param port the port used to bind the {@link HttpServer} {@code server} - * @throws IllegalStateException if the server is already started. - * @throws IOException if the server cannot bind to the specified port. - */ - public static void startHttpServerAndRegisterAllPages(int port) throws IOException { - synchronized (mutex) { - if (server != null) { - throw new IllegalStateException("The HttpServer is already started."); - } - server = HttpServer.create(new InetSocketAddress(port), HTTPSERVER_BACKLOG); - ZPageServer.registerAllPagesToHttpServer(server); - server.start(); - } - - Runtime.getRuntime() - .addShutdownHook( - new Thread() { - @Override - public void run() { - ZPageServer.stop(); - } - }); - } - - private ZPageServer() {} -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageStyle.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageStyle.java deleted file mode 100644 index 2407ad18f45..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/ZPageStyle.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -/** This class contains the unified CSS styles for all zPages. */ -final class ZPageStyle { - private ZPageStyle() {} - - /** Style here will be applied to the generated HTML pages for all zPages. */ - static String style = - "body{font-family: \"Roboto\", sans-serif; font-size: 16px;" - + "background-color: #fff;}" - + "h1{padding: 0 20px; color: #363636; text-align: center; margin-bottom: 20px;}" - + "h2{padding: 0 20px; color: #363636; text-align: center; margin-bottom: 20px;}" - + "p{padding: 0 20px; color: #363636;}" - + "tr.bg-color{background-color: #4b5fab;}" - + "table{margin: 0 auto;}" - + "th{padding: 0 1em; line-height: 2.0}" - + "td{padding: 0 1em; line-height: 2.0}" - + ".border-right-white{border-right: 1px solid #fff;}" - + ".border-left-white{border-left: 1px solid #fff;}" - + ".border-left-dark{border-left: 1px solid #363636;}" - + "th.header-text{color: #fff; line-height: 3.0;}" - + ".align-center{text-align: center;}" - + ".align-right{text-align: right;}" - + "pre.no-margin{margin: 0;}" - + "pre.wrap-text{white-space:pre-wrap;}" - + "td.bg-white{background-color: #fff;}" - + "button.button{background-color: #fff; margin-top: 15px;}" - + "form.form-flex{display: flex; flex-direction: column; align-items: center;}"; -} diff --git a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/package-info.java b/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/package-info.java deleted file mode 100644 index b5de275da60..00000000000 --- a/sdk-extensions/zpages/src/main/java/io/opentelemetry/sdk/extension/zpages/package-info.java +++ /dev/null @@ -1,12 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * The ZPages endpoint for providing debug information about an app instrumented with OpenTelemetry. - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.extension.zpages; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk-extensions/zpages/src/main/resources/favicon.png b/sdk-extensions/zpages/src/main/resources/favicon.png deleted file mode 100644 index 91f2be7b2eb..00000000000 Binary files a/sdk-extensions/zpages/src/main/resources/favicon.png and /dev/null differ diff --git a/sdk-extensions/zpages/src/main/resources/logo.png b/sdk-extensions/zpages/src/main/resources/logo.png deleted file mode 100644 index f225db4f3be..00000000000 Binary files a/sdk-extensions/zpages/src/main/resources/logo.png and /dev/null differ diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/IndexZPageHandlerTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/IndexZPageHandlerTest.java deleted file mode 100644 index a42e56c1cb7..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/IndexZPageHandlerTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.util.Map; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link IndexZPageHandler}. */ -public final class IndexZPageHandlerTest { - private static final ZPageHandler tracezZPageHandler = new TracezZPageHandler(null); - private final Map emptyQueryMap = ImmutableMap.of(); - - @Test - void emitHtmlCorrectly() { - OutputStream output = new ByteArrayOutputStream(); - IndexZPageHandler indexZPageHandler = - new IndexZPageHandler(ImmutableList.of(tracezZPageHandler)); - - indexZPageHandler.emitHtml(emptyQueryMap, output); - - assertThat(output.toString()).contains(""); - assertThat(output.toString()).contains(">" + tracezZPageHandler.getPageName() + ""); - assertThat(output.toString()) - .contains("

      " + tracezZPageHandler.getPageDescription() + "

      "); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/SpanBucketTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/SpanBucketTest.java deleted file mode 100644 index 3fe6aaf9bb5..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/SpanBucketTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; - -class SpanBucketTest { - private static final String SPAN_NAME = "span"; - private static final int LATENCY_BUCKET_SIZE = 16; - private static final int ERROR_BUCKET_SIZE = 8; - private final SdkTracerProvider sdkTracerProvider = SdkTracerProvider.builder().build(); - private final Tracer tracer = sdkTracerProvider.get("SpanBucketTest"); - - @Test - void verifyLatencyBucketSizeLimit() { - SpanBucket latencyBucket = new SpanBucket(/* isLatencyBucket= */ true); - Span[] spans = new Span[LATENCY_BUCKET_SIZE + 1]; - for (int i = 0; i < LATENCY_BUCKET_SIZE + 1; i++) { - spans[i] = tracer.spanBuilder(SPAN_NAME).startSpan(); - latencyBucket.add((ReadableSpan) spans[i]); - spans[i].end(); - } - List bucketSpans = new ArrayList<>(); - latencyBucket.addTo(bucketSpans); - /* The latency SpanBucket should have the most recent LATENCY_BUCKET_SIZE spans */ - assertThat(latencyBucket.size()).isEqualTo(LATENCY_BUCKET_SIZE); - assertThat(bucketSpans.size()).isEqualTo(LATENCY_BUCKET_SIZE); - assertThat(bucketSpans).doesNotContain((ReadableSpan) spans[0]); - for (int i = 1; i < LATENCY_BUCKET_SIZE + 1; i++) { - assertThat(bucketSpans).contains((ReadableSpan) spans[i]); - } - } - - @Test - void verifyErrorBucketSizeLimit() { - SpanBucket errorBucket = new SpanBucket(/* isLatencyBucket= */ false); - Span[] spans = new Span[ERROR_BUCKET_SIZE + 1]; - for (int i = 0; i < ERROR_BUCKET_SIZE + 1; i++) { - spans[i] = tracer.spanBuilder(SPAN_NAME).startSpan(); - errorBucket.add((ReadableSpan) spans[i]); - spans[i].end(); - } - List bucketSpans = new ArrayList<>(); - errorBucket.addTo(bucketSpans); - /* The error SpanBucket should have the most recent ERROR_BUCKET_SIZE spans */ - assertThat(errorBucket.size()).isEqualTo(ERROR_BUCKET_SIZE); - assertThat(bucketSpans.size()).isEqualTo(ERROR_BUCKET_SIZE); - assertThat(bucketSpans).doesNotContain((ReadableSpan) spans[0]); - for (int i = 1; i < ERROR_BUCKET_SIZE + 1; i++) { - assertThat(bucketSpans).contains((ReadableSpan) spans[i]); - } - } - - @Timeout(value = 1) - public void verifyThreadSafety() throws InterruptedException { - int numberOfThreads = 4; - int numberOfSpans = 4; - SpanBucket spanBucket = new SpanBucket(/* isLatencyBucket= */ true); - CountDownLatch startSignal = new CountDownLatch(1); - CountDownLatch endSignal = new CountDownLatch(numberOfThreads); - for (int i = 0; i < numberOfThreads; i++) { - new Thread( - () -> { - try { - startSignal.await(); - for (int j = 0; j < numberOfSpans; j++) { - Span span = tracer.spanBuilder(SPAN_NAME).startSpan(); - spanBucket.add((ReadableSpan) span); - span.end(); - } - endSignal.countDown(); - } catch (InterruptedException e) { - return; - } - }) - .start(); - } - startSignal.countDown(); - endSignal.await(); - /* The SpanBucket should have exactly 16 spans */ - assertThat(spanBucket.size()).isEqualTo(numberOfThreads * numberOfSpans); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TraceConfigzZPageHandlerTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TraceConfigzZPageHandlerTest.java deleted file mode 100644 index 2d8b0971f8e..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TraceConfigzZPageHandlerTest.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.trace.SpanLimits; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.util.Map; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class TraceConfigzZPageHandlerTest { - private static final Map emptyQueryMap = ImmutableMap.of(); - - private TracezTraceConfigSupplier configSupplier; - - @BeforeEach - void setup() { - configSupplier = new TracezTraceConfigSupplier(); - } - - @Test - void changeTable_emitRowsCorrectly() { - OutputStream output = new ByteArrayOutputStream(); - String querySamplingProbability = "samplingprobability"; - String queryMaxNumOfAttributes = "maxnumofattributes"; - String queryMaxNumOfEvents = "maxnumofevents"; - String queryMaxNumOfLinks = "maxnumoflinks"; - String queryMaxNumOfAttributesPerEvent = "maxnumofattributesperevent"; - String queryMaxNumOfAttributesPerLink = "maxnumofattributesperlink"; - - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - traceConfigzZPageHandler.emitHtml(emptyQueryMap, output); - - assertThat(output.toString()).contains("SamplingProbability to"); - assertThat(output.toString()).contains("name=" + querySamplingProbability); - assertThat(output.toString()).contains("(1.0)"); - assertThat(output.toString()).contains("MaxNumberOfAttributes to"); - assertThat(output.toString()).contains("name=" + queryMaxNumOfAttributes); - assertThat(output.toString()) - .contains("(" + Integer.toString(SpanLimits.getDefault().getMaxNumberOfAttributes()) + ")"); - assertThat(output.toString()).contains("MaxNumberOfEvents to"); - assertThat(output.toString()).contains("name=" + queryMaxNumOfEvents); - assertThat(output.toString()) - .contains("(" + Integer.toString(SpanLimits.getDefault().getMaxNumberOfEvents()) + ")"); - assertThat(output.toString()).contains("MaxNumberOfLinks to"); - assertThat(output.toString()).contains("name=" + queryMaxNumOfLinks); - assertThat(output.toString()) - .contains("(" + Integer.toString(SpanLimits.getDefault().getMaxNumberOfLinks()) + ")"); - assertThat(output.toString()).contains("MaxNumberOfAttributesPerEvent to"); - assertThat(output.toString()).contains("name=" + queryMaxNumOfAttributesPerEvent); - assertThat(output.toString()) - .contains( - "(" - + Integer.toString(SpanLimits.getDefault().getMaxNumberOfAttributesPerEvent()) - + ")"); - assertThat(output.toString()).contains("MaxNumberOfAttributesPerLink to"); - assertThat(output.toString()).contains("name=" + queryMaxNumOfAttributesPerLink); - assertThat(output.toString()) - .contains( - "(" - + Integer.toString(SpanLimits.getDefault().getMaxNumberOfAttributesPerLink()) - + ")"); - } - - @Test - void activeTable_emitRowsCorrectly() { - OutputStream output = new ByteArrayOutputStream(); - - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - traceConfigzZPageHandler.emitHtml(emptyQueryMap, output); - - assertThat(output.toString()).contains("Sampler"); - assertThat(output.toString()) - .contains(">" + configSupplier.getSampler().getDescription() + "<"); - assertThat(output.toString()).contains("MaxNumberOfAttributes"); - assertThat(output.toString()) - .contains(">" + Integer.toString(configSupplier.get().getMaxNumberOfAttributes()) + "<"); - assertThat(output.toString()).contains("MaxNumberOfEvents"); - assertThat(output.toString()) - .contains(">" + Integer.toString(configSupplier.get().getMaxNumberOfEvents()) + "<"); - assertThat(output.toString()).contains("MaxNumberOfLinks"); - assertThat(output.toString()) - .contains(">" + Integer.toString(configSupplier.get().getMaxNumberOfLinks()) + "<"); - assertThat(output.toString()).contains("MaxNumberOfAttributesPerEvent"); - assertThat(output.toString()) - .contains( - ">" + Integer.toString(configSupplier.get().getMaxNumberOfAttributesPerEvent()) + "<"); - assertThat(output.toString()).contains("MaxNumberOfAttributesPerLink"); - assertThat(output.toString()) - .contains( - ">" + Integer.toString(configSupplier.get().getMaxNumberOfAttributesPerLink()) + "<"); - } - - @Test - void appliesChangesCorrectly_formSubmit() { - OutputStream output = new ByteArrayOutputStream(); - String querySamplingProbability = "samplingprobability"; - String queryMaxNumOfAttributes = "maxnumofattributes"; - String queryMaxNumOfEvents = "maxnumofevents"; - String queryMaxNumOfLinks = "maxnumoflinks"; - String queryMaxNumOfAttributesPerEvent = "maxnumofattributesperevent"; - String queryMaxNumOfAttributesPerLink = "maxnumofattributesperlink"; - String newSamplingProbability = "0.001"; - String newMaxNumOfAttributes = "16"; - String newMaxNumOfEvents = "16"; - String newMaxNumOfLinks = "16"; - String newMaxNumOfAttributesPerEvent = "16"; - String newMaxNumOfAttributesPerLink = "16"; - - Map queryMap = - new ImmutableMap.Builder() - .put("action", "change") - .put(querySamplingProbability, newSamplingProbability) - .put(queryMaxNumOfAttributes, newMaxNumOfAttributes) - .put(queryMaxNumOfEvents, newMaxNumOfEvents) - .put(queryMaxNumOfLinks, newMaxNumOfLinks) - .put(queryMaxNumOfAttributesPerEvent, newMaxNumOfAttributesPerEvent) - .put(queryMaxNumOfAttributesPerLink, newMaxNumOfAttributesPerLink) - .build(); - - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - traceConfigzZPageHandler.emitHtml(queryMap, output); - - assertThat(configSupplier.getSampler().getDescription()) - .isEqualTo( - Sampler.traceIdRatioBased(Double.parseDouble(newSamplingProbability)).getDescription()); - assertThat(configSupplier.get().getMaxNumberOfAttributes()) - .isEqualTo(Integer.parseInt(newMaxNumOfAttributes)); - assertThat(configSupplier.get().getMaxNumberOfEvents()) - .isEqualTo(Integer.parseInt(newMaxNumOfEvents)); - assertThat(configSupplier.get().getMaxNumberOfLinks()) - .isEqualTo(Integer.parseInt(newMaxNumOfLinks)); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerEvent()) - .isEqualTo(Integer.parseInt(newMaxNumOfAttributesPerEvent)); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerLink()) - .isEqualTo(Integer.parseInt(newMaxNumOfAttributesPerLink)); - } - - @Test - void appliesChangesCorrectly_restoreDefault() { - OutputStream output = new ByteArrayOutputStream(); - - Map queryMap = ImmutableMap.of("action", "default"); - - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - traceConfigzZPageHandler.emitHtml(queryMap, output); - - assertThat(configSupplier.getSampler().getDescription()) - .isEqualTo(Sampler.traceIdRatioBased(1.0).getDescription()); - assertThat(configSupplier.get().getMaxNumberOfAttributes()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributes()); - assertThat(configSupplier.get().getMaxNumberOfEvents()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfEvents()); - assertThat(configSupplier.get().getMaxNumberOfLinks()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfLinks()); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerEvent()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributesPerEvent()); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerLink()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributesPerLink()); - } - - @Test - void appliesChangesCorrectly_doNotCrashOnNullParameters() { - OutputStream output = new ByteArrayOutputStream(); - - Map queryMap = ImmutableMap.of("action", "change"); - - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - traceConfigzZPageHandler.emitHtml(queryMap, output); - - assertThat(configSupplier.getSampler().getDescription()) - .isEqualTo(Sampler.traceIdRatioBased(1.0).getDescription()); - assertThat(configSupplier.get().getMaxNumberOfAttributes()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributes()); - assertThat(configSupplier.get().getMaxNumberOfEvents()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfEvents()); - assertThat(configSupplier.get().getMaxNumberOfLinks()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfLinks()); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerEvent()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributesPerEvent()); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerLink()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributesPerLink()); - } - - @Test - @SuppressLogger(TraceConfigzZPageHandler.class) - void applyChanges_emitErrorOnInvalidInput() { - // Invalid samplingProbability (not type of double) - OutputStream output = new ByteArrayOutputStream(); - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - Map queryMap = - ImmutableMap.of("action", "change", "samplingprobability", "invalid"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("SamplingProbability must be of the type double"); - - // Invalid samplingProbability (< 0) - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "samplingprobability", "-1"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("ratio must be in range [0.0, 1.0]"); - - // Invalid samplingProbability (> 1) - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "samplingprobability", "1.1"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("ratio must be in range [0.0, 1.0]"); - - // Invalid maxNumOfAttributes - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "maxnumofattributes", "invalid"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("MaxNumOfAttributes must be of the type integer"); - - // Invalid maxNumOfEvents - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "maxnumofevents", "invalid"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("MaxNumOfEvents must be of the type integer"); - - // Invalid maxNumLinks - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "maxnumoflinks", "invalid"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("MaxNumOfLinks must be of the type integer"); - - // Invalid maxNumOfAttributesPerEvent - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "maxnumofattributesperevent", "invalid"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()) - .contains("MaxNumOfAttributesPerEvent must be of the type integer"); - - // Invalid maxNumOfAttributesPerLink - output = new ByteArrayOutputStream(); - traceConfigzZPageHandler = new TraceConfigzZPageHandler(configSupplier); - queryMap = ImmutableMap.of("action", "change", "maxnumofattributesperlink", "invalid"); - - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - - assertThat(output.toString()).contains("Error while applying trace config changes: "); - assertThat(output.toString()).contains("MaxNumOfAttributesPerLink must be of the type integer"); - } - - @Test - void applyChanges_shouldNotUpdateOnGetRequest() { - OutputStream output = new ByteArrayOutputStream(); - String querySamplingProbability = "samplingprobability"; - String queryMaxNumOfAttributes = "maxnumofattributes"; - String queryMaxNumOfEvents = "maxnumofevents"; - String queryMaxNumOfLinks = "maxnumoflinks"; - String queryMaxNumOfAttributesPerEvent = "maxnumofattributesperevent"; - String queryMaxNumOfAttributesPerLink = "maxnumofattributesperlink"; - String newSamplingProbability = "0.001"; - String newMaxNumOfAttributes = "16"; - String newMaxNumOfEvents = "16"; - String newMaxNumOfLinks = "16"; - String newMaxNumOfAttributesPerEvent = "16"; - String newMaxNumOfAttributesPerLink = "16"; - - // Apply new config - Map queryMap = - new ImmutableMap.Builder() - .put("action", "change") - .put(querySamplingProbability, newSamplingProbability) - .put(queryMaxNumOfAttributes, newMaxNumOfAttributes) - .put(queryMaxNumOfEvents, newMaxNumOfEvents) - .put(queryMaxNumOfLinks, newMaxNumOfLinks) - .put(queryMaxNumOfAttributesPerEvent, newMaxNumOfAttributesPerEvent) - .put(queryMaxNumOfAttributesPerLink, newMaxNumOfAttributesPerLink) - .build(); - - TraceConfigzZPageHandler traceConfigzZPageHandler = - new TraceConfigzZPageHandler(configSupplier); - - // GET request, Should not apply changes - traceConfigzZPageHandler.emitHtml(queryMap, output); - - assertThat(configSupplier.getSampler().getDescription()) - .isEqualTo(Sampler.traceIdRatioBased(1.0).getDescription()); - assertThat(configSupplier.get().getMaxNumberOfAttributes()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributes()); - assertThat(configSupplier.get().getMaxNumberOfEvents()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfEvents()); - assertThat(configSupplier.get().getMaxNumberOfLinks()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfLinks()); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerEvent()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributesPerEvent()); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerLink()) - .isEqualTo(SpanLimits.getDefault().getMaxNumberOfAttributesPerLink()); - - // POST request, Should apply changes - traceConfigzZPageHandler.processRequest("POST", queryMap, output); - traceConfigzZPageHandler.emitHtml(queryMap, output); - - assertThat(configSupplier.getSampler().getDescription()) - .isEqualTo( - Sampler.traceIdRatioBased(Double.parseDouble(newSamplingProbability)).getDescription()); - assertThat(configSupplier.get().getMaxNumberOfAttributes()) - .isEqualTo(Integer.parseInt(newMaxNumOfAttributes)); - assertThat(configSupplier.get().getMaxNumberOfEvents()) - .isEqualTo(Integer.parseInt(newMaxNumOfEvents)); - assertThat(configSupplier.get().getMaxNumberOfLinks()) - .isEqualTo(Integer.parseInt(newMaxNumOfLinks)); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerEvent()) - .isEqualTo(Integer.parseInt(newMaxNumOfAttributesPerEvent)); - assertThat(configSupplier.get().getMaxNumberOfAttributesPerLink()) - .isEqualTo(Integer.parseInt(newMaxNumOfAttributesPerLink)); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregatorTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregatorTest.java deleted file mode 100644 index 04bac8de48a..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezDataAggregatorTest.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.testing.time.TestClock; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.time.Duration; -import java.util.List; -import java.util.Map; -import java.util.Set; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link TracezDataAggregator}. */ -public final class TracezDataAggregatorTest { - private static final String SPAN_NAME_ONE = "one"; - private static final String SPAN_NAME_TWO = "two"; - private final TestClock testClock = TestClock.create(); - private final TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - private final SdkTracerProvider sdkTracerProvider = - SdkTracerProvider.builder().setClock(testClock).addSpanProcessor(spanProcessor).build(); - private final Tracer tracer = sdkTracerProvider.get("TracezDataAggregatorTest"); - private final TracezDataAggregator dataAggregator = new TracezDataAggregator(spanProcessor); - - @Test - void getSpanNames_noSpans() { - assertThat(dataAggregator.getSpanNames()).isEmpty(); - } - - @Test - void getSpanNames_twoSpanNames() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - Span span3 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - /* getSpanNames should return a set with 2 span names */ - Set names = dataAggregator.getSpanNames(); - assertThat(names).containsExactly(SPAN_NAME_ONE, SPAN_NAME_TWO); - span1.end(); - span2.end(); - span3.end(); - /* getSpanNames should still return a set with 2 span names */ - names = dataAggregator.getSpanNames(); - assertThat(names).containsExactly(SPAN_NAME_ONE, SPAN_NAME_TWO); - } - - @Test - void getRunningSpanCounts_noSpans() { - /* getRunningSpanCounts should return a an empty map */ - Map counts = dataAggregator.getRunningSpanCounts(); - assertThat(counts).isEmpty(); - } - - @Test - void getRunningSpanCounts_oneSpanName() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span3 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - /* getRunningSpanCounts should return a map with 1 span name */ - Map counts = dataAggregator.getRunningSpanCounts(); - assertThat(counts.get(SPAN_NAME_ONE)).isEqualTo(3); - span1.end(); - span2.end(); - span3.end(); - /* getRunningSpanCounts should return a map with no span names */ - counts = dataAggregator.getRunningSpanCounts(); - assertThat(counts).isEmpty(); - } - - @Test - void getRunningSpanCounts_twoSpanNames() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - /* getRunningSpanCounts should return a map with 2 different span names */ - Map counts = dataAggregator.getRunningSpanCounts(); - assertThat(counts.get(SPAN_NAME_ONE)).isEqualTo(1); - assertThat(counts.get(SPAN_NAME_TWO)).isEqualTo(1); - - span1.end(); - /* getRunningSpanCounts should return a map with 1 unique span name */ - counts = dataAggregator.getRunningSpanCounts(); - assertThat(counts.get(SPAN_NAME_ONE)).isNull(); - assertThat(counts.get(SPAN_NAME_TWO)).isEqualTo(1); - - span2.end(); - /* getRunningSpanCounts should return a map with no span names */ - counts = dataAggregator.getRunningSpanCounts(); - assertThat(counts).isEmpty(); - } - - @Test - void getRunningSpans_noSpans() { - /* getRunningSpans should return an empty List */ - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_ONE)).isEmpty(); - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_TWO)).isEmpty(); - } - - @Test - void getRunningSpans_oneSpanName() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span3 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - /* getRunningSpans should return a List with all 3 spans */ - List spans = dataAggregator.getRunningSpans(SPAN_NAME_ONE); - assertThat(spans) - .containsExactlyInAnyOrder( - ((ReadableSpan) span1).toSpanData(), - ((ReadableSpan) span2).toSpanData(), - ((ReadableSpan) span3).toSpanData()); - span1.end(); - span2.end(); - span3.end(); - /* getRunningSpans should return an empty List */ - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_ONE)).isEmpty(); - } - - @Test - void getRunningSpans_twoSpanNames() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - /* getRunningSpans should return a List with only the corresponding span */ - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_ONE)) - .containsExactly(((ReadableSpan) span1).toSpanData()); - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_TWO)) - .containsExactly(((ReadableSpan) span2).toSpanData()); - span1.end(); - span2.end(); - /* getRunningSpans should return an empty List for each span name */ - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_ONE)).isEmpty(); - assertThat(dataAggregator.getRunningSpans(SPAN_NAME_TWO)).isEmpty(); - } - - @Test - void getSpanLatencyCounts_noSpans() { - /* getSpanLatencyCounts should return a an empty map */ - Map> counts = dataAggregator.getSpanLatencyCounts(); - assertThat(counts).isEmpty(); - } - - @Test - void getSpanLatencyCounts_noCompletedSpans() { - /* getSpanLatencyCounts should return a an empty map */ - Span span = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Map> counts = dataAggregator.getSpanLatencyCounts(); - span.end(); - assertThat(counts).isEmpty(); - } - - @Test - void getSpanLatencyCounts_oneSpanPerLatencyBucket() { - for (LatencyBoundary bucket : LatencyBoundary.values()) { - Span span = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - testClock.advance(Duration.ofNanos(bucket.getLatencyLowerBound())); - span.end(); - } - /* getSpanLatencyCounts should return 1 span per latency bucket */ - Map> counts = dataAggregator.getSpanLatencyCounts(); - for (LatencyBoundary bucket : LatencyBoundary.values()) { - assertThat(counts.get(SPAN_NAME_ONE).get(bucket)).isEqualTo(1); - } - } - - @Test - void getOkSpans_noSpans() { - /* getOkSpans should return an empty List */ - assertThat(dataAggregator.getOkSpans(SPAN_NAME_ONE, 0, Long.MAX_VALUE)).isEmpty(); - assertThat(dataAggregator.getOkSpans(SPAN_NAME_TWO, 0, Long.MAX_VALUE)).isEmpty(); - } - - @Test - void getOkSpans_oneSpanNameWithDifferentLatencies() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - /* getOkSpans should return an empty List */ - assertThat(dataAggregator.getOkSpans(SPAN_NAME_ONE, 0, Long.MAX_VALUE)).isEmpty(); - span1.end(); - testClock.advance(Duration.ofNanos(1000)); - span2.end(); - /* getOkSpans should return a List with both spans */ - List spans = dataAggregator.getOkSpans(SPAN_NAME_ONE, 0, Long.MAX_VALUE); - assertThat(spans) - .containsExactly(((ReadableSpan) span1).toSpanData(), ((ReadableSpan) span2).toSpanData()); - /* getOkSpans should return a List with only the first span */ - spans = dataAggregator.getOkSpans(SPAN_NAME_ONE, 0, 1000); - assertThat(spans).containsExactly(((ReadableSpan) span1).toSpanData()); - /* getOkSpans should return a List with only the second span */ - spans = dataAggregator.getOkSpans(SPAN_NAME_ONE, 1000, Long.MAX_VALUE); - assertThat(spans).containsExactly(((ReadableSpan) span2).toSpanData()); - } - - @Test - void getOkSpans_twoSpanNames() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - /* getOkSpans should return an empty List for each span name */ - assertThat(dataAggregator.getOkSpans(SPAN_NAME_ONE, 0, Long.MAX_VALUE)).isEmpty(); - assertThat(dataAggregator.getOkSpans(SPAN_NAME_TWO, 0, Long.MAX_VALUE)).isEmpty(); - span1.end(); - span2.end(); - /* getOkSpans should return a List with only the corresponding span */ - assertThat(dataAggregator.getOkSpans(SPAN_NAME_ONE, 0, Long.MAX_VALUE)) - .containsExactly(((ReadableSpan) span1).toSpanData()); - assertThat(dataAggregator.getOkSpans(SPAN_NAME_TWO, 0, Long.MAX_VALUE)) - .containsExactly(((ReadableSpan) span2).toSpanData()); - } - - @Test - void getErrorSpanCounts_noSpans() { - Map counts = dataAggregator.getErrorSpanCounts(); - assertThat(counts).isEmpty(); - } - - @Test - void getErrorSpanCounts_noCompletedSpans() { - /* getErrorSpanCounts should return a an empty map */ - Span span = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Map counts = dataAggregator.getErrorSpanCounts(); - span.setStatus(StatusCode.ERROR); - span.end(); - assertThat(counts).isEmpty(); - } - - @Test - void getErrorSpanCounts_oneSpanPerErrorCode() { - for (StatusCode errorCode : StatusCode.values()) { - if (errorCode.equals(StatusCode.ERROR)) { - Span span = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - span.setStatus(errorCode); - span.end(); - } - } - Map errorCounts = dataAggregator.getErrorSpanCounts(); - assertThat(errorCounts.get(SPAN_NAME_ONE)).isEqualTo(1); - } - - @Test - void getErrorSpanCounts_twoSpanNames() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - span1.setStatus(StatusCode.ERROR); - span1.end(); - Span span2 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - span2.setStatus(StatusCode.ERROR); - span2.end(); - /* getErrorSpanCounts should return a map with 2 different span names */ - Map errorCounts = dataAggregator.getErrorSpanCounts(); - assertThat(errorCounts.get(SPAN_NAME_ONE)).isEqualTo(1); - assertThat(errorCounts.get(SPAN_NAME_TWO)).isEqualTo(1); - } - - @Test - void getErrorSpans_noSpans() { - /* getErrorSpans should return an empty List */ - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_ONE)).isEmpty(); - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_TWO)).isEmpty(); - } - - @Test - void getErrorSpans_oneSpanNameWithDifferentErrors() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - /* getErrorSpans should return an empty List */ - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_ONE)).isEmpty(); - span1.setStatus(StatusCode.ERROR); - span1.end(); - span2.setStatus(StatusCode.ERROR, "ABORTED"); - span2.end(); - /* getErrorSpans should return a List with both spans */ - List errorSpans = dataAggregator.getErrorSpans(SPAN_NAME_ONE); - assertThat(errorSpans) - .containsExactly(((ReadableSpan) span1).toSpanData(), ((ReadableSpan) span2).toSpanData()); - } - - @Test - void getErrorSpans_twoSpanNames() { - Span span1 = tracer.spanBuilder(SPAN_NAME_ONE).startSpan(); - Span span2 = tracer.spanBuilder(SPAN_NAME_TWO).startSpan(); - /* getErrorSpans should return an empty List for each span name */ - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_ONE)).isEmpty(); - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_TWO)).isEmpty(); - span1.setStatus(StatusCode.ERROR); - span1.end(); - span2.setStatus(StatusCode.ERROR); - span2.end(); - /* getErrorSpans should return a List with only the corresponding span */ - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_ONE)) - .containsExactly(((ReadableSpan) span1).toSpanData()); - assertThat(dataAggregator.getErrorSpans(SPAN_NAME_TWO)) - .containsExactly(((ReadableSpan) span2).toSpanData()); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezSpanProcessorTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezSpanProcessorTest.java deleted file mode 100644 index 044ad5621bf..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezSpanProcessorTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.SpanId; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.trace.ReadWriteSpan; -import io.opentelemetry.sdk.trace.ReadableSpan; -import io.opentelemetry.sdk.trace.data.SpanData; -import io.opentelemetry.sdk.trace.data.StatusData; -import java.util.Collection; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; - -/** Unit tests for {@link TracezSpanProcessor}. */ -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.LENIENT) -class TracezSpanProcessorTest { - private static final String SPAN_NAME = "span"; - private static final SpanContext SAMPLED_SPAN_CONTEXT = - SpanContext.create( - TraceId.getInvalid(), - SpanId.getInvalid(), - TraceFlags.getSampled(), - TraceState.getDefault()); - private static final SpanContext NOT_SAMPLED_SPAN_CONTEXT = SpanContext.getInvalid(); - private static final StatusData SPAN_STATUS = StatusData.error(); - - private static void assertSpanCacheSizes( - TracezSpanProcessor spanProcessor, int runningSpanCacheSize, int completedSpanCacheSize) { - Collection runningSpans = spanProcessor.getRunningSpans(); - Collection completedSpans = spanProcessor.getCompletedSpans(); - assertThat(runningSpans.size()).isEqualTo(runningSpanCacheSize); - assertThat(completedSpans.size()).isEqualTo(completedSpanCacheSize); - } - - @Mock private ReadableSpan readableSpan; - @Mock private ReadWriteSpan readWriteSpan; - @Mock private SpanData spanData; - - @Test - void onStart_sampledSpan_inCache() { - TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - /* Return a sampled span, which should be added to the running cache by default */ - when(readWriteSpan.getSpanContext()).thenReturn(SAMPLED_SPAN_CONTEXT); - spanProcessor.onStart(Context.root(), readWriteSpan); - assertSpanCacheSizes(spanProcessor, 1, 0); - } - - @Test - void onEnd_sampledSpan_inCache() { - TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - /* Return a sampled span, which should be added to the completed cache upon ending */ - when(readWriteSpan.getSpanContext()).thenReturn(SAMPLED_SPAN_CONTEXT); - when(readWriteSpan.getName()).thenReturn(SPAN_NAME); - spanProcessor.onStart(Context.root(), readWriteSpan); - - when(readableSpan.getSpanContext()).thenReturn(SAMPLED_SPAN_CONTEXT); - when(readableSpan.getName()).thenReturn(SPAN_NAME); - when(readableSpan.toSpanData()).thenReturn(spanData); - when(spanData.getStatus()).thenReturn(SPAN_STATUS); - spanProcessor.onEnd(readableSpan); - assertSpanCacheSizes(spanProcessor, 0, 1); - } - - @Test - void onStart_notSampledSpan_inCache() { - TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - /* Return a non-sampled span, which should not be added to the running cache by default */ - when(readWriteSpan.getSpanContext()).thenReturn(NOT_SAMPLED_SPAN_CONTEXT); - spanProcessor.onStart(Context.root(), readWriteSpan); - assertSpanCacheSizes(spanProcessor, 1, 0); - } - - @Test - void onEnd_notSampledSpan_notInCache() { - TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - /* Return a non-sampled span, which should not be added to the running cache by default */ - when(readWriteSpan.getSpanContext()).thenReturn(NOT_SAMPLED_SPAN_CONTEXT); - when(readableSpan.getSpanContext()).thenReturn(NOT_SAMPLED_SPAN_CONTEXT); - spanProcessor.onStart(Context.root(), readWriteSpan); - spanProcessor.onEnd(readableSpan); - assertSpanCacheSizes(spanProcessor, 0, 0); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezZPageHandlerTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezZPageHandlerTest.java deleted file mode 100644 index e67691f3322..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/TracezZPageHandlerTest.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static com.google.common.net.UrlEscapers.urlFormParameterEscaper; -import static org.assertj.core.api.Assertions.assertThat; - -import com.google.common.collect.ImmutableMap; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.StatusCode; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.testing.time.TestClock; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import java.io.ByteArrayOutputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; - -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.LENIENT) -class TracezZPageHandlerTest { - private static final String FINISHED_SPAN_ONE = "FinishedSpanOne"; - private static final String FINISHED_SPAN_TWO = "FinishedSpanTwo"; - private static final String WEIRD_SPAN = "Weird \"' & 1 < 3 \""; - private static final String RUNNING_SPAN = "RunningSpan"; - private static final String LATENCY_SPAN = "LatencySpan"; - private static final String ERROR_SPAN = "ErrorSpan"; - private static final String EVENT = "event on a span"; - private final TestClock testClock = TestClock.create(); - private final TracezSpanProcessor spanProcessor = TracezSpanProcessor.builder().build(); - private final SdkTracerProvider sdkTracerProvider = - SdkTracerProvider.builder().setClock(testClock).addSpanProcessor(spanProcessor).build(); - private final Tracer tracer = sdkTracerProvider.get("TracezZPageHandlerTest"); - private final TracezDataAggregator dataAggregator = new TracezDataAggregator(spanProcessor); - private final Map emptyQueryMap = ImmutableMap.of(); - - @Test - void summaryTable_emitRowForEachSpan() { - OutputStream output = new ByteArrayOutputStream(); - tracer.spanBuilder(FINISHED_SPAN_ONE).startSpan().end(); - tracer.spanBuilder(FINISHED_SPAN_TWO).startSpan().end(); - tracer.spanBuilder(WEIRD_SPAN).startSpan().end(); - - Span runningSpan = tracer.spanBuilder(RUNNING_SPAN).startSpan(); - - Span latencySpan = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan.end(10002, TimeUnit.NANOSECONDS); - - Span errorSpan = tracer.spanBuilder(ERROR_SPAN).startSpan(); - errorSpan.setStatus(StatusCode.ERROR); - errorSpan.end(); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(emptyQueryMap, output); - - String result = output.toString(); - // Emit a row for all types of spans. - assertThat(result).contains(FINISHED_SPAN_ONE); - assertThat(result).contains(FINISHED_SPAN_TWO); - assertThat(result).contains("Weird"' & 1 < 3 ""); - assertThat(result).contains(RUNNING_SPAN); - assertThat(result).contains(LATENCY_SPAN); - assertThat(result).contains(ERROR_SPAN); - - runningSpan.end(); - } - - @Test - void summaryTable_linkForRunningSpans() { - OutputStream output = new ByteArrayOutputStream(); - Span runningSpan1 = tracer.spanBuilder(RUNNING_SPAN).startSpan(); - Span runningSpan2 = tracer.spanBuilder(RUNNING_SPAN).startSpan(); - Span runningSpan3 = tracer.spanBuilder(RUNNING_SPAN).startSpan(); - Span finishedSpan = tracer.spanBuilder(FINISHED_SPAN_ONE).startSpan(); - finishedSpan.end(); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(emptyQueryMap, output); - - // Link for running span with 3 running - assertThat(output.toString()) - .contains("href=\"?zspanname=" + RUNNING_SPAN + "&ztype=0&zsubtype=0\">3"); - // No link for finished spans - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + FINISHED_SPAN_ONE + "&ztype=0&subtype=0\""); - - runningSpan1.end(); - runningSpan2.end(); - runningSpan3.end(); - } - - @Test - void summaryTable_linkForLatencyBasedSpans_NoneForEmptyBoundary() { - OutputStream output = new ByteArrayOutputStream(); - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(emptyQueryMap, output); - - // No link for boundary 0 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=0\""); - // No link for boundary 1 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=1\""); - // No link for boundary 2 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=2\""); - // No link for boundary 3 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=3\""); - // No link for boundary 4 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=4\""); - // No link for boundary 5 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=5\""); - // No link for boundary 6 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=6\""); - // No link for boundary 7 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=7\""); - // No link for boundary 8 - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=8\""); - } - - @Test - void summaryTable_linkForLatencyBasedSpans_OnePerBoundary() { - OutputStream output = new ByteArrayOutputStream(); - // Boundary 0, >1us - Span latencySpanSubtype0 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype0.end(1002, TimeUnit.NANOSECONDS); - // Boundary 1, >10us - Span latencySpanSubtype1 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype1.end(10002, TimeUnit.NANOSECONDS); - // Boundary 2, >100us - Span latencySpanSubtype2 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype2.end(100002, TimeUnit.NANOSECONDS); - // Boundary 3, >1ms - Span latencySpanSubtype3 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype3.end(1000002, TimeUnit.NANOSECONDS); - // Boundary 4, >10ms - Span latencySpanSubtype4 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype4.end(10000002, TimeUnit.NANOSECONDS); - // Boundary 5, >100ms - Span latencySpanSubtype5 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype5.end(100000002, TimeUnit.NANOSECONDS); - // Boundary 6, >1s - Span latencySpanSubtype6 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype6.end(1000000002, TimeUnit.NANOSECONDS); - // Boundary 7, >10s - Span latencySpanSubtype7 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype7.end(10000000002L, TimeUnit.NANOSECONDS); - // Boundary 8, >100s - Span latencySpanSubtype8 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpanSubtype8.end(100000000002L, TimeUnit.NANOSECONDS); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(emptyQueryMap, output); - - // Link for boundary 0 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=0\">1"); - // Link for boundary 1 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=1\">1"); - // Link for boundary 2 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=2\">1"); - // Link for boundary 3 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=3\">1"); - // Link for boundary 4 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=4\">1"); - // Link for boundary 5 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=5\">1"); - // Link for boundary 6 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=6\">1"); - // Link for boundary 7 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=7\">1"); - // Link for boundary 8 - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=8\">1"); - } - - @Test - void summaryTable_linkForLatencyBasedSpans_MultipleForOneBoundary() { - OutputStream output = new ByteArrayOutputStream(); - // 4 samples in boundary 5, >100ms - Span latencySpan100ms1 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan100ms1.end(112931232L, TimeUnit.NANOSECONDS); - Span latencySpan100ms2 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan100ms2.end(138694322L, TimeUnit.NANOSECONDS); - Span latencySpan100ms3 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan100ms3.end(154486482L, TimeUnit.NANOSECONDS); - Span latencySpan100ms4 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan100ms4.end(194892582L, TimeUnit.NANOSECONDS); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(emptyQueryMap, output); - - // Link for boundary 5 with 4 samples - assertThat(output.toString()) - .contains("href=\"?zspanname=" + LATENCY_SPAN + "&ztype=1&zsubtype=5\">4"); - } - - @Test - void summaryTable_linkForErrorSpans() { - OutputStream output = new ByteArrayOutputStream(); - Span errorSpan1 = tracer.spanBuilder(ERROR_SPAN).startSpan(); - Span errorSpan2 = tracer.spanBuilder(ERROR_SPAN).startSpan(); - Span errorSpan3 = tracer.spanBuilder(ERROR_SPAN).startSpan(); - Span finishedSpan = tracer.spanBuilder(FINISHED_SPAN_ONE).startSpan(); - errorSpan1.setStatus(StatusCode.ERROR, "CANCELLED"); - errorSpan2.setStatus(StatusCode.ERROR, "ABORTED"); - errorSpan3.setStatus(StatusCode.ERROR, "DEADLINE_EXCEEDED"); - errorSpan1.end(); - errorSpan2.end(); - errorSpan3.end(); - finishedSpan.end(); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(emptyQueryMap, output); - - // Link for error based spans with 3 samples - assertThat(output.toString()) - .contains("href=\"?zspanname=" + ERROR_SPAN + "&ztype=2&zsubtype=0\">3"); - // No link for Status{#OK} spans - assertThat(output.toString()) - .doesNotContain("href=\"?zspanname=" + FINISHED_SPAN_ONE + "&ztype=2&subtype=0\""); - } - - @Test - void spanDetails_emitRunningSpanDetailsCorrectly() { - OutputStream output = new ByteArrayOutputStream(); - Span runningSpan = tracer.spanBuilder(RUNNING_SPAN).startSpan().addEvent(EVENT); - Map queryMap = - ImmutableMap.of("zspanname", RUNNING_SPAN, "ztype", "0", "zsubtype", "0"); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(queryMap, output); - - String result = output.toString(); - assertThat(result).contains("

      Span Details

      "); - assertThat(result).contains(" Span Name: " + RUNNING_SPAN + ""); - assertThat(result).contains(" Number of running: 1"); - assertThat(result).contains(runningSpan.getSpanContext().getTraceId()); - assertThat(result).contains(runningSpan.getSpanContext().getSpanId()); - assertThat(result).contains(EVENT); - - runningSpan.end(); - } - - @Test - void spanDetails_emitLatencySpanDetailsCorrectly() { - OutputStream output = new ByteArrayOutputStream(); - Span latencySpan1 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan1.end(10002, TimeUnit.NANOSECONDS); - Span latencySpan2 = - tracer.spanBuilder(LATENCY_SPAN).setStartTimestamp(1L, TimeUnit.NANOSECONDS).startSpan(); - latencySpan2.end(10002, TimeUnit.NANOSECONDS); - Map queryMap = - ImmutableMap.of("zspanname", LATENCY_SPAN, "ztype", "1", "zsubtype", "1"); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(queryMap, output); - - assertThat(output.toString()).contains("

      Span Details

      "); - assertThat(output.toString()).contains(" Span Name: " + LATENCY_SPAN + ""); - assertThat(output.toString()).contains(" Number of latency samples: 2"); - assertThat(output.toString()).contains(latencySpan1.getSpanContext().getTraceId()); - assertThat(output.toString()).contains(latencySpan1.getSpanContext().getSpanId()); - assertThat(output.toString()).contains(latencySpan2.getSpanContext().getTraceId()); - assertThat(output.toString()).contains(latencySpan2.getSpanContext().getSpanId()); - } - - @Test - void spanDetails_emitErrorSpanDetailsCorrectly() { - OutputStream output = new ByteArrayOutputStream(); - Span errorSpan1 = tracer.spanBuilder(ERROR_SPAN).startSpan(); - Span errorSpan2 = tracer.spanBuilder(ERROR_SPAN).startSpan(); - errorSpan1.setStatus(StatusCode.ERROR, "CANCELLED"); - errorSpan2.setStatus(StatusCode.ERROR, "ABORTED"); - errorSpan1.end(); - errorSpan2.end(); - Map queryMap = - ImmutableMap.of("zspanname", ERROR_SPAN, "ztype", "2", "zsubtype", "0"); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(queryMap, output); - - assertThat(output.toString()).contains("

      Span Details

      "); - assertThat(output.toString()).contains(" Span Name: " + ERROR_SPAN + ""); - assertThat(output.toString()).contains(" Number of error samples: 2"); - assertThat(output.toString()).contains(errorSpan1.getSpanContext().getTraceId()); - assertThat(output.toString()).contains(errorSpan1.getSpanContext().getSpanId()); - assertThat(output.toString()).contains(errorSpan2.getSpanContext().getTraceId()); - assertThat(output.toString()).contains(errorSpan2.getSpanContext().getSpanId()); - } - - @Test - void spanDetails_shouldNotBreakOnUnknownType() { - OutputStream output = new ByteArrayOutputStream(); - Map queryMap = - ImmutableMap.of("zspanname", "Span", "ztype", "-1", "zsubtype", "0"); - - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - tracezZPageHandler.emitHtml(queryMap, output); - - assertThat(output.toString()).doesNotContain("

      Span Details

      "); - assertThat(output.toString()).doesNotContain(" Span Name: Span"); - } - - private static Map generateQueryMap(String spanName, String type, String subtype) - throws URISyntaxException { - return ZPageHttpHandler.parseQueryString( - new URI( - "tracez?zspanname=" - + urlFormParameterEscaper().escape(spanName) - + "&ztype=" - + type - + "&zsubtype=" - + subtype) - .getRawQuery()); - } - - @Test - void spanDetails_emitNameWithSpaceCorrectly() - throws UnsupportedEncodingException, URISyntaxException { - OutputStream output = new ByteArrayOutputStream(); - String nameWithSpace = "SPAN NAME"; - Span runningSpan = tracer.spanBuilder(nameWithSpace).startSpan(); - tracer.spanBuilder(nameWithSpace).startSpan().end(); - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - - tracezZPageHandler.emitHtml(generateQueryMap(nameWithSpace, "0", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithSpace + ""); - assertThat(output.toString()).contains(" Number of running: 1"); - tracezZPageHandler.emitHtml(generateQueryMap(nameWithSpace, "1", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithSpace + ""); - assertThat(output.toString()).contains(" Number of latency samples: 1"); - - runningSpan.end(); - } - - @Test - void spanDetails_emitNameWithPlusCorrectly() - throws UnsupportedEncodingException, URISyntaxException { - OutputStream output = new ByteArrayOutputStream(); - String nameWithPlus = "SPAN+NAME"; - Span runningSpan = tracer.spanBuilder(nameWithPlus).startSpan(); - tracer.spanBuilder(nameWithPlus).startSpan().end(); - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - - tracezZPageHandler.emitHtml(generateQueryMap(nameWithPlus, "0", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithPlus + ""); - assertThat(output.toString()).contains(" Number of running: 1"); - tracezZPageHandler.emitHtml(generateQueryMap(nameWithPlus, "1", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithPlus + ""); - assertThat(output.toString()).contains(" Number of latency samples: 1"); - - runningSpan.end(); - } - - @Test - void spanDetails_emitNamesWithSpaceAndPlusCorrectly() - throws UnsupportedEncodingException, URISyntaxException { - OutputStream output = new ByteArrayOutputStream(); - String nameWithSpaceAndPlus = "SPAN + NAME"; - Span runningSpan = tracer.spanBuilder(nameWithSpaceAndPlus).startSpan(); - tracer.spanBuilder(nameWithSpaceAndPlus).startSpan().end(); - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - - tracezZPageHandler.emitHtml(generateQueryMap(nameWithSpaceAndPlus, "0", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithSpaceAndPlus + ""); - assertThat(output.toString()).contains(" Number of running: 1"); - tracezZPageHandler.emitHtml(generateQueryMap(nameWithSpaceAndPlus, "1", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithSpaceAndPlus + ""); - assertThat(output.toString()).contains(" Number of latency samples: 1"); - - runningSpan.end(); - } - - @Test - void spanDetails_emitNamesWithSpecialUrlCharsCorrectly() - throws UnsupportedEncodingException, URISyntaxException { - OutputStream output = new ByteArrayOutputStream(); - String nameWithUrlChars = "{SPAN/NAME}"; - Span runningSpan = tracer.spanBuilder(nameWithUrlChars).startSpan(); - tracer.spanBuilder(nameWithUrlChars).startSpan().end(); - TracezZPageHandler tracezZPageHandler = new TracezZPageHandler(dataAggregator); - - tracezZPageHandler.emitHtml(generateQueryMap(nameWithUrlChars, "0", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithUrlChars + ""); - assertThat(output.toString()).contains(" Number of running: 1"); - tracezZPageHandler.emitHtml(generateQueryMap(nameWithUrlChars, "1", "0"), output); - assertThat(output.toString()).contains(" Span Name: " + nameWithUrlChars + ""); - assertThat(output.toString()).contains(" Number of latency samples: 1"); - - runningSpan.end(); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/ZPageHttpHandlerTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/ZPageHttpHandlerTest.java deleted file mode 100644 index 2ac3f419520..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/ZPageHttpHandlerTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.entry; - -import java.io.UnsupportedEncodingException; -import java.net.URI; -import java.net.URISyntaxException; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link ZPageHttpHandler}. */ -public final class ZPageHttpHandlerTest { - @Test - void parseEmptyQuery() throws URISyntaxException, UnsupportedEncodingException { - URI uri = new URI("http://localhost:8000/tracez"); - String queryString = ""; - assertThat(ZPageHttpHandler.parseQueryString(uri.getRawQuery())).isEmpty(); - assertThat(ZPageHttpHandler.parseQueryString(queryString)).isEmpty(); - } - - @Test - void parseNormalQuery() throws URISyntaxException, UnsupportedEncodingException { - URI uri = - new URI("http://localhost:8000/tracez/tracez?zspanname=Test&ztype=1&zsubtype=5&noval"); - String queryString = "zspanname=Test&ztype=1&zsubtype=5&noval"; - assertThat(ZPageHttpHandler.parseQueryString(uri.getRawQuery())) - .containsOnly(entry("zspanname", "Test"), entry("ztype", "1"), entry("zsubtype", "5")); - assertThat(ZPageHttpHandler.parseQueryString(queryString)) - .containsOnly(entry("zspanname", "Test"), entry("ztype", "1"), entry("zsubtype", "5")); - } -} diff --git a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/ZPageServerTest.java b/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/ZPageServerTest.java deleted file mode 100644 index c844a63f8a3..00000000000 --- a/sdk-extensions/zpages/src/test/java/io/opentelemetry/sdk/extension/zpages/ZPageServerTest.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.extension.zpages; - -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.jupiter.api.Test; - -class ZPageServerTest { - - @Test - void spanProcessor() { - assertThat(ZPageServer.getSpanProcessor()).isInstanceOf(TracezSpanProcessor.class); - } - - @Test - void traceConfigSupplier() { - assertThat(ZPageServer.getTracezTraceConfigSupplier()) - .isInstanceOf(TracezTraceConfigSupplier.class); - } - - @Test - void testSampler() { - assertThat(ZPageServer.getTracezSampler()).isInstanceOf(TracezTraceConfigSupplier.class); - } -} diff --git a/sdk/all/README.md b/sdk/all/README.md deleted file mode 100644 index 9ee9006a4b0..00000000000 --- a/sdk/all/README.md +++ /dev/null @@ -1,13 +0,0 @@ -OpenTelemetry SDK -====================================================== - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk - ---- -#### Running micro-benchmarks -From the root of the repo run `./gradlew clean :opentelemetry-sdk:jmh` to run all the benchmarks -or run `./gradlew clean :opentelemetry-sdk:jmh -PjmhIncludeSingleClass=` -to run a specific benchmark class. diff --git a/sdk/all/build.gradle.kts b/sdk/all/build.gradle.kts index 2aa81a4300b..5ef583575dc 100644 --- a/sdk/all/build.gradle.kts +++ b/sdk/all/build.gradle.kts @@ -8,21 +8,42 @@ plugins { description = "OpenTelemetry SDK" otelJava.moduleName.set("io.opentelemetry.sdk") +otelJava.requireSuppressWarningsExplanation.set(false) base.archivesName.set("opentelemetry-sdk") +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) dependencies { api(project(":api:all")) api(project(":sdk:common")) api(project(":sdk:trace")) api(project(":sdk:metrics")) + api(project(":sdk:logs")) - // implementation dependency to require users to add the artifact directly to their build to use - // SdkLogEmitterProvider. - implementation(project(":sdk:logs")) + compileOnly(project(":api:incubator")) annotationProcessor("com.google.auto.value:auto-value") testAnnotationProcessor("com.google.auto.value:auto-value") testImplementation(project(":sdk:testing")) + + jmh(project(":sdk:testing")) + jmh(project(":api:incubator")) +} + +testing { + suites { + register("testIncubating") { + dependencies { + implementation(project(":api:incubator")) + implementation(project(":sdk:testing")) + } + } + } +} + +tasks { + check { + dependsOn(testing.suites) + } } diff --git a/sdk/all/src/jmh/java/io/opentelemetry/sdk/BenchmarkUtils.java b/sdk/all/src/jmh/java/io/opentelemetry/sdk/BenchmarkUtils.java new file mode 100644 index 00000000000..106f22afea9 --- /dev/null +++ b/sdk/all/src/jmh/java/io/opentelemetry/sdk/BenchmarkUtils.java @@ -0,0 +1,17 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk; + +public class BenchmarkUtils { + + private BenchmarkUtils() {} + + /** + * The number of record operations per benchmark invocation. By using a constant across benchmarks + * of different signals, it's easier to compare benchmark results across signals. + */ + public static final int RECORDS_PER_INVOCATION = 1024 * 10; +} diff --git a/sdk/all/src/jmh/java/io/opentelemetry/sdk/LogRecordBenchmark.java b/sdk/all/src/jmh/java/io/opentelemetry/sdk/LogRecordBenchmark.java new file mode 100644 index 00000000000..a704ecd8621 --- /dev/null +++ b/sdk/all/src/jmh/java/io/opentelemetry/sdk/LogRecordBenchmark.java @@ -0,0 +1,176 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.incubator.logs.ExtendedLogRecordBuilder; +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.GroupThreads; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.OperationsPerInvocation; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Warmup; + +/** + * This benchmark measures the performance of recording log records. It includes the following + * dimensions: + * + *
        + *
      • {@link BenchmarkState#logSize}: the size of the log record, which is a composite of the + * number of attributes, length of body, and whether an exception is attached to the log + * record. + *
      + * + *

      Each operation consists of recording {@link LogRecordBenchmark#RECORDS_PER_INVOCATION} log + * records. + * + *

      In order to isolate the record path while remaining realistic, the benchmark uses a {@link + * BatchLogRecordProcessor} paired with a noop {@link LogRecordExporter}. In order to avoid quickly + * outpacing the batch processor queue and dropping log records, the processor is configured with a + * queue size of {@link LogRecordBenchmark#RECORDS_PER_INVOCATION} * {@link + * LogRecordBenchmark#MAX_THREADS} and is flushed after each invocation. + */ +public class LogRecordBenchmark { + + private static final int RECORDS_PER_INVOCATION = BenchmarkUtils.RECORDS_PER_INVOCATION; + private static final int MAX_THREADS = 4; + private static final int QUEUE_SIZE = RECORDS_PER_INVOCATION * MAX_THREADS; + + @State(Scope.Benchmark) + public static class BenchmarkState { + + // The size of the log record, dictated by the number of attributes attached to it. + @Param LogRecordSize logSize; + + SdkLoggerProvider loggerProvider; + Logger logger; + long timestampNanos = Clock.getDefault().now(); + List> attributeKeys; + List attributeValues; + String body; + @Nullable Throwable exception; + + @Setup + public void setup() { + loggerProvider = + SdkLoggerProvider.builder() + // Configure a batch processor with a noop exporter (LogRecordExporter.composite() is + // a shortcut for a noop exporter). This allows testing the throughput / performance + // impact of BatchLogRecordProcessor, which is essential for real workloads, while + // avoiding noise from LogRecordExporters whose performance is subject to + // implementation and network details. + .addLogRecordProcessor( + BatchLogRecordProcessor.builder(LogRecordExporter.composite()) + .setMaxQueueSize(QUEUE_SIZE) + .build()) + .build(); + logger = loggerProvider.get("benchmark"); + + attributeKeys = new ArrayList<>(logSize.attributes); + attributeValues = new ArrayList<>(logSize.attributes); + for (int i = 0; i < logSize.attributes; i++) { + attributeKeys.add(AttributeKey.stringKey("key" + i)); + attributeValues.add("value" + i); + } + + body = randomString(logSize.bodyChars); + + exception = logSize.hasException ? new Exception("test exception") : null; + } + + @TearDown(Level.Invocation) + public void flush() { + loggerProvider.forceFlush().join(10, TimeUnit.SECONDS); + } + + @TearDown + public void tearDown() { + loggerProvider.shutdown(); + } + } + + @Benchmark + @Group("threads1") + @GroupThreads(1) + @Fork(3) + @Warmup(iterations = 3, time = 1) + @Measurement(iterations = 10, time = 1) + @OperationsPerInvocation(RECORDS_PER_INVOCATION) + public void record_SingleThread(BenchmarkState benchmarkState) { + record(benchmarkState); + } + + @Benchmark + @Group("threads" + MAX_THREADS) + @GroupThreads(MAX_THREADS) + @Fork(3) + @Warmup(iterations = 3, time = 1) + @Measurement(iterations = 10, time = 1) + @OperationsPerInvocation(RECORDS_PER_INVOCATION) + public void record_MultipleThreads(BenchmarkState benchmarkState) { + record(benchmarkState); + } + + private static void record(BenchmarkState benchmarkState) { + for (int i = 0; i < RECORDS_PER_INVOCATION; i++) { + LogRecordBuilder builder = + benchmarkState + .logger + .logRecordBuilder() + .setTimestamp(benchmarkState.timestampNanos, TimeUnit.NANOSECONDS); + for (int j = 0; j < benchmarkState.attributeKeys.size(); j++) { + builder.setAttribute( + benchmarkState.attributeKeys.get(j), benchmarkState.attributeValues.get(j)); + } + if (benchmarkState.exception != null) { + ((ExtendedLogRecordBuilder) builder).setException(benchmarkState.exception); + } + builder.setBody(benchmarkState.body); + builder.emit(); + } + } + + public enum LogRecordSize { + SMALL(0, 0, /* hasException= */ false), + MEDIUM(10, 100, /* hasException= */ false), + LARGE(100, 10000, /* hasException= */ true); + + private final int attributes; + private final int bodyChars; + private final boolean hasException; + + LogRecordSize(int attributes, int bodyChars, boolean hasException) { + this.attributes = attributes; + this.bodyChars = bodyChars; + this.hasException = hasException; + } + } + + private static String randomString(int length) { + StringBuilder sb = new StringBuilder(length); + for (int i = 0; i < length; i++) { + sb.append((char) ('a' + (int) (Math.random() * 26))); + } + return sb.toString(); + } +} diff --git a/sdk/all/src/jmh/java/io/opentelemetry/sdk/MetricRecordBenchmark.java b/sdk/all/src/jmh/java/io/opentelemetry/sdk/MetricRecordBenchmark.java new file mode 100644 index 00000000000..400abbbd58e --- /dev/null +++ b/sdk/all/src/jmh/java/io/opentelemetry/sdk/MetricRecordBenchmark.java @@ -0,0 +1,436 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk; + +import static io.opentelemetry.sdk.metrics.InstrumentType.COUNTER; +import static io.opentelemetry.sdk.metrics.InstrumentType.GAUGE; +import static io.opentelemetry.sdk.metrics.InstrumentType.HISTOGRAM; +import static io.opentelemetry.sdk.metrics.InstrumentType.UP_DOWN_COUNTER; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundDoubleCounter; +import io.opentelemetry.api.incubator.metrics.BoundDoubleGauge; +import io.opentelemetry.api.incubator.metrics.BoundDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.BoundDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.BoundLongCounter; +import io.opentelemetry.api.incubator.metrics.BoundLongGauge; +import io.opentelemetry.api.incubator.metrics.BoundLongHistogram; +import io.opentelemetry.api.incubator.metrics.BoundLongUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.ExemplarFilter; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.InstrumentValueType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Random; +import java.util.concurrent.atomic.AtomicInteger; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.GroupThreads; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.OperationsPerInvocation; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Warmup; + +/** + * This benchmark measures the performance of recording metrics. It includes the following + * dimensions: + * + *

        + *
      • {@link BenchmarkState#instrumentTypeAndAggregation} composite of {@link InstrumentType} and + * {@link Aggregation}, including all relevant combinations for synchronous instruments. + *
      • {@link BenchmarkState#aggregationTemporality} + *
      • {@link BenchmarkState#cardinality} + *
      • {@link BenchmarkState#bound} whether recording goes through bound instruments ({@code + * Extended*#bind(Attributes)}) or unbound instruments. + *
      • thread count + *
      • {@link BenchmarkState#instrumentValueType}, {@link BenchmarkState#memoryMode}, and {@link + * BenchmarkState#exemplars} are disabled to reduce combinatorial explosion. + *
      + * + *

      Each operation consists of recording {@link MetricRecordBenchmark#RECORDS_PER_INVOCATION} + * measurements. + * + *

      The cardinality and thread count dimensions partially overlap. Cardinality dictates how many + * unique attribute sets (i.e. series) are recorded to, and thread count dictates how many threads + * are simultaneously recording to those series. For unbound instruments, the record path looks up + * an aggregation handle for the series corresponding to the measurement's {@link Attributes} in a + * {@link java.util.concurrent.ConcurrentHashMap}; for bound instruments ({@link + * BenchmarkState#bound}) that handle is resolved once at bind time, so the record path skips the + * lookup and attribute processing entirely. The cardinality dictates the size of this map, which + * has some impact on performance. However, by far the dominant bottleneck is contention. That is, + * the number of threads simultaneously trying to record to the same series. Increasing the threads + * increases contention. Increasing cardinality decreases contention, as the threads are now + * spreading their record activities over more distinct series. The highest contention scenario is + * cardinality=1, threads=4. Any scenario with threads=1 has zero contention. + * + *

      It's useful to characterize the performance of the metrics system under contention, as some + * high-performance applications may have many threads trying to record to the same series. It's + * also useful to characterize the performance of the metrics system under low contention, as some + * high-performance applications may not frequently be trying to concurrently record to the same + * series yet still care about the overhead of each record operation. + * + *

      {@link AggregationTemporality} can impact performance because additional concurrency controls + * are needed to ensure there are no duplicate, partial, or lost writes while resetting the set of + * timeseries each collection. + */ +public class MetricRecordBenchmark { + + private static final int INITIAL_SEED = 513423236; + private static final int MAX_THREADS = 4; + private static final int RECORDS_PER_INVOCATION = BenchmarkUtils.RECORDS_PER_INVOCATION; + + @State(Scope.Benchmark) + public static class BenchmarkState { + + @Param InstrumentTypeAndAggregation instrumentTypeAndAggregation; + + @Param AggregationTemporality aggregationTemporality; + + @Param({"1", "128"}) + int cardinality; + + // Whether to record through bound instruments (Extended*#bind(Attributes)), which resolve the + // timeseries once up front, or unbound instruments, which look up the timeseries by Attributes + // on every record. + @Param({"false", "true"}) + boolean bound; + + // The following parameters are excluded from the benchmark to reduce combinatorial explosion + // but can optionally be enabled for adhoc evaluation. + + // InstrumentValueType doesn't materially impact performance. Uncomment to evaluate. + // @Param + // InstrumentValueType instrumentValueType; + InstrumentValueType instrumentValueType = InstrumentValueType.LONG; + + // MemoryMode almost exclusively impacts collect from a performance standpoint. Uncomment to + // evaluate. + // @Param + // MemoryMode memoryMode; + MemoryMode memoryMode = MemoryMode.REUSABLE_DATA; + + // Exemplars can impact performance, but we skip evaluation to limit test cases. Uncomment to + // evaluate. + // @Param({"true", "false"}) + // boolean exemplars; + boolean exemplars = false; + + OpenTelemetrySdk openTelemetry; + // Populated when bound == false. + private Instrument instrument; + // Populated when bound == true; parallel to attributesList (one bound instrument per series). + private List boundInstruments; + List measurements; + List attributesList; + Span span; + io.opentelemetry.context.Scope contextScope; + // Hands out a distinct seed to each recording thread's ThreadState so threads traverse the + // series in independent orders (see ThreadState). + final AtomicInteger threadSeedSequence = new AtomicInteger(); + + @Setup + @SuppressWarnings("MustBeClosedChecker") + public void setup() { + InstrumentType instrumentType = instrumentTypeAndAggregation.instrumentType; + Aggregation aggregation = instrumentTypeAndAggregation.aggregation; + + openTelemetry = + OpenTelemetrySdk.builder() + .setTracerProvider(SdkTracerProvider.builder().setSampler(Sampler.alwaysOn()).build()) + .setMeterProvider( + SdkMeterProvider.builder() + .registerMetricReader( + InMemoryMetricReader.builder() + .setAggregationTemporalitySelector(unused -> aggregationTemporality) + .setDefaultAggregationSelector( + DefaultAggregationSelector.getDefault() + .with(instrumentType, aggregation)) + .setMemoryMode(memoryMode) + .build()) + .setExemplarFilter( + exemplars ? ExemplarFilter.traceBased() : ExemplarFilter.alwaysOff()) + .build()) + .build(); + + Meter meter = openTelemetry.getMeter("benchmark"); + Tracer tracer = openTelemetry.getTracer("benchmark"); + span = tracer.spanBuilder("benchmark").startSpan(); + // We suppress warnings on closing here, as we rely on tests to make sure context is closed. + contextScope = span.makeCurrent(); + + Random random = new Random(INITIAL_SEED); + attributesList = new ArrayList<>(cardinality); + AttributeKey key = AttributeKey.stringKey("key"); + String last = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; + for (int i = 0; i < cardinality; i++) { + char[] chars = last.toCharArray(); + chars[random.nextInt(last.length())] = (char) (random.nextInt(26) + 'a'); + last = new String(chars); + attributesList.add(Attributes.of(key, last)); + } + Collections.shuffle(attributesList); + + if (bound) { + boundInstruments = + bindInstruments(meter, instrumentType, instrumentValueType, attributesList); + } else { + instrument = getInstrument(meter, instrumentType, instrumentValueType); + } + + measurements = new ArrayList<>(RECORDS_PER_INVOCATION); + for (int i = 0; i < RECORDS_PER_INVOCATION; i++) { + measurements.add((long) random.nextInt(2000)); + } + Collections.shuffle(measurements); + } + + @TearDown + public void tearDown() { + contextScope.close(); + span.end(); + openTelemetry.shutdown(); + } + } + + /** + * Per-thread series traversal order. Each recording thread shuffles {@code [0, cardinality)} with + * a distinct seed, so that at any given record the threads are recording to different + * series rather than marching through the same series in lockstep. Without this, the shared + * sequential {@code i % cardinality} index plus contention's self-synchronizing effect collapses + * the high-cardinality, multi-thread cases into a single rotating hotspot (effectively + * cardinality=1 contention), which does not reflect real-world recording where independent + * threads touch arbitrary series. + */ + @State(Scope.Thread) + public static class ThreadState { + int[] order; + + @Setup + public void setup(BenchmarkState benchmarkState) { + int cardinality = benchmarkState.cardinality; + order = new int[cardinality]; + for (int i = 0; i < cardinality; i++) { + order[i] = i; + } + // Distinct seed per thread => independent permutations => no cross-thread lockstep. + Random random = + new Random(INITIAL_SEED + benchmarkState.threadSeedSequence.getAndIncrement()); + for (int i = cardinality - 1; i > 0; i--) { + int j = random.nextInt(i + 1); + int tmp = order[i]; + order[i] = order[j]; + order[j] = tmp; + } + } + } + + @Benchmark + @Group("threads1") + @GroupThreads(1) + @Fork(3) + @Warmup(iterations = 3, time = 1) + @Measurement(iterations = 10, time = 1) + @OperationsPerInvocation(RECORDS_PER_INVOCATION) + public void record_SingleThread(BenchmarkState benchmarkState, ThreadState threadState) { + record(benchmarkState, threadState); + } + + @Benchmark + @Group("threads" + MAX_THREADS) + @GroupThreads(MAX_THREADS) + @Fork(3) + @Warmup(iterations = 3, time = 1) + @Measurement(iterations = 10, time = 1) + @OperationsPerInvocation(RECORDS_PER_INVOCATION) + public void record_MultipleThreads(BenchmarkState benchmarkState, ThreadState threadState) { + record(benchmarkState, threadState); + } + + private static void record(BenchmarkState benchmarkState, ThreadState threadState) { + // Per-thread series order: at a given i, different threads hit different series (no lockstep). + int[] order = threadState.order; + if (benchmarkState.bound) { + // Bound: record straight to the pre-resolved bound instrument for the series β€” no per-record + // Attributes lookup. + List boundInstruments = benchmarkState.boundInstruments; + for (int i = 0; i < RECORDS_PER_INVOCATION; i++) { + long value = benchmarkState.measurements.get(i % benchmarkState.measurements.size()); + boundInstruments.get(order[i % order.length]).record(value); + } + } else { + for (int i = 0; i < RECORDS_PER_INVOCATION; i++) { + Attributes attributes = benchmarkState.attributesList.get(order[i % order.length]); + long value = benchmarkState.measurements.get(i % benchmarkState.measurements.size()); + benchmarkState.instrument.record(value, attributes); + } + } + } + + @SuppressWarnings("ImmutableEnumChecker") + public enum InstrumentTypeAndAggregation { + COUNTER_SUM(COUNTER, Aggregation.sum()), + UP_DOWN_COUNTER_SUM(UP_DOWN_COUNTER, Aggregation.sum()), + GAUGE_LAST_VALUE(GAUGE, Aggregation.lastValue()), + HISTOGRAM_EXPLICIT(HISTOGRAM, Aggregation.explicitBucketHistogram()), + HISTOGRAM_BASE2_EXPONENTIAL(HISTOGRAM, Aggregation.base2ExponentialBucketHistogram()); + + InstrumentTypeAndAggregation(InstrumentType instrumentType, Aggregation aggregation) { + this.instrumentType = instrumentType; + this.aggregation = aggregation; + } + + private final InstrumentType instrumentType; + private final Aggregation aggregation; + } + + private interface Instrument { + void record(long value, Attributes attributes); + } + + private static Instrument getInstrument( + Meter meter, InstrumentType instrumentType, InstrumentValueType instrumentValueType) { + String name = "instrument"; + switch (instrumentType) { + case COUNTER: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.counterBuilder(name).ofDoubles().build()::add + : meter.counterBuilder(name).build()::add; + case UP_DOWN_COUNTER: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.upDownCounterBuilder(name).ofDoubles().build()::add + : meter.upDownCounterBuilder(name).build()::add; + case HISTOGRAM: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.histogramBuilder(name).build()::record + : meter.histogramBuilder(name).ofLongs().build()::record; + case GAUGE: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.gaugeBuilder(name).build()::set + : meter.gaugeBuilder(name).ofLongs().build()::set; + case OBSERVABLE_COUNTER: + case OBSERVABLE_UP_DOWN_COUNTER: + case OBSERVABLE_GAUGE: + } + throw new IllegalArgumentException(); + } + + @FunctionalInterface + private interface BoundInstrument { + void record(long value); + } + + /** + * Builds the instrument, then binds one {@link BoundInstrument} per series in {@code + * attributesList}, returned in the same order so the record loop can index it in lockstep. + */ + private static List bindInstruments( + Meter meter, + InstrumentType instrumentType, + InstrumentValueType instrumentValueType, + List attributesList) { + boolean isDouble = instrumentValueType == InstrumentValueType.DOUBLE; + String name = "instrument"; + List result = new ArrayList<>(attributesList.size()); + switch (instrumentType) { + case COUNTER: + if (isDouble) { + ExtendedDoubleCounter instrument = + (ExtendedDoubleCounter) meter.counterBuilder(name).ofDoubles().build(); + for (Attributes attributes : attributesList) { + BoundDoubleCounter bound = instrument.bind(attributes); + result.add(bound::add); + } + } else { + ExtendedLongCounter instrument = (ExtendedLongCounter) meter.counterBuilder(name).build(); + for (Attributes attributes : attributesList) { + BoundLongCounter bound = instrument.bind(attributes); + result.add(bound::add); + } + } + return result; + case UP_DOWN_COUNTER: + if (isDouble) { + ExtendedDoubleUpDownCounter instrument = + (ExtendedDoubleUpDownCounter) meter.upDownCounterBuilder(name).ofDoubles().build(); + for (Attributes attributes : attributesList) { + BoundDoubleUpDownCounter bound = instrument.bind(attributes); + result.add(bound::add); + } + } else { + ExtendedLongUpDownCounter instrument = + (ExtendedLongUpDownCounter) meter.upDownCounterBuilder(name).build(); + for (Attributes attributes : attributesList) { + BoundLongUpDownCounter bound = instrument.bind(attributes); + result.add(bound::add); + } + } + return result; + case HISTOGRAM: + if (isDouble) { + ExtendedDoubleHistogram instrument = + (ExtendedDoubleHistogram) meter.histogramBuilder(name).build(); + for (Attributes attributes : attributesList) { + BoundDoubleHistogram bound = instrument.bind(attributes); + result.add(bound::record); + } + } else { + ExtendedLongHistogram instrument = + (ExtendedLongHistogram) meter.histogramBuilder(name).ofLongs().build(); + for (Attributes attributes : attributesList) { + BoundLongHistogram bound = instrument.bind(attributes); + result.add(bound::record); + } + } + return result; + case GAUGE: + if (isDouble) { + ExtendedDoubleGauge instrument = (ExtendedDoubleGauge) meter.gaugeBuilder(name).build(); + for (Attributes attributes : attributesList) { + BoundDoubleGauge bound = instrument.bind(attributes); + result.add(bound::set); + } + } else { + ExtendedLongGauge instrument = + (ExtendedLongGauge) meter.gaugeBuilder(name).ofLongs().build(); + for (Attributes attributes : attributesList) { + BoundLongGauge bound = instrument.bind(attributes); + result.add(bound::set); + } + } + return result; + case OBSERVABLE_COUNTER: + case OBSERVABLE_UP_DOWN_COUNTER: + case OBSERVABLE_GAUGE: + } + throw new IllegalArgumentException(); + } +} diff --git a/sdk/all/src/jmh/java/io/opentelemetry/sdk/SpanRecordBenchmark.java b/sdk/all/src/jmh/java/io/opentelemetry/sdk/SpanRecordBenchmark.java new file mode 100644 index 00000000000..24aae90060e --- /dev/null +++ b/sdk/all/src/jmh/java/io/opentelemetry/sdk/SpanRecordBenchmark.java @@ -0,0 +1,177 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.sdk.trace.IdGenerator; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Group; +import org.openjdk.jmh.annotations.GroupThreads; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.OperationsPerInvocation; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Warmup; + +/** + * This benchmark measures the performance of recording spans. It includes the following dimensions: + * + *

        + *
      • {@link BenchmarkState#spanSize}: the size of the span, which is a composite of the number + * of attributes, events, and links attached to the span. + *
      + * + *

      Each operation consists of recording {@link SpanRecordBenchmark#RECORDS_PER_INVOCATION} spans. + * + *

      In order to isolate the record path while remaining realistic, the benchmark uses a {@link + * BatchSpanProcessor} paired with a noop {@link SpanExporter}. In order to avoid quickly outpacing + * the batch processor queue and dropping spans, the processor is configured with a queue size of + * {@link SpanRecordBenchmark#RECORDS_PER_INVOCATION} * {@link SpanRecordBenchmark#MAX_THREADS} and + * is flushed after each invocation. + */ +public class SpanRecordBenchmark { + + private static final int RECORDS_PER_INVOCATION = BenchmarkUtils.RECORDS_PER_INVOCATION; + private static final int MAX_THREADS = 4; + private static final int QUEUE_SIZE = RECORDS_PER_INVOCATION * MAX_THREADS; + + @State(Scope.Benchmark) + public static class BenchmarkState { + + // Encode a variety of dimensions (# attributes, # events, # links) into a single enum to + // benchmark various shapes of spans without combinatorial explosion. + @Param SpanSize spanSize; + + SdkTracerProvider tracerProvider; + Tracer tracer; + List> attributeKeys; + List attributeValues; + List exceptions; + List linkContexts; + + @Setup + public void setup() { + tracerProvider = + SdkTracerProvider.builder() + // Configure a batch processor with a noop exporter (SpanExporter.composite() is a + // shortcut for a noop exporter). This allows testing the throughput / performance + // impact of BatchSpanProcessor, which is essential for real workloads, while avoiding + // noise from SpanExporters whose performance is subject to implementation and network + // details. + .addSpanProcessor( + BatchSpanProcessor.builder(SpanExporter.composite()) + .setMaxQueueSize(QUEUE_SIZE) + .build()) + .setSampler(Sampler.alwaysOn()) + .build(); + tracer = tracerProvider.get("benchmark"); + + attributeKeys = new ArrayList<>(spanSize.attributes); + attributeValues = new ArrayList<>(spanSize.attributes); + for (int i = 0; i < spanSize.attributes; i++) { + attributeKeys.add(AttributeKey.stringKey("key" + i)); + attributeValues.add("value" + i); + } + + exceptions = new ArrayList<>(spanSize.events); + for (int i = 0; i < spanSize.events; i++) { + exceptions.add(new Exception("test exception")); + } + + linkContexts = new ArrayList<>(spanSize.links); + for (int i = 0; i < spanSize.links; i++) { + linkContexts.add( + SpanContext.create( + IdGenerator.random().generateTraceId(), + IdGenerator.random().generateSpanId(), + TraceFlags.getDefault(), + TraceState.getDefault())); + } + } + + @TearDown(Level.Invocation) + public void flush() { + tracerProvider.forceFlush().join(10, TimeUnit.SECONDS); + } + + @TearDown + public void tearDown() { + tracerProvider.shutdown(); + } + } + + @Benchmark + @Group("threads1") + @GroupThreads(1) + @Fork(3) + @Warmup(iterations = 3, time = 1) + @Measurement(iterations = 10, time = 1) + @OperationsPerInvocation(RECORDS_PER_INVOCATION) + public void record_SingleThread(BenchmarkState benchmarkState) { + record(benchmarkState); + } + + @Benchmark + @Group("threads" + MAX_THREADS) + @GroupThreads(MAX_THREADS) + @Fork(3) + @Warmup(iterations = 3, time = 1) + @Measurement(iterations = 10, time = 1) + @OperationsPerInvocation(RECORDS_PER_INVOCATION) + public void record_MultipleThreads(BenchmarkState benchmarkState) { + record(benchmarkState); + } + + private static void record(BenchmarkState benchmarkState) { + for (int i = 0; i < RECORDS_PER_INVOCATION; i++) { + Span span = benchmarkState.tracer.spanBuilder("test span name").startSpan(); + for (int j = 0; j < benchmarkState.attributeKeys.size(); j++) { + span.setAttribute( + benchmarkState.attributeKeys.get(j), benchmarkState.attributeValues.get(j)); + } + for (int j = 0; j < benchmarkState.exceptions.size(); j++) { + span.recordException(benchmarkState.exceptions.get(j)); + } + for (int j = 0; j < benchmarkState.linkContexts.size(); j++) { + span.addLink(benchmarkState.linkContexts.get(j)); + } + span.end(); + } + } + + public enum SpanSize { + SMALL(0, 0, 0), + MEDIUM(10, 1, 0), + LARGE(100, 10, 5); + + private final int attributes; + private final int events; + private final int links; + + SpanSize(int attributes, int events, int links) { + this.attributes = attributes; + this.events = events; + this.links = links; + } + } +} diff --git a/sdk/all/src/main/java/io/opentelemetry/sdk/IncubatingUtil.java b/sdk/all/src/main/java/io/opentelemetry/sdk/IncubatingUtil.java new file mode 100644 index 00000000000..98877b0886c --- /dev/null +++ b/sdk/all/src/main/java/io/opentelemetry/sdk/IncubatingUtil.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import javax.annotation.Nullable; + +/** + * Utilities for interacting with {@code io.opentelemetry:opentelemetry-api-incubator}, which is not + * guaranteed to be present on the classpath. For all methods, callers MUST first separately + * reflectively confirm that the incubator is available on the classpath. + */ +final class IncubatingUtil { + + private IncubatingUtil() {} + + static OpenTelemetrySdk createExtendedOpenTelemetrySdk( + OpenTelemetrySdk openTelemetrySdk, @Nullable Object sdkConfigProvider) { + SdkConfigProvider resolvedConfigProvider = + sdkConfigProvider == null + ? SdkConfigProvider.create(DeclarativeConfigProperties.empty()) + : (SdkConfigProvider) sdkConfigProvider; + return ExtendedOpenTelemetrySdk.create(openTelemetrySdk, resolvedConfigProvider); + } +} diff --git a/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdk.java b/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdk.java index a277eded172..5600a676da3 100644 --- a/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdk.java +++ b/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdk.java @@ -6,33 +6,46 @@ package io.opentelemetry.sdk; import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.logs.LoggerBuilder; +import io.opentelemetry.api.logs.LoggerProvider; import io.opentelemetry.api.metrics.MeterBuilder; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerBuilder; import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.context.propagation.ContextPropagators; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.trace.SdkTracerProvider; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Logger; import javax.annotation.concurrent.ThreadSafe; /** The SDK implementation of {@link OpenTelemetry}. */ @ThreadSafe -public final class OpenTelemetrySdk implements OpenTelemetry { +public class OpenTelemetrySdk implements OpenTelemetry, Closeable { + + private static final Logger LOGGER = Logger.getLogger(OpenTelemetrySdk.class.getName()); + + private final AtomicBoolean isShutdown = new AtomicBoolean(false); private final ObfuscatedTracerProvider tracerProvider; private final ObfuscatedMeterProvider meterProvider; - private final SdkLogEmitterProvider logEmitterProvider; + private final ObfuscatedLoggerProvider loggerProvider; private final ContextPropagators propagators; - OpenTelemetrySdk( + protected OpenTelemetrySdk( SdkTracerProvider tracerProvider, SdkMeterProvider meterProvider, - SdkLogEmitterProvider logEmitterProvider, + SdkLoggerProvider loggerProvider, ContextPropagators propagators) { this.tracerProvider = new ObfuscatedTracerProvider(tracerProvider); this.meterProvider = new ObfuscatedMeterProvider(meterProvider); - this.logEmitterProvider = logEmitterProvider; + this.loggerProvider = new ObfuscatedLoggerProvider(loggerProvider); this.propagators = propagators; } @@ -45,43 +58,78 @@ public static OpenTelemetrySdkBuilder builder() { } @Override - public TracerProvider getTracerProvider() { + public final TracerProvider getTracerProvider() { return tracerProvider; } /** Returns the {@link SdkTracerProvider} for this {@link OpenTelemetrySdk}. */ - public SdkTracerProvider getSdkTracerProvider() { + public final SdkTracerProvider getSdkTracerProvider() { return tracerProvider.unobfuscate(); } @Override - public MeterProvider getMeterProvider() { + public final MeterProvider getMeterProvider() { return meterProvider; } /** Returns the {@link SdkMeterProvider} for this {@link OpenTelemetrySdk}. */ - public SdkMeterProvider getSdkMeterProvider() { + public final SdkMeterProvider getSdkMeterProvider() { return meterProvider.unobfuscate(); } - /** Returns the {@link SdkLogEmitterProvider} for this {@link OpenTelemetrySdk}. */ - public SdkLogEmitterProvider getSdkLogEmitterProvider() { - return logEmitterProvider; + @Override + public final LoggerProvider getLogsBridge() { + return loggerProvider; + } + + /** + * Returns the {@link SdkLoggerProvider} for this {@link OpenTelemetrySdk}. + * + * @since 1.19.0 + */ + public final SdkLoggerProvider getSdkLoggerProvider() { + return loggerProvider.unobfuscate(); } @Override - public ContextPropagators getPropagators() { + public final ContextPropagators getPropagators() { return propagators; } + /** + * Shutdown the SDK. Calls {@link SdkTracerProvider#shutdown()}, {@link + * SdkMeterProvider#shutdown()}, and {@link SdkLoggerProvider#shutdown()}. + * + * @return a {@link CompletableResultCode} which completes when all providers are shutdown + */ + public CompletableResultCode shutdown() { + if (!isShutdown.compareAndSet(false, true)) { + LOGGER.info("Multiple shutdown calls"); + return CompletableResultCode.ofSuccess(); + } + List results = new ArrayList<>(); + results.add(tracerProvider.unobfuscate().shutdown()); + results.add(meterProvider.unobfuscate().shutdown()); + results.add(loggerProvider.unobfuscate().shutdown()); + return CompletableResultCode.ofAll(results); + } + + @Override + public void close() { + shutdown().join(10, TimeUnit.SECONDS); + } + @Override public String toString() { - // TODO(anuraaga): Add logs / propagators return "OpenTelemetrySdk{" + "tracerProvider=" + tracerProvider.unobfuscate() + ", meterProvider=" + meterProvider.unobfuscate() + + ", loggerProvider=" + + loggerProvider.unobfuscate() + + ", propagators=" + + propagators + "}"; } @@ -148,4 +196,31 @@ public SdkMeterProvider unobfuscate() { return delegate; } } + + /** + * This class allows the SDK to unobfuscate an obfuscated static global provider. + * + *

      Static global providers are obfuscated when they are returned from the API to prevent users + * from casting them to their SDK specific implementation. For example, we do not want users to + * use patterns like {@code (SdkLoggerProvider) openTelemetry.getLogsBridge()}. + */ + @ThreadSafe + // Visible for testing + static class ObfuscatedLoggerProvider implements LoggerProvider { + + private final SdkLoggerProvider delegate; + + ObfuscatedLoggerProvider(SdkLoggerProvider delegate) { + this.delegate = delegate; + } + + @Override + public LoggerBuilder loggerBuilder(String instrumentationScopeName) { + return delegate.loggerBuilder(instrumentationScopeName); + } + + public SdkLoggerProvider unobfuscate() { + return delegate; + } + } } diff --git a/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdkBuilder.java b/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdkBuilder.java index d03cfd495f2..c7168599554 100644 --- a/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdkBuilder.java +++ b/sdk/all/src/main/java/io/opentelemetry/sdk/OpenTelemetrySdkBuilder.java @@ -5,9 +5,14 @@ package io.opentelemetry.sdk; +import static java.util.Objects.requireNonNull; + import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.context.propagation.ContextPropagators; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; +import io.opentelemetry.sdk.internal.OpenTelemetrySdkBuilderUtil; +import io.opentelemetry.sdk.internal.SdkConfigProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.trace.SdkTracerProvider; import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; @@ -19,7 +24,21 @@ public final class OpenTelemetrySdkBuilder { private ContextPropagators propagators = ContextPropagators.noop(); @Nullable private SdkTracerProvider tracerProvider; @Nullable private SdkMeterProvider meterProvider; - @Nullable private SdkLogEmitterProvider logEmitterProvider; + @Nullable private SdkLoggerProvider loggerProvider; + @Nullable private Object configProvider; + + private static final boolean INCUBATOR_AVAILABLE; + + static { + boolean incubatorAvailable = false; + try { + Class.forName("io.opentelemetry.api.incubator.ExtendedOpenTelemetry"); + incubatorAvailable = true; + } catch (ClassNotFoundException e) { + // Not available + } + INCUBATOR_AVAILABLE = incubatorAvailable; + } /** * Package protected to disallow direct initialization. @@ -52,20 +71,31 @@ public OpenTelemetrySdkBuilder setMeterProvider(SdkMeterProvider meterProvider) } /** - * Sets the {@link SdkLogEmitterProvider} to use. This can be used to configure log settings by - * returning the instance created by a {@link - * io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder}. + * Sets the {@link SdkLoggerProvider} to use. This can be used to configure log settings by + * returning the instance created by a {@link SdkLoggerProviderBuilder}. * - * @see SdkLogEmitterProvider#builder() + * @see SdkLoggerProvider#builder() + * @since 1.19.0 */ - public OpenTelemetrySdkBuilder setLogEmitterProvider(SdkLogEmitterProvider logEmitterProvider) { - this.logEmitterProvider = logEmitterProvider; + public OpenTelemetrySdkBuilder setLoggerProvider(SdkLoggerProvider loggerProvider) { + this.loggerProvider = loggerProvider; return this; } /** Sets the {@link ContextPropagators} to use. */ public OpenTelemetrySdkBuilder setPropagators(ContextPropagators propagators) { - this.propagators = propagators; + this.propagators = requireNonNull(propagators); + return this; + } + + /** + * Sets the {@link SdkConfigProvider} to use. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * OpenTelemetrySdkBuilderUtil#setConfigProvider(OpenTelemetrySdkBuilder, SdkConfigProvider)}. + */ + OpenTelemetrySdkBuilder setConfigProvider(SdkConfigProvider configProvider) { + this.configProvider = requireNonNull(configProvider); return this; } @@ -105,11 +135,15 @@ public OpenTelemetrySdk build() { meterProvider = SdkMeterProvider.builder().build(); } - SdkLogEmitterProvider logEmitterProvider = this.logEmitterProvider; - if (logEmitterProvider == null) { - logEmitterProvider = SdkLogEmitterProvider.builder().build(); + SdkLoggerProvider loggerProvider = this.loggerProvider; + if (loggerProvider == null) { + loggerProvider = SdkLoggerProvider.builder().build(); } - return new OpenTelemetrySdk(tracerProvider, meterProvider, logEmitterProvider, propagators); + OpenTelemetrySdk openTelemetrySdk = + new OpenTelemetrySdk(tracerProvider, meterProvider, loggerProvider, propagators); + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedOpenTelemetrySdk(openTelemetrySdk, configProvider) + : openTelemetrySdk; } } diff --git a/sdk/all/src/main/java/io/opentelemetry/sdk/internal/ExtendedOpenTelemetrySdk.java b/sdk/all/src/main/java/io/opentelemetry/sdk/internal/ExtendedOpenTelemetrySdk.java new file mode 100644 index 00000000000..84acb3435a2 --- /dev/null +++ b/sdk/all/src/main/java/io/opentelemetry/sdk/internal/ExtendedOpenTelemetrySdk.java @@ -0,0 +1,137 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.ExtendedOpenTelemetry; +import io.opentelemetry.api.incubator.config.ConfigProvider; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import javax.annotation.Nullable; +import javax.annotation.concurrent.ThreadSafe; + +/** + * {@link ExtendedOpenTelemetrySdk} is SDK implementation of {@link ExtendedOpenTelemetry}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class ExtendedOpenTelemetrySdk extends OpenTelemetrySdk + implements ExtendedOpenTelemetry { + + private final OpenTelemetrySdk openTelemetrySdk; + private final ObfuscatedConfigProvider configProvider; + @Nullable private final SdkResourceProvider resourceProvider; + + private ExtendedOpenTelemetrySdk( + OpenTelemetrySdk openTelemetrySdk, + SdkConfigProvider configProvider, + @Nullable SdkResourceProvider resourceProvider) { + super( + openTelemetrySdk.getSdkTracerProvider(), + openTelemetrySdk.getSdkMeterProvider(), + openTelemetrySdk.getSdkLoggerProvider(), + openTelemetrySdk.getPropagators()); + this.openTelemetrySdk = openTelemetrySdk; + this.configProvider = new ObfuscatedConfigProvider(configProvider); + this.resourceProvider = resourceProvider; + } + + public static ExtendedOpenTelemetrySdk create( + OpenTelemetrySdk openTelemetrySdk, SdkConfigProvider sdkConfigProvider) { + return new ExtendedOpenTelemetrySdk( + openTelemetrySdk, sdkConfigProvider, resolveSdkResourceProvider(openTelemetrySdk)); + } + + @Override + public ConfigProvider getConfigProvider() { + return configProvider; + } + + /** Returns the {@link SdkConfigProvider} for this {@link ExtendedOpenTelemetrySdk}. */ + public SdkConfigProvider getSdkConfigProvider() { + return configProvider.unobfuscate(); + } + + /** + * Returns the {@link SdkResourceProvider} shared by the SDK's tracer, meter, and logger + * providers. + * + * @throws IllegalStateException if the three signal providers were not configured with equivalent + * resources. + */ + public SdkResourceProvider getSdkResourceProvider() { + if (resourceProvider == null) { + throw new IllegalStateException( + "SdkTracerProvider, SdkMeterProvider, and SdkLoggerProvider are configured with" + + " different resources. Configure all three signal providers with the same" + + " SdkResourceProvider (or the same Resource) to resolve this."); + } + return resourceProvider; + } + + @Nullable + private static SdkResourceProvider resolveSdkResourceProvider(OpenTelemetrySdk sdk) { + SdkTracerProvider tracerProvider = sdk.getSdkTracerProvider(); + SdkMeterProvider meterProvider = sdk.getSdkMeterProvider(); + SdkLoggerProvider loggerProvider = sdk.getSdkLoggerProvider(); + SdkResourceProvider tracerRp = SdkTracerProviderUtil.getSdkResourceProvider(tracerProvider); + SdkResourceProvider meterRp = SdkMeterProviderUtil.getSdkResourceProvider(meterProvider); + SdkResourceProvider loggerRp = SdkLoggerProviderUtil.getSdkResourceProvider(loggerProvider); + Resource tracerResource = tracerRp.getResource(); + if (tracerResource.equals(meterRp.getResource()) + && tracerResource.equals(loggerRp.getResource())) { + return tracerRp; + } + return null; + } + + @Override + public String toString() { + return "ExtendedOpenTelemetrySdk{" + + "openTelemetrySdk=" + + openTelemetrySdk + + ", configProvider=" + + configProvider.unobfuscate() + + ", resourceProvider=" + + resourceProvider + + "}"; + } + + /** + * This class allows the SDK to unobfuscate an obfuscated provider. + * + *

      Static global providers are obfuscated when they are returned from the API to prevent users + * from casting them to their SDK specific implementation. For example, we do not want users to + * use patterns like {@code (SdkConfigProvider) openTelemetry.getConfigProvider()}. + */ + @ThreadSafe + private static class ObfuscatedConfigProvider implements ConfigProvider { + + private final SdkConfigProvider delegate; + + private ObfuscatedConfigProvider(SdkConfigProvider delegate) { + this.delegate = delegate; + } + + @Override + public DeclarativeConfigProperties getInstrumentationConfig() { + return delegate.getInstrumentationConfig(); + } + + private SdkConfigProvider unobfuscate() { + return delegate; + } + } +} diff --git a/sdk/all/src/main/java/io/opentelemetry/sdk/internal/OpenTelemetrySdkBuilderUtil.java b/sdk/all/src/main/java/io/opentelemetry/sdk/internal/OpenTelemetrySdkBuilderUtil.java new file mode 100644 index 00000000000..e2fc26fc8b3 --- /dev/null +++ b/sdk/all/src/main/java/io/opentelemetry/sdk/internal/OpenTelemetrySdkBuilderUtil.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.internal; + +import io.opentelemetry.sdk.OpenTelemetrySdkBuilder; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +/** + * A collection of methods that allow use of experimental features prior to availability in public + * APIs. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class OpenTelemetrySdkBuilderUtil { + + private OpenTelemetrySdkBuilderUtil() {} + + /** Reflectively set the {@link SdkConfigProvider} on the {@link OpenTelemetrySdkBuilder}. */ + public static OpenTelemetrySdkBuilder setConfigProvider( + OpenTelemetrySdkBuilder builder, SdkConfigProvider configProvider) { + try { + Method method = + OpenTelemetrySdkBuilder.class.getDeclaredMethod( + "setConfigProvider", SdkConfigProvider.class); + method.setAccessible(true); + method.invoke(builder, configProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setConfigProvider on OpenTelemetrySdkBuilder", e); + } + return builder; + } +} diff --git a/sdk/all/src/main/java/io/opentelemetry/sdk/internal/SdkConfigProvider.java b/sdk/all/src/main/java/io/opentelemetry/sdk/internal/SdkConfigProvider.java new file mode 100644 index 00000000000..04b23cc9587 --- /dev/null +++ b/sdk/all/src/main/java/io/opentelemetry/sdk/internal/SdkConfigProvider.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.internal; + +import io.opentelemetry.api.config.DeclarativeConfigProperties; +import io.opentelemetry.api.incubator.config.ConfigProvider; + +/** + * SDK implementation of {@link ConfigProvider}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class SdkConfigProvider implements ConfigProvider { + + private final DeclarativeConfigProperties instrumentationConfig; + + private SdkConfigProvider(DeclarativeConfigProperties openTelemetryConfigModel) { + this.instrumentationConfig = openTelemetryConfigModel.get("instrumentation/development"); + } + + /** + * Create a {@link SdkConfigProvider}. + * + * @param openTelemetryConfigModel {@link DeclarativeConfigProperties} corresponding to the {@code + * OpenTelemetryConfiguration} type, i.e. the root node. + * @return the {@link SdkConfigProvider} instance + */ + public static SdkConfigProvider create(DeclarativeConfigProperties openTelemetryConfigModel) { + return new SdkConfigProvider(openTelemetryConfigModel); + } + + @Override + public DeclarativeConfigProperties getInstrumentationConfig() { + return instrumentationConfig; + } + + @Override + public String toString() { + return "SdkConfigProvider{" + "instrumentationConfig=" + instrumentationConfig + '}'; + } +} diff --git a/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java b/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java index 4de2d21915b..8186aebdb13 100644 --- a/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java +++ b/sdk/all/src/test/java/io/opentelemetry/sdk/OpenTelemetrySdkTest.java @@ -8,16 +8,24 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.InstanceOfAssertFactories.type; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.GlobalOpenTelemetry; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; import io.opentelemetry.context.propagation.ContextPropagators; import io.opentelemetry.context.propagation.TextMapPropagator; import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.InstrumentType; @@ -33,18 +41,28 @@ import io.opentelemetry.sdk.trace.export.SpanExporter; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.time.Duration; +import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; +import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class OpenTelemetrySdkTest { + @RegisterExtension + LogCapturer logCapturer = LogCapturer.create().captureForLogger(OpenTelemetrySdk.class.getName()); + + @Mock private MetricExporter metricExporter; @Mock private SdkTracerProvider tracerProvider; @Mock private SdkMeterProvider meterProvider; - @Mock private SdkLogEmitterProvider logEmitterProvider; + @Mock private SdkLoggerProvider loggerProvider; @Mock private ContextPropagators propagators; @AfterEach @@ -105,7 +123,7 @@ void builder() { OpenTelemetrySdk.builder() .setTracerProvider(tracerProvider) .setMeterProvider(meterProvider) - .setLogEmitterProvider(logEmitterProvider) + .setLoggerProvider(loggerProvider) .setPropagators(propagators) .build(); assertThat( @@ -117,7 +135,7 @@ void builder() { ((OpenTelemetrySdk.ObfuscatedMeterProvider) openTelemetry.getMeterProvider()) .unobfuscate()) .isEqualTo(meterProvider); - assertThat(openTelemetry.getSdkLogEmitterProvider()).isEqualTo(logEmitterProvider); + assertThat(openTelemetry.getSdkLoggerProvider()).isEqualTo(loggerProvider); assertThat(openTelemetry.getPropagators()).isEqualTo(propagators); } @@ -142,14 +160,26 @@ void getTracer() { @Test void tracerBuilder() { - OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder().build(); + OpenTelemetrySdk openTelemetry = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(mock(SpanExporter.class))) + .build()) + .build(); assertThat(openTelemetry.tracerBuilder("instr")) .isNotSameAs(OpenTelemetry.noop().tracerBuilder("instr")); } @Test void tracerBuilder_ViaProvider() { - OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder().build(); + OpenTelemetrySdk openTelemetry = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(mock(SpanExporter.class))) + .build()) + .build(); assertThat(openTelemetry.getTracerProvider().tracerBuilder("instr")) .isNotSameAs(OpenTelemetry.noop().tracerBuilder("instr")); } @@ -185,11 +215,12 @@ void getMeter() { @Test void meterBuilder() { + when(metricExporter.getDefaultAggregation(any())).thenCallRealMethod(); OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() - .registerMetricReader(PeriodicMetricReader.create(mock(MetricExporter.class))) + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) .build()) .build(); assertThat(openTelemetry.meterBuilder("instr")) @@ -198,11 +229,12 @@ void meterBuilder() { @Test void meterBuilder_ViaProvider() { + when(metricExporter.getDefaultAggregation(any())).thenCallRealMethod(); OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() - .registerMetricReader(PeriodicMetricReader.create(mock(MetricExporter.class))) + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) .build()) .build(); assertThat(openTelemetry.getMeterProvider().meterBuilder("instr")) @@ -225,16 +257,17 @@ void getMeterProvider() { // Demonstrates how clear or confusing is SDK configuration @Test void fullOpenTelemetrySdkConfigurationDemo() { + when(metricExporter.getDefaultAggregation(any())).thenCallRealMethod(); OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() .setResource(Resource.empty()) .setClock(mock(Clock.class)) .registerMetricReader( - PeriodicMetricReader.builder(mock(MetricExporter.class)) + PeriodicMetricReader.builder(metricExporter) .setInterval(Duration.ofSeconds(10)) .build()) - .registerMetricReader(PeriodicMetricReader.create(mock(MetricExporter.class))) + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) .registerView( InstrumentSelector.builder().setName("name").build(), View.builder().setName("new-name").build()) @@ -261,10 +294,11 @@ void fullOpenTelemetrySdkConfigurationDemo() { // Demonstrates how clear or confusing is SDK configuration @Test void trivialOpenTelemetrySdkConfigurationDemo() { + when(metricExporter.getDefaultAggregation(any())).thenCallRealMethod(); OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() - .registerMetricReader(PeriodicMetricReader.create(mock(MetricExporter.class))) + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) .build()) .setTracerProvider( SdkTracerProvider.builder() @@ -278,10 +312,11 @@ void trivialOpenTelemetrySdkConfigurationDemo() { // Demonstrates how clear or confusing is SDK configuration @Test void minimalOpenTelemetrySdkConfigurationDemo() { + when(metricExporter.getDefaultAggregation(any())).thenCallRealMethod(); OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() - .registerMetricReader(PeriodicMetricReader.create(mock(MetricExporter.class))) + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) .build()) .setTracerProvider( SdkTracerProvider.builder() @@ -294,7 +329,7 @@ void minimalOpenTelemetrySdkConfigurationDemo() { OpenTelemetrySdk.builder() .setMeterProvider( SdkMeterProvider.builder() - .registerMetricReader(PeriodicMetricReader.create(mock(MetricExporter.class))) + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) .registerView( InstrumentSelector.builder().setType(InstrumentType.COUNTER).build(), View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build()) @@ -309,12 +344,51 @@ void minimalOpenTelemetrySdkConfigurationDemo() { .build(); } + @Test + void shutdown() { + when(tracerProvider.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(meterProvider.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(loggerProvider.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider(tracerProvider) + .setMeterProvider(meterProvider) + .setLoggerProvider(loggerProvider) + .build(); + + // First call should call shutdown + assertThat(sdk.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + verify(tracerProvider).shutdown(); + verify(meterProvider).shutdown(); + verify(loggerProvider).shutdown(); + assertThat(logCapturer.getEvents()).isEmpty(); + + // Subsequent calls should log not call shutdown + Mockito.reset(tracerProvider, meterProvider, loggerProvider); + assertThat(sdk.shutdown().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + sdk.close(); + + verify(tracerProvider, never()).shutdown(); + verify(meterProvider, never()).shutdown(); + verify(loggerProvider, never()).shutdown(); + + assertThat(logCapturer.getEvents()) + .hasSize(2) + .allSatisfy(loggingEvent -> + assertThat(loggingEvent.getMessage()).isEqualTo("Multiple shutdown calls")); + } + @Test void stringRepresentation() { SpanExporter spanExporter = mock(SpanExporter.class); when(spanExporter.toString()).thenReturn("MockSpanExporter{}"); - MetricExporter metricExporter = mock(MetricExporter.class); + when(metricExporter.getDefaultAggregation(any())).thenCallRealMethod(); when(metricExporter.toString()).thenReturn("MockMetricExporter{}"); + LogRecordExporter logRecordExporter = mock(LogRecordExporter.class); + when(logRecordExporter.toString()).thenReturn("MockLogRecordExporter{}"); + TextMapPropagator propagator = mock(TextMapPropagator.class); + when(propagator.toString()).thenReturn("MockTextMapPropagator{}"); Resource resource = Resource.builder().put(AttributeKey.stringKey("service.name"), "otel-test").build(); OpenTelemetrySdk sdk = @@ -334,25 +408,47 @@ void stringRepresentation() { InstrumentSelector.builder().setName("instrument").build(), View.builder().setName("new-instrument").build()) .build()) + .setLoggerProvider( + SdkLoggerProvider.builder() + .setResource(resource) + .addLogRecordProcessor( + SimpleLogRecordProcessor.create( + LogRecordExporter.composite(logRecordExporter, logRecordExporter))) + .build()) + .setPropagators(ContextPropagators.create(propagator)) .build(); + // Test that toString delegates to underlying classes, and make sure their toString is also + // nice. assertThat(sdk.toString()) - .isEqualTo( - "OpenTelemetrySdk{" - + "tracerProvider=SdkTracerProvider{" - + "clock=SystemClock{}, " - + "idGenerator=RandomIdGenerator{}, " - + "resource=Resource{schemaUrl=null, attributes={service.name=\"otel-test\"}}, " - + "spanLimitsSupplier=SpanLimitsValue{maxNumberOfAttributes=128, maxNumberOfEvents=128, maxNumberOfLinks=128, maxNumberOfAttributesPerEvent=128, maxNumberOfAttributesPerLink=128, maxAttributeValueLength=2147483647}, " - + "sampler=ParentBased{root:AlwaysOnSampler,remoteParentSampled:AlwaysOnSampler,remoteParentNotSampled:AlwaysOffSampler,localParentSampled:AlwaysOnSampler,localParentNotSampled:AlwaysOffSampler}, " - + "spanProcessor=SimpleSpanProcessor{spanExporter=MultiSpanExporter{spanExporters=[MockSpanExporter{}, MockSpanExporter{}]}}" - + "}, " - + "meterProvider=SdkMeterProvider{" - + "clock=SystemClock{}, " - + "resource=Resource{schemaUrl=null, attributes={service.name=\"otel-test\"}}, " - + "metricReaders=[PeriodicMetricReader{exporter=MockMetricExporter{}, intervalNanos=60000000000}], " - + "views=[RegisteredView{instrumentSelector=InstrumentSelector{instrumentName=instrument}, view=View{name=new-instrument, aggregation=DefaultAggregation, attributesProcessor=NoopAttributesProcessor{}}}]" - + "}" - + "}"); + .matches("OpenTelemetrySdk\\{.*}") + .matches("OpenTelemetrySdk\\{tracerProvider=SdkTracerProvider\\{.*}.*}") + .matches("OpenTelemetrySdk\\{.*, meterProvider=SdkMeterProvider\\{.*}.*}") + .matches("OpenTelemetrySdk\\{.*, loggerProvider=SdkLoggerProvider\\{.*}.*}") + .matches("OpenTelemetrySdk\\{.*, propagators=DefaultContextPropagators\\{.*}}"); + } + + @Test + void builderDefaults_tracerProviderHasNoProcessors_spansNotRecording() { + // Regression test for #8740: no processors must produce non-recording spans. + OpenTelemetrySdk openTelemetry = OpenTelemetrySdk.builder().build(); + + Span span = openTelemetry.getTracer("test").spanBuilder("test-span").startSpan(); + assertThat(span.isRecording()).isFalse(); + } + + @Test + void tracerProviderWithSpanProcessor_spansRecording() { + // Verify that configuring a SpanProcessor still produces recording spans. + OpenTelemetrySdk openTelemetry = + OpenTelemetrySdk.builder() + .setTracerProvider( + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(mock(SpanExporter.class))) + .build()) + .build(); + + Span span = openTelemetry.getTracer("test").spanBuilder("test-span").startSpan(); + assertThat(span.isRecording()).isTrue(); } } diff --git a/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java b/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java new file mode 100644 index 00000000000..39d4a6395bc --- /dev/null +++ b/sdk/all/src/test/java/io/opentelemetry/sdk/ScopeConfiguratorTest.java @@ -0,0 +1,229 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.internal.TracerConfig; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; + +class ScopeConfiguratorTest { + + private final InMemoryLogRecordExporter logRecordExporter = InMemoryLogRecordExporter.create(); + private final InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + private final InMemorySpanExporter spanExporter = InMemorySpanExporter.create(); + + private static final InstrumentationScopeInfo scopeA = InstrumentationScopeInfo.create("scopeA"); + private static final InstrumentationScopeInfo scopeB = InstrumentationScopeInfo.create("scopeB"); + private static final InstrumentationScopeInfo scopeC = InstrumentationScopeInfo.create("scopeC"); + + /** Disable "scopeB". All other scopes are enabled by default. */ + @Test + void disableScopeB() { + // Configuration ergonomics will improve after APIs stabilize + SdkTracerProviderBuilder tracerProviderBuilder = SdkTracerProvider.builder(); + SdkTracerProviderUtil.addTracerConfiguratorCondition( + tracerProviderBuilder, nameEquals(scopeB.getName()), TracerConfig.disabled()); + SdkMeterProviderBuilder meterProviderBuilder = SdkMeterProvider.builder(); + SdkMeterProviderUtil.addMeterConfiguratorCondition( + meterProviderBuilder, nameEquals(scopeB.getName()), MeterConfig.disabled()); + SdkLoggerProviderBuilder loggerProviderBuilder = SdkLoggerProvider.builder(); + SdkLoggerProviderUtil.addLoggerConfiguratorCondition( + loggerProviderBuilder, nameEquals(scopeB.getName()), LoggerConfig.disabled()); + + OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider( + tracerProviderBuilder + .addSpanProcessor(SimpleSpanProcessor.create(spanExporter)) + .build()) + .setMeterProvider(meterProviderBuilder.registerMetricReader(metricReader).build()) + .setLoggerProvider( + loggerProviderBuilder + .addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter)) + .build()) + .build(); + + simulateInstrumentation(sdk); + + // Collect all the telemetry. Ensure we don't see any from scopeB, and that the telemetry from + // scopeA and scopeC is valid. + assertThat(spanExporter.getFinishedSpanItems()) + .satisfies(spans -> { + Map> spansByScope = + spans.stream().collect(Collectors.groupingBy(SpanData::getInstrumentationScopeInfo)); + assertThat(spansByScope.get(scopeA)).hasSize(1); + assertThat(spansByScope.get(scopeB)).isNull(); + assertThat(spansByScope.get(scopeC)).hasSize(1); + }); + assertThat(metricReader.collectAllMetrics()) + .satisfies(metrics -> { + Map> metricsByScope = + metrics.stream() + .collect(Collectors.groupingBy(MetricData::getInstrumentationScopeInfo)); + assertThat(metricsByScope.get(scopeA)).hasSize(1); + assertThat(metricsByScope.get(scopeB)).isNull(); + assertThat(metricsByScope.get(scopeC)).hasSize(1); + }); + assertThat(logRecordExporter.getFinishedLogRecordItems()) + .satisfies(logs -> { + Map> logsByScope = + logs.stream() + .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); + assertThat(logsByScope.get(scopeA)).hasSize(1); + assertThat(logsByScope.get(scopeB)).isNull(); + assertThat(logsByScope.get(scopeC)).hasSize(1); + }); + } + + /** Disable all scopes by default and enable a single scope. */ + @Test + void disableAllScopesExceptB() { + // Configuration ergonomics will improve after APIs stabilize + SdkTracerProviderBuilder tracerProviderBuilder = SdkTracerProvider.builder(); + SdkTracerProviderUtil.setTracerConfigurator( + tracerProviderBuilder, + TracerConfig.configuratorBuilder() + .setDefault(TracerConfig.disabled()) + .addCondition(nameEquals(scopeB.getName()), TracerConfig.enabled()) + .build()); + SdkMeterProviderBuilder meterProviderBuilder = SdkMeterProvider.builder(); + SdkMeterProviderUtil.setMeterConfigurator( + meterProviderBuilder, + MeterConfig.configuratorBuilder() + .setDefault(MeterConfig.disabled()) + .addCondition(nameEquals(scopeB.getName()), MeterConfig.enabled()) + .build()); + SdkLoggerProviderBuilder loggerProviderBuilder = SdkLoggerProvider.builder(); + SdkLoggerProviderUtil.setLoggerConfigurator( + loggerProviderBuilder, + LoggerConfig.configuratorBuilder() + .setDefault(LoggerConfig.disabled()) + .addCondition(nameEquals(scopeB.getName()), LoggerConfig.enabled()) + .build()); + + OpenTelemetrySdk sdk = + OpenTelemetrySdk.builder() + .setTracerProvider( + tracerProviderBuilder + .addSpanProcessor(SimpleSpanProcessor.create(spanExporter)) + .build()) + .setMeterProvider(meterProviderBuilder.registerMetricReader(metricReader).build()) + .setLoggerProvider( + loggerProviderBuilder + .addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter)) + .build()) + .build(); + + simulateInstrumentation(sdk); + + // Collect all the telemetry. Ensure we only see telemetry from scopeB, since other scopes have + // been disabled by default. + assertThat(spanExporter.getFinishedSpanItems()) + .satisfies(spans -> { + Map> spansByScope = + spans.stream().collect(Collectors.groupingBy(SpanData::getInstrumentationScopeInfo)); + assertThat(spansByScope.get(scopeA)).isNull(); + assertThat(spansByScope.get(scopeB)).hasSize(1); + assertThat(spansByScope.get(scopeC)).isNull(); + }); + assertThat(metricReader.collectAllMetrics()) + .satisfies(metrics -> { + Map> metricsByScope = + metrics.stream() + .collect(Collectors.groupingBy(MetricData::getInstrumentationScopeInfo)); + assertThat(metricsByScope.get(scopeA)).isNull(); + assertThat(metricsByScope.get(scopeB)).hasSize(1); + assertThat(metricsByScope.get(scopeC)).isNull(); + }); + assertThat(logRecordExporter.getFinishedLogRecordItems()) + .satisfies(logs -> { + Map> logsByScope = + logs.stream() + .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); + assertThat(logsByScope.get(scopeA)).isNull(); + assertThat(logsByScope.get(scopeB)).hasSize(1); + assertThat(logsByScope.get(scopeC)).isNull(); + }); + } + + /** + * Emit spans, metrics and logs in a hierarchy of 3 scopes: scopeA -> scopeB -> scopeC. Exercise + * the scope config which is common across all signals. + */ + private static void simulateInstrumentation(OpenTelemetry openTelemetry) { + // Start scopeA + Tracer scopeATracer = openTelemetry.getTracer(scopeA.getName()); + Meter scopeAMeter = openTelemetry.getMeter(scopeA.getName()); + Logger scopeALogger = openTelemetry.getLogsBridge().get(scopeA.getName()); + Span spanA = scopeATracer.spanBuilder("spanA").startSpan(); + try (Scope spanAScope = spanA.makeCurrent()) { + scopeALogger.logRecordBuilder().setBody("scopeA log message").emit(); + + // Start scopeB + Tracer scopeBTracer = openTelemetry.getTracer(scopeB.getName()); + Meter scopeBMeter = openTelemetry.getMeter(scopeB.getName()); + Logger scopeBLogger = openTelemetry.getLogsBridge().get(scopeB.getName()); + Span spanB = scopeBTracer.spanBuilder("spanB").startSpan(); + try (Scope spanBScope = spanB.makeCurrent()) { + scopeBLogger.logRecordBuilder().setBody("scopeB log message").emit(); + + // Start scopeC + Tracer scopeCTracer = openTelemetry.getTracer(scopeC.getName()); + Meter scopeCMeter = openTelemetry.getMeter(scopeC.getName()); + Logger scopeCLogger = openTelemetry.getLogsBridge().get(scopeC.getName()); + Span spanC = scopeCTracer.spanBuilder("spanC").startSpan(); + try (Scope spanCScope = spanC.makeCurrent()) { + scopeCLogger.logRecordBuilder().setBody("scopeC log message").emit(); + } finally { + spanC.end(); + scopeCMeter.counterBuilder("scopeCCounter").build().add(1); + } + // End scopeC + + } finally { + spanB.end(); + scopeBMeter.counterBuilder("scopeBCounter").build().add(1); + } + // End scopeB + + } finally { + spanA.end(); + scopeAMeter.counterBuilder("scopeACounter").build().add(1); + } + // End scopeA + } +} diff --git a/sdk/all/src/test/java/io/opentelemetry/sdk/common/SystemClockTest.java b/sdk/all/src/test/java/io/opentelemetry/sdk/common/SystemClockTest.java index 5472a6a99e1..2f374c1568b 100644 --- a/sdk/all/src/test/java/io/opentelemetry/sdk/common/SystemClockTest.java +++ b/sdk/all/src/test/java/io/opentelemetry/sdk/common/SystemClockTest.java @@ -9,32 +9,54 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnJre; -import org.junit.jupiter.api.condition.EnabledOnJre; import org.junit.jupiter.api.condition.JRE; -// This test is placed in the all artifact instead of the common one so it uses the dependency jar -// instead of the classes directly, which allows verifying mrjar behavior. class SystemClockTest { - @EnabledOnJre(JRE.JAVA_8) @Test - void millisPrecision() { + void now() { + assertThat(SystemClock.getInstance().now()).isNotZero(); + assertThat(SystemClock.getInstance().now(true)).isNotZero(); + assertThat(SystemClock.getInstance().now(false)).isNotZero(); + } + + @Test + // On java 8, the APIs used to produce micro precision are available but still only produce millis + // precision + @DisabledOnJre(JRE.JAVA_8) + void now_microsPrecision() { + // If we test many times, we can be fairly sure we get at least one timestamp that isn't + // coincidentally rounded to millis precision. + int numHasMicros = 0; + for (int i = 0; i < 100; i++) { + long now = SystemClock.getInstance().now(); + if (now % 1000000 != 0) { + numHasMicros++; + } + } + assertThat(numHasMicros).isNotZero(); + } + + @Test + void now_lowPrecision() { // If we test many times, we can be fairly sure we didn't just get lucky with having a rounded // result on a higher than expected precision timestamp. for (int i = 0; i < 100; i++) { - long now = SystemClock.getInstance().now(); + long now = SystemClock.getInstance().now(false); assertThat(now % 1000000).isZero(); } } - @DisabledOnJre(JRE.JAVA_8) @Test - void microsPrecision() { + // On java 8, the APIs used to produce micro precision are available but still only produce millis + // precision + @DisabledOnJre(JRE.JAVA_8) + void now_highPrecision() { // If we test many times, we can be fairly sure we get at least one timestamp that isn't // coincidentally rounded to millis precision. int numHasMicros = 0; for (int i = 0; i < 100; i++) { - long now = SystemClock.getInstance().now(); + long now = SystemClock.getInstance().now(true); if (now % 1000000 != 0) { numHasMicros++; } diff --git a/sdk/all/src/testIncubating/java/io/opentelemetry/sdk/internal/ExtendedOpenTelemetrySdkTest.java b/sdk/all/src/testIncubating/java/io/opentelemetry/sdk/internal/ExtendedOpenTelemetrySdkTest.java new file mode 100644 index 00000000000..eaf620933be --- /dev/null +++ b/sdk/all/src/testIncubating/java/io/opentelemetry/sdk/internal/ExtendedOpenTelemetrySdkTest.java @@ -0,0 +1,108 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; + +class ExtendedOpenTelemetrySdkTest { + + private static final Resource RESOURCE_A = + Resource.create(Attributes.of(AttributeKey.stringKey("a"), "1")); + private static final Resource RESOURCE_B = + Resource.create(Attributes.of(AttributeKey.stringKey("b"), "2")); + + @Test + void getSdkResourceProvider_defaultResources_returnsAutoWrapped() { + ExtendedOpenTelemetrySdk sdk = buildExtended(null, null, null, null, null, null); + + assertThat(sdk.getSdkResourceProvider().getResource()).isEqualTo(Resource.getDefault()); + } + + @Test + void getSdkResourceProvider_sameSdkResourceProviderOnAll_returnsIt() { + SdkResourceProvider resourceProvider = SdkResourceProvider.create(RESOURCE_A); + ExtendedOpenTelemetrySdk sdk = + buildExtended(null, resourceProvider, null, resourceProvider, null, resourceProvider); + + assertThat(sdk.getSdkResourceProvider()).isSameAs(resourceProvider); + } + + @Test + void getSdkResourceProvider_equivalentAutoWrappedResources_returnsFirst() { + // Distinct RP instances resolving to the same Resource: composite check is equal-by-Resource + // so this must succeed. + ExtendedOpenTelemetrySdk sdk = + buildExtended(RESOURCE_A, null, RESOURCE_A, null, RESOURCE_A, null); + + assertThat(sdk.getSdkResourceProvider().getResource()).isEqualTo(RESOURCE_A); + } + + @Test + void getSdkResourceProvider_mismatchedResources_throws() { + ExtendedOpenTelemetrySdk sdk = + buildExtended(RESOURCE_A, null, RESOURCE_B, null, RESOURCE_A, null); + + assertThatThrownBy(sdk::getSdkResourceProvider) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("configured with different"); + } + + private static ExtendedOpenTelemetrySdk buildExtended( + @Nullable Resource tracerResource, + @Nullable SdkResourceProvider tracerRp, + @Nullable Resource meterResource, + @Nullable SdkResourceProvider meterRp, + @Nullable Resource loggerResource, + @Nullable SdkResourceProvider loggerRp) { + SdkTracerProviderBuilder tracerBuilder = SdkTracerProvider.builder(); + if (tracerResource != null) { + tracerBuilder.setResource(tracerResource); + } + if (tracerRp != null) { + SdkTracerProviderUtil.setSdkResourceProvider(tracerBuilder, tracerRp); + } + SdkMeterProviderBuilder meterBuilder = + SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()); + if (meterResource != null) { + meterBuilder.setResource(meterResource); + } + if (meterRp != null) { + SdkMeterProviderUtil.setSdkResourceProvider(meterBuilder, meterRp); + } + SdkLoggerProviderBuilder loggerBuilder = SdkLoggerProvider.builder(); + if (loggerResource != null) { + loggerBuilder.setResource(loggerResource); + } + if (loggerRp != null) { + SdkLoggerProviderUtil.setSdkResourceProvider(loggerBuilder, loggerRp); + } + return (ExtendedOpenTelemetrySdk) + OpenTelemetrySdk.builder() + .setTracerProvider(tracerBuilder.build()) + .setMeterProvider(meterBuilder.build()) + .setLoggerProvider(loggerBuilder.build()) + .build(); + } +} diff --git a/sdk/common/README.md b/sdk/common/README.md deleted file mode 100644 index ca0d8b5d9b8..00000000000 --- a/sdk/common/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry SDK Common - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-common.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-common diff --git a/sdk/common/build.gradle.kts b/sdk/common/build.gradle.kts index bec2d637cf8..f046ea24554 100644 --- a/sdk/common/build.gradle.kts +++ b/sdk/common/build.gradle.kts @@ -1,83 +1,33 @@ +import io.opentelemetry.gradle.OtelVersionClassPlugin + plugins { id("otel.java-conventions") id("otel.publish-conventions") - id("otel.animalsniffer-conventions") + id("otel.jmh-conventions") } +apply() description = "OpenTelemetry SDK Common" otelJava.moduleName.set("io.opentelemetry.sdk.common") - -val mrJarVersions = listOf(9) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) dependencies { api(project(":api:all")) - - implementation(project(":semconv")) + compileOnly(project(":api:incubator")) annotationProcessor("com.google.auto.value:auto-value") testAnnotationProcessor("com.google.auto.value:auto-value") testImplementation(project(":sdk:testing")) - testImplementation(project(":sdk-extensions:resources")) testImplementation("com.google.guava:guava-testlib") -} - -testing { - suites { - val testResourceDisabledByProperty by registering(JvmTestSuite::class) - val testResourceDisabledByEnv by registering(JvmTestSuite::class) - } -} - -for (version in mrJarVersions) { - sourceSets { - create("java$version") { - java { - setSrcDirs(listOf("src/main/java$version")) - } - } - } - - tasks { - named("compileJava${version}Java") { - sourceCompatibility = "$version" - targetCompatibility = "$version" - options.release.set(version) - } - } - - configurations { - named("java${version}Implementation") { - extendsFrom(configurations["implementation"]) - } - } - - dependencies { - // Common to reference classes in main sourceset from Java 9 one (e.g., to return a common interface) - add("java${version}Implementation", files(sourceSets.main.get().output.classesDirs)) - } + testImplementation("io.opentelemetry.semconv:opentelemetry-semconv-incubating") } tasks { - withType(Jar::class) { - for (version in mrJarVersions) { - into("META-INF/versions/$version") { - from(sourceSets["java$version"].output) - } - } - manifest.attributes( - "Multi-Release" to "true" - ) - } - test { // For checking version number included in Resource. systemProperty("otel.test.project-version", project.version.toString()) } - - check { - dependsOn(testing.suites) - } } diff --git a/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/AttributesMapBenchmark.java b/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/AttributesMapBenchmark.java new file mode 100644 index 00000000000..e0baa45e405 --- /dev/null +++ b/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/AttributesMapBenchmark.java @@ -0,0 +1,139 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; + +import io.opentelemetry.api.common.AttributeKey; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.Blackhole; + +/** + * Microbenchmark for {@link AttributesMap}. Parametrized by number of attributes. + * + *

      Write scenarios: + * + *

        + *
      • {@code uniqueKeys} β€” normal production case: each key name is distinct + *
      • {@code putThenForEach} β€” combined write + export cycle: N unique puts followed by one + * {@code forEach}, modeling the dominant span lifecycle + *
      + * + *

      Read scenarios (run on a pre-filled map of {@code numAttributes} unique string entries): + * + *

        + *
      • {@code getHit} β€” lookup with the exact stored key type (hit) + *
      • {@code getTypeMiss} β€” lookup with a different type for the same key name (type miss) + *
      • {@code forEachAll} β€” full iteration over all entries + *
      + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5, time = 200, timeUnit = TimeUnit.MILLISECONDS) +@Measurement(iterations = 10, time = 200, timeUnit = TimeUnit.MILLISECONDS) +@Fork(2) +@State(Scope.Thread) +public class AttributesMapBenchmark { + + // Default SpanLimits attribute count limit. + private static final int CAPACITY = 128; + + @Param({"4", "16", "20", "32", "128"}) + int numAttributes; + + private List> stringKeys; + private List> boolKeys; + private List values; + + // Pre-filled map used by read benchmarks β€” populated once in @Setup. + private AttributesMap filledMap; + + @Setup + public void setup() { + stringKeys = new ArrayList<>(numAttributes); + boolKeys = new ArrayList<>(numAttributes); + values = new ArrayList<>(numAttributes); + for (int i = 0; i < numAttributes; i++) { + stringKeys.add(stringKey("key" + i)); + boolKeys.add(booleanKey("key" + i)); + values.add("value" + i); + } + filledMap = AttributesMap.create(CAPACITY, Integer.MAX_VALUE); + for (int i = 0; i < numAttributes; i++) { + filledMap.put(stringKeys.get(i), values.get(i)); + } + } + + /** Each key name is unique β€” the common production case. */ + @Benchmark + public AttributesMap uniqueKeys() { + AttributesMap map = AttributesMap.create(CAPACITY, Integer.MAX_VALUE); + for (int i = 0; i < numAttributes; i++) { + map.put(stringKeys.get(i), values.get(i)); + } + return map; + } + + // ---- Read benchmarks (operate on pre-filled map) ---- + + /** + * Lookup with the exact stored key type β€” always a hit. Measures the cost of a successful {@code + * get()} for each entry in the map. + */ + @Benchmark + public void getHit(Blackhole bh) { + for (int i = 0; i < numAttributes; i++) { + bh.consume(filledMap.get(stringKeys.get(i))); + } + } + + /** + * Lookup with a different type for the same key name β€” always returns null. + * + *

      The map holds N string-typed entries; boolean keys for the same names locate each entry by + * name but fail the type check. Isolates the cost of a name-hit / type-miss lookup. + */ + @Benchmark + public void getTypeMiss(Blackhole bh) { + for (int i = 0; i < numAttributes; i++) { + bh.consume(filledMap.get(boolKeys.get(i))); + } + } + + /** Full iteration over all entries via {@code forEach}. */ + @Benchmark + public void forEachAll(Blackhole bh) { + filledMap.forEach((k, v) -> bh.consume(v)); + } + + /** + * Combined write + read cycle: fill a fresh map with N unique string keys, then iterate all + * entries once. Models the dominant production path: N puts during span building, followed by one + * forEach at export time. + */ + @Benchmark + public void putThenForEach(Blackhole bh) { + AttributesMap map = AttributesMap.create(CAPACITY, Integer.MAX_VALUE); + for (int i = 0; i < numAttributes; i++) { + map.put(stringKeys.get(i), values.get(i)); + } + map.forEach((k, v) -> bh.consume(v)); + } +} diff --git a/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java b/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java new file mode 100644 index 00000000000..0421592df51 --- /dev/null +++ b/sdk/common/src/jmh/java/io/opentelemetry/sdk/common/internal/StacktraceRenderBenchmark.java @@ -0,0 +1,106 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.concurrent.TimeUnit; +import java.util.function.BiFunction; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +/** + * This benchmark compares the performance of {@link StackTraceRenderer}, the custom length limit + * aware exception render, to the built-in JDK stacktrace renderer {@link + * Throwable#printStackTrace(PrintStream)}. + */ +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS) +@Measurement(iterations = 5, time = 100, timeUnit = TimeUnit.MILLISECONDS) +@Fork(1) +@SuppressWarnings("StaticAssignmentOfThrowable") +public class StacktraceRenderBenchmark { + + private static final Exception simple = new Exception("error"); + private static final Exception complex = + new Exception("error", new Exception("cause1", new Exception("cause2"))); + + static { + complex.addSuppressed(new Exception("suppressed1")); + complex.addSuppressed(new Exception("suppressed2", new Exception("cause"))); + } + + @State(Scope.Benchmark) + public static class BenchmarkState { + + @Param Renderer renderer; + @Param ExceptionParam exceptionParam; + + @Param({"10", "1000", "100000"}) + int lengthLimit; + } + + @SuppressWarnings("ImmutableEnumChecker") + public enum Renderer { + JDK((throwable, limit) -> { + StringWriter stringWriter = new StringWriter(); + try (PrintWriter printWriter = new PrintWriter(stringWriter)) { + throwable.printStackTrace(printWriter); + } + String stacktrace = stringWriter.toString(); + return stacktrace.substring(0, Math.min(stacktrace.length(), limit)); + }), + CUSTOM((throwable, limit) -> new StackTraceRenderer(throwable, limit).render()); + + private final BiFunction renderer; + + Renderer(BiFunction renderer) { + this.renderer = renderer; + } + + BiFunction renderer() { + return renderer; + } + } + + @SuppressWarnings("ImmutableEnumChecker") + public enum ExceptionParam { + SIMPLE(simple), + COMPLEX(complex); + + private final Throwable throwable; + + ExceptionParam(Throwable throwable) { + this.throwable = throwable; + } + + Throwable throwable() { + return throwable; + } + } + + @Benchmark + @Threads(1) + @SuppressWarnings("ReturnValueIgnored") + public void render(BenchmarkState benchmarkState) { + BiFunction renderer = benchmarkState.renderer.renderer(); + Throwable throwable = benchmarkState.exceptionParam.throwable(); + int limit = benchmarkState.lengthLimit; + + renderer.apply(throwable, limit); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/Clock.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/Clock.java index 9c61dce3271..dab812ebe3b 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/common/Clock.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/Clock.java @@ -34,9 +34,29 @@ static Clock getDefault() { * // Spend time... * long durationNanos = clock.now() - startNanos; * }

      + * + *

      Calling this is equivalent to calling {@link #now(boolean)} with {@code highPrecision=true}. */ long now(); + /** + * Returns the current epoch timestamp in nanos from this clock. + * + *

      This overload of {@link #now()} includes a {@code highPrecision} argument which specifies + * whether the implementation should attempt to resolve higher precision at the potential expense + * of performance. For example, in java 9+ its sometimes possible to resolve ns precision higher + * than the ms precision of {@link System#currentTimeMillis()}, but doing so incurs a performance + * penalty which some callers may wish to avoid. In contrast, we don't currently know if resolving + * ns precision is possible in java 8, regardless of the value of {@code highPrecision}. + * + *

      See {@link #now()} javadoc for details on usage. + * + * @since 1.38.0 + */ + default long now(boolean highPrecision) { + return now(); + } + /** * Returns a time measurement with nanosecond precision that can only be used to calculate elapsed * time. diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java index b7f7fa944fd..f53cbf95d38 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/CompletableResultCode.java @@ -8,11 +8,15 @@ import io.opentelemetry.api.internal.GuardedBy; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.logging.Level; +import java.util.logging.Logger; import javax.annotation.Nullable; /** @@ -23,6 +27,9 @@ * convey a result at a later time. CompletableResultCode facilitates this. */ public final class CompletableResultCode { + + private static final Logger logger = Logger.getLogger(CompletableResultCode.class.getName()); + /** Returns a {@link CompletableResultCode} that has been completed successfully. */ public static CompletableResultCode ofSuccess() { return SUCCESS; @@ -33,9 +40,21 @@ public static CompletableResultCode ofFailure() { return FAILURE; } + /** + * Returns a {@link CompletableResultCode} that has been {@link #failExceptionally(Throwable) + * failed exceptionally}. + * + * @since 1.41.0 + */ + public static CompletableResultCode ofExceptionalFailure(Throwable throwable) { + return new CompletableResultCode().failExceptionally(throwable); + } + /** * Returns a {@link CompletableResultCode} that completes after all the provided {@link - * CompletableResultCode}s complete. If any of the results fail, the result will be failed. + * CompletableResultCode}s complete. If any of the results fail, the result will be failed. If any + * {@link #failExceptionally(Throwable) failed exceptionally}, the result will be failed + * exceptionally with the first {@link Throwable} from {@code codes}. */ public static CompletableResultCode ofAll(Collection codes) { if (codes.isEmpty()) { @@ -44,20 +63,24 @@ public static CompletableResultCode ofAll(Collection code CompletableResultCode result = new CompletableResultCode(); AtomicInteger pending = new AtomicInteger(codes.size()); AtomicBoolean failed = new AtomicBoolean(); + AtomicReference throwableRef = new AtomicReference<>(); for (CompletableResultCode code : codes) { - code.whenComplete( - () -> { - if (!code.isSuccess()) { - failed.set(true); - } - if (pending.decrementAndGet() == 0) { - if (failed.get()) { - result.fail(); - } else { - result.succeed(); - } - } - }); + code.whenComplete(() -> { + if (!code.isSuccess()) { + failed.set(true); + Throwable codeThrowable = code.getFailureThrowable(); + if (codeThrowable != null) { + throwableRef.compareAndSet(null, codeThrowable); + } + } + if (pending.decrementAndGet() == 0) { + if (failed.get()) { + result.failInternal(throwableRef.get()); + } else { + result.succeed(); + } + } + }); } return result; } @@ -71,6 +94,10 @@ public CompletableResultCode() {} @GuardedBy("lock") private Boolean succeeded = null; + @Nullable + @GuardedBy("lock") + private Throwable throwable = null; + @GuardedBy("lock") private final List completionActions = new ArrayList<>(); @@ -78,33 +105,75 @@ public CompletableResultCode() {} /** Complete this {@link CompletableResultCode} successfully if it is not already completed. */ public CompletableResultCode succeed() { + return complete(/* success= */ true, /* throwable= */ null); + } + + /** + * Complete this {@link CompletableResultCode} unsuccessfully if it is not already completed, + * setting the {@link #getFailureThrowable() failure throwable} to {@code null}. + */ + public CompletableResultCode fail() { + return failInternal(null); + } + + /** + * Completes this {@link CompletableResultCode} unsuccessfully if it is not already completed, + * setting the {@link #getFailureThrowable() failure throwable} to {@code throwable}. + * + * @param throwable the {@code Throwable} that caused the failure, or {@code null} + * @since 1.41.0 + */ + public CompletableResultCode failExceptionally(@Nullable Throwable throwable) { + return failInternal(throwable); + } + + private CompletableResultCode failInternal(@Nullable Throwable throwable) { + return complete(/* success= */ false, throwable); + } + + private CompletableResultCode complete(boolean success, @Nullable Throwable throwable) { + List actions = null; synchronized (lock) { if (succeeded == null) { - succeeded = true; - for (Runnable action : completionActions) { - action.run(); + succeeded = success; + if (!success) { + this.throwable = throwable; + } + if (!completionActions.isEmpty()) { + actions = new ArrayList<>(completionActions); + completionActions.clear(); } } } + // Completion actions run without the lock held. Running them under the lock lets an action + // which completes another result deadlock through lock inversion. + if (actions != null) { + runActions(actions); + } return this; } - /** Complete this {@link CompletableResultCode} unsuccessfully if it is not already completed. */ - public CompletableResultCode fail() { - synchronized (lock) { - if (succeeded == null) { - succeeded = false; - for (Runnable action : completionActions) { - action.run(); + private static void runActions(List actions) { + RuntimeException firstException = null; + for (Runnable action : actions) { + try { + action.run(); + } catch (RuntimeException e) { + // Continue executing the remaining actions, so ofAll is not blocked from completing. + logger.log(Level.WARNING, "Exception thrown by completion action.", e); + if (firstException == null) { + firstException = e; } } } - return this; + if (firstException != null) { + throw firstException; + } } /** * Obtain the current state of completion. Generally call once completion is achieved via the - * thenRun method. + * {@link #whenComplete(Runnable)} method. * * @return the current state of completion */ @@ -115,7 +184,27 @@ public boolean isSuccess() { } /** - * Perform an action on completion. Actions are guaranteed to be called only once. + * Returns {@link Throwable} if this {@link CompletableResultCode} was {@link + * #failExceptionally(Throwable) failed exceptionally}. Generally call once completion is achieved + * via the {@link #whenComplete(Runnable)} method. + * + * @return the throwable if failed exceptionally, or null if: {@link #fail() failed without + * exception}, {@link #succeed() succeeded}, {@link #failExceptionally(Throwable)} with a null + * {@code throwable}, or not complete. + * @since 1.41.0 + */ + @Nullable + public Throwable getFailureThrowable() { + synchronized (lock) { + return throwable; + } + } + + /** + * Perform an action on completion. Actions are guaranteed to be called only once. Actions are not + * invoked while internal locks are held. Every action runs even if an earlier one throws a {@link + * RuntimeException}. Each exception is logged, and the first one is rethrown after all the + * actions have executed. * * @param action the action to perform * @return this completable result so that it may be further composed @@ -130,7 +219,7 @@ public CompletableResultCode whenComplete(Runnable action) { } } if (runNow) { - action.run(); + runActions(Collections.singletonList(action)); } return this; } diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfo.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfo.java index 2980d369d2d..249840b05d6 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfo.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfo.java @@ -8,6 +8,7 @@ import static java.util.Objects.requireNonNull; import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @@ -26,15 +27,35 @@ public abstract class InstrumentationScopeInfo { /** Creates a new instance of {@link InstrumentationScopeInfo}. */ public static InstrumentationScopeInfo create(String name) { - requireNonNull(name, "name"); - return new AutoValue_InstrumentationScopeInfo(name, null, null); + return InstrumentationScopeInfo.create(name, null, null, Attributes.empty()); } - /** Creates a new instance of {@link InstrumentationScopeInfo}. */ + /** + * Creates a new instance of {@link InstrumentationScopeInfo}. + * + * @deprecated Use {@link #builder(String)} or {@link #create(String)}. + */ + @Deprecated public static InstrumentationScopeInfo create( String name, @Nullable String version, @Nullable String schemaUrl) { + return InstrumentationScopeInfo.create(name, version, schemaUrl, Attributes.empty()); + } + + static InstrumentationScopeInfo create( + String name, @Nullable String version, @Nullable String schemaUrl, Attributes attributes) { requireNonNull(name, "name"); - return new AutoValue_InstrumentationScopeInfo(name, version, schemaUrl); + requireNonNull(attributes, "attributes"); + return new AutoValue_InstrumentationScopeInfo(name, version, schemaUrl, attributes); + } + + /** + * Returns a {@link InstrumentationScopeInfoBuilder builder} for a {@link + * InstrumentationScopeInfo}. + * + * @since 1.18.0 + */ + public static InstrumentationScopeInfoBuilder builder(String name) { + return new InstrumentationScopeInfoBuilder(name); } /** Returns an "empty" {@link InstrumentationScopeInfo}. */ @@ -56,5 +77,12 @@ public static InstrumentationScopeInfo empty() { @Nullable public abstract String getSchemaUrl(); + /** + * Returns the attributes of this instrumentation scope. + * + * @since 1.18.0 + */ + public abstract Attributes getAttributes(); + InstrumentationScopeInfo() {} } diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoBuilder.java new file mode 100644 index 00000000000..15729b78cf7 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoBuilder.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common; + +import io.opentelemetry.api.common.Attributes; +import javax.annotation.Nullable; + +/** + * A builder for {@link InstrumentationScopeInfo}. + * + * @since 1.18.0 + */ +public final class InstrumentationScopeInfoBuilder { + + private final String name; + @Nullable private String version; + @Nullable private String schemaUrl; + @Nullable private Attributes attributes; + + InstrumentationScopeInfoBuilder(String name) { + this.name = name; + } + + /** Set the version. */ + public InstrumentationScopeInfoBuilder setVersion(String version) { + this.version = version; + return this; + } + + /** Set the schema URL. */ + public InstrumentationScopeInfoBuilder setSchemaUrl(String schemaUrl) { + this.schemaUrl = schemaUrl; + return this; + } + + /** Set the attributes. */ + public InstrumentationScopeInfoBuilder setAttributes(Attributes attributes) { + this.attributes = attributes; + return this; + } + + /** Return a {@link InstrumentationScopeInfo} with the configuration of this builder. */ + public InstrumentationScopeInfo build() { + return InstrumentationScopeInfo.create( + name, version, schemaUrl, attributes == null ? Attributes.empty() : attributes); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/InternalTelemetryVersion.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/InternalTelemetryVersion.java new file mode 100644 index 00000000000..e575ce6b686 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/InternalTelemetryVersion.java @@ -0,0 +1,24 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common; + +/** + * Defines the self-monitoring telemetry SDK components should capture. + * + * @since 1.51.0 + */ +public enum InternalTelemetryVersion { + /** + * Record self-monitoring metrics defined in the SDK prior to the standardization in semantic + * conventions. + */ + LEGACY, + /** + * Record self-monitoring metrics defined in the latest semantic conventions version supported by + * this SDK version. + */ + LATEST +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/SystemClock.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/SystemClock.java index 11ac0179ea0..c03957b4d89 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/common/SystemClock.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/SystemClock.java @@ -5,10 +5,14 @@ package io.opentelemetry.sdk.common; -import io.opentelemetry.sdk.internal.JavaVersionSpecific; +import java.time.Instant; +import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; -/** A {@link Clock} that uses {@link System#currentTimeMillis()} and {@link System#nanoTime()}. */ +/** + * A {@link Clock} that uses {@link java.time.Clock#systemUTC()}, {@link + * System#currentTimeMillis()}, and {@link System#nanoTime()}. + */ @ThreadSafe final class SystemClock implements Clock { @@ -16,18 +20,23 @@ final class SystemClock implements Clock { private SystemClock() {} - /** - * Returns a {@code MillisClock}. - * - * @return a {@code MillisClock}. - */ + /** Returns a {@link SystemClock}. */ static Clock getInstance() { return INSTANCE; } @Override public long now() { - return JavaVersionSpecific.get().currentTimeNanos(); + return now(true); + } + + @Override + public long now(boolean highPrecision) { + if (highPrecision) { + Instant now = java.time.Clock.systemUTC().instant(); + return TimeUnit.SECONDS.toNanos(now.getEpochSecond()) + now.getNano(); + } + return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); } @Override diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/Compressor.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/Compressor.java new file mode 100644 index 00000000000..8b560ccfefa --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/Compressor.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.io.IOException; +import java.io.OutputStream; +import javax.annotation.concurrent.ThreadSafe; + +/** + * A service provider interface (SPI) for compression. Implementation MUST be thread safe as the + * same instance is expected to be used many times and concurrently. + * + * @since 1.59.0 + */ +@ThreadSafe +public interface Compressor { + + /** + * The name of the compressor encoding. + * + *

      Used to identify the compressor during configuration and to populate the {@code + * Content-Encoding} header. + */ + String getEncoding(); + + /** Wrap the {@code outputStream} with a compressing output stream. */ + OutputStream compress(OutputStream outputStream) throws IOException; +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcResponse.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcResponse.java new file mode 100644 index 00000000000..68992c5e0ec --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcResponse.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.util.function.Consumer; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * A gRPC response. + * + * @see GrpcSender#send(MessageWriter, Consumer, Consumer) + * @since 1.59.0 + */ +@Immutable +public interface GrpcResponse { + + /** The response gRPC status code. */ + GrpcStatusCode getStatusCode(); + + /** A string description of the status. */ + @Nullable + String getStatusDescription(); + + /** + * The unframed gRPC response protobuf message bytes, stripped of the length / compression prefix, + * and decompressed. The resulting bytes are deserialized to an in-memory representation of the + * protobuf message without any additional context. + */ + @SuppressWarnings("mutable") + byte[] getResponseMessage(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSender.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSender.java new file mode 100644 index 00000000000..047d99eccec --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSender.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import java.util.function.Consumer; + +/** + * An abstraction for executing gRPC calls, allowing for implementations backed by different client + * libraries. + * + *

      While this interface is public, implementing a custom sender is generally not recommended. The + * {@code opentelemetry-java} project provides built-in implementations that cover virtually all + * cases. + * + * @see GrpcSenderProvider + * @since 1.59.0 + */ +public interface GrpcSender { + + /** + * Execute a gRPC unary call, including any retry attempts. {@code onResponse} is called with the + * gRPC response, either a success response or an error response after retries. {@code onError} is + * called when the call could not be executed due to cancellation, connectivity problems, or + * timeout. + * + *

      The byte array returned by {@link GrpcResponse#getResponseMessage()} should contain at most + * {@link GrpcSenderConfig#getMaxResponseBodySize()} bytes. + * + * @param messageWriter the message writer + * @param onResponse the callback to invoke with the gRPC response + * @param onError the callback to invoke when the gRPC call could not be executed + */ + void send( + MessageWriter messageWriter, Consumer onResponse, Consumer onError); + + /** Shutdown the sender. */ + CompletableResultCode shutdown(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSenderConfig.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSenderConfig.java new file mode 100644 index 00000000000..d768bda5d68 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSenderConfig.java @@ -0,0 +1,120 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.io.OutputStream; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Configuration for {@link GrpcSender} implementations, provided via {@link + * GrpcSenderProvider#createSender(GrpcSenderConfig)}. + * + * @since 1.59.0 + */ +@Immutable +public interface GrpcSenderConfig { + + /** + * The gRPC endpoint to send to, including scheme. Omits path, which must be obtained from {@link + * #getFullMethodName()}. + */ + URI getEndpoint(); + + /** + * The fully qualified gRPC method name, e.g. {@code + * opentelemetry.proto.collector.trace.v1.TraceService/Export}. + */ + String getFullMethodName(); + + /** + * The compressor, or {@code null} if no compression is used. If present, {@link + * Compressor#compress(OutputStream)} must be applied to {@link + * MessageWriter#writeMessage(OutputStream)} when {@link GrpcSender#send(MessageWriter, Consumer, + * Consumer)} is called and {@link Compressor#getEncoding()} must be set as the {@code + * grpc-encoding}. + */ + @Nullable + Compressor getCompressor(); + + /** + * The max duration allowed to send a request, including resolving DNS, connecting, writing the + * request, reading the response, and any retries via {@link #getRetryPolicy()}. + */ + Duration getTimeout(); + + /** The max duration allowed to connect to a target host. */ + Duration getConnectTimeout(); + + /** + * Additional headers that must be appended to every request. The resulting {@link Supplier} must + * be invoked for each request. + */ + Supplier>> getHeadersSupplier(); + + /** The retry policy, or {@code null} if retry is disabled. */ + @Nullable + RetryPolicy getRetryPolicy(); + + /** + * The SSL context to use, or {@code null} if the system default is used. If non-null, {@link + * #getTrustManager()} will also be non-null. + */ + @Nullable + SSLContext getSslContext(); + + /** + * The trust manager to use, or {@code null} if the system default is used. If non-null, {@link + * #getSslContext()} will also be non-null. + */ + @Nullable + X509TrustManager getTrustManager(); + + /** + * The executor service used to execute any asynchronous processing, or {@code null} if the sender + * default executor service should be used. + */ + @Nullable + ExecutorService getExecutorService(); + + /** + * The maximum number of bytes to read from a response body. Defaults to 4 MiB. + * + *

      Warning: setting a high or unbounded limit allows a malicious or misconfigured server to + * cause unbounded heap allocation, potentially leading to out-of-memory errors. + * + * @since 1.61.0 + */ + default long getMaxResponseBodySize() { + return 4 * 1024L * 1024L; + } + + /** + * The TLS protocol versions to enable when connecting to an HTTPS endpoint, or {@code null} to + * defer to the sender implementation's default. + * + *

      Protocol names follow the JSSE convention: {@code "TLSv1"}, {@code "TLSv1.1"}, {@code + * "TLSv1.2"}, {@code "TLSv1.3"}. When set, only the listed versions will be enabled. + * + *

      Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + @Nullable + default List getEnabledProtocols() { + return null; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSenderProvider.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSenderProvider.java new file mode 100644 index 00000000000..31f5f5ca754 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcSenderProvider.java @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +/** + * A service provider interface (SPI) for providing {@link GrpcSender}s backed by different client + * libraries. + * + * @since 1.59.0 + */ +public interface GrpcSenderProvider { + + /** Returns a {@link GrpcSender} configured with the provided config. */ + GrpcSender createSender(GrpcSenderConfig grpcSenderConfig); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcStatusCode.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcStatusCode.java new file mode 100644 index 00000000000..9ffae3cec15 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/GrpcStatusCode.java @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +/** + * gRPC status codes. See official grpc.io + * docs for usage. + * + * @since 1.59.0 + */ +public enum GrpcStatusCode { + OK(0), + CANCELLED(1), + UNKNOWN(2), + INVALID_ARGUMENT(3), + DEADLINE_EXCEEDED(4), + NOT_FOUND(5), + ALREADY_EXISTS(6), + PERMISSION_DENIED(7), + RESOURCE_EXHAUSTED(8), + FAILED_PRECONDITION(9), + ABORTED(10), + OUT_OF_RANGE(11), + UNIMPLEMENTED(12), + INTERNAL(13), + UNAVAILABLE(14), + DATA_LOSS(15), + UNAUTHENTICATED(16); + + private final int value; + + GrpcStatusCode(int value) { + this.value = value; + } + + /** Returns the integer representation of the status code. */ + public int getValue() { + return value; + } + + /** + * Returns the {@link GrpcStatusCode} corresponding to the integer {@code value}, or {@link + * GrpcStatusCode#UNKNOWN} if the {@code value} is not recognized. + */ + public static GrpcStatusCode fromValue(int value) { + GrpcStatusCode[] values = GrpcStatusCode.values(); + if (value >= 0 && value < values.length) { + return values[value]; + } + return UNKNOWN; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpResponse.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpResponse.java new file mode 100644 index 00000000000..390969ab9f2 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpResponse.java @@ -0,0 +1,29 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.util.function.Consumer; +import javax.annotation.concurrent.Immutable; + +/** + * A HTTP response. + * + * @see HttpSender#send(MessageWriter, Consumer, Consumer) + * @since 1.59.0 + */ +@Immutable +public interface HttpResponse { + + /** The HTTP status code. */ + int getStatusCode(); + + /** The HTTP status message. */ + String getStatusMessage(); + + /** The HTTP response body bytes. */ + @SuppressWarnings("mutable") + byte[] getResponseBody(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSender.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSender.java new file mode 100644 index 00000000000..bf0d75524f1 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSender.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import java.util.function.Consumer; + +/** + * An abstraction for executing HTTP requests, allowing for implementations backed by different + * client libraries. + * + *

      While this interface is public, implementing a custom sender is generally not recommended. The + * {@code opentelemetry-java} project provides built-in implementations that cover virtually all + * cases. + * + * @see HttpSenderProvider + * @since 1.59.0 + */ +public interface HttpSender { + + /** + * Send an HTTP request, including any retry attempts. {@code onResponse} is called with the HTTP + * response, either a success response or an error response after retries. {@code onError} is + * called when the request could not be executed due to cancellation, connectivity problems, or + * timeout. + * + *

      The byte array returned by {@link HttpResponse#getResponseBody()} should contain at most + * {@link HttpSenderConfig#getMaxResponseBodySize()} bytes. + * + * @param messageWriter the request body message writer + * @param onResponse the callback to invoke with the HTTP response + * @param onError the callback to invoke when the HTTP request could not be executed + */ + void send( + MessageWriter messageWriter, Consumer onResponse, Consumer onError); + + /** Shutdown the sender. */ + CompletableResultCode shutdown(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSenderConfig.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSenderConfig.java new file mode 100644 index 00000000000..7be493232b2 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSenderConfig.java @@ -0,0 +1,118 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.io.OutputStream; +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; +import javax.net.ssl.SSLContext; +import javax.net.ssl.X509TrustManager; + +/** + * Configuration for {@link HttpSender} implementations, provided via {@link + * HttpSenderProvider#createSender(HttpSenderConfig)}. + * + * @since 1.59.0 + */ +@Immutable +public interface HttpSenderConfig { + + /** The fully qualified endpoint to send to, including scheme and path. */ + URI getEndpoint(); + + /** The payload content type to set as the {@code Content-Type} header. */ + String getContentType(); + + /** + * The compressor, or {@code null} if no compression is used. If present, {@link + * Compressor#compress(OutputStream)} must be applied to {@link + * MessageWriter#writeMessage(OutputStream)} when {@link HttpSender#send(MessageWriter, Consumer, + * Consumer)} is called and {@link Compressor#getEncoding()} must be set as the {@code + * Content-Encoding} header. + */ + @Nullable + Compressor getCompressor(); + + /** + * The max duration allowed to send a request, including resolving DNS, connecting, writing the + * request, reading the response, and any retries via {@link #getRetryPolicy()}. + */ + Duration getTimeout(); + + /** The max duration allowed to connect to a target host. */ + Duration getConnectTimeout(); + + /** + * Additional headers that must be appended to every request. The resulting {@link Supplier} must + * be invoked for each request. + */ + Supplier>> getHeadersSupplier(); + + /** The proxy options, or {@code null} if no proxy is used. */ + @Nullable + ProxyOptions getProxyOptions(); + + /** The retry policy, or {@code null} if retry is disabled. */ + @Nullable + RetryPolicy getRetryPolicy(); + + /** + * The SSL context to use, or {@code null} if the system default is used. If non-null, {@link + * #getTrustManager()} will also be non-null. + */ + @Nullable + SSLContext getSslContext(); + + /** + * The trust manager to use, or {@code null} if the system default is used. If non-null, {@link + * #getSslContext()} will also be non-null. + */ + @Nullable + X509TrustManager getTrustManager(); + + /** + * The executor service used to execute any asynchronous processing, or {@code null} if the sender + * default executor service should be used. + */ + @Nullable + ExecutorService getExecutorService(); + + /** + * The maximum number of bytes to read from a response body. Defaults to 4 MiB. + * + *

      Warning: setting a high or unbounded limit allows a malicious or misconfigured server to + * cause unbounded heap allocation, potentially leading to out-of-memory errors. + * + * @since 1.61.0 + */ + default long getMaxResponseBodySize() { + return 4 * 1024L * 1024L; + } + + /** + * The TLS protocol versions to enable when connecting to an HTTPS endpoint, or {@code null} to + * defer to the sender implementation's default. + * + *

      Protocol names follow the JSSE convention: {@code "TLSv1"}, {@code "TLSv1.1"}, {@code + * "TLSv1.2"}, {@code "TLSv1.3"}. When set, only the listed versions will be enabled. + * + *

      Note: enabling legacy protocol versions (TLSv1, TLSv1.1) also requires removing them from + * the JVM's {@code jdk.tls.disabledAlgorithms} security property. + * + * @since 1.66.0 + */ + @Nullable + default List getEnabledProtocols() { + return null; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSenderProvider.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSenderProvider.java new file mode 100644 index 00000000000..9ae2d21a59e --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/HttpSenderProvider.java @@ -0,0 +1,18 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +/** + * A service provider interface (SPI) for providing {@link HttpSender}s backed by different HTTP + * client libraries. + * + * @since 1.59.0 + */ +public interface HttpSenderProvider { + + /** Returns a {@link HttpSender} configured with the provided config. */ + HttpSender createSender(HttpSenderConfig httpSenderConfig); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/MemoryMode.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/MemoryMode.java new file mode 100644 index 00000000000..4ebf23a9deb --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/MemoryMode.java @@ -0,0 +1,48 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +/** + * The memory semantics of the SDK. + * + * @since 1.31.0 + */ +public enum MemoryMode { + + /** + * Reuses objects to reduce allocations. + * + *

      In this mode, the SDK reuses objects to reduce allocations, at the expense of disallowing + * concurrent collections / exports. + * + *

      Metric Signal: For DELTA aggregation temporality, the memory used for recording and + * aggregating metric values is kept between MetricReader collect operation, to avoid memory + * allocations. When the configured maximum cardinality of Attributes is reached, unused + * Attributes are cleared from memory during collect operation, at the cost of requiring new + * memory allocations the next time those attributes are used. Allocations can be minimized by + * increasing the configured max cardinality. For example, suppose instrumentation has recorded + * values for 1000 unique Attributes while the max cardinality configured was 2000. If after a + * collection only 100 unique Attributes values are recorded, the MetricReader's collect operation + * would return 100 points, while in memory the Attributes data structure keeps 1000 unique + * Attributes. If a user recorded values for 3000 unique attributes, the values for the first 1999 + * Attributes would be recorded, and the rest of 1001 unique Attributes values would be recorded + * in the CARDINALITY_OVERFLOW Attributes. If after several collect operations, the user now + * records values to only 500 unique attributes, during collect operation, the unused 1500 + * Attributes memory would be cleared from memory. + */ + REUSABLE_DATA, + + /** + * Uses immutable data structures. + * + *

      In this mode, the SDK passes immutable objects to exporters / readers, increasing + * allocations but ensuring safe concurrent exports. + * + *

      Metric Signal: In DELTA aggregation temporality, the memory used for recording and + * aggregating Attributes values is cleared during a MetricReader collect operation. + */ + IMMUTABLE_DATA +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/MessageWriter.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/MessageWriter.java new file mode 100644 index 00000000000..16a78372d98 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/MessageWriter.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.io.IOException; +import java.io.OutputStream; + +/** + * Responsible for writing messages to an output stream. + * + * @since 1.59.0 + */ +public interface MessageWriter { + + /** Write the message to the {@link OutputStream}. */ + void writeMessage(OutputStream output) throws IOException; + + /** Return the message length in bytes, or -1 if the length is unknown. */ + int getContentLength(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/ProxyOptions.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/ProxyOptions.java new file mode 100644 index 00000000000..5e4ad463a92 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/ProxyOptions.java @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Proxy; +import java.net.ProxySelector; +import java.net.SocketAddress; +import java.net.URI; +import java.util.Collections; +import java.util.List; + +/** + * Configuration for proxy settings. + * + * @since 1.36.0 + */ +public final class ProxyOptions { + private final ProxySelector proxySelector; + + private ProxyOptions(ProxySelector proxySelector) { + this.proxySelector = proxySelector; + } + + /** Create proxy options with the {@code proxySelector}. */ + public static ProxyOptions create(ProxySelector proxySelector) { + return new ProxyOptions(proxySelector); + } + + /** + * Create proxy options with a {@link ProxySelector} which always uses an {@link Proxy.Type#HTTP} + * proxy with the {@code socketAddress}. + */ + public static ProxyOptions create(InetSocketAddress socketAddress) { + return new ProxyOptions(new SimpleProxySelector(new Proxy(Proxy.Type.HTTP, socketAddress))); + } + + /** Return the {@link ProxySelector}. */ + public ProxySelector getProxySelector() { + return proxySelector; + } + + @Override + public String toString() { + return "ProxyOptions{proxySelector=" + proxySelector + "}"; + } + + private static final class SimpleProxySelector extends ProxySelector { + + private final List proxyList; + + private SimpleProxySelector(Proxy proxy) { + this.proxyList = Collections.singletonList(proxy); + } + + @Override + public List select(URI uri) { + return proxyList; + } + + @Override + public void connectFailed(URI uri, SocketAddress sa, IOException e) { + // ignore + } + + @Override + public String toString() { + return "SimpleProxySelector{proxy=" + proxyList.get(0).toString() + "}"; + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/RetryPolicy.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/RetryPolicy.java new file mode 100644 index 00000000000..732dc1da1a2 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/export/RetryPolicy.java @@ -0,0 +1,141 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.export; + +import com.google.auto.value.AutoValue; +import java.io.IOException; +import java.time.Duration; +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** + * Configuration for exporter exponential retry policy. + * + * @since 1.28.0 + */ +@AutoValue +public abstract class RetryPolicy { + + private static final int DEFAULT_MAX_ATTEMPTS = 5; + + @SuppressWarnings("StronglyTypeTime") + private static final int DEFAULT_INITIAL_BACKOFF_SECONDS = 1; + + @SuppressWarnings("StronglyTypeTime") + private static final int DEFAULT_MAX_BACKOFF_SECONDS = 5; + + private static final double DEFAULT_BACKOFF_MULTIPLIER = 1.5; + + private static final RetryPolicy DEFAULT = RetryPolicy.builder().build(); + + RetryPolicy() {} + + /** Return the default {@link RetryPolicy}. */ + public static RetryPolicy getDefault() { + return DEFAULT; + } + + /** Returns a new {@link RetryPolicyBuilder} to construct a {@link RetryPolicy}. */ + public static RetryPolicyBuilder builder() { + return new AutoValue_RetryPolicy.Builder() + .setMaxAttempts(DEFAULT_MAX_ATTEMPTS) + .setInitialBackoff(Duration.ofSeconds(DEFAULT_INITIAL_BACKOFF_SECONDS)) + .setMaxBackoff(Duration.ofSeconds(DEFAULT_MAX_BACKOFF_SECONDS)) + .setBackoffMultiplier(DEFAULT_BACKOFF_MULTIPLIER); + } + + /** + * Returns a {@link RetryPolicyBuilder} reflecting configuration values for this {@link + * RetryPolicy}. + * + * @since 1.29.0 + */ + public abstract RetryPolicyBuilder toBuilder(); + + /** Returns the max number of attempts, including the original request. */ + public abstract int getMaxAttempts(); + + /** Returns the initial backoff. */ + public abstract Duration getInitialBackoff(); + + /** Returns the max backoff. */ + public abstract Duration getMaxBackoff(); + + /** Returns the backoff multiplier. */ + public abstract double getBackoffMultiplier(); + + /** + * Returns the predicate used to determine if an attempt which failed exceptionally should be + * retried, or {@code null} if the exporter specific default predicate should be used. + * + * @since 1.47.0 + */ + @Nullable + public abstract Predicate getRetryExceptionPredicate(); + + /** Builder for {@link RetryPolicy}. */ + @AutoValue.Builder + public abstract static class RetryPolicyBuilder { + + RetryPolicyBuilder() {} + + /** + * Set the maximum number of attempts, including the original request. Must be greater than 1 + * and less than 6. Defaults to {@value DEFAULT_MAX_ATTEMPTS}. + */ + public abstract RetryPolicyBuilder setMaxAttempts(int maxAttempts); + + /** + * Set the initial backoff. Must be greater than 0. Defaults to {@value + * DEFAULT_INITIAL_BACKOFF_SECONDS} seconds. + */ + public abstract RetryPolicyBuilder setInitialBackoff(Duration initialBackoff); + + /** + * Set the maximum backoff. Must be greater than 0. Defaults to {@value + * DEFAULT_MAX_BACKOFF_SECONDS} seconds. + */ + public abstract RetryPolicyBuilder setMaxBackoff(Duration maxBackoff); + + /** + * Set the backoff multiplier. Must be greater than 0.0. Defaults to {@value + * DEFAULT_BACKOFF_MULTIPLIER}. + */ + public abstract RetryPolicyBuilder setBackoffMultiplier(double backoffMultiplier); + + /** + * Set the predicate used to determine if an attempt which failed exceptionally should be + * retried. By default, an exporter specific default predicate should be used. + * + * @since 1.47.0 + */ + public abstract RetryPolicyBuilder setRetryExceptionPredicate( + Predicate retryExceptionPredicate); + + abstract RetryPolicy autoBuild(); + + /** Build and return a {@link RetryPolicy} with the values of this builder. */ + public RetryPolicy build() { + RetryPolicy retryPolicy = autoBuild(); + checkArgument( + retryPolicy.getMaxAttempts() > 1 && retryPolicy.getMaxAttempts() < 6, + "maxAttempts must be greater than 1 and less than 6"); + checkArgument( + retryPolicy.getInitialBackoff().toNanos() > 0, "initialBackoff must be greater than 0"); + checkArgument(retryPolicy.getMaxBackoff().toNanos() > 0, "maxBackoff must be greater than 0"); + checkArgument( + retryPolicy.getBackoffMultiplier() > 0, "backoffMultiplier must be greater than 0"); + + return retryPolicy; + } + + private static void checkArgument(boolean isValid, String errorMessage) { + if (!isValid) { + throw new IllegalArgumentException(errorMessage); + } + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/AndroidFriendlyRandomHolder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AndroidFriendlyRandomHolder.java similarity index 86% rename from sdk/common/src/main/java/io/opentelemetry/sdk/internal/AndroidFriendlyRandomHolder.java rename to sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AndroidFriendlyRandomHolder.java index 6a8f76d7e5e..623d61a5932 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/AndroidFriendlyRandomHolder.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AndroidFriendlyRandomHolder.java @@ -3,14 +3,14 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; import java.util.Random; import java.util.function.Supplier; /** * {@link RandomSupplier} instance that doesn't use {@link java.util.concurrent.ThreadLocalRandom}, - * which is broken on most versions of Android (it uses the same seed everytime it starts up). + * which is broken on most versions of Android (it uses the same seed every time it starts up). */ enum AndroidFriendlyRandomHolder implements Supplier { INSTANCE; diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AttributeUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AttributeUtil.java new file mode 100644 index 00000000000..c0c21d37eec --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AttributeUtil.java @@ -0,0 +1,189 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.common.ValueType; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Predicate; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class AttributeUtil { + + private AttributeUtil() {} + + /** + * Apply the {@code countLimit} and {@code lengthLimit} to the attributes. + * + *

      If all attributes fall within the limits, return as is. Else, return an attributes instance + * with the limits applied. {@code countLimit} limits the number of unique attribute keys. {@code + * lengthLimit} limits the length of attribute string and string list values. + */ + // Attributes guarantees matching key/value types, and length limiting preserves value types. + @SuppressWarnings({"unchecked", "rawtypes"}) + public static Attributes applyAttributesLimit( + Attributes attributes, int countLimit, int lengthLimit) { + if (attributes.isEmpty() || attributes.size() <= countLimit) { + if (lengthLimit == Integer.MAX_VALUE) { + return attributes; + } + boolean allValidLength = + allMatch(attributes.asMap().values(), value -> isValidLength(value, lengthLimit)); + if (allValidLength) { + return attributes; + } + } + + AttributesBuilder result = Attributes.builder(); + int i = 0; + for (Map.Entry, Object> entry : attributes.asMap().entrySet()) { + if (i >= countLimit) { + break; + } + result.put( + (AttributeKey) entry.getKey(), applyAttributeLengthLimit(entry.getValue(), lengthLimit)); + i++; + } + return result.build(); + } + + private static boolean isValidLength(Object value, int lengthLimit) { + if (value instanceof List) { + return allMatch((List) value, entry -> isValidLength(entry, lengthLimit)); + } else if (value instanceof String) { + return ((String) value).length() < lengthLimit; + } else if (value instanceof Value) { + return isValidLengthValue((Value) value, lengthLimit); + } + return true; + } + + private static boolean isValidLengthValue(Value value, int lengthLimit) { + ValueType type = value.getType(); + if (type == ValueType.STRING) { + return ((String) value.getValue()).length() < lengthLimit; + } else if (type == ValueType.BYTES) { + ByteBuffer buffer = (ByteBuffer) value.getValue(); + return buffer.remaining() <= lengthLimit; + } else if (type == ValueType.ARRAY) { + // ValueType.ARRAY guarantees a List>. + @SuppressWarnings("unchecked") + List> array = (List>) value.getValue(); + return allMatch(array, element -> isValidLengthValue(element, lengthLimit)); + } else if (type == ValueType.KEY_VALUE_LIST) { + // ValueType.KEY_VALUE_LIST guarantees a List. + @SuppressWarnings("unchecked") + List kvList = (List) value.getValue(); + return allMatch(kvList, kv -> isValidLengthValue(kv.getValue(), lengthLimit)); + } + return true; + } + + private static boolean allMatch(Iterable iterable, Predicate predicate) { + for (T value : iterable) { + if (!predicate.test(value)) { + return false; + } + } + return true; + } + + /** + * Apply the {@code lengthLimit} to the attribute {@code value}. Strings, byte arrays, and nested + * values which exceed the length limit are truncated. + * + *

      Applies to: + * + *

        + *
      • String values + *
      • Each string within an array of strings + *
      • String values within {@link Value} objects + *
      • Byte array values within {@link Value} objects + *
      • Recursively, each element in an array of {@link Value}s + *
      • Recursively, each value in a {@link Value} key-value list + *
      + */ + public static Object applyAttributeLengthLimit(Object value, int lengthLimit) { + if (lengthLimit == Integer.MAX_VALUE) { + return value; + } + if (value instanceof List) { + List values = (List) value; + List response = new ArrayList<>(values.size()); + for (Object entry : values) { + response.add(applyAttributeLengthLimit(entry, lengthLimit)); + } + return response; + } + if (value instanceof String) { + String str = (String) value; + return str.length() < lengthLimit ? value : str.substring(0, lengthLimit); + } + if (value instanceof Value) { + return applyValueLengthLimit((Value) value, lengthLimit); + } + return value; + } + + // The ValueType checks below ensure the list casts match Value.getValue()'s contract. + @SuppressWarnings("unchecked") + private static Value applyValueLengthLimit(Value value, int lengthLimit) { + ValueType type = value.getType(); + + if (type == ValueType.STRING) { + String str = (String) value.getValue(); + if (str.length() <= lengthLimit) { + return value; + } + return Value.of(str.substring(0, lengthLimit)); + } else if (type == ValueType.BYTES) { + ByteBuffer buffer = (ByteBuffer) value.getValue(); + int length = buffer.remaining(); + if (length <= lengthLimit) { + return value; + } + byte[] truncated = new byte[lengthLimit]; + buffer.get(truncated); + return Value.of(truncated); + } else if (type == ValueType.ARRAY) { + List> array = (List>) value.getValue(); + boolean allValidLength = allMatch(array, element -> isValidLengthValue(element, lengthLimit)); + if (allValidLength) { + return value; + } + List> result = new ArrayList<>(array.size()); + for (Value element : array) { + result.add(applyValueLengthLimit(element, lengthLimit)); + } + return Value.of(result); + } else if (type == ValueType.KEY_VALUE_LIST) { + List kvList = (List) value.getValue(); + boolean allValidLength = + allMatch(kvList, kv -> isValidLengthValue(kv.getValue(), lengthLimit)); + if (allValidLength) { + return value; + } + List result = new ArrayList<>(kvList.size()); + for (KeyValue kv : kvList) { + result.add(KeyValue.of(kv.getKey(), applyValueLengthLimit(kv.getValue(), lengthLimit))); + } + return Value.of(result.toArray(new KeyValue[0])); + } + + // For BOOLEAN, LONG, DOUBLE - no truncation needed + return value; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AttributesMap.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AttributesMap.java new file mode 100644 index 00000000000..10d84b6e19b --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/AttributesMap.java @@ -0,0 +1,304 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import java.util.Arrays; +import java.util.Collections; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; + +/** + * A map with a fixed capacity that drops attributes when the map gets full, and which truncates + * string and array string attribute values to the {@link #lengthLimit}. + * + *

      Keyed internally by attribute name, so that attributes with the same name but different types + * are treated as the same key (last-value-wins), consistent with the OpenTelemetry specification. + * + *

      Backed by parallel arrays and an open-addressing {@code int[]} hash table (linear probing, + * load factor ≀ 0.5). Avoids per-entry object allocation; {@code forEach} is a tight sequential + * array loop with no pointer chasing. + * + *

      Not thread-safe. Callers sharing an instance across threads must externally + * synchronize. Concurrent mutation is undefined behavior and may throw {@link + * ArrayIndexOutOfBoundsException} as readers observe the parallel arrays and hash table in + * inconsistent states. {@link #forEach}'s {@link ConcurrentModificationException} on structural + * modification is a same-thread misuse detector, not a synchronization primitive. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AttributesMap implements Attributes { + + /** + * Sentinel meaning "slot is empty" in the hash table. This is a value stored in {@code + * hashTable[slot]}, not a slot address; a name whose {@link String#hashCode()} is 0 simply hashes + * to slot 0 like any other slot address, and occupancy is decided by comparing the stored value. + * + *

      Using 0 lets {@code new int[n]} (JVM zero-initialization) serve as the initial fill, + * eliminating explicit {@code Arrays.fill} calls. Occupied slots store {@code entryIndex + 1} so + * that entry index 0 is distinguishable from EMPTY. + */ + private static final int EMPTY = 0; + + private final int capacity; + private final int lengthLimit; + private int totalAddedValues = 0; + private int size = 0; + + /** + * Open-addressing hash table: {@code hashTable[slot]} = index into entry arrays, or {@link + * #EMPTY}. Length is always a power of 2 and β‰₯ 2Γ— the entry array length (load factor ≀ 0.5). + */ + private int[] hashTable; + + /** Cached {@code hashTable.length - 1}; kept in sync with {@link #hashTable}. */ + private int mask; + + /** + * Parallel entry arrays. For entry {@code i} (in insertion order): + * + *

        + *
      • {@link #entryNames}{@code [i]} is the attribute name (cached from {@code + * entryKeys[i].getKey()} to avoid an extra dereference on every probe step). + *
      • {@link #entryKeys}{@code [i]} is the last-put {@link AttributeKey} for that name, + * preserving the caller's type at query time via {@link #get}. + *
      • {@link #entryValues}{@code [i]} is the last-put value, post-length-limit application. + *
      + * + *

      All three are reallocated together in {@link #grow}; entry positions never change. + */ + private String[] entryNames; + + private AttributeKey[] entryKeys; + private Object[] entryValues; + + /** + * Incremented on every mutation that changes observable state (insert or overwrite). Snapshotted + * by {@link #forEach} to detect same-thread structural modification during iteration. + */ + private int modCount = 0; + + private AttributesMap(long capacity, int lengthLimit) { + this.capacity = (int) Math.min(capacity, Integer.MAX_VALUE); + this.lengthLimit = lengthLimit; + int init = (int) Math.min(capacity, 16L); + entryNames = new String[init]; + entryKeys = new AttributeKey[init]; + entryValues = new Object[init]; + hashTable = new int[tableSizeFor(init)]; // JVM zero-init == EMPTY + mask = hashTable.length - 1; + } + + /** + * Create an instance. + * + * @param capacity the max number of attribute entries + * @param lengthLimit the maximum length of string attributes + */ + public static AttributesMap create(long capacity, int lengthLimit) { + return new AttributesMap(capacity, lengthLimit); + } + + /** + * Add the attribute key value pair, applying capacity and length limits. Callers MUST ensure the + * {@code value} type matches the type required by {@code key}. + * + *

      If an attribute with the same string key name already exists (regardless of type), it is + * overwritten β€” last-value-wins, consistent with the OTel spec. + */ + @Nullable + public Object put(AttributeKey key, @Nullable Object value) { + if (value == null) { + return null; + } + String name = key.getKey(); + int slot = findSlot(name); + int stored = hashTable[slot]; + if (stored == EMPTY) { + totalAddedValues++; + if (size >= capacity) { + // Drop new entry per spec. totalAddedValues++ above captures the drop for + // getTotalAddedValues() / downstream drop-count metrics. + return null; + } + } + Object limitedValue = AttributeUtil.applyAttributeLengthLimit(value, lengthLimit); + int idx; + Object old; + if (stored == EMPTY) { + if (size == entryNames.length) { + grow(); + slot = findSlot(name); // grow() rebuilt hashTable + } + idx = size; + entryNames[idx] = name; + hashTable[slot] = idx + 1; + size++; + old = null; + } else { + idx = stored - 1; + old = entryValues[idx]; + } + modCount++; + entryKeys[idx] = key; + entryValues[idx] = limitedValue; + return old; + } + + /** Generic overload of {@link #put(AttributeKey, Object)}. */ + public void putIfCapacity(AttributeKey key, @Nullable T value) { + put(key, value); + } + + /** Get the total number of attributes added, including those dropped for capacity limits. */ + public int getTotalAddedValues() { + return totalAddedValues; + } + + // put requires matching key/value types, and the stored key type is checked before casting. + @SuppressWarnings("unchecked") + @Override + @Nullable + public T get(AttributeKey key) { + int stored = hashTable[findSlot(key.getKey())]; + if (stored == EMPTY) { + return null; + } + int idx = stored - 1; + if (!entryKeys[idx].getType().equals(key.getType())) { + return null; + } + return (T) entryValues[idx]; + } + + /** + * Returns whether an attribute with the given key name exists in this map, regardless of type. + * + *

      Runs with expected/amortized O(1) complexity using the internal open-addressing table. + * + * @param key the attribute key name to look up. Must not be null. + */ + public boolean containsKey(String key) { + return hashTable[findSlot(key)] != EMPTY; + } + + @Override + public int size() { + return size; + } + + @Override + public boolean isEmpty() { + return size == 0; + } + + @Override + public Map, Object> asMap() { + Map, Object> snapshot = new HashMap<>(size); + for (int i = 0; i < size; i++) { + snapshot.put(entryKeys[i], entryValues[i]); + } + return Collections.unmodifiableMap(snapshot); + } + + @Override + public AttributesBuilder toBuilder() { + return Attributes.builder().putAll(this); + } + + @Override + public void forEach(BiConsumer, ? super Object> action) { + int expectedModCount = modCount; + for (int i = 0; i < size; i++) { + action.accept(entryKeys[i], entryValues[i]); + } + if (modCount != expectedModCount) { + throw new ConcurrentModificationException(); + } + } + + @Override + public boolean equals(@Nullable Object o) { + if (this == o) { + return true; + } + if (!(o instanceof AttributesMap)) { + return false; + } + return asMap().equals(((AttributesMap) o).asMap()); + } + + @Override + public int hashCode() { + return asMap().hashCode(); + } + + @Override + public String toString() { + return "AttributesMap{" + + "data=" + + asMap() + + ", capacity=" + + capacity + + ", totalAddedValues=" + + totalAddedValues + + '}'; + } + + /** Create an immutable copy of the attributes in this map. */ + public Attributes immutableCopy() { + return Attributes.builder().putAll(this).build(); + } + + /** + * Returns the hash table slot that either contains the entry for {@code name} or is the first + * empty slot available for insertion. Single shared probe loop used by {@code put}, {@code get}, + * and {@code grow}. Slots store {@code entryIndex + 1}; 0 ({@link #EMPTY}) means unoccupied. + */ + private int findSlot(String name) { + // Linear probe: stop on empty slot (name absent; insertion point) or matching-name slot (name + // found). `& mask` wraps at the end of the table. + int slot = name.hashCode() & mask; + int stored; + while ((stored = hashTable[slot]) != EMPTY && !entryNames[stored - 1].equals(name)) { + slot = (slot + 1) & mask; + } + return slot; + } + + private void grow() { + long maxLen = Math.min(capacity, (long) Integer.MAX_VALUE - 8); + int newLen = (int) Math.min((long) entryNames.length * 2, maxLen); + entryNames = Arrays.copyOf(entryNames, newLen); + entryKeys = Arrays.copyOf(entryKeys, newLen); + entryValues = Arrays.copyOf(entryValues, newLen); + hashTable = new int[tableSizeFor(newLen)]; // JVM zero-init == EMPTY + mask = hashTable.length - 1; + // Rehash: entry positions in the arrays don't change, but their slot addresses do (new mask). + for (int i = 0; i < size; i++) { + int slot = findSlot(entryNames[i]); + hashTable[slot] = i + 1; + } + } + + /** + * Returns the smallest power of 2 that is β‰₯ 2n, guaranteeing load factor ≀ 0.5. Using {@code + * (2n-1)} instead of {@code 2n} prevents doubling the result when {@code n} is itself a power of + * 2. + */ + private static int tableSizeFor(int n) { + if (n <= 2) { + return 4; + } + return Integer.highestOneBit(2 * n - 1) << 1; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ComponentId.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ComponentId.java new file mode 100644 index 00000000000..1c2475d9553 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ComponentId.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nullable; + +/** + * The component id used for SDK health metrics. This corresponds to the otel.component.name and + * otel.component.id semconv attributes. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public abstract class ComponentId { + + private ComponentId() {} + + public abstract String getTypeName(); + + public abstract String getComponentName(); + + static class Lazy extends ComponentId { + + private static final Map nextIdCounters = new ConcurrentHashMap<>(); + + private final String componentType; + @Nullable private volatile String componentName = null; + + Lazy(String componentType) { + this.componentType = componentType; + } + + @Override + public String getTypeName() { + return componentType; + } + + @Override + public String getComponentName() { + if (componentName == null) { + synchronized (this) { + if (componentName == null) { + int id = + nextIdCounters + .computeIfAbsent(componentType, k -> new AtomicInteger(0)) + .getAndIncrement(); + componentName = componentType + "/" + id; + } + } + } + return componentName; + } + } + + public static ComponentId generateLazy(String componentType) { + return new Lazy(componentType); + } + + public static StandardComponentId generateLazy(StandardComponentId.ExporterType exporterType) { + return new StandardComponentId(exporterType); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ComponentRegistry.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ComponentRegistry.java new file mode 100644 index 00000000000..6a86d39ddc6 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ComponentRegistry.java @@ -0,0 +1,133 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.internal.GuardedBy; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Function; +import javax.annotation.Nullable; + +/** + * Component (tracer, meter, etc) registry class for all the provider classes (TracerProvider, + * MeterProvider, etc.). + * + *

      Components are identified by name, version, and schema. Name is required, but version and + * schema are optional. Therefore, we have 4 possible scenarios for component keys: + * + *

        + *
      1. Only name is provided, represented by {@link #componentByName} + *
      2. Name and version are provided, represented by {@link #componentByNameAndVersion} + *
      3. Name and schema are provided, represented by {@link #componentByNameAndSchema} + *
      4. Name, version and schema are provided, represented by {@link + * #componentByNameVersionAndSchema} + *
      + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @param the type of the registered value. + */ +public final class ComponentRegistry { + + private final Map componentByName = new ConcurrentHashMap<>(); + private final Map> componentByNameAndVersion = new ConcurrentHashMap<>(); + private final Map> componentByNameAndSchema = new ConcurrentHashMap<>(); + private final Map>> componentByNameVersionAndSchema = + new ConcurrentHashMap<>(); + + private final Object lock = new Object(); + + @GuardedBy("lock") + private final Set allComponents = Collections.newSetFromMap(new IdentityHashMap<>()); + + private final Function factory; + + public ComponentRegistry(Function factory) { + this.factory = factory; + } + + /** + * Returns the component associated with the {@code name}, {@code version}, and {@code schemaUrl}. + * {@link Attributes} are not part of component identity. Behavior is undefined when different + * {@link Attributes} are provided where {@code name}, {@code version}, and {@code schemaUrl} are + * identical. + */ + public V get( + String name, @Nullable String version, @Nullable String schemaUrl, Attributes attributes) { + if (version != null && schemaUrl != null) { + Map> componentByVersionAndSchema = + componentByNameVersionAndSchema.computeIfAbsent( + name, unused -> new ConcurrentHashMap<>()); + Map componentBySchema = + componentByVersionAndSchema.computeIfAbsent(version, unused -> new ConcurrentHashMap<>()); + return componentBySchema.computeIfAbsent( + schemaUrl, + schemaUrl1 -> + buildComponent( + InstrumentationScopeInfo.builder(name) + .setVersion(version) + .setSchemaUrl(schemaUrl1) + .setAttributes(attributes) + .build())); + } else if (version != null) { // schemaUrl == null + Map componentByVersion = + componentByNameAndVersion.computeIfAbsent(name, unused -> new ConcurrentHashMap<>()); + return componentByVersion.computeIfAbsent( + version, + version1 -> + buildComponent( + InstrumentationScopeInfo.builder(name) + .setVersion(version1) + .setAttributes(attributes) + .build())); + } + if (schemaUrl != null) { // version == null + Map componentBySchema = + componentByNameAndSchema.computeIfAbsent(name, unused -> new ConcurrentHashMap<>()); + return componentBySchema.computeIfAbsent( + schemaUrl, + schemaUrl1 -> + buildComponent( + InstrumentationScopeInfo.builder(name) + .setSchemaUrl(schemaUrl1) + .setAttributes(attributes) + .build())); + } else { // schemaUrl == null && version == null + return componentByName.computeIfAbsent( + name, + name1 -> + buildComponent( + InstrumentationScopeInfo.builder(name1).setAttributes(attributes).build())); + } + } + + private V buildComponent(InstrumentationScopeInfo instrumentationScopeInfo) { + V component = factory.apply(instrumentationScopeInfo); + synchronized (lock) { + allComponents.add(component); + } + return component; + } + + /** + * Returns a {@code Collection} view of the registered components. + * + * @return a {@code Collection} view of the registered components. + */ + public Collection getComponents() { + synchronized (lock) { + return Collections.unmodifiableCollection(new ArrayList<>(allComponents)); + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DaemonThreadFactory.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DaemonThreadFactory.java new file mode 100644 index 00000000000..a9077d1bacc --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DaemonThreadFactory.java @@ -0,0 +1,72 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nullable; + +/** + * A {@link ThreadFactory} that delegates to {@code Executors.defaultThreadFactory()} and marks all + * threads as daemon. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class DaemonThreadFactory implements ThreadFactory { + private final String namePrefix; + private final AtomicInteger counter = new AtomicInteger(); + private final ThreadFactory delegate; + + public DaemonThreadFactory(String namePrefix) { + this(namePrefix, Executors.defaultThreadFactory()); + } + + /** + * {@link DaemonThreadFactory}'s constructor. + * + * @param namePrefix Used when setting the new thread's name. + * @param delegate Delegate to create threads. + */ + public DaemonThreadFactory(String namePrefix, ThreadFactory delegate) { + this.namePrefix = namePrefix; + this.delegate = delegate; + } + + @Override + public Thread newThread(Runnable runnable) { + Thread t = delegate.newThread(runnable); + t.setUncaughtExceptionHandler( + new ManagedUncaughtExceptionHandler(t.getUncaughtExceptionHandler())); + try { + t.setDaemon(true); + t.setName(namePrefix + "-" + counter.incrementAndGet()); + t.setContextClassLoader(null); + } catch (SecurityException e) { + // Well, we tried. + } + return t; + } + + static class ManagedUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { + @Nullable private final Thread.UncaughtExceptionHandler delegate; + + private ManagedUncaughtExceptionHandler(@Nullable Thread.UncaughtExceptionHandler delegate) { + this.delegate = delegate; + } + + @SuppressWarnings("Interruption") + @Override + public void uncaughtException(Thread t, Throwable e) { + if (e instanceof InterruptedException) { + t.interrupt(); + } else if (delegate != null) { + delegate.uncaughtException(t, e); + } + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DefaultExceptionAttributeResolver.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DefaultExceptionAttributeResolver.java new file mode 100644 index 00000000000..0e1963e2c64 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DefaultExceptionAttributeResolver.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.io.PrintWriter; +import java.io.StringWriter; + +/** + * The default {@link ExceptionAttributeResolver}, populating standard {@code exception.*} as + * defined by the semantic conventions. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + * + * @see ExceptionAttributeResolver#getDefault() + * @see ExceptionAttributeResolver#getDefault(boolean) + */ +final class DefaultExceptionAttributeResolver implements ExceptionAttributeResolver { + + static final String ENABLE_JVM_STACKTRACE_PROPERTY = "otel.experimental.sdk.jvm_stacktrace"; + + private final boolean jvmStacktraceEnabled; + + DefaultExceptionAttributeResolver(boolean jvmStacktraceEnabled) { + this.jvmStacktraceEnabled = jvmStacktraceEnabled; + } + + @Override + public void setExceptionAttributes( + AttributeSetter attributeSetter, Throwable throwable, int maxAttributeLength) { + String exceptionType = throwable.getClass().getCanonicalName(); + if (exceptionType != null) { + attributeSetter.setAttribute(ExceptionAttributeResolver.EXCEPTION_TYPE, exceptionType); + } + + String exceptionMessage = throwable.getMessage(); + if (exceptionMessage != null) { + attributeSetter.setAttribute(ExceptionAttributeResolver.EXCEPTION_MESSAGE, exceptionMessage); + } + + String exceptionStacktrace = + jvmStacktraceEnabled + ? jvmStacktrace(throwable) + : limitsAwareStacktrace(throwable, maxAttributeLength); + attributeSetter.setAttribute( + ExceptionAttributeResolver.EXCEPTION_STACKTRACE, exceptionStacktrace); + } + + private static String jvmStacktrace(Throwable throwable) { + StringWriter stringWriter = new StringWriter(); + try (PrintWriter printWriter = new PrintWriter(stringWriter)) { + throwable.printStackTrace(printWriter); + } + return stringWriter.toString(); + } + + private static String limitsAwareStacktrace(Throwable throwable, int maxAttributeLength) { + return new StackTraceRenderer(throwable, maxAttributeLength).render(); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DynamicPrimitiveLongList.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DynamicPrimitiveLongList.java new file mode 100644 index 00000000000..66f86c822a8 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/DynamicPrimitiveLongList.java @@ -0,0 +1,151 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.util.AbstractList; +import java.util.Arrays; + +/** + * A resizable list for storing primitive `long` values. + * + *

      This class implements a dynamically resizable list specifically for primitive long values. The + * values are stored in a chain of arrays (named sub-array), so it can grow efficiently, by adding + * more sub-arrays per its defined size. The backing array also helps avoid auto-boxing and helps + * provide access to values as primitives without boxing. + * + *

      The list is designed to minimize memory allocations, by: + * + *

        + *
      1. Adding sub-arrays and not creating new arrays and copying. + *
      2. When the size is changing to a smaller size, arrays are not removed. + *
      + * + *

      Supported {@code List} methods: + * + *

        + *
      • {@link #get(int)} - Retrieves the element at the specified position in this list as a + * {@code Long} object. + *
      • {@link #set(int, Long)} - Replaces the element at the specified position in this list with + * the specified {@code Long} object. + *
      • {@link #size()} - Returns the number of elements in this list. + *
      + * + *

      Additional utility methods: + * + *

        + *
      • {@link #getLong(int)} - Retrieves the element at the specified position in this list as a + * primitive long. + *
      • {@link #setLong(int, long)} - Replaces the element at the specified position in this list + * with the specified primitive long element. + *
      • {@link #resizeAndClear(int)} - Resizes the list to the specified size, resetting all + * elements to zero. + *
      + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public class DynamicPrimitiveLongList extends AbstractList { + + private static final int DEFAULT_SUBARRAY_CAPACITY = 10; + private final int subarrayCapacity; + private long[][] arrays; + private int size; + private int arrayCount; + + public static DynamicPrimitiveLongList of(long... values) { + DynamicPrimitiveLongList list = new DynamicPrimitiveLongList(); + list.resizeAndClear(values.length); + for (int i = 0; i < values.length; i++) { + list.setLong(i, values[i]); + } + return list; + } + + public static DynamicPrimitiveLongList ofSubArrayCapacity(int subarrayCapacity) { + return new DynamicPrimitiveLongList(subarrayCapacity); + } + + public static DynamicPrimitiveLongList empty() { + return new DynamicPrimitiveLongList(); + } + + DynamicPrimitiveLongList() { + this(DEFAULT_SUBARRAY_CAPACITY); + } + + DynamicPrimitiveLongList(int subarrayCapacity) { + if (subarrayCapacity <= 0) { + throw new IllegalArgumentException("Subarray capacity must be positive"); + } + this.subarrayCapacity = subarrayCapacity; + arrays = new long[0][subarrayCapacity]; + arrayCount = 0; + size = 0; + } + + @Override + public Long get(int index) { + return getLong(index); + } + + public long getLong(int index) { + rangeCheck(index); + return arrays[index / subarrayCapacity][index % subarrayCapacity]; + } + + @Override + public Long set(int index, Long element) { + return setLong(index, element); + } + + public long setLong(int index, long element) { + rangeCheck(index); + long oldValue = arrays[index / subarrayCapacity][index % subarrayCapacity]; + arrays[index / subarrayCapacity][index % subarrayCapacity] = element; + return oldValue; + } + + @Override + public int size() { + return size; + } + + public void resizeAndClear(int newSize) { + if (newSize < 0) { + throw new IllegalArgumentException("New size must be non-negative"); + } + ensureCapacity(newSize); + size = newSize; + for (int i = 0; i < newSize; i++) { + setLong(i, 0); + } + } + + private void ensureCapacity(int minCapacity) { + // A faster way to do ceil(minCapacity/subArrayCapacity) + int requiredArrays = (minCapacity + subarrayCapacity - 1) / subarrayCapacity; + + if (requiredArrays > arrayCount) { + arrays = Arrays.copyOf(arrays, /* newLength= */ requiredArrays); + for (int i = arrayCount; i < requiredArrays; i++) { + arrays[i] = new long[subarrayCapacity]; + } + arrayCount = requiredArrays; + } + } + + private void rangeCheck(int index) { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); + } + } + + private String outOfBoundsMsg(int index) { + return "Index: " + index + ", Size: " + size; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ExceptionAttributeResolver.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ExceptionAttributeResolver.java new file mode 100644 index 00000000000..d36b0ef2e88 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ExceptionAttributeResolver.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static io.opentelemetry.sdk.common.internal.DefaultExceptionAttributeResolver.ENABLE_JVM_STACKTRACE_PROPERTY; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.common.impl.ConfigUtil; +import javax.annotation.Nullable; + +/** + * Implementations resolve {@code exception.*} attributes attached to span events, logs, etc. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public interface ExceptionAttributeResolver { + + AttributeKey EXCEPTION_TYPE = AttributeKey.stringKey("exception.type"); + AttributeKey EXCEPTION_MESSAGE = AttributeKey.stringKey("exception.message"); + AttributeKey EXCEPTION_STACKTRACE = AttributeKey.stringKey("exception.stacktrace"); + + void setExceptionAttributes( + AttributeSetter attributeSetter, Throwable throwable, int maxAttributeLength); + + /** + * Return the default exception attribute resolver, setting {@code jvmStacktraceEnabled} based on + * {@link DefaultExceptionAttributeResolver#ENABLE_JVM_STACKTRACE_PROPERTY}. + */ + static ExceptionAttributeResolver getDefault() { + return getDefault( + Boolean.parseBoolean(ConfigUtil.getString(ENABLE_JVM_STACKTRACE_PROPERTY, "false"))); + } + + /** + * Return the default exception attribute resolver. + * + * @param jvmStacktraceEnabled if true, resolve stacktrace using the stacktrace renderer built + * into the JVM. This built in JVM renderer is not attribute limits aware, and may utilize + * more CPU / memory than is needed. Most users will prefer to set this to {@code false}. + */ + static ExceptionAttributeResolver getDefault(boolean jvmStacktraceEnabled) { + return new DefaultExceptionAttributeResolver(jvmStacktraceEnabled); + } + + /** + * This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ + // TODO(jack-berg): Consider promoting to opentelemetry and extending with Span, LogRecordBuilder, + // AttributeBuilder, AttributesMap etc. + interface AttributeSetter { + void setAttribute(AttributeKey key, @Nullable T value); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/GlobUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/GlobUtil.java new file mode 100644 index 00000000000..5416f7598a2 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/GlobUtil.java @@ -0,0 +1,126 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** + * Utilities for glob pattern matching. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class GlobUtil { + + private GlobUtil() {} + + /** + * Return a predicate that returns {@code true} if a string matches the {@code globPattern}. + * + *

      {@code globPattern} may contain the wildcard characters {@code *} and {@code ?} with the + * following matching criteria: + * + *

        + *
      • {@code *} matches 0 or more instances of any character + *
      • {@code ?} matches exactly one instance of any character + *
      + */ + public static Predicate createGlobPatternPredicate(String globPattern) { + for (int i = 0; i < globPattern.length(); i++) { + char c = globPattern.charAt(i); + if (c == '*' || c == '?') { + return new GlobPatternPredicate(globPattern, globPattern.codePoints().toArray()); + } + } + return new GlobPatternPredicate(globPattern, null); + } + + /** + * A predicate which evaluates if a test string matches the {@link #globPattern}, and which has a + * valid {@link #toString()} implementation. + */ + private static class GlobPatternPredicate implements Predicate { + private final String globPattern; + @Nullable private final int[] pattern; + + private GlobPatternPredicate(String globPattern, @Nullable int[] pattern) { + this.globPattern = globPattern; + this.pattern = pattern; + } + + @Override + public boolean test(String s) { + // Match all + if (globPattern.equals("*")) { + return true; + } + if (pattern != null) { + return matches(pattern, s); + } + // Exact match + return globPattern.equals(s); + } + + @Override + public String toString() { + return "GlobPatternPredicate{globPattern=" + globPattern + "}"; + } + + /** + * Retries only the most recent star, bounding matching time to O(pattern length * input length) + * with constant per-match space. + */ + private static boolean matches(int[] pattern, String s) { + int patternIndex = 0; + int inputIndex = 0; + int starIndex = -1; + int starInputIndex = -1; + while (inputIndex < s.length()) { + if (patternIndex < pattern.length && pattern[patternIndex] == '*') { + // Try an empty match first, remembering this star as the next retry point. + starIndex = patternIndex++; + starInputIndex = inputIndex; + continue; + } + // Match whole code points so '?' consumes a supplementary character as one unit. + int codePoint = s.codePointAt(inputIndex); + if (patternIndex < pattern.length + && (pattern[patternIndex] == codePoint + || (pattern[patternIndex] == '?' && matchesWildcard(codePoint)))) { + patternIndex++; + inputIndex += Character.charCount(codePoint); + continue; + } + if (starIndex == -1) { + return false; + } + // On mismatch, extend the most recent star by one code point and retry its suffix. + int starCodePoint = s.codePointAt(starInputIndex); + if (!matchesWildcard(starCodePoint)) { + return false; + } + starInputIndex += Character.charCount(starCodePoint); + inputIndex = starInputIndex; + patternIndex = starIndex + 1; + } + // With the input exhausted, only stars can match the remaining pattern (as empty matches). + while (patternIndex < pattern.length && pattern[patternIndex] == '*') { + patternIndex++; + } + return patternIndex == pattern.length; + } + + private static boolean matchesWildcard(int codePoint) { + // Preserve the line terminator exclusions of regex '.' without DOTALL. + return codePoint != '\n' + && codePoint != '\r' + && codePoint != 0x85 + && codePoint != 0x2028 + && codePoint != 0x2029; + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicate.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicate.java new file mode 100644 index 00000000000..db315cdbc51 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicate.java @@ -0,0 +1,131 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static io.opentelemetry.sdk.common.internal.GlobUtil.createGlobPatternPredicate; +import static java.util.stream.Collectors.joining; + +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.StringJoiner; +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** + * A predicate that evaluates if a string matches a configurable set of {@code included} and {@code + * excluded} string. + * + *

      Supports optional glob pattern matching. See {@link GlobUtil}. + * + *

      String equality is evaluated using {@link String#equals(Object)}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class IncludeExcludePredicate implements Predicate { + + private final boolean globMatchingEnabled; + @Nullable private final Set included; + @Nullable private final Set excluded; + private final Predicate predicate; + + private IncludeExcludePredicate( + @Nullable Collection included, + @Nullable Collection excluded, + boolean globMatchingEnabled) { + this.globMatchingEnabled = globMatchingEnabled; + this.included = copyIfNotEmpty(included); + this.excluded = copyIfNotEmpty(excluded); + if (this.included != null && this.excluded != null) { + this.predicate = + includedPredicate(this.included, globMatchingEnabled) + .and(excludedPredicate(this.excluded, globMatchingEnabled)); + } else if (this.excluded != null) { + this.predicate = excludedPredicate(this.excluded, globMatchingEnabled); + } else if (this.included != null) { + this.predicate = includedPredicate(this.included, globMatchingEnabled); + } else { + // include everything by default if both included and excluded are null or empt + this.predicate = s -> true; + } + } + + /** + * Create a (case-sensitive) exact matching include exclude predicate. + * + *

      When {@code included} is empty or {@literal null}, all values are included. + * + *

      When {@code excluded} is empty or {@literal null}, no value are excluded. + */ + public static Predicate createExactMatching( + @Nullable Collection included, @Nullable Collection excluded) { + return new IncludeExcludePredicate(included, excluded, /* globMatchingEnabled= */ false); + } + + /** + * Create a pattern matching include exclude predicate. + * + *

      When {@code included} is empty or {@literal null}, all values are included by default. + * + *

      When {@code excluded} is empty or {@literal null}, no value is excluded by default. + * + *

      See {@link GlobUtil} for pattern matching details. + */ + public static Predicate createPatternMatching( + @Nullable Collection included, @Nullable Collection excluded) { + return new IncludeExcludePredicate(included, excluded, /* globMatchingEnabled= */ true); + } + + @Override + public boolean test(String s) { + return predicate.test(s); + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "IncludeExcludePredicate{", "}"); + joiner.add("globMatchingEnabled=" + globMatchingEnabled); + if (included != null) { + joiner.add("included=" + included.stream().collect(joining(", ", "[", "]"))); + } + if (excluded != null) { + joiner.add("excluded=" + excluded.stream().collect(joining(", ", "[", "]"))); + } + return joiner.toString(); + } + + private static Predicate includedPredicate( + Set included, boolean globMatchingEnabled) { + Predicate result = attributeKey -> false; + for (String include : included) { + if (globMatchingEnabled) { + result = result.or(createGlobPatternPredicate(include)); + } else { + result = result.or(include::equals); + } + } + return result; + } + + private static Predicate excludedPredicate( + Set excluded, boolean globMatchingEnabled) { + Predicate result = attributeKey -> true; + for (String exclude : excluded) { + if (globMatchingEnabled) { + result = result.and(createGlobPatternPredicate(exclude).negate()); + } else { + result = result.and(s -> !exclude.equals(s)); + } + } + return result; + } + + @Nullable + private static Set copyIfNotEmpty(@Nullable Collection collection) { + return collection == null || collection.isEmpty() ? null : new LinkedHashSet<>(collection); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/InstrumentationScopeUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/InstrumentationScopeUtil.java new file mode 100644 index 00000000000..7ee344c38aa --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/InstrumentationScopeUtil.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.InstrumentationScopeInfoBuilder; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public final class InstrumentationScopeUtil { + + /** Convert to {@link InstrumentationLibraryInfo}. */ + @SuppressWarnings("deprecation") // Utility method for compatibility + public static InstrumentationLibraryInfo toInstrumentationLibraryInfo( + InstrumentationScopeInfo instrumentationScopeInfo) { + return InstrumentationLibraryInfo.create( + instrumentationScopeInfo.getName(), + instrumentationScopeInfo.getVersion(), + instrumentationScopeInfo.getSchemaUrl()); + } + + /** Convert to {@link InstrumentationScopeInfo}. */ + @SuppressWarnings("deprecation") // Utility method for compatibility + public static InstrumentationScopeInfo toInstrumentationScopeInfo( + InstrumentationLibraryInfo instrumentationLibraryInfo) { + InstrumentationScopeInfoBuilder builder = + InstrumentationScopeInfo.builder(instrumentationLibraryInfo.getName()); + if (instrumentationLibraryInfo.getVersion() != null) { + builder.setVersion(instrumentationLibraryInfo.getVersion()); + } + if (instrumentationLibraryInfo.getSchemaUrl() != null) { + builder.setSchemaUrl(instrumentationLibraryInfo.getSchemaUrl()); + } + return builder.build(); + } + + private InstrumentationScopeUtil() {} +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/PrimitiveLongList.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/PrimitiveLongList.java similarity index 98% rename from sdk/common/src/main/java/io/opentelemetry/sdk/internal/PrimitiveLongList.java rename to sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/PrimitiveLongList.java index 184a8a9aa8f..a8f14f150b0 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/PrimitiveLongList.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/PrimitiveLongList.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; import java.util.AbstractList; import java.util.Arrays; diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/RandomSupplier.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/RandomSupplier.java similarity index 89% rename from sdk/common/src/main/java/io/opentelemetry/sdk/internal/RandomSupplier.java rename to sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/RandomSupplier.java index 5cef91edc72..62c066d8e7c 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/RandomSupplier.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/RandomSupplier.java @@ -3,14 +3,14 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Supplier; /** - * Provides random number generater constructor utilities. + * Provides random number generator constructor utilities. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/RateLimiter.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/RateLimiter.java similarity index 98% rename from sdk/common/src/main/java/io/opentelemetry/sdk/internal/RateLimiter.java rename to sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/RateLimiter.java index 94ce8accd0e..8dd2c86a968 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/RateLimiter.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/RateLimiter.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; import io.opentelemetry.sdk.common.Clock; import java.util.concurrent.atomic.AtomicLong; diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ScopeConfigurator.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ScopeConfigurator.java new file mode 100644 index 00000000000..28c2db4dcce --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ScopeConfigurator.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import java.util.function.Function; + +/** + * A {@link ScopeConfigurator} computes configuration for a given {@link InstrumentationScopeInfo}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@FunctionalInterface +public interface ScopeConfigurator extends Function { + + /** Create a new builder. */ + static ScopeConfiguratorBuilder builder() { + return new ScopeConfiguratorBuilder<>(null); + } + + /** + * Convert this {@link ScopeConfigurator} to a builder. Additional added matchers only apply when + * {@link #apply(Object)} returns {@code null}. If this configurator contains {@link + * ScopeConfiguratorBuilder#setDefault(Object)}, additional matchers are never applied. + */ + default ScopeConfiguratorBuilder toBuilder() { + return new ScopeConfiguratorBuilder<>(this); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ScopeConfiguratorBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ScopeConfiguratorBuilder.java new file mode 100644 index 00000000000..54325eaabfc --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ScopeConfiguratorBuilder.java @@ -0,0 +1,179 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.StringJoiner; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import javax.annotation.Nullable; + +/** + * Builder for {@link ScopeConfigurator}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @param The scope configuration object, e.g. {@code TracerConfig}, {@code LoggerConfig}, + * {@code MeterConfig}. + */ +public final class ScopeConfiguratorBuilder { + + @Nullable private final ScopeConfigurator baseScopeConfigurator; + @Nullable private T defaultScopeConfig; + private final List> conditions = new ArrayList<>(); + + ScopeConfiguratorBuilder(@Nullable ScopeConfigurator baseScopeConfigurator) { + this.baseScopeConfigurator = baseScopeConfigurator; + } + + /** + * Set the default scope config, which is returned by {@link ScopeConfigurator#apply(Object)} if a + * {@link InstrumentationScopeInfo} does not match any {@link #addCondition(Predicate, Object) + * conditions}. If a default is not set, an SDK defined default is used. + */ + public ScopeConfiguratorBuilder setDefault(T defaultScopeConfig) { + this.defaultScopeConfig = defaultScopeConfig; + return this; + } + + /** + * Add a condition. Conditions are evaluated in order. The {@code scopeConfig} for the first match + * is returned by {@link ScopeConfigurator#apply(Object)}. + * + * @param scopePredicate predicate that {@link InstrumentationScopeInfo}s are evaluated against + * @param scopeConfig the scope config to use when this condition is the first matching {@code + * scopePredicate} + * @see #nameMatchesGlob(String) + * @see #nameEquals(String) + */ + public ScopeConfiguratorBuilder addCondition( + Predicate scopePredicate, T scopeConfig) { + conditions.add(new Condition<>(scopePredicate, scopeConfig)); + return this; + } + + /** + * Helper function for pattern matching {@link InstrumentationScopeInfo#getName()} against the + * {@code globPattern}. + * + *

      {@code globPattern} may contain the wildcard characters {@code *} and {@code ?} with the + * following matching criteria: + * + *

        + *
      • {@code *} matches 0 or more instances of any character + *
      • {@code ?} matches exactly one instance of any character + *
      + * + * @see #addCondition(Predicate, Object) + */ + public static Predicate nameMatchesGlob(String globPattern) { + return new ScopeNameMatcher(GlobUtil.createGlobPatternPredicate(globPattern)); + } + + /** + * Helper function for exact matching {@link InstrumentationScopeInfo#getName()} against the + * {@code scopeName}. + * + * @see #addCondition(Predicate, Object) + */ + public static Predicate nameEquals(String scopeName) { + return new ScopeNameMatcher(name -> name.equals(scopeName)); + } + + /** Build a {@link ScopeConfigurator} with the configuration of this builder. */ + public ScopeConfigurator build() { + return new ScopeConfiguratorImpl<>(baseScopeConfigurator, defaultScopeConfig, conditions); + } + + private static final class Condition { + private final Predicate scopeMatcher; + private final T scopeConfig; + + private Condition(Predicate scopeMatcher, T scopeConfig) { + this.scopeMatcher = scopeMatcher; + this.scopeConfig = scopeConfig; + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "Condition{", "}"); + joiner.add("scopeMatcher=" + scopeMatcher); + joiner.add("scopeConfig=" + scopeConfig); + return joiner.toString(); + } + } + + private static class ScopeConfiguratorImpl implements ScopeConfigurator { + @Nullable private final ScopeConfigurator baseScopeConfigurator; + @Nullable private final T defaultScopeConfig; + private final List> conditions; + + private ScopeConfiguratorImpl( + @Nullable ScopeConfigurator baseScopeConfigurator, + @Nullable T defaultScopeConfig, + List> conditions) { + this.baseScopeConfigurator = baseScopeConfigurator; + this.defaultScopeConfig = defaultScopeConfig; + this.conditions = conditions; + } + + @Override + @Nullable + public T apply(InstrumentationScopeInfo scopeInfo) { + if (baseScopeConfigurator != null) { + T scopeConfig = baseScopeConfigurator.apply(scopeInfo); + if (scopeConfig != null) { + return scopeConfig; + } + } + for (Condition condition : conditions) { + if (condition.scopeMatcher.test(scopeInfo)) { + return condition.scopeConfig; + } + } + return defaultScopeConfig; + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(", ", "ScopeConfiguratorImpl{", "}"); + if (baseScopeConfigurator != null) { + joiner.add("baseScopeConfigurator=" + baseScopeConfigurator); + } + if (defaultScopeConfig != null) { + joiner.add("defaultScopeConfig=" + defaultScopeConfig); + } + joiner.add( + "conditions=" + + conditions.stream() + .map(Objects::toString) + .collect(Collectors.joining(",", "[", "]"))); + return joiner.toString(); + } + } + + private static class ScopeNameMatcher implements Predicate { + private final Predicate nameMatcher; + + private ScopeNameMatcher(Predicate nameMatcher) { + this.nameMatcher = nameMatcher; + } + + @Override + public boolean test(InstrumentationScopeInfo scopeInfo) { + return nameMatcher.test(scopeInfo.getName()); + } + + @Override + public String toString() { + return "ScopeNameMatcher{nameMatcher=" + nameMatcher + "}"; + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/SemConvConstants.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/SemConvConstants.java new file mode 100644 index 00000000000..0cc91e0633f --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/SemConvConstants.java @@ -0,0 +1,153 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import io.opentelemetry.api.common.AttributeKey; + +/** + * Provides access to semantic convention attributes, metric names, units, and descriptions used + * within the SDK implementation. This avoids having to pull in semantic conventions as a + * dependency, which would easily collide and conflict with user-provided dependencies. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class SemConvConstants { + + private SemConvConstants() {} + + // Schema url + + // TODO(jack-berg): decide when and why we change schema url + public static final String SCHEMA_URL_V1_40_0 = "https://opentelemetry.io/schemas/1.40.0"; + + // Entity types + + public static final String SERVICE_TYPE = "service"; + public static final String SERVICE_INSTANCE_TYPE = "service.instance"; + + // Attributes + + public static final AttributeKey SERVICE_NAME = AttributeKey.stringKey("service.name"); + public static final AttributeKey SERVICE_INSTANCE_ID = + AttributeKey.stringKey("service.instance.id"); + + public static final AttributeKey OTEL_COMPONENT_TYPE = + AttributeKey.stringKey("otel.component.type"); + public static final AttributeKey OTEL_COMPONENT_NAME = + AttributeKey.stringKey("otel.component.name"); + public static final AttributeKey ERROR_TYPE = AttributeKey.stringKey("error.type"); + + public static final AttributeKey SERVER_ADDRESS = + AttributeKey.stringKey("server.address"); + public static final AttributeKey SERVER_PORT = AttributeKey.longKey("server.port"); + + public static final AttributeKey RPC_STATUS_CODE = + AttributeKey.stringKey("rpc.status_code"); + public static final AttributeKey HTTP_RESPONSE_STATUS_CODE = + AttributeKey.longKey("http.response.status_code"); + + public static final AttributeKey OTEL_SPAN_PARENT_ORIGIN = + AttributeKey.stringKey("otel.span.parent.origin"); + public static final AttributeKey OTEL_SPAN_SAMPLING_RESULT = + AttributeKey.stringKey("otel.span.sampling_result"); + + public static final String OTEL_SDK_SPAN_STARTED_NAME = "otel.sdk.span.started"; + public static final String OTEL_SDK_SPAN_STARTED_UNIT = "{span}"; + public static final String OTEL_SDK_SPAN_STARTED_DESCRIPTION = "The number of created spans."; + + public static final String OTEL_SDK_SPAN_LIVE_NAME = "otel.sdk.span.live"; + public static final String OTEL_SDK_SPAN_LIVE_UNIT = "{span}"; + public static final String OTEL_SDK_SPAN_LIVE_DESCRIPTION = + "The number of created spans with `recording=true` for which the end operation has not been called yet."; + + public static final String OTEL_SDK_PROCESSOR_SPAN_PROCESSED_NAME = + "otel.sdk.processor.span.processed"; + public static final String OTEL_SDK_PROCESSOR_SPAN_PROCESSED_UNIT = "{span}"; + public static final String OTEL_SDK_PROCESSOR_SPAN_PROCESSED_DESCRIPTION = + "The number of spans for which the processing has finished, either successful or failed."; + + public static final String OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_NAME = + "otel.sdk.processor.span.queue.capacity"; + public static final String OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_UNIT = "{span}"; + public static final String OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_DESCRIPTION = + "The maximum number of spans the queue of a given instance of an SDK span processor can hold."; + + public static final String OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_NAME = + "otel.sdk.processor.span.queue.size"; + public static final String OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_UNIT = "{span}"; + public static final String OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_DESCRIPTION = + "The number of spans in the queue of a given instance of an SDK span processor."; + + public static final String OTEL_SDK_LOG_CREATED_NAME = "otel.sdk.log.created"; + public static final String OTEL_SDK_LOG_CREATED_UNIT = "{log_record}"; + public static final String OTEL_SDK_LOG_CREATED_DESCRIPTION = + "The number of log records submitted to an enabled `Logger`."; + + public static final String OTEL_SDK_PROCESSOR_LOG_PROCESSED_NAME = + "otel.sdk.processor.log.processed"; + public static final String OTEL_SDK_PROCESSOR_LOG_PROCESSED_UNIT = "{log_record}"; + public static final String OTEL_SDK_PROCESSOR_LOG_PROCESSED_DESCRIPTION = + "The number of log records for which the processing has finished, either successful or failed."; + + public static final String OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_NAME = + "otel.sdk.processor.log.queue.capacity"; + public static final String OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_UNIT = "{log_record}"; + public static final String OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_DESCRIPTION = + "The maximum number of log records the queue of a given instance of an SDK Log Record processor can hold."; + + public static final String OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_NAME = + "otel.sdk.processor.log.queue.size"; + public static final String OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_UNIT = "{log_record}"; + public static final String OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_DESCRIPTION = + "The number of log records in the queue of a given instance of an SDK log processor."; + + public static final String OTEL_SDK_METRIC_READER_COLLECTION_DURATION_NAME = + "otel.sdk.metric_reader.collection.duration"; + public static final String OTEL_SDK_METRIC_READER_COLLECTION_DURATION_UNIT = "s"; + public static final String OTEL_SDK_METRIC_READER_COLLECTION_DURATION_DESCRIPTION = + "The duration of the collect operation of the metric reader."; + + public static final String OTEL_SDK_EXPORTER_OPERATION_DURATION_NAME = + "otel.sdk.exporter.operation.duration"; + public static final String OTEL_SDK_EXPORTER_OPERATION_DURATION_UNIT = "s"; + public static final String OTEL_SDK_EXPORTER_OPERATION_DURATION_DESCRIPTION = + "The duration of exporting a batch of telemetry records."; + + public static final String OTEL_SDK_EXPORTER_SPAN_INFLIGHT_NAME = + "otel.sdk.exporter.span.inflight"; + public static final String OTEL_SDK_EXPORTER_SPAN_INFLIGHT_UNIT = "{span}"; + public static final String OTEL_SDK_EXPORTER_SPAN_INFLIGHT_DESCRIPTION = + "The number of spans which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)."; + + public static final String OTEL_SDK_EXPORTER_SPAN_EXPORTED_NAME = + "otel.sdk.exporter.span.exported"; + public static final String OTEL_SDK_EXPORTER_SPAN_EXPORTED_UNIT = "{span}"; + public static final String OTEL_SDK_EXPORTER_SPAN_EXPORTED_DESCRIPTION = + "The number of spans for which the export has finished, either successful or failed."; + + public static final String OTEL_SDK_EXPORTER_LOG_INFLIGHT_NAME = "otel.sdk.exporter.log.inflight"; + public static final String OTEL_SDK_EXPORTER_LOG_INFLIGHT_UNIT = "{log_record}"; + public static final String OTEL_SDK_EXPORTER_LOG_INFLIGHT_DESCRIPTION = + "The number of log records which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)."; + + public static final String OTEL_SDK_EXPORTER_LOG_EXPORTED_NAME = "otel.sdk.exporter.log.exported"; + public static final String OTEL_SDK_EXPORTER_LOG_EXPORTED_UNIT = "{log_record}"; + public static final String OTEL_SDK_EXPORTER_LOG_EXPORTED_DESCRIPTION = + "The number of log records for which the export has finished, either successful or failed."; + + public static final String OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_NAME = + "otel.sdk.exporter.metric_data_point.inflight"; + public static final String OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_UNIT = "{data_point}"; + public static final String OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_DESCRIPTION = + "The number of metric data points which were passed to the exporter, but that have not been exported yet (neither successful, nor failed)."; + + public static final String OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_NAME = + "otel.sdk.exporter.metric_data_point.exported"; + public static final String OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_UNIT = "{data_point}"; + public static final String OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_DESCRIPTION = + "The number of metric data points for which the export has finished, either successful or failed."; +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/Signal.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/Signal.java new file mode 100644 index 00000000000..3884890380a --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/Signal.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.util.Locale; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +public enum Signal { + SPAN( + SemConvConstants.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_NAME, + SemConvConstants.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_UNIT, + SemConvConstants.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_DESCRIPTION, + SemConvConstants.OTEL_SDK_EXPORTER_SPAN_EXPORTED_NAME, + SemConvConstants.OTEL_SDK_EXPORTER_SPAN_EXPORTED_UNIT, + SemConvConstants.OTEL_SDK_EXPORTER_SPAN_EXPORTED_DESCRIPTION), + METRIC( + SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_NAME, + SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_UNIT, + SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_DESCRIPTION, + SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_NAME, + SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_UNIT, + SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_DESCRIPTION), + LOG( + SemConvConstants.OTEL_SDK_EXPORTER_LOG_INFLIGHT_NAME, + SemConvConstants.OTEL_SDK_EXPORTER_LOG_INFLIGHT_UNIT, + SemConvConstants.OTEL_SDK_EXPORTER_LOG_INFLIGHT_DESCRIPTION, + SemConvConstants.OTEL_SDK_EXPORTER_LOG_EXPORTED_NAME, + SemConvConstants.OTEL_SDK_EXPORTER_LOG_EXPORTED_UNIT, + SemConvConstants.OTEL_SDK_EXPORTER_LOG_EXPORTED_DESCRIPTION), + PROFILE("TBD", "TBD", "TBD", "TBD", "TBD", "TBD"); + + private final String exporterInflightMetricName; + private final String exporterInflightMetricUnit; + private final String exporterInflightMetricDescription; + private final String exporterExportedMetricName; + private final String exporterExportedMetricUnit; + private final String exporterExportedMetricDescription; + + Signal( + String exporterInflightMetricName, + String exporterInflightMetricUnit, + String exporterInflightMetricDescription, + String exporterExportedMetricName, + String exporterExportedMetricUnit, + String exporterExportedMetricDescription) { + this.exporterInflightMetricName = exporterInflightMetricName; + this.exporterInflightMetricUnit = exporterInflightMetricUnit; + this.exporterInflightMetricDescription = exporterInflightMetricDescription; + this.exporterExportedMetricName = exporterExportedMetricName; + this.exporterExportedMetricUnit = exporterExportedMetricUnit; + this.exporterExportedMetricDescription = exporterExportedMetricDescription; + } + + public String logFriendlyName() { + return name().toLowerCase(Locale.ENGLISH); + } + + public String getExporterInflightMetricName() { + return exporterInflightMetricName; + } + + public String getExporterInflightMetricUnit() { + return exporterInflightMetricUnit; + } + + public String getExporterInflightMetricDescription() { + return exporterInflightMetricDescription; + } + + public String getExporterExportedMetricName() { + return exporterExportedMetricName; + } + + public String getExporterExportedMetricUnit() { + return exporterExportedMetricUnit; + } + + public String getExporterExportedMetricDescription() { + return exporterExportedMetricDescription; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/StackTraceRenderer.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/StackTraceRenderer.java new file mode 100644 index 00000000000..eda1cb7cbc9 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/StackTraceRenderer.java @@ -0,0 +1,154 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import java.io.PrintStream; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +/** + * An alternative to exception stacktrace renderer that replicates the behavior of {@link + * Throwable#printStackTrace(PrintStream)}, but which is aware of a maximum stacktrace length limit, + * and exits early when the length limit has been exceeded to avoid unnecessary computation. + * + *

      Instances should only be used once. + */ +class StackTraceRenderer { + + private static final String CAUSED_BY = "Caused by: "; + private static final String SUPPRESSED = "Suppressed: "; + + private final Throwable throwable; + private final int lengthLimit; + private final StringBuilder builder = new StringBuilder(); + + StackTraceRenderer(Throwable throwable, int lengthLimit) { + this.throwable = throwable; + this.lengthLimit = lengthLimit; + } + + String render() { + if (builder.length() == 0) { + appendStackTrace(); + } + + return builder.substring(0, Math.min(builder.length(), lengthLimit)); + } + + private void appendStackTrace() { + builder.append(throwable).append(System.lineSeparator()); + if (isOverLimit()) { + return; + } + + StackTraceElement[] stackTraceElements = throwable.getStackTrace(); + for (StackTraceElement stackTraceElement : stackTraceElements) { + builder.append("\tat ").append(stackTraceElement).append(System.lineSeparator()); + if (isOverLimit()) { + return; + } + } + + Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + seen.add(throwable); + + for (Throwable suppressed : throwable.getSuppressed()) { + appendInnerStacktrace(stackTraceElements, suppressed, "\t", SUPPRESSED, seen); + } + + Throwable cause = throwable.getCause(); + if (cause != null) { + appendInnerStacktrace(stackTraceElements, cause, "", CAUSED_BY, seen); + } + } + + /** + * Append the {@code innerThrowable} to the {@link #builder}, returning {@code true} if the + * builder now exceeds the length limit. + */ + private boolean appendInnerStacktrace( + StackTraceElement[] parentElements, + Throwable innerThrowable, + String prefix, + String caption, + Set seen) { + if (seen.contains(innerThrowable)) { + builder + .append(prefix) + .append(caption) + .append("[CIRCULAR REFERENCE: ") + .append(innerThrowable) + .append("]") + .append(System.lineSeparator()); + return true; + } + seen.add(innerThrowable); + + // Iterating back to front, compute the lastSharedFrameIndex, which tracks the point at which + // this exception's stacktrace elements start repeating the parent's elements + StackTraceElement[] currentElements = innerThrowable.getStackTrace(); + int parentIndex = parentElements.length - 1; + int lastSharedFrameIndex = currentElements.length - 1; + while (true) { + if (parentIndex < 0 || lastSharedFrameIndex < 0) { + break; + } + if (!parentElements[parentIndex].equals(currentElements[lastSharedFrameIndex])) { + break; + } + parentIndex--; + lastSharedFrameIndex--; + } + + builder.append(prefix).append(caption).append(innerThrowable).append(System.lineSeparator()); + if (isOverLimit()) { + return true; + } + + for (int i = 0; i <= lastSharedFrameIndex; i++) { + StackTraceElement stackTraceElement = currentElements[i]; + builder + .append(prefix) + .append("\tat ") + .append(stackTraceElement) + .append(System.lineSeparator()); + if (isOverLimit()) { + return true; + } + } + + int duplicateFrames = currentElements.length - 1 - lastSharedFrameIndex; + if (duplicateFrames != 0) { + builder + .append(prefix) + .append("\t... ") + .append(duplicateFrames) + .append(" more") + .append(System.lineSeparator()); + if (isOverLimit()) { + return true; + } + } + + for (Throwable suppressed : innerThrowable.getSuppressed()) { + if (appendInnerStacktrace(currentElements, suppressed, prefix + "\t", SUPPRESSED, seen)) { + return true; + } + } + + Throwable cause = innerThrowable.getCause(); + if (cause != null) { + return appendInnerStacktrace(currentElements, cause, prefix, CAUSED_BY, seen); + } + + return false; + } + + private boolean isOverLimit() { + return builder.length() >= lengthLimit; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/StandardComponentId.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/StandardComponentId.java new file mode 100644 index 00000000000..c9716bdfc15 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/StandardComponentId.java @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +/** + * A {@link ComponentId} where the component type is one of {@link ExporterType}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class StandardComponentId extends ComponentId.Lazy { + + /** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ + public enum ExporterType { + OTLP_GRPC_SPAN_EXPORTER("otlp_grpc_span_exporter", Signal.SPAN), + OTLP_HTTP_SPAN_EXPORTER("otlp_http_span_exporter", Signal.SPAN), + OTLP_HTTP_JSON_SPAN_EXPORTER("otlp_http_json_span_exporter", Signal.SPAN), + OTLP_GRPC_LOG_EXPORTER("otlp_grpc_log_exporter", Signal.LOG), + OTLP_HTTP_LOG_EXPORTER("otlp_http_log_exporter", Signal.LOG), + OTLP_HTTP_JSON_LOG_EXPORTER("otlp_http_json_log_exporter", Signal.LOG), + OTLP_GRPC_METRIC_EXPORTER("otlp_grpc_metric_exporter", Signal.METRIC), + OTLP_HTTP_METRIC_EXPORTER("otlp_http_metric_exporter", Signal.METRIC), + OTLP_HTTP_JSON_METRIC_EXPORTER("otlp_http_json_metric_exporter", Signal.METRIC), + OTLP_GRPC_PROFILES_EXPORTER("TBD", Signal.PROFILE); // TODO: not yet standardized in semconv + + final String value; + private final Signal signal; + + ExporterType(String value, Signal signal) { + this.value = value; + this.signal = signal; + } + + public Signal signal() { + return signal; + } + } + + private final ExporterType standardType; + + StandardComponentId(ExporterType standardType) { + super(standardType.value); + this.standardType = standardType; + } + + public ExporterType getStandardType() { + return standardType; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ThrottlingLogger.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ThrottlingLogger.java new file mode 100644 index 00000000000..4b10c888b1a --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ThrottlingLogger.java @@ -0,0 +1,126 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static java.util.concurrent.TimeUnit.MINUTES; + +import io.opentelemetry.sdk.common.Clock; +import java.util.Locale; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; + +/** + * Will limit the number of log messages emitted, so as not to spam when problems are happening. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public class ThrottlingLogger { + private static final double DEFAULT_RATE_LIMIT = 5; + private static final double DEFAULT_THROTTLED_RATE_LIMIT = 1; + private static final TimeUnit DEFAULT_RATE_TIME_UNIT = MINUTES; + + private final Logger delegate; + private final AtomicBoolean throttled = new AtomicBoolean(false); + private final RateLimiter fastRateLimiter; + private final RateLimiter throttledRateLimiter; + + private final double rateLimit; + private final double throttledRateLimit; + private final TimeUnit rateTimeUnit; + + /** Create a new logger which will enforce a max number of messages per minute. */ + public ThrottlingLogger(Logger delegate) { + this(delegate, Clock.getDefault()); + } + + /** Alternate way to create logger that allows setting custom intervals and units. * */ + public ThrottlingLogger( + Logger delegate, double rateLimit, double throttledRateLimit, TimeUnit rateTimeUnit) { + this(delegate, Clock.getDefault(), rateLimit, throttledRateLimit, rateTimeUnit); + } + + // visible for testing + ThrottlingLogger(Logger delegate, Clock clock) { + this(delegate, clock, DEFAULT_RATE_LIMIT, DEFAULT_THROTTLED_RATE_LIMIT, DEFAULT_RATE_TIME_UNIT); + } + + ThrottlingLogger( + Logger delegate, + Clock clock, + double rateLimit, + double throttledRateLimit, + TimeUnit rateTimeUnit) { + this.delegate = delegate; + this.rateLimit = rateLimit; + this.throttledRateLimit = throttledRateLimit; + this.rateTimeUnit = rateTimeUnit; + this.fastRateLimiter = + new RateLimiter(this.rateLimit / this.rateTimeUnit.toSeconds(1), this.rateLimit, clock); + this.throttledRateLimiter = + new RateLimiter( + this.throttledRateLimit / this.rateTimeUnit.toSeconds(1), + this.throttledRateLimit, + clock); + } + + /** Log a message at the given level. */ + public void log(Level level, String message) { + log(level, message, null); + } + + /** Log a message at the given level with a throwable. */ + public void log(Level level, String message, @Nullable Throwable throwable) { + if (!isLoggable(level)) { + return; + } + if (throttled.get()) { + if (throttledRateLimiter.trySpend(1.0)) { + doLog(level, message, throwable); + } + return; + } + + if (fastRateLimiter.trySpend(1.0)) { + doLog(level, message, throwable); + return; + } + + if (throttled.compareAndSet(false, true)) { + // spend the balance in the throttled one, so that it starts at zero. + throttledRateLimiter.trySpend(throttledRateLimit); + String timeUnitString = rateTimeUnit.toString().toLowerCase(Locale.ROOT); + String throttleMessage = + String.format( + Locale.ROOT, + "Too many log messages detected. Will only log %.0f time(s) per %s from now on.", + throttledRateLimit, + timeUnitString.substring(0, timeUnitString.length() - 1)); + delegate.log(level, throttleMessage); + doLog(level, message, throwable); + } + } + + private void doLog(Level level, String message, @Nullable Throwable throwable) { + if (throwable != null) { + delegate.log(level, message, throwable); + } else { + delegate.log(level, message); + } + } + + /** + * Returns whether the current wrapped logger is set to log at the given level. + * + * @return true if the logger set to log at the requested level. + */ + public boolean isLoggable(Level level) { + return delegate.isLoggable(level); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ThrowableUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ThrowableUtil.java similarity index 93% rename from sdk/common/src/main/java/io/opentelemetry/sdk/internal/ThrowableUtil.java rename to sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ThrowableUtil.java index a8709940dd7..23808ec5823 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ThrowableUtil.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/ThrowableUtil.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; /** * This class is internal and is hence not for public use. Its APIs are unstable and can change at diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/package-info.java b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/package-info.java new file mode 100644 index 00000000000..ee8c83e8ad8 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/common/internal/package-info.java @@ -0,0 +1,15 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * Interfaces and implementations that are internal to OpenTelemetry. + * + *

      All the content under this package and its subpackages are considered not part of the public + * API, and must not be used by users of the OpenTelemetry library. + */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.common.internal; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/AttributeUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/AttributeUtil.java deleted file mode 100644 index de7fac88eba..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/AttributeUtil.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.function.Predicate; - -/** - * This class is internal and is hence not for public use. Its APIs are unstable and can change at - * any time. - */ -public final class AttributeUtil { - - private AttributeUtil() {} - - /** - * Apply the {@code countLimit} and {@code lengthLimit} to the attributes. - * - *

      If all attributes fall within the limits, return as is. Else, return an attributes instance - * with the limits applied. {@code countLimit} limits the number of unique attribute keys. {@code - * lengthLimit} limits the length of attribute string and string list values. - */ - @SuppressWarnings({"unchecked", "rawtypes"}) - public static Attributes applyAttributesLimit( - Attributes attributes, int countLimit, int lengthLimit) { - if (attributes.isEmpty() || attributes.size() <= countLimit) { - if (lengthLimit == Integer.MAX_VALUE) { - return attributes; - } - boolean allValidLength = - allMatch(attributes.asMap().values(), value -> isValidLength(value, lengthLimit)); - if (allValidLength) { - return attributes; - } - } - - AttributesBuilder result = Attributes.builder(); - int i = 0; - for (Map.Entry, Object> entry : attributes.asMap().entrySet()) { - if (i >= countLimit) { - break; - } - result.put( - (AttributeKey) entry.getKey(), applyAttributeLengthLimit(entry.getValue(), lengthLimit)); - i++; - } - return result.build(); - } - - private static boolean isValidLength(Object value, int lengthLimit) { - if (value instanceof List) { - return allMatch((List) value, entry -> isValidLength(entry, lengthLimit)); - } else if (value instanceof String) { - return ((String) value).length() < lengthLimit; - } - return true; - } - - private static boolean allMatch(Iterable iterable, Predicate predicate) { - for (T value : iterable) { - if (!predicate.test(value)) { - return false; - } - } - return true; - } - - /** - * Apply the {@code lengthLimit} to the attribute {@code value}. Strings and strings in lists - * which exceed the length limit are truncated. - */ - public static Object applyAttributeLengthLimit(Object value, int lengthLimit) { - if (lengthLimit == Integer.MAX_VALUE) { - return value; - } - if (value instanceof List) { - List values = (List) value; - List response = new ArrayList<>(values.size()); - for (Object entry : values) { - response.add(applyAttributeLengthLimit(entry, lengthLimit)); - } - return response; - } - if (value instanceof String) { - String str = (String) value; - return str.length() < lengthLimit ? value : str.substring(0, lengthLimit); - } - return value; - } -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ComponentRegistry.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ComponentRegistry.java deleted file mode 100644 index 9aa09ddddb2..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ComponentRegistry.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Function; -import javax.annotation.Nullable; - -/** - * Base class for all the provider classes (TracerProvider, MeterProvider, etc.). - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - * - * @param the type of the registered value. - */ -public final class ComponentRegistry { - - private final ConcurrentMap registry = new ConcurrentHashMap<>(); - private final Function factory; - - public ComponentRegistry(Function factory) { - this.factory = factory; - } - - /** - * Returns the registered value associated with this name and {@code null} version if any, - * otherwise creates a new instance and associates it with the given name and {@code null} version - * and schemaUrl. - * - * @param instrumentationScopeName the name of the instrumentation scope. - * @return the registered value associated with this name and {@code null} version. - */ - public V get(String instrumentationScopeName) { - return get(instrumentationScopeName, null); - } - - /** - * Returns the registered value associated with this name and version if any, otherwise creates a - * new instance and associates it with the given name and version. The schemaUrl will be set to - * null. - * - * @param instrumentationScopeName the name of the instrumentation scope. - * @param instrumentationScopeVersion the version of the instrumentation scope. - * @return the registered value associated with this name and version. - */ - public V get(String instrumentationScopeName, @Nullable String instrumentationScopeVersion) { - return get(instrumentationScopeName, instrumentationScopeVersion, null); - } - - /** - * Returns the registered value associated with this name and version if any, otherwise creates a - * new instance and associates it with the given name and version. - * - * @param instrumentationScopeName the name of the instrumentation scope. - * @param instrumentationScopeVersion the version of the instrumentation scope. - * @param schemaUrl the URL of the OpenTelemetry schema used by the instrumentation scope. - * @return the registered value associated with this name and version. - * @since 1.4.0 - */ - public V get( - String instrumentationScopeName, - @Nullable String instrumentationScopeVersion, - @Nullable String schemaUrl) { - InstrumentationScopeInfo instrumentationScopeInfo = - InstrumentationScopeInfo.create( - instrumentationScopeName, instrumentationScopeVersion, schemaUrl); - - // Optimistic lookup, before creating the new component. - V component = registry.get(instrumentationScopeInfo); - if (component != null) { - return component; - } - - V newComponent = factory.apply(instrumentationScopeInfo); - V oldComponent = registry.putIfAbsent(instrumentationScopeInfo, newComponent); - return oldComponent != null ? oldComponent : newComponent; - } - - /** - * Returns a {@code Collection} view of the registered components. - * - * @return a {@code Collection} view of the registered components. - */ - public Collection getComponents() { - return Collections.unmodifiableCollection(new ArrayList<>(registry.values())); - } -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/CurrentJavaVersionSpecific.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/CurrentJavaVersionSpecific.java deleted file mode 100644 index f4f5e07c9f7..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/CurrentJavaVersionSpecific.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2019 LINE Corporation - * - * LINE Corporation licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package io.opentelemetry.sdk.internal; - -final class CurrentJavaVersionSpecific { - - static JavaVersionSpecific get() { - return new JavaVersionSpecific(); - } - - private CurrentJavaVersionSpecific() {} -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/DaemonThreadFactory.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/DaemonThreadFactory.java deleted file mode 100644 index 9e319d8f735..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/DaemonThreadFactory.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * A {@link ThreadFactory} that delegates to {@code Executors.defaultThreadFactory()} and marks all - * threads as daemon. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class DaemonThreadFactory implements ThreadFactory { - private final String namePrefix; - private final AtomicInteger counter = new AtomicInteger(); - private final ThreadFactory delegate = Executors.defaultThreadFactory(); - - public DaemonThreadFactory(String namePrefix) { - this.namePrefix = namePrefix; - } - - @Override - public Thread newThread(Runnable runnable) { - Thread t = delegate.newThread(runnable); - try { - t.setDaemon(true); - t.setName(namePrefix + "-" + counter.incrementAndGet()); - } catch (SecurityException e) { - // Well, we tried. - } - return t; - } -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/InstrumentationScopeUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/InstrumentationScopeUtil.java deleted file mode 100644 index 299a6f7d778..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/InstrumentationScopeUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; - -/** - * This class is internal and is hence not for public use. Its APIs are unstable and can change at - * any time. - */ -public final class InstrumentationScopeUtil { - - /** Convert to {@link io.opentelemetry.sdk.common.InstrumentationLibraryInfo}. */ - @SuppressWarnings("deprecation") // Utility method for compatibility - public static io.opentelemetry.sdk.common.InstrumentationLibraryInfo toInstrumentationLibraryInfo( - InstrumentationScopeInfo instrumentationScopeInfo) { - return io.opentelemetry.sdk.common.InstrumentationLibraryInfo.create( - instrumentationScopeInfo.getName(), - instrumentationScopeInfo.getVersion(), - instrumentationScopeInfo.getSchemaUrl()); - } - - /** Convert to {@link InstrumentationScopeInfo}. */ - @SuppressWarnings("deprecation") // Utility method for compatibility - public static InstrumentationScopeInfo toInstrumentationScopeInfo( - io.opentelemetry.sdk.common.InstrumentationLibraryInfo instrumentationLibraryInfo) { - return InstrumentationScopeInfo.create( - instrumentationLibraryInfo.getName(), - instrumentationLibraryInfo.getVersion(), - instrumentationLibraryInfo.getSchemaUrl()); - } - - private InstrumentationScopeUtil() {} -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/JavaVersionSpecific.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/JavaVersionSpecific.java deleted file mode 100644 index 31025fc2675..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/JavaVersionSpecific.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2019 LINE Corporation - * - * LINE Corporation licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package io.opentelemetry.sdk.internal; - -import java.util.concurrent.TimeUnit; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Contains APIs that are implemented differently based on the version of Java being run. This class - * implements the default, using Java 8 APIs, the minimum version supported by OpenTelemetry. All - * implementations in this class must be forwards-compatible on all Java versions because this class - * may be used outside the multi-release JAR, e.g., in testing or when a user shades without - * creating their own multi-release JAR. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public class JavaVersionSpecific { - - private static final Logger logger = Logger.getLogger(JavaVersionSpecific.class.getName()); - - private static final JavaVersionSpecific CURRENT = CurrentJavaVersionSpecific.get(); - - static { - if (CURRENT.getClass() != JavaVersionSpecific.class) { - logger.log(Level.FINE, "Using the APIs optimized for: {0}", CURRENT.name()); - } - } - - /** Returns the {@link JavaVersionSpecific} for the current version of Java. */ - public static JavaVersionSpecific get() { - return CURRENT; - } - - String name() { - return "Java 8"; - } - - /** Returns the number of nanoseconds since the epoch (00:00:00, 01-Jan-1970, GMT). */ - public long currentTimeNanos() { - return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - } -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ThrottlingLogger.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ThrottlingLogger.java deleted file mode 100644 index d4bd64d1af8..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/ThrottlingLogger.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import static java.util.concurrent.TimeUnit.MINUTES; - -import io.opentelemetry.sdk.common.Clock; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.annotation.Nullable; - -/** - * Will limit the number of log messages emitted, so as not to spam when problems are happening. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public class ThrottlingLogger { - private static final double RATE_LIMIT = 5; - private static final double THROTTLED_RATE_LIMIT = 1; - private static final TimeUnit rateTimeUnit = MINUTES; - - private final Logger delegate; - private final AtomicBoolean throttled = new AtomicBoolean(false); - private final RateLimiter fastRateLimiter; - private final RateLimiter throttledRateLimiter; - - /** Create a new logger which will enforce a max number of messages per minute. */ - public ThrottlingLogger(Logger delegate) { - this(delegate, Clock.getDefault()); - } - - // visible for testing - ThrottlingLogger(Logger delegate, Clock clock) { - this.delegate = delegate; - this.fastRateLimiter = - new RateLimiter(RATE_LIMIT / rateTimeUnit.toSeconds(1), RATE_LIMIT, clock); - this.throttledRateLimiter = - new RateLimiter(RATE_LIMIT / rateTimeUnit.toSeconds(1), THROTTLED_RATE_LIMIT, clock); - } - - /** Log a message at the given level. */ - public void log(Level level, String message) { - log(level, message, null); - } - - /** Log a message at the given level with a throwable. */ - public void log(Level level, String message, @Nullable Throwable throwable) { - if (!isLoggable(level)) { - return; - } - if (throttled.get()) { - if (throttledRateLimiter.trySpend(1.0)) { - doLog(level, message, throwable); - } - return; - } - - if (fastRateLimiter.trySpend(1.0)) { - doLog(level, message, throwable); - return; - } - - if (throttled.compareAndSet(false, true)) { - // spend the balance in the throttled one, so that it starts at zero. - throttledRateLimiter.trySpend(THROTTLED_RATE_LIMIT); - delegate.log( - level, "Too many log messages detected. Will only log once per minute from now on."); - doLog(level, message, throwable); - } - } - - private void doLog(Level level, String message, @Nullable Throwable throwable) { - if (throwable != null) { - delegate.log(level, message, throwable); - } else { - delegate.log(level, message); - } - } - - /** - * Returns whether the current wrapped logger is set to log at the given level. - * - * @return true if the logger set to log at the requested level. - */ - public boolean isLoggable(Level level) { - return delegate.isLoggable(level); - } -} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/package-info.java b/sdk/common/src/main/java/io/opentelemetry/sdk/internal/package-info.java deleted file mode 100644 index ca31e897eb9..00000000000 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/internal/package-info.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * Interfaces and implementations that are internal to OpenTelemetry. - * - *

      All the content under this package and its subpackages are considered not part of the public - * API, and must not be used by users of the OpenTelemetry library. - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.internal; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java index 0b3b6408824..aed76474408 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/Resource.java @@ -5,25 +5,26 @@ package io.opentelemetry.sdk.resources; -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.SERVICE_NAME; -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.TELEMETRY_SDK_LANGUAGE; -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.TELEMETRY_SDK_NAME; -import static io.opentelemetry.semconv.resource.attributes.ResourceAttributes.TELEMETRY_SDK_VERSION; - import com.google.auto.value.AutoValue; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.api.internal.StringUtils; -import io.opentelemetry.api.internal.Utils; +import io.opentelemetry.sdk.common.internal.OtelVersion; +import io.opentelemetry.sdk.resources.internal.AttributeCheckUtil; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; import java.util.Objects; -import java.util.Properties; +import java.util.Set; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** - * {@link Resource} represents a resource, which capture identifying information about the entities + * {@link Resource} represents a resource, which captures identifying information about the entities * for which signals (stats or traces) are reported. */ @Immutable @@ -31,13 +32,13 @@ public abstract class Resource { private static final Logger logger = Logger.getLogger(Resource.class.getName()); - private static final int MAX_LENGTH = 255; - private static final String ERROR_MESSAGE_INVALID_CHARS = - " should be a ASCII string with a length greater than 0 and not exceed " - + MAX_LENGTH - + " characters."; - private static final String ERROR_MESSAGE_INVALID_VALUE = - " should be a ASCII string with a length not exceed " + MAX_LENGTH + " characters."; + private static final AttributeKey SERVICE_NAME = AttributeKey.stringKey("service.name"); + private static final AttributeKey TELEMETRY_SDK_LANGUAGE = + AttributeKey.stringKey("telemetry.sdk.language"); + private static final AttributeKey TELEMETRY_SDK_NAME = + AttributeKey.stringKey("telemetry.sdk.name"); + private static final AttributeKey TELEMETRY_SDK_VERSION = + AttributeKey.stringKey("telemetry.sdk.version"); private static final Resource EMPTY = create(Attributes.empty()); private static final Resource TELEMETRY_SDK; @@ -54,7 +55,7 @@ public abstract class Resource { Attributes.builder() .put(TELEMETRY_SDK_NAME, "opentelemetry") .put(TELEMETRY_SDK_LANGUAGE, "java") - .put(TELEMETRY_SDK_VERSION, readVersion()) + .put(TELEMETRY_SDK_VERSION, OtelVersion.VERSION) .build()); } @@ -87,8 +88,8 @@ public static Resource empty() { * @param attributes a map of attributes that describe the resource. * @return a {@code Resource}. * @throws NullPointerException if {@code attributes} is null. - * @throws IllegalArgumentException if attribute key or attribute value is not a valid printable - * ASCII string or exceed {@link #MAX_LENGTH} characters. + * @throws IllegalArgumentException if an attribute key is empty, is not printable ASCII, or + * exceeds 255 characters. */ public static Resource create(Attributes attributes) { return create(attributes, null); @@ -101,24 +102,59 @@ public static Resource create(Attributes attributes) { * @param schemaUrl The URL of the OpenTelemetry schema used to create this Resource. * @return a {@code Resource}. * @throws NullPointerException if {@code attributes} is null. - * @throws IllegalArgumentException if attribute key or attribute value is not a valid printable - * ASCII string or exceed {@link #MAX_LENGTH} characters. + * @throws IllegalArgumentException if an attribute key is empty, is not printable ASCII, or + * exceeds 255 characters. */ public static Resource create(Attributes attributes, @Nullable String schemaUrl) { - checkAttributes(Objects.requireNonNull(attributes, "attributes")); - return new AutoValue_Resource(schemaUrl, attributes); + return create(attributes, schemaUrl, Collections.emptyList()); } - private static String readVersion() { - Properties properties = new Properties(); - try { - properties.load( - Resource.class.getResourceAsStream("/io/opentelemetry/sdk/common/version.properties")); - } catch (Exception e) { - // we left the attribute empty - return "unknown"; + /** + * Builds a resource after conflicts have been resolved. Entity types and attribute key owners + * must be unique, and ordinary attribute keys must not also belong to entities. This method + * rejects conflicting input rather than choosing which value wins; callers must merge ordinary + * attributes first and entities second before calling it. + * + * @param attributes unassociated attributes that describe the resource. + * @param schemaUrl The URL of the OpenTelemetry schema used to create this Resource. + * @param entities The normalized set of valid entities that participate in this resource. + * @return a {@code Resource}. + * @throws NullPointerException if {@code attributes} is null. + * @throws IllegalArgumentException if attribute keys are invalid or the state is not normalized. + */ + static Resource create( + Attributes attributes, @Nullable String schemaUrl, Collection entities) { + AttributeCheckUtil.checkAttributes(Objects.requireNonNull(attributes, "attributes")); + Collection immutableEntities = Collections.unmodifiableList(new ArrayList<>(entities)); + Set entityTypes = new HashSet<>(); + Set entityKeys = new HashSet<>(); + AttributesBuilder fullAttributes = Attributes.builder(); + for (Entity entity : immutableEntities) { + if (!entityTypes.add(entity.getType())) { + throw new IllegalArgumentException("Entity types must be unique in normalized resources."); + } + putEntityAttributes(entity.getId(), entityKeys, fullAttributes); + putEntityAttributes(entity.getDescription(), entityKeys, fullAttributes); } - return properties.getProperty("sdk.version", "unknown"); + attributes.forEach((key, value) -> { + if (entityKeys.contains(key.getKey())) { + throw new IllegalArgumentException( + "Unassociated attributes must not overlap entity attributes."); + } + }); + fullAttributes.putAll(attributes); + return new AutoValue_Resource(schemaUrl, immutableEntities, fullAttributes.build()); + } + + private static void putEntityAttributes( + Attributes attributes, Set entityKeys, AttributesBuilder fullAttributes) { + attributes.forEach((key, value) -> { + if (!entityKeys.add(key.getKey())) { + throw new IllegalArgumentException( + "Entity attribute keys must have a single owner and classification."); + } + }); + fullAttributes.putAll(attributes); } /** @@ -130,6 +166,24 @@ private static String readVersion() { @Nullable public abstract String getSchemaUrl(); + /** + * Returns a map of attributes that describe the resource, not associated with entities. + * + * @return a map of attributes. + */ + final Attributes getUnassociatedAttributes() { + AttributesBuilder unassociatedAttributes = getAttributes().toBuilder(); + unassociatedAttributes.removeIf(key -> EntityUtil.hasAttributeKey(getEntities(), key)); + return unassociatedAttributes.build(); + } + + /** + * Returns a collection of associated entities. + * + * @return a collection of entities. + */ + abstract Collection getEntities(); + /** * Returns a map of attributes that describe the resource. * @@ -151,67 +205,43 @@ public T getAttribute(AttributeKey key) { * Returns a new, merged {@link Resource} by merging the current {@code Resource} with the {@code * other} {@code Resource}. In case of a collision, the "other" {@code Resource} takes precedence. * + *

      Entity associations follow the rules documented in {@link ResourceBuilder}. Incoming + * entities are processed before incoming unassociated attributes. Merging the same resources in + * the same order can produce different entity associations depending on which pair is merged + * first: {@code a.merge(b).merge(c)} can differ from {@code a.merge(b.merge(c))}, even if both + * results have the same attribute keys and values. + * + *

      The merged {@code schemaUrl} is computed from the two resources' {@code schemaUrl} values, + * not from their entities. If either is null, the other is used. If both are non-null and differ, + * the merged resource has no {@code schemaUrl}. + * * @param other the {@code Resource} that will be merged with {@code this}. * @return the newly merged {@code Resource}. */ public Resource merge(@Nullable Resource other) { - if (other == null) { + if (other == null || other.equals(EMPTY)) { return this; } - - AttributesBuilder attrBuilder = Attributes.builder(); - attrBuilder.putAll(this.getAttributes()); - attrBuilder.putAll(other.getAttributes()); - - if (other.getSchemaUrl() == null) { - return create(attrBuilder.build(), getSchemaUrl()); - } - if (getSchemaUrl() == null) { - return create(attrBuilder.build(), other.getSchemaUrl()); - } - if (!other.getSchemaUrl().equals(getSchemaUrl())) { - logger.info( - "Attempting to merge Resources with different schemaUrls. " - + "The resulting Resource will have no schemaUrl assigned. Schema 1: " - + getSchemaUrl() - + " Schema 2: " - + other.getSchemaUrl()); - // currently, behavior is undefined if schema URLs don't match. In the future, we may - // apply schema transformations if possible. - return create(attrBuilder.build(), null); - } - return create(attrBuilder.build(), getSchemaUrl()); - } - - private static void checkAttributes(Attributes attributes) { - attributes.forEach( - (key, value) -> { - Utils.checkArgument( - isValidAndNotEmpty(key), "Attribute key" + ERROR_MESSAGE_INVALID_CHARS); - Objects.requireNonNull(value, "Attribute value" + ERROR_MESSAGE_INVALID_VALUE); - }); + return builder() + .putAll(this) + .putAll(other) + .buildWithSchemaUrl(mergeSchemaUrl(getSchemaUrl(), other.getSchemaUrl())); } - /** - * Determines whether the given {@code String} is a valid printable ASCII string with a length not - * exceed {@link #MAX_LENGTH} characters. - * - * @param name the name to be validated. - * @return whether the name is valid. - */ - private static boolean isValid(String name) { - return name.length() <= MAX_LENGTH && StringUtils.isPrintableString(name); - } - - /** - * Determines whether the given {@code String} is a valid printable ASCII string with a length - * greater than 0 and not exceed {@link #MAX_LENGTH} characters. - * - * @param name the name to be validated. - * @return whether the name is valid. - */ - private static boolean isValidAndNotEmpty(AttributeKey name) { - return !name.getKey().isEmpty() && isValid(name.getKey()); + @Nullable + private static String mergeSchemaUrl(@Nullable String base, @Nullable String next) { + if (base == null || next == null || base.equals(next)) { + return base == null ? next : base; + } + logger.info( + "Attempting to merge Resources with different schemaUrls. " + + "The resulting Resource will have no schemaUrl assigned. Schema 1: " + + base + + " Schema 2: " + + next); + // currently, behavior is undefined if schema URLs don't match. In the future, we may + // apply schema transformations if possible. + return null; } /** @@ -227,6 +257,9 @@ public static ResourceBuilder builder() { * Returns a new {@link ResourceBuilder} instance populated with the data of this {@link * Resource}. * + *

      A non-null schema URL is copied as explicit builder configuration, even if originally + * derived from entities. Subsequent entity changes do not cause this URL to be re-derived. + * * @since 1.1.0 */ public ResourceBuilder toBuilder() { diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java index 9963eeaf541..e073bf7c29a 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/ResourceBuilder.java @@ -8,18 +8,77 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.Objects; +import java.util.Set; import java.util.function.Predicate; +import java.util.logging.Logger; import javax.annotation.Nullable; /** - * A builder of {@link Resource} that allows to add key-value pairs and copy attributes from other - * {@link Attributes} or {@link Resource}. + * A builder for {@link Resource} that allows adding key-value pairs and copying attributes from + * other {@link Attributes} or {@link Resource} instances. + * + *

      Resources may carry experimental entity associations. Within an entity, identifying and + * descriptive attribute keys must not overlap. + * + *

      Resource-level {@code schemaUrl} handling is best effort: conflicts do not prevent attribute + * merging, but leave the merged resource without a {@code schemaUrl}. Entity merge compatibility + * requires matching types, identifying attributes, and entity {@code schemaUrl} values. For + * entities, null and empty {@code schemaUrl} values both represent absence and match each other. + * Conflicting entity {@code schemaUrl} values may indicate a configuration or version mismatch. + * + *

      Builder operations follow these rules: + * + *

        + *
      • Later writes win, whether attributes are ordinary or entity-owned. Writing the same value + * with the same attribute type does not remove the entity association. + *
      • Compatible incoming entities merge descriptions. Different identifying attributes or {@code + * schemaUrl} values with the same type replace the whole old entity, including all its + * attributes. + *
      • An ordinary write that changes any entity-owned attribute, or an incoming entity that + * claims attributes from a different entity type, removes the affected entity association. + * All non-conflicting attributes remain as ordinary attributes. + *
      • Filtering applies to ordinary and entity-owned attributes. Removing any entity identifying + * attribute key removes the entity association and retains surviving attributes as ordinary + * attributes. Removing only descriptive attributes preserves entity association. + *
      + * + *

      Both {@link #putAll(Resource)} and {@link Resource#merge(Resource)} apply incoming entities + * before incoming ordinary attributes. Merging the same resources in the same order can produce + * different entity associations depending on which pair is merged first: {@code + * a.merge(b).merge(c)} can differ from {@code a.merge(b.merge(c))}. + * + *

      Without explicit configuration, each {@link #build()} call derives the {@code schemaUrl} + * shared by all current entities that declare one, or null if none declare one or their values + * differ. {@link #putAll(Resource)} does not copy {@code schemaUrl}. {@link Resource#toBuilder()} + * copies a non-null source {@code schemaUrl} as explicit configuration, even if it was derived from + * entities. + * + *

      {@link #build()} rejects ordinary attributes whose key names are empty, contain characters + * outside printable ASCII, or exceed 255 characters. + * + *

      These rules describe resource APIs, not environment parsing. Java {@link + * Object#equals(Object)} is structural equality, not semantic resource identity. Descriptions and + * entity order affect resource equality. + * + *

      Entity replacements, description changes, and association removals are logged at {@code + * WARNING}. * * @since 1.1.0 */ public class ResourceBuilder { + private static final Logger logger = Logger.getLogger(ResourceBuilder.class.getName()); + private final AttributesBuilder attributesBuilder = Attributes.builder(); + private final List entities = new ArrayList<>(); @Nullable private String schemaUrl; /** @@ -33,6 +92,7 @@ public class ResourceBuilder { public ResourceBuilder put(String key, String value) { if (key != null && value != null) { attributesBuilder.put(key, value); + removeEntityAssociations(key); } return this; } @@ -48,6 +108,7 @@ public ResourceBuilder put(String key, String value) { public ResourceBuilder put(String key, long value) { if (key != null) { attributesBuilder.put(key, value); + removeEntityAssociations(key); } return this; } @@ -63,6 +124,7 @@ public ResourceBuilder put(String key, long value) { public ResourceBuilder put(String key, double value) { if (key != null) { attributesBuilder.put(key, value); + removeEntityAssociations(key); } return this; } @@ -78,6 +140,7 @@ public ResourceBuilder put(String key, double value) { public ResourceBuilder put(String key, boolean value) { if (key != null) { attributesBuilder.put(key, value); + removeEntityAssociations(key); } return this; } @@ -93,6 +156,7 @@ public ResourceBuilder put(String key, boolean value) { public ResourceBuilder put(String key, String... values) { if (key != null && values != null) { attributesBuilder.put(key, values); + removeEntityAssociations(key); } return this; } @@ -108,6 +172,7 @@ public ResourceBuilder put(String key, String... values) { public ResourceBuilder put(String key, long... values) { if (key != null && values != null) { attributesBuilder.put(key, values); + removeEntityAssociations(key); } return this; } @@ -123,6 +188,7 @@ public ResourceBuilder put(String key, long... values) { public ResourceBuilder put(String key, double... values) { if (key != null && values != null) { attributesBuilder.put(key, values); + removeEntityAssociations(key); } return this; } @@ -138,6 +204,7 @@ public ResourceBuilder put(String key, double... values) { public ResourceBuilder put(String key, boolean... values) { if (key != null && values != null) { attributesBuilder.put(key, values); + removeEntityAssociations(key); } return this; } @@ -146,6 +213,7 @@ public ResourceBuilder put(String key, boolean... values) { public ResourceBuilder put(AttributeKey key, T value) { if (key != null && key.getKey() != null && !key.getKey().isEmpty() && value != null) { attributesBuilder.put(key, value); + removeEntityAssociations(key.getKey()); } return this; } @@ -154,6 +222,7 @@ public ResourceBuilder put(AttributeKey key, T value) { public ResourceBuilder put(AttributeKey key, int value) { if (key != null && key.getKey() != null && !key.getKey().isEmpty()) { attributesBuilder.put(key, value); + removeEntityAssociations(key.getKey()); } return this; } @@ -162,21 +231,38 @@ public ResourceBuilder put(AttributeKey key, int value) { public ResourceBuilder putAll(Attributes attributes) { if (attributes != null) { attributesBuilder.putAll(attributes); + removeEntityAssociations(); } return this; } - /** Puts all attributes from {@link Resource} into this. */ + /** + * Copies entity associations and attributes from {@link Resource}, following the class-level + * rules. Does not copy {@code schemaUrl}. + */ public ResourceBuilder putAll(Resource resource) { if (resource != null) { - attributesBuilder.putAll(resource.getAttributes()); + resource.getEntities().forEach(this::addEntity); + putAll(resource.getUnassociatedAttributes()); } return this; } /** Remove all attributes that satisfy the given predicate from {@link Resource}. */ public ResourceBuilder removeIf(Predicate> filter) { + if (filter == null) { + return this; + } attributesBuilder.removeIf(filter); + ListIterator iterator = entities.listIterator(); + while (iterator.hasNext()) { + Entity filtered = removeAttributes(iterator.next(), filter); + if (filtered == null) { + iterator.remove(); + } else { + iterator.set(filtered); + } + } return this; } @@ -194,6 +280,165 @@ public ResourceBuilder setSchemaUrl(String schemaUrl) { /** Create the {@link Resource} from this. */ public Resource build() { - return Resource.create(attributesBuilder.build(), schemaUrl); + return buildWithSchemaUrl(schemaUrl != null ? schemaUrl : deriveSchemaUrl(entities)); + } + + /** Builds using {@code resourceSchemaUrl} as-is, without deriving it from entities. */ + Resource buildWithSchemaUrl(@Nullable String resourceSchemaUrl) { + return Resource.create(attributesBuilder.build(), resourceSchemaUrl, entities); + } + + /** + * Merges an incoming entity without validating pending ordinary attributes. + * + *

      An existing entity of the same type with equal identifying attributes and schema URL merges + * descriptions, with incoming values winning. Otherwise, the incoming entity replaces it. Any + * other entity sharing an attribute key with the incoming entity loses its association, and its + * attributes are retained as unassociated unless the incoming entity owns them. + */ + ResourceBuilder addEntity(Entity incoming) { + Entity next = incoming; + Entity old = removeEntity(incoming.getType()); + if (old != null) { + if (old.getId().equals(incoming.getId()) + && Objects.equals( + normalizeSchemaUrl(old.getSchemaUrl()), + normalizeSchemaUrl(incoming.getSchemaUrl()))) { + next = + incoming.toBuilder() + .setDescription( + Attributes.builder() + .putAll(old.getDescription()) + .putAll(incoming.getDescription()) + .build()) + .build(); + if (!next.getDescription().equals(old.getDescription())) { + logger.warning("Updating descriptive attributes of entity [" + next.getType() + "]."); + } + } else { + logger.warning( + "Replacing entity [" + + old.getType() + + "] because " + + (old.getId().equals(incoming.getId()) + ? "schema URLs differ." + : "identifying attributes differ.")); + } + } + Iterator iterator = entities.iterator(); + while (iterator.hasNext()) { + Entity existing = iterator.next(); + if (EntityUtil.sharesAttributeKey(existing, next)) { + logger.warning( + "Removing entity association [" + + existing.getType() + + "] because incoming entity [" + + next.getType() + + "] overwrites its attributes. Non-conflicting attributes are retained as unassociated."); + attributesBuilder.putAll(existing.getId()).putAll(existing.getDescription()); + iterator.remove(); + } + } + entities.add(next); + attributesBuilder.removeIf(key -> EntityUtil.hasAttributeKey(entities, key)); + return this; + } + + @Nullable + private Entity removeEntity(String type) { + Iterator iterator = entities.iterator(); + while (iterator.hasNext()) { + Entity entity = iterator.next(); + if (entity.getType().equals(type)) { + iterator.remove(); + return entity; + } + } + return null; + } + + /** + * Removes matching attributes from the entity. Removing any identifying attribute removes the + * association and retains the remaining attributes as unassociated. + * + * @return the filtered entity, or null if its association was removed. + */ + @Nullable + private Entity removeAttributes(Entity entity, Predicate> filter) { + Attributes id = entity.getId().toBuilder().removeIf(filter).build(); + Attributes description = entity.getDescription().toBuilder().removeIf(filter).build(); + if (!id.equals(entity.getId())) { + logger.warning( + "Removing entity association [" + + entity.getType() + + "] because identifying attribute keys were filtered. Remaining attributes are retained as unassociated."); + attributesBuilder.putAll(id).putAll(description); + return null; + } + if (description.equals(entity.getDescription())) { + return entity; + } + logger.warning("Removing descriptive attribute keys from entity [" + entity.getType() + "]."); + return entity.toBuilder().setDescription(description).build(); + } + + private void removeEntityAssociations(String key) { + if (!entities.isEmpty() && EntityUtil.hasAttributeKey(entities, key)) { + removeEntityAssociations(); + } + } + + private void removeEntityAssociations() { + if (entities.isEmpty()) { + return; + } + Attributes overrides = attributesBuilder.build(); + boolean removed = false; + Iterator iterator = entities.iterator(); + while (iterator.hasNext()) { + Entity entity = iterator.next(); + if (hasAttributeOverride(entity.getId(), overrides) + || hasAttributeOverride(entity.getDescription(), overrides)) { + logger.warning( + "Removing entity association [" + + entity.getType() + + "] because resource attributes change the value or type of its attributes. Other attributes are retained as unassociated."); + attributesBuilder.putAll(entity.getId()).putAll(entity.getDescription()); + iterator.remove(); + removed = true; + } + } + if (removed) { + attributesBuilder.putAll(overrides); + } + // Unchanged writes remain entity-owned rather than becoming loose attributes. + attributesBuilder.removeIf(key -> EntityUtil.hasAttributeKey(entities, key)); + } + + /** Returns true if incoming attributes change the value or type of a current attribute. */ + private static boolean hasAttributeOverride(Attributes current, Attributes incoming) { + // Map lookup compares attribute types without valueKey's type coercion. + return incoming.asMap().entrySet().stream() + .anyMatch(entry -> + EntityUtil.hasAttributeKey(current, entry.getKey().getKey()) + && !Objects.equals(current.asMap().get(entry.getKey()), entry.getValue())); + } + + /** Returns the schema URL shared by all entities that declare one, or null if they differ. */ + @Nullable + private static String deriveSchemaUrl(List entities) { + Set schemaUrls = new HashSet<>(); + for (Entity entity : entities) { + String entitySchemaUrl = normalizeSchemaUrl(entity.getSchemaUrl()); + if (entitySchemaUrl != null) { + schemaUrls.add(entitySchemaUrl); + } + } + return schemaUrls.size() == 1 ? schemaUrls.iterator().next() : null; + } + + @Nullable + static String normalizeSchemaUrl(@Nullable String schemaUrl) { + return schemaUrl == null || schemaUrl.isEmpty() ? null : schemaUrl; } } diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java new file mode 100644 index 00000000000..941828539d3 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/AttributeCheckUtil.java @@ -0,0 +1,73 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.util.Objects; + +/** + * Helpers to check resource entity attributes. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @see SdkEntityBuilder + */ +public final class AttributeCheckUtil { + private AttributeCheckUtil() {} + + // Note: Max length is actually configurable by specification. + private static final int MAX_LENGTH = 255; + private static final String ERROR_MESSAGE_INVALID_CHARS = + " should be a ASCII string with a length greater than 0 and not exceed " + + MAX_LENGTH + + " characters."; + private static final String ERROR_MESSAGE_INVALID_VALUE = + " should be a ASCII string with a length not exceed " + MAX_LENGTH + " characters."; + + /** Determine if the set of attributes if valid for Resource / Entity. */ + public static void checkAttributes(Attributes attributes) { + attributes.forEach((key, value) -> { + if (!isValidAndNotEmpty(key)) { + throw new IllegalArgumentException("Attribute key" + ERROR_MESSAGE_INVALID_CHARS); + } + Objects.requireNonNull(value, "Attribute value" + ERROR_MESSAGE_INVALID_VALUE); + }); + } + + /** + * Determines whether the given {@code String} is a valid printable ASCII string with a length + * greater than 0 and not exceed {@link #MAX_LENGTH} characters. + * + * @param name the name to be validated. + * @return whether the name is valid. + */ + public static boolean isValidAndNotEmpty(AttributeKey name) { + return !name.getKey().isEmpty() && isValid(name.getKey()); + } + + /** + * Determines whether the given {@code String} is a valid printable ASCII string with a length not + * exceed {@link #MAX_LENGTH} characters. + * + * @param name the name to be validated. + * @return whether the name is valid. + */ + public static boolean isValid(String name) { + return name.length() <= MAX_LENGTH && isPrintableString(name); + } + + private static boolean isPrintableString(String str) { + for (int i = 0; i < str.length(); i++) { + char ch = str.charAt(i); + if (ch < ' ' || ch > '~') { + return false; + } + } + return true; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/ConstantResourceDetector.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/ConstantResourceDetector.java new file mode 100644 index 00000000000..67044d70a2e --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/ConstantResourceDetector.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.Nullable; + +final class ConstantResourceDetector implements ResourceDetector { + + @Nullable private final String name; + private final Resource resource; + + ConstantResourceDetector(@Nullable String name, Resource resource) { + this.name = name; + this.resource = resource; + } + + @Nullable + @Override + public String getName() { + return name; + } + + @Override + public Resource getResource() { + return resource; + } + + @Override + public String toString() { + return "ConstantResourceDetector{name=" + name + ", resource=" + resource + "}"; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/Entity.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/Entity.java new file mode 100644 index 00000000000..efb9f4f39a2 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/Entity.java @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.api.common.Attributes; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * Entity represents an object of interest associated with produced telemetry: traces, metrics or + * logs. + * + *

      For example, telemetry produced using OpenTelemetry SDK is normally associated with a Service + * entity. Similarly, OpenTelemetry defines system metrics for a host. The Host is the entity we + * want to associate metrics with in this case. + * + *

      Entities may be also associated with produced telemetry indirectly. For example a service that + * produces telemetry is also related with a process in which the service runs, so we say that the + * Service entity is related to the Process entity. The process normally also runs on a host, so we + * say that the Process entity is related to the Host entity. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +// TODO(jack-berg): Should Entity/EntityBuilder be replaced with autovalue equivalent +@Immutable +public interface Entity { + /** + * Returns the entity type string of this entity. Must not be null. + * + * @return the entity type. + */ + String getType(); + + /** + * Returns a map of attributes that identify the entity. + * + * @return the entity identity. + */ + Attributes getId(); + + /** + * Returns a map of attributes that describe the entity. + * + * @return the entity description. + */ + Attributes getDescription(); + + /** + * Returns this entity's optional OpenTelemetry schema URL. Null and empty URLs both represent + * absence; SDK-created entities use null. + * + * @return An OpenTelemetry schema URL. + */ + @Nullable + String getSchemaUrl(); + + /** + * Returns a new {@link EntityBuilder} instance populated with the data of this {@link Entity}. + */ + EntityBuilder toBuilder(); + + /** + * Returns a new {@link EntityBuilder} instance for creating arbitrary {@link Entity}. + * + * @param entityType the entity type string of this entity. + * @param id the identifying attributes of this entity + */ + static EntityBuilder builder(String entityType, Attributes id) { + return new SdkEntityBuilder(entityType, id); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/EntityBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/EntityBuilder.java new file mode 100644 index 00000000000..9ac810923b3 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/EntityBuilder.java @@ -0,0 +1,37 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.api.common.Attributes; + +/** + * A builder of {@link Entity} that allows to add identifying or descriptive {@link Attributes}, as + * well as type and schema_url. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface EntityBuilder { + /** + * Assign an OpenTelemetry schema URL to the resulting Entity. An empty URL represents absence. + * + * @param schemaUrl The URL of the OpenTelemetry schema being used to create this Entity. + * @return this + */ + EntityBuilder setSchemaUrl(String schemaUrl); + + /** + * Modify the descriptive attributes of this Entity. + * + * @param description The attributes that describe the Entity. + * @return this + * @throws IllegalArgumentException if an attribute key also occurs in identifying attributes. + */ + EntityBuilder setDescription(Attributes description); + + /** Create the {@link Entity} from this. */ + Entity build(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/EntityUtil.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/EntityUtil.java new file mode 100644 index 00000000000..14a2e98fe30 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/EntityUtil.java @@ -0,0 +1,118 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collection; +import javax.annotation.Nullable; + +/** + * Helper class for dealing with Entities. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class EntityUtil { + + private EntityUtil() {} + + /** + * Constructs a new {@link Resource} with Entity support. + * + * @param entities The set of entities the resource needs. + * @return A constructed resource. + */ + public static Resource createResource(Collection entities) { + ResourceBuilder builder = Resource.builder(); + entities.forEach(entity -> addEntity(builder, entity)); + return builder.build(); + } + + /** + * Merges an entity into the builder, following the rules documented in {@link ResourceBuilder}. + */ + public static ResourceBuilder addEntity(ResourceBuilder rb, Entity e) { + try { + Method method = ResourceBuilder.class.getDeclaredMethod("addEntity", Entity.class); + method.setAccessible(true); + method.invoke(rb, e); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ex) { + throw new IllegalStateException("Error calling addEntity on ResourceBuilder", ex); + } + return rb; + } + + /** + * Returns a collection of associated entities. + * + * @return a collection of entities. + */ + @SuppressWarnings("unchecked") + public static Collection getEntities(Resource r) { + try { + Method method = Resource.class.getDeclaredMethod("getEntities"); + method.setAccessible(true); + return (Collection) method.invoke(r); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException("Error calling getEntities on Resource", e); + } + } + + /** + * Returns a map of attributes that describe the resource, not associated with entities. + * + * @return a map of attributes. + */ + public static Attributes getUnassociatedAttributes(Resource r) { + try { + Method method = Resource.class.getDeclaredMethod("getUnassociatedAttributes"); + method.setAccessible(true); + return (Attributes) method.invoke(r); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException("Error calling getUnassociatedAttributes on Resource", e); + } + } + + /** Returns true if any entity in the collection has the attribute key, in id or description. */ + public static boolean hasAttributeKey(Collection entities, AttributeKey key) { + return hasAttributeKey(entities, key.getKey()); + } + + /** Returns true if any entity references an attribute with the given name. */ + public static boolean hasAttributeKey(Collection entities, String key) { + return entities.stream() + .anyMatch(e -> hasAttributeKey(e.getId(), key) || hasAttributeKey(e.getDescription(), key)); + } + + /** Returns true if the attributes contain the given attribute key name, regardless of type. */ + public static boolean hasAttributeKey(Attributes attributes, String key) { + return attributes.asMap().keySet().stream().anyMatch(existing -> existing.getKey().equals(key)); + } + + /** Returns true if the attributes share any attribute key name, regardless of type. */ + public static boolean sharesAttributeKey(Attributes first, Attributes second) { + return first.asMap().keySet().stream().anyMatch(key -> hasAttributeKey(second, key.getKey())); + } + + /** Returns true if the entities share any attribute key name, regardless of type. */ + public static boolean sharesAttributeKey(Entity first, Entity second) { + return sharesAttributeKey(first.getId(), second.getId()) + || sharesAttributeKey(first.getId(), second.getDescription()) + || sharesAttributeKey(first.getDescription(), second.getId()) + || sharesAttributeKey(first.getDescription(), second.getDescription()); + } + + /** Returns null for either representation of an absent schema URL. */ + @Nullable + static String normalizeSchemaUrl(@Nullable String schemaUrl) { + return schemaUrl == null || schemaUrl.isEmpty() ? null : schemaUrl; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/ResourceDetector.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/ResourceDetector.java new file mode 100644 index 00000000000..7cea19e273e --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/ResourceDetector.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.Nullable; + +/** A source of a {@link Resource} to be merged by an {@link SdkResourceProvider}. */ +interface ResourceDetector { + + // TODO(jack-berg): Add shouldReinvoke() or equivalent to distinguish static detectors from + // detectors whose entity + // descriptive attributes can change at runtime. + + /** + * Returns a diagnostic label for logging / debugging, or {@code null} if unnamed. This is not a + * detector lookup identifier and need not be unique. + */ + @Nullable + String getName(); + + /** Returns the {@link Resource} detected by this detector. */ + Resource getResource(); +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkEntity.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkEntity.java new file mode 100644 index 00000000000..a96c33c8f1c --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkEntity.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * SDK implementation of Entity. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class SdkEntity implements Entity { + /** + * Returns a {@link Entity}. + * + * @param entityType the entity type string of this entity. + * @param id a map of attributes that identify the entity. + * @param description a map of attributes that describe the entity. + * @return a {@code Entity}. + */ + static Entity create( + String entityType, Attributes id, Attributes description, @Nullable String schemaUrl) { + return new AutoValue_SdkEntity( + entityType, id, description, EntityUtil.normalizeSchemaUrl(schemaUrl)); + } + + @Override + public final EntityBuilder toBuilder() { + return new SdkEntityBuilder(this); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkEntityBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkEntityBuilder.java new file mode 100644 index 00000000000..d392678eade --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkEntityBuilder.java @@ -0,0 +1,71 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import io.opentelemetry.api.common.Attributes; +import java.util.Objects; +import javax.annotation.Nullable; + +/** + * A builder of {@link Entity} that allows to add identifying or descriptive {@link Attributes}, as + * well as type and schema_url. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class SdkEntityBuilder implements EntityBuilder { + private final String entityType; + private final Attributes id; + private Attributes description; + @Nullable private String schemaUrl; + + SdkEntityBuilder(String entityType, Attributes id) { + Objects.requireNonNull(entityType, "entityType"); + Objects.requireNonNull(id, "id"); + checkArgument( + !entityType.isEmpty() && AttributeCheckUtil.isValid(entityType), + "Entity type must be a valid non-empty printable ASCII string."); + checkArgument(!id.isEmpty(), "Entity must have at least one identifying attribute."); + AttributeCheckUtil.checkAttributes(id); + this.entityType = entityType; + this.id = id; + this.description = Attributes.empty(); + } + + SdkEntityBuilder(Entity seed) { + this.entityType = seed.getType(); + this.schemaUrl = seed.getSchemaUrl(); + this.id = seed.getId(); + this.description = seed.getDescription(); + } + + @Override + public EntityBuilder setSchemaUrl(String schemaUrl) { + this.schemaUrl = schemaUrl; + return this; + } + + @Override + public EntityBuilder setDescription(Attributes description) { + AttributeCheckUtil.checkAttributes(Objects.requireNonNull(description, "description")); + checkArgument( + !EntityUtil.sharesAttributeKey(id, description), + "Identifying and descriptive attribute keys must not overlap."); + this.description = description; + return this; + } + + @Override + public Entity build() { + return SdkEntity.create(entityType, id, description, schemaUrl); + } + + private static void checkArgument(boolean isValid, String errorMessage) { + if (!isValid) { + throw new IllegalArgumentException(errorMessage); + } + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkResourceProvider.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkResourceProvider.java new file mode 100644 index 00000000000..13d016cff07 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkResourceProvider.java @@ -0,0 +1,72 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Provides the {@link Resource} used by the SDK by merging the results of a configured, ordered + * list of {@link ResourceDetector}s. + * + *

      All detectors are invoked once when the provider is built. The merged {@link Resource} is + * cached for the lifetime of this provider. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class SdkResourceProvider { + + private final List detectors; + // TODO: Add TTL-based cache refresh that re-invokes only refreshable detectors while keeping + // hot-path resource reads cheap. + private final Resource cachedResource; + + private SdkResourceProvider(List detectors, Resource cachedResource) { + this.detectors = detectors; + this.cachedResource = cachedResource; + } + + static SdkResourceProvider createFromDetectors(List detectors) { + List detectorSnapshot = + Collections.unmodifiableList(new ArrayList<>(detectors)); + return new SdkResourceProvider(detectorSnapshot, merge(detectorSnapshot)); + } + + /** Returns a new {@link SdkResourceProviderBuilder}. */ + public static SdkResourceProviderBuilder builder() { + return new SdkResourceProviderBuilder(); + } + + /** Returns an {@link SdkResourceProvider} backed by a single constant {@link Resource}. */ + public static SdkResourceProvider create(Resource resource) { + requireNonNull(resource, "resource"); + return builder().addConstantResource(resource).build(); + } + + /** Returns the merged {@link Resource}. */ + public Resource getResource() { + return cachedResource; + } + + private static Resource merge(List detectors) { + Resource resource = Resource.empty(); + for (ResourceDetector detector : detectors) { + resource = resource.merge(detector.getResource()); + } + return resource; + } + + @Override + public String toString() { + return "SdkResourceProvider{detectors=" + detectors + "}"; + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkResourceProviderBuilder.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkResourceProviderBuilder.java new file mode 100644 index 00000000000..0f193c1f146 --- /dev/null +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/internal/SdkResourceProviderBuilder.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.List; +import javax.annotation.Nullable; + +/** + * Builder for {@link SdkResourceProvider}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class SdkResourceProviderBuilder { + + private final List detectors = new ArrayList<>(); + + SdkResourceProviderBuilder() {} + + /** + * Adds a constant {@link Resource} with no name. + * + * @param resource the resource to add + * @return this builder + */ + public SdkResourceProviderBuilder addConstantResource(Resource resource) { + return addConstantResource(resource, null); + } + + /** + * Adds a constant {@link Resource}. Resources are merged in the order they are added, with + * later-added attributes winning on conflict (per {@link Resource#merge}). + * + * @param resource the resource to add + * @param name a diagnostic label for logging / debugging, or {@code null} if unnamed. This is not + * a detector lookup identifier and need not be unique. + * @return this builder + */ + public SdkResourceProviderBuilder addConstantResource(Resource resource, @Nullable String name) { + requireNonNull(resource, "resource"); + detectors.add(new ConstantResourceDetector(name, resource)); + return this; + } + + /** + * Returns a new {@link SdkResourceProvider}. + * + * @throws IllegalStateException if no resource has been added via {@link + * #addConstantResource(Resource)}. + */ + public SdkResourceProvider build() { + if (detectors.isEmpty()) { + throw new IllegalStateException( + "At least one Resource must be added via addConstantResource before calling build()."); + } + return SdkResourceProvider.createFromDetectors(detectors); + } +} diff --git a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/package-info.java b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/package-info.java index f905c4c3f6f..07808bdbe8e 100644 --- a/sdk/common/src/main/java/io/opentelemetry/sdk/resources/package-info.java +++ b/sdk/common/src/main/java/io/opentelemetry/sdk/resources/package-info.java @@ -13,7 +13,7 @@ * *

      Attribute keys, and attribute values MUST contain only printable ASCII (codes between 32 and * 126, inclusive) and less than 256 characters. Type and attribute keys MUST have a length greater - * than zero. They SHOULD start with a domain name and separate hierarchies with / characters, e.g. + * than zero. They should start with a domain name and separate hierarchies with / characters, e.g. * k8s.io/namespace/name. */ @ParametersAreNonnullByDefault diff --git a/sdk/common/src/main/java9/io/opentelemetry/sdk/internal/CurrentJavaVersionSpecific.java b/sdk/common/src/main/java9/io/opentelemetry/sdk/internal/CurrentJavaVersionSpecific.java deleted file mode 100644 index 08dfe8eabdd..00000000000 --- a/sdk/common/src/main/java9/io/opentelemetry/sdk/internal/CurrentJavaVersionSpecific.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2019 LINE Corporation - * - * LINE Corporation licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package io.opentelemetry.sdk.internal; - -final class CurrentJavaVersionSpecific { - - static JavaVersionSpecific get() { - return new Java9VersionSpecific(); - } - - private CurrentJavaVersionSpecific() {} -} diff --git a/sdk/common/src/main/java9/io/opentelemetry/sdk/internal/Java9VersionSpecific.java b/sdk/common/src/main/java9/io/opentelemetry/sdk/internal/Java9VersionSpecific.java deleted file mode 100644 index 72ad70970c6..00000000000 --- a/sdk/common/src/main/java9/io/opentelemetry/sdk/internal/Java9VersionSpecific.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -// Includes work from: -/* - * Copyright 2019 LINE Corporation - * - * LINE Corporation licenses this file to you under the Apache License, - * version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at: - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations - * under the License. - */ - -package io.opentelemetry.sdk.internal; - -import java.time.Clock; -import java.time.Instant; -import java.util.concurrent.TimeUnit; - -/** Implementation of {@link JavaVersionSpecific} using Java 9 APIs. */ -class Java9VersionSpecific extends JavaVersionSpecific { - - @Override - String name() { - return "Java 9+"; - } - - @Override - public long currentTimeNanos() { - Instant now = Clock.systemUTC().instant(); - return TimeUnit.SECONDS.toNanos(now.getEpochSecond()) + now.getNano(); - } -} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java index 544777430f5..9f83d6d082e 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/CompletableResultCodeTest.java @@ -6,14 +6,17 @@ package io.opentelemetry.sdk.common; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.awaitility.Awaitility.await; import com.google.common.util.concurrent.Uninterruptibles; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.Test; @@ -21,12 +24,29 @@ class CompletableResultCodeTest { @Test void ofSuccess() { - assertThat(CompletableResultCode.ofSuccess().isSuccess()).isTrue(); + assertThat(CompletableResultCode.ofSuccess()) + .satisfies(code -> { + assertThat(code.isSuccess()).isTrue(); + assertThat(code.getFailureThrowable()).isNull(); + }); } @Test void ofFailure() { - assertThat(CompletableResultCode.ofFailure().isSuccess()).isFalse(); + assertThat(CompletableResultCode.ofFailure()) + .satisfies(code -> { + assertThat(code.isSuccess()).isFalse(); + assertThat(code.getFailureThrowable()).isNull(); + }); + } + + @Test + void ofExceptionalFailure() { + assertThat(CompletableResultCode.ofExceptionalFailure(new Exception("error"))) + .satisfies(code -> { + assertThat(code.isSuccess()).isFalse(); + assertThat(code.getFailureThrowable()).hasMessage("error"); + }); } @Test @@ -59,6 +79,15 @@ void fail() throws InterruptedException { assertThat(resultCode.isSuccess()).isFalse(); } + @Test + void failExceptionallyWithNull() { + CompletableResultCode resultCode = new CompletableResultCode(); + CompletableResultCode result = resultCode.failExceptionally(null); + assertThat(result.isDone()).isTrue(); + assertThat(result.isSuccess()).isFalse(); + assertThat(result.getFailureThrowable()).isNull(); + } + @Test void whenDoublyCompleteSuccessfully() throws InterruptedException { CompletableResultCode resultCode = new CompletableResultCode(); @@ -82,12 +111,11 @@ void whenDoublyNestedComplete() throws InterruptedException { new Thread(resultCode::succeed).start(); - resultCode.whenComplete( - () -> { - completions.countDown(); + resultCode.whenComplete(() -> { + completions.countDown(); - resultCode.whenComplete(completions::countDown); - }); + resultCode.whenComplete(completions::countDown); + }); completions.await(3, TimeUnit.SECONDS); @@ -149,6 +177,23 @@ void ofAllWithFailure() { .isFalse(); } + @Test + void ofAllWithExceptionalFailure() { + assertThat( + CompletableResultCode.ofAll( + Arrays.asList( + CompletableResultCode.ofSuccess(), + CompletableResultCode.ofFailure(), + CompletableResultCode.ofExceptionalFailure(new Exception("error1")), + CompletableResultCode.ofExceptionalFailure(new Exception("error2")), + CompletableResultCode.ofSuccess()))) + .satisfies(code -> { + assertThat(code.isSuccess()).isFalse(); + // failure throwable is set to first throwable seen in the collection + assertThat(code.getFailureThrowable()).hasMessage("error1"); + }); + } + @Test void join() { CompletableResultCode result = new CompletableResultCode(); @@ -175,11 +220,10 @@ void joinInterrupted() { CompletableResultCode result = new CompletableResultCode(); AtomicReference interrupted = new AtomicReference<>(); Thread thread = - new Thread( - () -> { - result.join(10, TimeUnit.SECONDS); - interrupted.set(Thread.currentThread().isInterrupted()); - }); + new Thread(() -> { + result.join(10, TimeUnit.SECONDS); + interrupted.set(Thread.currentThread().isInterrupted()); + }); thread.start(); thread.interrupt(); // Different thread so wait a bit for result to be propagated. @@ -187,4 +231,94 @@ void joinInterrupted() { assertThat(result.isSuccess()).isFalse(); assertThat(result.isDone()).isFalse(); } + + @Test + void callbackCompletionAnotherResultDoesNotDeadlock() throws InterruptedException { + CompletableResultCode first = new CompletableResultCode(); + CompletableResultCode second = new CompletableResultCode(); + CountDownLatch callbackEntered = new CountDownLatch(2); + CountDownLatch release = new CountDownLatch(1); + + first.whenComplete(() -> { + callbackEntered.countDown(); + Uninterruptibles.awaitUninterruptibly(release); + second.succeed(); + }); + + second.whenComplete(() -> { + callbackEntered.countDown(); + Uninterruptibles.awaitUninterruptibly(release); + first.succeed(); + }); + + Thread firstThread = new Thread(first::succeed, "complete-first"); + Thread secondThread = new Thread(second::succeed, "complete-second"); + firstThread.setDaemon(true); + secondThread.setDaemon(true); + firstThread.start(); + secondThread.start(); + + assertThat(callbackEntered.await(10, TimeUnit.SECONDS)).isTrue(); + release.countDown(); + + firstThread.join(10_000); + secondThread.join(10_000); + + assertThat(firstThread.isAlive()).isFalse(); + assertThat(secondThread.isAlive()).isFalse(); + assertThat(first.isSuccess()).isTrue(); + assertThat(second.isSuccess()).isTrue(); + } + + @Test + @SuppressLogger(CompletableResultCode.class) + void completionActionExceptionDoesNotAbortLaterActions() { + CompletableResultCode result = new CompletableResultCode(); + AtomicBoolean actionInvoked = new AtomicBoolean(); + + result.whenComplete(() -> { + throw new RuntimeException("callback failure"); + }); + result.whenComplete(() -> actionInvoked.set(true)); + assertThatThrownBy(result::succeed) + .isInstanceOf(RuntimeException.class) + .hasMessage("callback failure"); + + assertThat(actionInvoked).isTrue(); + assertThat(result.isSuccess()).isTrue(); + } + + @Test + @SuppressLogger(CompletableResultCode.class) + void completionActionExceptionDoesNotPreventOfAllCompletion() { + CompletableResultCode source = new CompletableResultCode(); + CompletableResultCode other = new CompletableResultCode(); + + // Registered before ofAll so that it runs before ofAll's bookkeeping action. + source.whenComplete(() -> { + throw new RuntimeException("callback failure"); + }); + CompletableResultCode all = CompletableResultCode.ofAll(Arrays.asList(source, other)); + other.succeed(); + + assertThatThrownBy(source::succeed) + .isInstanceOf(RuntimeException.class) + .hasMessage("callback failure"); + + assertThat(all.isDone()).isTrue(); + assertThat(all.isSuccess()).isTrue(); + } + + @Test + @SuppressLogger(CompletableResultCode.class) + void completionActionExceptionPropagatesWhenAlreadyComplete() { + CompletableResultCode result = new CompletableResultCode().succeed(); + + assertThatThrownBy(() -> + result.whenComplete(() -> { + throw new RuntimeException("callback failure"); + })) + .isInstanceOf(RuntimeException.class) + .hasMessage("callback failure"); + } } diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationLibraryInfoTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationLibraryInfoTest.java index 48d1b93e384..5a3cffc2251 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationLibraryInfoTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationLibraryInfoTest.java @@ -10,21 +10,19 @@ import org.junit.jupiter.api.Test; -/** Tests for {@link io.opentelemetry.sdk.common.InstrumentationLibraryInfo}. */ +/** Tests for {@link InstrumentationLibraryInfo}. */ @SuppressWarnings("deprecation") // Testing deprecated code class InstrumentationLibraryInfoTest { @Test void emptyLibraryInfo() { - assertThat(io.opentelemetry.sdk.common.InstrumentationLibraryInfo.empty().getName()).isEmpty(); - assertThat(io.opentelemetry.sdk.common.InstrumentationLibraryInfo.empty().getVersion()) - .isNull(); + assertThat(InstrumentationLibraryInfo.empty().getName()).isEmpty(); + assertThat(InstrumentationLibraryInfo.empty().getVersion()).isNull(); } @Test void nullName() { - assertThatThrownBy( - () -> io.opentelemetry.sdk.common.InstrumentationLibraryInfo.create(null, "1.0.0")) + assertThatThrownBy(() -> InstrumentationLibraryInfo.create(null, "1.0.0")) .isInstanceOf(NullPointerException.class) .hasMessage("name"); } diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoTest.java index fd628d38278..d5093d2f3bf 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/InstrumentationScopeInfoTest.java @@ -8,20 +8,54 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.opentelemetry.api.common.Attributes; import org.junit.jupiter.api.Test; class InstrumentationScopeInfoTest { @Test - void emptyScopeInfo() { - assertThat(InstrumentationScopeInfo.empty().getName()).isEmpty(); - assertThat(InstrumentationScopeInfo.empty().getVersion()).isNull(); + void create_InvalidArguments() { + assertThatThrownBy(() -> InstrumentationScopeInfo.builder(null).build()) + .isInstanceOf(NullPointerException.class) + .hasMessage("name"); } @Test - void nullName() { - assertThatThrownBy(() -> InstrumentationScopeInfo.create(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("name"); + void create_Valid() { + InstrumentationScopeInfo scope = InstrumentationScopeInfo.builder("name").build(); + assertThat(scope.getName()).isEqualTo("name"); + assertThat(scope.getVersion()).isNull(); + assertThat(scope.getSchemaUrl()).isNull(); + assertThat(scope.getAttributes()).isEqualTo(Attributes.empty()); + + scope = + InstrumentationScopeInfo.builder("name") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build(); + assertThat(scope.getName()).isEqualTo("name"); + assertThat(scope.getVersion()).isEqualTo("version"); + assertThat(scope.getSchemaUrl()).isEqualTo("schemaUrl"); + assertThat(scope.getAttributes()).isEqualTo(Attributes.builder().put("key", "value").build()); + } + + @Test + @SuppressWarnings("deprecation") // Testing deprecated code + void create_AllArgs() { + assertThat(InstrumentationScopeInfo.create("name", "version", "schemaUrl")) + .isEqualTo( + InstrumentationScopeInfo.builder("name") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .build()); + assertThat(InstrumentationScopeInfo.create("name", null, null)) + .isEqualTo(InstrumentationScopeInfo.builder("name").build()); + } + + @Test + void emptyScopeInfo() { + assertThat(InstrumentationScopeInfo.empty().getName()).isEmpty(); + assertThat(InstrumentationScopeInfo.empty().getVersion()).isNull(); } } diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/RetryPolicyTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/RetryPolicyTest.java new file mode 100644 index 00000000000..e0f56ff58a5 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/RetryPolicyTest.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.sdk.common.export.RetryPolicy; +import java.time.Duration; +import org.junit.jupiter.api.Test; + +public class RetryPolicyTest { + + @Test + void defaultRetryPolicy() { + RetryPolicy retryPolicy = RetryPolicy.builder().build(); + + assertThat(retryPolicy.getMaxAttempts()).isEqualTo(5); + assertThat(retryPolicy.getInitialBackoff()).isEqualTo(Duration.ofSeconds(1)); + assertThat(retryPolicy.getMaxBackoff()).isEqualTo(Duration.ofSeconds(5)); + assertThat(retryPolicy.getBackoffMultiplier()).isEqualTo(1.5); + + assertThat(RetryPolicy.getDefault()).isEqualTo(retryPolicy); + } + + @Test + void build() { + RetryPolicy retryPolicy = + RetryPolicy.builder() + .setMaxAttempts(2) + .setInitialBackoff(Duration.ofMillis(2)) + .setMaxBackoff(Duration.ofSeconds(1)) + .setBackoffMultiplier(1.1) + .build(); + + assertThat(retryPolicy.getMaxAttempts()).isEqualTo(2); + assertThat(retryPolicy.getInitialBackoff()).isEqualTo(Duration.ofMillis(2)); + assertThat(retryPolicy.getMaxBackoff()).isEqualTo(Duration.ofSeconds(1)); + assertThat(retryPolicy.getBackoffMultiplier()).isEqualTo(1.1); + assertThat(retryPolicy.getRetryExceptionPredicate()).isEqualTo(null); + } + + @Test + void invalidRetryPolicy() { + assertThatThrownBy(() -> RetryPolicy.builder().setMaxAttempts(1).build()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RetryPolicy.builder().setMaxAttempts(6).build()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RetryPolicy.builder().setInitialBackoff(null).build()) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> RetryPolicy.builder().setInitialBackoff(Duration.ofMillis(0)).build()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RetryPolicy.builder().setMaxBackoff(null).build()) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> RetryPolicy.builder().setMaxBackoff(Duration.ofMillis(0)).build()) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> RetryPolicy.builder().setBackoffMultiplier(0).build()) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/AttributesMapTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/AttributesMapTest.java new file mode 100644 index 00000000000..f2d12b6aa00 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/AttributesMapTest.java @@ -0,0 +1,401 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.entry; + +import com.google.common.testing.EqualsTester; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.util.AbstractList; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.ConcurrentModificationException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import org.junit.jupiter.api.Test; + +class AttributesMapTest { + + // ---- put ---- + + @Test + void put_returnsNullForNewEntry() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + + assertThat(map.put(stringKey("k"), "v")).isNull(); + } + + @Test + void put_returnsOldValueOnOverwrite() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("k"), "first"); + + assertThat(map.put(stringKey("k"), "second")).isEqualTo("first"); + assertThat(map.get(stringKey("k"))).isEqualTo("second"); + } + + @Test + void put_overwriteDoesNotIncrementTotalAddedValues() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("k"), "first"); + map.put(stringKey("k"), "second"); // overwrite β€” not a drop, must not widen total - size + + assertThat(map.size()).isEqualTo(1); + assertThat(map.getTotalAddedValues()).isEqualTo(1); + } + + @Test + void put_ignoresNullValue() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("k"), null); + + assertThat(map.size()).isEqualTo(0); + assertThat(map.isEmpty()).isTrue(); + assertThat(map.getTotalAddedValues()).isEqualTo(0); + } + + @Test + void putSameKeyDifferentType_lastValueWins() { + AttributesMap map = AttributesMap.create(128, Integer.MAX_VALUE); + map.put(stringKey("k"), "hello"); + map.put(booleanKey("k"), false); + + assertThat(map.size()).isEqualTo(1); + assertThat(map.get(booleanKey("k"))).isEqualTo(false); + assertThat(map.get(stringKey("k"))).isNull(); + } + + @Test + void putSameKeyDifferentType_doesNotConsumeExtraCapacity() { + AttributesMap map = AttributesMap.create(2, Integer.MAX_VALUE); + map.put(stringKey("a"), "v1"); + map.put(booleanKey("a"), false); // overwrite β€” must not consume a new capacity slot + map.put(longKey("b"), 42L); + + assertThat(map.size()).isEqualTo(2); + assertThat(map.getTotalAddedValues()).isEqualTo(2); + assertThat(map.get(booleanKey("a"))).isEqualTo(false); + assertThat(map.get(longKey("b"))).isEqualTo(42L); + } + + @Test + void putSameKeyDifferentType_previousTypeGetReturnsNull() { + AttributesMap map = AttributesMap.create(128, Integer.MAX_VALUE); + map.put(stringKey("k"), "hello"); + map.put(booleanKey("k"), true); + + assertThat(map.get(stringKey("k"))).isNull(); + assertThat(map.get(booleanKey("k"))).isEqualTo(true); + } + + // ---- get ---- + + @Test + void get_returnsNullForAbsentKey() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + + assertThat(map.get(stringKey("absent"))).isNull(); + } + + // ---- containsKey ---- + + @Test + void containsKey_returnsTrueForPresentKey() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("k"), "v"); + + assertThat(map.containsKey("k")).isTrue(); + assertThat(map.containsKey("absent")).isFalse(); + } + + @Test + void containsKey_returnsTrueForSameNameDifferentType() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(longKey("count"), 42L); + + // containsKey() is name-based: true even if originally put as longKey("count") + assertThat(map.containsKey("count")).isTrue(); + } + + // ---- capacity ---- + + @Test + void capacity_dropsEntriesBeyondLimit() { + AttributesMap map = AttributesMap.create(2, Integer.MAX_VALUE); + map.put(stringKey("a"), "v1"); + map.put(stringKey("b"), "v2"); + map.put(stringKey("c"), "v3"); // dropped β€” capacity reached + + assertThat(map.size()).isEqualTo(2); + assertThat(map.getTotalAddedValues()).isEqualTo(3); + assertThat(map.get(stringKey("c"))).isNull(); + } + + @Test + void capacity_zeroDropsAllEntries() { + AttributesMap map = AttributesMap.create(0, Integer.MAX_VALUE); + map.put(stringKey("k"), "v"); + + assertThat(map.size()).isEqualTo(0); + assertThat(map.isEmpty()).isTrue(); + } + + // ---- grow ---- + + @Test + void grow_preservesAllEntriesWhenSizeExceedsInitialArrayLength() { + // init = min(capacity, 16) = 16; grow() is triggered when the 17th entry is inserted + int n = 20; + AttributesMap map = AttributesMap.create(n, Integer.MAX_VALUE); + for (int i = 0; i < n; i++) { + map.put(stringKey("key" + i), "val" + i); + } + + assertThat(map.size()).isEqualTo(n); + for (int i = 0; i < n; i++) { + assertThat(map.get(stringKey("key" + i))).isEqualTo("val" + i); + } + } + + // ---- lengthLimit ---- + + @Test + void lengthLimit_truncatesStringValues() { + AttributesMap map = AttributesMap.create(10, 3); + map.put(stringKey("k"), "hello"); + + assertThat(map.get(stringKey("k"))).isEqualTo("hel"); + } + + @Test + void lengthLimit_failureDoesNotInsertPartialEntry() { + AttributesMap map = AttributesMap.create(10, 3); + + assertThatThrownBy(() -> map.put(stringArrayKey("k"), throwingList())) + .isInstanceOf(IllegalStateException.class); + + assertThat(map.isEmpty()).isTrue(); + assertThat(map.asMap()).isEmpty(); + } + + @Test + void lengthLimit_failureDoesNotPartiallyOverwriteEntry() { + AttributesMap map = AttributesMap.create(10, 3); + map.put(stringKey("k"), "old"); + + assertThatThrownBy(() -> map.put(stringArrayKey("k"), throwingList())) + .isInstanceOf(IllegalStateException.class); + + assertThat(map.size()).isEqualTo(1); + assertThat(map.get(stringKey("k"))).isEqualTo("old"); + assertThat(map.get(stringArrayKey("k"))).isNull(); + } + + // ---- forEach ---- + + @Test + void forEach_iteratesInInsertionOrder() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("first"), "v1"); + map.put(stringKey("second"), "v2"); + map.put(stringKey("third"), "v3"); + + List keys = new ArrayList<>(); + map.forEach((k, v) -> keys.add(k.getKey())); + + assertThat(keys).containsExactly("first", "second", "third"); + } + + // ---- views ---- + + @Test + void asMap() { + AttributesMap attributesMap = AttributesMap.create(2, Integer.MAX_VALUE); + attributesMap.put(longKey("one"), 1L); + attributesMap.put(longKey("two"), 2L); + + assertThat(attributesMap.asMap()) + .containsOnly(entry(longKey("one"), 1L), entry(longKey("two"), 2L)); + } + + @Test + void immutableCopy_containsAllEntries() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("a"), "v1"); + map.put(longKey("b"), 42L); + + Attributes copy = map.immutableCopy(); + + assertThat(copy.get(stringKey("a"))).isEqualTo("v1"); + assertThat(copy.get(longKey("b"))).isEqualTo(42L); + } + + // ---- hash collisions ---- + + @Test + void hashCollision_bothEntriesStoredAndRetrievable() { + // "Aa".hashCode() == "BB".hashCode() == 2112: collide in any table size. + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("Aa"), "v-Aa"); + map.put(stringKey("BB"), "v-BB"); + + assertThat(map.size()).isEqualTo(2); + assertThat(map.get(stringKey("Aa"))).isEqualTo("v-Aa"); + assertThat(map.get(stringKey("BB"))).isEqualTo("v-BB"); + } + + @Test + void findSlot_wrapsAroundEndOfTable() { + // capacity=4 => mask=7. "o" (111) and "w" (119) both hash to slot 7; the second wraps to 0. + AttributesMap map = AttributesMap.create(4, Integer.MAX_VALUE); + map.put(stringKey("o"), "v-o"); + map.put(stringKey("w"), "v-w"); + + assertThat(map.size()).isEqualTo(2); + assertThat(map.get(stringKey("o"))).isEqualTo("v-o"); + assertThat(map.get(stringKey("w"))).isEqualTo("v-w"); + } + + @Test + void grow_preservesEntriesIncludingPreExistingCollision() { + // capacity=20 => init=16 => grow triggers on 17th insert. "Aa"/"BB" collide at slot 0 both + // before and after grow (2112 & 31 == 2112 & 63 == 0), so rehash must preserve the probe path. + AttributesMap map = AttributesMap.create(20, Integer.MAX_VALUE); + map.put(stringKey("Aa"), "v-Aa"); + map.put(stringKey("BB"), "v-BB"); + for (int i = 0; i < 18; i++) { + map.put(stringKey("k" + i), "v" + i); + } + + assertThat(map.size()).isEqualTo(20); + assertThat(map.get(stringKey("Aa"))).isEqualTo("v-Aa"); + assertThat(map.get(stringKey("BB"))).isEqualTo("v-BB"); + for (int i = 0; i < 18; i++) { + assertThat(map.get(stringKey("k" + i))).isEqualTo("v" + i); + } + } + + // ---- concurrent modification detection ---- + + @Test + void forEach_throwsCmeOnConcurrentModification() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("a"), "v1"); + map.put(stringKey("b"), "v2"); + + assertThatThrownBy(() -> map.forEach((k, v) -> map.put(stringKey("c"), "v3"))) + .isInstanceOf(ConcurrentModificationException.class); + } + + @Test + void forEach_overwriteDuringIterationThrowsCme() { + // Overwrite (no size change) still bumps modCount. + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("a"), "v1"); + + assertThatThrownBy(() -> map.forEach((k, v) -> map.put(stringKey("a"), "v2"))) + .isInstanceOf(ConcurrentModificationException.class); + } + + @Test + void forEach_noModification_doesNotThrow() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("a"), "v1"); + map.put(stringKey("b"), "v2"); + + map.forEach((k, v) -> {}); + } + + // ---- fuzz ---- + + @Test + void fuzz_matchesReferenceHashMap() { + // Random puts vs reference HashMap. Exercises grow, overwrites, and type-varying puts to + // the same name. Fixed seed for reproducibility. + long seed = 0xC0FFEEL; + Random r = new Random(seed); + int capacity = 1000; + int ops = 5000; + int namePoolSize = 200; // ~25 overwrites per name on average + + AttributesMap map = AttributesMap.create(capacity, Integer.MAX_VALUE); + Map, Object>> reference = new HashMap<>(); + + for (int i = 0; i < ops; i++) { + String name = "key" + r.nextInt(namePoolSize); + AttributeKey key; + Object value; + switch (r.nextInt(3)) { + case 0: + key = stringKey(name); + value = "s" + i; + break; + case 1: + key = longKey(name); + value = (long) i; + break; + default: + key = booleanKey(name); + value = (i & 1) == 0; + break; + } + map.put(key, value); + reference.put(name, new AbstractMap.SimpleImmutableEntry<>(key, value)); + } + + assertThat(map.size()).isEqualTo(reference.size()); + for (Map.Entry, Object>> refEntry : reference.entrySet()) { + AttributeKey expectedKey = refEntry.getValue().getKey(); + Object expectedValue = refEntry.getValue().getValue(); + assertThat(map.get(expectedKey)).as("key=%s", expectedKey).isEqualTo(expectedValue); + } + } + + @Test + void equals_andHashCode() { + AttributesMap mapV1a = AttributesMap.create(10, Integer.MAX_VALUE); + mapV1a.put(stringKey("k"), "v1"); + AttributesMap mapV1b = AttributesMap.create(10, Integer.MAX_VALUE); + mapV1b.put(stringKey("k"), "v1"); + AttributesMap mapV2 = AttributesMap.create(10, Integer.MAX_VALUE); + mapV2.put(stringKey("k"), "v2"); + + new EqualsTester().addEqualityGroup(mapV1a, mapV1b).addEqualityGroup(mapV2).testEquals(); + } + + @Test + void equals_isSymmetricWithOtherAttributesImplementations() { + AttributesMap map = AttributesMap.create(10, Integer.MAX_VALUE); + map.put(stringKey("k"), "v"); + Attributes attributes = Attributes.of(stringKey("k"), "v"); + + assertThat(map).isNotEqualTo(attributes); + assertThat(attributes).isNotEqualTo(map); + } + + private static List throwingList() { + return new AbstractList() { + @Override + public String get(int index) { + throw new IllegalStateException("test"); + } + + @Override + public int size() { + return 1; + } + }; + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentIdTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentIdTest.java new file mode 100644 index 00000000000..7e291660843 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentIdTest.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.semconv.incubating.OtelIncubatingAttributes; +import org.junit.jupiter.api.Test; + +class ComponentIdTest { + + @Test + void testStandardTypesUpToDate() { + assertThat(StandardComponentId.ExporterType.OTLP_GRPC_SPAN_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_GRPC_SPAN_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_HTTP_SPAN_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_HTTP_SPAN_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_HTTP_JSON_SPAN_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues + .OTLP_HTTP_JSON_SPAN_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_GRPC_LOG_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_GRPC_LOG_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_HTTP_LOG_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_HTTP_LOG_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_HTTP_JSON_LOG_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_HTTP_JSON_LOG_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_GRPC_METRIC_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_GRPC_METRIC_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_HTTP_METRIC_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues.OTLP_HTTP_METRIC_EXPORTER); + assertThat(StandardComponentId.ExporterType.OTLP_HTTP_JSON_METRIC_EXPORTER.value) + .isEqualTo( + OtelIncubatingAttributes.OtelComponentTypeIncubatingValues + .OTLP_HTTP_JSON_METRIC_EXPORTER); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java new file mode 100644 index 00000000000..f7cb137e028 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ComponentRegistryTest.java @@ -0,0 +1,95 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static java.util.stream.Collectors.joining; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.stream.IntStream; +import org.junit.jupiter.api.Test; + +class ComponentRegistryTest { + + private static final String NAME = "test_name"; + private static final String VERSION = "version"; + private static final String SCHEMA_URL = "http://schema.com"; + private static final Attributes ATTRIBUTES = Attributes.builder().put("k1", "v1").build(); + private final ComponentRegistry registry = + new ComponentRegistry<>(unused -> new TestComponent()); + + @Test + void get_SameInstance() { + assertThat(registry.get(NAME, null, null, Attributes.empty())) + .isSameAs(registry.get(NAME, null, null, Attributes.empty())) + .isSameAs(registry.get(NAME, null, null, Attributes.builder().put("k1", "v2").build())); + + assertThat(registry.get(NAME, VERSION, null, Attributes.empty())) + .isSameAs(registry.get(NAME, VERSION, null, Attributes.empty())) + .isSameAs(registry.get(NAME, VERSION, null, Attributes.builder().put("k1", "v2").build())); + assertThat(registry.get(NAME, null, SCHEMA_URL, Attributes.empty())) + .isSameAs(registry.get(NAME, null, SCHEMA_URL, Attributes.empty())) + .isSameAs( + registry.get(NAME, null, SCHEMA_URL, Attributes.builder().put("k1", "v2").build())); + assertThat(registry.get(NAME, VERSION, SCHEMA_URL, Attributes.empty())) + .isSameAs(registry.get(NAME, VERSION, SCHEMA_URL, Attributes.empty())) + .isSameAs( + registry.get(NAME, VERSION, SCHEMA_URL, Attributes.builder().put("k1", "v2").build())); + } + + @Test + void get_DifferentInstance() { + assertThat(registry.get(NAME, VERSION, SCHEMA_URL, ATTRIBUTES)) + .isNotSameAs(registry.get(NAME + "_1", VERSION, SCHEMA_URL, ATTRIBUTES)) + .isNotSameAs(registry.get(NAME, VERSION + "_1", SCHEMA_URL, ATTRIBUTES)) + .isNotSameAs(registry.get(NAME, VERSION, SCHEMA_URL + "_1", ATTRIBUTES)); + + assertThat(registry.get(NAME, VERSION, null, Attributes.empty())) + .isNotSameAs(registry.get(NAME, null, null, Attributes.empty())); + + assertThat(registry.get(NAME, null, SCHEMA_URL, Attributes.empty())) + .isNotSameAs(registry.get(NAME, null, null, Attributes.empty())); + } + + @Test + @SuppressWarnings("ReturnValueIgnored") + void getComponents_HighConcurrency() throws ExecutionException, InterruptedException { + List> futures = new ArrayList<>(); + Random random = new Random(); + int concurrency = 2; + ExecutorService executor = Executors.newFixedThreadPool(concurrency); + + try { + for (int i = 0; i < 100; i++) { + futures.add( + executor.submit(() -> { + String name = + IntStream.range(0, 20) + .mapToObj(unused -> String.valueOf((char) random.nextInt(26))) + .collect(joining()); + registry.get(name, null, null, Attributes.empty()); + })); + futures.add( + executor.submit(() -> registry.getComponents().forEach(TestComponent::hashCode))); + } + + for (Future future : futures) { + future.get(); + } + } finally { + executor.shutdown(); + } + } + + private static final class TestComponent {} +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DaemonThreadFactoryTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DaemonThreadFactoryTest.java new file mode 100644 index 00000000000..69ef5d8b301 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DaemonThreadFactoryTest.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import org.junit.jupiter.api.Test; + +class DaemonThreadFactoryTest { + + @Test + void verifyUncaughtExceptions() + throws ExecutionException, InterruptedException, TimeoutException { + Thread.UncaughtExceptionHandler defaultHandler = mock(); + ThreadFactory delegateFactory = + r -> { + Thread thread = Executors.defaultThreadFactory().newThread(r); + thread.setUncaughtExceptionHandler(defaultHandler); + return thread; + }; + ExecutorService service = + Executors.newSingleThreadExecutor(new DaemonThreadFactory("test", delegateFactory)); + Callable callable = + () -> { + Thread.UncaughtExceptionHandler uncaughtExceptionHandler = + Thread.currentThread().getUncaughtExceptionHandler(); + + assertThat(uncaughtExceptionHandler) + .isInstanceOf(DaemonThreadFactory.ManagedUncaughtExceptionHandler.class); + + Thread threadMock = mock(); + + // Verify interrupted exception + uncaughtExceptionHandler.uncaughtException(threadMock, new InterruptedException()); + verify(threadMock).interrupt(); + verifyNoInteractions(defaultHandler); + + // Verify delegate exception + clearInvocations(threadMock, defaultHandler); + IllegalStateException e = new IllegalStateException(); + uncaughtExceptionHandler.uncaughtException(threadMock, e); + verify(defaultHandler).uncaughtException(threadMock, e); + return true; + }; + + assertThat(service.submit(callable).get(5, TimeUnit.SECONDS)).isTrue(); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DefaultExceptionAttributeResolverTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DefaultExceptionAttributeResolverTest.java new file mode 100644 index 00000000000..266a3904225 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DefaultExceptionAttributeResolverTest.java @@ -0,0 +1,76 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Predicate; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class DefaultExceptionAttributeResolverTest { + + @ParameterizedTest + @MethodSource("setExceptionAttributesArgs") + void setExceptionAttributes( + boolean jvmStacktraceEnabled, + Throwable throwable, + int maxAttributeLength, + String expectedMessage, + String expectedType, + Predicate validStacktrace) { + ExceptionAttributeResolver resolver = + ExceptionAttributeResolver.getDefault(jvmStacktraceEnabled); + Map attributes = new HashMap<>(); + + resolver.setExceptionAttributes( + new ExceptionAttributeResolver.AttributeSetter() { + @Override + public void setAttribute(AttributeKey key, @Nullable T value) { + attributes.put(key.toString(), value); + } + }, + throwable, + maxAttributeLength); + + assertThat(attributes.get(ExceptionAttributeResolver.EXCEPTION_MESSAGE.getKey())) + .isEqualTo(expectedMessage); + assertThat(attributes.get(ExceptionAttributeResolver.EXCEPTION_TYPE.getKey())) + .isEqualTo(expectedType); + assertThat((String) attributes.get(ExceptionAttributeResolver.EXCEPTION_STACKTRACE.getKey())) + .matches(validStacktrace); + } + + private static Stream setExceptionAttributesArgs() { + return Stream.of( + Arguments.argumentSet( + "jvm stacktrace enabled limit ignored", + true, + new Exception("error"), + 10, + "error", + "java.lang.Exception", + predicate(stacktrace -> stacktrace.length() > 10)), + Arguments.argumentSet( + "jvm stacktrace disabled limit adhered", + false, + new Exception("error"), + 10, + "error", + "java.lang.Exception", + predicate(stacktrace -> stacktrace.length() == 10))); + } + + private static Predicate predicate(Predicate predicate) { + return predicate; + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DynamicPrimitiveLongListTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DynamicPrimitiveLongListTest.java new file mode 100644 index 00000000000..b2885c8d244 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/DynamicPrimitiveLongListTest.java @@ -0,0 +1,132 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class DynamicPrimitiveLongListTest { + + @Test + void subArrayCapacityMustBePositive() { + assertThatThrownBy( + () -> { + int subArrayCapacity = 0; + new DynamicPrimitiveLongList(subArrayCapacity); + }) + .isInstanceOf(IllegalArgumentException.class); + + assertThatThrownBy( + () -> { + int subArrayCapacity = -2; + new DynamicPrimitiveLongList(subArrayCapacity); + }) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void newListIsEmpty() { + DynamicPrimitiveLongList list = new DynamicPrimitiveLongList(); + assertThat(list).isEmpty(); + assertThatThrownBy(() -> list.getLong(0)).isInstanceOf(IndexOutOfBoundsException.class); + } + + @Test + void resizeListAndSetElement() { + DynamicPrimitiveLongList list = new DynamicPrimitiveLongList(); + list.resizeAndClear(5); + list.setLong(3, 10L); + + for (int i = 0; i < 5; i++) { + if (i == 3) { + assertThat(list.getLong(i)).isEqualTo(10L); + } else { + assertThat(list.getLong(i)).isEqualTo(0L); + } + } + } + + @Test + void resizeAndFillThenResizeSmallerAndCheck() { + DynamicPrimitiveLongList list = new DynamicPrimitiveLongList(); + list.resizeAndClear(6); + + for (int i = 0; i < 6; i++) { + list.setLong(i, i + 1); + } + + list.resizeAndClear(3); + + for (int i = 0; i < 3; i++) { + assertThat(list.getLong(i)).isEqualTo(0L); + } + + assertThatThrownBy(() -> list.getLong(4)).isInstanceOf(IndexOutOfBoundsException.class); + + for (int i = 0; i < 3; i++) { + list.setLong(i, i + 10); + assertThat(list.getLong(i)).isEqualTo(i + 10); + } + } + + @Test + void resizeToNegativeNumber() { + assertThatThrownBy(() -> DynamicPrimitiveLongList.of(0, 10, 20).resizeAndClear(-2)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void resizeAndFillThenResizeLargerAndCheck() { + DynamicPrimitiveLongList list = new DynamicPrimitiveLongList(); + list.resizeAndClear(6); + + for (int i = 0; i < 6; i++) { + list.setLong(i, i + 1); + } + + list.resizeAndClear(8); + + for (int i = 0; i < 8; i++) { + assertThat(list.getLong(i)).isEqualTo(0L); + } + + assertThatThrownBy(() -> list.getLong(8)).isInstanceOf(IndexOutOfBoundsException.class); + } + + @Test + void of() { + DynamicPrimitiveLongList list = DynamicPrimitiveLongList.of(1, 4, 5, 6); + assertThat(list.getLong(0)).isEqualTo(1); + assertThat(list.getLong(1)).isEqualTo(4); + assertThat(list.getLong(2)).isEqualTo(5); + assertThat(list.getLong(3)).isEqualTo(6); + + list = DynamicPrimitiveLongList.of(); + assertThat(list).isEmpty(); + } + + @Test + void empty() { + DynamicPrimitiveLongList list = DynamicPrimitiveLongList.empty(); + assertThat(list).isEmpty(); + + // I can still add elements + list.resizeAndClear(1); + list.set(0, 10L); + assertThat(list.getLong(0)).isEqualTo(10L); + } + + @Test + void set() { + DynamicPrimitiveLongList list = DynamicPrimitiveLongList.of(0, 10, 20); + assertThat(list.get(1)).isEqualTo(10L); + + list.set(1, 100L); + assertThat(list.get(1)).isEqualTo(100L); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/GlobUtilTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/GlobUtilTest.java new file mode 100644 index 00000000000..37f9dc1b81b --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/GlobUtilTest.java @@ -0,0 +1,91 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class GlobUtilTest { + + @ParameterizedTest + @MethodSource("globPatternPredicateArgs") + void matchesName(String globPattern, String testString, boolean isMatchExpected) { + assertThat(GlobUtil.createGlobPatternPredicate(globPattern).test(testString)) + .isEqualTo(isMatchExpected); + } + + private static Stream globPatternPredicateArgs() { + return Stream.of( + Arguments.argumentSet("empty matches empty", "", "", true), + Arguments.argumentSet("empty no match foo", "", "foo", false), + Arguments.argumentSet("foo no match null", "foo", null, false), + Arguments.argumentSet("question no match empty", "?", "", false), + Arguments.argumentSet("adjacent stars match empty", "**", "", true), + Arguments.argumentSet("adjacent stars match suffix", "**b", "aaab", true), + Arguments.argumentSet("adjacent stars no match suffix", "**b", "aaaa", false), + Arguments.argumentSet("separated stars match suffix", "*a*a*a*b", "aaaab", true), + Arguments.argumentSet("separated stars no match suffix", "*a*a*a*b", "aaaa", false), + Arguments.argumentSet("star matches newline", "*", "\n", true), + Arguments.argumentSet("adjacent stars no match newline", "**", "\n", false), + Arguments.argumentSet("question no match newline", "?", "\n", false), + Arguments.argumentSet("question no match carriage return", "?", "\r", false), + Arguments.argumentSet("question no match next line", "?", "\u0085", false), + Arguments.argumentSet("question no match line separator", "?", "\u2028", false), + Arguments.argumentSet("question no match paragraph separator", "?", "\u2029", false), + Arguments.argumentSet("literal newline matches", "*\n*", "a\nb", true), + Arguments.argumentSet("star cannot cross newline", "*b", "a\nb", false), + Arguments.argumentSet("question matches code point", "?", "πŸ˜€", true), + Arguments.argumentSet("two questions no match code point", "??", "πŸ˜€", false), + Arguments.argumentSet("literal code point matches", "*πŸ˜€?", "aπŸ˜€b", true), + Arguments.argumentSet("star matches code point", "a*b", "aπŸ˜€b", true), + Arguments.argumentSet( + "question matches unpaired surrogate", "?", Character.toString((char) 0xD83D), true), + Arguments.argumentSet("backslash literal with star", "*\\E", "a\\E", true), + Arguments.argumentSet("backslash does not escape question", "\\?", "\\a", true), + Arguments.argumentSet("suffix retry", "*ab", "aab", true), + Arguments.argumentSet("question suffix retry", "*a?b", "aacb", true), + Arguments.argumentSet("multiple stars retry", "*ab*cd", "aabcccd", true), + Arguments.argumentSet("suffix anchored", "*ab", "aba", false), + Arguments.argumentSet("prefix anchored", "ab*", "aab", false), + Arguments.argumentSet("foo matches foo", "foo", "foo", true), + Arguments.argumentSet("foo no match Foo", "foo", "Foo", false), + Arguments.argumentSet("foo no match bar", "foo", "bar", false), + Arguments.argumentSet("fo? matches foo", "fo?", "foo", true), + Arguments.argumentSet("fo?? matches fooo", "fo??", "fooo", true), + Arguments.argumentSet("fo? matches fob", "fo?", "fob", true), + Arguments.argumentSet("fo? no match fooo", "fo?", "fooo", false), + Arguments.argumentSet("* matches foo", "*", "foo", true), + Arguments.argumentSet("* matches bar", "*", "bar", true), + Arguments.argumentSet("* matches baz", "*", "baz", true), + Arguments.argumentSet("* matches foo.bar.baz", "*", "foo.bar.baz", true), + Arguments.argumentSet("* matches null", "*", null, true), + Arguments.argumentSet("* matches empty", "*", "", true), + Arguments.argumentSet("fo* matches fo", "fo*", "fo", true), + Arguments.argumentSet("fo* matches foo", "fo*", "foo", true), + Arguments.argumentSet("fo* matches foO", "fo*", "foO", true), + Arguments.argumentSet("fo* no match FOO", "fo*", "FOO", false), + Arguments.argumentSet("fo* matches fooo", "fo*", "fooo", true), + Arguments.argumentSet("fo* matches foo.bar.baz", "fo*", "foo.bar.baz", true), + Arguments.argumentSet("*bar matches sandbar", "*bar", "sandbar", true), + Arguments.argumentSet("fo*b* matches foobar", "fo*b*", "foobar", true), + Arguments.argumentSet("fo*b* matches foob", "fo*b*", "foob", true), + Arguments.argumentSet("fo*b* matches foo bar", "fo*b*", "foo bar", true), + Arguments.argumentSet("fo? b?? matches foo bar", "fo? b??", "foo bar", true), + Arguments.argumentSet("fo? b?? matches foO bAR", "fo? b??", "foO bAR", true), + Arguments.argumentSet("fo? b?? no match FOO BAR", "fo? b??", "FOO BAR", false), + Arguments.argumentSet("fo? b?? no match fooo bar", "fo? b??", "fooo bar", false), + Arguments.argumentSet("fo* ba? matches foo is not bar", "fo* ba?", "foo is not bar", true), + Arguments.argumentSet( + "fo? b* matches fox beetles for lunch", "fo? b*", "fox beetles for lunch", true), + Arguments.argumentSet("special chars literal", "f()[]$^.{}|", "f()[]$^.{}|", true), + Arguments.argumentSet("special chars with ?", "f()[]$^.{}|?", "f()[]$^.{}|o", true), + Arguments.argumentSet("special chars with *", "f()[]$^.{}|*", "f()[]$^.{}|ooo", true)); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java new file mode 100644 index 00000000000..0585845214c --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/IncludeExcludePredicateTest.java @@ -0,0 +1,190 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static java.util.Arrays.asList; +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Predicate; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class IncludeExcludePredicateTest { + + private static final Predicate EXACT_INCLUDE = + IncludeExcludePredicate.createExactMatching(singletonList("foo"), null); + private static final Predicate EXACT_EXCLUDE = + IncludeExcludePredicate.createExactMatching(null, singletonList("bar")); + private static final Predicate EXACT_INCLUDE_AND_EXCLUDE = + IncludeExcludePredicate.createExactMatching(singletonList("foo"), singletonList("bar")); + private static final Predicate EXACT_MULTI = + IncludeExcludePredicate.createExactMatching(asList("foo", "fooo"), asList("bar", "barr")); + + private static final Predicate PATTERN_INCLUDE = + IncludeExcludePredicate.createPatternMatching(singletonList("f?o"), null); + private static final Predicate PATTERN_EXCLUDE = + IncludeExcludePredicate.createPatternMatching(null, singletonList("b?r")); + private static final Predicate PATTERN_INCLUDE_AND_EXCLUDE = + IncludeExcludePredicate.createPatternMatching(singletonList("f?o"), singletonList("b?r")); + private static final Predicate PATTERN_MULTI = + IncludeExcludePredicate.createPatternMatching(asList("f?o", "f?oo"), asList("b?r", "b?rr")); + + @ParameterizedTest + @MethodSource("testArgs") + void test(Predicate predicate, String testCase, boolean expectedResult) { + assertThat(predicate.test(testCase)).isEqualTo(expectedResult); + } + + private static Stream testArgs() { + return Stream.of( + Arguments.argumentSet("exact include foo", EXACT_INCLUDE, "foo", true), + Arguments.argumentSet("exact include bar no match", EXACT_INCLUDE, "bar", false), + Arguments.argumentSet("exact include baz no match", EXACT_INCLUDE, "baz", false), + Arguments.argumentSet("exact include Foo no match", EXACT_INCLUDE, "Foo", false), + Arguments.argumentSet("exact include FOO no match", EXACT_INCLUDE, "FOO", false), + Arguments.argumentSet("exact exclude foo", EXACT_EXCLUDE, "foo", true), + Arguments.argumentSet("exact exclude bar no match", EXACT_EXCLUDE, "bar", false), + Arguments.argumentSet("exact exclude baz", EXACT_EXCLUDE, "baz", true), + Arguments.argumentSet("exact exclude Bar", EXACT_EXCLUDE, "Bar", true), + Arguments.argumentSet("exact exclude BAR", EXACT_EXCLUDE, "BAR", true), + Arguments.argumentSet("exact include+exclude foo", EXACT_INCLUDE_AND_EXCLUDE, "foo", true), + Arguments.argumentSet( + "exact include+exclude Foo no match", EXACT_INCLUDE_AND_EXCLUDE, "Foo", false), + Arguments.argumentSet( + "exact include+exclude FOO no match", EXACT_INCLUDE_AND_EXCLUDE, "FOO", false), + Arguments.argumentSet( + "exact include+exclude bar no match", EXACT_INCLUDE_AND_EXCLUDE, "bar", false), + Arguments.argumentSet( + "exact include+exclude baz no match", EXACT_INCLUDE_AND_EXCLUDE, "baz", false), + Arguments.argumentSet("exact multi foo", EXACT_MULTI, "foo", true), + Arguments.argumentSet("exact multi fooo", EXACT_MULTI, "fooo", true), + Arguments.argumentSet("exact multi Foo no match", EXACT_MULTI, "Foo", false), + Arguments.argumentSet("exact multi FOO no match", EXACT_MULTI, "FOO", false), + Arguments.argumentSet("exact multi bar no match", EXACT_MULTI, "bar", false), + Arguments.argumentSet("exact multi barr no match", EXACT_MULTI, "barr", false), + Arguments.argumentSet("exact multi baz no match", EXACT_MULTI, "baz", false), + Arguments.argumentSet("pattern include foo", PATTERN_INCLUDE, "foo", true), + Arguments.argumentSet("pattern include fOo", PATTERN_INCLUDE, "fOo", true), + Arguments.argumentSet("pattern include Foo no match", PATTERN_INCLUDE, "Foo", false), + Arguments.argumentSet("pattern include bar no match", PATTERN_INCLUDE, "bar", false), + Arguments.argumentSet("pattern include baz no match", PATTERN_INCLUDE, "baz", false), + Arguments.argumentSet("pattern exclude foo", PATTERN_EXCLUDE, "foo", true), + Arguments.argumentSet("pattern exclude bar no match", PATTERN_EXCLUDE, "bar", false), + Arguments.argumentSet("pattern exclude bAr no match", PATTERN_EXCLUDE, "bAr", false), + Arguments.argumentSet("pattern exclude Bar", PATTERN_EXCLUDE, "Bar", true), + Arguments.argumentSet("pattern exclude BAR", PATTERN_EXCLUDE, "BAR", true), + Arguments.argumentSet("pattern exclude baz", PATTERN_EXCLUDE, "baz", true), + Arguments.argumentSet( + "pattern include+exclude foo", PATTERN_INCLUDE_AND_EXCLUDE, "foo", true), + Arguments.argumentSet( + "pattern include+exclude fOo", PATTERN_INCLUDE_AND_EXCLUDE, "fOo", true), + Arguments.argumentSet( + "pattern include+exclude FOO no match", PATTERN_INCLUDE_AND_EXCLUDE, "FOO", false), + Arguments.argumentSet( + "pattern include+exclude bar no match", PATTERN_INCLUDE_AND_EXCLUDE, "bar", false), + Arguments.argumentSet( + "pattern include+exclude baz no match", PATTERN_INCLUDE_AND_EXCLUDE, "baz", false), + Arguments.argumentSet("pattern multi foo", PATTERN_MULTI, "foo", true), + Arguments.argumentSet("pattern multi fooo", PATTERN_MULTI, "fooo", true), + Arguments.argumentSet("pattern multi fOo", PATTERN_MULTI, "fOo", true), + Arguments.argumentSet("pattern multi FOO no match", PATTERN_MULTI, "FOO", false), + Arguments.argumentSet("pattern multi bar no match", PATTERN_MULTI, "bar", false), + Arguments.argumentSet("pattern multi bAr no match", PATTERN_MULTI, "bAr", false), + Arguments.argumentSet("pattern multi barr no match", PATTERN_MULTI, "barr", false), + Arguments.argumentSet("pattern multi bArr no match", PATTERN_MULTI, "bArr", false), + Arguments.argumentSet("pattern multi baz no match", PATTERN_MULTI, "baz", false)); + } + + @ParameterizedTest + @MethodSource("stringRepresentationArgs") + void stringRepresentation(Predicate predicate, String exepectedString) { + assertThat(predicate.toString()).isEqualTo(exepectedString); + } + + private static Stream stringRepresentationArgs() { + return Stream.of( + Arguments.argumentSet( + "exact include", + EXACT_INCLUDE, + "IncludeExcludePredicate{globMatchingEnabled=false, included=[foo]}"), + Arguments.argumentSet( + "exact exclude", + EXACT_EXCLUDE, + "IncludeExcludePredicate{globMatchingEnabled=false, excluded=[bar]}"), + Arguments.argumentSet( + "exact include and exclude", + EXACT_INCLUDE_AND_EXCLUDE, + "IncludeExcludePredicate{globMatchingEnabled=false, included=[foo], excluded=[bar]}"), + Arguments.argumentSet( + "exact multi", + EXACT_MULTI, + "IncludeExcludePredicate{globMatchingEnabled=false, included=[foo, fooo], excluded=[bar, barr]}"), + Arguments.argumentSet( + "pattern include", + PATTERN_INCLUDE, + "IncludeExcludePredicate{globMatchingEnabled=true, included=[f?o]}"), + Arguments.argumentSet( + "pattern exclude", + PATTERN_EXCLUDE, + "IncludeExcludePredicate{globMatchingEnabled=true, excluded=[b?r]}"), + Arguments.argumentSet( + "pattern include and exclude", + PATTERN_INCLUDE_AND_EXCLUDE, + "IncludeExcludePredicate{globMatchingEnabled=true, included=[f?o], excluded=[b?r]}"), + Arguments.argumentSet( + "pattern multi", + PATTERN_MULTI, + "IncludeExcludePredicate{globMatchingEnabled=true, included=[f?o, f?oo], excluded=[b?r, b?rr]}")); + } + + @Test + void emptyOrNullShouldIncludeAll() { + shouldIncludeAll(null, null); + shouldIncludeAll(Collections.emptyList(), null); + shouldIncludeAll(null, Collections.emptyList()); + shouldIncludeAll(Collections.emptyList(), Collections.emptyList()); + } + + private static void shouldIncludeAll( + @Nullable Collection included, @Nullable Collection excluded) { + Arrays.asList("foo", "fooo", "fOo", "FOO", "bar", "bAr", "barr", "bArr", "baz") + .forEach(s -> { + Predicate exactMatching = + IncludeExcludePredicate.createExactMatching(included, excluded); + assertThat(exactMatching.test(s)).isTrue(); + assertThat(exactMatching.toString()) + .isEqualTo("IncludeExcludePredicate{globMatchingEnabled=false}"); + Predicate patternMatching = + IncludeExcludePredicate.createPatternMatching(included, excluded); + assertThat(patternMatching.test(s)).isTrue(); + assertThat(patternMatching.toString()) + .isEqualTo("IncludeExcludePredicate{globMatchingEnabled=true}"); + }); + } + + @Test + void shouldExcludeWhenValueMatchesBothIncludeAndExclude() { + String value = "a"; + Collection exactMatchingArg = Collections.singletonList("a"); + + Predicate exactMatching = + IncludeExcludePredicate.createExactMatching(exactMatchingArg, exactMatchingArg); + assertThat(exactMatching.test(value)).isFalse(); + + Collection patternMatchingArg = Collections.singletonList("*"); + Predicate patternMatching = + IncludeExcludePredicate.createPatternMatching(patternMatchingArg, patternMatchingArg); + assertThat(patternMatching.test(value)).isFalse(); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/InstrumentationScopeUtilTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/InstrumentationScopeUtilTest.java new file mode 100644 index 00000000000..0d8d3ba93a7 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/InstrumentationScopeUtilTest.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import org.junit.jupiter.api.Test; + +@SuppressWarnings("deprecation") // Testing deprecated code +class InstrumentationScopeUtilTest { + + @Test + void toInstrumentationLibraryInfo() { + assertThat( + InstrumentationScopeUtil.toInstrumentationLibraryInfo( + InstrumentationScopeInfo.builder("name").build())) + .isEqualTo(InstrumentationLibraryInfo.create("name", null, null)); + assertThat( + InstrumentationScopeUtil.toInstrumentationLibraryInfo( + InstrumentationScopeInfo.builder("name") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .setAttributes(Attributes.builder().put("key", "value").build()) + .build())) + .isEqualTo(InstrumentationLibraryInfo.create("name", "version", "schemaUrl")); + } + + @Test + void toInstrumentationScopeInfo() { + assertThat( + InstrumentationScopeUtil.toInstrumentationScopeInfo( + InstrumentationLibraryInfo.create("name", null, null))) + .isEqualTo(InstrumentationScopeInfo.builder("name").build()); + assertThat( + InstrumentationScopeUtil.toInstrumentationScopeInfo( + InstrumentationLibraryInfo.create("name", "version", "schemaUrl"))) + .isEqualTo( + InstrumentationScopeInfo.builder("name") + .setVersion("version") + .setSchemaUrl("schemaUrl") + .build()); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/PrimitiveLongListTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/PrimitiveLongListTest.java similarity index 96% rename from sdk/common/src/test/java/io/opentelemetry/sdk/internal/PrimitiveLongListTest.java rename to sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/PrimitiveLongListTest.java index 726fedae249..dd48d033d84 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/PrimitiveLongListTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/PrimitiveLongListTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/RateLimiterTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java similarity index 95% rename from sdk/common/src/test/java/io/opentelemetry/sdk/internal/RateLimiterTest.java rename to sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java index c659c790581..ba0bcee3e37 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/RateLimiterTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/RateLimiterTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; import static org.assertj.core.api.Assertions.assertThat; @@ -161,14 +161,13 @@ void testRateLimiterConcurrency() throws InterruptedException, ExecutionExceptio List> futures = new ArrayList<>(numWorkers); for (int w = 0; w < numWorkers; ++w) { Future future = - executorService.submit( - () -> { - for (int i = 0; i < creditsPerWorker * 2; ++i) { - if (limiter.trySpend(1)) { - count.getAndIncrement(); // count allowed operations - } - } - }); + executorService.submit(() -> { + for (int i = 0; i < creditsPerWorker * 2; ++i) { + if (limiter.trySpend(1)) { + count.getAndIncrement(); // count allowed operations + } + } + }); futures.add(future); } for (Future future : futures) { diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/SemConvConstantsTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/SemConvConstantsTest.java new file mode 100644 index 00000000000..2fea1ee240c --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/SemConvConstantsTest.java @@ -0,0 +1,190 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.semconv.ErrorAttributes; +import io.opentelemetry.semconv.HttpAttributes; +import io.opentelemetry.semconv.RpcAttributes; +import io.opentelemetry.semconv.SchemaUrls; +import io.opentelemetry.semconv.ServerAttributes; +import io.opentelemetry.semconv.ServiceAttributes; +import io.opentelemetry.semconv.incubating.OtelIncubatingAttributes; +import io.opentelemetry.semconv.incubating.OtelIncubatingMetrics; +import org.junit.jupiter.api.Test; + +class SemConvConstantsTest { + + @Test + void attributeKeys() { + assertThat(SemConvConstants.SCHEMA_URL_V1_40_0).isEqualTo(SchemaUrls.V1_40_0); + + // TODO(jack-berg): assert against generated constants once we start generating for entities + // types + assertThat(SemConvConstants.SERVICE_TYPE).isEqualTo("service"); + assertThat(SemConvConstants.SERVICE_INSTANCE_TYPE).isEqualTo("service.instance"); + + assertThat(SemConvConstants.SERVICE_NAME).isEqualTo(ServiceAttributes.SERVICE_NAME); + assertThat(SemConvConstants.SERVICE_INSTANCE_ID) + .isEqualTo(ServiceAttributes.SERVICE_INSTANCE_ID); + + assertThat(SemConvConstants.OTEL_COMPONENT_NAME) + .isEqualTo(OtelIncubatingAttributes.OTEL_COMPONENT_NAME); + assertThat(SemConvConstants.OTEL_COMPONENT_TYPE) + .isEqualTo(OtelIncubatingAttributes.OTEL_COMPONENT_TYPE); + + assertThat(SemConvConstants.ERROR_TYPE).isEqualTo(ErrorAttributes.ERROR_TYPE); + + assertThat(SemConvConstants.SERVER_ADDRESS).isEqualTo(ServerAttributes.SERVER_ADDRESS); + assertThat(SemConvConstants.SERVER_PORT).isEqualTo(ServerAttributes.SERVER_PORT); + assertThat(SemConvConstants.RPC_STATUS_CODE).isEqualTo(RpcAttributes.RPC_STATUS_CODE); + assertThat(SemConvConstants.HTTP_RESPONSE_STATUS_CODE) + .isEqualTo(HttpAttributes.HTTP_RESPONSE_STATUS_CODE); + + assertThat(SemConvConstants.OTEL_SPAN_PARENT_ORIGIN) + .isEqualTo(OtelIncubatingAttributes.OTEL_SPAN_PARENT_ORIGIN); + assertThat(SemConvConstants.OTEL_SPAN_SAMPLING_RESULT) + .isEqualTo(OtelIncubatingAttributes.OTEL_SPAN_SAMPLING_RESULT); + } + + @Test + void spanMetrics() { + assertThat(SemConvConstants.OTEL_SDK_SPAN_STARTED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_SPAN_STARTED_NAME); + assertThat(SemConvConstants.OTEL_SDK_SPAN_STARTED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_SPAN_STARTED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_SPAN_STARTED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_SPAN_STARTED_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_SPAN_LIVE_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_SPAN_LIVE_NAME); + assertThat(SemConvConstants.OTEL_SDK_SPAN_LIVE_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_SPAN_LIVE_UNIT); + assertThat(SemConvConstants.OTEL_SDK_SPAN_LIVE_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_SPAN_LIVE_DESCRIPTION); + } + + @Test + void spanProcessorMetrics() { + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_NAME); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_NAME); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_UNIT); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_NAME); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_UNIT); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_DESCRIPTION); + } + + @Test + void logMetrics() { + assertThat(SemConvConstants.OTEL_SDK_LOG_CREATED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_LOG_CREATED_NAME); + assertThat(SemConvConstants.OTEL_SDK_LOG_CREATED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_LOG_CREATED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_LOG_CREATED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_LOG_CREATED_DESCRIPTION); + } + + @Test + void logProcessorMetrics() { + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_PROCESSED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_PROCESSED_NAME); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_PROCESSED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_PROCESSED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_PROCESSED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_PROCESSED_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_NAME); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_UNIT); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_NAME); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_UNIT); + assertThat(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_DESCRIPTION); + } + + @Test + void metricReaderMetrics() { + assertThat(SemConvConstants.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_NAME); + assertThat(SemConvConstants.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_UNIT); + assertThat(SemConvConstants.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_DESCRIPTION); + } + + @Test + void exporterMetrics() { + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_OPERATION_DURATION_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_OPERATION_DURATION_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_OPERATION_DURATION_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_OPERATION_DURATION_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_OPERATION_DURATION_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_OPERATION_DURATION_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_SPAN_INFLIGHT_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_SPAN_EXPORTED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_SPAN_EXPORTED_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_SPAN_EXPORTED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_SPAN_EXPORTED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_SPAN_EXPORTED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_SPAN_EXPORTED_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_LOG_INFLIGHT_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_LOG_INFLIGHT_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_LOG_INFLIGHT_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_LOG_INFLIGHT_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_LOG_INFLIGHT_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_LOG_INFLIGHT_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_LOG_EXPORTED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_LOG_EXPORTED_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_LOG_EXPORTED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_LOG_EXPORTED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_LOG_EXPORTED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_LOG_EXPORTED_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_INFLIGHT_DESCRIPTION); + + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_NAME) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_NAME); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_UNIT) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_UNIT); + assertThat(SemConvConstants.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_DESCRIPTION) + .isEqualTo(OtelIncubatingMetrics.OTEL_SDK_EXPORTER_METRIC_DATA_POINT_EXPORTED_DESCRIPTION); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/StackTraceRendererTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/StackTraceRendererTest.java new file mode 100644 index 00000000000..108f70dff29 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/StackTraceRendererTest.java @@ -0,0 +1,97 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.Random; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class StackTraceRendererTest { + + private static final Random random = new Random(); + + @ParameterizedTest + @MethodSource("renderStacktraceArgs") + void renderStacktrace_randomLength(Throwable throwable) { + // Test equal stacktrace for random lengths to test edges + for (int i = 0; i < 100; i++) { + int length = random.nextInt(10_000); + assertThat(new StackTraceRenderer(throwable, length).render()) + .isEqualTo(jdkStackTrace(throwable, length)); + } + } + + @ParameterizedTest + @MethodSource("renderStacktraceArgs") + void renderStacktrace_fixedLengths(Throwable throwable) { + assertThat(new StackTraceRenderer(throwable, 10).render()) + .isEqualTo(jdkStackTrace(throwable, 10)); + assertThat(new StackTraceRenderer(throwable, 100).render()) + .isEqualTo(jdkStackTrace(throwable, 100)); + assertThat(new StackTraceRenderer(throwable, 1000).render()) + .isEqualTo(jdkStackTrace(throwable, 1000)); + assertThat(new StackTraceRenderer(throwable, Integer.MAX_VALUE).render()) + .isEqualTo(jdkStackTrace(throwable, Integer.MAX_VALUE)); + } + + private static Stream renderStacktraceArgs() { + Exception withCycle = new Exception("error1"); + Exception withCycleInner = new Exception("error2", withCycle); + withCycle.initCause(withCycleInner); + + Exception withSuppressed = new Exception("error"); + withSuppressed.addSuppressed(new Exception("suppressed")); + + Exception withMultipleSuppressed = new Exception("error"); + withMultipleSuppressed.addSuppressed(new Exception("suppressed1")); + withMultipleSuppressed.addSuppressed(new Exception("suppressed2")); + + Exception withNestedSuppressed = new Exception("error"); + withNestedSuppressed.addSuppressed(withSuppressed); + withNestedSuppressed.addSuppressed(withMultipleSuppressed); + + Exception withKitchenSink = new Exception("kitchenSink", withCycle); + withKitchenSink.addSuppressed(withMultipleSuppressed); + withKitchenSink.addSuppressed(withNestedSuppressed); + + return Stream.of( + Arguments.argumentSet("no message", new Exception()), + Arguments.argumentSet("with message", new Exception("error")), + Arguments.argumentSet("cause only", new Exception(new Exception("cause"))), + Arguments.argumentSet("message and cause", new Exception("error", new Exception("cause"))), + Arguments.argumentSet( + "nested causes", + new Exception( + "error", + new Exception( + "cause1", + new Exception( + "cause2", + new Exception( + "cause3", new Exception("cause4", new Exception("cause5"))))))), + Arguments.argumentSet("circular reference", withCycle), + Arguments.argumentSet("with suppressed", withSuppressed), + Arguments.argumentSet("with multiple suppressed", withMultipleSuppressed), + Arguments.argumentSet("with nested suppressed", withNestedSuppressed), + // with cause, cycle, and suppressed! + Arguments.argumentSet("kitchen sink", withKitchenSink)); + } + + private static String jdkStackTrace(Throwable exception, int limit) { + StringWriter stringWriter = new StringWriter(); + try (PrintWriter printWriter = new PrintWriter(stringWriter)) { + exception.printStackTrace(printWriter); + } + String stacktrace = stringWriter.toString(); + return stacktrace.substring(0, Math.min(stacktrace.length(), limit)); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ThrottlingLoggerTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ThrottlingLoggerTest.java new file mode 100644 index 00000000000..b93692f6832 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ThrottlingLoggerTest.java @@ -0,0 +1,297 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.common.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.slf4j.event.Level.ERROR; +import static org.slf4j.event.Level.INFO; +import static org.slf4j.event.Level.WARN; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.testing.time.TestClock; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +@SuppressLogger(ThrottlingLoggerTest.class) +class ThrottlingLoggerTest { + + private static final Logger realLogger = Logger.getLogger(ThrottlingLoggerTest.class.getName()); + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(ThrottlingLoggerTest.class); + + @Test + void delegation() { + ThrottlingLogger logger = new ThrottlingLogger(realLogger); + + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.INFO, "oh yes!"); + RuntimeException throwable = new RuntimeException(); + logger.log(Level.SEVERE, "secrets", throwable); + + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(WARN), "oh no!"); + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(INFO), "oh yes!"); + assertThat( + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(ERROR), "secrets") + .getThrowable()) + .isSameAs(throwable); + } + + @Test + void delegationCustom() { + ThrottlingLogger logger = new ThrottlingLogger(realLogger, 10, 2, TimeUnit.HOURS); + + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.INFO, "oh yes!"); + RuntimeException throwable = new RuntimeException(); + logger.log(Level.SEVERE, "secrets", throwable); + + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(WARN), "oh no!"); + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(INFO), "oh yes!"); + assertThat( + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(ERROR), "secrets") + .getThrowable()) + .isSameAs(throwable); + } + + @Test + void logsBelowLevelDontCount() { + ThrottlingLogger logger = + new ThrottlingLogger(Logger.getLogger(ThrottlingLoggerTest.class.getName())); + + for (int i = 0; i < 100; i++) { + // FINE is below the default level and thus shouldn't impact the rate. + logger.log(Level.FINE, "secrets", new RuntimeException()); + } + logger.log(Level.INFO, "oh yes!"); + + logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(INFO), "oh yes!"); + } + + @Test + void fiveInAMinuteTriggersLimiting() { + Clock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); + + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + + logger.log(Level.WARNING, "oh no I should trigger suppression!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + + assertThat(logs.getEvents()).hasSize(7); + logs.assertDoesNotContain("oh no I should be suppressed!"); + logs.assertContains( + "Too many log messages detected. Will only log 1 time(s) per minute from now on."); + logs.assertContains("oh no I should trigger suppression!"); + } + + @Test + void tenInAnHourTriggersLimiting() { + Clock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock, 10, 2, TimeUnit.HOURS); + + for (int i = 0; i < 10; i++) { + logger.log(Level.WARNING, "oh no!"); + } + + logger.log(Level.WARNING, "oh no I should trigger suppression!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + + assertThat(logs.getEvents()).hasSize(12); + logs.assertDoesNotContain("oh no I should be suppressed!"); + logs.assertContains( + "Too many log messages detected. Will only log 2 time(s) per hour from now on."); + logs.assertContains("oh no I should trigger suppression!"); + } + + @Test + void allowsTrickleOfMessages() { + TestClock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); + logger.log(Level.WARNING, "oh no!"); + assertThat(logs.size()).isEqualTo(1); + logger.log(Level.WARNING, "oh no!"); + assertThat(logs.size()).isEqualTo(2); + clock.advance(Duration.ofMillis(30_001)); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + assertThat(logs.size()).isEqualTo(4); + + clock.advance(Duration.ofMillis(30_001)); + logger.log(Level.WARNING, "oh no 2nd minute!"); + logger.log(Level.WARNING, "oh no 2nd minute!"); + assertThat(logs.size()).isEqualTo(6); + clock.advance(Duration.ofMillis(30_001)); + logger.log(Level.WARNING, "oh no 2nd minute!"); + logger.log(Level.WARNING, "oh no 2nd minute!"); + assertThat(logs.size()).isEqualTo(8); + + clock.advance(Duration.ofMillis(30_001)); + logger.log(Level.WARNING, "oh no 3rd minute!"); + logger.log(Level.WARNING, "oh no 3rd minute!"); + assertThat(logs.size()).isEqualTo(10); + clock.advance(Duration.ofMillis(30_001)); + logger.log(Level.WARNING, "oh no 3rd minute!"); + logger.log(Level.WARNING, "oh no 3rd minute!"); + assertThat(logs.size()).isEqualTo(12); + } + + @Test + void afterAMinuteLetOneThrough() { + TestClock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); + + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + + logger.log(Level.WARNING, "oh no I should trigger suppression!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + + assertThat(logs.getEvents()).hasSize(7); + logs.assertDoesNotContain("oh no I should be suppressed!"); + logs.assertContains("oh no I should trigger suppression!"); + logs.assertContains( + "Too many log messages detected. Will only log 1 time(s) per minute from now on."); + + clock.advance(Duration.ofMillis(60_001)); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + assertThat(logs.getEvents()).hasSize(8); + assertThat(logs.getEvents().get(7).getMessage()).isEqualTo("oh no!"); + + clock.advance(Duration.ofMillis(60_001)); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + assertThat(logs.getEvents()).hasSize(9); + assertThat(logs.getEvents().get(8).getMessage()).isEqualTo("oh no!"); + } + + @Test + void afterAnHourLetTwoThrough() { + TestClock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock, 10, 2, TimeUnit.HOURS); + + for (int i = 0; i < 10; i++) { + logger.log(Level.WARNING, "oh no!"); + } + + logger.log(Level.WARNING, "oh no I should trigger suppression!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + + assertThat(logs.getEvents()).hasSize(12); + logs.assertDoesNotContain("oh no I should be suppressed!"); + logs.assertContains("oh no I should trigger suppression!"); + logs.assertContains( + "Too many log messages detected. Will only log 2 time(s) per hour from now on."); + + clock.advance(Duration.ofMinutes(61)); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + assertThat(logs.getEvents()).hasSize(14); + assertThat(logs.getEvents().get(13).getMessage()).isEqualTo("oh no!"); + + clock.advance(Duration.ofMinutes(61)); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + assertThat(logs.getEvents()).hasSize(16); + assertThat(logs.getEvents().get(15).getMessage()).isEqualTo("oh no!"); + + logs.assertDoesNotContain("oh no I should be suppressed!"); + } + + @Test + void allowOnlyOneLogPerMinuteAfterSuppression() { + TestClock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); + + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + logger.log(Level.WARNING, "oh no!"); + + logger.log(Level.WARNING, "oh no I should trigger suppression!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + + assertThat(logs.getEvents()).hasSize(7); + + clock.advance(Duration.ofMillis(12_001)); + logger.log(Level.WARNING, "suppression 1"); + clock.advance(Duration.ofMillis(12_001)); + logger.log(Level.WARNING, "suppression 2"); + clock.advance(Duration.ofMillis(12_001)); + logger.log(Level.WARNING, "suppression 3"); + clock.advance(Duration.ofMillis(12_001)); + logger.log(Level.WARNING, "suppression 4"); + clock.advance(Duration.ofMillis(12_001)); + logger.log(Level.WARNING, "allowed 1"); + + logs.assertDoesNotContain("suppression 1"); + logs.assertDoesNotContain("suppression 2"); + logs.assertDoesNotContain("suppression 3"); + logs.assertDoesNotContain("suppression 4"); + logs.assertContains("allowed 1"); + + assertThat(logs.getEvents()).hasSize(8); + assertThat(logs.getEvents().get(7).getMessage()).isEqualTo("allowed 1"); + } + + @Test + void allowOnlyTwoLogPerHourAfterSuppression() { + TestClock clock = TestClock.create(); + ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock, 10, 2, TimeUnit.HOURS); + + for (int i = 0; i < 10; i++) { + logger.log(Level.WARNING, "oh no!"); + } + + logger.log(Level.WARNING, "oh no I should trigger suppression!"); + logger.log(Level.WARNING, "oh no I should be suppressed!"); + + assertThat(logs.getEvents()).hasSize(12); + + clock.advance(Duration.ofMinutes(10)); + logger.log(Level.WARNING, "suppression 1"); + clock.advance(Duration.ofMinutes(10)); + logger.log(Level.WARNING, "suppression 2"); + clock.advance(Duration.ofMinutes(10)); + clock.advance(Duration.ofSeconds(1)); + logger.log(Level.WARNING, "allowed 1"); + clock.advance(Duration.ofMinutes(10)); + logger.log(Level.WARNING, "suppression 3"); + clock.advance(Duration.ofMinutes(10)); + logger.log(Level.WARNING, "suppression 4"); + clock.advance(Duration.ofMinutes(10)); + clock.advance(Duration.ofSeconds(1)); + logger.log(Level.WARNING, "allowed 2"); + + logs.assertDoesNotContain("suppression 1"); + logs.assertDoesNotContain("suppression 2"); + logs.assertDoesNotContain("suppression 3"); + logs.assertDoesNotContain("suppression 4"); + logs.assertContains("allowed 1"); + logs.assertContains("allowed 2"); + + assertThat(logs.getEvents()).hasSize(14); + assertThat(logs.getEvents().get(12).getMessage()).isEqualTo("allowed 1"); + assertThat(logs.getEvents().get(13).getMessage()).isEqualTo("allowed 2"); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ThrowableUtilTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ThrowableUtilTest.java similarity index 87% rename from sdk/common/src/test/java/io/opentelemetry/sdk/internal/ThrowableUtilTest.java rename to sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ThrowableUtilTest.java index 9da1aaa8e68..17154fe30ea 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ThrowableUtilTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/common/internal/ThrowableUtilTest.java @@ -3,9 +3,9 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.internal; +package io.opentelemetry.sdk.common.internal; -import static io.opentelemetry.sdk.internal.ThrowableUtil.propagateIfFatal; +import static io.opentelemetry.sdk.common.internal.ThrowableUtil.propagateIfFatal; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ComponentRegistryTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ComponentRegistryTest.java deleted file mode 100644 index df2a7181912..00000000000 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ComponentRegistryTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import org.junit.jupiter.api.Test; - -class ComponentRegistryTest { - - private static final String INSTRUMENTATION_NAME = "test_name"; - private static final String INSTRUMENTATION_VERSION = "version"; - private final ComponentRegistry registry = - new ComponentRegistry<>(TestComponent::new); - - @Test - void scopeName_MustNotBeNull() { - assertThatThrownBy(() -> registry.get(null, "version")) - .isInstanceOf(NullPointerException.class) - .hasMessage("name"); - } - - @Test - void scopeVersion_AllowsNull() { - TestComponent testComponent = registry.get(INSTRUMENTATION_NAME, null); - assertThat(testComponent).isNotNull(); - assertThat(testComponent.instrumentationScopeInfo.getName()).isEqualTo(INSTRUMENTATION_NAME); - assertThat(testComponent.instrumentationScopeInfo.getVersion()).isNull(); - } - - @Test - void getSameInstanceForSameName_WithoutVersion() { - assertThat(registry.get(INSTRUMENTATION_NAME)).isSameAs(registry.get(INSTRUMENTATION_NAME)); - assertThat(registry.get(INSTRUMENTATION_NAME)) - .isSameAs(registry.get(INSTRUMENTATION_NAME, null)); - } - - @Test - void getSameInstanceForSameName_WithVersion() { - assertThat(registry.get(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION)) - .isSameAs(registry.get(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION)); - } - - @Test - void getDifferentInstancesForDifferentNames() { - assertThat(registry.get(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION)) - .isNotSameAs(registry.get(INSTRUMENTATION_NAME + "_2", INSTRUMENTATION_VERSION)); - } - - @Test - void getDifferentInstancesForDifferentVersions() { - assertThat(registry.get(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION)) - .isNotSameAs(registry.get(INSTRUMENTATION_NAME, INSTRUMENTATION_VERSION + "_1")); - } - - private static final class TestComponent { - private final InstrumentationScopeInfo instrumentationScopeInfo; - - private TestComponent(InstrumentationScopeInfo instrumentationScopeInfo) { - this.instrumentationScopeInfo = instrumentationScopeInfo; - } - } -} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ThrottlingLoggerTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ThrottlingLoggerTest.java deleted file mode 100644 index 1c35b23ba0f..00000000000 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/internal/ThrottlingLoggerTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.internal; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.slf4j.event.Level.ERROR; -import static org.slf4j.event.Level.INFO; -import static org.slf4j.event.Level.WARN; - -import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.testing.time.TestClock; -import java.time.Duration; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.RegisterExtension; - -@SuppressLogger(ThrottlingLoggerTest.class) -class ThrottlingLoggerTest { - - private static final Logger realLogger = Logger.getLogger(ThrottlingLoggerTest.class.getName()); - - @RegisterExtension - LogCapturer logs = LogCapturer.create().captureForType(ThrottlingLoggerTest.class); - - @Test - void delegation() { - ThrottlingLogger logger = new ThrottlingLogger(realLogger); - - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.INFO, "oh yes!"); - RuntimeException throwable = new RuntimeException(); - logger.log(Level.SEVERE, "secrets", throwable); - - logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(WARN), "oh no!"); - logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(INFO), "oh yes!"); - assertThat( - logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(ERROR), "secrets") - .getThrowable()) - .isSameAs(throwable); - } - - @Test - void logsBelowLevelDontCount() { - ThrottlingLogger logger = - new ThrottlingLogger(Logger.getLogger(ThrottlingLoggerTest.class.getName())); - - for (int i = 0; i < 100; i++) { - // FINE is below the default level and thus shouldn't impact the rate. - logger.log(Level.FINE, "secrets", new RuntimeException()); - } - logger.log(Level.INFO, "oh yes!"); - - logs.assertContains(loggingEvent -> loggingEvent.getLevel().equals(INFO), "oh yes!"); - } - - @Test - void fiveInAMinuteTriggersLimiting() { - Clock clock = TestClock.create(); - ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); - - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - - logger.log(Level.WARNING, "oh no I should trigger suppression!"); - logger.log(Level.WARNING, "oh no I should be suppressed!"); - - assertThat(logs.getEvents()).hasSize(7); - logs.assertDoesNotContain("oh no I should be suppressed!"); - logs.assertContains( - "Too many log messages detected. Will only log once per minute from now on."); - logs.assertContains("oh no I should trigger suppression!"); - } - - @Test - void allowsTrickleOfMessages() { - TestClock clock = TestClock.create(); - ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); - logger.log(Level.WARNING, "oh no!"); - assertThat(logs.size()).isEqualTo(1); - logger.log(Level.WARNING, "oh no!"); - assertThat(logs.size()).isEqualTo(2); - clock.advance(Duration.ofMillis(30_001)); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - assertThat(logs.size()).isEqualTo(4); - - clock.advance(Duration.ofMillis(30_001)); - logger.log(Level.WARNING, "oh no 2nd minute!"); - logger.log(Level.WARNING, "oh no 2nd minute!"); - assertThat(logs.size()).isEqualTo(6); - clock.advance(Duration.ofMillis(30_001)); - logger.log(Level.WARNING, "oh no 2nd minute!"); - logger.log(Level.WARNING, "oh no 2nd minute!"); - assertThat(logs.size()).isEqualTo(8); - - clock.advance(Duration.ofMillis(30_001)); - logger.log(Level.WARNING, "oh no 3rd minute!"); - logger.log(Level.WARNING, "oh no 3rd minute!"); - assertThat(logs.size()).isEqualTo(10); - clock.advance(Duration.ofMillis(30_001)); - logger.log(Level.WARNING, "oh no 3rd minute!"); - logger.log(Level.WARNING, "oh no 3rd minute!"); - assertThat(logs.size()).isEqualTo(12); - } - - @Test - void afterAMinuteLetOneThrough() { - TestClock clock = TestClock.create(); - ThrottlingLogger logger = new ThrottlingLogger(realLogger, clock); - - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no!"); - - logger.log(Level.WARNING, "oh no I should trigger suppression!"); - logger.log(Level.WARNING, "oh no I should be suppressed!"); - - assertThat(logs.getEvents()).hasSize(7); - logs.assertDoesNotContain("oh no I should be suppressed!"); - logs.assertContains("oh no I should trigger suppression!"); - logs.assertContains( - "Too many log messages detected. Will only log once per minute from now on."); - - clock.advance(Duration.ofMillis(60_001)); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no I should be suppressed!"); - assertThat(logs.getEvents()).hasSize(8); - assertThat(logs.getEvents().get(7).getMessage()).isEqualTo("oh no!"); - - clock.advance(Duration.ofMillis(60_001)); - logger.log(Level.WARNING, "oh no!"); - logger.log(Level.WARNING, "oh no I should be suppressed!"); - assertThat(logs.getEvents()).hasSize(9); - assertThat(logs.getEvents().get(8).getMessage()).isEqualTo("oh no!"); - } -} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java index 243e72db940..6bb519ed929 100644 --- a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/ResourceTest.java @@ -13,22 +13,43 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.slf4j.event.Level.WARN; import com.google.common.testing.EqualsTester; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.AttributeType; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.resources.internal.Entity; +import io.opentelemetry.sdk.resources.internal.EntityUtil; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; /** Unit tests for {@link Resource}. */ +@SuppressLogger(Resource.class) +@SuppressLogger(ResourceBuilder.class) class ResourceTest { + @RegisterExtension + LogCapturer logs = + LogCapturer.create().captureForType(ResourceBuilder.class).captureForType(Resource.class); + private Resource resource1; private Resource resource2; @@ -54,6 +75,94 @@ void create() { assertThat(resource1.getAttributes().isEmpty()).isTrue(); } + @ParameterizedTest + @MethodSource("entityInsertionOperations") + void entityInsertionDefersPendingAttributeValidation(Consumer insert) { + ResourceBuilder builder = Resource.builder().put("invalid-Γ©", "pending"); + insert.accept(builder); + + assertThatThrownBy(builder::build).isInstanceOf(IllegalArgumentException.class); + Resource filtered = builder.removeIf(key -> key.getKey().equals("invalid-Γ©")).build(); + assertThat(filtered.getEntities()).hasSize(1); + assertThat(filtered.getAttributes()).isEqualTo(Attributes.of(stringKey("host.id"), "H1")); + } + + static Stream entityInsertionOperations() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + return Stream.of( + Arguments.argumentSet( + "direct insertion", (Consumer) builder -> builder.addEntity(host)), + Arguments.argumentSet( + "resource copy", + (Consumer) + builder -> builder.putAll(EntityUtil.createResource(singletonList(host))))); + } + + @Test + void jointCreationAppliesAttributesBeforeEntities() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build(); + Attributes attributes = + Attributes.builder() + .put("host.id", 2L) + .put("host.name", "earlier") + .put("env", "prod") + .build(); + Resource resource = Resource.builder().putAll(attributes).addEntity(host).build(); + + assertThat(resource.getEntities()).containsExactly(host); + assertThat(resource.getAttributes()) + .isEqualTo( + Attributes.builder() + .put("host.id", "H1") + .put("host.name", "machine") + .put("env", "prod") + .build()); + assertThat(resource) + .isEqualTo( + Resource.create(attributes).merge(EntityUtil.createResource(singletonList(host)))); + } + + @ParameterizedTest + @MethodSource("overlappingRawAttributes") + void normalizedAssemblerRejectsOverlappingAttributes(Attributes attributes) { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build(); + assertThatThrownBy(() -> Resource.create(attributes, null, singletonList(host))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unassociated attributes must not overlap entity attributes."); + } + + static Stream overlappingRawAttributes() { + return Stream.of( + Arguments.argumentSet( + "unchanged identifying value", Attributes.of(stringKey("host.id"), "H1")), + Arguments.argumentSet( + "changed identifying value", Attributes.of(stringKey("host.id"), "H2")), + Arguments.argumentSet("changed identifying type", Attributes.of(longKey("host.id"), 1L)), + Arguments.argumentSet( + "descriptive attribute key", Attributes.of(stringKey("host.name"), "other"))); + } + + @Test + void normalizedAssemblerRejectsDuplicateTypesAndAttributeOwners() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + Entity otherHost = Entity.builder("host", Attributes.of(stringKey("other.id"), "H2")).build(); + Entity process = Entity.builder("process", Attributes.of(stringKey("host.id"), "P1")).build(); + assertThatThrownBy( + () -> Resource.create(Attributes.empty(), null, Arrays.asList(host, otherHost))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Entity types must be unique in normalized resources."); + assertThatThrownBy( + () -> Resource.create(Attributes.empty(), null, Arrays.asList(host, process))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Entity attribute keys must have a single owner and classification."); + } + @Test void create_ignoreNull() { AttributesBuilder attributes = Attributes.builder(); @@ -168,6 +277,42 @@ void create_NullEmptyArray() { assertThat(resource.getAttributes().size()).isEqualTo(8); } + @Test + void create_NullEmptyValue() { + AttributesBuilder attributes = Attributes.builder(); + + // Empty values should be maintained + attributes.put(valueKey("value"), Value.empty()); + + Resource resource = Resource.create(attributes.build()); + assertThat(resource.getAttributes()).isNotNull(); + assertThat(resource.getAttributes().size()).isEqualTo(1); + + // Null values should be dropped + attributes.put(valueKey("dropNullValue"), null); + resource = Resource.create(attributes.build()); + assertThat(resource.getAttributes()).isNotNull(); + assertThat(resource.getAttributes().size()).isEqualTo(1); + } + + @Test + void create_invalidAttributeKey() { + assertThatThrownBy(() -> Resource.create(Attributes.of(stringKey("\u0002ab"), "value"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Attribute key should be a ASCII string"); + + assertThatThrownBy(() -> Resource.create(Attributes.of(stringKey("key\u007f"), "value"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Attribute key should be a ASCII string"); + + char[] chars = new char[256]; + Arrays.fill(chars, 'a'); + String tooLongKey = new String(chars); + assertThatThrownBy(() -> Resource.create(Attributes.of(stringKey(tooLongKey), "value"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Attribute key should be a ASCII string"); + } + @Test void testResourceEquals() { Attributes attribute1 = Attributes.of(stringKey("a"), "1", stringKey("b"), "2"); @@ -182,6 +327,14 @@ void testResourceEquals() { .testEquals(); } + @Test + void testToString() { + Attributes attribute1 = Attributes.of(stringKey("a"), "1", stringKey("b"), "2"); + Resource resource = Resource.create(attribute1, "http://schema"); + assertThat(resource.toString()) + .isEqualTo("Resource{schemaUrl=http://schema, entities=[], attributes={a=\"1\", b=\"2\"}}"); + } + @Test void testMergeResources() { Attributes expectedAttributes = @@ -208,6 +361,465 @@ void testMergeResources_schema() { assertThat(schemaTwo.merge(schemaOne).getSchemaUrl()).isNull(); } + @Test + void testMergeResources_emptySchemaIsPresent() { + Resource schemaOne = Resource.create(Attributes.of(stringKey("a"), "1"), "http://schema.1"); + Resource emptySchema = Resource.create(Attributes.of(stringKey("b"), "2"), ""); + + assertThat(schemaOne.merge(emptySchema).getSchemaUrl()).isNull(); + assertThat(emptySchema.merge(schemaOne).getSchemaUrl()).isNull(); + assertThat(emptySchema.merge(emptySchema).getSchemaUrl()).isEmpty(); + } + + @Test + void testMergeResources_entitySchemas() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setSchemaUrl("S1") + .build(); + Entity process = + Entity.builder("process", Attributes.of(longKey("process.pid"), 1L)) + .setSchemaUrl("S2") + .build(); + Entity withoutSchema = + Entity.builder("service", Attributes.of(stringKey("service.name"), "svc")).build(); + Resource pinned = + Resource.builder().addEntity(host).build().toBuilder().addEntity(process).build(); + Resource explicit = Resource.builder().setSchemaUrl("explicit").addEntity(host).build(); + Resource withoutEntitySchema = Resource.builder().addEntity(withoutSchema).build(); + + assertThat(pinned.getSchemaUrl()).isEqualTo("S1"); + assertThat(Resource.empty().merge(pinned)).isEqualTo(pinned); + assertThat(Resource.getDefault().merge(explicit).getSchemaUrl()).isEqualTo("explicit"); + assertThat(withoutEntitySchema.getSchemaUrl()).isNull(); + assertThat( + Resource.create(Attributes.of(stringKey("a"), "1"), "S1") + .merge(withoutEntitySchema) + .getSchemaUrl()) + .isEqualTo("S1"); + assertThat(Resource.builder().addEntity(host).addEntity(withoutSchema).build().getSchemaUrl()) + .isEqualTo("S1"); + } + + @Test + void testMergeResources_entityReplacementUsesResolvedSchemas() { + Resource base = + Resource.builder() + .addEntity( + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setSchemaUrl("S1") + .build()) + .build(); + Resource replacement = + Resource.builder() + .addEntity( + Entity.builder("host", Attributes.of(stringKey("host.id"), "H2")) + .setSchemaUrl("S2") + .build()) + .build(); + + assertThat(base.getSchemaUrl()).isEqualTo("S1"); + assertThat(replacement.getSchemaUrl()).isEqualTo("S2"); + assertThat(base.merge(replacement).getSchemaUrl()).isNull(); + } + + @Test + void entitySnapshotsAreImmutable() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + Entity service = + Entity.builder("service", Attributes.of(stringKey("service.name"), "S1")).build(); + ResourceBuilder builder = Resource.builder().addEntity(host); + Resource snapshot = builder.build(); + int hashCode = snapshot.hashCode(); + + builder.addEntity(service).put("raw", "later").build(); + + assertThat(snapshot.getEntities()).containsExactly(host); + assertThat(snapshot.getAttributes()).isEqualTo(host.getId()); + assertThat(snapshot.hashCode()).isEqualTo(hashCode); + assertThatThrownBy(() -> snapshot.getEntities().clear()) + .isInstanceOf(UnsupportedOperationException.class); + + List input = new ArrayList<>(singletonList(host)); + Resource fromCollection = Resource.create(Attributes.empty(), null, input); + input.clear(); + assertThat(fromCollection).isEqualTo(snapshot); + } + + @Test + void nullFilteringIsANoopWithAndWithoutEntities() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + for (Resource original : + Arrays.asList( + Resource.create(Attributes.of(stringKey("ordinary"), "value")), + EntityUtil.createResource(singletonList(host)))) { + assertThat(original.toBuilder().removeIf(null).build()).isEqualTo(original); + } + logs.assertDoesNotContain("Removing entity association"); + } + + @Test + void mergeDoesNotMutateInputs() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + Resource base = Resource.create(Attributes.empty(), null, singletonList(host)); + Resource updating = Resource.create(Attributes.of(stringKey("host.id"), "H2")); + + Resource merged = base.merge(updating); + + assertThat(merged.getEntities()).isEmpty(); + assertThat(merged.getAttributes()).isEqualTo(updating.getAttributes()); + assertThat(base.getEntities()).containsExactly(host); + assertThat(base.getAttributes()).isEqualTo(host.getId()); + assertThat(updating.getEntities()).isEmpty(); + assertThat(updating.getAttributes()).isEqualTo(Attributes.of(stringKey("host.id"), "H2")); + assertThat(Resource.empty().merge(base)).isEqualTo(base); + } + + @ParameterizedTest + @MethodSource("entityAttributeOverrideCases") + void entityAttributeOverride(Consumer override, Attributes expectedOverride) { + Entity entity = + Entity.builder("test", Attributes.of(stringKey("target"), "original")) + .setDescription(Attributes.of(stringKey("retained"), "value")) + .build(); + Resource original = Resource.builder().addEntity(entity).build(); + ResourceBuilder builder = original.toBuilder(); + + override.accept(builder); + Resource resource = builder.build(); + + assertThat(resource.getEntities()).isEmpty(); + assertThat(resource.getAttributes()) + .isEqualTo(Attributes.builder().put("retained", "value").putAll(expectedOverride).build()); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Removing entity association [test]"); + } + + static Stream entityAttributeOverrideCases() { + return Stream.of( + overrideCase( + "string", + b -> b.put("target", "updated"), + Attributes.of(stringKey("target"), "updated")), + overrideCase("long", b -> b.put("target", 2L), Attributes.of(longKey("target"), 2L)), + overrideCase("double", b -> b.put("target", 2.0), Attributes.of(doubleKey("target"), 2.0)), + overrideCase( + "boolean", b -> b.put("target", true), Attributes.of(booleanKey("target"), true)), + overrideCase( + "string array", + b -> b.put("target", "updated", "next"), + Attributes.of(stringArrayKey("target"), Arrays.asList("updated", "next"))), + overrideCase( + "long array", + b -> b.put("target", 2L, 3L), + Attributes.of(longArrayKey("target"), Arrays.asList(2L, 3L))), + overrideCase( + "double array", + b -> b.put("target", 2.0, 3.0), + Attributes.of(doubleArrayKey("target"), Arrays.asList(2.0, 3.0))), + overrideCase( + "boolean array", + b -> b.put("target", true, false), + Attributes.of(booleanArrayKey("target"), Arrays.asList(true, false))), + overrideCase( + "typed key", + b -> b.put(stringKey("target"), "updated"), + Attributes.of(stringKey("target"), "updated")), + overrideCase( + "typed int", b -> b.put(longKey("target"), 2), Attributes.of(longKey("target"), 2L)), + overrideCase( + "attributes", + b -> b.putAll(Attributes.of(stringKey("target"), "updated")), + Attributes.of(stringKey("target"), "updated")), + overrideCase( + "resource", + b -> b.putAll(Resource.create(Attributes.of(stringKey("target"), "updated"))), + Attributes.of(stringKey("target"), "updated")), + overrideCase( + "multiple attributes", + b -> + b.putAll( + Attributes.builder().put("target", "updated").put("retained", "new").build()), + Attributes.builder().put("target", "updated").put("retained", "new").build()), + overrideCase( + "multiple puts", + b -> b.put("target", "updated").put("retained", "new"), + Attributes.builder().put("target", "updated").put("retained", "new").build())); + } + + private static Arguments overrideCase( + String name, Consumer override, Attributes expected) { + return Arguments.argumentSet(name, override, expected); + } + + @ParameterizedTest + @MethodSource("entityAttributeOverrideCases") + void unchangedEntityAttributesPreserveAssociations( + Consumer write, Attributes attributes) { + for (boolean identifying : new boolean[] {true, false}) { + Entity entity = + Entity.builder( + "test", identifying ? attributes : Attributes.of(stringKey("identity"), "E1")) + .setDescription( + identifying ? Attributes.of(stringKey("other"), "retained") : attributes) + .build(); + Resource original = Resource.builder().addEntity(entity).build(); + ResourceBuilder builder = original.toBuilder(); + + write.accept(builder); + + assertThat(builder.build()).isEqualTo(original); + assertThat(builder.build().getEntities()).containsExactly(entity); + logs.assertDoesNotContain("Removing entity association"); + } + } + + @Test + void mixedUnchangedAndChangedAttributes() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "old")) + .build(); + Entity service = + Entity.builder("service", Attributes.of(stringKey("service.name"), "S1")).build(); + Resource original = Resource.builder().addEntity(host).addEntity(service).build(); + Attributes incoming = + Attributes.builder() + .put("host.id", "H1") + .put("host.name", "new") + .put("service.name", "S1") + .put("raw", "new") + .build(); + Resource expected = original.merge(Resource.create(incoming)); + + assertThat(expected.getEntities()).containsExactly(service); + assertThat(expected.getAttributes()).isEqualTo(incoming); + assertThat(original.toBuilder().putAll(incoming).build()).isEqualTo(expected); + assertThat(original.toBuilder().putAll(Resource.create(incoming)).build()).isEqualTo(expected); + assertThat( + original.toBuilder() + .put("host.id", "H1") + .put("host.name", "new") + .put("service.name", "S1") + .put("raw", "new") + .build()) + .isEqualTo(expected); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Removing entity association [host]"); + logs.assertDoesNotContain("Removing entity association [service]"); + } + + @Test + void unchangedCoercedValuePreservesAssociation() { + Entity entity = Entity.builder("test", Attributes.of(stringKey("target"), "same")).build(); + Resource original = Resource.builder().addEntity(entity).build(); + Resource resource = + original.toBuilder() + .put(valueKey("target"), Value.of("same")) + .putAll(Attributes.of(valueKey("target"), Value.of("same"))) + .build(); + assertThat(resource).isEqualTo(original); + logs.assertDoesNotContain("Removing entity association"); + } + + @Test + void ignoredNullOverridesDoNotRemoveAssociations() { + Entity entity = Entity.builder("test", Attributes.of(stringKey("target"), "original")).build(); + Resource original = Resource.builder().addEntity(entity).build(); + Resource resource = + original.toBuilder() + .put("target", (String) null) + .put(stringKey("target"), null) + .put("target", (long[]) null) + .putAll((Attributes) null) + .build(); + assertThat(resource).isEqualTo(original); + } + + @Test + void entityOperationOrdering() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "detected")) + .build(); + ResourceBuilder builder = Resource.builder().put("host.name", "earlier").addEntity(host); + assertThat(builder.build().getAttribute(stringKey("host.name"))).isEqualTo("detected"); + builder.put("host.name", "override"); + assertThat(builder.build().getEntities()).isEmpty(); + builder.addEntity(host); + assertThat(builder.build().getEntities()).containsExactly(host); + assertThat(builder.build().getAttribute(stringKey("host.name"))).isEqualTo("detected"); + } + + @Test + void filterEntityAttributes() { + Entity host = + Entity.builder( + "host", + Attributes.builder().put("host.id", "H1").put("host.region", "west").build()) + .setDescription( + Attributes.builder().put("host.name", "machine").put("host.type", "vm").build()) + .build(); + Resource original = Resource.builder().addEntity(host).put("raw", "remove").build(); + Resource filtered = + original.toBuilder() + .removeIf(key -> + key.getKey().equals("host.id") + || key.getKey().equals("host.name") + || key.getKey().equals("raw")) + .build(); + + assertThat(filtered.getEntities()).isEmpty(); + assertThat(filtered.getUnassociatedAttributes()).isEqualTo(filtered.getAttributes()); + assertThat(filtered.getAttributes()) + .isEqualTo(Attributes.builder().put("host.region", "west").put("host.type", "vm").build()); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Removing entity association [host]"); + } + + @Test + void filterLastIdentifyingAttribute() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build(); + Resource filtered = + Resource.builder().addEntity(host).removeIf(key -> key.getKey().equals("host.id")).build(); + assertThat(filtered.getEntities()).isEmpty(); + assertThat(filtered.getUnassociatedAttributes()).isEqualTo(host.getDescription()); + assertThat(filtered.getAttributes()).isEqualTo(host.getDescription()); + assertThat(filtered.toBuilder().build()).isEqualTo(filtered); + } + + @Test + void noOpEntityOperationsDoNotLogChanges() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build(); + Resource original = EntityUtil.createResource(singletonList(host)); + assertThat(original.merge(original)).isEqualTo(original); + assertThat( + original.toBuilder() + .removeIf(key -> false) + .put("host.id", "H1") + .put("host.name", "machine") + .build()) + .isEqualTo(original); + logs.assertDoesNotContain("Updating descriptive attributes"); + logs.assertDoesNotContain("Removing descriptive attribute keys"); + logs.assertDoesNotContain("Removing entity association"); + logs.assertDoesNotContain("Replacing entity"); + } + + @Test + void filterDescriptionPreservesAssociation() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build(); + Resource original = Resource.builder().addEntity(host).build(); + Resource filtered = + original.toBuilder().removeIf(key -> key.getKey().equals("host.name")).build(); + + assertThat(filtered.getEntities()) + .singleElement() + .satisfies(entity -> { + assertThat(entity.getId()).isEqualTo(host.getId()); + assertThat(entity.getDescription()).isEqualTo(Attributes.empty()); + }); + assertThat(filtered.getAttributes()).isEqualTo(host.getId()); + assertThat(filtered.getUnassociatedAttributes()).isEqualTo(Attributes.empty()); + logs.assertContains( + event -> event.getLevel().equals(WARN), + "Removing descriptive attribute keys from entity [host]"); + } + + @Test + void schemaCopyingDiffersFromDerivationAndMerging() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setSchemaUrl("S1") + .build(); + Entity process = + Entity.builder("process", Attributes.of(longKey("process.pid"), 1L)) + .setSchemaUrl("S2") + .build(); + ResourceBuilder builder = Resource.builder().addEntity(host); + Resource hostResource = builder.build(); + Resource processResource = EntityUtil.createResource(singletonList(process)); + + assertThat(builder.addEntity(process).build().getSchemaUrl()).isNull(); + assertThat(hostResource.toBuilder().addEntity(process).build().getSchemaUrl()).isEqualTo("S1"); + assertThat(hostResource.merge(processResource).getSchemaUrl()).isNull(); + assertThat( + Resource.builder().putAll(hostResource).putAll(processResource).build().getSchemaUrl()) + .isNull(); + assertThat( + Resource.builder() + .setSchemaUrl("configured") + .putAll(hostResource) + .putAll(processResource) + .build() + .getSchemaUrl()) + .isEqualTo("configured"); + } + + @Test + void mergeGroupingCanChangeAssociations() { + Entity host = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "old")) + .build(); + Resource a = EntityUtil.createResource(singletonList(host)); + Resource b = Resource.create(Attributes.of(stringKey("host.name"), "new")); + Resource c = + EntityUtil.createResource(singletonList(Entity.builder("host", host.getId()).build())); + Resource left = a.merge(b).merge(c); + Resource right = a.merge(b.merge(c)); + + assertThat(left.getAttributes()).isEqualTo(right.getAttributes()); + assertThat(left.getEntities()).hasSize(1); + assertThat(right.getEntities()).isEmpty(); + } + + @Test + void valueEqualityIncludesEntityOrderAndDescriptions() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + Entity process = Entity.builder("process", Attributes.of(longKey("process.pid"), 1L)).build(); + Resource original = EntityUtil.createResource(Arrays.asList(host, process)); + Resource reordered = original.merge(EntityUtil.createResource(singletonList(host))); + Resource described = + original.merge( + EntityUtil.createResource( + singletonList( + host.toBuilder() + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build()))); + + assertThat(reordered.getAttributes()).isEqualTo(original.getAttributes()); + assertThat(reordered.getEntities()).containsExactlyInAnyOrderElementsOf(original.getEntities()); + assertThat(reordered).isNotEqualTo(original); + assertThat(described).isNotEqualTo(original); + assertThat(described.getAttribute(stringKey("host.id"))).isEqualTo("H1"); + } + + @Test + void equalityIncludesDescriptionClassification() { + Entity host = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).build(); + Resource ordinaryName = Resource.builder().addEntity(host).put("host.name", "machine").build(); + Resource describedName = + Resource.builder() + .addEntity( + host.toBuilder() + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .build()) + .build(); + assertThat(ordinaryName.getAttributes()).isEqualTo(describedName.getAttributes()); + assertThat(ordinaryName.getSchemaUrl()).isEqualTo(describedName.getSchemaUrl()); + assertThat(ordinaryName).isNotEqualTo(describedName); + } + @Test void testMergeResources_Resource1() { Attributes expectedAttributes = Attributes.of(stringKey("a"), "1", stringKey("b"), "2"); @@ -238,12 +850,10 @@ void testMergeResources_Resource2_Null() { @Test void testDefaultResources() { Resource resource = Resource.getDefault(); - assertThat(resource.getAttribute(ResourceAttributes.SERVICE_NAME)) - .isEqualTo("unknown_service:java"); - assertThat(resource.getAttribute(ResourceAttributes.TELEMETRY_SDK_NAME)) - .isEqualTo("opentelemetry"); - assertThat(resource.getAttribute(ResourceAttributes.TELEMETRY_SDK_LANGUAGE)).isEqualTo("java"); - assertThat(resource.getAttribute(ResourceAttributes.TELEMETRY_SDK_VERSION)) + assertThat(resource.getAttribute(stringKey("service.name"))).isEqualTo("unknown_service:java"); + assertThat(resource.getAttribute(stringKey("telemetry.sdk.name"))).isEqualTo("opentelemetry"); + assertThat(resource.getAttribute(stringKey("telemetry.sdk.language"))).isEqualTo("java"); + assertThat(resource.getAttribute(stringKey("telemetry.sdk.version"))) .isEqualTo(System.getProperty("otel.test.project-version")); } @@ -257,7 +867,7 @@ void shouldBuilderNotFailWithNullResource() { // then no exception is thrown // and - assertThat(builder.build().getAttribute(ResourceAttributes.SERVICE_NAME)) + assertThat(builder.build().getAttribute(stringKey("service.name"))) .isEqualTo("unknown_service:java"); } @@ -357,9 +967,8 @@ public void removeIf() { Resource.builder() .put("key1", "value1A") .put("key1", true) - .removeIf( - key -> - key.getKey().equals("key1") && key.getType().equals(AttributeType.STRING)) + .removeIf(key -> + key.getKey().equals("key1") && key.getType().equals(AttributeType.STRING)) .build()) .isEqualTo(Resource.builder().put("key1", true).build()); assertThat( diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/ConstantResourceDetectorTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/ConstantResourceDetectorTest.java new file mode 100644 index 00000000000..c54dfe39a5d --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/ConstantResourceDetectorTest.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.resources.Resource; +import org.junit.jupiter.api.Test; + +class ConstantResourceDetectorTest { + + private static final Resource RESOURCE = + Resource.create(Attributes.of(AttributeKey.stringKey("k"), "v")); + + @Test + void constant_unnamed() { + ResourceDetector detector = new ConstantResourceDetector(null, RESOURCE); + + assertThat(detector.getName()).isNull(); + assertThat(detector.getResource()).isEqualTo(RESOURCE); + } + + @Test + void constant_named() { + ResourceDetector detector = new ConstantResourceDetector("my-detector", RESOURCE); + + assertThat(detector.getName()).isEqualTo("my-detector"); + assertThat(detector.getResource()).isEqualTo(RESOURCE); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java new file mode 100644 index 00000000000..6e9ccfed38e --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/EntityUtilTest.java @@ -0,0 +1,389 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.slf4j.event.Level.WARN; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.ResourceBuilder; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** Unit tests for {@link EntityUtil}. */ +@SuppressLogger(Resource.class) +@SuppressLogger(ResourceBuilder.class) +class EntityUtilTest { + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(ResourceBuilder.class, WARN); + + @ParameterizedTest + @MethodSource("mergeEntitiesTestCases") + void mergeEntities( + Collection base, + Collection added, + Collection expected, + @Nullable String expectedSchemaUrl) { + Resource merged = EntityUtil.createResource(base).merge(EntityUtil.createResource(added)); + assertThat(EntityUtil.getEntities(merged)).containsExactlyElementsOf(expected); + assertThat(EntityUtil.getUnassociatedAttributes(merged)).isEmpty(); + assertThat(merged.getSchemaUrl()).isEqualTo(expectedSchemaUrl); + } + + static Stream mergeEntitiesTestCases() { + Entity withoutSchema = + Entity.builder("a", Attributes.builder().put("a.id", "a").build()) + .setDescription(Attributes.builder().put("a.desc1", "a").build()) + .build(); + Entity withSchema = + Entity.builder("a", Attributes.builder().put("a.id", "a").build()) + .setSchemaUrl("one") + .setDescription(Attributes.builder().put("a.desc2", "b").build()) + .build(); + return Stream.of( + Arguments.argumentSet( + "same type and id different schema - incoming entity replaces old entity", + Collections.singletonList(withSchema), + Collections.singletonList(withSchema.toBuilder().setSchemaUrl("two").build()), + Collections.singletonList(withSchema.toBuilder().setSchemaUrl("two").build()), + null), + Arguments.argumentSet( + "absent schema replaced by present schema", + Collections.singletonList(withoutSchema), + Collections.singletonList(withSchema), + Collections.singletonList(withSchema), + "one"), + Arguments.argumentSet( + "present schema replaced by absent schema", + Collections.singletonList(withSchema), + Collections.singletonList(withoutSchema), + Collections.singletonList(withoutSchema), + "one"), + Arguments.argumentSet( + "same type different id - incoming entity replaces old entity", + Collections.singletonList(withSchema), + Collections.singletonList( + Entity.builder("a", Attributes.builder().put("a.id", "b").build()) + .setSchemaUrl("one") + .build()), + Collections.singletonList( + Entity.builder("a", Attributes.builder().put("a.id", "b").build()) + .setSchemaUrl("one") + .build()), + "one"), + Arguments.argumentSet( + "separate types and schema - both entities are kept", + Collections.singletonList( + Entity.builder("a", Attributes.builder().put("a.id", "a").build()) + .setSchemaUrl("one") + .build()), + Collections.singletonList( + Entity.builder("b", Attributes.builder().put("b.id", "b").build()) + .setSchemaUrl("two") + .build()), + Arrays.asList( + Entity.builder("a", Attributes.builder().put("a.id", "a").build()) + .setSchemaUrl("one") + .build(), + Entity.builder("b", Attributes.builder().put("b.id", "b").build()) + .setSchemaUrl("two") + .build()), + null)); + } + + @ParameterizedTest + @MethodSource("mergeDescriptionTestCases") + void mergeDescriptions(@Nullable String schemaUrl) { + Entity base = + Entity.builder("host", Attributes.builder().put("host.id", "H1").build()) + .setDescription( + Attributes.builder().put("host.name", "old").put("host.arch", "arm64").build()) + .build(); + Entity incoming = + Entity.builder("host", base.getId()) + .setDescription( + Attributes.builder().put("host.name", "new").put("host.type", "vm").build()) + .build(); + if (schemaUrl != null) { + base = base.toBuilder().setSchemaUrl(schemaUrl).build(); + incoming = incoming.toBuilder().setSchemaUrl(schemaUrl).build(); + } + + Resource merged = + EntityUtil.createResource(Collections.singletonList(base)) + .merge(EntityUtil.createResource(Collections.singletonList(incoming))); + Entity expected = + incoming.toBuilder() + .setDescription( + Attributes.builder() + .put("host.name", "new") + .put("host.arch", "arm64") + .put("host.type", "vm") + .build()) + .build(); + + assertThat(merged).isEqualTo(EntityUtil.createResource(Collections.singletonList(expected))); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Updating descriptive attributes of entity [host]"); + } + + static Stream mergeDescriptionTestCases() { + return Stream.of( + Arguments.argumentSet("matching schemas", "https://opentelemetry.io/schemas/1.40.0"), + Arguments.argumentSet("both schemas absent", (String) null)); + } + + @ParameterizedTest + @MethodSource("absentSchemaRepresentations") + void mergeAbsentSchemaRepresentations( + @Nullable String baseSchema, @Nullable String incomingSchema) { + Attributes id = Attributes.of(AttributeKey.stringKey("host.id"), "H1"); + Entity base = + spy( + SdkEntity.create( + "host", + id, + Attributes.of(AttributeKey.stringKey("host.arch"), "arm64"), + baseSchema)); + Entity incoming = + spy( + SdkEntity.create( + "host", + id, + Attributes.of(AttributeKey.stringKey("host.name"), "new"), + incomingSchema)); + doReturn(baseSchema).when(base).getSchemaUrl(); + doReturn(incomingSchema).when(incoming).getSchemaUrl(); + + Resource merged = + EntityUtil.createResource(Collections.singletonList(base)) + .merge(EntityUtil.createResource(Collections.singletonList(incoming))); + + assertThat(EntityUtil.getEntities(merged)) + .singleElement() + .satisfies(entity -> { + assertThat(entity.getId()).isEqualTo(id); + assertThat(entity.getDescription()) + .isEqualTo( + Attributes.builder().put("host.arch", "arm64").put("host.name", "new").build()); + assertThat(entity.getSchemaUrl()).isNull(); + }); + assertThat(merged.getSchemaUrl()).isNull(); + logs.assertDoesNotContain("Replacing entity"); + } + + static Stream absentSchemaRepresentations() { + return Stream.of( + Arguments.argumentSet("null / null", null, null), + Arguments.argumentSet("empty / empty", "", ""), + Arguments.argumentSet("null / empty", null, ""), + Arguments.argumentSet("empty / null", "", null)); + } + + @ParameterizedTest + @MethodSource("mergeCrossEntityConflictTestCases") + void mergeCrossEntityConflict( + boolean existingIdentifying, + boolean incomingIdentifying, + Attributes existingConflict, + Attributes incomingConflict) { + Entity existing = + Entity.builder( + "existing", + Attributes.builder() + .put("existing.id", "E1") + .putAll(existingIdentifying ? existingConflict : Attributes.empty()) + .build()) + .setDescription( + Attributes.builder() + .put("existing.description", "preserved") + .putAll(existingIdentifying ? Attributes.empty() : existingConflict) + .build()) + .build(); + Entity incoming = + Entity.builder( + "incoming", + Attributes.builder() + .put("incoming.id", "I1") + .putAll(incomingIdentifying ? incomingConflict : Attributes.empty()) + .build()) + .setDescription(incomingIdentifying ? Attributes.empty() : incomingConflict) + .build(); + Entity unrelated = + Entity.builder("unrelated", Attributes.builder().put("other.id", "O1").build()).build(); + ResourceBuilder baseBuilder = Resource.builder().put("raw", "preserved"); + EntityUtil.addEntity(baseBuilder, existing); + EntityUtil.addEntity(baseBuilder, unrelated); + + Resource merged = + baseBuilder.build().merge(EntityUtil.createResource(Collections.singletonList(incoming))); + + assertThat(EntityUtil.getEntities(merged)).containsExactly(unrelated, incoming); + assertThat(EntityUtil.getUnassociatedAttributes(merged)) + .isEqualTo( + Attributes.builder() + .put("raw", "preserved") + .put("existing.id", "E1") + .put("existing.description", "preserved") + .build()); + assertThat(merged.getAttributes()) + .isEqualTo( + Attributes.builder() + .putAll(EntityUtil.getUnassociatedAttributes(merged)) + .putAll(unrelated.getId()) + .putAll(incoming.getId()) + .putAll(incoming.getDescription()) + .build()); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Removing entity association [existing]"); + } + + static Stream mergeCrossEntityConflictTestCases() { + Attributes old = Attributes.of(AttributeKey.stringKey("shared"), "old"); + Attributes updated = Attributes.of(AttributeKey.stringKey("shared"), "new"); + return Stream.of( + Arguments.argumentSet("incoming id overwrites existing id", true, true, old, updated), + Arguments.argumentSet( + "incoming description overwrites existing id", true, false, old, updated), + Arguments.argumentSet( + "incoming id overwrites existing description", false, true, old, updated), + Arguments.argumentSet( + "incoming description overwrites existing description", false, false, old, updated), + Arguments.argumentSet( + "equal values still transfer attribute key ownership", false, false, old, old), + Arguments.argumentSet( + "different attribute types", + true, + true, + Attributes.of(AttributeKey.longKey("shared"), 1L), + updated)); + } + + @Test + void mergeReplacementAndCrossEntityConflict() { + Entity oldHost = + Entity.builder("host", Attributes.builder().put("host.id", "H2").build()) + .setDescription(Attributes.builder().put("host.name", "discarded").build()) + .build(); + Entity service = + Entity.builder("service", Attributes.builder().put("service.name", "S1").build()) + .setDescription(Attributes.builder().put("env", "dev").build()) + .build(); + Entity incoming = + Entity.builder("host", Attributes.builder().put("host.id", "H1").build()) + .setDescription(Attributes.builder().put("env", "prod").build()) + .build(); + + Resource merged = + EntityUtil.createResource(Arrays.asList(oldHost, service)) + .merge(EntityUtil.createResource(Collections.singletonList(incoming))); + + assertThat(EntityUtil.getEntities(merged)).containsExactly(incoming); + assertThat(merged.getAttributes()) + .isEqualTo( + Attributes.builder() + .put("host.id", "H1") + .put("env", "prod") + .put("service.name", "S1") + .build()); + assertThat(EntityUtil.getUnassociatedAttributes(merged)) + .isEqualTo(Attributes.of(AttributeKey.stringKey("service.name"), "S1")); + logs.assertContains( + event -> event.getLevel().equals(WARN), + "Replacing entity [host] because identifying attributes differ."); + logs.assertContains( + event -> event.getLevel().equals(WARN), + "Removing entity association [service] because incoming entity [host] overwrites its attributes. Non-conflicting attributes are retained as unassociated."); + } + + @Test + void mergeIncomingEntitiesInOrder() { + Entity host = + Entity.builder("host", Attributes.builder().put("host.id", "H1").build()) + .setDescription(Attributes.builder().put("env", "host-env").build()) + .build(); + Entity service = + Entity.builder("service", Attributes.builder().put("service.name", "S1").build()) + .setDescription(Attributes.builder().put("env", "service-env").build()) + .build(); + + Resource hostThenService = + Resource.empty().merge(EntityUtil.createResource(Arrays.asList(host, service))); + Resource serviceThenHost = + Resource.empty().merge(EntityUtil.createResource(Arrays.asList(service, host))); + + assertThat(EntityUtil.getEntities(hostThenService)).containsExactly(service); + assertThat(EntityUtil.getUnassociatedAttributes(hostThenService)) + .isEqualTo(Attributes.of(AttributeKey.stringKey("host.id"), "H1")); + assertThat(hostThenService.getAttributes()).containsEntry("env", "service-env"); + assertThat(EntityUtil.getEntities(serviceThenHost)).containsExactly(host); + assertThat(EntityUtil.getUnassociatedAttributes(serviceThenHost)) + .isEqualTo(Attributes.of(AttributeKey.stringKey("service.name"), "S1")); + assertThat(serviceThenHost.getAttributes()).containsEntry("env", "host-env"); + } + + @ParameterizedTest + @MethodSource("attributeTypeChangeCases") + void attributeTypeChangeRemovesAssociation(Attributes before, Attributes after) { + Entity entity = Entity.builder("test", before).build(); + Resource original = EntityUtil.createResource(Collections.singletonList(entity)); + Resource merged = original.merge(Resource.create(after)); + assertThat(EntityUtil.getEntities(merged)).isEmpty(); + assertThat(merged.getAttributes()).isEqualTo(after); + assertThat(original.toBuilder().putAll(after).build()).isEqualTo(merged); + logs.assertContains( + event -> event.getLevel().equals(WARN), "Removing entity association [test]"); + } + + static Stream attributeTypeChangeCases() { + return Stream.of( + Arguments.argumentSet( + "equal-looking numbers", + Attributes.of(AttributeKey.longKey("key"), 1L), + Attributes.of(AttributeKey.doubleKey("key"), 1.0)), + Arguments.argumentSet( + "equal empty lists", + Attributes.of(AttributeKey.longArrayKey("key"), Collections.emptyList()), + Attributes.of(AttributeKey.stringArrayKey("key"), Collections.emptyList()))); + } + + @Test + void duplicateEntityReferencesAreNormalized() { + Entity first = Entity.builder("test", Attributes.of(AttributeKey.stringKey("id"), "1")).build(); + Entity second = + Entity.builder("test", Attributes.of(AttributeKey.stringKey("id"), "2")).build(); + Resource resource = EntityUtil.createResource(Arrays.asList(first, first, second)); + assertThat(EntityUtil.getEntities(resource)).containsExactly(second); + assertThat(resource.getAttributes()).isEqualTo(second.getId()); + } + + @Test + void addEntity_reflection() { + Resource result = + EntityUtil.addEntity( + Resource.builder(), + Entity.builder("a", Attributes.builder().put("a", 1).build()).build()) + .build(); + assertThat(EntityUtil.getEntities(result)) + .satisfiesExactlyInAnyOrder(e -> assertThat(e.getType()).isEqualTo("a")); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/SdkEntityBuilderTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/SdkEntityBuilderTest.java new file mode 100644 index 00000000000..72e96103100 --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/SdkEntityBuilderTest.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.util.Collections; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class SdkEntityBuilderTest { + + @ParameterizedTest + @MethodSource("invalidTypes") + void invalidType(String type) { + assertThatThrownBy(() -> Entity.builder(type, Attributes.of(stringKey("id"), "1"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Entity type must be a valid non-empty printable ASCII string."); + } + + static Stream invalidTypes() { + return Stream.of( + Arguments.argumentSet("empty", ""), + Arguments.argumentSet("non-ASCII", "hΓΆst"), + Arguments.argumentSet("control character", "host\n"), + Arguments.argumentSet("too long", String.join("", Collections.nCopies(256, "a")))); + } + + @Test + void emptyIdentity() { + assertThatThrownBy(() -> Entity.builder("host", Attributes.empty())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Entity must have at least one identifying attribute."); + } + + @ParameterizedTest + @MethodSource("overlappingDescriptions") + void rejectsOverlappingDescription(Attributes description) { + EntityBuilder builder = Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")); + assertThatThrownBy(() -> builder.setDescription(description)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Identifying and descriptive attribute keys must not overlap."); + assertThat(builder.build().getDescription()).isEqualTo(Attributes.empty()); + } + + static Stream overlappingDescriptions() { + return Stream.of( + Arguments.argumentSet("same value", Attributes.of(stringKey("host.id"), "H1")), + Arguments.argumentSet("changed value", Attributes.of(stringKey("host.id"), "H2")), + Arguments.argumentSet("changed type", Attributes.of(AttributeKey.longKey("host.id"), 1L))); + } + + @Test + void emptySchemaIsAbsent() { + Entity entity = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")).setSchemaUrl("").build(); + assertThat(entity.getSchemaUrl()).isNull(); + assertThat(entity.toBuilder().build()).isEqualTo(entity); + } + + @Test + void nullInputs() { + assertThatThrownBy(() -> Entity.builder(null, Attributes.of(stringKey("id"), "1"))) + .isInstanceOf(NullPointerException.class) + .hasMessage("entityType"); + assertThatThrownBy(() -> Entity.builder("host", null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("id"); + assertThatThrownBy( + () -> Entity.builder("host", Attributes.of(stringKey("id"), "1")).setDescription(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("description"); + } + + @Test + void validConstructionAndCopy() { + Entity entity = + Entity.builder("host", Attributes.of(stringKey("host.id"), "H1")) + .setDescription(Attributes.of(stringKey("host.name"), "machine")) + .setSchemaUrl("https://opentelemetry.io/schemas/1.40.0") + .build(); + assertThat(entity.toBuilder().build()).isEqualTo(entity); + } +} diff --git a/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/SdkResourceProviderTest.java b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/SdkResourceProviderTest.java new file mode 100644 index 00000000000..02f8891e3ee --- /dev/null +++ b/sdk/common/src/test/java/io/opentelemetry/sdk/resources/internal/SdkResourceProviderTest.java @@ -0,0 +1,160 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.resources.internal; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Arrays; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class SdkResourceProviderTest { + + private static final Resource RESOURCE_A = + Resource.create(Attributes.of(AttributeKey.stringKey("a"), "1")); + private static final Resource RESOURCE_B = + Resource.create(Attributes.of(AttributeKey.stringKey("b"), "2")); + + @Test + void create_wrapsResourceInConstantDetector() { + SdkResourceProvider provider = SdkResourceProvider.create(RESOURCE_A); + + assertThat(provider.getResource()).isEqualTo(RESOURCE_A); + } + + @Test + void create_nullResource_throws() { + assertThatThrownBy(() -> SdkResourceProvider.create(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("resource"); + } + + @Test + void builder_singleConstantResource() { + SdkResourceProvider provider = + SdkResourceProvider.builder().addConstantResource(RESOURCE_A).build(); + + assertThat(provider.getResource()).isEqualTo(RESOURCE_A); + } + + @Test + void builder_multipleConstantResources_mergedInOrder() { + AttributeKey sharedKey = AttributeKey.stringKey("shared"); + Resource first = RESOURCE_A.toBuilder().put(sharedKey, "first").build(); + Resource second = RESOURCE_B.toBuilder().put(sharedKey, "second").build(); + SdkResourceProvider provider = + SdkResourceProvider.builder() + .addConstantResource(first) + .addConstantResource(second) + .build(); + + assertThat(provider.getResource()).isEqualTo(first.merge(second)); + assertThat(provider.getResource().getAttribute(sharedKey)).isEqualTo("second"); + } + + @Test + void builder_conflictingSchemaUrls_usesSequentialMergeSemantics() { + Resource first = Resource.create(RESOURCE_A.getAttributes(), "https://example.com/schema/1"); + Resource second = Resource.create(RESOURCE_B.getAttributes(), "https://example.com/schema/2"); + Resource third = Resource.create(Attributes.empty(), "https://example.com/schema/3"); + SdkResourceProviderBuilder builder = + SdkResourceProvider.builder().addConstantResource(first).addConstantResource(second); + + assertThat(builder.build().getResource().getSchemaUrl()).isNull(); + + SdkResourceProvider provider = builder.addConstantResource(third).build(); + + assertThat(provider.getResource()).isEqualTo(first.merge(second).merge(third)); + assertThat(provider.getResource().getSchemaUrl()).isEqualTo(third.getSchemaUrl()); + } + + @Test + void builder_reuse_doesNotChangePreviousProvider() { + SdkResourceProviderBuilder builder = + SdkResourceProvider.builder().addConstantResource(RESOURCE_A); + SdkResourceProvider first = builder.build(); + SdkResourceProvider second = builder.addConstantResource(RESOURCE_B).build(); + + assertThat(first.getResource()).isEqualTo(RESOURCE_A); + assertThat(second.getResource()).isEqualTo(RESOURCE_A.merge(RESOURCE_B)); + } + + @Test + void builder_addConstantResource_named() { + SdkResourceProvider provider = + SdkResourceProvider.builder().addConstantResource(RESOURCE_A, "my-detector").build(); + + assertThat(provider.getResource()).isEqualTo(RESOURCE_A); + assertThat(provider.toString()).contains("ConstantResourceDetector{name=my-detector"); + } + + @Test + void builder_addConstantResource_nullName() { + SdkResourceProvider provider = + SdkResourceProvider.builder().addConstantResource(RESOURCE_A, null).build(); + + assertThat(provider.getResource()).isEqualTo(RESOURCE_A); + assertThat(provider.toString()).contains("ConstantResourceDetector{name=null"); + } + + @Test + void builder_addConstantResource_nullResource_throws() { + assertThatThrownBy(() -> SdkResourceProvider.builder().addConstantResource(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("resource"); + assertThatThrownBy(() -> SdkResourceProvider.builder().addConstantResource(null, "name")) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("resource"); + } + + @Test + void builder_build_withoutAddConstantResource_throws() { + assertThatThrownBy(() -> SdkResourceProvider.builder().build()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("At least one Resource must be added via addConstantResource"); + } + + @Test + void getResource_allDetectorsResolvedOnceAtCreation() { + CountingDetector first = new CountingDetector(RESOURCE_A); + CountingDetector second = new CountingDetector(RESOURCE_B); + SdkResourceProvider provider = + SdkResourceProvider.createFromDetectors(Arrays.asList(first, second)); + + assertThat(first.invocations.get()).isEqualTo(1); + assertThat(second.invocations.get()).isEqualTo(1); + + assertThat(provider.getResource()).isEqualTo(RESOURCE_A.merge(RESOURCE_B)); + assertThat(provider.getResource()).isEqualTo(RESOURCE_A.merge(RESOURCE_B)); + + assertThat(first.invocations.get()).isEqualTo(1); + assertThat(second.invocations.get()).isEqualTo(1); + } + + private static final class CountingDetector implements ResourceDetector { + final AtomicInteger invocations = new AtomicInteger(); + private final Resource resource; + + CountingDetector(Resource resource) { + this.resource = resource; + } + + @Override + public String getName() { + return "counting"; + } + + @Override + public Resource getResource() { + invocations.incrementAndGet(); + return resource; + } + } +} diff --git a/sdk/logs-testing/README.md b/sdk/logs-testing/README.md deleted file mode 100644 index 8f6c8ec7c8c..00000000000 --- a/sdk/logs-testing/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Logs SDK Testing - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-logs-testing.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-logs-testing diff --git a/sdk/logs-testing/build.gradle.kts b/sdk/logs-testing/build.gradle.kts deleted file mode 100644 index f7fcce0c487..00000000000 --- a/sdk/logs-testing/build.gradle.kts +++ /dev/null @@ -1,22 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") -} - -description = "OpenTelemetry Logs SDK Testing utilities" -otelJava.moduleName.set("io.opentelemetry.sdk.logs.testing") - -dependencies { - api(project(":api:all")) - api(project(":sdk:all")) - api(project(":sdk:logs")) - api(project(":sdk:testing")) - - compileOnly("org.assertj:assertj-core") - compileOnly("junit:junit") - compileOnly("org.junit.jupiter:junit-jupiter-api") - - annotationProcessor("com.google.auto.value:auto-value") - - testImplementation("junit:junit") -} diff --git a/sdk/logs-testing/gradle.properties b/sdk/logs-testing/gradle.properties deleted file mode 100644 index 4476ae57e31..00000000000 --- a/sdk/logs-testing/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -otel.release=alpha diff --git a/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogAssertions.java b/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogAssertions.java deleted file mode 100644 index b4400ce9a68..00000000000 --- a/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogAssertions.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.sdk.logs.data.LogData; -import org.assertj.core.api.Assertions; - -/** Test assertions for data heading to exporters within the Metrics SDK. */ -public final class LogAssertions extends Assertions { - - /** Returns an assertion for {@link io.opentelemetry.sdk.logs.data.LogData}. */ - public static LogDataAssert assertThat(LogData log) { - return new LogDataAssert(log); - } - - private LogAssertions() {} -} diff --git a/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogDataAssert.java b/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogDataAssert.java deleted file mode 100644 index c2e853a8dbe..00000000000 --- a/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogDataAssert.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Map; -import java.util.function.Consumer; -import org.assertj.core.api.AbstractAssert; - -/** Test assertions for {@link LogData}. */ -public class LogDataAssert extends AbstractAssert { - protected LogDataAssert(LogData actual) { - super(actual, LogDataAssert.class); - } - - /** Asserts the {@link Resource} associated with a log matches the expected value. */ - public LogDataAssert hasResource(Resource resource) { - isNotNull(); - if (!actual.getResource().equals(resource)) { - failWithActualExpectedAndMessage( - actual, - "resource: " + resource, - "Expected log to have resource <%s> but found <%s>", - resource, - actual.getResource()); - } - return this; - } - - /** - * Asserts the {@link InstrumentationScopeInfo} associated with a log matches the expected value. - */ - public LogDataAssert hasInstrumentationScope(InstrumentationScopeInfo instrumentationScopeInfo) { - isNotNull(); - if (!actual.getInstrumentationScopeInfo().equals(instrumentationScopeInfo)) { - failWithActualExpectedAndMessage( - actual, - "instrumentation scope: " + instrumentationScopeInfo, - "Expected log to have scope <%s> but found <%s>", - instrumentationScopeInfo, - actual.getInstrumentationScopeInfo()); - } - return this; - } - - /** Asserts the log has the given epoch timestamp. */ - public LogDataAssert hasEpochNanos(long epochNanos) { - isNotNull(); - if (actual.getEpochNanos() != epochNanos) { - failWithActualExpectedAndMessage( - actual.getEpochNanos(), - epochNanos, - "Expected log to have epoch <%s> nanos but was <%s>", - epochNanos, - actual.getEpochNanos()); - } - return this; - } - - /** Asserts the log has the given span context. */ - public LogDataAssert hasSpanContext(SpanContext spanContext) { - isNotNull(); - if (!actual.getSpanContext().equals(spanContext)) { - failWithActualExpectedAndMessage( - actual.getSpanContext(), - spanContext, - "Expected log to have span context <%s> nanos but was <%s>", - spanContext, - actual.getSpanContext()); - } - return this; - } - - /** Asserts the log has the given severity. */ - public LogDataAssert hasSeverity(Severity severity) { - isNotNull(); - if (actual.getSeverity() != severity) { - failWithActualExpectedAndMessage( - actual.getSeverity(), - severity, - "Expected log to have severity <%s> but was <%s>", - severity, - actual.getSeverity()); - } - return this; - } - - /** Asserts the log has the given severity text. */ - public LogDataAssert hasSeverityText(String severityText) { - isNotNull(); - if (!severityText.equals(actual.getSeverityText())) { - failWithActualExpectedAndMessage( - actual.getSeverityText(), - severityText, - "Expected log to have severity text <%s> but was <%s>", - severityText, - actual.getSeverityText()); - } - return this; - } - - /** Asserts the log has the given body. */ - public LogDataAssert hasBody(String body) { - isNotNull(); - if (!actual.getBody().asString().equals(body)) { - failWithActualExpectedAndMessage( - actual.getBody(), - body, - "Expected log to have body <%s> but was <%s>", - body, - actual.getBody().asString()); - } - return this; - } - - /** Asserts the log has the given attributes. */ - public LogDataAssert hasAttributes(Attributes attributes) { - isNotNull(); - if (!attributesAreEqual(attributes)) { - failWithActualExpectedAndMessage( - actual.getAttributes(), - attributes, - "Expected log to have attributes <%s> but was <%s>", - attributes, - actual.getAttributes()); - } - return this; - } - - /** Asserts the log has the given attributes. */ - @SuppressWarnings({"rawtypes", "unchecked"}) - @SafeVarargs - public final LogDataAssert hasAttributes(Map.Entry, ?>... entries) { - AttributesBuilder attributesBuilder = Attributes.builder(); - for (Map.Entry, ?> attr : entries) { - attributesBuilder.put((AttributeKey) attr.getKey(), attr.getValue()); - } - Attributes attributes = attributesBuilder.build(); - return hasAttributes(attributes); - } - - /** Asserts the log has attributes satisfying the given condition. */ - public LogDataAssert hasAttributesSatisfying(Consumer attributes) { - isNotNull(); - assertThat(actual.getAttributes()).as("attributes").satisfies(attributes); - return this; - } - - private boolean attributesAreEqual(Attributes attributes) { - // compare as maps, since implementations do not have equals that work correctly across - // implementations. - return actual.getAttributes().asMap().equals(attributes.asMap()); - } -} diff --git a/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/package-info.java b/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/package-info.java deleted file mode 100644 index c2388a7b6f5..00000000000 --- a/sdk/logs-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.testing.assertj; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/logs-testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java b/sdk/logs-testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java deleted file mode 100644 index 324ce819dab..00000000000 --- a/sdk/logs-testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static io.opentelemetry.sdk.testing.assertj.LogAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Arrays; -import java.util.concurrent.TimeUnit; -import org.junit.jupiter.api.Test; - -public class LogAssertionsTest { - private static final Resource RESOURCE = - Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); - private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("instrumentation_library"); - private static final String TRACE_ID = "00000000000000010000000000000002"; - private static final String SPAN_ID = "0000000000000003"; - private static final Attributes ATTRIBUTES = - Attributes.builder() - .put("bear", "mya") - .put("warm", true) - .put("temperature", 30) - .put("length", 1.2) - .put("colors", "red", "blue") - .put("conditions", false, true) - .put("scores", 0L, 1L) - .put("coins", 0.01, 0.05, 0.1) - .build(); - - private static final LogData LOG_DATA = - LogDataBuilder.create(RESOURCE, INSTRUMENTATION_SCOPE_INFO) - .setEpoch(100, TimeUnit.NANOSECONDS) - .setSpanContext( - SpanContext.create( - TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .setSeverity(Severity.INFO) - .setSeverityText("info") - .setBody("message") - .setAttributes(ATTRIBUTES) - .build(); - - @Test - void passing() { - assertThat(LOG_DATA) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasEpochNanos(100) - .hasSpanContext( - SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) - .hasSeverity(Severity.INFO) - .hasSeverityText("info") - .hasBody("message") - .hasAttributes(ATTRIBUTES) - .hasAttributes( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1)) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .hasSize(8) - .containsEntry(AttributeKey.stringKey("bear"), "mya") - .hasEntrySatisfying( - AttributeKey.stringKey("bear"), value -> assertThat(value).hasSize(3)) - .containsEntry("bear", "mya") - .containsEntry("warm", true) - .containsEntry("temperature", 30) - .containsEntry(AttributeKey.longKey("temperature"), 30L) - .containsEntry(AttributeKey.longKey("temperature"), 30) - .containsEntry("length", 1.2) - .containsEntry("colors", "red", "blue") - .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) - .containsEntry("conditions", false, true) - .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) - .containsEntry("scores", 0L, 1L) - .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) - .containsEntry("coins", 0.01, 0.05, 0.1) - .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) - .containsKey(AttributeKey.stringKey("bear")) - .containsKey("bear") - .containsOnly( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1))); - } - - @Test - void failure() { - assertThatThrownBy(() -> assertThat(LOG_DATA).hasResource(Resource.empty())); - assertThatThrownBy( - () -> assertThat(LOG_DATA).hasInstrumentationScope(InstrumentationScopeInfo.empty())); - assertThatThrownBy(() -> assertThat(LOG_DATA).hasEpochNanos(200)); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasSpanContext( - SpanContext.create( - TRACE_ID, - "0000000000000004", - TraceFlags.getDefault(), - TraceState.getDefault()))); - assertThatThrownBy(() -> assertThat(LOG_DATA).hasSeverity(Severity.DEBUG)); - assertThatThrownBy(() -> assertThat(LOG_DATA).hasSeverityText("warning")); - assertThatThrownBy(() -> assertThat(LOG_DATA).hasBody("bar")); - assertThatThrownBy(() -> assertThat(LOG_DATA).hasAttributes(Attributes.empty())) - .isInstanceOf(AssertionError.class); - assertThatThrownBy(() -> assertThat(LOG_DATA).hasAttributes(attributeEntry("food", "burger"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .containsEntry("cat", "bark"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .containsKey(AttributeKey.stringKey("cat")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes).containsKey("cat"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> OpenTelemetryAssertions.assertThat(attributes).isEmpty())) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> OpenTelemetryAssertions.assertThat(attributes).hasSize(33))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LOG_DATA) - .hasAttributesSatisfying( - attributes -> - OpenTelemetryAssertions.assertThat(attributes) - .hasEntrySatisfying( - AttributeKey.stringKey("bear"), - value -> assertThat(value).hasSize(2)))) - .isInstanceOf(AssertionError.class); - } -} diff --git a/sdk/logs/README.md b/sdk/logs/README.md deleted file mode 100644 index a939cdba53f..00000000000 --- a/sdk/logs/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# OpenTelemetry Experimental Logging Support - -[![Javadocs][javadoc-image]][javadoc-url] - -This project contains experimental support for transport of logs via OpenTelemetry. The API -presented is intended for the use of logging library adapters to enable resource and request -correlation with other observability signals and transport of logs through the OpenTelemetry -collector. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-extension-logging.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-extension-logging diff --git a/sdk/logs/build.gradle.kts b/sdk/logs/build.gradle.kts index 5773999a8d4..38ae98fc8e3 100644 --- a/sdk/logs/build.gradle.kts +++ b/sdk/logs/build.gradle.kts @@ -2,18 +2,43 @@ plugins { id("otel.java-conventions") id("otel.publish-conventions") + id("otel.jmh-conventions") id("otel.animalsniffer-conventions") } -description = "OpenTelemetry Contrib Logging Support" -otelJava.moduleName.set("io.opentelemetry.sdk.extension.logging") +description = "OpenTelemetry Log SDK" +otelJava.moduleName.set("io.opentelemetry.sdk.logs") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) dependencies { + api(project(":api:all")) api(project(":sdk:common")) + compileOnly(project(":api:incubator")) - testImplementation(project(":sdk:logs-testing")) + annotationProcessor("com.google.auto.value:auto-value") + + testImplementation(project(":sdk:testing")) testImplementation("org.awaitility:awaitility") + testImplementation("com.google.guava:guava") +} - annotationProcessor("com.google.auto.value:auto-value") +testing { + suites { + register("testIncubating") { + dependencies { + implementation(project(":sdk:testing")) + implementation(project(":api:incubator")) + implementation("io.opentelemetry.semconv:opentelemetry-semconv-incubating") + implementation("com.google.guava:guava") + } + } + } +} + +tasks { + check { + dependsOn(testing.suites) + } } diff --git a/sdk/logs/gradle.properties b/sdk/logs/gradle.properties deleted file mode 100644 index 4476ae57e31..00000000000 --- a/sdk/logs/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -otel.release=alpha diff --git a/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java b/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java new file mode 100644 index 00000000000..5efaa173e82 --- /dev/null +++ b/sdk/logs/src/jmh/java/io/opentelemetry/sdk/logs/LogsBenchmarks.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static java.util.stream.Collectors.joining; + +import io.opentelemetry.api.logs.Severity; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 10, time = 1) +@Fork(1) +public class LogsBenchmarks { + + private static final Random RANDOM = new Random(); + + @State(Scope.Benchmark) + public static class BenchmarkState { + + private final SdkLoggerProvider sdk = + SdkLoggerProvider.builder() + .addLogRecordProcessor((context, logRecord) -> { + // Do nothing + }) + .build(); + + private List loggerNames; + + @Setup + public void setup() { + int numLoggers = 100; + loggerNames = new ArrayList<>(numLoggers); + for (int i = 0; i < numLoggers; i++) { + loggerNames.add( + IntStream.range(0, 50) + .mapToObj(unused -> String.valueOf((char) RANDOM.nextInt(26))) + .collect(joining())); + } + } + } + + /** + * Simulates the behavior of a log appender implementation, which has to bridge logs from logging + * frameworks (Log4j, Logback, etc). The name of the logger being bridged is used as the + * OpenTelemetry logger name. Therefore, each log processed has to obtain a logger. + */ + @Benchmark + @Threads(1) + public void emitSimpleLog(BenchmarkState benchmarkState) { + String loggerName = + benchmarkState.loggerNames.get(RANDOM.nextInt(benchmarkState.loggerNames.size())); + benchmarkState + .sdk + .get(loggerName) + .logRecordBuilder() + .setBody("log message body") + .setSeverity(Severity.DEBUG) + .emit(); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ExtendedSdkLogRecordBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ExtendedSdkLogRecordBuilder.java new file mode 100644 index 00000000000..8e627207fca --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ExtendedSdkLogRecordBuilder.java @@ -0,0 +1,100 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.incubator.logs.ExtendedLogRecordBuilder; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import javax.annotation.Nullable; + +/** SDK implementation of {@link ExtendedLogRecordBuilder}. */ +final class ExtendedSdkLogRecordBuilder extends SdkLogRecordBuilder + implements ExtendedLogRecordBuilder { + + ExtendedSdkLogRecordBuilder( + LoggerSharedState loggerSharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + SdkLogger logger) { + super(loggerSharedState, instrumentationScopeInfo, logger); + } + + @Override + public ExtendedSdkLogRecordBuilder setEventName(String eventName) { + super.setEventName(eventName); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setException(Throwable throwable) { + super.setException(throwable); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setTimestamp(long timestamp, TimeUnit unit) { + super.setTimestamp(timestamp, unit); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setTimestamp(Instant instant) { + super.setTimestamp(instant); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setObservedTimestamp(long timestamp, TimeUnit unit) { + super.setObservedTimestamp(timestamp, unit); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setObservedTimestamp(Instant instant) { + super.setObservedTimestamp(instant); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setContext(Context context) { + super.setContext(context); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setSeverity(Severity severity) { + super.setSeverity(severity); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setSeverityText(String severityText) { + super.setSeverityText(severityText); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setBody(String body) { + super.setBody(body); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setBody(Value value) { + super.setBody(value); + return this; + } + + @Override + public ExtendedSdkLogRecordBuilder setAttribute(AttributeKey key, @Nullable T value) { + super.setAttribute(key, value); + return this; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ExtendedSdkLogger.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ExtendedSdkLogger.java new file mode 100644 index 00000000000..7940a45d600 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ExtendedSdkLogger.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.incubator.logs.ExtendedLogRecordBuilder; +import io.opentelemetry.api.incubator.logs.ExtendedLogger; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; + +/** SDK implementation of {@link ExtendedLogger}. */ +final class ExtendedSdkLogger extends SdkLogger implements ExtendedLogger { + + ExtendedSdkLogger( + LoggerSharedState loggerSharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + LoggerConfig loggerConfig) { + super(loggerSharedState, instrumentationScopeInfo, loggerConfig); + } + + @Override + public ExtendedLogRecordBuilder logRecordBuilder() { + return (ExtendedLogRecordBuilder) super.logRecordBuilder(); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/IncubatingUtil.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/IncubatingUtil.java new file mode 100644 index 00000000000..f2b3c8473ce --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/IncubatingUtil.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.common.ContextAttributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; + +/** + * Utilities for interacting with {@code io.opentelemetry:opentelemetry-api-incubator}, which is not + * guaranteed to be present on the classpath. For all methods, callers MUST first separately + * reflectively confirm that the incubator is available on the classpath. + */ +final class IncubatingUtil { + + private IncubatingUtil() {} + + static SdkLogger createExtendedLogger( + LoggerSharedState sharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + LoggerConfig tracerConfig) { + return new ExtendedSdkLogger(sharedState, instrumentationScopeInfo, tracerConfig); + } + + static SdkLogRecordBuilder createExtendedLogRecordBuilder( + LoggerSharedState loggerSharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + SdkLogger logger) { + return new ExtendedSdkLogRecordBuilder(loggerSharedState, instrumentationScopeInfo, logger); + } + + static Attributes getContextAttributes(Context context) { + return ContextAttributes.get(context); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogBuilder.java deleted file mode 100644 index af66889c917..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogBuilder.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.logs.data.Severity; -import java.time.Instant; -import java.util.concurrent.TimeUnit; - -/** - * Used to construct and emit logs from a {@link LogEmitter}. - * - *

      Obtain a {@link LogBuilder} via {@link LogEmitter#logBuilder()}, add properties using the - * setters, and emit the log to downstream {@link LogProcessor}(s) by calling {@link #emit()}. - */ -public interface LogBuilder { - - /** Set the epoch timestamp using the timestamp and unit. */ - LogBuilder setEpoch(long timestamp, TimeUnit unit); - - /** Set the epoch timestamp using the instant. */ - LogBuilder setEpoch(Instant instant); - - /** Set the context. */ - LogBuilder setContext(Context context); - - /** Set the severity. */ - LogBuilder setSeverity(Severity severity); - - /** Set the severity text. */ - LogBuilder setSeverityText(String severityText); - - /** Set the body string. */ - LogBuilder setBody(String body); - - /** Set the attributes. */ - LogBuilder setAttributes(Attributes attributes); - - /** Emit the log to downstream {@link LogProcessor}(s). */ - void emit(); -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitter.java deleted file mode 100644 index 37a0a48a822..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitter.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import javax.annotation.concurrent.ThreadSafe; - -/** - * A {@link LogEmitter} is the entry point into a log pipeline. - * - *

      Obtain a log builder via {@link #logBuilder()}, add properties using the setters, and emit it - * to downstream {@link LogProcessor}(s) via {@link LogBuilder#emit()}. - */ -@ThreadSafe -public interface LogEmitter { - - /** - * Return a {@link LogBuilder} to emit a log. - * - *

      Build the log using the {@link LogBuilder} setters, and emit it to downstream {@link - * LogProcessor}(s) via {@link LogBuilder#emit()}. - */ - LogBuilder logBuilder(); -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitterBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitterBuilder.java deleted file mode 100644 index fc055ab2a43..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitterBuilder.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -/** Builder class for creating {@link LogEmitter} instances. */ -public interface LogEmitterBuilder { - - /** - * Assign an OpenTelemetry schema URL to the resulting {@link LogEmitter}. - * - * @param schemaUrl the URL of the OpenTelemetry schema being used by this instrumentation scope - * @return this - */ - LogEmitterBuilder setSchemaUrl(String schemaUrl); - - /** - * Assign a version to the instrumentation scope that is using the resulting {@link LogEmitter}. - * - * @param instrumentationScopeVersion the version of the instrumentation scope - * @return this - */ - LogEmitterBuilder setInstrumentationVersion(String instrumentationScopeVersion); - - /** - * Gets or creates a {@link LogEmitter} instance. - * - * @return a log emitter instance configured with the provided options - */ - LogEmitter build(); -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitterSharedState.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitterSharedState.java deleted file mode 100644 index 0b4e50561e5..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogEmitterSharedState.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.resources.Resource; -import java.util.List; -import java.util.function.Supplier; -import javax.annotation.Nullable; - -/** - * Represents shared state and config between all {@link SdkLogEmitter}s created by the same {@link - * SdkLogEmitterProvider}. - */ -final class LogEmitterSharedState { - private final Object lock = new Object(); - private final Resource resource; - private final Supplier logLimitsSupplier; - private final LogProcessor logProcessor; - private final Clock clock; - @Nullable private volatile CompletableResultCode shutdownResult = null; - - LogEmitterSharedState( - Resource resource, - Supplier logLimitsSupplier, - List logProcessors, - Clock clock) { - this.resource = resource; - this.logLimitsSupplier = logLimitsSupplier; - this.logProcessor = LogProcessor.composite(logProcessors); - this.clock = clock; - } - - Resource getResource() { - return resource; - } - - LogLimits getLogLimits() { - return logLimitsSupplier.get(); - } - - LogProcessor getLogProcessor() { - return logProcessor; - } - - Clock getClock() { - return clock; - } - - boolean hasBeenShutdown() { - return shutdownResult != null; - } - - CompletableResultCode shutdown() { - synchronized (lock) { - if (shutdownResult != null) { - return shutdownResult; - } - shutdownResult = logProcessor.shutdown(); - return shutdownResult; - } - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimits.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimits.java index cd34e7615fd..eb98802acd9 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimits.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimits.java @@ -6,7 +6,7 @@ package io.opentelemetry.sdk.logs; import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.logs.data.LogData; +import io.opentelemetry.sdk.logs.data.LogRecordData; import java.util.function.Supplier; import javax.annotation.concurrent.Immutable; @@ -14,9 +14,10 @@ * Class that holds limits enforced during log recording. * *

      Note: To allow dynamic updates of {@link LogLimits} you should register a {@link - * java.util.function.Supplier} with {@link - * io.opentelemetry.sdk.logs.SdkLogEmitterProviderBuilder#setLogLimits(Supplier)} which supplies - * dynamic configs when queried. + * java.util.function.Supplier} with {@link SdkLoggerProviderBuilder#setLogLimits(Supplier)} which + * supplies dynamic configs when queried. + * + * @since 1.27.0 */ @AutoValue @Immutable @@ -41,9 +42,9 @@ static LogLimits create(int maxNumAttributes, int maxAttributeLength) { LogLimits() {} /** - * Returns the max number of attributes per {@link LogData}. + * Returns the max number of attributes per {@link LogRecordData}. * - * @return the max number of attributes per {@link LogData}. + * @return the max number of attributes per {@link LogRecordData}. */ public abstract int getMaxNumberOfAttributes(); diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimitsBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimitsBuilder.java index 361f9951e8b..f4f74bf5ac3 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimitsBuilder.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogLimitsBuilder.java @@ -6,9 +6,13 @@ package io.opentelemetry.sdk.logs; import io.opentelemetry.api.internal.Utils; -import io.opentelemetry.sdk.logs.data.LogData; +import io.opentelemetry.sdk.logs.data.LogRecordData; -/** Builder for {@link LogLimits}. */ +/** + * Builder for {@link LogLimits}. + * + * @since 1.27.0 + */ public final class LogLimitsBuilder { private static final int DEFAULT_LOG_MAX_NUM_ATTRIBUTES = 128; @@ -20,15 +24,15 @@ public final class LogLimitsBuilder { LogLimitsBuilder() {} /** - * Sets the max number of attributes per {@link LogData}. + * Sets the max number of attributes per {@link LogRecordData}. * - * @param maxNumberOfAttributes the max number of attributes per {@link LogData}. Must be + * @param maxNumberOfAttributes the max number of attributes per {@link LogRecordData}. Must be * positive. * @return this. * @throws IllegalArgumentException if {@code maxNumberOfAttributes} is not positive. */ public LogLimitsBuilder setMaxNumberOfAttributes(int maxNumberOfAttributes) { - Utils.checkArgument(maxNumberOfAttributes > 0, "maxNumberOfAttributes must be greater than 0"); + Utils.checkArgument(maxNumberOfAttributes >= 0, "maxNumberOfAttributes must be non-negative"); this.maxNumAttributes = maxNumberOfAttributes; return this; } @@ -44,7 +48,7 @@ public LogLimitsBuilder setMaxNumberOfAttributes(int maxNumberOfAttributes) { */ public LogLimitsBuilder setMaxAttributeValueLength(int maxAttributeValueLength) { Utils.checkArgument( - maxAttributeValueLength > -1, "maxAttributeValueLength must be non-negative"); + maxAttributeValueLength >= 0, "maxAttributeValueLength must be non-negative"); this.maxAttributeValueLength = maxAttributeValueLength; return this; } diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogProcessor.java deleted file mode 100644 index 77a6cbb8858..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogProcessor.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import java.io.Closeable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.TimeUnit; -import javax.annotation.concurrent.ThreadSafe; - -/** - * {@link LogProcessor} is the interface to allow synchronous hooks for logs emitted by {@link - * LogEmitter}s. - */ -@ThreadSafe -public interface LogProcessor extends Closeable { - - /** - * Returns a {@link LogProcessor} which simply delegates to all processing to the {@code - * processors} in order. - */ - static LogProcessor composite(LogProcessor... processors) { - return composite(Arrays.asList(processors)); - } - - /** - * Returns a {@link LogProcessor} which simply delegates to all processing to the {@code - * processors} in order. - */ - static LogProcessor composite(Iterable processors) { - List processorList = new ArrayList<>(); - for (LogProcessor processor : processors) { - processorList.add(processor); - } - if (processorList.isEmpty()) { - return NoopLogProcessor.getInstance(); - } - if (processorList.size() == 1) { - return processorList.get(0); - } - return MultiLogProcessor.create(processorList); - } - - /** - * Emit a log. - * - * @param logData the log - */ - void emit(LogData logData); - - /** - * Shutdown the log processor. - * - * @return result - */ - default CompletableResultCode shutdown() { - return forceFlush(); - } - - /** - * Process all logs that have not yet been processed. - * - * @return result - */ - default CompletableResultCode forceFlush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Closes this {@link LogProcessor} after processing any remaining logs, releasing any resources. - */ - @Override - default void close() { - shutdown().join(10, TimeUnit.SECONDS); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogRecordProcessor.java new file mode 100644 index 00000000000..a14acaa042d --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LogRecordProcessor.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import javax.annotation.concurrent.ThreadSafe; + +/** + * {@link LogRecordProcessor} is the interface to allow synchronous hooks for log records emitted by + * {@link Logger}s. + * + * @since 1.27.0 + */ +@ThreadSafe +public interface LogRecordProcessor extends Closeable { + + /** + * Returns a {@link LogRecordProcessor} which simply delegates to all processing to the {@code + * processors} in order. + */ + static LogRecordProcessor composite(LogRecordProcessor... processors) { + return composite(Arrays.asList(processors)); + } + + /** + * Returns a {@link LogRecordProcessor} which simply delegates to all processing to the {@code + * processors} in order. + */ + static LogRecordProcessor composite(Iterable processors) { + List processorList = new ArrayList<>(); + for (LogRecordProcessor processor : processors) { + processorList.add(processor); + } + if (processorList.isEmpty()) { + return NoopLogRecordProcessor.getInstance(); + } + if (processorList.size() == 1) { + return processorList.get(0); + } + return MultiLogRecordProcessor.create(processorList); + } + + /** + * Called when a {@link Logger} {@link LogRecordBuilder#emit()}s a log record. + * + * @param context the context set via {@link LogRecordBuilder#setContext(Context)}, or {@link + * Context#current()} if not explicitly set + * @param logRecord the log record + */ + void onEmit(Context context, ReadWriteLogRecord logRecord); + + /** + * Shutdown the log processor. + * + * @return result + */ + default CompletableResultCode shutdown() { + return forceFlush(); + } + + /** + * Process all log records that have not yet been processed. + * + * @return result + */ + default CompletableResultCode forceFlush() { + return CompletableResultCode.ofSuccess(); + } + + /** + * Closes this {@link LogRecordProcessor} after processing any remaining log records, releasing + * any resources. + */ + @Override + default void close() { + shutdown().join(10, TimeUnit.SECONDS); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LoggerSharedState.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LoggerSharedState.java new file mode 100644 index 00000000000..d7f13c4f70e --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/LoggerSharedState.java @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.util.function.BiPredicate; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * Represents shared state and config between all {@link SdkLogger}s created by the same {@link + * SdkLoggerProvider}. + */ +final class LoggerSharedState { + private final Object lock = new Object(); + private final SdkResourceProvider resourceProvider; + private final Supplier logLimitsSupplier; + private final LogRecordProcessor logRecordProcessor; + private final Clock clock; + private final ExceptionAttributeResolver exceptionAttributeResolver; + private final SdkLoggerInstrumentation loggerInstrumentation; + + @Nullable + private final BiPredicate> + contextScopedAttributesFilter; + + @Nullable private volatile CompletableResultCode shutdownResult = null; + + LoggerSharedState( + SdkResourceProvider resourceProvider, + Supplier logLimitsSupplier, + LogRecordProcessor logRecordProcessor, + Clock clock, + ExceptionAttributeResolver exceptionAttributeResolver, + SdkLoggerInstrumentation loggerInstrumentation, + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.resourceProvider = resourceProvider; + this.logLimitsSupplier = logLimitsSupplier; + this.logRecordProcessor = logRecordProcessor; + this.clock = clock; + this.exceptionAttributeResolver = exceptionAttributeResolver; + this.loggerInstrumentation = loggerInstrumentation; + this.contextScopedAttributesFilter = contextScopedAttributesFilter; + } + + Resource getResource() { + return resourceProvider.getResource(); + } + + LogLimits getLogLimits() { + return logLimitsSupplier.get(); + } + + LogRecordProcessor getLogRecordProcessor() { + return logRecordProcessor; + } + + Clock getClock() { + return clock; + } + + ExceptionAttributeResolver getExceptionAttributeResolver() { + return exceptionAttributeResolver; + } + + SdkLoggerInstrumentation getLoggerInstrumentation() { + return loggerInstrumentation; + } + + @Nullable + BiPredicate> getContextScopedAttributesFilter() { + return contextScopedAttributesFilter; + } + + boolean hasBeenShutdown() { + return shutdownResult != null; + } + + CompletableResultCode shutdown() { + synchronized (lock) { + if (shutdownResult != null) { + return shutdownResult; + } + shutdownResult = logRecordProcessor.shutdown(); + return shutdownResult; + } + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/MultiLogProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/MultiLogProcessor.java deleted file mode 100644 index 8f07c00a3b6..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/MultiLogProcessor.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Implementation of {@link LogProcessor} that forwards all logs to a list of {@link LogProcessor}s. - */ -final class MultiLogProcessor implements LogProcessor { - - private final List logProcessors; - private final AtomicBoolean isShutdown = new AtomicBoolean(false); - - /** - * Create a new {@link MultiLogProcessor}. - * - * @param logProcessorsList list of log processors to forward logs to - * @return a multi log processor instance - */ - static LogProcessor create(List logProcessorsList) { - return new MultiLogProcessor( - new ArrayList<>(Objects.requireNonNull(logProcessorsList, "logProcessorsList"))); - } - - @Override - public void emit(LogData logData) { - for (LogProcessor logProcessor : logProcessors) { - logProcessor.emit(logData); - } - } - - @Override - public CompletableResultCode shutdown() { - if (isShutdown.getAndSet(true)) { - return CompletableResultCode.ofSuccess(); - } - List results = new ArrayList<>(logProcessors.size()); - for (LogProcessor logProcessor : logProcessors) { - results.add(logProcessor.shutdown()); - } - return CompletableResultCode.ofAll(results); - } - - @Override - public CompletableResultCode forceFlush() { - List results = new ArrayList<>(logProcessors.size()); - for (LogProcessor logProcessor : logProcessors) { - results.add(logProcessor.forceFlush()); - } - return CompletableResultCode.ofAll(results); - } - - private MultiLogProcessor(List logProcessorsList) { - this.logProcessors = logProcessorsList; - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/MultiLogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/MultiLogRecordProcessor.java new file mode 100644 index 00000000000..e84b38c86b6 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/MultiLogRecordProcessor.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +/** + * Implementation of {@link LogRecordProcessor} that forwards all logs to a list of {@link + * LogRecordProcessor}s. + */ +final class MultiLogRecordProcessor implements LogRecordProcessor { + + private final List logRecordProcessors; + private final AtomicBoolean isShutdown = new AtomicBoolean(false); + + /** + * Create a new {@link MultiLogRecordProcessor}. + * + * @param logRecordProcessorsList list of log processors to forward logs to + * @return a multi log processor instance + */ + static LogRecordProcessor create(List logRecordProcessorsList) { + return new MultiLogRecordProcessor( + new ArrayList<>( + Objects.requireNonNull(logRecordProcessorsList, "logRecordProcessorsList"))); + } + + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) { + for (LogRecordProcessor logRecordProcessor : logRecordProcessors) { + logRecordProcessor.onEmit(context, logRecord); + } + } + + @Override + public CompletableResultCode shutdown() { + if (isShutdown.getAndSet(true)) { + return CompletableResultCode.ofSuccess(); + } + List results = new ArrayList<>(logRecordProcessors.size()); + for (LogRecordProcessor logRecordProcessor : logRecordProcessors) { + results.add(logRecordProcessor.shutdown()); + } + return CompletableResultCode.ofAll(results); + } + + @Override + public CompletableResultCode forceFlush() { + List results = new ArrayList<>(logRecordProcessors.size()); + for (LogRecordProcessor logRecordProcessor : logRecordProcessors) { + results.add(logRecordProcessor.forceFlush()); + } + return CompletableResultCode.ofAll(results); + } + + private MultiLogRecordProcessor(List logRecordProcessorsList) { + this.logRecordProcessors = logRecordProcessorsList; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/NoopLogProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/NoopLogProcessor.java deleted file mode 100644 index a7ef2f2f22d..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/NoopLogProcessor.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.logs.data.LogData; - -final class NoopLogProcessor implements LogProcessor { - private static final NoopLogProcessor INSTANCE = new NoopLogProcessor(); - - static LogProcessor getInstance() { - return INSTANCE; - } - - private NoopLogProcessor() {} - - @Override - public void emit(LogData logData) {} -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/NoopLogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/NoopLogRecordProcessor.java new file mode 100644 index 00000000000..31f3350f13e --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/NoopLogRecordProcessor.java @@ -0,0 +1,26 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.context.Context; + +final class NoopLogRecordProcessor implements LogRecordProcessor { + private static final NoopLogRecordProcessor INSTANCE = new NoopLogRecordProcessor(); + + static LogRecordProcessor getInstance() { + return INSTANCE; + } + + private NoopLogRecordProcessor() {} + + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) {} + + @Override + public String toString() { + return "NoopLogRecordProcessor"; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ReadWriteLogRecord.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ReadWriteLogRecord.java new file mode 100644 index 00000000000..83d1d993095 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/ReadWriteLogRecord.java @@ -0,0 +1,149 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import javax.annotation.Nullable; + +/** + * A log record that can be read from and written to. + * + * @since 1.27.0 + */ +public interface ReadWriteLogRecord { + + /** + * Sets an attribute on the log record. If the log record previously contained a mapping for the + * key, the old value is replaced by the specified value. + * + *

      Note: the behavior of null values is undefined, and hence strongly discouraged. + */ + ReadWriteLogRecord setAttribute(AttributeKey key, T value); + + // TODO: add additional setters + + /** + * Sets attributes to the {@link ReadWriteLogRecord}. If the {@link ReadWriteLogRecord} previously + * contained a mapping for any of the keys, the old values are replaced by the specified values. + * + * @param attributes the attributes + * @return this. + * @since 1.31.0 + */ + @SuppressWarnings("unchecked") + default ReadWriteLogRecord setAllAttributes(Attributes attributes) { + if (attributes == null || attributes.isEmpty()) { + return this; + } + attributes.forEach( + (attributeKey, value) -> this.setAttribute((AttributeKey) attributeKey, value)); + return this; + } + + /** Return an immutable {@link LogRecordData} instance representing this log record. */ + LogRecordData toLogRecordData(); + + /** + * Returns the log record event name, or {@code null} if none is set. + * + * @since 1.50.0 + */ + @Nullable + default String getEventName() { + return toLogRecordData().getEventName(); + } + + /** + * Returns the value of a given attribute if it exists. This is the equivalent of calling {@code + * getAttributes().get(key)}. + * + * @since 1.46.0 + */ + @Nullable + default T getAttribute(AttributeKey key) { + return toLogRecordData().getAttributes().get(key); + } + + /** + * Returns the instrumentation scope that generated this log. + * + * @since 1.46.0 + */ + default InstrumentationScopeInfo getInstrumentationScopeInfo() { + return toLogRecordData().getInstrumentationScopeInfo(); + } + + /** + * Returns the timestamp at which the log record occurred, in epoch nanos. + * + * @since 1.46.0 + */ + default long getTimestampEpochNanos() { + return toLogRecordData().getTimestampEpochNanos(); + } + + /** + * Returns the timestamp at which the log record was observed, in epoch nanos. + * + * @since 1.46.0 + */ + default long getObservedTimestampEpochNanos() { + return toLogRecordData().getObservedTimestampEpochNanos(); + } + + /** + * Return the span context for this log, or {@link SpanContext#getInvalid()} if unset. + * + * @since 1.46.0 + */ + default SpanContext getSpanContext() { + return toLogRecordData().getSpanContext(); + } + + /** + * Returns the severity for this log, or {@link Severity#UNDEFINED_SEVERITY_NUMBER} if unset. + * + * @since 1.46.0 + */ + default Severity getSeverity() { + return toLogRecordData().getSeverity(); + } + + /** + * Returns the severity text for this log, or null if unset. + * + * @since 1.46.0 + */ + @Nullable + default String getSeverityText() { + return toLogRecordData().getSeverityText(); + } + + /** + * Returns the {@link Value} representation of the log body, of null if unset. + * + * @since 1.46.0 + */ + @Nullable + default Value getBodyValue() { + return toLogRecordData().getBodyValue(); + } + + /** + * Returns the attributes for this log, or {@link Attributes#empty()} if unset. + * + * @since 1.46.0 + */ + default Attributes getAttributes() { + return toLogRecordData().getAttributes(); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogBuilder.java deleted file mode 100644 index 437fba19eb6..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogBuilder.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.AttributeUtil; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import java.time.Instant; -import java.util.concurrent.TimeUnit; - -/** {@link SdkLogBuilder} is the SDK implementation of {@link LogBuilder}. */ -final class SdkLogBuilder implements LogBuilder { - - private final LogDataBuilder logDataBuilder; - private final LogEmitterSharedState logEmitterSharedState; - private final LogLimits logLimits; - - SdkLogBuilder(LogEmitterSharedState logEmitterSharedState, LogDataBuilder logDataBuilder) { - this.logEmitterSharedState = logEmitterSharedState; - this.logDataBuilder = logDataBuilder; - this.logLimits = logEmitterSharedState.getLogLimits(); - } - - @Override - public LogBuilder setEpoch(long timestamp, TimeUnit unit) { - logDataBuilder.setEpoch(timestamp, unit); - return this; - } - - @Override - public LogBuilder setEpoch(Instant instant) { - logDataBuilder.setEpoch(instant); - return this; - } - - @Override - public LogBuilder setContext(Context context) { - logDataBuilder.setContext(context); - return this; - } - - @Override - public LogBuilder setSeverity(Severity severity) { - logDataBuilder.setSeverity(severity); - return this; - } - - @Override - public LogBuilder setSeverityText(String severityText) { - logDataBuilder.setSeverityText(severityText); - return this; - } - - @Override - public LogBuilder setBody(String body) { - logDataBuilder.setBody(body); - return this; - } - - @Override - public LogBuilder setAttributes(Attributes attributes) { - logDataBuilder.setAttributes( - AttributeUtil.applyAttributesLimit( - attributes, - logLimits.getMaxNumberOfAttributes(), - logLimits.getMaxAttributeValueLength())); - return this; - } - - @Override - public void emit() { - if (logEmitterSharedState.hasBeenShutdown()) { - return; - } - logEmitterSharedState.getLogProcessor().emit(logDataBuilder.build()); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitter.java deleted file mode 100644 index cf9d60439ff..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitter.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; - -/** SDK implementation of {@link LogEmitter}. */ -final class SdkLogEmitter implements LogEmitter { - - private final LogEmitterSharedState logEmitterSharedState; - private final InstrumentationScopeInfo instrumentationScopeInfo; - - SdkLogEmitter( - LogEmitterSharedState logEmitterSharedState, - InstrumentationScopeInfo instrumentationScopeInfo) { - this.logEmitterSharedState = logEmitterSharedState; - this.instrumentationScopeInfo = instrumentationScopeInfo; - } - - @Override - public LogBuilder logBuilder() { - LogDataBuilder logDataBuilder = - LogDataBuilder.create( - logEmitterSharedState.getResource(), - instrumentationScopeInfo, - logEmitterSharedState.getClock()); - return new SdkLogBuilder(logEmitterSharedState, logDataBuilder); - } - - // VisibleForTesting - InstrumentationScopeInfo getInstrumentationScopeInfo() { - return instrumentationScopeInfo; - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterBuilder.java deleted file mode 100644 index f4eef291354..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterBuilder.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.internal.ComponentRegistry; -import javax.annotation.Nullable; - -final class SdkLogEmitterBuilder implements LogEmitterBuilder { - - private final ComponentRegistry registry; - private final String instrumentationScopeName; - @Nullable private String instrumentationScopeVersion; - @Nullable private String schemaUrl; - - SdkLogEmitterBuilder(ComponentRegistry registry, String instrumentationScopeName) { - this.registry = registry; - this.instrumentationScopeName = instrumentationScopeName; - } - - @Override - public SdkLogEmitterBuilder setSchemaUrl(String schemaUrl) { - this.schemaUrl = schemaUrl; - return this; - } - - @Override - public SdkLogEmitterBuilder setInstrumentationVersion(String instrumentationScopeVersion) { - this.instrumentationScopeVersion = instrumentationScopeVersion; - return this; - } - - @Override - public SdkLogEmitter build() { - return registry.get(instrumentationScopeName, instrumentationScopeVersion, schemaUrl); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterProvider.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterProvider.java deleted file mode 100644 index b2d14e52cf0..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterProvider.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ComponentRegistry; -import io.opentelemetry.sdk.resources.Resource; -import java.io.Closeable; -import java.util.List; -import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** SDK registry for creating {@link LogEmitter}s. */ -public final class SdkLogEmitterProvider implements Closeable { - - static final String DEFAULT_EMITTER_NAME = "unknown"; - private static final Logger LOGGER = Logger.getLogger(SdkLogEmitterProvider.class.getName()); - - private final LogEmitterSharedState sharedState; - private final ComponentRegistry logEmitterComponentRegistry; - - /** - * Returns a new {@link SdkLogEmitterProviderBuilder} for {@link SdkLogEmitterProvider}. - * - * @return a new builder instance - */ - public static SdkLogEmitterProviderBuilder builder() { - return new SdkLogEmitterProviderBuilder(); - } - - SdkLogEmitterProvider( - Resource resource, - Supplier logLimitsSupplier, - List processors, - Clock clock) { - this.sharedState = new LogEmitterSharedState(resource, logLimitsSupplier, processors, clock); - this.logEmitterComponentRegistry = - new ComponentRegistry<>( - instrumentationScopeInfo -> new SdkLogEmitter(sharedState, instrumentationScopeInfo)); - } - - /** - * Gets or creates a named log emitter instance. - * - * @param instrumentationScopeName A name uniquely identifying the instrumentation scope, such as - * the instrumentation library, package, or fully qualified class name. Must not be null. - * @return a log emitter instance - */ - public LogEmitter get(String instrumentationScopeName) { - return logEmitterBuilder(instrumentationScopeName).build(); - } - - /** - * Creates a {@link LogEmitterBuilder} instance. - * - * @param instrumentationScopeName the name of the instrumentation scope - * @return a log emitter builder instance - */ - public LogEmitterBuilder logEmitterBuilder(String instrumentationScopeName) { - if (instrumentationScopeName == null || instrumentationScopeName.isEmpty()) { - LOGGER.fine("LogEmitter requested without instrumentation scope name."); - instrumentationScopeName = DEFAULT_EMITTER_NAME; - } - return new SdkLogEmitterBuilder(logEmitterComponentRegistry, instrumentationScopeName); - } - - /** - * Request the active log processor to process all logs that have not yet been processed. - * - * @return a {@link CompletableResultCode} which is completed when the flush is finished - */ - public CompletableResultCode forceFlush() { - return sharedState.getLogProcessor().forceFlush(); - } - - /** - * Attempt to shut down the active log processor. - * - * @return a {@link CompletableResultCode} which is completed when the active log process has been - * shut down. - */ - public CompletableResultCode shutdown() { - if (sharedState.hasBeenShutdown()) { - LOGGER.log(Level.WARNING, "Calling shutdown() multiple times."); - return CompletableResultCode.ofSuccess(); - } - return sharedState.shutdown(); - } - - @Override - public void close() { - shutdown().join(10, TimeUnit.SECONDS); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterProviderBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterProviderBuilder.java deleted file mode 100644 index 315c5234a67..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogEmitterProviderBuilder.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static java.util.Objects.requireNonNull; - -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Supplier; - -/** Builder class for {@link SdkLogEmitterProvider} instances. */ -public final class SdkLogEmitterProviderBuilder { - - private final List logProcessors = new ArrayList<>(); - private Resource resource = Resource.getDefault(); - private Supplier logLimitsSupplier = LogLimits::getDefault; - private Clock clock = Clock.getDefault(); - - SdkLogEmitterProviderBuilder() {} - - /** - * Assign a {@link Resource} to be attached to all {@link LogData} created by {@link LogEmitter}s - * obtained from the {@link SdkLogEmitterProvider}. - * - * @param resource the resource - * @return this - */ - public SdkLogEmitterProviderBuilder setResource(Resource resource) { - requireNonNull(resource, "resource"); - this.resource = resource; - return this; - } - - /** - * Assign a {@link Supplier} of {@link LogLimits}. {@link LogLimits} will be retrieved each time a - * {@link LogEmitter#logBuilder()} is called. - * - *

      The {@code logLimitsSupplier} must be thread-safe and return immediately (no remote calls, - * as contention free as possible). - * - * @param logLimitsSupplier the supplier that will be used to retrieve the {@link LogLimits} for - * every {@link LogBuilder}. - * @return this - */ - public SdkLogEmitterProviderBuilder setLogLimits(Supplier logLimitsSupplier) { - requireNonNull(logLimitsSupplier, "logLimitsSupplier"); - this.logLimitsSupplier = logLimitsSupplier; - return this; - } - - /** - * Add a log processor. {@link LogProcessor#emit(LogData)} will be called each time a log is - * emitted by {@link LogEmitter} instances obtained from the {@link SdkLogEmitterProvider}. - * - * @param processor the log processor - * @return this - */ - public SdkLogEmitterProviderBuilder addLogProcessor(LogProcessor processor) { - requireNonNull(processor, "processor"); - logProcessors.add(processor); - return this; - } - - /** - * Assign a {@link Clock}. The {@link Clock} may be used to determine "now" in the event that the - * epoch millis are not set directly. - * - *

      The {@code clock} must be thread-safe and return immediately (no remote calls, as contention - * free as possible). - * - * @param clock The clock to use for all temporal needs. - * @return this - */ - public SdkLogEmitterProviderBuilder setClock(Clock clock) { - requireNonNull(clock, "clock"); - this.clock = clock; - return this; - } - - /** - * Create a {@link SdkLogEmitterProvider} instance. - * - * @return an instance configured with the provided options - */ - public SdkLogEmitterProvider build() { - return new SdkLogEmitterProvider(resource, logLimitsSupplier, logProcessors, clock); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilder.java new file mode 100644 index 00000000000..781d6581565 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilder.java @@ -0,0 +1,225 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.AttributesMap; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import java.util.function.BiPredicate; +import javax.annotation.Nullable; + +/** + * SDK implementation of {@link LogRecordBuilder}. + * + *

      Note: When context-scoped attributes are enabled, {@link #emit()} mutates the builder's + * internal attribute storage in-place by appending filtered context-scoped attributes, then + * transfers ownership of that attribute map directly to the created {@link ReadWriteLogRecord}. + * Consequently, builder instances are single-use lifecycle objects and reusing a builder across + * multiple {@link #emit()} calls is unsupported. + */ +class SdkLogRecordBuilder implements LogRecordBuilder { + + private final LoggerSharedState loggerSharedState; + private final LogLimits logLimits; + private final SdkLogger logger; + + private final InstrumentationScopeInfo instrumentationScopeInfo; + private long timestampEpochNanos; + private long observedTimestampEpochNanos; + @Nullable private Context context; + private Severity severity = Severity.UNDEFINED_SEVERITY_NUMBER; + @Nullable private String severityText; + @Nullable private Value body; + @Nullable private String eventName; + @Nullable private AttributesMap attributes; + + SdkLogRecordBuilder( + LoggerSharedState loggerSharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + SdkLogger logger) { + this.loggerSharedState = loggerSharedState; + this.logLimits = loggerSharedState.getLogLimits(); + this.instrumentationScopeInfo = instrumentationScopeInfo; + this.logger = logger; + } + + @Override + public SdkLogRecordBuilder setEventName(String eventName) { + this.eventName = eventName; + return this; + } + + @Override + public SdkLogRecordBuilder setTimestamp(long timestamp, TimeUnit unit) { + this.timestampEpochNanos = unit.toNanos(timestamp); + return this; + } + + @Override + public SdkLogRecordBuilder setTimestamp(Instant instant) { + this.timestampEpochNanos = + TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano(); + return this; + } + + @Override + public LogRecordBuilder setObservedTimestamp(long timestamp, TimeUnit unit) { + this.observedTimestampEpochNanos = unit.toNanos(timestamp); + return this; + } + + @Override + public LogRecordBuilder setObservedTimestamp(Instant instant) { + this.observedTimestampEpochNanos = + TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano(); + return this; + } + + @Override + public SdkLogRecordBuilder setContext(Context context) { + this.context = context; + return this; + } + + @Override + public SdkLogRecordBuilder setSeverity(Severity severity) { + this.severity = severity; + return this; + } + + @Override + public SdkLogRecordBuilder setSeverityText(String severityText) { + this.severityText = severityText; + return this; + } + + @Override + public SdkLogRecordBuilder setBody(String body) { + return setBody(Value.of(body)); + } + + @Override + public SdkLogRecordBuilder setBody(Value value) { + this.body = value; + return this; + } + + @Override + public SdkLogRecordBuilder setException(Throwable throwable) { + if (throwable == null) { + return this; + } + + loggerSharedState + .getExceptionAttributeResolver() + .setExceptionAttributes( + this::setExceptionAttribute, + throwable, + loggerSharedState.getLogLimits().getMaxAttributeValueLength()); + + return this; + } + + @Override + public SdkLogRecordBuilder setAttribute(AttributeKey key, @Nullable T value) { + if (key == null || key.getKey().isEmpty() || value == null) { + return this; + } + if (this.attributes == null) { + this.attributes = + AttributesMap.create( + logLimits.getMaxNumberOfAttributes(), logLimits.getMaxAttributeValueLength()); + } + this.attributes.put(key, value); + return this; + } + + @Override + public void emit() { + if (loggerSharedState.hasBeenShutdown()) { + return; + } + Context context = this.context == null ? Context.current() : this.context; + if (!logger.isEnabled(severity, context)) { + return; + } + long observedTimestampEpochNanos = + this.observedTimestampEpochNanos == 0 + ? this.loggerSharedState.getClock().now() + : this.observedTimestampEpochNanos; + + loggerSharedState.getLoggerInstrumentation().emitLog(); + loggerSharedState + .getLogRecordProcessor() + .onEmit(context, createLogRecord(context, observedTimestampEpochNanos)); + } + + /** + * Sets an exception-derived attribute only if it hasn't already been set by the user. This + * ensures user-set attributes take precedence over exception-derived attributes. + */ + protected void setExceptionAttribute(AttributeKey key, @Nullable T value) { + if (key == null || key.getKey().isEmpty() || value == null) { + return; + } + if (attributes == null || attributes.get(key) == null) { + setAttribute(key, value); + } + } + + @SuppressWarnings("rawtypes") + private void populateContextAttributes(Context context) { + BiPredicate> filter = + loggerSharedState.getContextScopedAttributesFilter(); + if (filter == null || !SdkLogger.INCUBATOR_AVAILABLE) { + return; + } + Attributes contextAttributes = IncubatingUtil.getContextAttributes(context); + if (contextAttributes.isEmpty()) { + return; + } + AttributesMap attrs = this.attributes; + if (attrs == null) { + attrs = + AttributesMap.create( + logLimits.getMaxNumberOfAttributes(), logLimits.getMaxAttributeValueLength()); + this.attributes = attrs; + } + AttributesMap nonNullAttrs = attrs; + contextAttributes.forEach((key, value) -> { + if (!filter.test(instrumentationScopeInfo, key)) { + return; + } + if (!nonNullAttrs.containsKey(key.getKey())) { + nonNullAttrs.put((AttributeKey) key, value); + } + }); + } + + protected ReadWriteLogRecord createLogRecord(Context context, long observedTimestampEpochNanos) { + populateContextAttributes(context); + return SdkReadWriteLogRecord.create( + loggerSharedState.getLogLimits(), + loggerSharedState.getResource(), + instrumentationScopeInfo, + timestampEpochNanos, + observedTimestampEpochNanos, + Span.fromContext(context).getSpanContext(), + severity, + severityText, + body, + attributes, + eventName); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogRecordData.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogRecordData.java new file mode 100644 index 00000000000..3f0e4f72af4 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogRecordData.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.Body; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +@AutoValue +@AutoValue.CopyAnnotations +@Immutable +abstract class SdkLogRecordData implements LogRecordData { + + SdkLogRecordData() {} + + static SdkLogRecordData create( + Resource resource, + InstrumentationScopeInfo instrumentationScopeInfo, + long epochNanos, + long observedEpochNanos, + SpanContext spanContext, + Severity severity, + @Nullable String severityText, + @Nullable Value body, + Attributes attributes, + int totalAttributeCount, + @Nullable String eventName) { + return new AutoValue_SdkLogRecordData( + resource, + instrumentationScopeInfo, + epochNanos, + observedEpochNanos, + spanContext, + severity, + severityText, + attributes, + totalAttributeCount, + body, + eventName); + } + + @Override + @Nullable + public abstract Value getBodyValue(); + + @Override + @Nullable + public abstract String getEventName(); + + @Override + @SuppressWarnings("deprecation") // Implementation of deprecated method + public Body getBody() { + Value valueBody = getBodyValue(); + return valueBody == null ? Body.empty() : Body.string(valueBody.asString()); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogger.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogger.java new file mode 100644 index 00000000000..69f181d5774 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLogger.java @@ -0,0 +1,104 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; + +/** SDK implementation of {@link Logger}. */ +class SdkLogger implements Logger { + + private static final Logger NOOP_LOGGER = LoggerProvider.noop().get("noop"); + static final boolean INCUBATOR_AVAILABLE; + + static { + boolean incubatorAvailable = false; + try { + Class.forName("io.opentelemetry.api.incubator.logs.ExtendedDefaultLoggerProvider"); + incubatorAvailable = true; + } catch (ClassNotFoundException e) { + // Not available + } + INCUBATOR_AVAILABLE = incubatorAvailable; + } + + private final LoggerSharedState loggerSharedState; + private final InstrumentationScopeInfo instrumentationScopeInfo; + + protected volatile boolean loggerEnabled; + protected volatile Severity minimumSeverity; + protected volatile boolean traceBased; + + SdkLogger( + LoggerSharedState loggerSharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + LoggerConfig loggerConfig) { + this.loggerSharedState = loggerSharedState; + this.instrumentationScopeInfo = instrumentationScopeInfo; + this.loggerEnabled = loggerConfig.isEnabled(); + this.minimumSeverity = loggerConfig.getMinimumSeverity(); + this.traceBased = loggerConfig.isTraceBased(); + } + + static SdkLogger create( + LoggerSharedState sharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + LoggerConfig loggerConfig) { + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedLogger(sharedState, instrumentationScopeInfo, loggerConfig) + : new SdkLogger(sharedState, instrumentationScopeInfo, loggerConfig); + } + + @Override + public boolean isEnabled(Severity severity, Context context) { + if (!loggerEnabled) { + return false; + } + + if (severity != Severity.UNDEFINED_SEVERITY_NUMBER + && severity.getSeverityNumber() < minimumSeverity.getSeverityNumber()) { + return false; + } + + if (traceBased) { + SpanContext spanContext = Span.fromContext(context).getSpanContext(); + if (spanContext.isValid() && !spanContext.getTraceFlags().isSampled()) { + return false; + } + } + + return true; + } + + @Override + public LogRecordBuilder logRecordBuilder() { + if (loggerEnabled) { + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedLogRecordBuilder( + loggerSharedState, instrumentationScopeInfo, this) + : new SdkLogRecordBuilder(loggerSharedState, instrumentationScopeInfo, this); + } + return NOOP_LOGGER.logRecordBuilder(); + } + + // VisibleForTesting + InstrumentationScopeInfo getInstrumentationScopeInfo() { + return instrumentationScopeInfo; + } + + void updateLoggerConfig(LoggerConfig loggerConfig) { + loggerEnabled = loggerConfig.isEnabled(); + minimumSeverity = loggerConfig.getMinimumSeverity(); + traceBased = loggerConfig.isTraceBased(); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerBuilder.java new file mode 100644 index 00000000000..9cf083f7a2d --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerBuilder.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.LoggerBuilder; +import io.opentelemetry.sdk.common.internal.ComponentRegistry; +import javax.annotation.Nullable; + +final class SdkLoggerBuilder implements LoggerBuilder { + + private final ComponentRegistry registry; + private final String instrumentationScopeName; + @Nullable private String instrumentationScopeVersion; + @Nullable private String schemaUrl; + + SdkLoggerBuilder(ComponentRegistry registry, String instrumentationScopeName) { + this.registry = registry; + this.instrumentationScopeName = instrumentationScopeName; + } + + @Override + public SdkLoggerBuilder setSchemaUrl(String schemaUrl) { + this.schemaUrl = schemaUrl; + return this; + } + + @Override + public SdkLoggerBuilder setInstrumentationVersion(String instrumentationScopeVersion) { + this.instrumentationScopeVersion = instrumentationScopeVersion; + return this; + } + + @Override + public SdkLogger build() { + return registry.get( + instrumentationScopeName, instrumentationScopeVersion, schemaUrl, Attributes.empty()); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerInstrumentation.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerInstrumentation.java new file mode 100644 index 00000000000..6f06ace5e19 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerInstrumentation.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * SDK metrics exported for emitted logs as defined in the semantic + * conventions. + */ +final class SdkLoggerInstrumentation { + private final Object lock = new Object(); + + private final Supplier meterProvider; + + @Nullable private Meter meter; + @Nullable private volatile LongCounter createdLogs; + + SdkLoggerInstrumentation(Supplier meterProvider) { + this.meterProvider = meterProvider; + } + + void emitLog() { + createdLogs().add(1); + } + + private LongCounter createdLogs() { + LongCounter createdLogs = this.createdLogs; + if (createdLogs == null) { + synchronized (lock) { + createdLogs = this.createdLogs; + if (createdLogs == null) { + createdLogs = + meter() + .counterBuilder(SemConvConstants.OTEL_SDK_LOG_CREATED_NAME) + .setUnit(SemConvConstants.OTEL_SDK_LOG_CREATED_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_LOG_CREATED_DESCRIPTION) + .build(); + this.createdLogs = createdLogs; + } + } + } + return createdLogs; + } + + private Meter meter() { + if (meter == null) { + // Safe to call from multiple threads. + meter = meterProvider.get().get("io.opentelemetry.sdk.logs"); + } + return meter; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java new file mode 100644 index 00000000000..820245e46a2 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProvider.java @@ -0,0 +1,193 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.LoggerBuilder; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.io.Closeable; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.function.BiPredicate; +import java.util.function.Supplier; +import java.util.logging.Level; +import javax.annotation.Nullable; + +/** + * SDK implementation for {@link LoggerProvider}. + * + * @since 1.27.0 + */ +public final class SdkLoggerProvider implements LoggerProvider, Closeable { + + static final String DEFAULT_LOGGER_NAME = "unknown"; + private static final java.util.logging.Logger LOGGER = + java.util.logging.Logger.getLogger(SdkLoggerProvider.class.getName()); + + private final LoggerSharedState sharedState; + private final SdkResourceProvider resourceProvider; + private final ComponentRegistry loggerComponentRegistry; + private final boolean isNoopLogRecordProcessor; + + // deliberately not volatile because of performance concerns + // - which means its eventually consistent + private ScopeConfigurator loggerConfigurator; + + /** + * Returns a new {@link SdkLoggerProviderBuilder} for {@link SdkLoggerProvider}. + * + * @return a new builder instance + */ + public static SdkLoggerProviderBuilder builder() { + return new SdkLoggerProviderBuilder(); + } + + SdkLoggerProvider( + SdkResourceProvider resourceProvider, + Supplier logLimitsSupplier, + List processors, + Clock clock, + ScopeConfigurator loggerConfigurator, + ExceptionAttributeResolver exceptionAttributeResolver, + Supplier meterProvider, + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.resourceProvider = resourceProvider; + LogRecordProcessor logRecordProcessor = LogRecordProcessor.composite(processors); + this.sharedState = + new LoggerSharedState( + resourceProvider, + logLimitsSupplier, + logRecordProcessor, + clock, + exceptionAttributeResolver, + new SdkLoggerInstrumentation(meterProvider), + contextScopedAttributesFilter); + this.loggerComponentRegistry = + new ComponentRegistry<>(instrumentationScopeInfo -> + SdkLogger.create( + sharedState, instrumentationScopeInfo, getLoggerConfig(instrumentationScopeInfo))); + this.loggerConfigurator = loggerConfigurator; + this.isNoopLogRecordProcessor = logRecordProcessor instanceof NoopLogRecordProcessor; + } + + /** + * Returns the {@link SdkResourceProvider} used to resolve the {@link Resource} attached to log + * records. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkLoggerProviderUtil#getSdkResourceProvider(SdkLoggerProvider)}. + */ + SdkResourceProvider getSdkResourceProvider() { + return resourceProvider; + } + + private LoggerConfig getLoggerConfig(InstrumentationScopeInfo instrumentationScopeInfo) { + LoggerConfig loggerConfig = loggerConfigurator.apply(instrumentationScopeInfo); + return loggerConfig == null ? LoggerConfig.defaultConfig() : loggerConfig; + } + + @Override + public Logger get(String instrumentationScopeName) { + if (isNoopLogRecordProcessor) { + return LoggerProvider.noop().get(instrumentationScopeName); + } + return loggerComponentRegistry.get( + instrumentationNameOrDefault(instrumentationScopeName), null, null, Attributes.empty()); + } + + @Override + public LoggerBuilder loggerBuilder(String instrumentationScopeName) { + if (isNoopLogRecordProcessor) { + return LoggerProvider.noop().loggerBuilder(instrumentationScopeName); + } + return new SdkLoggerBuilder( + loggerComponentRegistry, instrumentationNameOrDefault(instrumentationScopeName)); + } + + private static String instrumentationNameOrDefault(@Nullable String instrumentationScopeName) { + if (instrumentationScopeName == null || instrumentationScopeName.isEmpty()) { + LOGGER.fine("Logger requested without instrumentation scope name."); + return DEFAULT_LOGGER_NAME; + } + return instrumentationScopeName; + } + + /** + * Updates the logger configurator, which computes {@link LoggerConfig} for each {@link + * InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil#setLoggerConfigurator(SdkLoggerProvider, + * ScopeConfigurator)}. + * + * @see LoggerConfig#configuratorBuilder() + */ + void setLoggerConfigurator(ScopeConfigurator loggerConfigurator) { + this.loggerConfigurator = loggerConfigurator; + this.loggerComponentRegistry + .getComponents() + .forEach(sdkLogger -> + sdkLogger.updateLoggerConfig(getLoggerConfig(sdkLogger.getInstrumentationScopeInfo()))); + } + + /** + * Request the active log processor to process all logs that have not yet been processed. + * + * @return a {@link CompletableResultCode} which is completed when the flush is finished + */ + public CompletableResultCode forceFlush() { + return sharedState.getLogRecordProcessor().forceFlush(); + } + + /** + * Attempt to shut down the active log processor. + * + * @return a {@link CompletableResultCode} which is completed when the active log process has been + * shut down. + */ + public CompletableResultCode shutdown() { + if (sharedState.hasBeenShutdown()) { + LOGGER.log(Level.INFO, "Calling shutdown() multiple times."); + return CompletableResultCode.ofSuccess(); + } + return sharedState.shutdown(); + } + + @Override + public void close() { + shutdown().join(10, TimeUnit.SECONDS); + } + + @Override + public String toString() { + return "SdkLoggerProvider{" + + "clock=" + + sharedState.getClock() + + ", resource=" + + sharedState.getResource() + + ", logLimits=" + + sharedState.getLogLimits() + + ", logRecordProcessor=" + + sharedState.getLogRecordProcessor() + + ", loggerConfigurator=" + + loggerConfigurator + + '}'; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProviderBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProviderBuilder.java new file mode 100644 index 00000000000..06ad7a62a9b --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkLoggerProviderBuilder.java @@ -0,0 +1,279 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.function.BiPredicate; +import java.util.function.Predicate; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * Builder class for {@link SdkLoggerProvider} instances. + * + * @since 1.27.0 + */ +public final class SdkLoggerProviderBuilder { + + private final List logRecordProcessors = new ArrayList<>(); + private Resource resource = Resource.getDefault(); + private boolean resourceExplicitlySet = false; + @Nullable private SdkResourceProvider resourceProvider; + private Supplier logLimitsSupplier = LogLimits::getDefault; + private Clock clock = Clock.getDefault(); + private ScopeConfiguratorBuilder loggerConfiguratorBuilder = + LoggerConfig.configuratorBuilder(); + private ExceptionAttributeResolver exceptionAttributeResolver = + ExceptionAttributeResolver.getDefault(); + private Supplier meterProvider = MeterProvider::noop; + + @Nullable + private BiPredicate> contextScopedAttributesFilter; + + SdkLoggerProviderBuilder() {} + + /** + * Assign a {@link Resource} to be attached to all {@link LogRecordData} created by {@link + * Logger}s obtained from the {@link SdkLoggerProvider}. + * + * @param resource the resource + * @return this + * @throws IllegalStateException if {@link #setSdkResourceProvider(SdkResourceProvider)} was + * already called + */ + public SdkLoggerProviderBuilder setResource(Resource resource) { + requireNonNull(resource, "resource"); + if (resourceProvider != null) { + throw new IllegalStateException( + "Cannot call setResource after setSdkResourceProvider has been called."); + } + this.resource = resource; + this.resourceExplicitlySet = true; + return this; + } + + /** + * Merge a {@link Resource} with the current. + * + * @param resource {@link Resource} to merge with current. + * @throws IllegalStateException if {@link #setSdkResourceProvider(SdkResourceProvider)} was + * already called + * @since 1.29.0 + */ + public SdkLoggerProviderBuilder addResource(Resource resource) { + Objects.requireNonNull(resource, "resource"); + if (resourceProvider != null) { + throw new IllegalStateException( + "Cannot call addResource after setSdkResourceProvider has been called."); + } + this.resource = this.resource.merge(resource); + this.resourceExplicitlySet = true; + return this; + } + + /** + * Sets the {@link SdkResourceProvider} used to resolve the {@link Resource} attached to all log + * records. + * + *

      Mutually exclusive with {@link #setResource(Resource)} and {@link #addResource(Resource)}. + * The conflicting setter throws {@link IllegalStateException} if both are configured. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkLoggerProviderUtil#setSdkResourceProvider(SdkLoggerProviderBuilder, SdkResourceProvider)}. + */ + SdkLoggerProviderBuilder setSdkResourceProvider(SdkResourceProvider resourceProvider) { + requireNonNull(resourceProvider, "resourceProvider"); + if (resourceExplicitlySet) { + throw new IllegalStateException( + "Cannot call setSdkResourceProvider after setResource or addResource has been called."); + } + this.resourceProvider = resourceProvider; + return this; + } + + /** + * Assign a {@link Supplier} of {@link LogLimits}. {@link LogLimits} will be retrieved each time a + * {@link Logger#logRecordBuilder()} is called. + * + *

      The {@code logLimitsSupplier} must be thread-safe and return immediately (no remote calls, + * as contention free as possible). + * + * @param logLimitsSupplier the supplier that will be used to retrieve the {@link LogLimits} for + * every {@link LogRecordBuilder}. + * @return this + */ + public SdkLoggerProviderBuilder setLogLimits(Supplier logLimitsSupplier) { + requireNonNull(logLimitsSupplier, "logLimitsSupplier"); + this.logLimitsSupplier = logLimitsSupplier; + return this; + } + + /** + * Add a log processor. {@link LogRecordProcessor#onEmit(Context, ReadWriteLogRecord)} will be + * called each time a log is emitted by {@link Logger} instances obtained from the {@link + * SdkLoggerProvider}. + * + * @param processor the log processor + * @return this + */ + public SdkLoggerProviderBuilder addLogRecordProcessor(LogRecordProcessor processor) { + requireNonNull(processor, "processor"); + logRecordProcessors.add(processor); + return this; + } + + /** + * Add a log processor as first. {@link LogRecordProcessor#onEmit(Context, ReadWriteLogRecord)} + * will be called each time a log is emitted by {@link Logger} instances obtained from the {@link + * SdkLoggerProvider}. + * + *

      Compared to {@link SdkLoggerProviderBuilder#addLogRecordProcessor(LogRecordProcessor)}, this + * method adds the processor to the beginning of the processor pipeline. So the {@code processor} + * given will be executed before than the other processors already added. + * + * @param processor the log processor + * @return this + * @since 1.50.0 + */ + public SdkLoggerProviderBuilder addLogRecordProcessorFirst(LogRecordProcessor processor) { + requireNonNull(processor, "processor"); + logRecordProcessors.add(0, processor); + return this; + } + + /** + * Assign a {@link Clock}. + * + * @param clock The clock to use for all temporal needs. + * @return this + */ + public SdkLoggerProviderBuilder setClock(Clock clock) { + requireNonNull(clock, "clock"); + this.clock = clock; + return this; + } + + /** + * Set the logger configurator, which computes {@link LoggerConfig} for each {@link + * InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkLoggerProviderUtil#setLoggerConfigurator(SdkLoggerProviderBuilder, ScopeConfigurator)}. + * + *

      Overrides any matchers added via {@link #addLoggerConfiguratorCondition(Predicate, + * LoggerConfig)}. + * + * @see LoggerConfig#configuratorBuilder() + */ + SdkLoggerProviderBuilder setLoggerConfigurator( + ScopeConfigurator loggerConfigurator) { + this.loggerConfiguratorBuilder = loggerConfigurator.toBuilder(); + return this; + } + + /** + * Adds a condition to the logger configurator, which computes {@link LoggerConfig} for each + * {@link InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkLoggerProviderUtil#addLoggerConfiguratorCondition(SdkLoggerProviderBuilder, Predicate, + * LoggerConfig)}. + * + *

      Applies after any previously added conditions. + * + *

      If {@link #setLoggerConfigurator(ScopeConfigurator)} was previously called, this condition + * will only be applied if the {@link ScopeConfigurator#apply(Object)} returns null for the + * matched {@link InstrumentationScopeInfo}(s). + * + * @see ScopeConfiguratorBuilder#nameEquals(String) + * @see ScopeConfiguratorBuilder#nameMatchesGlob(String) + */ + SdkLoggerProviderBuilder addLoggerConfiguratorCondition( + Predicate scopeMatcher, LoggerConfig loggerConfig) { + this.loggerConfiguratorBuilder.addCondition(scopeMatcher, loggerConfig); + return this; + } + + /** + * Set the exception attribute resolver, which resolves {@code exception.*} attributes an + * exception is set on a log. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkLoggerProviderUtil#setExceptionAttributeResolver(SdkLoggerProviderBuilder, + * ExceptionAttributeResolver)}. + */ + SdkLoggerProviderBuilder setExceptionAttributeResolver( + ExceptionAttributeResolver exceptionAttributeResolver) { + requireNonNull(exceptionAttributeResolver, "exceptionAttributeResolver"); + this.exceptionAttributeResolver = exceptionAttributeResolver; + return this; + } + + /** + * Sets the {@link MeterProvider} to use to generate SDK Log + * Metrics. + * + * @since 1.58.0 + */ + public SdkLoggerProviderBuilder setMeterProvider(Supplier meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = meterProvider; + return this; + } + + /** + * Sets the filter predicate to determine which context-scoped attributes are inherited by log + * records. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkLoggerProviderUtil#setContextScopedAttributesFilter(SdkLoggerProviderBuilder, BiPredicate)}. + */ + SdkLoggerProviderBuilder setContextScopedAttributesFilter( + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.contextScopedAttributesFilter = contextScopedAttributesFilter; + return this; + } + + /** + * Create a {@link SdkLoggerProvider} instance. + * + * @return an instance configured with the provided options + */ + public SdkLoggerProvider build() { + SdkResourceProvider effectiveSdkResourceProvider = + resourceProvider != null ? resourceProvider : SdkResourceProvider.create(resource); + return new SdkLoggerProvider( + effectiveSdkResourceProvider, + logLimitsSupplier, + logRecordProcessors, + clock, + loggerConfiguratorBuilder.build(), + exceptionAttributeResolver, + meterProvider, + contextScopedAttributesFilter); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkReadWriteLogRecord.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkReadWriteLogRecord.java new file mode 100644 index 00000000000..4bb837668fd --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/SdkReadWriteLogRecord.java @@ -0,0 +1,193 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.internal.GuardedBy; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.AttributesMap; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.Nullable; +import javax.annotation.concurrent.ThreadSafe; + +@ThreadSafe +class SdkReadWriteLogRecord implements ReadWriteLogRecord { + + private final LogLimits logLimits; + private final Resource resource; + private final InstrumentationScopeInfo instrumentationScopeInfo; + private final long timestampEpochNanos; + private final long observedTimestampEpochNanos; + private final SpanContext spanContext; + private final Severity severity; + @Nullable private final String severityText; + @Nullable private final Value body; + @Nullable private final String eventName; + private final Object lock = new Object(); + + @GuardedBy("lock") + @Nullable + private AttributesMap attributes; + + protected SdkReadWriteLogRecord( + LogLimits logLimits, + Resource resource, + InstrumentationScopeInfo instrumentationScopeInfo, + long timestampEpochNanos, + long observedTimestampEpochNanos, + SpanContext spanContext, + Severity severity, + @Nullable String severityText, + @Nullable Value body, + @Nullable AttributesMap attributes, + @Nullable String eventName) { + this.logLimits = logLimits; + this.resource = resource; + this.instrumentationScopeInfo = instrumentationScopeInfo; + this.timestampEpochNanos = timestampEpochNanos; + this.observedTimestampEpochNanos = observedTimestampEpochNanos; + this.spanContext = spanContext; + this.severity = severity; + this.severityText = severityText; + this.body = body; + this.eventName = eventName; + this.attributes = attributes; + } + + /** Create the log record with the given configuration. */ + static SdkReadWriteLogRecord create( + LogLimits logLimits, + Resource resource, + InstrumentationScopeInfo instrumentationScopeInfo, + long timestampEpochNanos, + long observedTimestampEpochNanos, + SpanContext spanContext, + Severity severity, + @Nullable String severityText, + @Nullable Value body, + @Nullable AttributesMap attributes, + @Nullable String eventName) { + return new SdkReadWriteLogRecord( + logLimits, + resource, + instrumentationScopeInfo, + timestampEpochNanos, + observedTimestampEpochNanos, + spanContext, + severity, + severityText, + body, + attributes, + eventName); + } + + @Override + public ReadWriteLogRecord setAttribute(AttributeKey key, T value) { + if (key == null || key.getKey().isEmpty() || value == null) { + return this; + } + synchronized (lock) { + if (attributes == null) { + attributes = + AttributesMap.create( + logLimits.getMaxNumberOfAttributes(), logLimits.getMaxAttributeValueLength()); + } + attributes.put(key, value); + } + return this; + } + + protected Attributes getImmutableAttributes() { + synchronized (lock) { + if (attributes == null || attributes.isEmpty()) { + return Attributes.empty(); + } + return attributes.immutableCopy(); + } + } + + @Override + public LogRecordData toLogRecordData() { + synchronized (lock) { + return SdkLogRecordData.create( + resource, + instrumentationScopeInfo, + timestampEpochNanos, + observedTimestampEpochNanos, + spanContext, + severity, + severityText, + body, + getImmutableAttributes(), + attributes == null ? 0 : attributes.getTotalAddedValues(), + eventName); + } + } + + @Override + public InstrumentationScopeInfo getInstrumentationScopeInfo() { + return instrumentationScopeInfo; + } + + @Override + public long getTimestampEpochNanos() { + return timestampEpochNanos; + } + + @Override + public long getObservedTimestampEpochNanos() { + return observedTimestampEpochNanos; + } + + @Override + public SpanContext getSpanContext() { + return spanContext; + } + + @Override + public Severity getSeverity() { + return severity; + } + + @Nullable + @Override + public String getSeverityText() { + return severityText; + } + + @Nullable + @Override + public Value getBodyValue() { + return body; + } + + @Override + public Attributes getAttributes() { + return getImmutableAttributes(); + } + + @Override + @Nullable + public String getEventName() { + return eventName; + } + + @Nullable + @Override + public T getAttribute(AttributeKey key) { + synchronized (lock) { + if (attributes == null || attributes.isEmpty()) { + return null; + } + return attributes.get(key); + } + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Body.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Body.java index 78bcdeb2509..fda485f5eaf 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Body.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/Body.java @@ -5,6 +5,8 @@ package io.opentelemetry.sdk.logs.data; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.common.ValueType; import javax.annotation.concurrent.Immutable; /** @@ -12,11 +14,20 @@ * have 1 type of values: {@code String}, represented through {@code Body.Type}. This class will * likely be extended in the future to include additional body types supported by the OpenTelemetry * log data model. + * + * @since 1.27.0 + * @deprecated Use {@link LogRecordData#getBodyValue()} and {@link Value}. */ @Immutable +@Deprecated public interface Body { - /** An enum that represents all the possible value types for an {@code Body}. */ + /** + * An enum that represents all the possible value types for an {@code Body}. + * + * @deprecated Use {@link Value#getType()}. + */ + @Deprecated enum Type { EMPTY, STRING @@ -41,9 +52,20 @@ static Body empty() { return EmptyBody.INSTANCE; } - /** Returns the String value of this {@code Body}. */ + /** + * Returns the String value of this {@code Body}. + * + *

      If the log record body is some {@link ValueType} other than {@link ValueType#STRING}, this + * returns {@link Value#asString()}. Consumers should use {@link LogRecordData#getBodyValue()} + * instead. + */ String asString(); - /** Returns the type of the {@code Body}. */ + /** + * Returns the type of the {@code Body}. + * + * @deprecated Use {@link Value#getType()}. + */ + @Deprecated Type getType(); } diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/EmptyBody.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/EmptyBody.java index c70e866ee78..921895e6125 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/EmptyBody.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/EmptyBody.java @@ -5,6 +5,7 @@ package io.opentelemetry.sdk.logs.data; +@SuppressWarnings("deprecation") // Implementation of deprecated Body enum EmptyBody implements Body { INSTANCE; diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogData.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogData.java deleted file mode 100644 index db207d3f1c0..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogData.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.data; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import javax.annotation.Nullable; -import javax.annotation.concurrent.Immutable; - -/** - * Log definition as described in OpenTelemetry - * Log Data Model. - */ -@Immutable -public interface LogData { - - /** Returns the resource of this log. */ - Resource getResource(); - - /** Returns the instrumentation scope that generated this log. */ - InstrumentationScopeInfo getInstrumentationScopeInfo(); - - /** Returns the epoch timestamp in nanos when the log was recorded. */ - long getEpochNanos(); - - /** Return the span context for this log, or {@link SpanContext#getInvalid()} if unset. */ - SpanContext getSpanContext(); - - /** Returns the severity for this log, or {@link Severity#UNDEFINED_SEVERITY_NUMBER} if unset. */ - Severity getSeverity(); - - /** Returns the severity text for this log, or null if unset. */ - @Nullable - String getSeverityText(); - - /** Returns the body for this log, or {@link Body#empty()} if unset. */ - Body getBody(); - - /** Returns the attributes for this log, or {@link Attributes#empty()} if unset. */ - Attributes getAttributes(); -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogDataBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogDataBuilder.java deleted file mode 100644 index e339510f57a..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogDataBuilder.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.data; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import java.time.Instant; -import java.util.concurrent.TimeUnit; -import javax.annotation.Nullable; - -/** Builder for {@link LogData}. */ -public final class LogDataBuilder { - - private final Resource resource; - private final InstrumentationScopeInfo instrumentationScopeInfo; - - private long epochNanos; - private SpanContext spanContext = SpanContext.getInvalid(); - private Severity severity = Severity.UNDEFINED_SEVERITY_NUMBER; - @Nullable private String severityText; - private Body body = Body.empty(); - private final Clock clock; - private Attributes attributes = Attributes.empty(); - - private LogDataBuilder( - Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, Clock clock) { - this.resource = resource; - this.instrumentationScopeInfo = instrumentationScopeInfo; - this.clock = clock; - } - - /** Returns a new {@link LogDataBuilder} with the default clock. */ - public static LogDataBuilder create( - Resource resource, InstrumentationScopeInfo instrumentationScopeInfo) { - return create(resource, instrumentationScopeInfo, Clock.getDefault()); - } - - /** Returns a new {@link LogDataBuilder}. */ - public static LogDataBuilder create( - Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, Clock clock) { - return new LogDataBuilder(resource, instrumentationScopeInfo, clock); - } - - /** Set the epoch timestamp using the timestamp and unit. */ - public LogDataBuilder setEpoch(long timestamp, TimeUnit unit) { - this.epochNanos = unit.toNanos(timestamp); - return this; - } - - /** Set the epoch timestamp using the instant. */ - public LogDataBuilder setEpoch(Instant instant) { - this.epochNanos = TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano(); - return this; - } - - /** Sets the context. */ - public LogDataBuilder setContext(Context context) { - return setSpanContext(Span.fromContext(context).getSpanContext()); - } - - /** Sets the span context. */ - public LogDataBuilder setSpanContext(SpanContext spanContext) { - this.spanContext = spanContext == null ? SpanContext.getInvalid() : spanContext; - return this; - } - - /** Set the severity. */ - public LogDataBuilder setSeverity(Severity severity) { - this.severity = severity; - return this; - } - - /** Set the severity text. */ - public LogDataBuilder setSeverityText(String severityText) { - this.severityText = severityText; - return this; - } - - /** Set the body string. */ - public LogDataBuilder setBody(String body) { - this.body = Body.string(body); - return this; - } - - /** Set the attributes. */ - public LogDataBuilder setAttributes(Attributes attributes) { - this.attributes = attributes; - return this; - } - - /** Build a {@link LogData} instance from the configured properties. */ - public LogData build() { - if (epochNanos == 0) { - epochNanos = clock.now(); - } - return LogDataImpl.create( - resource, - instrumentationScopeInfo, - epochNanos, - spanContext, - severity, - severityText, - body, - attributes); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogDataImpl.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogDataImpl.java deleted file mode 100644 index 42b690f68f4..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogDataImpl.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.data; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import javax.annotation.Nullable; -import javax.annotation.concurrent.Immutable; - -@AutoValue -@AutoValue.CopyAnnotations -@Immutable -abstract class LogDataImpl implements LogData { - - LogDataImpl() {} - - static LogDataImpl create( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - long epochNanos, - SpanContext spanContext, - Severity severity, - @Nullable String severityText, - Body body, - Attributes attributes) { - return new AutoValue_LogDataImpl( - resource, - instrumentationScopeInfo, - epochNanos, - spanContext, - severity, - severityText, - body, - attributes); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogRecordData.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogRecordData.java new file mode 100644 index 00000000000..a343d8b2228 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/LogRecordData.java @@ -0,0 +1,95 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.data; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.common.ValueType; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.LogLimits; +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * Log definition as described in OpenTelemetry + * Log Data Model. + * + * @since 1.27.0 + */ +@Immutable +public interface LogRecordData { + + /** Returns the resource of this log. */ + Resource getResource(); + + /** Returns the instrumentation scope that generated this log. */ + InstrumentationScopeInfo getInstrumentationScopeInfo(); + + /** Returns the timestamp at which the log record occurred, in epoch nanos. */ + long getTimestampEpochNanos(); + + /** Returns the timestamp at which the log record was observed, in epoch nanos. */ + long getObservedTimestampEpochNanos(); + + /** Return the span context for this log, or {@link SpanContext#getInvalid()} if unset. */ + SpanContext getSpanContext(); + + /** Returns the severity for this log, or {@link Severity#UNDEFINED_SEVERITY_NUMBER} if unset. */ + Severity getSeverity(); + + /** Returns the severity text for this log, or null if unset. */ + @Nullable + String getSeverityText(); + + /** + * Returns the body for this log, or {@link Body#empty()} if unset. + * + *

      If the body has been set to some {@link ValueType} other than {@link ValueType#STRING}, this + * will return a {@link Body} with a string representation of the {@link Value}. + * + * @deprecated Use {@link #getBodyValue()} instead. + */ + @Deprecated + Body getBody(); + + /** + * Returns the {@link Value} representation of the log body, of null if unset. + * + * @since 1.42.0 + */ + @Nullable + @SuppressWarnings("deprecation") // Default impl uses deprecated code for backwards compatibility + default Value getBodyValue() { + Body body = getBody(); + return body.getType() == Body.Type.EMPTY ? null : Value.of(body.asString()); + } + + /** Returns the attributes for this log, or {@link Attributes#empty()} if unset. */ + Attributes getAttributes(); + + /** + * Returns the total number of attributes that were recorded on this log. + * + *

      This number may be larger than the number of attributes that are attached to this log, if + * the total number recorded was greater than the configured maximum value. See {@link + * LogLimits#getMaxNumberOfAttributes()}. + */ + int getTotalAttributeCount(); + + /** + * Returns the event name, or {@code null} if none is set. + * + * @since 1.50.0 + */ + @Nullable + default String getEventName() { + return null; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/StringBody.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/StringBody.java index 4496528f7f0..a08dcab55fa 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/StringBody.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/data/StringBody.java @@ -10,6 +10,7 @@ @Immutable @AutoValue +@SuppressWarnings("deprecation") // Implementation of deprecated Body abstract class StringBody implements Body { StringBody() {} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogProcessor.java deleted file mode 100644 index 096bd66a4ce..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogProcessor.java +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.LongCounter; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.DaemonThreadFactory; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.data.LogData; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Queue; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * Implementation of the {@link LogProcessor} that batches logs exported by the SDK then pushes them - * to the exporter pipeline. - * - *

      All logs reported by the SDK implementation are first added to a synchronized queue (with a - * {@code maxQueueSize} maximum size, if queue is full logs are dropped). Logs are exported either - * when there are {@code maxExportBatchSize} pending logs or {@code scheduleDelayNanos} has passed - * since the last export finished. - */ -public final class BatchLogProcessor implements LogProcessor { - - private static final String WORKER_THREAD_NAME = - BatchLogProcessor.class.getSimpleName() + "_WorkerThread"; - private static final AttributeKey LOG_PROCESSOR_TYPE_LABEL = - AttributeKey.stringKey("logProcessorType"); - private static final AttributeKey LOG_PROCESSOR_DROPPED_LABEL = - AttributeKey.booleanKey("dropped"); - private static final String LOG_PROCESSOR_TYPE_VALUE = BatchLogProcessor.class.getSimpleName(); - - private final Worker worker; - private final AtomicBoolean isShutdown = new AtomicBoolean(false); - - /** - * Returns a new Builder for {@link BatchLogProcessor}. - * - * @param logExporter the {@link LogExporter} to which the Logs are pushed - * @return a new {@link BatchLogProcessorBuilder}. - * @throws NullPointerException if the {@code logExporter} is {@code null}. - */ - public static BatchLogProcessorBuilder builder(LogExporter logExporter) { - return new BatchLogProcessorBuilder(logExporter); - } - - BatchLogProcessor( - LogExporter logExporter, - MeterProvider meterProvider, - long scheduleDelayNanos, - int maxQueueSize, - int maxExportBatchSize, - long exporterTimeoutNanos) { - this.worker = - new Worker( - logExporter, - meterProvider, - scheduleDelayNanos, - maxExportBatchSize, - exporterTimeoutNanos, - new ArrayBlockingQueue<>(maxQueueSize)); // TODO: use JcTools.newFixedSizeQueue(..) - Thread workerThread = new DaemonThreadFactory(WORKER_THREAD_NAME).newThread(worker); - workerThread.start(); - } - - @Override - public void emit(LogData logData) { - if (logData == null) { - return; - } - worker.addLog(logData); - } - - @Override - public CompletableResultCode shutdown() { - if (isShutdown.getAndSet(true)) { - return CompletableResultCode.ofSuccess(); - } - return worker.shutdown(); - } - - @Override - public CompletableResultCode forceFlush() { - return worker.forceFlush(); - } - - // Visible for testing - ArrayList getBatch() { - return worker.batch; - } - - // Worker is a thread that batches multiple logs and calls the registered LogExporter to export - // the data. - private static final class Worker implements Runnable { - - private static final Logger logger = Logger.getLogger(Worker.class.getName()); - - private final LongCounter processedLogsCounter; - private final Attributes droppedAttrs; - private final Attributes exportedAttrs; - - private final LogExporter logExporter; - private final long scheduleDelayNanos; - private final int maxExportBatchSize; - private final long exporterTimeoutNanos; - - private long nextExportTime; - - private final Queue queue; - // When waiting on the logs queue, exporter thread sets this atomic to the number of more - // logs it needs before doing an export. Writer threads would then wait for the queue to reach - // logsNeeded size before notifying the exporter thread about new entries. - // Integer.MAX_VALUE is used to imply that exporter thread is not expecting any signal. Since - // exporter thread doesn't expect any signal initially, this value is initialized to - // Integer.MAX_VALUE. - private final AtomicInteger logsNeeded = new AtomicInteger(Integer.MAX_VALUE); - private final BlockingQueue signal; - private final AtomicReference flushRequested = new AtomicReference<>(); - private volatile boolean continueWork = true; - private final ArrayList batch; - - private Worker( - LogExporter logExporter, - MeterProvider meterProvider, - long scheduleDelayNanos, - int maxExportBatchSize, - long exporterTimeoutNanos, - Queue queue) { - this.logExporter = logExporter; - this.scheduleDelayNanos = scheduleDelayNanos; - this.maxExportBatchSize = maxExportBatchSize; - this.exporterTimeoutNanos = exporterTimeoutNanos; - this.queue = queue; - this.signal = new ArrayBlockingQueue<>(1); - Meter meter = meterProvider.meterBuilder("io.opentelemetry.sdk.logs").build(); - meter - .gaugeBuilder("queueSize") - .ofLongs() - .setDescription("The number of logs queued") - .setUnit("1") - .buildWithCallback( - result -> - result.record( - queue.size(), - Attributes.of(LOG_PROCESSOR_TYPE_LABEL, LOG_PROCESSOR_TYPE_VALUE))); - processedLogsCounter = - meter - .counterBuilder("processedLogs") - .setUnit("1") - .setDescription( - "The number of logs processed by the BatchLogProcessor. " - + "[dropped=true if they were dropped due to high throughput]") - .build(); - droppedAttrs = - Attributes.of( - LOG_PROCESSOR_TYPE_LABEL, - LOG_PROCESSOR_TYPE_VALUE, - LOG_PROCESSOR_DROPPED_LABEL, - true); - exportedAttrs = - Attributes.of( - LOG_PROCESSOR_TYPE_LABEL, - LOG_PROCESSOR_TYPE_VALUE, - LOG_PROCESSOR_DROPPED_LABEL, - false); - - this.batch = new ArrayList<>(this.maxExportBatchSize); - } - - private void addLog(LogData logData) { - if (!queue.offer(logData)) { - processedLogsCounter.add(1, droppedAttrs); - } else { - if (queue.size() >= logsNeeded.get()) { - signal.offer(true); - } - } - } - - @Override - public void run() { - updateNextExportTime(); - - while (continueWork) { - if (flushRequested.get() != null) { - flush(); - } - while (!queue.isEmpty() && batch.size() < maxExportBatchSize) { - batch.add(queue.poll()); - } - if (batch.size() >= maxExportBatchSize || System.nanoTime() >= nextExportTime) { - exportCurrentBatch(); - updateNextExportTime(); - } - if (queue.isEmpty()) { - try { - long pollWaitTime = nextExportTime - System.nanoTime(); - if (pollWaitTime > 0) { - logsNeeded.set(maxExportBatchSize - batch.size()); - signal.poll(pollWaitTime, TimeUnit.NANOSECONDS); - logsNeeded.set(Integer.MAX_VALUE); - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - return; - } - } - } - } - - private void flush() { - int logsToFlush = queue.size(); - while (logsToFlush > 0) { - LogData logData = queue.poll(); - assert logData != null; - batch.add(logData); - logsToFlush--; - if (batch.size() >= maxExportBatchSize) { - exportCurrentBatch(); - } - } - exportCurrentBatch(); - CompletableResultCode flushResult = flushRequested.get(); - if (flushResult != null) { - flushResult.succeed(); - flushRequested.set(null); - } - } - - private void updateNextExportTime() { - nextExportTime = System.nanoTime() + scheduleDelayNanos; - } - - private CompletableResultCode shutdown() { - CompletableResultCode result = new CompletableResultCode(); - - CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - continueWork = false; - CompletableResultCode shutdownResult = logExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); - - return result; - } - - private CompletableResultCode forceFlush() { - CompletableResultCode flushResult = new CompletableResultCode(); - // we set the atomic here to trigger the worker loop to do a flush of the entire queue. - if (flushRequested.compareAndSet(null, flushResult)) { - signal.offer(true); - } - CompletableResultCode possibleResult = flushRequested.get(); - // there's a race here where the flush happening in the worker loop could complete before we - // get what's in the atomic. In that case, just return success, since we know it succeeded in - // the interim. - return possibleResult == null ? CompletableResultCode.ofSuccess() : possibleResult; - } - - private void exportCurrentBatch() { - if (batch.isEmpty()) { - return; - } - - try { - CompletableResultCode result = logExporter.export(Collections.unmodifiableList(batch)); - result.join(exporterTimeoutNanos, TimeUnit.NANOSECONDS); - if (result.isSuccess()) { - processedLogsCounter.add(batch.size(), exportedAttrs); - } else { - logger.log(Level.FINE, "Exporter failed"); - } - } catch (RuntimeException e) { - logger.log(Level.WARNING, "Exporter threw an Exception", e); - } finally { - batch.clear(); - } - } - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogProcessorBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogProcessorBuilder.java deleted file mode 100644 index b4be201d67b..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogProcessorBuilder.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import static io.opentelemetry.api.internal.Utils.checkArgument; -import static java.util.Objects.requireNonNull; - -import io.opentelemetry.api.metrics.MeterProvider; -import java.time.Duration; -import java.util.concurrent.TimeUnit; - -/** Builder class for {@link BatchLogProcessor}. */ -public final class BatchLogProcessorBuilder { - - // Visible for testing - static final long DEFAULT_SCHEDULE_DELAY_MILLIS = 200; - // Visible for testing - static final int DEFAULT_MAX_QUEUE_SIZE = 2048; - // Visible for testing - static final int DEFAULT_MAX_EXPORT_BATCH_SIZE = 512; - // Visible for testing - static final int DEFAULT_EXPORT_TIMEOUT_MILLIS = 30_000; - - private final LogExporter logExporter; - private long scheduleDelayNanos = TimeUnit.MILLISECONDS.toNanos(DEFAULT_SCHEDULE_DELAY_MILLIS); - private int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; - private int maxExportBatchSize = DEFAULT_MAX_EXPORT_BATCH_SIZE; - private long exporterTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(DEFAULT_EXPORT_TIMEOUT_MILLIS); - private MeterProvider meterProvider = MeterProvider.noop(); - - BatchLogProcessorBuilder(LogExporter logExporter) { - this.logExporter = requireNonNull(logExporter, "logExporter"); - } - - /** - * Sets the delay interval between two consecutive exports. If unset, defaults to {@value - * DEFAULT_SCHEDULE_DELAY_MILLIS}ms. - */ - public BatchLogProcessorBuilder setScheduleDelay(long delay, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(delay >= 0, "delay must be non-negative"); - scheduleDelayNanos = unit.toNanos(delay); - return this; - } - - /** - * Sets the delay interval between two consecutive exports. If unset, defaults to {@value - * DEFAULT_SCHEDULE_DELAY_MILLIS}ms. - */ - public BatchLogProcessorBuilder setScheduleDelay(Duration delay) { - requireNonNull(delay, "delay"); - return setScheduleDelay(delay.toNanos(), TimeUnit.NANOSECONDS); - } - - // Visible for testing - long getScheduleDelayNanos() { - return scheduleDelayNanos; - } - - /** - * Sets the maximum time an export will be allowed to run before being cancelled. If unset, - * defaults to {@value DEFAULT_EXPORT_TIMEOUT_MILLIS}ms. - */ - public BatchLogProcessorBuilder setExporterTimeout(long timeout, TimeUnit unit) { - requireNonNull(unit, "unit"); - checkArgument(timeout >= 0, "timeout must be non-negative"); - exporterTimeoutNanos = unit.toNanos(timeout); - return this; - } - - /** - * Sets the maximum time an export will be allowed to run before being cancelled. If unset, - * defaults to {@value DEFAULT_EXPORT_TIMEOUT_MILLIS}ms. - */ - public BatchLogProcessorBuilder setExporterTimeout(Duration timeout) { - requireNonNull(timeout, "timeout"); - return setExporterTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); - } - - // Visible for testing - long getExporterTimeoutNanos() { - return exporterTimeoutNanos; - } - - /** - * Sets the maximum number of Logs that are kept in the queue before start dropping. More memory - * than this value may be allocated to optimize queue access. - * - *

      Default value is {@code 2048}. - * - * @param maxQueueSize the maximum number of Logs that are kept in the queue before start - * dropping. - * @return this. - * @see BatchLogProcessorBuilder#DEFAULT_MAX_QUEUE_SIZE - */ - public BatchLogProcessorBuilder setMaxQueueSize(int maxQueueSize) { - this.maxQueueSize = maxQueueSize; - return this; - } - - // Visible for testing - int getMaxQueueSize() { - return maxQueueSize; - } - - /** - * Sets the maximum batch size for every export. This must be smaller or equal to {@code - * maxQueueSize}. - * - *

      Default value is {@code 512}. - * - * @param maxExportBatchSize the maximum batch size for every export. - * @return this. - * @see BatchLogProcessorBuilder#DEFAULT_MAX_EXPORT_BATCH_SIZE - */ - public BatchLogProcessorBuilder setMaxExportBatchSize(int maxExportBatchSize) { - checkArgument(maxExportBatchSize > 0, "maxExportBatchSize must be positive."); - this.maxExportBatchSize = maxExportBatchSize; - return this; - } - - /** - * Sets the {@link MeterProvider} to use to collect metrics related to batch export. If not set, - * metrics will not be collected. - */ - public BatchLogProcessorBuilder setMeterProvider(MeterProvider meterProvider) { - requireNonNull(meterProvider, "meterProvider"); - this.meterProvider = meterProvider; - return this; - } - - // Visible for testing - int getMaxExportBatchSize() { - return maxExportBatchSize; - } - - /** - * Returns a new {@link BatchLogProcessor} that batches, then forwards them to the given {@code - * logExporter}. - * - * @return a new {@link BatchLogProcessor}. - */ - public BatchLogProcessor build() { - return new BatchLogProcessor( - logExporter, - meterProvider, - scheduleDelayNanos, - maxQueueSize, - maxExportBatchSize, - exporterTimeoutNanos); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java new file mode 100644 index 00000000000..13ce175e6b7 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessor.java @@ -0,0 +1,312 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.common.internal.ThrowableUtil; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.ReadWriteLogRecord; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Implementation of the {@link LogRecordProcessor} that batches logs exported by the SDK then + * pushes them to the exporter pipeline. + * + *

      All logs reported by the SDK implementation are first added to a synchronized queue (with a + * {@code maxQueueSize} maximum size, if queue is full logs are dropped). Logs are exported either + * when there are {@code maxExportBatchSize} pending logs or {@code scheduleDelayNanos} has passed + * since the last export finished. + * + * @since 1.27.0 + */ +public final class BatchLogRecordProcessor implements LogRecordProcessor { + + private static final ComponentId COMPONENT_ID = + ComponentId.generateLazy("batching_log_processor"); + + private static final String WORKER_THREAD_NAME = + BatchLogRecordProcessor.class.getSimpleName() + "_WorkerThread"; + + private final Worker worker; + + /** + * Returns a new Builder for {@link BatchLogRecordProcessor}. + * + * @param logRecordExporter the {@link LogRecordExporter} to which the Logs are pushed + * @return a new {@link BatchLogRecordProcessor}. + * @throws NullPointerException if the {@code logRecordExporter} is {@code null}. + */ + public static BatchLogRecordProcessorBuilder builder(LogRecordExporter logRecordExporter) { + return new BatchLogRecordProcessorBuilder(logRecordExporter); + } + + BatchLogRecordProcessor( + LogRecordExporter logRecordExporter, + Supplier meterProvider, + InternalTelemetryVersion telemetryVersion, + long scheduleDelayNanos, + int maxQueueSize, + int maxExportBatchSize, + long exporterTimeoutNanos) { + this.worker = + new Worker( + logRecordExporter, + meterProvider, + telemetryVersion, + scheduleDelayNanos, + maxExportBatchSize, + exporterTimeoutNanos, + new ArrayBlockingQueue<>(maxQueueSize), + maxQueueSize); // TODO: use JcTools.newFixedSizeQueue(..) + Thread workerThread = new DaemonThreadFactory(WORKER_THREAD_NAME).newThread(worker); + workerThread.start(); + } + + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) { + if (logRecord == null) { + return; + } + worker.addLog(logRecord); + } + + @Override + public CompletableResultCode shutdown() { + return worker.shutdown(); + } + + @Override + public CompletableResultCode forceFlush() { + return worker.forceFlush(); + } + + /** + * Return the processor's configured {@link LogRecordExporter}. + * + * @since 1.37.0 + */ + public LogRecordExporter getLogRecordExporter() { + return worker.logRecordExporter; + } + + // Visible for testing + List getBatch() { + return worker.batch; + } + + @Override + public String toString() { + return "BatchLogRecordProcessor{" + + "logRecordExporter=" + + worker.logRecordExporter + + ", scheduleDelayNanos=" + + worker.scheduleDelayNanos + + ", maxExportBatchSize=" + + worker.maxExportBatchSize + + ", exporterTimeoutNanos=" + + worker.exporterTimeoutNanos + + '}'; + } + + // Worker is a thread that batches multiple logs and calls the registered LogRecordExporter to + // export + // the data. + private static final class Worker implements Runnable { + + private static final Logger logger = Logger.getLogger(Worker.class.getName()); + + private final LogRecordProcessorInstrumentation logProcessorInstrumentation; + + private final LogRecordExporter logRecordExporter; + private final long scheduleDelayNanos; + private final int maxExportBatchSize; + private final long exporterTimeoutNanos; + + private long nextExportTime; + + private final Queue queue; + // When waiting on the logs queue, exporter thread sets this atomic to the number of more + // logs it needs before doing an export. Writer threads would then wait for the queue to reach + // logsNeeded size before notifying the exporter thread about new entries. + // Integer.MAX_VALUE is used to imply that exporter thread is not expecting any signal. Since + // exporter thread doesn't expect any signal initially, this value is initialized to + // Integer.MAX_VALUE. + private final AtomicInteger logsNeeded = new AtomicInteger(Integer.MAX_VALUE); + private final BlockingQueue signal; + private final AtomicReference flushRequested = new AtomicReference<>(); + private final AtomicBoolean isShutdown = new AtomicBoolean(false); + private volatile boolean continueWork = true; + private final ArrayList batch; + private final long maxQueueSize; + + private Worker( + LogRecordExporter logRecordExporter, + Supplier meterProvider, + InternalTelemetryVersion telemetryVersion, + long scheduleDelayNanos, + int maxExportBatchSize, + long exporterTimeoutNanos, + Queue queue, + long maxQueueSize) { + this.logRecordExporter = logRecordExporter; + this.scheduleDelayNanos = scheduleDelayNanos; + this.maxExportBatchSize = maxExportBatchSize; + this.exporterTimeoutNanos = exporterTimeoutNanos; + this.queue = queue; + this.signal = new ArrayBlockingQueue<>(1); + logProcessorInstrumentation = + LogRecordProcessorInstrumentation.get(telemetryVersion, COMPONENT_ID, meterProvider); + this.maxQueueSize = maxQueueSize; + + this.batch = new ArrayList<>(this.maxExportBatchSize); + } + + private void addLog(ReadWriteLogRecord logData) { + if (isShutdown.get()) { + logProcessorInstrumentation.dropLogsAlreadyShutdown(1); + return; + } + logProcessorInstrumentation.buildQueueMetricsOnce(maxQueueSize, queue::size); + if (!queue.offer(logData)) { + logProcessorInstrumentation.dropLogsQueueFull(1); + } else { + if (queue.size() >= logsNeeded.get()) { + signal.offer(true); + } + } + } + + @Override + public void run() { + updateNextExportTime(); + + while (continueWork) { + if (flushRequested.get() != null) { + flush(); + } + while (!queue.isEmpty() && batch.size() < maxExportBatchSize) { + batch.add(queue.poll().toLogRecordData()); + } + if (batch.size() >= maxExportBatchSize || System.nanoTime() >= nextExportTime) { + exportCurrentBatch(); + updateNextExportTime(); + } + if (queue.isEmpty()) { + try { + long pollWaitTime = nextExportTime - System.nanoTime(); + if (pollWaitTime > 0) { + logsNeeded.set(maxExportBatchSize - batch.size()); + signal.poll(pollWaitTime, TimeUnit.NANOSECONDS); + logsNeeded.set(Integer.MAX_VALUE); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + } + } + } + + private void flush() { + int logsToFlush = queue.size(); + while (logsToFlush > 0) { + ReadWriteLogRecord logRecord = queue.poll(); + assert logRecord != null; + batch.add(logRecord.toLogRecordData()); + logsToFlush--; + if (batch.size() >= maxExportBatchSize) { + exportCurrentBatch(); + } + } + exportCurrentBatch(); + CompletableResultCode flushResult = flushRequested.get(); + if (flushResult != null) { + flushResult.succeed(); + flushRequested.set(null); + } + } + + private void updateNextExportTime() { + nextExportTime = System.nanoTime() + scheduleDelayNanos; + } + + private CompletableResultCode shutdown() { + if (isShutdown.getAndSet(true)) { + return CompletableResultCode.ofSuccess(); + } + CompletableResultCode result = new CompletableResultCode(); + + CompletableResultCode flushResult = forceFlush(); + flushResult.whenComplete(() -> { + continueWork = false; + CompletableResultCode shutdownResult = logRecordExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); + + return result; + } + + private CompletableResultCode forceFlush() { + CompletableResultCode flushResult = new CompletableResultCode(); + // we set the atomic here to trigger the worker loop to do a flush of the entire queue. + if (flushRequested.compareAndSet(null, flushResult)) { + signal.offer(true); + } + CompletableResultCode possibleResult = flushRequested.get(); + // there's a race here where the flush happening in the worker loop could complete before we + // get what's in the atomic. In that case, just return success, since we know it succeeded in + // the interim. + return possibleResult == null ? CompletableResultCode.ofSuccess() : possibleResult; + } + + private void exportCurrentBatch() { + if (batch.isEmpty()) { + return; + } + + try { + // We always increment for every export invocation, so we increment before the export call + // to make sure thrown errors don't affect it. + logProcessorInstrumentation.finishLogs(batch.size()); + CompletableResultCode result = + logRecordExporter.export(Collections.unmodifiableList(batch)); + result.join(exporterTimeoutNanos, TimeUnit.NANOSECONDS); + if (!result.isSuccess()) { + logger.log(Level.FINE, "Exporter failed"); + } + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); + logger.log(Level.WARNING, "Exporter threw an Exception", t); + } finally { + batch.clear(); + } + } + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorBuilder.java new file mode 100644 index 00000000000..b586f9875b3 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorBuilder.java @@ -0,0 +1,200 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static io.opentelemetry.api.internal.Utils.checkArgument; +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Builder class for {@link BatchLogRecordProcessor}. + * + * @since 1.27.0 + */ +public final class BatchLogRecordProcessorBuilder { + private static final Logger logger = + Logger.getLogger(BatchLogRecordProcessorBuilder.class.getName()); + + // Visible for testing + static final long DEFAULT_SCHEDULE_DELAY_MILLIS = 1000; + // Visible for testing + static final int DEFAULT_MAX_QUEUE_SIZE = 2048; + // Visible for testing + static final int DEFAULT_MAX_EXPORT_BATCH_SIZE = 512; + // Visible for testing + static final int DEFAULT_EXPORT_TIMEOUT_MILLIS = 30_000; + + private final LogRecordExporter logRecordExporter; + private long scheduleDelayNanos = TimeUnit.MILLISECONDS.toNanos(DEFAULT_SCHEDULE_DELAY_MILLIS); + private int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; + private int maxExportBatchSize = DEFAULT_MAX_EXPORT_BATCH_SIZE; + private long exporterTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(DEFAULT_EXPORT_TIMEOUT_MILLIS); + private Supplier meterProvider = MeterProvider::noop; + private InternalTelemetryVersion telemetryVersion = InternalTelemetryVersion.LEGACY; + + BatchLogRecordProcessorBuilder(LogRecordExporter logRecordExporter) { + this.logRecordExporter = requireNonNull(logRecordExporter, "logRecordExporter"); + } + + /** + * Sets the delay interval between two consecutive exports. If unset, defaults to {@value + * DEFAULT_SCHEDULE_DELAY_MILLIS}ms. + */ + public BatchLogRecordProcessorBuilder setScheduleDelay(long delay, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(delay >= 0, "delay must be non-negative"); + scheduleDelayNanos = unit.toNanos(delay); + return this; + } + + /** + * Sets the delay interval between two consecutive exports. If unset, defaults to {@value + * DEFAULT_SCHEDULE_DELAY_MILLIS}ms. + */ + public BatchLogRecordProcessorBuilder setScheduleDelay(Duration delay) { + requireNonNull(delay, "delay"); + return setScheduleDelay(delay.toNanos(), TimeUnit.NANOSECONDS); + } + + // Visible for testing + long getScheduleDelayNanos() { + return scheduleDelayNanos; + } + + /** + * Sets the maximum time an export will be allowed to run before being cancelled. If unset, + * defaults to {@value DEFAULT_EXPORT_TIMEOUT_MILLIS}ms. + */ + public BatchLogRecordProcessorBuilder setExporterTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + exporterTimeoutNanos = timeout == 0 ? Long.MAX_VALUE : unit.toNanos(timeout); + return this; + } + + /** + * Sets the maximum time an export will be allowed to run before being cancelled. If unset, + * defaults to {@value DEFAULT_EXPORT_TIMEOUT_MILLIS}ms. + */ + public BatchLogRecordProcessorBuilder setExporterTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + return setExporterTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); + } + + // Visible for testing + long getExporterTimeoutNanos() { + return exporterTimeoutNanos; + } + + /** + * Sets the maximum number of Logs that are kept in the queue before start dropping. More memory + * than this value may be allocated to optimize queue access. + * + *

      Default value is {@code 2048}. + * + * @param maxQueueSize the maximum number of Logs that are kept in the queue before start + * dropping. + * @return this. + * @throws IllegalArgumentException if {@code maxQueueSize} is not positive. + * @see BatchLogRecordProcessorBuilder#DEFAULT_MAX_QUEUE_SIZE + */ + public BatchLogRecordProcessorBuilder setMaxQueueSize(int maxQueueSize) { + checkArgument(maxQueueSize > 0, "maxQueueSize must be positive."); + this.maxQueueSize = maxQueueSize; + return this; + } + + // Visible for testing + int getMaxQueueSize() { + return maxQueueSize; + } + + /** + * Sets the maximum batch size for every export. This must be smaller or equal to {@code + * maxQueueSize}. + * + *

      Default value is {@code 512}. + * + * @param maxExportBatchSize the maximum batch size for every export. + * @return this. + * @see BatchLogRecordProcessorBuilder#DEFAULT_MAX_EXPORT_BATCH_SIZE + */ + public BatchLogRecordProcessorBuilder setMaxExportBatchSize(int maxExportBatchSize) { + checkArgument(maxExportBatchSize > 0, "maxExportBatchSize must be positive."); + this.maxExportBatchSize = maxExportBatchSize; + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to batch export. If not set, + * metrics will not be collected. + */ + public BatchLogRecordProcessorBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = () -> meterProvider; + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to batch export. If not set, + * metrics will not be collected. + * + * @since 1.58.0 + */ + public BatchLogRecordProcessorBuilder setMeterProvider(Supplier meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = meterProvider; + return this; + } + + /** + * Sets the {@link InternalTelemetryVersion} defining which metrics this processor records. + * + * @since 1.58.0 + */ + public BatchLogRecordProcessorBuilder setInternalTelemetryVersion( + InternalTelemetryVersion telemetryVersion) { + requireNonNull(telemetryVersion, "telemetryVersion"); + this.telemetryVersion = telemetryVersion; + return this; + } + + // Visible for testing + int getMaxExportBatchSize() { + return maxExportBatchSize; + } + + /** + * Returns a new {@link BatchLogRecordProcessor} that batches, then forwards them to the given + * {@code logRecordExporter}. + * + * @return a new {@link BatchLogRecordProcessor}. + */ + public BatchLogRecordProcessor build() { + if (maxExportBatchSize > maxQueueSize) { + logger.log( + Level.WARNING, + "maxExportBatchSize should not exceed maxQueueSize. Setting maxExportBatchSize to {0} instead of {1}", + new Object[] {maxQueueSize, maxExportBatchSize}); + maxExportBatchSize = maxQueueSize; + } + return new BatchLogRecordProcessor( + logRecordExporter, + meterProvider, + telemetryVersion, + scheduleDelayNanos, + maxQueueSize, + maxExportBatchSize, + exporterTimeoutNanos); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/InMemoryLogExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/InMemoryLogExporter.java deleted file mode 100644 index 3b34f27e9af..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/InMemoryLogExporter.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -/** A {@link LogExporter} implementation that can be used to test OpenTelemetry integration. */ -public final class InMemoryLogExporter implements LogExporter { - private final Queue finishedLogItems = new ConcurrentLinkedQueue<>(); - private boolean isStopped = false; - - private InMemoryLogExporter() {} - - /** - * Returns a new instance of the {@code InMemoryLogExporter}. - * - * @return a new instance of the {@code InMemoryLogExporter}. - */ - public static InMemoryLogExporter create() { - return new InMemoryLogExporter(); - } - - /** - * Returns a {@code List} of the finished {@code Log}s, represented by {@code LogRecord}. - * - * @return a {@code List} of the finished {@code Log}s. - */ - public List getFinishedLogItems() { - return Collections.unmodifiableList(new ArrayList<>(finishedLogItems)); - } - - /** - * Clears the internal {@code List} of finished {@code Log}s. - * - *

      Does not reset the state of this exporter if already shutdown. - */ - public void reset() { - finishedLogItems.clear(); - } - - /** - * Exports the collection of {@code Log}s into the inmemory queue. - * - *

      If this is called after {@code shutdown}, this will return {@code ResultCode.FAILURE}. - */ - @Override - public CompletableResultCode export(Collection logs) { - if (isStopped) { - return CompletableResultCode.ofFailure(); - } - finishedLogItems.addAll(logs); - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - /** - * Clears the internal {@code List} of finished {@code Log}s. - * - *

      Any subsequent call to export() function on this LogExporter, will return {@code - * CompletableResultCode.ofFailure()} - */ - @Override - public CompletableResultCode shutdown() { - isStopped = true; - finishedLogItems.clear(); - return CompletableResultCode.ofSuccess(); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java new file mode 100644 index 00000000000..d95d64a15ec --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LegacyLogRecordProcessorInstrumentation.java @@ -0,0 +1,104 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** Log processor metrics defined before they were standardized in semconv. */ +final class LegacyLogRecordProcessorInstrumentation implements LogRecordProcessorInstrumentation { + private static final AttributeKey PROCESSOR_TYPE_LABEL = + AttributeKey.stringKey("processorType"); + private static final AttributeKey PROCESSOR_DROPPED_LABEL = + AttributeKey.booleanKey("dropped"); + // Legacy metrics are only created for batch log processor. + private static final String PROCESSOR_TYPE_VALUE = BatchLogRecordProcessor.class.getSimpleName(); + + private final Object lock = new Object(); + private final AtomicBoolean builtQueueMetrics = new AtomicBoolean(false); + + private final Supplier meterProvider; + private final Attributes standardAttrs; + private final Attributes droppedAttrs; + + @Nullable private Meter meter; + @Nullable private volatile LongCounter processedLogs; + + LegacyLogRecordProcessorInstrumentation(Supplier meterProvider) { + this.meterProvider = meterProvider; + + standardAttrs = + Attributes.of(PROCESSOR_TYPE_LABEL, PROCESSOR_TYPE_VALUE, PROCESSOR_DROPPED_LABEL, false); + droppedAttrs = + Attributes.of(PROCESSOR_TYPE_LABEL, PROCESSOR_TYPE_VALUE, PROCESSOR_DROPPED_LABEL, true); + } + + @Override + public void dropLogsQueueFull(int count) { + processedLogs().add(count, droppedAttrs); + } + + @Override + public void dropLogsAlreadyShutdown(int count) { + // Legacy did not record this metric. + } + + @Override + public void finishLogs(int count) { + processedLogs().add(count, standardAttrs); + } + + @Override + public void buildQueueMetricsOnce(long unusedCapacity, LongCallable getSize) { + if (!builtQueueMetrics.compareAndSet(false, true)) { + return; + } + meter() + .gaugeBuilder("queueSize") + .ofLongs() + .setDescription("The number of items queued") + .setUnit("1") + .buildWithCallback(result -> + result.record( + getSize.get(), Attributes.of(PROCESSOR_TYPE_LABEL, PROCESSOR_TYPE_VALUE))); + // No capacity metric when legacy. + } + + private LongCounter processedLogs() { + LongCounter processedLogs = this.processedLogs; + if (processedLogs == null) { + synchronized (lock) { + processedLogs = this.processedLogs; + if (processedLogs == null) { + processedLogs = + meter() + .counterBuilder("processedLogs") + .setUnit("1") + .setDescription( + "The number of logs processed by the BatchLogRecordProcessor. " + + "[dropped=true if they were dropped due to high throughput]") + .build(); + this.processedLogs = processedLogs; + } + } + } + return processedLogs; + } + + private Meter meter() { + if (meter == null) { + // Safe to call from multiple threads. + meter = meterProvider.get().get("io.opentelemetry.sdk.logs"); + } + return meter; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogExporter.java deleted file mode 100644 index 06ab373d80f..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogExporter.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; -import io.opentelemetry.sdk.logs.data.LogData; -import java.io.Closeable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.TimeUnit; - -/** - * An exporter is responsible for taking a collection of {@link LogData}s and transmitting them to - * their ultimate destination. - */ -public interface LogExporter extends Closeable { - - /** - * Returns a {@link LogExporter} which delegates all exports to the {@code exporters} in order. - * - *

      Can be used to export to multiple backends using the same {@link LogProcessor} like a {@link - * SimpleLogProcessor} or a {@link BatchLogProcessor}. - */ - static LogExporter composite(LogExporter... exporters) { - return composite(Arrays.asList(exporters)); - } - - /** - * Returns a {@link LogExporter} which delegates all exports to the {@code exporters} in order. - * - *

      Can be used to export to multiple backends using the same {@link LogProcessor} like a {@link - * SimpleLogProcessor} or a {@link BatchLogProcessor}. - */ - static LogExporter composite(Iterable exporters) { - List exportersList = new ArrayList<>(); - for (LogExporter exporter : exporters) { - exportersList.add(exporter); - } - if (exportersList.isEmpty()) { - return NoopLogExporter.getInstance(); - } - if (exportersList.size() == 1) { - return exportersList.get(0); - } - return MultiLogExporter.create(exportersList); - } - - /** - * Exports the collections of given {@link LogData}. - * - * @param logs the collection of {@link LogData} to be exported - * @return the result of the export, which is often an asynchronous operation - */ - CompletableResultCode export(Collection logs); - - /** - * Exports the collection of {@link LogData} that have not yet been exported. - * - * @return the result of the flush, which is often an asynchronous operation - */ - CompletableResultCode flush(); - - /** - * Shutdown the log exporter. Called when {@link SdkLogEmitterProvider#shutdown()} is called when - * this exporter is registered to the provider via {@link BatchLogProcessor} or {@link - * SimpleLogProcessor}. - * - * @return a {@link CompletableResultCode} which is completed when shutdown completes - */ - CompletableResultCode shutdown(); - - /** Closes this {@link LogExporter}, releasing any resources. */ - @Override - default void close() { - shutdown().join(10, TimeUnit.SECONDS); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogRecordExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogRecordExporter.java new file mode 100644 index 00000000000..cccdf326505 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogRecordExporter.java @@ -0,0 +1,97 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.io.Closeable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * An exporter is responsible for taking a collection of {@link LogRecordData}s and transmitting + * them to their ultimate destination. + * + * @since 1.27.0 + */ +public interface LogRecordExporter extends Closeable { + + /** + * Returns a {@link LogRecordExporter} which delegates all exports to the {@code exporters} in + * order. + * + *

      Can be used to export to multiple backends using the same {@link LogRecordProcessor} like a + * {@link SimpleLogRecordProcessor} or a {@link BatchLogRecordProcessor}. + */ + static LogRecordExporter composite(LogRecordExporter... exporters) { + return composite(Arrays.asList(exporters)); + } + + /** + * Returns a {@link LogRecordExporter} which delegates all exports to the {@code exporters} in + * order. + * + *

      Can be used to export to multiple backends using the same {@link LogRecordProcessor} like a + * {@link SimpleLogRecordProcessor} or a {@link BatchLogRecordProcessor}. + */ + static LogRecordExporter composite(Iterable exporters) { + List exportersList = new ArrayList<>(); + for (LogRecordExporter exporter : exporters) { + exportersList.add(exporter); + } + if (exportersList.isEmpty()) { + return NoopLogRecordExporter.getInstance(); + } + if (exportersList.size() == 1) { + return exportersList.get(0); + } + return MultiLogRecordExporter.create(exportersList); + } + + /** + * Returns a {@link LogRecordExporter} that does nothing. All exported LogRecordData are ignored. + * + * @since 1.63.0 + */ + static LogRecordExporter noop() { + return NoopLogRecordExporter.getInstance(); + } + + /** + * Exports the collections of given {@link LogRecordData}. + * + * @param logs the collection of {@link LogRecordData} to be exported + * @return the result of the export, which is often an asynchronous operation + */ + CompletableResultCode export(Collection logs); + + /** + * Exports the collection of {@link LogRecordData} that have not yet been exported. + * + * @return the result of the flush, which is often an asynchronous operation + */ + CompletableResultCode flush(); + + /** + * Shutdown the log exporter. Called when {@link SdkLoggerProvider#shutdown()} is called when this + * exporter is registered to the provider via {@link BatchLogRecordProcessor} or {@link + * SimpleLogRecordProcessor}. + * + * @return a {@link CompletableResultCode} which is completed when shutdown completes + */ + CompletableResultCode shutdown(); + + /** Closes this {@link LogRecordExporter}, releasing any resources. */ + @Override + default void close() { + shutdown().join(10, TimeUnit.SECONDS); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogRecordProcessorInstrumentation.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogRecordProcessorInstrumentation.java new file mode 100644 index 00000000000..cc3a17a6fa2 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LogRecordProcessorInstrumentation.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import java.util.function.Supplier; + +/** Metrics exported by span processors. */ +interface LogRecordProcessorInstrumentation { + + static LogRecordProcessorInstrumentation get( + InternalTelemetryVersion telemetryVersion, + ComponentId componentId, + Supplier meterProvider) { + switch (telemetryVersion) { + case LEGACY: + return new LegacyLogRecordProcessorInstrumentation(meterProvider); + default: + return new SemConvLogRecordProcessorInstrumentation(componentId, meterProvider); + } + } + + /** Records metrics for logs dropped because a queue is full. */ + void dropLogsQueueFull(int count); + + /** Record metrics for logs dropped since processor is shutdown. */ + void dropLogsAlreadyShutdown(int count); + + /** Record metrics for logs processed successfully. */ + void finishLogs(int count); + + /** Registers metrics for processor queue capacity and size. */ + void buildQueueMetricsOnce(long capacity, LongCallable getSize); +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LongCallable.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LongCallable.java new file mode 100644 index 00000000000..b5c85f2ced5 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/LongCallable.java @@ -0,0 +1,13 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +/** A Callable returning a primitive long value. */ +@FunctionalInterface +interface LongCallable { + /** Returns the value. */ + long get(); +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/MultiLogExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/MultiLogExporter.java deleted file mode 100644 index 216d03f57ee..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/MultiLogExporter.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * {@link LogExporter} that forwards all received logs to a list of {@link LogExporter}. - * - *

      Can be used to export to multiple backends using the same {@link LogExporter} like a {@link - * SimpleLogProcessor} or a {@link BatchLogProcessor}. - */ -final class MultiLogExporter implements LogExporter { - private static final Logger logger = Logger.getLogger(MultiLogExporter.class.getName()); - - private final LogExporter[] logExporters; - - /** - * Constructs and returns an instance of this class. - * - * @param logExporters the exporters logs should be sent to - * @return the aggregate log exporter - */ - static LogExporter create(List logExporters) { - return new MultiLogExporter(logExporters.toArray(new LogExporter[0])); - } - - @Override - public CompletableResultCode export(Collection logs) { - List results = new ArrayList<>(logExporters.length); - for (LogExporter logExporter : logExporters) { - CompletableResultCode exportResult; - try { - exportResult = logExporter.export(logs); - } catch (RuntimeException e) { - // If an exception was thrown by the exporter - logger.log(Level.WARNING, "Exception thrown by the export.", e); - results.add(CompletableResultCode.ofFailure()); - continue; - } - results.add(exportResult); - } - return CompletableResultCode.ofAll(results); - } - - /** - * Flushes the data of all registered {@link LogExporter}s. - * - * @return the result of the operation - */ - @Override - public CompletableResultCode flush() { - List results = new ArrayList<>(logExporters.length); - for (LogExporter logExporter : logExporters) { - CompletableResultCode flushResult; - try { - flushResult = logExporter.flush(); - } catch (RuntimeException e) { - // If an exception was thrown by the exporter - logger.log(Level.WARNING, "Exception thrown by the flush.", e); - results.add(CompletableResultCode.ofFailure()); - continue; - } - results.add(flushResult); - } - return CompletableResultCode.ofAll(results); - } - - @Override - public CompletableResultCode shutdown() { - List results = new ArrayList<>(logExporters.length); - for (LogExporter logExporter : logExporters) { - CompletableResultCode shutdownResult; - try { - shutdownResult = logExporter.shutdown(); - } catch (RuntimeException e) { - // If an exception was thrown by the exporter - logger.log(Level.WARNING, "Exception thrown by the shutdown.", e); - results.add(CompletableResultCode.ofFailure()); - continue; - } - results.add(shutdownResult); - } - return CompletableResultCode.ofAll(results); - } - - private MultiLogExporter(LogExporter[] logExporters) { - this.logExporters = logExporters; - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/MultiLogRecordExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/MultiLogRecordExporter.java new file mode 100644 index 00000000000..92004ec8c75 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/MultiLogRecordExporter.java @@ -0,0 +1,112 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.internal.ThrowableUtil; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * {@link LogRecordExporter} that forwards all received logs to a list of {@link LogRecordExporter}. + * + *

      Can be used to export to multiple backends using the same {@link LogRecordExporter} like a + * {@link SimpleLogRecordProcessor} or a {@link BatchLogRecordProcessor}. + */ +final class MultiLogRecordExporter implements LogRecordExporter { + private static final Logger logger = Logger.getLogger(MultiLogRecordExporter.class.getName()); + + private final LogRecordExporter[] logRecordExporters; + + private MultiLogRecordExporter(LogRecordExporter[] logRecordExporters) { + this.logRecordExporters = logRecordExporters; + } + + /** + * Constructs and returns an instance of this class. + * + * @param logRecordExporters the exporters logs should be sent to + * @return the aggregate log exporter + */ + static LogRecordExporter create(List logRecordExporters) { + return new MultiLogRecordExporter(logRecordExporters.toArray(new LogRecordExporter[0])); + } + + @Override + public CompletableResultCode export(Collection logs) { + List results = new ArrayList<>(logRecordExporters.length); + for (LogRecordExporter logRecordExporter : logRecordExporters) { + CompletableResultCode exportResult; + try { + exportResult = logRecordExporter.export(logs); + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); + // If an exception was thrown by the exporter + logger.log(Level.WARNING, "Exception thrown by the export.", t); + results.add(CompletableResultCode.ofFailure()); + continue; + } + results.add(exportResult); + } + return CompletableResultCode.ofAll(results); + } + + /** + * Flushes the data of all registered {@link LogRecordExporter}s. + * + * @return the result of the operation + */ + @Override + public CompletableResultCode flush() { + List results = new ArrayList<>(logRecordExporters.length); + for (LogRecordExporter logRecordExporter : logRecordExporters) { + CompletableResultCode flushResult; + try { + flushResult = logRecordExporter.flush(); + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); + // If an exception was thrown by the exporter + logger.log(Level.WARNING, "Exception thrown by the flush.", t); + results.add(CompletableResultCode.ofFailure()); + continue; + } + results.add(flushResult); + } + return CompletableResultCode.ofAll(results); + } + + @Override + public CompletableResultCode shutdown() { + List results = new ArrayList<>(logRecordExporters.length); + for (LogRecordExporter logRecordExporter : logRecordExporters) { + CompletableResultCode shutdownResult; + try { + shutdownResult = logRecordExporter.shutdown(); + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); + // If an exception was thrown by the exporter + logger.log(Level.WARNING, "Exception thrown by the shutdown.", t); + results.add(CompletableResultCode.ofFailure()); + continue; + } + results.add(shutdownResult); + } + return CompletableResultCode.ofAll(results); + } + + @Override + public String toString() { + return "MultiLogRecordExporter{" + + "logRecordExporters=" + + Arrays.toString(logRecordExporters) + + '}'; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/NoopLogExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/NoopLogExporter.java deleted file mode 100644 index fe11b98c4b4..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/NoopLogExporter.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import java.util.Collection; - -final class NoopLogExporter implements LogExporter { - - private static final LogExporter INSTANCE = new NoopLogExporter(); - - static LogExporter getInstance() { - return INSTANCE; - } - - @Override - public CompletableResultCode export(Collection logs) { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - return CompletableResultCode.ofSuccess(); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/NoopLogRecordExporter.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/NoopLogRecordExporter.java new file mode 100644 index 00000000000..8c0018826f4 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/NoopLogRecordExporter.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.Collection; + +final class NoopLogRecordExporter implements LogRecordExporter { + + private static final LogRecordExporter INSTANCE = new NoopLogRecordExporter(); + + static LogRecordExporter getInstance() { + return INSTANCE; + } + + @Override + public CompletableResultCode export(Collection logs) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SemConvLogRecordProcessorInstrumentation.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SemConvLogRecordProcessorInstrumentation.java new file mode 100644 index 00000000000..62b3ba09509 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SemConvLogRecordProcessorInstrumentation.java @@ -0,0 +1,122 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * SDK metrics exported for log processors as defined in the semantic + * conventions. + */ +final class SemConvLogRecordProcessorInstrumentation implements LogRecordProcessorInstrumentation { + + private final Object lock = new Object(); + private final AtomicBoolean builtQueueMetrics = new AtomicBoolean(false); + + private final Supplier meterProvider; + private final Attributes standardAttrs; + private final Attributes queueFullAttrs; + private final Attributes shutdownAttrs; + + @Nullable private Meter meter; + @Nullable private volatile LongCounter processedLogs; + + SemConvLogRecordProcessorInstrumentation( + ComponentId componentId, Supplier meterProvider) { + this.meterProvider = meterProvider; + + standardAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName()); + queueFullAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName(), + SemConvConstants.ERROR_TYPE, + "queue_full"); + shutdownAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName(), + SemConvConstants.ERROR_TYPE, + "already_shutdown"); + } + + @Override + public void dropLogsQueueFull(int count) { + processedLogs().add(count, queueFullAttrs); + } + + @Override + public void dropLogsAlreadyShutdown(int count) { + processedLogs().add(count, shutdownAttrs); + } + + @Override + public void finishLogs(int count) { + processedLogs().add(count, standardAttrs); + } + + @Override + public void buildQueueMetricsOnce(long capacity, LongCallable getSize) { + if (!builtQueueMetrics.compareAndSet(false, true)) { + return; + } + meter() + .upDownCounterBuilder(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_NAME) + .setUnit(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_CAPACITY_DESCRIPTION) + .buildWithCallback(m -> m.record(capacity, standardAttrs)); + meter() + .upDownCounterBuilder(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_NAME) + .setUnit(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_QUEUE_SIZE_DESCRIPTION) + .buildWithCallback(m -> m.record(getSize.get(), standardAttrs)); + } + + private LongCounter processedLogs() { + LongCounter processedLogs = this.processedLogs; + if (processedLogs == null) { + synchronized (lock) { + processedLogs = this.processedLogs; + if (processedLogs == null) { + processedLogs = + meter() + .counterBuilder(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_PROCESSED_NAME) + .setUnit(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_PROCESSED_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_PROCESSOR_LOG_PROCESSED_DESCRIPTION) + .build(); + this.processedLogs = processedLogs; + } + } + } + return processedLogs; + } + + private Meter meter() { + if (meter == null) { + // Safe to call from multiple threads. + meter = meterProvider.get().get("io.opentelemetry.sdk.logs"); + } + return meter; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogProcessor.java deleted file mode 100644 index ff1049ae742..00000000000 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogProcessor.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import static java.util.Objects.requireNonNull; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.data.LogData; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -/** - * An implementation of the {@link LogProcessor} that passes {@link LogData} directly to the - * configured exporter. - * - *

      This processor will cause all logs to be exported directly as they finish, meaning each export - * request will have a single log. Most backends will not perform well with a single log per request - * so unless you know what you're doing, strongly consider using {@link BatchLogProcessor} instead, - * including in special environments such as serverless runtimes. {@link SimpleLogProcessor} is - * generally meant to for testing only. - */ -public final class SimpleLogProcessor implements LogProcessor { - - private static final Logger logger = Logger.getLogger(SimpleLogProcessor.class.getName()); - - private final LogExporter logExporter; - private final Set pendingExports = - Collections.newSetFromMap(new ConcurrentHashMap<>()); - private final AtomicBoolean isShutdown = new AtomicBoolean(false); - - /** - * Returns a new {@link SimpleLogProcessor} which exports logs to the {@link LogExporter} - * synchronously. - * - *

      This processor will cause all logs to be exported directly as they finish, meaning each - * export request will have a single log. Most backends will not perform well with a single log - * per request so unless you know what you're doing, strongly consider using {@link - * BatchLogProcessor} instead, including in special environments such as serverless runtimes. - * {@link SimpleLogProcessor} is generally meant to for testing only. - */ - public static LogProcessor create(LogExporter exporter) { - requireNonNull(exporter, "exporter"); - return new SimpleLogProcessor(exporter); - } - - SimpleLogProcessor(LogExporter logExporter) { - this.logExporter = requireNonNull(logExporter, "logExporter"); - } - - @Override - public void emit(LogData logData) { - try { - List logs = Collections.singletonList(logData); - CompletableResultCode result = logExporter.export(logs); - pendingExports.add(result); - result.whenComplete( - () -> { - pendingExports.remove(result); - if (!result.isSuccess()) { - logger.log(Level.FINE, "Exporter failed"); - } - }); - } catch (RuntimeException e) { - logger.log(Level.WARNING, "Exporter threw an Exception", e); - } - } - - @Override - public CompletableResultCode shutdown() { - if (isShutdown.getAndSet(true)) { - return CompletableResultCode.ofSuccess(); - } - CompletableResultCode result = new CompletableResultCode(); - - CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - CompletableResultCode shutdownResult = logExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); - - return result; - } - - @Override - public CompletableResultCode forceFlush() { - return CompletableResultCode.ofAll(pendingExports); - } -} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java new file mode 100644 index 00000000000..7c1b1f8aec6 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessor.java @@ -0,0 +1,158 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.ThrowableUtil; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.ReadWriteLogRecord; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * An implementation of the {@link LogRecordProcessor} that passes {@link LogRecordData} directly to + * the configured exporter. + * + *

      This processor will cause all logs to be exported directly as they finish, meaning each export + * request will have a single log. Most backends will not perform well with a single log per request + * so unless you know what you're doing, strongly consider using {@link BatchLogRecordProcessor} + * instead, including in special environments such as serverless runtimes. {@link + * SimpleLogRecordProcessor} is generally meant to for testing only. + * + * @since 1.27.0 + */ +public final class SimpleLogRecordProcessor implements LogRecordProcessor { + + private static final ComponentId COMPONENT_ID = ComponentId.generateLazy("simple_log_processor"); + + private static final Logger logger = Logger.getLogger(SimpleLogRecordProcessor.class.getName()); + + private final LogRecordExporter logRecordExporter; + private final Set pendingExports = + Collections.newSetFromMap(new ConcurrentHashMap<>()); + private final AtomicBoolean isShutdown = new AtomicBoolean(false); + private final LogRecordProcessorInstrumentation logProcessorInstrumentation; + + private final Object exporterLock = new Object(); + + /** + * Returns a new {@link SimpleLogRecordProcessor} which exports logs to the {@link + * LogRecordExporter} synchronously. + * + *

      This processor will cause all logs to be exported directly as they finish, meaning each + * export request will have a single log. Most backends will not perform well with a single log + * per request so unless you know what you're doing, strongly consider using {@link + * BatchLogRecordProcessor} instead, including in special environments such as serverless + * runtimes. {@link SimpleLogRecordProcessor} is generally meant to for testing only. + */ + public static LogRecordProcessor create(LogRecordExporter exporter) { + requireNonNull(exporter, "exporter"); + return builder(exporter).build(); + } + + /** + * Returns a new Builder for {@link SimpleLogRecordProcessor}. + * + * @since 1.58.0 + */ + public static SimpleLogRecordProcessorBuilder builder(LogRecordExporter exporter) { + requireNonNull(exporter, "exporter"); + return new SimpleLogRecordProcessorBuilder(exporter); + } + + SimpleLogRecordProcessor( + LogRecordExporter logRecordExporter, Supplier meterProvider) { + this.logRecordExporter = requireNonNull(logRecordExporter, "logRecordExporter"); + logProcessorInstrumentation = + LogRecordProcessorInstrumentation.get( + InternalTelemetryVersion.LATEST, COMPONENT_ID, meterProvider); + } + + @Override + public void onEmit(Context context, ReadWriteLogRecord logRecord) { + if (isShutdown.get()) { + logProcessorInstrumentation.dropLogsAlreadyShutdown(1); + return; + } + + try { + List logs = Collections.singletonList(logRecord.toLogRecordData()); + CompletableResultCode result; + + synchronized (exporterLock) { + // We always increment for every export invocation, so we increment before the export call + // to make sure thrown errors don't affect it. + logProcessorInstrumentation.finishLogs(1); + result = logRecordExporter.export(logs); + } + + pendingExports.add(result); + result.whenComplete(() -> { + pendingExports.remove(result); + if (!result.isSuccess()) { + logger.log(Level.FINE, "Exporter failed"); + } + }); + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); + logger.log(Level.WARNING, "Exporter threw an Exception", t); + } + } + + @Override + public CompletableResultCode shutdown() { + if (isShutdown.getAndSet(true)) { + return CompletableResultCode.ofSuccess(); + } + CompletableResultCode result = new CompletableResultCode(); + + CompletableResultCode flushResult = forceFlush(); + flushResult.whenComplete(() -> { + CompletableResultCode shutdownResult = logRecordExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); + + return result; + } + + @Override + public CompletableResultCode forceFlush() { + return CompletableResultCode.ofAll(pendingExports); + } + + /** + * Return the processor's configured {@link LogRecordExporter}. + * + * @since 1.37.0 + */ + public LogRecordExporter getLogRecordExporter() { + return logRecordExporter; + } + + @Override + public String toString() { + return "SimpleLogRecordProcessor{" + "logRecordExporter=" + logRecordExporter + '}'; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorBuilder.java new file mode 100644 index 00000000000..a900186cc69 --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorBuilder.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.metrics.MeterProvider; +import java.util.function.Supplier; + +/** + * Builder for {@link SimpleLogRecordProcessor}. + * + * @since 1.58.0 + */ +public final class SimpleLogRecordProcessorBuilder { + private final LogRecordExporter exporter; + private Supplier meterProvider = MeterProvider::noop; + + SimpleLogRecordProcessorBuilder(LogRecordExporter exporter) { + this.exporter = requireNonNull(exporter, "exporter"); + } + + /** + * Sets the {@link MeterProvider} to use to generate SDK Log + * Metrics. + */ + public SimpleLogRecordProcessorBuilder setMeterProvider(Supplier meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = meterProvider; + return this; + } + + // TODO: add `setInternalTelemetryVersion when we support more than one version + + /** + * Returns a new {@link SimpleLogRecordProcessor} with the configuration of this builder. + * + * @return a new {@link SimpleLogRecordProcessor}. + */ + public SimpleLogRecordProcessor build() { + return new SimpleLogRecordProcessor(exporter, meterProvider); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/LoggerConfig.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/LoggerConfig.java new file mode 100644 index 00000000000..3b1b7dc2eac --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/LoggerConfig.java @@ -0,0 +1,104 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import java.util.function.Predicate; +import javax.annotation.concurrent.Immutable; + +/** + * A collection of configuration options which define the behavior of a {@link Logger}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + * + * @see SdkLoggerProviderUtil#setLoggerConfigurator(SdkLoggerProviderBuilder, ScopeConfigurator) + * @see SdkLoggerProviderUtil#addLoggerConfiguratorCondition(SdkLoggerProviderBuilder, Predicate, + * LoggerConfig) + */ +@AutoValue +@Immutable +public abstract class LoggerConfig { + + private static final LoggerConfig DEFAULT_CONFIG = + new AutoValue_LoggerConfig( + /* enabled= */ true, + /* minimumSeverity= */ Severity.UNDEFINED_SEVERITY_NUMBER, + /* traceBased= */ false); + private static final LoggerConfig DISABLED_CONFIG = + new AutoValue_LoggerConfig( + /* enabled= */ false, + /* minimumSeverity= */ Severity.UNDEFINED_SEVERITY_NUMBER, + /* traceBased= */ false); + + /** Returns a disabled {@link LoggerConfig}. */ + public static LoggerConfig disabled() { + return DISABLED_CONFIG; + } + + /** Returns an enabled {@link LoggerConfig}. */ + public static LoggerConfig enabled() { + return DEFAULT_CONFIG; + } + + /** Returns a new {@link LoggerConfigBuilder} for creating a {@link LoggerConfig}. */ + public static LoggerConfigBuilder builder() { + return new LoggerConfigBuilder(); + } + + /** + * Returns the default {@link LoggerConfig}, which is used when no configurator is set or when the + * logger configurator returns {@code null} for a {@link InstrumentationScopeInfo}. + */ + public static LoggerConfig defaultConfig() { + return DEFAULT_CONFIG; + } + + /** + * Create a {@link ScopeConfiguratorBuilder} for configuring {@link + * SdkLoggerProviderUtil#setLoggerConfigurator(SdkLoggerProviderBuilder, ScopeConfigurator)}. + */ + public static ScopeConfiguratorBuilder configuratorBuilder() { + return ScopeConfigurator.builder(); + } + + LoggerConfig() {} + + static LoggerConfig create(boolean enabled, Severity minimumSeverity, boolean traceBased) { + return new AutoValue_LoggerConfig(enabled, minimumSeverity, traceBased); + } + + /** Returns {@code true} if this logger is enabled. Defaults to {@code true}. */ + public abstract boolean isEnabled(); + + /** + * Returns the minimum severity level for log records to be processed. + * + *

      Log records with a severity number less than this value will be dropped. Log records without + * a specified severity are not affected by this setting. + * + *

      Defaults to {@link Severity#UNDEFINED_SEVERITY_NUMBER}. + */ + public abstract Severity getMinimumSeverity(); + + /** + * Returns {@code true} if this logger should only process log records from traces when the trace + * is sampled. + * + *

      When enabled, log records from unsampled traces will be dropped. Log records that are not + * associated with a trace context are unaffected. + * + *

      Defaults to {@code false}. + */ + public abstract boolean isTraceBased(); +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/LoggerConfigBuilder.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/LoggerConfigBuilder.java new file mode 100644 index 00000000000..af77cce7c9c --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/LoggerConfigBuilder.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.internal; + +import io.opentelemetry.api.logs.Severity; + +/** + * Builder for {@link LoggerConfig}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class LoggerConfigBuilder { + private boolean enabled = true; + private Severity minimumSeverity = Severity.UNDEFINED_SEVERITY_NUMBER; + private boolean traceBased = false; + + LoggerConfigBuilder() {} + + /** + * Sets whether the logger is enabled. + * + * @param enabled whether the logger is enabled + * @return this builder + */ + public LoggerConfigBuilder setEnabled(boolean enabled) { + this.enabled = enabled; + return this; + } + + /** + * Sets the minimum severity level for log records to be processed. + * + *

      Log records with a severity number less than this value will be dropped. Log records without + * a specified severity are not affected by this setting. + * + * @param minimumSeverity minimum severity level for log records to be processed + * @return this builder + */ + public LoggerConfigBuilder setMinimumSeverity(Severity minimumSeverity) { + this.minimumSeverity = minimumSeverity; + return this; + } + + /** + * Sets whether to only process log records from traces when the trace is sampled. + * + *

      When enabled, log records from unsampled traces will be dropped. Log records that are not + * associated with a trace context are unaffected. + * + * @param traceBased whether to only process log records from traces when the trace is sampled + * @return this builder + */ + public LoggerConfigBuilder setTraceBased(boolean traceBased) { + this.traceBased = traceBased; + return this; + } + + /** Builds and returns a {@link LoggerConfig}. */ + public LoggerConfig build() { + return LoggerConfig.create(enabled, minimumSeverity, traceBased); + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/SdkLoggerProviderUtil.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/SdkLoggerProviderUtil.java new file mode 100644 index 00000000000..4d63ceea0af --- /dev/null +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/internal/SdkLoggerProviderUtil.java @@ -0,0 +1,143 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.internal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.function.BiPredicate; +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** + * A collection of methods that allow use of experimental features prior to availability in public + * APIs. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class SdkLoggerProviderUtil { + + private SdkLoggerProviderUtil() {} + + /** Reflectively set the {@link SdkResourceProvider} on the {@link SdkLoggerProviderBuilder}. */ + public static void setSdkResourceProvider( + SdkLoggerProviderBuilder sdkLoggerProviderBuilder, SdkResourceProvider resourceProvider) { + try { + Method method = + SdkLoggerProviderBuilder.class.getDeclaredMethod( + "setSdkResourceProvider", SdkResourceProvider.class); + method.setAccessible(true); + method.invoke(sdkLoggerProviderBuilder, resourceProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setSdkResourceProvider on SdkLoggerProviderBuilder", e); + } + } + + /** Reflectively get the {@link SdkResourceProvider} from the {@link SdkLoggerProvider}. */ + public static SdkResourceProvider getSdkResourceProvider(SdkLoggerProvider sdkLoggerProvider) { + try { + Method method = SdkLoggerProvider.class.getDeclaredMethod("getSdkResourceProvider"); + method.setAccessible(true); + return (SdkResourceProvider) method.invoke(sdkLoggerProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling getSdkResourceProvider on SdkLoggerProvider", e); + } + } + + /** Reflectively set the {@link ScopeConfigurator} to the {@link SdkLoggerProvider}. */ + public static void setLoggerConfigurator( + SdkLoggerProvider sdkLoggerProvider, ScopeConfigurator scopeConfigurator) { + try { + Method method = + SdkLoggerProvider.class.getDeclaredMethod( + "setLoggerConfigurator", ScopeConfigurator.class); + method.setAccessible(true); + method.invoke(sdkLoggerProvider, scopeConfigurator); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setLoggerConfigurator on SdkLoggerProvider", e); + } + } + + /** Reflectively set the {@link ScopeConfigurator} to the {@link SdkLoggerProviderBuilder}. */ + public static SdkLoggerProviderBuilder setLoggerConfigurator( + SdkLoggerProviderBuilder sdkLoggerProviderBuilder, + ScopeConfigurator loggerConfigurator) { + try { + Method method = + SdkLoggerProviderBuilder.class.getDeclaredMethod( + "setLoggerConfigurator", ScopeConfigurator.class); + method.setAccessible(true); + method.invoke(sdkLoggerProviderBuilder, loggerConfigurator); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setLoggerConfigurator on SdkLoggerProviderBuilder", e); + } + return sdkLoggerProviderBuilder; + } + + /** Reflectively add a logger configurator condition to the {@link SdkLoggerProviderBuilder}. */ + public static SdkLoggerProviderBuilder addLoggerConfiguratorCondition( + SdkLoggerProviderBuilder sdkLoggerProviderBuilder, + Predicate scopeMatcher, + LoggerConfig loggerConfig) { + try { + Method method = + SdkLoggerProviderBuilder.class.getDeclaredMethod( + "addLoggerConfiguratorCondition", Predicate.class, LoggerConfig.class); + method.setAccessible(true); + method.invoke(sdkLoggerProviderBuilder, scopeMatcher, loggerConfig); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling addLoggerConfiguratorCondition on SdkLoggerProviderBuilder", e); + } + return sdkLoggerProviderBuilder; + } + + /** Reflectively set exception attribute resolver to the {@link SdkLoggerProviderBuilder}. */ + public static void setExceptionAttributeResolver( + SdkLoggerProviderBuilder sdkLoggerProviderBuilder, + ExceptionAttributeResolver exceptionAttributeResolver) { + try { + Method method = + SdkLoggerProviderBuilder.class.getDeclaredMethod( + "setExceptionAttributeResolver", ExceptionAttributeResolver.class); + method.setAccessible(true); + method.invoke(sdkLoggerProviderBuilder, exceptionAttributeResolver); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setExceptionAttributeResolver on SdkLoggerProviderBuilder", e); + } + } + + /** + * Reflectively set the context-scoped attributes filter on the {@link SdkLoggerProviderBuilder}. + */ + public static SdkLoggerProviderBuilder setContextScopedAttributesFilter( + SdkLoggerProviderBuilder sdkLoggerProviderBuilder, + @Nullable BiPredicate> filter) { + try { + Method method = + SdkLoggerProviderBuilder.class.getDeclaredMethod( + "setContextScopedAttributesFilter", BiPredicate.class); + method.setAccessible(true); + method.invoke(sdkLoggerProviderBuilder, filter); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setContextScopedAttributesFilter on SdkLoggerProviderBuilder", e); + } + return sdkLoggerProviderBuilder; + } +} diff --git a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/package-info.java b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/package-info.java index 3382f24ef97..cbb91d85898 100644 --- a/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/package-info.java +++ b/sdk/logs/src/main/java/io/opentelemetry/sdk/logs/package-info.java @@ -6,7 +6,7 @@ /** * The OpenTelemetry SDK implementation of logging. * - * @see io.opentelemetry.sdk.logs.SdkLogEmitterProvider + * @see io.opentelemetry.sdk.logs.SdkLoggerProvider */ @ParametersAreNonnullByDefault package io.opentelemetry.sdk.logs; diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogEmitterSharedStateTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogEmitterSharedStateTest.java deleted file mode 100644 index 625cf32ca90..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogEmitterSharedStateTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Collections; -import java.util.List; -import org.junit.jupiter.api.Test; - -class LogEmitterSharedStateTest { - - @Test - void shutdown() { - LogProcessor logProcessor = mock(LogProcessor.class); - CompletableResultCode code = new CompletableResultCode(); - when(logProcessor.shutdown()).thenReturn(code); - List processors = Collections.singletonList(logProcessor); - LogEmitterSharedState state = - new LogEmitterSharedState( - Resource.empty(), LogLimits::getDefault, processors, Clock.getDefault()); - state.shutdown(); - state.shutdown(); - verify(logProcessor, times(1)).shutdown(); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogLimitsTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogLimitsTest.java index 250d49f8402..06b128eeb5b 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogLimitsTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LogLimitsTest.java @@ -6,6 +6,7 @@ package io.opentelemetry.sdk.logs; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.jupiter.api.Test; @@ -28,16 +29,25 @@ void updateLogLimits_All() { // Preserves values LogLimits logLimitsDupe = logLimits.toBuilder().build(); // Use reflective comparison to catch when new fields are added. - assertThat(logLimitsDupe).usingRecursiveComparison().isEqualTo(logLimits); + assertThat(logLimitsDupe) + .usingRecursiveComparison() + .withStrictTypeChecking() + .isEqualTo(logLimits); } @Test void invalidLogLimits() { - assertThatThrownBy(() -> LogLimits.builder().setMaxNumberOfAttributes(0)) - .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> LogLimits.builder().setMaxNumberOfAttributes(-1)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> LogLimits.builder().setMaxAttributeValueLength(-1)) .isInstanceOf(IllegalArgumentException.class); } + + @Test + void validLogLimits() { + assertThatCode(() -> LogLimits.builder().setMaxNumberOfAttributes(0)) + .doesNotThrowAnyException(); + assertThatCode(() -> LogLimits.builder().setMaxAttributeValueLength(0)) + .doesNotThrowAnyException(); + } } diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LoggerSharedStateTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LoggerSharedStateTest.java new file mode 100644 index 00000000000..e42a6acfa36 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/LoggerSharedStateTest.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import org.junit.jupiter.api.Test; + +class LoggerSharedStateTest { + + @Test + void shutdown() { + LogRecordProcessor logRecordProcessor = mock(LogRecordProcessor.class); + CompletableResultCode code = new CompletableResultCode(); + when(logRecordProcessor.shutdown()).thenReturn(code); + LoggerSharedState state = + new LoggerSharedState( + SdkResourceProvider.create(Resource.empty()), + LogLimits::getDefault, + logRecordProcessor, + Clock.getDefault(), + ExceptionAttributeResolver.getDefault(), + new SdkLoggerInstrumentation(MeterProvider::noop), + /* contextScopedAttributesFilter= */ null); + state.shutdown(); + state.shutdown(); + verify(logRecordProcessor, times(1)).shutdown(); + } + + @Test + void contextScopedAttributesFilter() { + LoggerSharedState stateEnabled = + new LoggerSharedState( + SdkResourceProvider.create(Resource.empty()), + LogLimits::getDefault, + mock(LogRecordProcessor.class), + Clock.getDefault(), + ExceptionAttributeResolver.getDefault(), + new SdkLoggerInstrumentation(MeterProvider::noop), + (scope, key) -> true); + assertThat(stateEnabled.getContextScopedAttributesFilter()).isNotNull(); + + LoggerSharedState stateDisabled = + new LoggerSharedState( + SdkResourceProvider.create(Resource.empty()), + LogLimits::getDefault, + mock(LogRecordProcessor.class), + Clock.getDefault(), + ExceptionAttributeResolver.getDefault(), + new SdkLoggerInstrumentation(MeterProvider::noop), + /* contextScopedAttributesFilter= */ null); + assertThat(stateDisabled.getContextScopedAttributesFilter()).isNull(); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/MultiLogProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/MultiLogProcessorTest.java deleted file mode 100644 index 5d8e1c23585..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/MultiLogProcessorTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.logs.util.TestUtil; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; - -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.LENIENT) -class MultiLogProcessorTest { - - @Mock private LogProcessor logProcessor1; - @Mock private LogProcessor logProcessor2; - private static final LogData logData = TestUtil.createLogData(Severity.DEBUG, "message"); - - @BeforeEach - void setup() { - when(logProcessor1.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); - when(logProcessor2.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); - when(logProcessor1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - when(logProcessor2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - } - - @Test - void empty() { - LogProcessor multiLogProcessor = LogProcessor.composite(); - assertThat(multiLogProcessor).isInstanceOf(NoopLogProcessor.class); - multiLogProcessor.emit(logData); - multiLogProcessor.shutdown(); - } - - @Test - void oneLogProcessor() { - LogProcessor multiLogProcessor = LogProcessor.composite(logProcessor1); - assertThat(multiLogProcessor).isSameAs(logProcessor1); - } - - @Test - void twoLogProcessor() { - LogProcessor multiLogProcessor = LogProcessor.composite(logProcessor1, logProcessor2); - multiLogProcessor.emit(logData); - verify(logProcessor1).emit(same(logData)); - verify(logProcessor2).emit(same(logData)); - - multiLogProcessor.forceFlush(); - verify(logProcessor1).forceFlush(); - verify(logProcessor2).forceFlush(); - - multiLogProcessor.shutdown(); - verify(logProcessor1).shutdown(); - verify(logProcessor2).shutdown(); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/MultiLogRecordProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/MultiLogRecordProcessorTest.java new file mode 100644 index 00000000000..57aaa61fc32 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/MultiLogRecordProcessorTest.java @@ -0,0 +1,70 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class MultiLogRecordProcessorTest { + + @Mock private LogRecordProcessor logRecordProcessor1; + @Mock private LogRecordProcessor logRecordProcessor2; + @Mock private ReadWriteLogRecord logRecord; + + @BeforeEach + void setup() { + when(logRecordProcessor1.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordProcessor2.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordProcessor1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordProcessor2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + } + + @Test + void empty() { + LogRecordProcessor multiLogRecordProcessor = LogRecordProcessor.composite(); + assertThat(multiLogRecordProcessor).isInstanceOf(NoopLogRecordProcessor.class); + multiLogRecordProcessor.onEmit(Context.current(), logRecord); + multiLogRecordProcessor.shutdown(); + } + + @Test + void oneLogRecordProcessor() { + LogRecordProcessor multiLogRecordProcessor = LogRecordProcessor.composite(logRecordProcessor1); + assertThat(multiLogRecordProcessor).isSameAs(logRecordProcessor1); + } + + @Test + void twoLogRecordProcessor() { + LogRecordProcessor multiLogRecordProcessor = + LogRecordProcessor.composite(logRecordProcessor1, logRecordProcessor2); + Context context = Context.current(); + multiLogRecordProcessor.onEmit(context, logRecord); + verify(logRecordProcessor1).onEmit(same(context), same(logRecord)); + verify(logRecordProcessor2).onEmit(same(context), same(logRecord)); + + multiLogRecordProcessor.forceFlush(); + verify(logRecordProcessor1).forceFlush(); + verify(logRecordProcessor2).forceFlush(); + + multiLogRecordProcessor.shutdown(); + verify(logRecordProcessor1).shutdown(); + verify(logRecordProcessor2).shutdown(); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/NoopLogProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/NoopLogProcessorTest.java deleted file mode 100644 index 40ac3f57820..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/NoopLogProcessorTest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.logs.util.TestUtil; -import org.junit.jupiter.api.Test; - -class NoopLogProcessorTest { - - @Test - void noCrash() { - LogProcessor logProcessor = NoopLogProcessor.getInstance(); - logProcessor.emit(TestUtil.createLogData(Severity.DEBUG, "message")); - assertThat(logProcessor.forceFlush().isSuccess()).isEqualTo(true); - assertThat(logProcessor.shutdown().isSuccess()).isEqualTo(true); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/NoopLogRecordProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/NoopLogRecordProcessorTest.java new file mode 100644 index 00000000000..ed473c0d7ff --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/NoopLogRecordProcessorTest.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; + +import io.opentelemetry.context.Context; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class NoopLogRecordProcessorTest { + + @Mock private ReadWriteLogRecord logRecord; + + @Test + void noCrash() { + LogRecordProcessor logRecordProcessor = NoopLogRecordProcessor.getInstance(); + logRecordProcessor.onEmit(Context.current(), logRecord); + assertThat(logRecordProcessor.forceFlush().isSuccess()).isEqualTo(true); + assertThat(logRecordProcessor.shutdown().isSuccess()).isEqualTo(true); + } + + @Test + void toString_Valid() { + assertThat(NoopLogRecordProcessor.getInstance().toString()).isEqualTo("NoopLogRecordProcessor"); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ReadWriteLogRecordTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ReadWriteLogRecordTest.java new file mode 100644 index 00000000000..419b5d68ca4 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ReadWriteLogRecordTest.java @@ -0,0 +1,126 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.AttributesMap; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class ReadWriteLogRecordTest { + + @Test + void addAllAttributes() { + Attributes newAttributes = Attributes.of(stringKey("foo"), "bar", stringKey("bar"), "buzz"); + SdkReadWriteLogRecord logRecord = buildLogRecord(); + + logRecord.setAllAttributes(newAttributes); + + Attributes result = logRecord.getAttributes(); + assertThat(result.get(stringKey("foo"))).isEqualTo("bar"); + assertThat(result.get(stringKey("bar"))).isEqualTo("buzz"); + assertThat(result.get(stringKey("untouched"))).isEqualTo("yes"); + } + + @Test + void addAllHandlesNull() { + SdkReadWriteLogRecord logRecord = buildLogRecord(); + Attributes originalAttributes = logRecord.getAttributes(); + ReadWriteLogRecord result = logRecord.setAllAttributes(null); + assertThat(result.getAttributes()).isEqualTo(originalAttributes); + } + + @Test + void allHandlesEmpty() { + SdkReadWriteLogRecord logRecord = buildLogRecord(); + Attributes originalAttributes = logRecord.getAttributes(); + ReadWriteLogRecord result = logRecord.setAllAttributes(Attributes.empty()); + assertThat(result.getAttributes()).isEqualTo(originalAttributes); + } + + @Test + void defaultGetObservedTimestampEpochNanos_returnsObservedTimestamp() { + LogRecordData data = + TestLogRecordData.builder() + .setTimestamp(100, TimeUnit.NANOSECONDS) + .setObservedTimestamp(200, TimeUnit.NANOSECONDS) + .build(); + // A ReadWriteLogRecord that relies on the interface default methods, implementing only the + // abstract methods. The SDK's SdkReadWriteLogRecord overrides the getters, so the default + // method behavior must be exercised through a custom implementation. + ReadWriteLogRecord logRecord = + new ReadWriteLogRecord() { + @Override + public ReadWriteLogRecord setAttribute(AttributeKey key, T value) { + return this; + } + + @Override + public LogRecordData toLogRecordData() { + return data; + } + }; + + assertThat(logRecord.getObservedTimestampEpochNanos()).isEqualTo(200); + assertThat(logRecord.getTimestampEpochNanos()).isEqualTo(100); + } + + @Test + void defaultGetEventName_returnsEventNameFromLogRecordData() { + LogRecordData data = TestLogRecordData.builder().setEventName("my.event").build(); + // Same as above: exercise the interface default through an implementation of only the + // abstract methods. + ReadWriteLogRecord logRecord = + new ReadWriteLogRecord() { + @Override + public ReadWriteLogRecord setAttribute(AttributeKey key, T value) { + return this; + } + + @Override + public LogRecordData toLogRecordData() { + return data; + } + }; + + assertThat(logRecord.getEventName()).isEqualTo("my.event"); + } + + SdkReadWriteLogRecord buildLogRecord() { + Value body = Value.of("bod"); + AttributesMap initialAttributes = AttributesMap.create(100, 200); + initialAttributes.put(stringKey("foo"), "aaiosjfjioasdiojfjioasojifja"); + initialAttributes.put(stringKey("untouched"), "yes"); + LogLimits limits = LogLimits.getDefault(); + Resource resource = Resource.empty(); + InstrumentationScopeInfo scope = InstrumentationScopeInfo.create("test"); + SpanContext spanContext = SpanContext.getInvalid(); + + return SdkReadWriteLogRecord.create( + limits, + resource, + scope, + 0L, + 0L, + spanContext, + Severity.DEBUG, + "buggin", + body, + initialAttributes, + "my.event.name"); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogBuilderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogBuilderTest.java deleted file mode 100644 index 0f11830850f..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogBuilderTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import java.time.Instant; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -class SdkLogBuilderTest { - - @Test - void buildAndEmit() { - Instant now = Instant.now(); - String bodyStr = "body"; - String sevText = "sevText"; - Severity severity = Severity.DEBUG3; - Attributes attrs = Attributes.empty(); - AtomicReference seenLog = new AtomicReference<>(); - LogProcessor logProcessor = seenLog::set; - - LogEmitterSharedState state = mock(LogEmitterSharedState.class); - LogDataBuilder delegate = mock(LogDataBuilder.class); - LogData logData = mock(LogData.class); - Context context = mock(Context.class); - - when(state.getLogLimits()).thenReturn(LogLimits.getDefault()); - when(state.getLogProcessor()).thenReturn(logProcessor); - when(delegate.build()).thenReturn(logData); - - SdkLogBuilder builder = new SdkLogBuilder(state, delegate); - builder.setBody(bodyStr); - verify(delegate).setBody(bodyStr); - builder.setEpoch(123, TimeUnit.SECONDS); - verify(delegate).setEpoch(123, TimeUnit.SECONDS); - builder.setEpoch(now); - verify(delegate).setEpoch(now); - builder.setAttributes(attrs); - verify(delegate).setAttributes(attrs); - builder.setContext(context); - verify(delegate).setContext(context); - builder.setSeverity(severity); - verify(delegate).setSeverity(severity); - builder.setSeverityText(sevText); - verify(delegate).setSeverityText(sevText); - builder.emit(); - assertThat(seenLog.get()).isSameAs(logData); - } - - @Test - void emitAfterShutdown() { - LogEmitterSharedState state = mock(LogEmitterSharedState.class); - LogDataBuilder delegate = mock(LogDataBuilder.class); - - when(state.hasBeenShutdown()).thenReturn(true); - - SdkLogBuilder builder = new SdkLogBuilder(state, delegate); - builder.emit(); - verify(state, never()).getLogProcessor(); - verifyNoInteractions(delegate); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogEmitterProviderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogEmitterProviderTest.java deleted file mode 100644 index 7c339e2bc05..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogEmitterProviderTest.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static org.assertj.core.api.Assertions.as; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.TimeUnit; -import org.assertj.core.api.InstanceOfAssertFactories; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; - -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.LENIENT) -class SdkLogEmitterProviderTest { - - @Mock private LogProcessor logProcessor; - - private SdkLogEmitterProvider sdkLogEmitterProvider; - - @BeforeEach - void setup() { - sdkLogEmitterProvider = SdkLogEmitterProvider.builder().addLogProcessor(logProcessor).build(); - when(logProcessor.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); - when(logProcessor.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - } - - @Test - void builder_defaultResource() { - assertThat(SdkLogEmitterProvider.builder().build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getResource) - .isEqualTo(Resource.getDefault()); - } - - @Test - void builder_resourceProvided() { - Resource resource = Resource.create(Attributes.builder().put("key", "value").build()); - - assertThat(SdkLogEmitterProvider.builder().setResource(resource).build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getResource) - .isEqualTo(resource); - } - - @Test - void builder_noProcessor() { - assertThat(SdkLogEmitterProvider.builder().build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getLogProcessor) - .isSameAs(NoopLogProcessor.getInstance()); - } - - @Test - void builder_defaultLogLimits() { - assertThat(SdkLogEmitterProvider.builder().build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getLogLimits) - .isSameAs(LogLimits.getDefault()); - } - - @Test - void builder_logLimitsProvided() { - LogLimits logLimits = - LogLimits.builder().setMaxNumberOfAttributes(1).setMaxAttributeValueLength(1).build(); - assertThat(SdkLogEmitterProvider.builder().setLogLimits(() -> logLimits).build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getLogLimits) - .isSameAs(logLimits); - } - - @Test - void builder_defaultClock() { - assertThat(SdkLogEmitterProvider.builder().build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getClock) - .isSameAs(Clock.getDefault()); - } - - @Test - void builder_clockProvided() { - Clock clock = mock(Clock.class); - assertThat(SdkLogEmitterProvider.builder().setClock(clock).build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getClock) - .isSameAs(clock); - } - - @Test - void builder_multipleProcessors() { - assertThat( - SdkLogEmitterProvider.builder() - .addLogProcessor(logProcessor) - .addLogProcessor(logProcessor) - .build()) - .extracting("sharedState", as(InstanceOfAssertFactories.type(LogEmitterSharedState.class))) - .extracting(LogEmitterSharedState::getLogProcessor) - .satisfies( - activeLogProcessor -> { - assertThat(activeLogProcessor).isInstanceOf(MultiLogProcessor.class); - assertThat(activeLogProcessor) - .extracting( - "logProcessors", as(InstanceOfAssertFactories.list(LogProcessor.class))) - .hasSize(2); - }); - } - - @Test - void logEmitterBuilder_SameName() { - assertThat(sdkLogEmitterProvider.logEmitterBuilder("test").build()) - .isSameAs(sdkLogEmitterProvider.get("test")) - .isSameAs(sdkLogEmitterProvider.logEmitterBuilder("test").build()) - .isNotSameAs( - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .build()); - } - - @Test - void logEmitterBuilder_SameNameAndVersion() { - assertThat( - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .build()) - .isSameAs( - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .build()) - .isNotSameAs( - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .setSchemaUrl("http://url") - .build()); - } - - @Test - void logEmitterBuilder_SameNameVersionAndSchema() { - assertThat( - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .setSchemaUrl("http://url") - .build()) - .isSameAs( - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .setSchemaUrl("http://url") - .build()); - } - - @Test - void logEmitterBuilder_PropagatesToEmitter() { - InstrumentationScopeInfo expected = - InstrumentationScopeInfo.create("test", "version", "http://url"); - assertThat( - ((SdkLogEmitter) - sdkLogEmitterProvider - .logEmitterBuilder("test") - .setInstrumentationVersion("version") - .setSchemaUrl("http://url") - .build()) - .getInstrumentationScopeInfo()) - .isEqualTo(expected); - } - - @Test - void logEmitterBuilder_DefaultEmitterName() { - assertThat( - ((SdkLogEmitter) sdkLogEmitterProvider.logEmitterBuilder(null).build()) - .getInstrumentationScopeInfo() - .getName()) - .isEqualTo(SdkLogEmitterProvider.DEFAULT_EMITTER_NAME); - - assertThat( - ((SdkLogEmitter) sdkLogEmitterProvider.logEmitterBuilder("").build()) - .getInstrumentationScopeInfo() - .getName()) - .isEqualTo(SdkLogEmitterProvider.DEFAULT_EMITTER_NAME); - } - - @Test - void forceFlush() { - sdkLogEmitterProvider.forceFlush(); - verify(logProcessor).forceFlush(); - } - - @Test - @SuppressLogger(SdkLogEmitterProvider.class) - void shutdown() { - sdkLogEmitterProvider.shutdown(); - sdkLogEmitterProvider.shutdown(); - verify(logProcessor, times(1)).shutdown(); - } - - @Test - void close() { - sdkLogEmitterProvider.close(); - verify(logProcessor).shutdown(); - } - - @Test - void canSetClock() { - long now = TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); - Clock clock = mock(Clock.class); - when(clock.now()).thenReturn(now); - List seenLogs = new ArrayList<>(); - logProcessor = seenLogs::add; - sdkLogEmitterProvider = - SdkLogEmitterProvider.builder().setClock(clock).addLogProcessor(logProcessor).build(); - sdkLogEmitterProvider.logEmitterBuilder(null).build().logBuilder().emit(); - assertThat(seenLogs.size()).isEqualTo(1); - assertThat(seenLogs.get(0).getEpochNanos()).isEqualTo(now); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogEmitterTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogEmitterTest.java deleted file mode 100644 index 44c04288fea..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogEmitterTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs; - -import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; -import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; -import static io.opentelemetry.api.common.AttributeKey.longArrayKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; -import static io.opentelemetry.sdk.testing.assertj.LogAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.api.internal.StringUtils; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicReference; -import org.junit.jupiter.api.Test; - -class SdkLogEmitterTest { - - @Test - void logBuilder() { - LogEmitterSharedState state = mock(LogEmitterSharedState.class); - InstrumentationScopeInfo info = InstrumentationScopeInfo.create("foo"); - AtomicReference seenLog = new AtomicReference<>(); - LogProcessor logProcessor = seenLog::set; - Clock clock = mock(Clock.class); - when(clock.now()).thenReturn(5L); - - when(state.getResource()).thenReturn(Resource.getDefault()); - when(state.getLogProcessor()).thenReturn(logProcessor); - when(state.getClock()).thenReturn(clock); - - SdkLogEmitter emitter = new SdkLogEmitter(state, info); - LogBuilder logBuilder = emitter.logBuilder(); - logBuilder.setBody("foo"); - - // Have to test through the builder - logBuilder.emit(); - assertThat(seenLog.get()).hasBody("foo").hasEpochNanos(5); - } - - @Test - void logBuilder_maxAttributeLength() { - int maxLength = 25; - AtomicReference seenLog = new AtomicReference<>(); - SdkLogEmitterProvider logEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor(seenLog::set) - .setLogLimits(() -> LogLimits.builder().setMaxAttributeValueLength(maxLength).build()) - .build(); - LogBuilder logBuilder = logEmitterProvider.get("test").logBuilder(); - String strVal = StringUtils.padLeft("", maxLength); - String tooLongStrVal = strVal + strVal; - - logBuilder - .setAttributes( - Attributes.builder() - .put("string", tooLongStrVal) - .put("boolean", true) - .put("long", 1L) - .put("double", 1.0) - .put(stringArrayKey("stringArray"), Arrays.asList(strVal, tooLongStrVal)) - .put(booleanArrayKey("booleanArray"), Arrays.asList(true, false)) - .put(longArrayKey("longArray"), Arrays.asList(1L, 2L)) - .put(doubleArrayKey("doubleArray"), Arrays.asList(1.0, 2.0)) - .build()) - .emit(); - - Attributes attributes = seenLog.get().getAttributes(); - - assertThat(attributes) - .containsEntry("string", strVal) - .containsEntry("boolean", true) - .containsEntry("long", 1L) - .containsEntry("double", 1.0) - .containsEntry("stringArray", strVal, strVal) - .containsEntry("booleanArray", true, false) - .containsEntry("longArray", 1L, 2L) - .containsEntry("doubleArray", 1.0, 2.0); - } - - @Test - void logBuilder_maxAttributes() { - int maxNumberOfAttrs = 8; - AtomicReference seenLog = new AtomicReference<>(); - SdkLogEmitterProvider logEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor(seenLog::set) - .setLogLimits( - () -> LogLimits.builder().setMaxNumberOfAttributes(maxNumberOfAttrs).build()) - .build(); - - AttributesBuilder attributesBuilder = Attributes.builder(); - for (int i = 0; i < 2 * maxNumberOfAttrs; i++) { - attributesBuilder.put("key" + i, i); - } - - logEmitterProvider.get("test").logBuilder().setAttributes(attributesBuilder.build()).emit(); - - // NOTE: cannot guarantee which attributes are retained, only that there are no more that the - // max - assertThat(seenLog.get().getAttributes()).hasSize(maxNumberOfAttrs); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java new file mode 100644 index 00000000000..42fe8dd3fa9 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLogRecordBuilderTest.java @@ -0,0 +1,199 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.api.common.AttributeKey.booleanKey; +import static io.opentelemetry.api.common.AttributeKey.doubleKey; +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.resources.Resource; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class SdkLogRecordBuilderTest { + + private static final Resource RESOURCE = Resource.empty(); + private static final InstrumentationScopeInfo SCOPE_INFO = InstrumentationScopeInfo.empty(); + + @Mock LoggerSharedState loggerSharedState; + @Mock Clock clock; + + private final AtomicReference emittedLog = new AtomicReference<>(); + private SdkLogRecordBuilder builder; + + @BeforeEach + void setup() { + when(loggerSharedState.getLogLimits()).thenReturn(LogLimits.getDefault()); + when(loggerSharedState.getLogRecordProcessor()) + .thenReturn((context, logRecord) -> emittedLog.set(logRecord)); + when(loggerSharedState.getResource()).thenReturn(RESOURCE); + when(loggerSharedState.getClock()).thenReturn(clock); + when(loggerSharedState.getLoggerInstrumentation()) + .thenReturn(new SdkLoggerInstrumentation(MeterProvider::noop)); + when(loggerSharedState.getExceptionAttributeResolver()) + .thenReturn(ExceptionAttributeResolver.getDefault()); + + SdkLogger logger = new SdkLogger(loggerSharedState, SCOPE_INFO, LoggerConfig.enabled()); + builder = new SdkLogRecordBuilder(loggerSharedState, SCOPE_INFO, logger); + } + + @Test + void emit_AllFields() { + Instant timestamp = Instant.now(); + Instant observedTimestamp = Instant.now().plusNanos(100); + + String eventName = "my.event.name"; + String bodyStr = "body"; + String sevText = "sevText"; + Severity severity = Severity.DEBUG3; + SpanContext spanContext = + SpanContext.create( + "33333333333333333333333333333333", + "7777777777777777", + TraceFlags.getSampled(), + TraceState.getDefault()); + + builder.setEventName(eventName); + builder.setBody(bodyStr); + builder.setTimestamp(123, TimeUnit.SECONDS); + builder.setTimestamp(timestamp); + builder.setObservedTimestamp(456, TimeUnit.SECONDS); + builder.setObservedTimestamp(observedTimestamp); + builder.setAttribute((String) null, (String) null); + builder.setAttribute(AttributeKey.stringKey("k1"), "v1"); + builder.setAllAttributes(Attributes.builder().put("k2", "v2").put("k3", "v3").build()); + builder.setContext(Span.wrap(spanContext).storeInContext(Context.root())); + builder.setSeverity(severity); + builder.setSeverityText(sevText); + builder.emit(); + assertThat(emittedLog.get().toLogRecordData()) + .hasResource(RESOURCE) + .hasInstrumentationScope(SCOPE_INFO) + .hasEventName(eventName) + .hasBody(bodyStr) + .hasTimestamp(TimeUnit.SECONDS.toNanos(timestamp.getEpochSecond()) + timestamp.getNano()) + .hasObservedTimestamp( + TimeUnit.SECONDS.toNanos(observedTimestamp.getEpochSecond()) + + observedTimestamp.getNano()) + .hasAttributes(Attributes.builder().put("k1", "v1").put("k2", "v2").put("k3", "v3").build()) + .hasSpanContext(spanContext) + .hasSeverity(severity) + .hasSeverityText(sevText); + } + + @Test + void emit_NoFields() { + when(clock.now()).thenReturn(10L); + + builder.emit(); + + assertThat(emittedLog.get().toLogRecordData()) + .hasResource(RESOURCE) + .hasInstrumentationScope(SCOPE_INFO) + .hasBody((Value) null) + .hasTimestamp(0L) + .hasObservedTimestamp(10L) + .hasAttributes(Attributes.empty()) + .hasSpanContext(SpanContext.getInvalid()) + .hasSeverity(Severity.UNDEFINED_SEVERITY_NUMBER); + } + + @Test + void emit_ChecksLoggerIsEnabled() { + SdkLogger logger = mock(SdkLogger.class); + builder = new SdkLogRecordBuilder(loggerSharedState, SCOPE_INFO, logger); + + Severity severity = Severity.WARN; + Context context = Context.current(); + + // Configure mock to return false (disabled) + when(logger.isEnabled(severity, context)).thenReturn(false); + + builder.setSeverity(severity).setContext(context).emit(); + + // Verify isEnabled was called with correct parameters + verify(logger).isEnabled(eq(severity), eq(context)); + + // Verify log was not processed (because isEnabled returned false) + assertThat(emittedLog.get()).isNull(); + } + + @Test + void testConvenienceAttributeMethods() { + builder + .setAttribute("foo", "bar") + .setAttribute("lk", 12L) + .setAttribute("dk", 12.123) + .setAttribute("bk", true) + .setAttribute("ik", 13) + .setAttribute("vk", Value.of(new byte[] {1, 2, 3})) + .emit(); + assertThat(emittedLog.get().toLogRecordData()) + .hasAttributesSatisfyingExactly( + equalTo(stringKey("foo"), "bar"), + equalTo(longKey("lk"), 12L), + equalTo(doubleKey("dk"), 12.123), + equalTo(booleanKey("bk"), true), + equalTo(longKey("ik"), 13L), + equalTo(valueKey("vk"), Value.of(new byte[] {1, 2, 3}))); + } + + @Test + void setException() { + Exception exception = new Exception("error"); + + builder.setException(exception).emit(); + + assertThat(emittedLog.get().toLogRecordData()).hasException(exception); + } + + @Test + void setException_UserAttributesTakePrecedence() { + builder + .setAttribute(stringKey("exception.message"), "custom message") + .setException(new Exception("error")) + .emit(); + + assertThat(emittedLog.get().toLogRecordData()) + .hasAttributesSatisfying(attributes -> { + assertThat(attributes.get(stringKey("exception.type"))).isEqualTo("java.lang.Exception"); + assertThat(attributes.get(stringKey("exception.message"))).isEqualTo("custom message"); + assertThat(attributes.get(stringKey("exception.stacktrace"))).isNotNull(); + }); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderBuilderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderBuilderTest.java new file mode 100644 index 00000000000..b013b29386a --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderBuilderTest.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class SdkLoggerProviderBuilderTest { + + @Test + void addResource() { + Resource customResource = + Resource.create( + Attributes.of( + AttributeKey.stringKey("custom_attribute_key"), "custom_attribute_value")); + + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder().addResource(customResource).build(); + + assertThat(SdkLoggerProviderUtil.getSdkResourceProvider(sdkLoggerProvider).getResource()) + .isEqualTo(Resource.getDefault().merge(customResource)); + } + + @Test + void resourceProvider_defaultsToAutoWrappedStaticResource() { + SdkLoggerProvider provider = SdkLoggerProvider.builder().build(); + + assertThat(SdkLoggerProviderUtil.getSdkResourceProvider(provider).getResource()) + .isEqualTo(Resource.getDefault()); + } + + @Test + void setSdkResourceProvider_usedForResource() { + Resource customResource = + Resource.create(Attributes.of(AttributeKey.stringKey("key"), "value")); + SdkResourceProvider resourceProvider = SdkResourceProvider.create(customResource); + + SdkLoggerProviderBuilder builder = SdkLoggerProvider.builder(); + SdkLoggerProviderUtil.setSdkResourceProvider(builder, resourceProvider); + SdkLoggerProvider provider = builder.build(); + + assertThat(SdkLoggerProviderUtil.getSdkResourceProvider(provider)).isSameAs(resourceProvider); + assertThat(SdkLoggerProviderUtil.getSdkResourceProvider(provider).getResource()) + .isEqualTo(customResource); + } + + @ParameterizedTest + @MethodSource("resourceConfigurations") + void setSdkResourceProvider_afterResource_throws(boolean addResource, Resource resource) { + SdkLoggerProviderBuilder builder = SdkLoggerProvider.builder(); + if (addResource) { + builder.addResource(resource); + } else { + builder.setResource(resource); + } + + assertThatThrownBy(() -> builder.setSdkResourceProvider(SdkResourceProvider.create(resource))) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Cannot call setSdkResourceProvider after setResource or addResource has been called."); + assertThat(SdkLoggerProviderUtil.getSdkResourceProvider(builder.build()).getResource()) + .isEqualTo(addResource ? Resource.getDefault().merge(resource) : resource); + } + + @ParameterizedTest + @MethodSource("resourceConfigurations") + void resource_afterSetSdkResourceProvider_throws(boolean addResource, Resource resource) { + SdkResourceProvider resourceProvider = SdkResourceProvider.create(resource); + SdkLoggerProviderBuilder builder = SdkLoggerProvider.builder(); + SdkLoggerProviderUtil.setSdkResourceProvider(builder, resourceProvider); + + assertThatThrownBy( + () -> { + if (addResource) { + builder.addResource(resource); + } else { + builder.setResource(resource); + } + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Cannot call " + + (addResource ? "addResource" : "setResource") + + " after setSdkResourceProvider has been called."); + assertThat(SdkLoggerProviderUtil.getSdkResourceProvider(builder.build())) + .isSameAs(resourceProvider); + } + + private static Stream resourceConfigurations() { + Resource customResource = + Resource.create(Attributes.of(AttributeKey.stringKey("key"), "value")); + return Stream.of( + Arguments.argumentSet("setResource(custom)", false, customResource), + Arguments.argumentSet("setResource(default)", false, Resource.getDefault()), + Arguments.argumentSet("setResource(empty)", false, Resource.empty()), + Arguments.argumentSet("addResource(custom)", true, customResource), + Arguments.argumentSet("addResource(default)", true, Resource.getDefault()), + Arguments.argumentSet("addResource(empty)", true, Resource.empty())); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java new file mode 100644 index 00000000000..345e69dbf5c --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderMetricsTest.java @@ -0,0 +1,399 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.sdk.common.internal.SemConvConstants.ERROR_TYPE; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_COMPONENT_NAME; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_COMPONENT_TYPE; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor; +import io.opentelemetry.sdk.logs.export.BatchLogRecordProcessorBuilder; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class SdkLoggerProviderMetricsTest { + + @Mock private LogRecordExporter mockExporter; + + @Test + void simple() { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + MeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SimpleLogRecordProcessor processor = + SimpleLogRecordProcessor.builder(exporter).setMeterProvider(() -> meterProvider).build(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(processor) + .setMeterProvider(() -> meterProvider) + .build(); + + Logger logger = loggerProvider.get("test"); + + logger.logRecordBuilder().emit(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(1).hasAttributes())), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor"))))); + + logger.logRecordBuilder().emit(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(2).hasAttributes())), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor"))))); + + // Logs rejected after the call to shutdown, regardless of completion so no join. + processor.shutdown(); + logger.logRecordBuilder().emit(); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(3).hasAttributes())), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor", + ERROR_TYPE, + "already_shutdown"))))); + } + + @Test + @SuppressLogger(BatchLogRecordProcessorBuilder.class) + void batch() throws Exception { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + MeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + + BatchLogRecordProcessor processor = + BatchLogRecordProcessor.builder(mockExporter) + .setMaxQueueSize(1) + // Manually flush + .setScheduleDelay(Duration.ofDays(1)) + .setInternalTelemetryVersion(InternalTelemetryVersion.LATEST) + .setMeterProvider(() -> meterProvider) + .build(); + LoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(processor) + .setMeterProvider(() -> meterProvider) + .build(); + + Logger logger = loggerProvider.get("test"); + + CompletableResultCode result1 = new CompletableResultCode(); + CompletableResultCode result2 = new CompletableResultCode(); + when(mockExporter.export(any())).thenReturn(result1).thenReturn(result2); + + // Will immediately be processed. + logger.logRecordBuilder().emit(); + Thread.sleep(500); // give time to start processing a batch of size 1 + // We haven't completed the export so this log is queued. + logger.logRecordBuilder().emit(); + // Queue is full, this log is dropped. + logger.logRecordBuilder().emit(); + + // Export hasn't finished but processed metric is incremented + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.queue.capacity") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.queue.size") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "queue_full")))), + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(3).hasAttributes()))); + + result1.succeed(); + result2.fail(); + processor.forceFlush().join(1, TimeUnit.SECONDS); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.queue.capacity") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.queue.size") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "queue_full")))), + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(3).hasAttributes()))); + + lenient().when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + // Logs rejected after the call to shutdown, regardless of completion so no join. + processor.shutdown(); + + logger.logRecordBuilder().emit(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.queue.capacity") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.queue.size") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "already_shutdown")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_log_processor/0", + OTEL_COMPONENT_TYPE, + "batching_log_processor", + ERROR_TYPE, + "queue_full")))), + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(4).hasAttributes()))); + } + + @Test + void simpleExportError() { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + MeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + + LoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + SimpleLogRecordProcessor.builder(mockExporter) + .setMeterProvider(() -> meterProvider) + .build()) + .setMeterProvider(() -> meterProvider) + .build(); + + Logger logger = loggerProvider.get("test"); + + when(mockExporter.export(any())).thenReturn(CompletableResultCode.ofFailure()); + + logger.logRecordBuilder().emit(); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.log.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_log_processor/0", + OTEL_COMPONENT_TYPE, + "simple_log_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.log.created") + .hasLongSumSatisfying( + s -> s.hasPointsSatisfying(p -> p.hasValue(1).hasAttributes()))); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java new file mode 100644 index 00000000000..c74cac09e59 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerProviderTest.java @@ -0,0 +1,383 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.as; +import static org.assertj.core.api.Assertions.entry; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.logs.LoggerProvider; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; +import io.opentelemetry.context.Scope; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class SdkLoggerProviderTest { + + @Mock private LogRecordProcessor logRecordProcessor; + + private SdkLoggerProvider sdkLoggerProvider; + + @BeforeEach + void setup() { + sdkLoggerProvider = + SdkLoggerProvider.builder() + .setResource(Resource.empty().toBuilder().put("key", "value").build()) + .addLogRecordProcessor(logRecordProcessor) + .build(); + when(logRecordProcessor.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordProcessor.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + } + + @Test + void builder_defaultResource() { + assertThat(SdkLoggerProvider.builder().build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getResource) + .isEqualTo(Resource.getDefault()); + } + + @Test + void builder_resourceProvided() { + Resource resource = Resource.create(Attributes.builder().put("key", "value").build()); + + assertThat(SdkLoggerProvider.builder().setResource(resource).build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getResource) + .isEqualTo(resource); + } + + @Test + void builder_noProcessor() { + assertThat(SdkLoggerProvider.builder().build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getLogRecordProcessor) + .isSameAs(NoopLogRecordProcessor.getInstance()); + } + + @Test + void builder_defaultLogLimits() { + assertThat(SdkLoggerProvider.builder().build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getLogLimits) + .isSameAs(LogLimits.getDefault()); + } + + @Test + void builder_logLimitsProvided() { + LogLimits logLimits = + LogLimits.builder().setMaxNumberOfAttributes(1).setMaxAttributeValueLength(1).build(); + assertThat(SdkLoggerProvider.builder().setLogLimits(() -> logLimits).build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getLogLimits) + .isSameAs(logLimits); + } + + @Test + void builder_defaultClock() { + assertThat(SdkLoggerProvider.builder().build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getClock) + .isSameAs(Clock.getDefault()); + } + + @Test + void builder_clockProvided() { + Clock clock = mock(Clock.class); + assertThat(SdkLoggerProvider.builder().setClock(clock).build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getClock) + .isSameAs(clock); + } + + @Test + void builder_multipleProcessors() { + LogRecordProcessor firstProcessor = mock(LogRecordProcessor.class); + assertThat( + SdkLoggerProvider.builder() + .addLogRecordProcessor(logRecordProcessor) + .addLogRecordProcessor(logRecordProcessor) + .addLogRecordProcessorFirst(firstProcessor) + .build()) + .extracting("sharedState", as(InstanceOfAssertFactories.type(LoggerSharedState.class))) + .extracting(LoggerSharedState::getLogRecordProcessor) + .satisfies(activeLogRecordProcessor -> { + assertThat(activeLogRecordProcessor).isInstanceOf(MultiLogRecordProcessor.class); + assertThat(activeLogRecordProcessor) + .extracting( + "logRecordProcessors", + as(InstanceOfAssertFactories.list(LogRecordProcessor.class))) + .hasSize(3) + .first() + .isEqualTo(firstProcessor); + }); + } + + @Test + void loggerBuilder_SameName() { + assertThat(sdkLoggerProvider.loggerBuilder("test").build()) + .isSameAs(sdkLoggerProvider.get("test")) + .isSameAs(sdkLoggerProvider.loggerBuilder("test").build()) + .isNotSameAs( + sdkLoggerProvider.loggerBuilder("test").setInstrumentationVersion("version").build()); + } + + @Test + void loggerBuilder_SameNameAndVersion() { + assertThat(sdkLoggerProvider.loggerBuilder("test").setInstrumentationVersion("version").build()) + .isSameAs( + sdkLoggerProvider.loggerBuilder("test").setInstrumentationVersion("version").build()) + .isNotSameAs( + sdkLoggerProvider + .loggerBuilder("test") + .setInstrumentationVersion("version") + .setSchemaUrl("http://url") + .build()); + } + + @Test + void loggerBuilder_SameNameVersionAndSchema() { + assertThat( + sdkLoggerProvider + .loggerBuilder("test") + .setInstrumentationVersion("version") + .setSchemaUrl("http://url") + .build()) + .isSameAs( + sdkLoggerProvider + .loggerBuilder("test") + .setInstrumentationVersion("version") + .setSchemaUrl("http://url") + .build()); + } + + @Test + void loggerBuilder_PropagatesToLogger() { + InstrumentationScopeInfo expected = + InstrumentationScopeInfo.builder("test") + .setVersion("version") + .setSchemaUrl("http://url") + .build(); + assertThat( + ((SdkLogger) + sdkLoggerProvider + .loggerBuilder("test") + .setInstrumentationVersion("version") + .setSchemaUrl("http://url") + .build()) + .getInstrumentationScopeInfo()) + .isEqualTo(expected); + } + + @Test + void loggerBuilder_DefaultLoggerName() { + assertThat( + ((SdkLogger) sdkLoggerProvider.loggerBuilder(null).build()) + .getInstrumentationScopeInfo() + .getName()) + .isEqualTo(SdkLoggerProvider.DEFAULT_LOGGER_NAME); + + assertThat( + ((SdkLogger) sdkLoggerProvider.loggerBuilder("").build()) + .getInstrumentationScopeInfo() + .getName()) + .isEqualTo(SdkLoggerProvider.DEFAULT_LOGGER_NAME); + } + + @Test + void loggerBuilder_NoProcessor_UsesNoop() { + assertThat(SdkLoggerProvider.builder().build().loggerBuilder("test")) + .isSameAs(LoggerProvider.noop().loggerBuilder("test")); + } + + @Test + void get_NoProcessor_UsesNoop() { + assertThat(SdkLoggerProvider.builder().build().get("test")) + .isSameAs(LoggerProvider.noop().get("test")); + } + + @Test + void loggerBuilder_WithLogRecordProcessor() { + Resource resource = Resource.builder().put("r1", "v1").build(); + AtomicReference logRecordData = new AtomicReference<>(); + sdkLoggerProvider = + SdkLoggerProvider.builder() + .setResource(resource) + .addLogRecordProcessor((unused, logRecord) -> { + logRecord.setAttribute(null, null); + // Overwrite k1 + logRecord.setAttribute(AttributeKey.stringKey("k1"), "new-v1"); + // Add new attribute k3 + logRecord.setAttribute(AttributeKey.stringKey("k3"), "v3"); + logRecordData.set(logRecord.toLogRecordData()); + }) + .build(); + + SpanContext spanContext = + SpanContext.create( + "33333333333333333333333333333333", + "7777777777777777", + TraceFlags.getSampled(), + TraceState.getDefault()); + sdkLoggerProvider + .get("test") + .logRecordBuilder() + .setEventName("my.event.name") + .setTimestamp(100, TimeUnit.NANOSECONDS) + .setContext(Span.wrap(spanContext).storeInContext(Context.root())) + .setSeverity(Severity.DEBUG) + .setSeverityText("debug") + .setBody("body") + .setAttribute(AttributeKey.stringKey("k1"), "v1") + .setAttribute(AttributeKey.stringKey("k2"), "v2") + .emit(); + + assertThat(logRecordData.get()) + .hasResource(resource) + .hasInstrumentationScope(InstrumentationScopeInfo.create("test")) + .hasEventName("my.event.name") + .hasTimestamp(100) + .hasSpanContext(spanContext) + .hasSeverity(Severity.DEBUG) + .hasSeverityText("debug") + .hasBody("body") + .hasAttributes( + Attributes.builder().put("k1", "new-v1").put("k2", "v2").put("k3", "v3").build()); + } + + @Test + void loggerBuilder_ProcessorWithContext() { + ContextKey contextKey = ContextKey.named("my-context-key"); + AtomicReference logRecordData = new AtomicReference<>(); + + sdkLoggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor((context, logRecord) -> + logRecord.setAttribute( + AttributeKey.stringKey("my-context-key"), + Optional.ofNullable(context.get(contextKey)).orElse(""))) + .addLogRecordProcessor( + (unused, logRecord) -> logRecordData.set(logRecord.toLogRecordData())) + .build(); + + // With implicit context + try (Scope unused = Context.current().with(contextKey, "context-value1").makeCurrent()) { + sdkLoggerProvider + .loggerBuilder("test") + .build() + .logRecordBuilder() + .setBody("log message1") + .emit(); + } + assertThat(logRecordData.get()) + .hasBody("log message1") + .hasAttributes(entry(AttributeKey.stringKey("my-context-key"), "context-value1")); + + // With explicit context + try (Scope unused = Context.current().with(contextKey, "context-value2").makeCurrent()) { + sdkLoggerProvider + .loggerBuilder("test") + .build() + .logRecordBuilder() + .setContext(Context.current()) + .setBody("log message2") + .emit(); + } + assertThat(logRecordData.get()) + .hasBody("log message2") + .hasAttributes(entry(AttributeKey.stringKey("my-context-key"), "context-value2")); + } + + @Test + void forceFlush() { + sdkLoggerProvider.forceFlush(); + verify(logRecordProcessor).forceFlush(); + } + + @Test + @SuppressLogger(SdkLoggerProvider.class) + void shutdown() { + sdkLoggerProvider.shutdown(); + sdkLoggerProvider.shutdown(); + verify(logRecordProcessor, times(1)).shutdown(); + } + + @Test + void close() { + sdkLoggerProvider.close(); + verify(logRecordProcessor).shutdown(); + } + + @Test + void toString_Valid() { + when(logRecordProcessor.toString()).thenReturn("MockLogRecordProcessor"); + assertThat(sdkLoggerProvider.toString()) + .matches( + "SdkLoggerProvider\\{clock=SystemClock\\{\\}, " + + "resource=Resource\\{schemaUrl=null, entities=\\[\\], attributes=\\{key=\"value\"\\}\\}, " + + "logLimits=LogLimits\\{maxNumberOfAttributes=128, maxAttributeValueLength=2147483647\\}, " + + "logRecordProcessor=MockLogRecordProcessor, " + + "loggerConfigurator=ScopeConfiguratorImpl\\{conditions=\\[\\]\\}\\}"); + } + + private static ScopeConfigurator flipConfigurator(boolean enabled) { + return scopeInfo -> enabled ? LoggerConfig.disabled() : LoggerConfig.enabled(); + } + + @Test + void propagatesEnablementToLoggerDirectly() { + SdkLogger logger = (SdkLogger) sdkLoggerProvider.get("test"); + boolean isEnabled = logger.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current()); + + sdkLoggerProvider.setLoggerConfigurator(flipConfigurator(isEnabled)); + + assertThat(logger.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())) + .isEqualTo(!isEnabled); + } + + @Test + void propagatesEnablementToLoggerByUtil() { + SdkLogger logger = (SdkLogger) sdkLoggerProvider.get("test"); + boolean isEnabled = logger.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current()); + + SdkLoggerProviderUtil.setLoggerConfigurator(sdkLoggerProvider, flipConfigurator(isEnabled)); + + assertThat(logger.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())) + .isEqualTo(!isEnabled); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerTest.java new file mode 100644 index 00000000000..43f5abd2ee4 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/SdkLoggerTest.java @@ -0,0 +1,238 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.api.common.AttributeKey.booleanArrayKey; +import static io.opentelemetry.api.common.AttributeKey.doubleArrayKey; +import static io.opentelemetry.api.common.AttributeKey.longArrayKey; +import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import com.google.common.base.Strings; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.LogRecordBuilder; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Arrays; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +class SdkLoggerTest { + + @Test + void logRecordBuilder() { + LoggerSharedState state = mock(LoggerSharedState.class); + InstrumentationScopeInfo info = InstrumentationScopeInfo.create("foo"); + AtomicReference seenLog = new AtomicReference<>(); + LogRecordProcessor logRecordProcessor = (context, logRecord) -> seenLog.set(logRecord); + Clock clock = mock(Clock.class); + + when(state.getResource()).thenReturn(Resource.getDefault()); + when(state.getLogRecordProcessor()).thenReturn(logRecordProcessor); + when(state.getClock()).thenReturn(clock); + when(state.getLoggerInstrumentation()) + .thenReturn(new SdkLoggerInstrumentation(MeterProvider::noop)); + + SdkLogger logger = new SdkLogger(state, info, LoggerConfig.defaultConfig()); + LogRecordBuilder logRecordBuilder = logger.logRecordBuilder(); + logRecordBuilder.setBody("foo"); + + // Have to test through the builder + logRecordBuilder.emit(); + assertThat(seenLog.get().toLogRecordData()).hasBody("foo").hasTimestamp(0); + } + + @Test + void logRecordBuilder_maxAttributeLength() { + int maxLength = 25; + AtomicReference seenLog = new AtomicReference<>(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor((context, logRecord) -> seenLog.set(logRecord)) + .setLogLimits(() -> LogLimits.builder().setMaxAttributeValueLength(maxLength).build()) + .build(); + LogRecordBuilder logRecordBuilder = loggerProvider.get("test").logRecordBuilder(); + String strVal = Strings.repeat("0", maxLength); + String tooLongStrVal = strVal + strVal; + + logRecordBuilder + .setAllAttributes( + Attributes.builder() + .put("string", tooLongStrVal) + .put("boolean", true) + .put("long", 1L) + .put("double", 1.0) + .put(stringArrayKey("stringArray"), Arrays.asList(strVal, tooLongStrVal)) + .put(booleanArrayKey("booleanArray"), Arrays.asList(true, false)) + .put(longArrayKey("longArray"), Arrays.asList(1L, 2L)) + .put(doubleArrayKey("doubleArray"), Arrays.asList(1.0, 2.0)) + .put(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .put(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .put(valueKey("heterogeneousArray"), Value.of(Value.of("string"), Value.of(123L))) + .put(valueKey("empty"), Value.empty()) + .build()) + .emit(); + + Attributes attributes = seenLog.get().toLogRecordData().getAttributes(); + + assertThat(attributes) + .containsEntry("string", strVal) + .containsEntry("boolean", true) + .containsEntry("long", 1L) + .containsEntry("double", 1.0) + .containsEntry("stringArray", strVal, strVal) + .containsEntry("booleanArray", true, false) + .containsEntry("longArray", 1L, 2L) + .containsEntry("doubleArray", 1.0, 2.0) + .containsEntry(valueKey("bytes"), Value.of(new byte[] {1, 2, 3})) + .containsEntry(valueKey("map"), Value.of(KeyValue.of("nested", Value.of("value")))) + .containsEntry(valueKey("heterogeneousArray"), Value.of(Value.of("string"), Value.of(123L))) + .containsEntry(valueKey("empty"), Value.empty()); + } + + @Test + void logRecordBuilder_maxAttributes() { + int maxNumberOfAttrs = 8; + AtomicReference seenLog = new AtomicReference<>(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor((context, logRecord) -> seenLog.set(logRecord)) + .setLogLimits( + () -> LogLimits.builder().setMaxNumberOfAttributes(maxNumberOfAttrs).build()) + .build(); + + LogRecordBuilder builder = loggerProvider.get("test").logRecordBuilder(); + AttributesBuilder expectedAttributes = Attributes.builder(); + for (int i = 0; i < 2 * maxNumberOfAttrs; i++) { + AttributeKey key = AttributeKey.longKey("key" + i); + builder.setAttribute(key, (long) i); + if (i < maxNumberOfAttrs) { + expectedAttributes.put(key, (long) i); + } + } + builder.emit(); + + assertThat(seenLog.get().toLogRecordData()) + .hasAttributes(expectedAttributes.build()) + .hasTotalAttributeCount(maxNumberOfAttrs * 2); + } + + @Test + void logRecordBuilder_AfterShutdown() { + LogRecordProcessor logRecordProcessor = mock(LogRecordProcessor.class); + when(logRecordProcessor.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(logRecordProcessor).build(); + + loggerProvider.shutdown().join(10, TimeUnit.SECONDS); + loggerProvider.get("test").logRecordBuilder().emit(); + + verify(logRecordProcessor, never()).onEmit(any(), any()); + } + + @Test + void updateLoggerConfig() { + LogRecordProcessor logRecordProcessor = mock(LogRecordProcessor.class); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(logRecordProcessor).build(); + SdkLogger logger = (SdkLogger) loggerProvider.get("test"); + + // Start with default config + assertThat(logger.loggerEnabled).isTrue(); + assertThat(logger.minimumSeverity).isEqualTo(Severity.UNDEFINED_SEVERITY_NUMBER); + assertThat(logger.traceBased).isFalse(); + + // Update to custom config + LoggerConfig config = + LoggerConfig.builder() + .setEnabled(false) + .setMinimumSeverity(Severity.WARN) + .setTraceBased(true) + .build(); + logger.updateLoggerConfig(config); + + assertThat(logger.loggerEnabled).isFalse(); + assertThat(logger.minimumSeverity).isEqualTo(Severity.WARN); + assertThat(logger.traceBased).isTrue(); + } + + @Test + void isEnabled_MinimumSeverity() { + LogRecordProcessor logRecordProcessor = mock(LogRecordProcessor.class); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(logRecordProcessor).build(); + SdkLogger logger = (SdkLogger) loggerProvider.get("test"); + + LoggerConfig config = LoggerConfig.builder().setMinimumSeverity(Severity.WARN).build(); + logger.updateLoggerConfig(config); + + // Below minimum severity - should be disabled + assertThat(logger.isEnabled(Severity.INFO, Context.current())).isFalse(); + assertThat(logger.isEnabled(Severity.DEBUG, Context.current())).isFalse(); + + // At or above minimum severity - should be enabled + assertThat(logger.isEnabled(Severity.WARN, Context.current())).isTrue(); + assertThat(logger.isEnabled(Severity.ERROR, Context.current())).isTrue(); + + // Undefined severity - should be enabled (bypasses minimum severity filter) + assertThat(logger.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isTrue(); + } + + @Test + void isEnabled_TraceBased() { + LogRecordProcessor logRecordProcessor = mock(LogRecordProcessor.class); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(logRecordProcessor).build(); + SdkLogger logger = (SdkLogger) loggerProvider.get("test"); + + LoggerConfig config = LoggerConfig.builder().setTraceBased(true).build(); + logger.updateLoggerConfig(config); + + // No trace context - should be enabled + assertThat(logger.isEnabled(Severity.INFO, Context.current())).isTrue(); + + // Sampled trace - should be enabled + SpanContext sampledSpanContext = + SpanContext.create( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "bbbbbbbbbbbbbbbb", + TraceFlags.getSampled(), + TraceState.getDefault()); + Context sampledContext = Span.wrap(sampledSpanContext).storeInContext(Context.root()); + assertThat(logger.isEnabled(Severity.INFO, sampledContext)).isTrue(); + + // Unsampled trace - should be disabled + SpanContext unsampledSpanContext = + SpanContext.create( + "cccccccccccccccccccccccccccccccc", + "dddddddddddddddd", + TraceFlags.getDefault(), + TraceState.getDefault()); + Context unsampledContext = Span.wrap(unsampledSpanContext).storeInContext(Context.root()); + assertThat(logger.isEnabled(Severity.INFO, unsampledContext)).isFalse(); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java new file mode 100644 index 00000000000..a1c329ad4d7 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/ValueBodyTest.java @@ -0,0 +1,158 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.common.ValueType; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import org.junit.jupiter.api.Test; + +class ValueBodyTest { + + @Test + @SuppressWarnings("DoubleBraceInitialization") + void valueBody() { + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider provider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + Logger logger = provider.get(ValueBodyTest.class.getName()); + + // Value can be a primitive type, like a string, long, double, boolean + logger.logRecordBuilder().setBody(Value.of(1)).emit(); + assertThat(exporter.getFinishedLogRecordItems()) + .hasSize(1) + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.LONG); + assertThat((Long) body.getValue()).isEqualTo(1L); + }); + }); + exporter.reset(); + + // ...or a byte array of raw data + logger + .logRecordBuilder() + .setBody(Value.of("hello world".getBytes(StandardCharsets.UTF_8))) + .emit(); + assertThat(exporter.getFinishedLogRecordItems()) + .hasSize(1) + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.BYTES); + assertThat((ByteBuffer) body.getValue()) + .isEqualTo(ByteBuffer.wrap("hello world".getBytes(StandardCharsets.UTF_8))); + }); + }); + exporter.reset(); + + // But most commonly it will be used to represent complex structured like a map + logger + .logRecordBuilder() + .setBody( + // The protocol data structure uses a repeated KeyValue to represent a map: + // https://github.com/open-telemetry/opentelemetry-proto/blob/ac3242b03157295e4ee9e616af53b81517b06559/opentelemetry/proto/common/v1/common.proto#L59 + // The comment says that keys aren't allowed to repeat themselves, and because its + // represented as a repeated KeyValue, we need to at least offer the ability to preserve + // order. + // Accepting a Map> makes for a cleaner API, but ordering of the + // entries is lost. To accommodate use cases where ordering should be preserved we + // accept an array of key value pairs, but also a map based alternative (see the + // key_value_list_key entry). + Value.of( + KeyValue.of("str_key", Value.of("value")), + KeyValue.of("bool_key", Value.of(true)), + KeyValue.of("long_key", Value.of(1L)), + KeyValue.of("double_key", Value.of(1.1)), + KeyValue.of("bytes_key", Value.of("bytes".getBytes(StandardCharsets.UTF_8))), + KeyValue.of("arr_key", Value.of(Value.of("entry1"), Value.of(2), Value.of(3.3))), + KeyValue.of( + "key_value_list_key", + Value.of( + new LinkedHashMap>() { + { + put("child_str_key1", Value.of("child_value1")); + put("child_str_key2", Value.of("child_value2")); + } + })))) + .emit(); + assertThat(exporter.getFinishedLogRecordItems()) + .hasSize(1) + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + // TODO: use fluent asserts when available. See + // https://github.com/open-telemetry/opentelemetry-java/pull/6509 + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.KEY_VALUE_LIST); + assertThat(body) + .isEqualTo( + Value.of( + KeyValue.of("str_key", Value.of("value")), + KeyValue.of("bool_key", Value.of(true)), + KeyValue.of("long_key", Value.of(1L)), + KeyValue.of("double_key", Value.of(1.1)), + KeyValue.of( + "bytes_key", Value.of("bytes".getBytes(StandardCharsets.UTF_8))), + KeyValue.of( + "arr_key", + Value.of(Value.of("entry1"), Value.of(2), Value.of(3.3))), + KeyValue.of( + "key_value_list_key", + Value.of( + new LinkedHashMap>() { + { + put("child_str_key1", Value.of("child_value1")); + put("child_str_key2", Value.of("child_value2")); + } + })))); + assertThat(body.asString()) + .isEqualTo( + "{" + + "\"str_key\":\"value\"," + + "\"bool_key\":true," + + "\"long_key\":1," + + "\"double_key\":1.1," + + "\"bytes_key\":\"Ynl0ZXM=\"," + + "\"arr_key\":[\"entry1\",2,3.3]," + + "\"key_value_list_key\":{\"child_str_key1\":\"child_value1\",\"child_str_key2\":\"child_value2\"}" + + "}"); + }); + }); + exporter.reset(); + + // ..or an array (optionally with heterogeneous types) + logger + .logRecordBuilder() + .setBody(Value.of(Value.of("entry1"), Value.of("entry2"), Value.of(3))) + .emit(); + assertThat(exporter.getFinishedLogRecordItems()) + .hasSize(1) + .satisfiesExactly(logRecordData -> { + assertThat(logRecordData.getBodyValue()) + .isNotNull() + .satisfies(body -> { + assertThat(body.getType()).isEqualTo(ValueType.ARRAY); + assertThat(body) + .isEqualTo(Value.of(Value.of("entry1"), Value.of("entry2"), Value.of(3))); + }); + }); + exporter.reset(); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/BodyTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/BodyTest.java index d57fb085fb0..57143d4f49f 100644 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/BodyTest.java +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/BodyTest.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test; +@SuppressWarnings("deprecation") // Testing deprecated code class BodyTest { @Test diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/LogDataBuilderTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/LogDataBuilderTest.java deleted file mode 100644 index 1d71f3b608a..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/data/LogDataBuilderTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.data; - -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertSame; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import org.junit.jupiter.api.Test; - -class LogDataBuilderTest { - - private final Resource resource = Resource.getDefault(); - private final InstrumentationScopeInfo scopeInfo = InstrumentationScopeInfo.empty(); - - @Test - void canSetClock() { - Clock clock = mock(Clock.class); - when(clock.now()).thenReturn(12L); - LogDataBuilder builder = LogDataBuilder.create(resource, scopeInfo, clock); - - LogData result = builder.build(); - assertEquals(12L, result.getEpochNanos()); - } - - @Test - void canSetSpanContext() { - LogDataBuilder builder = LogDataBuilder.create(resource, scopeInfo); - SpanContext spanContext = mock(SpanContext.class); - LogData result = builder.setSpanContext(spanContext).build(); - assertSame(spanContext, result.getSpanContext()); - } - - @Test - void setSpanContext_nullSafe() { - LogDataBuilder builder = LogDataBuilder.create(resource, scopeInfo); - LogData result = builder.setSpanContext(null).build(); - assertSame(SpanContext.getInvalid(), result.getSpanContext()); - } - - @Test - void canSetSpanContextFromContext() { - String traceId = "33333333333333333333333333333333"; - String spanId = "7777777777777777"; - SpanContext spanContext = - SpanContext.create(traceId, spanId, TraceFlags.getSampled(), TraceState.getDefault()); - Span span = Span.wrap(spanContext); - - Context context = mock(Context.class); - when(context.get(any())).thenReturn(span); - - LogDataBuilder builder = LogDataBuilder.create(resource, scopeInfo); - - LogData result = builder.setContext(context).build(); - assertSame(spanContext, result.getSpanContext()); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogProcessorTest.java deleted file mode 100644 index 65bf757a1e5..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogProcessorTest.java +++ /dev/null @@ -1,586 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import static io.opentelemetry.sdk.testing.assertj.LogAssertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; -import static org.awaitility.Awaitility.await; -import static org.mockito.ArgumentMatchers.anyList; -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.when; - -import io.opentelemetry.api.internal.GuardedBy; -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.testing.assertj.LogAssertions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import javax.annotation.Nullable; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.Timeout; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; - -@SuppressWarnings("PreferJavaTimeOverload") -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.LENIENT) -class BatchLogProcessorTest { - - private static final String LOG_MESSAGE_1 = "Hello world 1!"; - private static final String LOG_MESSAGE_2 = "Hello world 2!"; - private static final long MAX_SCHEDULE_DELAY_MILLIS = 500; - - @Mock private LogExporter mockLogExporter; - - @BeforeEach - void setUp() { - when(mockLogExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - } - - private void emitLog(SdkLogEmitterProvider sdkLogEmitterProvider, String message) { - sdkLogEmitterProvider - .logEmitterBuilder(getClass().getName()) - .build() - .logBuilder() - .setBody(message) - .emit(); - } - - @Test - void builderDefaults() { - BatchLogProcessorBuilder builder = BatchLogProcessor.builder(mockLogExporter); - assertThat(builder.getScheduleDelayNanos()) - .isEqualTo( - TimeUnit.MILLISECONDS.toNanos(BatchLogProcessorBuilder.DEFAULT_SCHEDULE_DELAY_MILLIS)); - assertThat(builder.getMaxQueueSize()) - .isEqualTo(BatchLogProcessorBuilder.DEFAULT_MAX_QUEUE_SIZE); - assertThat(builder.getMaxExportBatchSize()) - .isEqualTo(BatchLogProcessorBuilder.DEFAULT_MAX_EXPORT_BATCH_SIZE); - assertThat(builder.getExporterTimeoutNanos()) - .isEqualTo( - TimeUnit.MILLISECONDS.toNanos(BatchLogProcessorBuilder.DEFAULT_EXPORT_TIMEOUT_MILLIS)); - } - - @Test - void builderInvalidConfig() { - assertThatThrownBy( - () -> - BatchLogProcessor.builder(mockLogExporter) - .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("delay must be non-negative"); - assertThatThrownBy(() -> BatchLogProcessor.builder(mockLogExporter).setScheduleDelay(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> BatchLogProcessor.builder(mockLogExporter).setScheduleDelay(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("delay"); - assertThatThrownBy( - () -> - BatchLogProcessor.builder(mockLogExporter) - .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("timeout must be non-negative"); - assertThatThrownBy(() -> BatchLogProcessor.builder(mockLogExporter).setExporterTimeout(1, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("unit"); - assertThatThrownBy(() -> BatchLogProcessor.builder(mockLogExporter).setExporterTimeout(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("timeout"); - } - - @Test - void emitMultipleLogs() { - WaitingLogExporter waitingLogExporter = - new WaitingLogExporter(2, CompletableResultCode.ofSuccess()); - SdkLogEmitterProvider logEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor( - BatchLogProcessor.builder(waitingLogExporter) - .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) - .build()) - .build(); - - emitLog(logEmitterProvider, LOG_MESSAGE_1); - emitLog(logEmitterProvider, LOG_MESSAGE_2); - List exported = waitingLogExporter.waitForExport(); - assertThat(exported) - .satisfiesExactly( - logData -> assertThat(logData).hasBody(LOG_MESSAGE_1), - logData -> assertThat(logData).hasBody(LOG_MESSAGE_2)); - } - - @Test - void emitMoreLogsThanBufferSize() { - CompletableLogExporter logExporter = new CompletableLogExporter(); - - SdkLogEmitterProvider sdkLogEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor( - BatchLogProcessor.builder(logExporter) - .setMaxQueueSize(6) - .setMaxExportBatchSize(2) - .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) - .build()) - .build(); - - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - - logExporter.succeed(); - - await() - .untilAsserted( - () -> - assertThat(logExporter.getExported()) - .hasSize(6) - .allSatisfy(logData -> assertThat(logData).hasBody(LOG_MESSAGE_1))); - } - - @Test - void forceEmit() { - WaitingLogExporter waitingLogExporter = - new WaitingLogExporter(100, CompletableResultCode.ofSuccess(), 1); - BatchLogProcessor batchLogProcessor = - BatchLogProcessor.builder(waitingLogExporter) - .setMaxQueueSize(10_000) - // Force flush should send all logs, make sure the number of logs we check here is - // not divisible by the batch size. - .setMaxExportBatchSize(49) - .setScheduleDelay(10, TimeUnit.SECONDS) - .build(); - - SdkLogEmitterProvider sdkLogEmitterProvider = - SdkLogEmitterProvider.builder().addLogProcessor(batchLogProcessor).build(); - for (int i = 0; i < 50; i++) { - emitLog(sdkLogEmitterProvider, "notExported"); - } - List exported = waitingLogExporter.waitForExport(); - assertThat(exported).isNotNull(); - assertThat(exported.size()).isEqualTo(49); - - for (int i = 0; i < 50; i++) { - emitLog(sdkLogEmitterProvider, "notExported"); - } - exported = waitingLogExporter.waitForExport(); - assertThat(exported).isNotNull(); - assertThat(exported.size()).isEqualTo(49); - - batchLogProcessor.forceFlush().join(10, TimeUnit.SECONDS); - exported = waitingLogExporter.getExported(); - assertThat(exported).isNotNull(); - assertThat(exported.size()).isEqualTo(2); - } - - @Test - void emitLogsToMultipleExporters() { - WaitingLogExporter waitingLogExporter1 = - new WaitingLogExporter(2, CompletableResultCode.ofSuccess()); - WaitingLogExporter waitingLogExporter2 = - new WaitingLogExporter(2, CompletableResultCode.ofSuccess()); - SdkLogEmitterProvider sdkLogEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor( - BatchLogProcessor.builder( - LogExporter.composite( - Arrays.asList(waitingLogExporter1, waitingLogExporter2))) - .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) - .build()) - .build(); - - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_2); - List exported1 = waitingLogExporter1.waitForExport(); - List exported2 = waitingLogExporter2.waitForExport(); - assertThat(exported1) - .hasSize(2) - .satisfiesExactly( - logData -> assertThat(logData).hasBody(LOG_MESSAGE_1), - logData -> assertThat(logData).hasBody(LOG_MESSAGE_2)); - assertThat(exported2) - .hasSize(2) - .satisfiesExactly( - logData -> assertThat(logData).hasBody(LOG_MESSAGE_1), - logData -> assertThat(logData).hasBody(LOG_MESSAGE_2)); - } - - @Test - void emitMoreLogsThanTheMaximumLimit() { - int maxQueuedLogs = 8; - BlockingLogExporter blockingLogExporter = new BlockingLogExporter(); - WaitingLogExporter waitingLogExporter = - new WaitingLogExporter(maxQueuedLogs, CompletableResultCode.ofSuccess()); - SdkLogEmitterProvider sdkTracerProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor( - BatchLogProcessor.builder( - LogExporter.composite( - Arrays.asList(blockingLogExporter, waitingLogExporter))) - .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) - .setMaxQueueSize(maxQueuedLogs) - .setMaxExportBatchSize(maxQueuedLogs / 2) - .build()) - .build(); - - // Wait to block the worker thread in the BatchLogProcessor. This ensures that no items - // can be removed from the queue. Need to add a log to trigger the export otherwise the - // pipeline is never called. - emitLog(sdkTracerProvider, "blocking log"); - blockingLogExporter.waitUntilIsBlocked(); - - for (int i = 0; i < maxQueuedLogs; i++) { - // First export maxQueuedLogs, the worker thread is blocked so all items should be queued. - emitLog(sdkTracerProvider, "log_1_" + 1); - } - - // Now we should start dropping. - for (int i = 0; i < 7; i++) { - emitLog(sdkTracerProvider, "log_2_" + i); - } - - // Release the blocking exporter - blockingLogExporter.unblock(); - - // While we wait for maxQueuedLogs we ensure that the queue is also empty after this. - List exported = waitingLogExporter.waitForExport(); - assertThat(exported).isNotNull(); - assertThat(exported).hasSize(maxQueuedLogs + 1); - - // Clear, reset, add another batch of logs, and confirm they are exported - exported.clear(); - waitingLogExporter.reset(); - for (int i = 0; i < maxQueuedLogs; i++) { - emitLog(sdkTracerProvider, "log_3_" + i); - } - - exported = waitingLogExporter.waitForExport(); - assertThat(exported).isNotNull(); - assertThat(exported).hasSize(maxQueuedLogs); - } - - @Test - void ignoresNullLogs() { - BatchLogProcessor processor = BatchLogProcessor.builder(mockLogExporter).build(); - try { - assertThatCode( - () -> { - processor.emit(null); - }) - .doesNotThrowAnyException(); - } finally { - processor.shutdown(); - } - } - - @Test - @SuppressLogger(MultiLogExporter.class) - void exporterThrowsException() { - WaitingLogExporter waitingLogExporter = - new WaitingLogExporter(1, CompletableResultCode.ofSuccess()); - doThrow(new IllegalArgumentException("No export for you.")) - .when(mockLogExporter) - .export(anyList()); - SdkLogEmitterProvider sdkLogEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor( - BatchLogProcessor.builder( - LogExporter.composite(Arrays.asList(mockLogExporter, waitingLogExporter))) - .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) - .build()) - .build(); - - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - List exported = waitingLogExporter.waitForExport(); - assertThat(exported).satisfiesExactly(logData -> assertThat(logData).hasBody(LOG_MESSAGE_1)); - waitingLogExporter.reset(); - // Continue to export after the exception was received. - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_2); - exported = waitingLogExporter.waitForExport(); - assertThat(exported).satisfiesExactly(logData -> assertThat(logData).hasBody(LOG_MESSAGE_2)); - } - - @Test - @Timeout(5) - public void continuesIfExporterTimesOut() throws InterruptedException { - int exporterTimeoutMillis = 10; - BatchLogProcessor blp = - BatchLogProcessor.builder(mockLogExporter) - .setExporterTimeout(exporterTimeoutMillis, TimeUnit.MILLISECONDS) - .setScheduleDelay(1, TimeUnit.MILLISECONDS) - .setMaxQueueSize(1) - .build(); - SdkLogEmitterProvider sdkLogEmitterProvider = - SdkLogEmitterProvider.builder().addLogProcessor(blp).build(); - - CountDownLatch exported = new CountDownLatch(1); - // We return a result we never complete, meaning it will timeout. - when(mockLogExporter.export( - argThat( - logs -> { - assertThat(logs) - .anySatisfy(log -> LogAssertions.assertThat(log).hasBody(LOG_MESSAGE_1)); - exported.countDown(); - return true; - }))) - .thenReturn(new CompletableResultCode()); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_1); - exported.await(); - // Timed out so the log was dropped. - await().untilAsserted(() -> assertThat(blp.getBatch()).isEmpty()); - - // Still processing new logs. - CountDownLatch exportedAgain = new CountDownLatch(1); - reset(mockLogExporter); - when(mockLogExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - when(mockLogExporter.export( - argThat( - logs -> { - assertThat(logs) - .anySatisfy(log -> LogAssertions.assertThat(log).hasBody(LOG_MESSAGE_2)); - exportedAgain.countDown(); - return true; - }))) - .thenReturn(CompletableResultCode.ofSuccess()); - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_2); - exported.await(); - await().untilAsserted(() -> assertThat(blp.getBatch()).isEmpty()); - } - - @Test - @Timeout(10) - void shutdownFlushes() { - WaitingLogExporter waitingLogExporter = - new WaitingLogExporter(1, CompletableResultCode.ofSuccess()); - // Set the export delay to large value, in order to confirm the #flush() below works - - SdkLogEmitterProvider sdkLogEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor( - BatchLogProcessor.builder(waitingLogExporter) - .setScheduleDelay(10, TimeUnit.SECONDS) - .build()) - .build(); - - emitLog(sdkLogEmitterProvider, LOG_MESSAGE_2); - - // Force a shutdown, which forces processing of all remaining logs. - sdkLogEmitterProvider.shutdown().join(10, TimeUnit.SECONDS); - - List exported = waitingLogExporter.getExported(); - assertThat(exported).satisfiesExactly(logData -> assertThat(logData).hasBody(LOG_MESSAGE_2)); - ; - assertThat(waitingLogExporter.shutDownCalled.get()).isTrue(); - } - - @Test - void shutdownPropagatesSuccess() { - BatchLogProcessor processor = BatchLogProcessor.builder(mockLogExporter).build(); - CompletableResultCode result = processor.shutdown(); - result.join(1, TimeUnit.SECONDS); - assertThat(result.isSuccess()).isTrue(); - } - - @Test - void shutdownPropagatesFailure() { - when(mockLogExporter.shutdown()).thenReturn(CompletableResultCode.ofFailure()); - BatchLogProcessor processor = BatchLogProcessor.builder(mockLogExporter).build(); - CompletableResultCode result = processor.shutdown(); - result.join(1, TimeUnit.SECONDS); - assertThat(result.isSuccess()).isFalse(); - } - - private static final class BlockingLogExporter implements LogExporter { - - final Object monitor = new Object(); - - private enum State { - WAIT_TO_BLOCK, - BLOCKED, - UNBLOCKED - } - - @GuardedBy("monitor") - State state = State.WAIT_TO_BLOCK; - - @Override - public CompletableResultCode export(Collection logs) { - synchronized (monitor) { - while (state != State.UNBLOCKED) { - try { - state = State.BLOCKED; - // Some threads may wait for Blocked State. - monitor.notifyAll(); - monitor.wait(); - } catch (InterruptedException e) { - // Do nothing - } - } - } - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - private void waitUntilIsBlocked() { - synchronized (monitor) { - while (state != State.BLOCKED) { - try { - monitor.wait(); - } catch (InterruptedException e) { - // Do nothing - } - } - } - } - - @Override - public CompletableResultCode shutdown() { - // Do nothing; - return CompletableResultCode.ofSuccess(); - } - - private void unblock() { - synchronized (monitor) { - state = State.UNBLOCKED; - monitor.notifyAll(); - } - } - } - - private static class CompletableLogExporter implements LogExporter { - - private final List results = new ArrayList<>(); - - private final List exported = new ArrayList<>(); - - private volatile boolean succeeded; - - List getExported() { - return exported; - } - - void succeed() { - succeeded = true; - results.forEach(CompletableResultCode::succeed); - } - - @Override - public CompletableResultCode export(Collection logs) { - exported.addAll(logs); - if (succeeded) { - return CompletableResultCode.ofSuccess(); - } - CompletableResultCode result = new CompletableResultCode(); - results.add(result); - return result; - } - - @Override - public CompletableResultCode flush() { - if (succeeded) { - return CompletableResultCode.ofSuccess(); - } else { - return CompletableResultCode.ofFailure(); - } - } - - @Override - public CompletableResultCode shutdown() { - return flush(); - } - } - - static class WaitingLogExporter implements LogExporter { - - private final List logDataList = new ArrayList<>(); - private final int numberToWaitFor; - private final CompletableResultCode exportResultCode; - private CountDownLatch countDownLatch; - private int timeout = 10; - private final AtomicBoolean shutDownCalled = new AtomicBoolean(false); - - WaitingLogExporter(int numberToWaitFor, CompletableResultCode exportResultCode) { - countDownLatch = new CountDownLatch(numberToWaitFor); - this.numberToWaitFor = numberToWaitFor; - this.exportResultCode = exportResultCode; - } - - WaitingLogExporter(int numberToWaitFor, CompletableResultCode exportResultCode, int timeout) { - this(numberToWaitFor, exportResultCode); - this.timeout = timeout; - } - - List getExported() { - List result = new ArrayList<>(logDataList); - logDataList.clear(); - return result; - } - - /** - * Waits until we received {@link #numberToWaitFor} logs to export. Returns the list of exported - * {@link LogData} objects, otherwise {@code null} if the current thread is interrupted. - * - * @return the list of exported {@link LogData} objects, otherwise {@code null} if the current - * thread is interrupted. - */ - @Nullable - List waitForExport() { - try { - countDownLatch.await(timeout, TimeUnit.SECONDS); - } catch (InterruptedException e) { - // Preserve the interruption status as per guidance. - Thread.currentThread().interrupt(); - return null; - } - return getExported(); - } - - @Override - public CompletableResultCode export(Collection logs) { - this.logDataList.addAll(logs); - for (int i = 0; i < logs.size(); i++) { - countDownLatch.countDown(); - } - return exportResultCode; - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - shutDownCalled.set(true); - return CompletableResultCode.ofSuccess(); - } - - public void reset() { - this.countDownLatch = new CountDownLatch(numberToWaitFor); - } - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java new file mode 100644 index 00000000000..1b86ba63dee --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/BatchLogRecordProcessorTest.java @@ -0,0 +1,688 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatCode; +import static org.awaitility.Awaitility.await; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.internal.GuardedBy; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import javax.annotation.Nullable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@SuppressWarnings("PreferJavaTimeOverload") +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class BatchLogRecordProcessorTest { + + private static final String LOG_MESSAGE_1 = "Hello world 1!"; + private static final String LOG_MESSAGE_2 = "Hello world 2!"; + private static final long MAX_SCHEDULE_DELAY_MILLIS = 500; + + @Mock private LogRecordExporter mockLogRecordExporter; + + @BeforeEach + void setUp() { + when(mockLogRecordExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + } + + private void emitLog(SdkLoggerProvider sdkLoggerProvider, String message) { + sdkLoggerProvider + .loggerBuilder(getClass().getName()) + .build() + .logRecordBuilder() + .setBody(message) + .emit(); + } + + @Test + void builderDefaults() { + BatchLogRecordProcessorBuilder builder = BatchLogRecordProcessor.builder(mockLogRecordExporter); + assertThat(builder.getScheduleDelayNanos()) + .isEqualTo( + TimeUnit.MILLISECONDS.toNanos( + BatchLogRecordProcessorBuilder.DEFAULT_SCHEDULE_DELAY_MILLIS)); + assertThat(builder.getMaxQueueSize()) + .isEqualTo(BatchLogRecordProcessorBuilder.DEFAULT_MAX_QUEUE_SIZE); + assertThat(builder.getMaxExportBatchSize()) + .isEqualTo(BatchLogRecordProcessorBuilder.DEFAULT_MAX_EXPORT_BATCH_SIZE); + assertThat(builder.getExporterTimeoutNanos()) + .isEqualTo( + TimeUnit.MILLISECONDS.toNanos( + BatchLogRecordProcessorBuilder.DEFAULT_EXPORT_TIMEOUT_MILLIS)); + } + + @Test + void builderInvalidConfig() { + assertThatThrownBy(() -> + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("delay must be non-negative"); + assertThatThrownBy( + () -> BatchLogRecordProcessor.builder(mockLogRecordExporter).setScheduleDelay(1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); + assertThatThrownBy( + () -> BatchLogRecordProcessor.builder(mockLogRecordExporter).setScheduleDelay(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("delay"); + assertThatThrownBy(() -> + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("timeout must be non-negative"); + assertThatThrownBy(() -> + BatchLogRecordProcessor.builder(mockLogRecordExporter).setExporterTimeout(1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); + assertThatThrownBy( + () -> BatchLogRecordProcessor.builder(mockLogRecordExporter).setExporterTimeout(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("timeout"); + assertThatThrownBy( + () -> BatchLogRecordProcessor.builder(mockLogRecordExporter).setMaxQueueSize(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxQueueSize must be positive."); + } + + @Test + @SuppressLogger(BatchLogRecordProcessorBuilder.class) + void builderAdjustMaxBatchSize() { + LogRecordExporter dummyExporter = new CompletableLogRecordExporter(); + + BatchLogRecordProcessorBuilder builder = + BatchLogRecordProcessor.builder(dummyExporter) + .setMaxQueueSize(513) + .setMaxExportBatchSize(1000); + builder.build(); + + assertThat(builder.getMaxExportBatchSize()).isEqualTo(513); + assertThat(builder.getMaxQueueSize()).isEqualTo(513); + } + + @Test + @SuppressLogger(BatchLogRecordProcessorBuilder.class) + void maxExportBatchSizeExceedsQueueSize() throws InterruptedException { + // Given a processor configured with a maxExportBatchSize > maxQueueSize, ensure that after n = + // maxQueueSize logs are emitted, export is triggered and that the queue is fully drained and + // exported. + int maxQueueSize = 2048; + when(mockLogRecordExporter.export(any())).thenReturn(CompletableResultCode.ofSuccess()); + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setScheduleDelay(Duration.ofSeconds(Integer.MAX_VALUE)) + .setMaxExportBatchSize(2049) + .setMaxQueueSize(maxQueueSize) + .build()) + .build(); + + for (int i = 0; i < maxQueueSize; i++) { + emitLog(sdkLoggerProvider, "log " + i); + } + + await().untilAsserted(() -> verify(mockLogRecordExporter, times(1)).export(any())); + } + + @Test + void emitMultipleLogs() { + WaitingLogRecordExporter waitingLogRecordExporter = + new WaitingLogRecordExporter(2, CompletableResultCode.ofSuccess()); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder(waitingLogRecordExporter) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .build()) + .build(); + + emitLog(loggerProvider, LOG_MESSAGE_1); + emitLog(loggerProvider, LOG_MESSAGE_2); + List exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported) + .satisfiesExactly( + logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1), + logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_2)); + } + + @Test + void emitMoreLogsThanBufferSize() { + CompletableLogRecordExporter logRecordExporter = new CompletableLogRecordExporter(); + + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder(logRecordExporter) + .setMaxQueueSize(6) + .setMaxExportBatchSize(2) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .build()) + .build(); + + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + + logRecordExporter.succeed(); + + await() + .untilAsserted(() -> + assertThat(logRecordExporter.getExported()) + .hasSize(6) + .allSatisfy(logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1))); + } + + @Test + void forceEmit() { + WaitingLogRecordExporter waitingLogRecordExporter = + new WaitingLogRecordExporter(100, CompletableResultCode.ofSuccess(), 1); + BatchLogRecordProcessor batchLogRecordProcessor = + BatchLogRecordProcessor.builder(waitingLogRecordExporter) + .setMaxQueueSize(10_000) + // Force flush should send all logs, make sure the number of logs we check here is + // not divisible by the batch size. + .setMaxExportBatchSize(49) + .setScheduleDelay(10, TimeUnit.SECONDS) + .build(); + + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(batchLogRecordProcessor).build(); + for (int i = 0; i < 50; i++) { + emitLog(sdkLoggerProvider, "notExported"); + } + List exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported).isNotNull(); + assertThat(exported.size()).isEqualTo(49); + + for (int i = 0; i < 50; i++) { + emitLog(sdkLoggerProvider, "notExported"); + } + exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported).isNotNull(); + assertThat(exported.size()).isEqualTo(49); + + batchLogRecordProcessor.forceFlush().join(10, TimeUnit.SECONDS); + exported = waitingLogRecordExporter.getExported(); + assertThat(exported).isNotNull(); + assertThat(exported.size()).isEqualTo(2); + } + + @Test + void emitLogsToMultipleExporters() { + WaitingLogRecordExporter waitingLogRecordExporter1 = + new WaitingLogRecordExporter(2, CompletableResultCode.ofSuccess()); + WaitingLogRecordExporter waitingLogRecordExporter2 = + new WaitingLogRecordExporter(2, CompletableResultCode.ofSuccess()); + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + LogRecordExporter.composite( + Arrays.asList(waitingLogRecordExporter1, waitingLogRecordExporter2))) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .build()) + .build(); + + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + emitLog(sdkLoggerProvider, LOG_MESSAGE_2); + List exported1 = waitingLogRecordExporter1.waitForExport(); + List exported2 = waitingLogRecordExporter2.waitForExport(); + assertThat(exported1) + .hasSize(2) + .satisfiesExactly( + logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1), + logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_2)); + assertThat(exported2) + .hasSize(2) + .satisfiesExactly( + logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1), + logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_2)); + } + + @Test + void emitMoreLogsThanTheMaximumLimit() { + int maxQueuedLogs = 8; + BlockingLogRecordExporter blockingLogRecordExporter = new BlockingLogRecordExporter(); + WaitingLogRecordExporter waitingLogRecordExporter = + new WaitingLogRecordExporter(maxQueuedLogs, CompletableResultCode.ofSuccess()); + SdkLoggerProvider sdkTracerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + LogRecordExporter.composite( + Arrays.asList(blockingLogRecordExporter, waitingLogRecordExporter))) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .setMaxQueueSize(maxQueuedLogs) + .setMaxExportBatchSize(maxQueuedLogs / 2) + .build()) + .build(); + + // Wait to block the worker thread in the BatchLogRecordProcessor. This ensures that no items + // can be removed from the queue. Need to add a log to trigger the export otherwise the + // pipeline is never called. + emitLog(sdkTracerProvider, "blocking log"); + blockingLogRecordExporter.waitUntilIsBlocked(); + + for (int i = 0; i < maxQueuedLogs; i++) { + // First export maxQueuedLogs, the worker thread is blocked so all items should be queued. + emitLog(sdkTracerProvider, "log_1_" + 1); + } + + // Now we should start dropping. + for (int i = 0; i < 7; i++) { + emitLog(sdkTracerProvider, "log_2_" + i); + } + + // Release the blocking exporter + blockingLogRecordExporter.unblock(); + + // While we wait for maxQueuedLogs we ensure that the queue is also empty after this. + List exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported).isNotNull(); + assertThat(exported).hasSize(maxQueuedLogs + 1); + + // Clear, reset, add another batch of logs, and confirm they are exported + exported.clear(); + waitingLogRecordExporter.reset(); + for (int i = 0; i < maxQueuedLogs; i++) { + emitLog(sdkTracerProvider, "log_3_" + i); + } + + exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported).isNotNull(); + assertThat(exported).hasSize(maxQueuedLogs); + } + + @Test + void ignoresNullLogs() { + BatchLogRecordProcessor processor = + BatchLogRecordProcessor.builder(mockLogRecordExporter).build(); + try { + assertThatCode(() -> processor.onEmit(null, null)).doesNotThrowAnyException(); + } finally { + processor.shutdown(); + } + } + + @Test + @SuppressLogger(MultiLogRecordExporter.class) + void exporterThrowsException() { + WaitingLogRecordExporter waitingLogRecordExporter = + new WaitingLogRecordExporter(1, CompletableResultCode.ofSuccess()); + doThrow(new IllegalArgumentException("No export for you.")) + .when(mockLogRecordExporter) + .export(anyList()); + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder( + LogRecordExporter.composite( + Arrays.asList(mockLogRecordExporter, waitingLogRecordExporter))) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .build()) + .build(); + + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + + List exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported) + .satisfiesExactly(logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_1)); + waitingLogRecordExporter.reset(); + // Continue to export after the exception was received. + emitLog(sdkLoggerProvider, LOG_MESSAGE_2); + exported = waitingLogRecordExporter.waitForExport(); + assertThat(exported) + .satisfiesExactly(logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_2)); + } + + @Test + @Timeout(5) + @SuppressLogger(BatchLogRecordProcessor.class) + @SuppressLogger(loggerName = "io.opentelemetry.sdk.logs.export.BatchLogRecordProcessor$Worker") + void exporterThrowsNonRuntimeException() { + AtomicInteger exportCount = new AtomicInteger(); + doAnswer( + invocation -> { + if (exportCount.incrementAndGet() == 1) { + throw new Exception("simulated non-RuntimeException"); + } + return CompletableResultCode.ofSuccess(); + }) + .when(mockLogRecordExporter) + .export(anyList()); + BatchLogRecordProcessor processor = + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .build(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(processor).build(); + + emitLog(loggerProvider, LOG_MESSAGE_1); + await().untilAsserted(() -> assertThat(exportCount.get()).isGreaterThanOrEqualTo(1)); + // Confirm worker is still alive after the non-RuntimeException + emitLog(loggerProvider, LOG_MESSAGE_2); + await().untilAsserted(() -> assertThat(exportCount.get()).isGreaterThanOrEqualTo(2)); + } + + @Test + @Timeout(5) + public void continuesIfExporterTimesOut() throws InterruptedException { + int exporterTimeoutMillis = 10; + BatchLogRecordProcessor blp = + BatchLogRecordProcessor.builder(mockLogRecordExporter) + .setExporterTimeout(exporterTimeoutMillis, TimeUnit.MILLISECONDS) + .setScheduleDelay(1, TimeUnit.MILLISECONDS) + .setMaxQueueSize(1) + .setMaxExportBatchSize(1) + .build(); + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder().addLogRecordProcessor(blp).build(); + + CountDownLatch exported = new CountDownLatch(1); + // We return a result we never complete, meaning it will timeout. + when(mockLogRecordExporter.export( + argThat(logs -> { + assertThat(logs).anySatisfy(log -> assertThat(log).hasBody(LOG_MESSAGE_1)); + exported.countDown(); + return true; + }))) + .thenReturn(new CompletableResultCode()); + emitLog(sdkLoggerProvider, LOG_MESSAGE_1); + exported.await(); + // Timed out so the log was dropped. + await().untilAsserted(() -> assertThat(blp.getBatch()).isEmpty()); + + // Still processing new logs. + CountDownLatch exportedAgain = new CountDownLatch(1); + reset(mockLogRecordExporter); + when(mockLogRecordExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockLogRecordExporter.export( + argThat(logs -> { + assertThat(logs).anySatisfy(log -> assertThat(log).hasBody(LOG_MESSAGE_2)); + exportedAgain.countDown(); + return true; + }))) + .thenReturn(CompletableResultCode.ofSuccess()); + emitLog(sdkLoggerProvider, LOG_MESSAGE_2); + exported.await(); + await().untilAsserted(() -> assertThat(blp.getBatch()).isEmpty()); + } + + @Test + @Timeout(10) + void shutdownFlushes() { + WaitingLogRecordExporter waitingLogRecordExporter = + new WaitingLogRecordExporter(1, CompletableResultCode.ofSuccess()); + // Set the export delay to large value, in order to confirm the #flush() below works + + SdkLoggerProvider sdkLoggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor( + BatchLogRecordProcessor.builder(waitingLogRecordExporter) + .setScheduleDelay(10, TimeUnit.SECONDS) + .build()) + .build(); + + emitLog(sdkLoggerProvider, LOG_MESSAGE_2); + + // Force a shutdown, which forces processing of all remaining logs. + sdkLoggerProvider.shutdown().join(10, TimeUnit.SECONDS); + + List exported = waitingLogRecordExporter.getExported(); + assertThat(exported) + .satisfiesExactly(logRecordData -> assertThat(logRecordData).hasBody(LOG_MESSAGE_2)); + assertThat(waitingLogRecordExporter.shutDownCalled.get()).isTrue(); + } + + @Test + void shutdownPropagatesSuccess() { + BatchLogRecordProcessor processor = + BatchLogRecordProcessor.builder(mockLogRecordExporter).build(); + CompletableResultCode result = processor.shutdown(); + result.join(1, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isTrue(); + } + + @Test + void shutdownPropagatesFailure() { + when(mockLogRecordExporter.shutdown()).thenReturn(CompletableResultCode.ofFailure()); + BatchLogRecordProcessor processor = + BatchLogRecordProcessor.builder(mockLogRecordExporter).build(); + CompletableResultCode result = processor.shutdown(); + result.join(1, TimeUnit.SECONDS); + assertThat(result.isSuccess()).isFalse(); + } + + @Test + void getLogRecordExporter() { + assertThat( + BatchLogRecordProcessor.builder(mockLogRecordExporter).build().getLogRecordExporter()) + .isSameAs(mockLogRecordExporter); + } + + @Test + void toString_Valid() { + when(mockLogRecordExporter.toString()).thenReturn("MockLogRecordExporter"); + assertThat(BatchLogRecordProcessor.builder(mockLogRecordExporter).build().toString()) + .isEqualTo( + "BatchLogRecordProcessor{" + + "logRecordExporter=MockLogRecordExporter" + + ", scheduleDelayNanos=1000000000" + + ", maxExportBatchSize=512" + + ", exporterTimeoutNanos=30000000000" + + "}"); + } + + private static final class BlockingLogRecordExporter implements LogRecordExporter { + + final Object monitor = new Object(); + + private enum State { + WAIT_TO_BLOCK, + BLOCKED, + UNBLOCKED + } + + @GuardedBy("monitor") + State state = State.WAIT_TO_BLOCK; + + @Override + public CompletableResultCode export(Collection logs) { + synchronized (monitor) { + while (state != State.UNBLOCKED) { + try { + state = State.BLOCKED; + // Some threads may wait for Blocked State. + monitor.notifyAll(); + monitor.wait(); + } catch (InterruptedException e) { + // Do nothing + } + } + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + private void waitUntilIsBlocked() { + synchronized (monitor) { + while (state != State.BLOCKED) { + try { + monitor.wait(); + } catch (InterruptedException e) { + // Do nothing + } + } + } + } + + @Override + public CompletableResultCode shutdown() { + // Do nothing; + return CompletableResultCode.ofSuccess(); + } + + private void unblock() { + synchronized (monitor) { + state = State.UNBLOCKED; + monitor.notifyAll(); + } + } + } + + private static class CompletableLogRecordExporter implements LogRecordExporter { + + private final List results = new ArrayList<>(); + + private final List exported = new ArrayList<>(); + + private volatile boolean succeeded; + + List getExported() { + return exported; + } + + void succeed() { + succeeded = true; + results.forEach(CompletableResultCode::succeed); + } + + @Override + public CompletableResultCode export(Collection logs) { + exported.addAll(logs); + if (succeeded) { + return CompletableResultCode.ofSuccess(); + } + CompletableResultCode result = new CompletableResultCode(); + results.add(result); + return result; + } + + @Override + public CompletableResultCode flush() { + if (succeeded) { + return CompletableResultCode.ofSuccess(); + } else { + return CompletableResultCode.ofFailure(); + } + } + + @Override + public CompletableResultCode shutdown() { + return flush(); + } + } + + static class WaitingLogRecordExporter implements LogRecordExporter { + + private final List logRecordDataList = new ArrayList<>(); + private final int numberToWaitFor; + private final CompletableResultCode exportResultCode; + private CountDownLatch countDownLatch; + private int timeout = 10; + private final AtomicBoolean shutDownCalled = new AtomicBoolean(false); + + WaitingLogRecordExporter(int numberToWaitFor, CompletableResultCode exportResultCode) { + countDownLatch = new CountDownLatch(numberToWaitFor); + this.numberToWaitFor = numberToWaitFor; + this.exportResultCode = exportResultCode; + } + + WaitingLogRecordExporter( + int numberToWaitFor, CompletableResultCode exportResultCode, int timeout) { + this(numberToWaitFor, exportResultCode); + this.timeout = timeout; + } + + List getExported() { + List result = new ArrayList<>(logRecordDataList); + logRecordDataList.clear(); + return result; + } + + /** + * Waits until we received {@link #numberToWaitFor} logs to export. Returns the list of exported + * {@link LogRecordData} objects, otherwise {@code null} if the current thread is interrupted. + * + * @return the list of exported {@link LogRecordData} objects, otherwise {@code null} if the + * current thread is interrupted. + */ + @Nullable + List waitForExport() { + try { + countDownLatch.await(timeout, TimeUnit.SECONDS); + } catch (InterruptedException e) { + // Preserve the interruption status as per guidance. + Thread.currentThread().interrupt(); + return null; + } + return getExported(); + } + + @Override + public CompletableResultCode export(Collection logs) { + this.logRecordDataList.addAll(logs); + for (int i = 0; i < logs.size(); i++) { + countDownLatch.countDown(); + } + return exportResultCode; + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + shutDownCalled.set(true); + return CompletableResultCode.ofSuccess(); + } + + public void reset() { + this.countDownLatch = new CountDownLatch(numberToWaitFor); + } + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/InMemoryLogExporterTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/InMemoryLogExporterTest.java deleted file mode 100644 index fcb1b546b9a..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/InMemoryLogExporterTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import static io.opentelemetry.sdk.logs.data.Severity.DEBUG; -import static io.opentelemetry.sdk.logs.util.TestUtil.createLogData; -import static org.assertj.core.api.Assertions.assertThat; - -import io.opentelemetry.sdk.logs.LogEmitter; -import io.opentelemetry.sdk.logs.SdkLogEmitterProvider; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.testing.assertj.LogAssertions; -import java.util.Collections; -import java.util.List; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -/** Unit tests for {@link InMemoryLogExporter}. */ -class InMemoryLogExporterTest { - private final InMemoryLogExporter exporter = InMemoryLogExporter.create(); - - private SdkLogEmitterProvider logEmitterProvider; - private LogEmitter logEmitter; - - @BeforeEach - void setup() { - logEmitterProvider = - SdkLogEmitterProvider.builder() - .addLogProcessor(SimpleLogProcessor.create(exporter)) - .build(); - logEmitter = logEmitterProvider.logEmitterBuilder("emitter").build(); - } - - @AfterEach - void tearDown() { - logEmitterProvider.shutdown(); - } - - @Test - void getFinishedLogItems() { - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 1").emit(); - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 2").emit(); - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 3").emit(); - - List logItems = exporter.getFinishedLogItems(); - assertThat(logItems).isNotNull(); - assertThat(logItems.size()).isEqualTo(3); - LogAssertions.assertThat(logItems.get(0)).hasBody("message 1"); - LogAssertions.assertThat(logItems.get(1)).hasBody("message 2"); - LogAssertions.assertThat(logItems.get(2)).hasBody("message 3"); - } - - @Test - void reset() { - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 1").emit(); - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 2").emit(); - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 3").emit(); - List logItems = exporter.getFinishedLogItems(); - assertThat(logItems).isNotNull(); - assertThat(logItems.size()).isEqualTo(3); - // Reset then expect no items in memory. - exporter.reset(); - assertThat(exporter.getFinishedLogItems()).isEmpty(); - } - - @Test - void shutdown() { - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 1").emit(); - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 2").emit(); - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 3").emit(); - List logItems = exporter.getFinishedLogItems(); - assertThat(logItems).isNotNull(); - assertThat(logItems.size()).isEqualTo(3); - // Shutdown then expect no items in memory. - exporter.shutdown(); - assertThat(exporter.getFinishedLogItems()).isEmpty(); - // Cannot add new elements after the shutdown. - logEmitter.logBuilder().setSeverity(DEBUG).setBody("message 1").emit(); - assertThat(exporter.getFinishedLogItems()).isEmpty(); - } - - @Test - void export_ReturnCode() { - LogData logData = createLogData(DEBUG, "message 1"); - assertThat(exporter.export(Collections.singletonList(logData)).isSuccess()).isTrue(); - exporter.shutdown(); - // After shutdown no more export. - assertThat(exporter.export(Collections.singletonList(logData)).isSuccess()).isFalse(); - exporter.reset(); - // Reset does not do anything if already shutdown. - assertThat(exporter.export(Collections.singletonList(logData)).isSuccess()).isFalse(); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/LogRecordExporterTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/LogRecordExporterTest.java new file mode 100644 index 00000000000..10325453adc --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/LogRecordExporterTest.java @@ -0,0 +1,45 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +class LogRecordExporterTest { + + @Test + void testNoop() { + LogRecordExporter noop = LogRecordExporter.noop(); + assertNotNull(noop); + assertSame(NoopLogRecordExporter.getInstance(), noop); + } + + @Test + void testComposite() { + LogRecordExporter exp1 = mock(); + LogRecordExporter exp2 = mock(); + List logs = Collections.singletonList(mock()); + + when(exp1.export(logs)).thenReturn(CompletableResultCode.ofSuccess()); + when(exp2.export(logs)).thenReturn(CompletableResultCode.ofSuccess()); + + LogRecordExporter exporter = LogRecordExporter.composite(exp1, exp2); + + exporter.export(logs); + + verify(exp1).export(logs); + verify(exp2).export(logs); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/MultiLogExporterTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/MultiLogExporterTest.java deleted file mode 100644 index 3e249a8bf9d..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/MultiLogExporterTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.logs.util.TestUtil; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentMatchers; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class MultiLogExporterTest { - @Mock private LogExporter logExporter1; - @Mock private LogExporter logExporter2; - private static final List LOG_LIST = - Collections.singletonList(TestUtil.createLogData(Severity.DEBUG, "Message!")); - - @Test - void empty() { - LogExporter multiLogExporter = LogExporter.composite(Collections.emptyList()); - multiLogExporter.export(LOG_LIST); - multiLogExporter.shutdown(); - } - - @Test - void oneLogExporter() { - LogExporter multiLogExporter = LogExporter.composite(Collections.singletonList(logExporter1)); - - when(logExporter1.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.export(LOG_LIST).isSuccess()).isTrue(); - verify(logExporter1).export(same(LOG_LIST)); - - when(logExporter1.flush()).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.flush().isSuccess()).isTrue(); - verify(logExporter1).flush(); - - when(logExporter1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - multiLogExporter.shutdown(); - verify(logExporter1).shutdown(); - } - - @Test - void twoLogExporter() { - LogExporter multiLogExporter = LogExporter.composite(Arrays.asList(logExporter1, logExporter2)); - - when(logExporter1.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.export(LOG_LIST).isSuccess()).isTrue(); - verify(logExporter1).export(same(LOG_LIST)); - verify(logExporter2).export(same(LOG_LIST)); - - when(logExporter1.flush()).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter2.flush()).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.flush().isSuccess()).isTrue(); - verify(logExporter1).flush(); - verify(logExporter2).flush(); - - when(logExporter1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - multiLogExporter.shutdown(); - verify(logExporter1).shutdown(); - verify(logExporter2).shutdown(); - } - - @Test - void twoLogExporter_OneReturnFailure() { - LogExporter multiLogExporter = LogExporter.composite(Arrays.asList(logExporter1, logExporter2)); - - when(logExporter1.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofFailure()); - assertThat(multiLogExporter.export(LOG_LIST).isSuccess()).isFalse(); - verify(logExporter1).export(same(LOG_LIST)); - verify(logExporter2).export(same(LOG_LIST)); - - when(logExporter1.flush()).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter2.flush()).thenReturn(CompletableResultCode.ofFailure()); - assertThat(multiLogExporter.flush().isSuccess()).isFalse(); - verify(logExporter1).flush(); - verify(logExporter2).flush(); - - when(logExporter1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter2.shutdown()).thenReturn(CompletableResultCode.ofFailure()); - assertThat(multiLogExporter.shutdown().isSuccess()).isFalse(); - verify(logExporter1).shutdown(); - verify(logExporter2).shutdown(); - } - - @Test - @SuppressLogger(MultiLogExporter.class) - void twoLogExporter_FirstThrows() { - LogExporter multiLogExporter = LogExporter.composite(Arrays.asList(logExporter1, logExporter2)); - - Mockito.doThrow(new IllegalArgumentException("No export for you.")) - .when(logExporter1) - .export(ArgumentMatchers.anyList()); - when(logExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.export(LOG_LIST).isSuccess()).isFalse(); - verify(logExporter1).export(same(LOG_LIST)); - verify(logExporter2).export(same(LOG_LIST)); - - Mockito.doThrow(new IllegalArgumentException("No flush for you.")).when(logExporter1).flush(); - when(logExporter2.flush()).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.flush().isSuccess()).isFalse(); - verify(logExporter1).flush(); - verify(logExporter2).flush(); - - Mockito.doThrow(new IllegalArgumentException("No shutdown for you.")) - .when(logExporter1) - .shutdown(); - when(logExporter2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - assertThat(multiLogExporter.shutdown().isSuccess()).isFalse(); - verify(logExporter1).shutdown(); - verify(logExporter2).shutdown(); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/MultiLogRecordExporterTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/MultiLogRecordExporterTest.java new file mode 100644 index 00000000000..38c4ba437f6 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/MultiLogRecordExporterTest.java @@ -0,0 +1,167 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentMatchers; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class MultiLogRecordExporterTest { + @Mock private LogRecordExporter logRecordExporter1; + @Mock private LogRecordExporter logRecordExporter2; + private static final List LOG_LIST = + Collections.singletonList( + TestLogRecordData.builder().setBody("Message!").setSeverity(Severity.DEBUG).build()); + + @Test + void empty() { + LogRecordExporter multiLogRecordExporter = LogRecordExporter.composite(Collections.emptyList()); + multiLogRecordExporter.export(LOG_LIST); + multiLogRecordExporter.shutdown(); + } + + @Test + void oneLogRecordExporter() { + LogRecordExporter multiLogRecordExporter = + LogRecordExporter.composite(Collections.singletonList(logRecordExporter1)); + + when(logRecordExporter1.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.export(LOG_LIST).isSuccess()).isTrue(); + verify(logRecordExporter1).export(same(LOG_LIST)); + + when(logRecordExporter1.flush()).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.flush().isSuccess()).isTrue(); + verify(logRecordExporter1).flush(); + + when(logRecordExporter1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + multiLogRecordExporter.shutdown(); + verify(logRecordExporter1).shutdown(); + } + + @Test + void twoLogRecordExporter() { + LogRecordExporter multiLogRecordExporter = + LogRecordExporter.composite(Arrays.asList(logRecordExporter1, logRecordExporter2)); + + when(logRecordExporter1.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.export(LOG_LIST).isSuccess()).isTrue(); + verify(logRecordExporter1).export(same(LOG_LIST)); + verify(logRecordExporter2).export(same(LOG_LIST)); + + when(logRecordExporter1.flush()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter2.flush()).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.flush().isSuccess()).isTrue(); + verify(logRecordExporter1).flush(); + verify(logRecordExporter2).flush(); + + when(logRecordExporter1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + multiLogRecordExporter.shutdown(); + verify(logRecordExporter1).shutdown(); + verify(logRecordExporter2).shutdown(); + } + + @Test + void twoLogRecordExporter_OneReturnFailure() { + LogRecordExporter multiLogRecordExporter = + LogRecordExporter.composite(Arrays.asList(logRecordExporter1, logRecordExporter2)); + + when(logRecordExporter1.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofFailure()); + assertThat(multiLogRecordExporter.export(LOG_LIST).isSuccess()).isFalse(); + verify(logRecordExporter1).export(same(LOG_LIST)); + verify(logRecordExporter2).export(same(LOG_LIST)); + + when(logRecordExporter1.flush()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter2.flush()).thenReturn(CompletableResultCode.ofFailure()); + assertThat(multiLogRecordExporter.flush().isSuccess()).isFalse(); + verify(logRecordExporter1).flush(); + verify(logRecordExporter2).flush(); + + when(logRecordExporter1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter2.shutdown()).thenReturn(CompletableResultCode.ofFailure()); + assertThat(multiLogRecordExporter.shutdown().isSuccess()).isFalse(); + verify(logRecordExporter1).shutdown(); + verify(logRecordExporter2).shutdown(); + } + + @Test + @SuppressLogger(MultiLogRecordExporter.class) + void twoLogRecordExporter_FirstThrows() { + LogRecordExporter multiLogRecordExporter = + LogRecordExporter.composite(Arrays.asList(logRecordExporter1, logRecordExporter2)); + + Mockito.doThrow(new IllegalArgumentException("No export for you.")) + .when(logRecordExporter1) + .export(ArgumentMatchers.anyList()); + when(logRecordExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.export(LOG_LIST).isSuccess()).isFalse(); + verify(logRecordExporter1).export(same(LOG_LIST)); + verify(logRecordExporter2).export(same(LOG_LIST)); + + Mockito.doThrow(new IllegalArgumentException("No flush for you.")) + .when(logRecordExporter1) + .flush(); + when(logRecordExporter2.flush()).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.flush().isSuccess()).isFalse(); + verify(logRecordExporter1).flush(); + verify(logRecordExporter2).flush(); + + Mockito.doThrow(new IllegalArgumentException("No shutdown for you.")) + .when(logRecordExporter1) + .shutdown(); + when(logRecordExporter2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + assertThat(multiLogRecordExporter.shutdown().isSuccess()).isFalse(); + verify(logRecordExporter1).shutdown(); + verify(logRecordExporter2).shutdown(); + } + + @Test + void toString_Valid() { + when(logRecordExporter1.toString()).thenReturn("LogRecordExporter1"); + when(logRecordExporter2.toString()).thenReturn("LogRecordExporter2"); + assertThat(LogRecordExporter.composite(logRecordExporter1, logRecordExporter2).toString()) + .isEqualTo( + "MultiLogRecordExporter{logRecordExporters=[LogRecordExporter1, LogRecordExporter2]}"); + } + + @Test + @SuppressLogger(MultiLogRecordExporter.class) + void twoLogRecordExporter_FirstThrowsCheckedException() { + LogRecordExporter multiLogRecordExporter = + LogRecordExporter.composite(Arrays.asList(logRecordExporter1, logRecordExporter2)); + + Mockito.doAnswer( + invocation -> { + throw new Exception("No export for you."); + }) + .when(logRecordExporter1) + .export(ArgumentMatchers.anyList()); + when(logRecordExporter2.export(same(LOG_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + + assertThat(multiLogRecordExporter.export(LOG_LIST).isSuccess()).isFalse(); + verify(logRecordExporter1).export(same(LOG_LIST)); + verify(logRecordExporter2).export(same(LOG_LIST)); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogProcessorTest.java deleted file mode 100644 index 7aaa7cf432f..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogProcessorTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.export; - -import static io.opentelemetry.sdk.logs.data.Severity.DEBUG; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyCollection; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import io.opentelemetry.internal.testing.slf4j.SuppressLogger; -import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.logs.LogProcessor; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.util.TestUtil; -import java.util.Collections; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; -import org.mockito.junit.jupiter.MockitoSettings; -import org.mockito.quality.Strictness; - -@ExtendWith(MockitoExtension.class) -@MockitoSettings(strictness = Strictness.LENIENT) -class SimpleLogProcessorTest { - - @Mock private LogExporter logExporter; - - private LogProcessor logProcessor; - - @BeforeEach - void setUp() { - logProcessor = SimpleLogProcessor.create(logExporter); - when(logExporter.export(anyCollection())).thenReturn(CompletableResultCode.ofSuccess()); - when(logExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); - } - - @Test - void create_NullExporter() { - assertThatThrownBy(() -> SimpleLogProcessor.create(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("exporter"); - } - - @Test - void addLogRecord() { - LogData logData = TestUtil.createLogData(DEBUG, "Log message"); - logProcessor.emit(logData); - verify(logExporter).export(Collections.singletonList(logData)); - } - - @Test - @SuppressLogger(SimpleLogProcessor.class) - void addLogRecord_ExporterError() { - LogData logData = TestUtil.createLogData(DEBUG, "Log message"); - when(logExporter.export(any())).thenThrow(new RuntimeException("Exporter error!")); - logProcessor.emit(logData); - logProcessor.emit(logData); - verify(logExporter, times(2)).export(Collections.singletonList(logData)); - } - - @Test - void forceFlush() { - CompletableResultCode export1 = new CompletableResultCode(); - CompletableResultCode export2 = new CompletableResultCode(); - - when(logExporter.export(any())).thenReturn(export1, export2); - - LogData logData = TestUtil.createLogData(DEBUG, "Log message"); - logProcessor.emit(logData); - logProcessor.emit(logData); - - verify(logExporter, times(2)).export(Collections.singletonList(logData)); - - CompletableResultCode flush = logProcessor.forceFlush(); - assertThat(flush.isDone()).isFalse(); - - export1.succeed(); - assertThat(flush.isDone()).isFalse(); - - export2.succeed(); - assertThat(flush.isDone()).isTrue(); - assertThat(flush.isSuccess()).isTrue(); - } - - @Test - void shutdown() { - CompletableResultCode export1 = new CompletableResultCode(); - CompletableResultCode export2 = new CompletableResultCode(); - - when(logExporter.export(any())).thenReturn(export1, export2); - - LogData logData = TestUtil.createLogData(DEBUG, "Log message"); - logProcessor.emit(logData); - logProcessor.emit(logData); - - verify(logExporter, times(2)).export(Collections.singletonList(logData)); - - CompletableResultCode shutdown = logProcessor.shutdown(); - assertThat(shutdown.isDone()).isFalse(); - - export1.succeed(); - assertThat(shutdown.isDone()).isFalse(); - verify(logExporter, never()).shutdown(); - - export2.succeed(); - assertThat(shutdown.isDone()).isTrue(); - assertThat(shutdown.isSuccess()).isTrue(); - verify(logExporter).shutdown(); - } -} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java new file mode 100644 index 00000000000..977a7590076 --- /dev/null +++ b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/export/SimpleLogRecordProcessorTest.java @@ -0,0 +1,151 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs.export; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.LogRecordProcessor; +import io.opentelemetry.sdk.logs.ReadWriteLogRecord; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; + +@ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) +class SimpleLogRecordProcessorTest { + + private static final LogRecordData LOG_RECORD_DATA = TestLogRecordData.builder().build(); + + @Mock private LogRecordExporter logRecordExporter; + @Mock private ReadWriteLogRecord readWriteLogRecord; + + private LogRecordProcessor logRecordProcessor; + + @BeforeEach + void setUp() { + logRecordProcessor = SimpleLogRecordProcessor.create(logRecordExporter); + when(logRecordExporter.export(anyCollection())).thenReturn(CompletableResultCode.ofSuccess()); + when(logRecordExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(readWriteLogRecord.toLogRecordData()).thenReturn(LOG_RECORD_DATA); + } + + @Test + void create_NullExporter() { + assertThatThrownBy(() -> SimpleLogRecordProcessor.create(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("exporter"); + } + + @Test + void onEmit() { + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + verify(logRecordExporter).export(Collections.singletonList(LOG_RECORD_DATA)); + } + + @Test + @SuppressLogger(SimpleLogRecordProcessor.class) + void onEmit_ExporterError() { + when(logRecordExporter.export(any())).thenThrow(new RuntimeException("Exporter error!")); + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + verify(logRecordExporter, times(2)).export(anyList()); + } + + @Test + @SuppressLogger(SimpleLogRecordProcessor.class) + void onEmit_ExporterThrowsCheckedException() { + when(logRecordExporter.export(any())) + .thenAnswer(invocation -> { + throw new Exception("Exporter error!"); + }); + + assertThatCode(() -> logRecordProcessor.onEmit(Context.current(), readWriteLogRecord)) + .doesNotThrowAnyException(); + verify(logRecordExporter).export(anyList()); + } + + @Test + void forceFlush() { + CompletableResultCode export1 = new CompletableResultCode(); + CompletableResultCode export2 = new CompletableResultCode(); + + when(logRecordExporter.export(any())).thenReturn(export1, export2); + + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + + verify(logRecordExporter, times(2)).export(Collections.singletonList(LOG_RECORD_DATA)); + + CompletableResultCode flush = logRecordProcessor.forceFlush(); + assertThat(flush.isDone()).isFalse(); + + export1.succeed(); + assertThat(flush.isDone()).isFalse(); + + export2.succeed(); + assertThat(flush.isDone()).isTrue(); + assertThat(flush.isSuccess()).isTrue(); + } + + @Test + void shutdown() { + CompletableResultCode export1 = new CompletableResultCode(); + CompletableResultCode export2 = new CompletableResultCode(); + + when(logRecordExporter.export(any())).thenReturn(export1, export2); + + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + logRecordProcessor.onEmit(Context.current(), readWriteLogRecord); + + verify(logRecordExporter, times(2)).export(Collections.singletonList(LOG_RECORD_DATA)); + + CompletableResultCode shutdown = logRecordProcessor.shutdown(); + assertThat(shutdown.isDone()).isFalse(); + + export1.succeed(); + assertThat(shutdown.isDone()).isFalse(); + verify(logRecordExporter, never()).shutdown(); + + export2.succeed(); + assertThat(shutdown.isDone()).isTrue(); + assertThat(shutdown.isSuccess()).isTrue(); + verify(logRecordExporter).shutdown(); + } + + @Test + void getLogRecordExporter() { + assertThat( + ((SimpleLogRecordProcessor) SimpleLogRecordProcessor.create(logRecordExporter)) + .getLogRecordExporter()) + .isSameAs(logRecordExporter); + } + + @Test + void toString_Valid() { + when(logRecordExporter.toString()).thenReturn("MockLogRecordExporter"); + assertThat(logRecordProcessor.toString()) + .isEqualTo("SimpleLogRecordProcessor{logRecordExporter=MockLogRecordExporter}"); + } +} diff --git a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/util/TestUtil.java b/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/util/TestUtil.java deleted file mode 100644 index 420bf214785..00000000000 --- a/sdk/logs/src/test/java/io/opentelemetry/sdk/logs/util/TestUtil.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.logs.util; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.logs.data.LogData; -import io.opentelemetry.sdk.logs.data.LogDataBuilder; -import io.opentelemetry.sdk.logs.data.Severity; -import io.opentelemetry.sdk.resources.Resource; -import java.util.concurrent.TimeUnit; - -public final class TestUtil { - - public static LogData createLogData(Severity severity, String message) { - return LogDataBuilder.create( - Resource.create(Attributes.builder().put("testKey", "testValue").build()), - InstrumentationScopeInfo.create("instrumentation", "1", null)) - .setEpoch(System.currentTimeMillis(), TimeUnit.MILLISECONDS) - .setSeverity(severity) - .setSeverityText("really severe") - .setBody(message) - .setAttributes(Attributes.builder().put("animal", "cat").build()) - .build(); - } - - private TestUtil() {} -} diff --git a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ContextScopedAttributesLogTest.java b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ContextScopedAttributesLogTest.java new file mode 100644 index 00000000000..c9e0fc63507 --- /dev/null +++ b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ContextScopedAttributesLogTest.java @@ -0,0 +1,202 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.common.ContextAttributes; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ContextScopedAttributesLogTest { + + private InMemoryLogRecordExporter exporter; + private SdkLoggerProviderBuilder builder; + + @BeforeEach + void setUp() { + exporter = InMemoryLogRecordExporter.create(); + builder = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)); + } + + @Test + void disabledByDefault() { + SdkLoggerProvider provider = builder.build(); + Logger logger = provider.get("test"); + + Context ctx = ContextAttributes.set(Context.current(), Attributes.of(stringKey("k1"), "v1")); + try (Scope ignored = ctx.makeCurrent()) { + logger.logRecordBuilder().setBody("hello").emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly( + log -> assertThat(log).hasBody("hello").hasAttributes(Attributes.empty())); + } + + @Test + void enabled_mergesWithExplicitPrecedence() { + SdkLoggerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkLoggerProvider provider = builder.build(); + Logger logger = provider.get("test"); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("k1"), "from-context", stringKey("k2"), "from-context")); + try (Scope ignored = ctx.makeCurrent()) { + logger + .logRecordBuilder() + .setAttribute(stringKey("k2"), "explicit") + .setAttribute(stringKey("k3"), "v3") + .setBody("hello") + .emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(log -> + assertThat(log) + .hasBody("hello") + .hasAttributes( + attributeEntry("k1", "from-context"), + attributeEntry("k2", "explicit"), + attributeEntry("k3", "v3"))); + } + + @Test + void usesExplicitContext() { + SdkLoggerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkLoggerProvider provider = builder.build(); + Logger logger = provider.get("test"); + + Context explicitCtx = + ContextAttributes.set(Context.root(), Attributes.of(stringKey("ctx"), "explicit")); + Context currentCtx = + ContextAttributes.set(Context.root(), Attributes.of(stringKey("ctx"), "current")); + + try (Scope ignored = currentCtx.makeCurrent()) { + logger.logRecordBuilder().setContext(explicitCtx).setBody("hello").emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(log -> + assertThat(log).hasBody("hello").hasAttributes(attributeEntry("ctx", "explicit"))); + } + + @Test + void sameNameDifferentType_explicitWins() { + SdkLoggerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkLoggerProvider provider = builder.build(); + Logger logger = provider.get("test"); + + Context ctx = + ContextAttributes.set( + Context.current(), Attributes.of(stringKey("collision"), "contextString")); + try (Scope ignored = ctx.makeCurrent()) { + logger + .logRecordBuilder() + .setAttribute(longKey("collision"), 999L) + .setBody("collision test") + .emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(log -> + assertThat(log) + .hasBody("collision test") + .hasAttributes(attributeEntry("collision", 999L))); + } + + @Test + void filterPredicate_filtersByScopeAndKey() { + SdkLoggerProviderUtil.setContextScopedAttributesFilter( + builder, + (scope, key) -> + scope.getName().equals("allowed-logger") && key.getKey().startsWith("allowed.")); + SdkLoggerProvider provider = builder.build(); + + Logger allowedLogger = provider.get("allowed-logger"); + Logger otherLogger = provider.get("other-logger"); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("allowed.k"), "v1", stringKey("denied.k"), "v2")); + + try (Scope ignored = ctx.makeCurrent()) { + allowedLogger.logRecordBuilder().setBody("msg1").emit(); + otherLogger.logRecordBuilder().setBody("msg2").emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly( + log1 -> + assertThat(log1).hasBody("msg1").hasAttributes(attributeEntry("allowed.k", "v1")), + log2 -> assertThat(log2).hasBody("msg2").hasAttributes(Attributes.empty())); + } + + @Test + void logRecordAttributeLimit() { + builder.setLogLimits(() -> LogLimits.builder().setMaxNumberOfAttributes(1).build()); + SdkLoggerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkLoggerProvider provider = builder.build(); + Logger logger = provider.get("test"); + + Context ctx = ContextAttributes.set(Context.root(), Attributes.of(stringKey("scope"), "ctx")); + + try (Scope ignored = ctx.makeCurrent()) { + logger.logRecordBuilder().setAttribute(stringKey("explicit"), "val").emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(record -> + assertThat(record) + .hasAttributes(attributeEntry("explicit", "val")) + .hasTotalAttributeCount(2)); + } + + @Test + void explicitExceedsLimitAndContextPresent_tracksDroppedAttributesCorrectly() { + builder.setLogLimits(() -> LogLimits.builder().setMaxNumberOfAttributes(2).build()); + SdkLoggerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkLoggerProvider provider = builder.build(); + Logger logger = provider.get("test"); + + Context ctx = + ContextAttributes.set( + Context.root(), + Attributes.of(stringKey("ctx1"), "ctxVal1", stringKey("ctx2"), "ctxVal2")); + + try (Scope ignored = ctx.makeCurrent()) { + logger + .logRecordBuilder() + .setAttribute(stringKey("exp1"), "expVal1") + .setAttribute(stringKey("exp2"), "expVal2") + .setAttribute(stringKey("exp3"), "expVal3") + .setBody("test log with dropped attributes") + .emit(); + } + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(record -> + assertThat(record) + .hasBody("test log with dropped attributes") + .hasAttributes(attributeEntry("exp1", "expVal1"), attributeEntry("exp2", "expVal2")) + .hasTotalAttributeCount(5)); + } +} diff --git a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java new file mode 100644 index 00000000000..79885f853b5 --- /dev/null +++ b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/ExtendedLoggerBuilderTest.java @@ -0,0 +1,94 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.satisfies; +import static io.opentelemetry.semconv.ExceptionAttributes.EXCEPTION_MESSAGE; +import static io.opentelemetry.semconv.ExceptionAttributes.EXCEPTION_STACKTRACE; +import static io.opentelemetry.semconv.ExceptionAttributes.EXCEPTION_TYPE; + +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import org.junit.jupiter.api.Test; + +class ExtendedLoggerBuilderTest { + + private final InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + private final SdkLoggerProviderBuilder loggerProviderBuilder = + SdkLoggerProvider.builder().addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)); + + @Test + void setException_DefaultResolver() { + Logger logger = loggerProviderBuilder.build().get("logger"); + + logger.logRecordBuilder().setException(new Exception("error")).emit(); + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(logRecord -> + assertThat(logRecord) + .hasAttributesSatisfyingExactly( + equalTo(EXCEPTION_TYPE, "java.lang.Exception"), + equalTo(EXCEPTION_MESSAGE, "error"), + satisfies( + EXCEPTION_STACKTRACE, + stacktrace -> + stacktrace.startsWith( + "java.lang.Exception: error" + System.lineSeparator())))); + } + + @Test + void setException_CustomResolver() { + SdkLoggerProviderUtil.setExceptionAttributeResolver( + loggerProviderBuilder, + new ExceptionAttributeResolver() { + @Override + public void setExceptionAttributes( + AttributeSetter attributeSetter, Throwable throwable, int maxAttributeLength) { + attributeSetter.setAttribute(ExceptionAttributeResolver.EXCEPTION_TYPE, "type"); + attributeSetter.setAttribute( + ExceptionAttributeResolver.EXCEPTION_STACKTRACE, "stacktrace"); + } + }); + + Logger logger = loggerProviderBuilder.build().get("logger"); + + logger.logRecordBuilder().setException(new Exception("error")).emit(); + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(logRecord -> + assertThat(logRecord) + .hasAttributesSatisfyingExactly( + equalTo(EXCEPTION_TYPE, "type"), equalTo(EXCEPTION_STACKTRACE, "stacktrace"))); + } + + @Test + void setException_UserAttributesTakePrecedence() { + Logger logger = loggerProviderBuilder.build().get("logger"); + + logger + .logRecordBuilder() + .setAttribute(EXCEPTION_MESSAGE, "custom message") + .setException(new Exception("error")) + .emit(); + + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly(logRecord -> + assertThat(logRecord) + .hasAttributesSatisfyingExactly( + equalTo(EXCEPTION_TYPE, "java.lang.Exception"), + equalTo(EXCEPTION_MESSAGE, "custom message"), + satisfies( + EXCEPTION_STACKTRACE, + stacktrace -> + stacktrace.startsWith( + "java.lang.Exception: error" + System.lineSeparator())))); + } +} diff --git a/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java new file mode 100644 index 00000000000..b2b24b25efe --- /dev/null +++ b/sdk/logs/src/testIncubating/java/io/opentelemetry/sdk/logs/LoggerConfigTest.java @@ -0,0 +1,215 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.logs; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameMatchesGlob; +import static io.opentelemetry.sdk.logs.internal.LoggerConfig.defaultConfig; +import static io.opentelemetry.sdk.logs.internal.LoggerConfig.disabled; +import static io.opentelemetry.sdk.logs.internal.LoggerConfig.enabled; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.incubator.logs.ExtendedLogger; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.logs.internal.LoggerConfig; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class LoggerConfigTest { + + @Test + void builder_AllFields() { + LoggerConfig config = + LoggerConfig.builder() + .setEnabled(false) + .setMinimumSeverity(Severity.WARN) + .setTraceBased(true) + .build(); + + assertThat(config.isEnabled()).isFalse(); + assertThat(config.getMinimumSeverity()).isEqualTo(Severity.WARN); + assertThat(config.isTraceBased()).isTrue(); + } + + @Test + void builder_Defaults() { + LoggerConfig config = LoggerConfig.builder().build(); + + assertThat(config.isEnabled()).isTrue(); + assertThat(config.getMinimumSeverity()).isEqualTo(Severity.UNDEFINED_SEVERITY_NUMBER); + assertThat(config.isTraceBased()).isFalse(); + } + + @Test + void disableScopes() { + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + // Disable loggerB. Since loggers are enabled by default, loggerA and loggerC are + // enabled. + .addLoggerConfiguratorCondition(nameEquals("loggerB"), disabled()) + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + + Logger loggerA = loggerProvider.get("loggerA"); + Logger loggerB = loggerProvider.get("loggerB"); + Logger loggerC = loggerProvider.get("loggerC"); + + loggerA.logRecordBuilder().setBody("messageA").emit(); + loggerB.logRecordBuilder().setBody("messageB").emit(); + loggerC.logRecordBuilder().setBody("messageC").emit(); + + // Only logs from loggerA and loggerC should be seen + assertThat(exporter.getFinishedLogRecordItems()) + .satisfies(metrics -> { + Map> logsByScope = + metrics.stream() + .collect(Collectors.groupingBy(LogRecordData::getInstrumentationScopeInfo)); + assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerA"))).hasSize(1); + assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerB"))).isNull(); + assertThat(logsByScope.get(InstrumentationScopeInfo.create("loggerC"))).hasSize(1); + }); + // loggerA and loggerC are enabled, loggerB is disabled. + assertThat(((ExtendedLogger) loggerA).isEnabled(Severity.INFO)).isTrue(); + assertThat(((ExtendedLogger) loggerB).isEnabled(Severity.INFO)).isFalse(); + assertThat(((ExtendedLogger) loggerC).isEnabled(Severity.INFO)).isTrue(); + } + + @ParameterizedTest + @MethodSource("loggerConfiguratorArgs") + void loggerConfigurator( + ScopeConfigurator loggerConfigurator, + InstrumentationScopeInfo scope, + LoggerConfig expectedLoggerConfig) { + LoggerConfig loggerConfig = loggerConfigurator.apply(scope); + loggerConfig = loggerConfig == null ? defaultConfig() : loggerConfig; + assertThat(loggerConfig).isEqualTo(expectedLoggerConfig); + } + + private static final InstrumentationScopeInfo scopeCat = InstrumentationScopeInfo.create("cat"); + private static final InstrumentationScopeInfo scopeDog = InstrumentationScopeInfo.create("dog"); + private static final InstrumentationScopeInfo scopeDuck = InstrumentationScopeInfo.create("duck"); + + private static Stream loggerConfiguratorArgs() { + ScopeConfigurator defaultConfigurator = + LoggerConfig.configuratorBuilder().build(); + ScopeConfigurator disableCat = + LoggerConfig.configuratorBuilder() + .addCondition(nameEquals("cat"), disabled()) + // Second matching rule for cat should be ignored + .addCondition(nameEquals("cat"), enabled()) + .build(); + ScopeConfigurator disableStartsWithD = + LoggerConfig.configuratorBuilder().addCondition(nameMatchesGlob("d*"), disabled()).build(); + ScopeConfigurator enableCat = + LoggerConfig.configuratorBuilder() + .setDefault(disabled()) + .addCondition(nameEquals("cat"), enabled()) + // Second matching rule for cat should be ignored + .addCondition(nameEquals("cat"), disabled()) + .build(); + ScopeConfigurator enableStartsWithD = + LoggerConfig.configuratorBuilder() + .setDefault(disabled()) + .addCondition(nameMatchesGlob("d*"), enabled()) + .build(); + + return Stream.of( + Arguments.argumentSet("default cat", defaultConfigurator, scopeCat, defaultConfig()), + Arguments.argumentSet("default dog", defaultConfigurator, scopeDog, defaultConfig()), + Arguments.argumentSet("default duck", defaultConfigurator, scopeDuck, defaultConfig()), + Arguments.argumentSet("disable cat - cat disabled", disableCat, scopeCat, disabled()), + Arguments.argumentSet("disable cat - dog enabled", disableCat, scopeDog, enabled()), + Arguments.argumentSet("disable cat - duck enabled", disableCat, scopeDuck, enabled()), + Arguments.argumentSet("disable d* - cat enabled", disableStartsWithD, scopeCat, enabled()), + Arguments.argumentSet( + "disable d* - dog disabled", disableStartsWithD, scopeDog, disabled()), + Arguments.argumentSet( + "disable d* - duck disabled", disableStartsWithD, scopeDuck, disabled()), + Arguments.argumentSet("enable cat - cat enabled", enableCat, scopeCat, enabled()), + Arguments.argumentSet("enable cat - dog disabled", enableCat, scopeDog, disabled()), + Arguments.argumentSet("enable cat - duck disabled", enableCat, scopeDuck, disabled()), + Arguments.argumentSet("enable d* - cat disabled", enableStartsWithD, scopeCat, disabled()), + Arguments.argumentSet("enable d* - dog enabled", enableStartsWithD, scopeDog, enabled()), + Arguments.argumentSet("enable d* - duck enabled", enableStartsWithD, scopeDuck, enabled())); + } + + @Test + void setScopeConfigurator() { + // 1. Initially, configure all loggers to be enabled except loggerB + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLoggerConfiguratorCondition(nameEquals("loggerB"), disabled()) + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + + ExtendedSdkLogger loggerA = (ExtendedSdkLogger) loggerProvider.get("loggerA"); + ExtendedSdkLogger loggerB = (ExtendedSdkLogger) loggerProvider.get("loggerB"); + ExtendedSdkLogger loggerC = (ExtendedSdkLogger) loggerProvider.get("loggerC"); + + // verify isEnabled() + assertThat(loggerA.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isTrue(); + assertThat(loggerB.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isFalse(); + assertThat(loggerC.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isTrue(); + + // verify logs are emitted as expected + loggerA.logRecordBuilder().setBody("logA").emit(); + loggerB.logRecordBuilder().setBody("logB").emit(); + loggerC.logRecordBuilder().setBody("logC").emit(); + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactlyInAnyOrder( + log -> assertThat(log).hasBody("logA"), log -> assertThat(log).hasBody("logC")); + exporter.reset(); + + // 2. Update config to disable all loggers + loggerProvider.setLoggerConfigurator( + ScopeConfigurator.builder().setDefault(disabled()).build()); + + // verify isEnabled() + assertThat(loggerA.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isFalse(); + assertThat(loggerB.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isFalse(); + assertThat(loggerC.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isFalse(); + + // verify logs are emitted as expected + loggerA.logRecordBuilder().setBody("logA").emit(); + loggerB.logRecordBuilder().setBody("logB").emit(); + loggerC.logRecordBuilder().setBody("logC").emit(); + assertThat(exporter.getFinishedLogRecordItems()).isEmpty(); + + // 3. Update config to restore original + loggerProvider.setLoggerConfigurator( + ScopeConfigurator.builder() + .addCondition(nameEquals("loggerB"), disabled()) + .build()); + + // verify isEnabled() + assertThat(loggerA.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isTrue(); + assertThat(loggerB.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isFalse(); + assertThat(loggerC.isEnabled(Severity.UNDEFINED_SEVERITY_NUMBER, Context.current())).isTrue(); + + // verify logs are emitted as expected + loggerA.logRecordBuilder().setBody("logA").emit(); + loggerB.logRecordBuilder().setBody("logB").emit(); + loggerC.logRecordBuilder().setBody("logC").emit(); + assertThat(exporter.getFinishedLogRecordItems()) + .satisfiesExactly( + log -> assertThat(log).hasBody("logA"), log -> assertThat(log).hasBody("logC")); + } +} diff --git a/sdk/metrics-testing/README.md b/sdk/metrics-testing/README.md deleted file mode 100644 index 8c191dabb9b..00000000000 --- a/sdk/metrics-testing/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Metrics SDK Testing - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-metrics-testing.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-metrics-testing diff --git a/sdk/metrics-testing/build.gradle.kts b/sdk/metrics-testing/build.gradle.kts deleted file mode 100644 index aeccdef66f4..00000000000 --- a/sdk/metrics-testing/build.gradle.kts +++ /dev/null @@ -1,21 +0,0 @@ -plugins { - id("otel.java-conventions") -} - -description = "OpenTelemetry Metrics SDK Testing utilities" -otelJava.moduleName.set("io.opentelemetry.sdk.metrics-testing") - -dependencies { - api(project(":api:all")) - api(project(":sdk:all")) - api(project(":sdk:metrics")) - api(project(":sdk:testing")) - - compileOnly("org.assertj:assertj-core") - compileOnly("junit:junit") - compileOnly("org.junit.jupiter:junit-jupiter-api") - - annotationProcessor("com.google.auto.value:auto-value") - - testImplementation("junit:junit") -} diff --git a/sdk/metrics-testing/gradle.properties b/sdk/metrics-testing/gradle.properties deleted file mode 100644 index 4476ae57e31..00000000000 --- a/sdk/metrics-testing/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -otel.release=alpha diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointDataAssert.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointDataAssert.java deleted file mode 100644 index 8a619208cf4..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointDataAssert.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.PointData; -import java.util.Arrays; -import java.util.stream.Collectors; -import org.assertj.core.api.AbstractAssert; -import org.assertj.core.api.AbstractIterableAssert; -import org.assertj.core.api.Assertions; - -/** Test assertions for {@link PointData}. */ -public class AbstractPointDataAssert< - PointAssertT extends AbstractPointDataAssert, - PointT extends PointData> - extends AbstractAssert { - protected AbstractPointDataAssert(PointT actual, Class assertClass) { - super(actual, assertClass); - } - - /** Ensures the {@code start_epoch_nanos} field matches the expected value. */ - public PointAssertT hasStartEpochNanos(long expected) { - isNotNull(); - Assertions.assertThat(actual.getStartEpochNanos()).as("startEpochNanos").isEqualTo(expected); - return myself; - } - - /** Ensures the {@code epoch_nanos} field matches the expected value. */ - public PointAssertT hasEpochNanos(long expected) { - isNotNull(); - Assertions.assertThat(actual.getEpochNanos()).as("epochNanos").isEqualTo(expected); - return myself; - } - - /** Ensures the {@code attributes} field matches the expected value. */ - public PointAssertT hasAttributes(Attributes expected) { - isNotNull(); - Assertions.assertThat(actual.getAttributes()).as("attributes").isEqualTo(expected); - return myself; - } - - /** Returns convenience API to assert against the {@code attributes} field. */ - public AttributesAssert attributes() { - isNotNull(); - return OpenTelemetryAssertions.assertThat(actual.getAttributes()); - } - - /** Returns convenience API to assert against the {@code exemplars} field. */ - public AbstractIterableAssert, ExemplarData, ?> - exemplars() { - isNotNull(); - return Assertions.assertThat(actual.getExemplars()); - } - - /** - * Ensures the {@code exemplars} field matches the expected value. - * - * @param exemplars The list of exemplars that will be checked, can be in any order. - */ - public PointAssertT hasExemplars(ExemplarData... exemplars) { - isNotNull(); - // TODO(anuraaga): This code will be removed so use hacky approach to check ExemplarData. - Assertions.assertThat( - actual.getExemplars().stream().map(Object.class::cast).collect(Collectors.toList())) - .as("exemplars") - .containsExactlyInAnyOrderElementsOf(Arrays.asList(exemplars)); - return myself; - } -} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExemplarDataAssert.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExemplarDataAssert.java deleted file mode 100644 index 846d81aabca..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExemplarDataAssert.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; -import org.assertj.core.api.AbstractAssert; -import org.assertj.core.api.Assertions; - -/** Test assertions for {@link ExemplarData}. */ -public class ExemplarDataAssert extends AbstractAssert { - protected ExemplarDataAssert(ExemplarData actual) { - super(actual, ExemplarDataAssert.class); - } - - /** Ensures the {@code epochNanos} field matches the expected value. */ - public ExemplarDataAssert hasEpochNanos(long expected) { - isNotNull(); - Assertions.assertThat(actual.getEpochNanos()).as("epochNanos").isEqualTo(expected); - return this; - } - - /** Ensures the {@code spanId} field matches the expected value. */ - public ExemplarDataAssert hasSpanId(String expected) { - isNotNull(); - Assertions.assertThat(actual.getSpanContext().getSpanId()).as("spanId").isEqualTo(expected); - return this; - } - - /** Ensures the {@code traceId} field matches the expected value. */ - public ExemplarDataAssert hasTraceId(String expected) { - isNotNull(); - Assertions.assertThat(actual.getSpanContext().getTraceId()).as("traceId").isEqualTo(expected); - return this; - } - - /** Ensures the {@code value} field matches the expected value. */ - public ExemplarDataAssert hasValue(double expected) { - isNotNull(); - double value = - actual instanceof DoubleExemplarData - ? ((DoubleExemplarData) actual).getValue() - : ((LongExemplarData) actual).getValue(); - Assertions.assertThat(value).as("value").isEqualTo(expected); - return this; - } - - /** Ensures the {@code fitleredAttributes} field matches the expected value. */ - public ExemplarDataAssert hasFilteredAttributes(Attributes expected) { - isNotNull(); - Assertions.assertThat(actual.getFilteredAttributes()) - .as("filtered_attributes") - .isEqualTo(expected); - return this; - } - - /** Returns convenience API to assert against the {@code filteredAttributes} field. */ - public AttributesAssert filteredAttributes() { - isNotNull(); - return OpenTelemetryAssertions.assertThat(actual.getFilteredAttributes()); - } -} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramAssert.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramAssert.java deleted file mode 100644 index 268fc672bef..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramAssert.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramPointData; -import org.assertj.core.api.AbstractAssert; -import org.assertj.core.api.AbstractIterableAssert; -import org.assertj.core.api.Assertions; - -/** Test assertions for {@link ExponentialHistogramData}. */ -public class ExponentialHistogramAssert - extends AbstractAssert { - - protected ExponentialHistogramAssert(ExponentialHistogramData actual) { - super(actual, ExponentialHistogramAssert.class); - } - - /** Ensures that {@code aggregation_temporality} field is {@code CUMULATIVE}. */ - public ExponentialHistogramAssert isCumulative() { - isNotNull(); - if (actual.getAggregationTemporality() != AggregationTemporality.CUMULATIVE) { - failWithActualExpectedAndMessage( - actual, - "aggregationTemporality: CUMULATIVE", - "Expected Histogram to have cumulative aggregation but found <%s>", - actual.getAggregationTemporality()); - } - return this; - } - - /** Ensures that {@code aggregation_temporality} field is {@code DELTA}. */ - public ExponentialHistogramAssert isDelta() { - isNotNull(); - if (actual.getAggregationTemporality() != AggregationTemporality.DELTA) { - failWithActualExpectedAndMessage( - actual, - "aggregationTemporality: DELTA", - "Expected Histogram to have cumulative aggregation but found <%s>", - AggregationTemporality.DELTA, - actual.getAggregationTemporality()); - } - return this; - } - - /** Returns convenience API to assert against the {@code points} field. */ - public AbstractIterableAssert< - ?, - ? extends Iterable, - ExponentialHistogramPointData, - ?> - points() { - isNotNull(); - return Assertions.assertThat(actual.getPoints()); - } -} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramPointDataAssert.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramPointDataAssert.java deleted file mode 100644 index cd5680b5c5a..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramPointDataAssert.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramPointData; -import org.assertj.core.api.Assertions; - -/** Test assertions for {@link ExponentialHistogramPointData}. */ -public class ExponentialHistogramPointDataAssert - extends AbstractPointDataAssert< - ExponentialHistogramPointDataAssert, ExponentialHistogramPointData> { - protected ExponentialHistogramPointDataAssert(ExponentialHistogramPointData actual) { - super(actual, ExponentialHistogramPointDataAssert.class); - } - - /** Ensures the {@code sum} field matches the expected value. */ - public ExponentialHistogramPointDataAssert hasSum(double expected) { - isNotNull(); - Assertions.assertThat(actual.getSum()).as("sum").isEqualTo(expected); - return this; - } - - /** Ensures the {@code min} field matches the expected value. */ - public ExponentialHistogramPointDataAssert hasMin(double expected) { - isNotNull(); - Assertions.assertThat(actual.getMin()).as("min").isEqualTo(expected); - return this; - } - - /** Ensures the {@code min} field matches the expected value. */ - public ExponentialHistogramPointDataAssert hasMax(double expected) { - isNotNull(); - Assertions.assertThat(actual.getMax()).as("max").isEqualTo(expected); - return this; - } - - /** Ensures the {@code count} field matches the expected value. */ - public ExponentialHistogramPointDataAssert hasCount(long expected) { - isNotNull(); - Assertions.assertThat(actual.getCount()).as("count").isEqualTo(expected); - return this; - } - - /** Ensures the {@code scale} field matches the expected value. */ - public ExponentialHistogramPointDataAssert hasScale(int expected) { - isNotNull(); - Assertions.assertThat(actual.getScale()).as("scale").isEqualTo(expected); - return this; - } - - /** Ensures the {@code zeroCount} field matches the expected value. */ - public ExponentialHistogramPointDataAssert hasZeroCount(long expected) { - isNotNull(); - Assertions.assertThat(actual.getZeroCount()).as("zeroCount").isEqualTo(expected); - return this; - } -} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssertions.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssertions.java deleted file mode 100644 index b096f8ef640..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssertions.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramBuckets; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramPointData; -import org.assertj.core.api.Assertions; - -/** Test assertions for data heading to exporters within the Metrics SDK. */ -public final class MetricAssertions extends Assertions { - /** Returns an assertion for {@link MetricData}. */ - public static MetricDataAssert assertThat(MetricData metric) { - return new MetricDataAssert(metric); - } - - /** Returns an assertion for {@link ExponentialHistogramPointData}. */ - public static ExponentialHistogramPointDataAssert assertThat( - ExponentialHistogramPointData point) { - return new ExponentialHistogramPointDataAssert(point); - } - - /** Returns an assertion for {@link ExponentialHistogramBuckets}. */ - public static ExponentialHistogramBucketsAssert assertThat(ExponentialHistogramBuckets buckets) { - return new ExponentialHistogramBucketsAssert(buckets); - } - - public static ExemplarDataAssert assertThat(ExemplarData exemplar) { - return new ExemplarDataAssert(exemplar); - } - - private MetricAssertions() {} -} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricDataAssert.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricDataAssert.java deleted file mode 100644 index d4e57b4c5a9..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricDataAssert.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.MetricDataType; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import io.opentelemetry.sdk.resources.Resource; -import org.assertj.core.api.AbstractAssert; - -/** Test assertions for {@link MetricData}. */ -public class MetricDataAssert extends AbstractAssert { - protected MetricDataAssert(MetricData actual) { - super(actual, MetricDataAssert.class); - } - - /** Ensures the {@link Resource} associated with a metric matches the expected value. */ - public MetricDataAssert hasResource(Resource resource) { - isNotNull(); - if (!actual.getResource().equals(resource)) { - failWithActualExpectedAndMessage( - actual, - "resource: " + resource, - "Expected MetricData to have resource <%s> but found <%s>", - resource, - actual.getResource()); - } - return this; - } - - /** - * Ensures the {@link InstrumentationScopeInfo} associated with a metric matches the expected - * value. - */ - public MetricDataAssert hasInstrumentationScope( - InstrumentationScopeInfo instrumentationScopeInfo) { - isNotNull(); - if (!actual.getInstrumentationScopeInfo().equals(instrumentationScopeInfo)) { - failWithActualExpectedAndMessage( - actual, - "instrumentation scope: " + instrumentationScopeInfo, - "Expected MetricData to have resource <%s> but found <%s>", - instrumentationScopeInfo, - actual.getInstrumentationScopeInfo()); - } - return this; - } - - /** Ensures the {@code name} field matches the expected value. */ - public MetricDataAssert hasName(String name) { - isNotNull(); - if (!actual.getName().equals(name)) { - failWithActualExpectedAndMessage( - actual, - "name: " + name, - "Expected MetricData to have name <%s> but found <%s>", - name, - actual.getName()); - } - return this; - } - - /** Ensures the {@code description} field matches the expected value. */ - public MetricDataAssert hasDescription(String description) { - isNotNull(); - if (!actual.getDescription().equals(description)) { - failWithActualExpectedAndMessage( - actual, - "description: " + description, - "Expected MetricData to have description <%s> but found <%s>", - description, - actual.getDescription()); - } - return this; - } - - /** Ensures the {@code unit} field matches the expected value. */ - public MetricDataAssert hasUnit(String unit) { - isNotNull(); - if (!actual.getUnit().equals(unit)) { - failWithActualExpectedAndMessage( - actual, - "unit: " + unit, - "Expected MetricData to have unit <%s> but found <%s>", - unit, - actual.getUnit()); - } - return this; - } - - /** - * Ensures this {@link MetricData} is a {@code ExponentialHistogram}. - * - * @return convenience API to assert against the {@code ExponentialHistogram}. - */ - public ExponentialHistogramAssert hasExponentialHistogram() { - isNotNull(); - if (actual.getType() != MetricDataType.EXPONENTIAL_HISTOGRAM) { - failWithActualExpectedAndMessage( - actual, - "type: EXPONENTIAL_HISTOGRAM", - "Expected MetricData to have type <%s> but found <%s>", - MetricDataType.EXPONENTIAL_HISTOGRAM, - actual.getType()); - } - return new ExponentialHistogramAssert(ExponentialHistogramData.fromMetricData(actual)); - } -} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/package-info.java b/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/package-info.java deleted file mode 100644 index c2388a7b6f5..00000000000 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/package-info.java +++ /dev/null @@ -1,9 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.testing.assertj; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/metrics-testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java b/sdk/metrics-testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java deleted file mode 100644 index 2cf03935f71..00000000000 --- a/sdk/metrics-testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.testing.assertj; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static io.opentelemetry.sdk.testing.assertj.MetricAssertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import io.opentelemetry.sdk.resources.Resource; -import java.util.Collections; -import org.junit.jupiter.api.Test; - -public class MetricAssertionsTest { - private static final Resource RESOURCE = - Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); - private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("instrumentation_library"); - - private static final MetricData EXPONENTIAL_HISTOGRAM_METRIC = - ImmutableMetricData.createExponentialHistogram( - RESOURCE, - INSTRUMENTATION_SCOPE_INFO, - /* name= */ "exponential_histogram", - /* description= */ "description", - /* unit= */ "unit", - ExponentialHistogramData.create( - AggregationTemporality.CUMULATIVE, - // Points - Collections.emptyList())); - - private static final MetricData EXPONENTIAL_HISTOGRAM_DELTA_METRIC = - ImmutableMetricData.createExponentialHistogram( - RESOURCE, - INSTRUMENTATION_SCOPE_INFO, - /* name= */ "exponential_histogram_delta", - /* description= */ "description", - /* unit= */ "unit", - ExponentialHistogramData.create( - AggregationTemporality.DELTA, - // Points - Collections.emptyList())); - - private static final MetricData DOUBLE_GAUGE_METRIC = - ImmutableMetricData.createDoubleGauge( - RESOURCE, - INSTRUMENTATION_SCOPE_INFO, - /* name= */ "gauge", - /* description= */ "description", - /* unit= */ "unit", - ImmutableGaugeData.create( - // Points - Collections.emptyList())); - - @Test - void metric_passing() { - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("exponential_histogram") - .hasDescription("description") - .hasUnit("unit"); - } - - @Test - void metric_fails() { - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasResource( - Resource.create(Attributes.of(stringKey("monkey_key"), "resource_value")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_METRIC) - .hasInstrumentationScope( - InstrumentationScopeInfo.create("instrumentation_library_for_monkeys"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy(() -> assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasName("Monkeys")) - .isInstanceOf(AssertionError.class); - assertThatThrownBy(() -> assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasDescription("Monkeys")) - .isInstanceOf(AssertionError.class); - assertThatThrownBy(() -> assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasUnit("Monkeys")) - .isInstanceOf(AssertionError.class); - } - - @Test - void exponential_histogram_passing() { - assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasExponentialHistogram().isCumulative(); - assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC).hasExponentialHistogram().isDelta(); - } - - @Test - void exponential_histogram_fails() { - assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasExponentialHistogram()) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasExponentialHistogram().isDelta()) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC) - .hasExponentialHistogram() - .isCumulative()) - .isInstanceOf(AssertionError.class); - } -} diff --git a/sdk/metrics/README.md b/sdk/metrics/README.md deleted file mode 100644 index 1b18aaca21e..00000000000 --- a/sdk/metrics/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Metrics SDK - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-metrics.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-metrics diff --git a/sdk/metrics/build.gradle.kts b/sdk/metrics/build.gradle.kts index a9ef2556a76..e8cac16764a 100644 --- a/sdk/metrics/build.gradle.kts +++ b/sdk/metrics/build.gradle.kts @@ -1,5 +1,3 @@ -import ru.vyarus.gradle.plugin.animalsniffer.AnimalSniffer - plugins { id("otel.java-conventions") id("otel.publish-conventions") @@ -11,10 +9,13 @@ plugins { description = "OpenTelemetry SDK Metrics" otelJava.moduleName.set("io.opentelemetry.sdk.metrics") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) dependencies { api(project(":api:all")) api(project(":sdk:common")) + compileOnly(project(":api:incubator")) compileOnly("org.codehaus.mojo:animal-sniffer-annotations") @@ -22,9 +23,9 @@ dependencies { testAnnotationProcessor("com.google.auto.value:auto-value") - testImplementation(project(":sdk:metrics-testing")) testImplementation(project(":sdk:testing")) testImplementation("com.google.guava:guava") + testImplementation("com.google.guava:guava-testlib") jmh(project(":sdk:trace")) jmh(project(":sdk:testing")) @@ -32,7 +33,14 @@ dependencies { testing { suites { - val debugEnabledTest by registering(JvmTestSuite::class) { + register("testIncubating") { + dependencies { + implementation(project(":sdk:testing")) + implementation(project(":api:incubator")) + implementation("com.google.guava:guava") + } + } + register("debugEnabledTest") { targets { all { testTask.configure { @@ -41,16 +49,17 @@ testing { } } } + register("jmhBasedTest") { + dependencies { + implementation("org.openjdk.jmh:jmh-core") + implementation("org.openjdk.jmh:jmh-generator-bytecode") + annotationProcessor("org.openjdk.jmh:jmh-generator-annprocess") + } + } } } tasks { - named("animalsnifferMain") { - // We cannot use IgnoreJreRequirement since it does not work correctly for fields. - // https://github.com/mojohaus/animal-sniffer/issues/131 - exclude("**/concurrent/Jre*Adder*") - } - check { dependsOn(testing.suites) } diff --git a/sdk/metrics/histograms.png b/sdk/metrics/histograms.png deleted file mode 100644 index a8ca2de8615..00000000000 Binary files a/sdk/metrics/histograms.png and /dev/null differ diff --git a/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptorTest.java b/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptorTest.java index cbc1f288905..acb1ae789c3 100644 --- a/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptorTest.java +++ b/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptorTest.java @@ -22,33 +22,63 @@ class InstrumentDescriptorTest { void equals() { InstrumentDescriptor descriptor = InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.LONG); + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()); assertThat(descriptor) .isEqualTo( InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.LONG)); + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty())); // Validate getSourceInfo() is not equal for otherwise equal descriptors assertThat(descriptor.getSourceInfo()) .isNotEqualTo( InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.LONG) + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()) .getSourceInfo()); // Validate that name, description, unit, type, and value type are considered in equals assertThat(descriptor) .isNotEqualTo( InstrumentDescriptor.create( - "foo", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.LONG)); + "foo", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty())); assertThat(descriptor) .isNotEqualTo( InstrumentDescriptor.create( - "name", "foo", "unit", InstrumentType.COUNTER, InstrumentValueType.LONG)); + "name", + "foo", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty())); assertThat(descriptor) .isNotEqualTo( InstrumentDescriptor.create( - "name", "description", "foo", InstrumentType.COUNTER, InstrumentValueType.LONG)); + "name", + "description", + "foo", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty())); assertThat(descriptor) .isNotEqualTo( InstrumentDescriptor.create( @@ -56,10 +86,16 @@ void equals() { "description", "unit", InstrumentType.UP_DOWN_COUNTER, - InstrumentValueType.LONG)); + InstrumentValueType.LONG, + Advice.empty())); assertThat(descriptor) .isNotEqualTo( InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.DOUBLE)); + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty())); } } diff --git a/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/testing/SourceInfoTest.java b/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/testing/SourceInfoTest.java index bb6dc42123e..64efb419820 100644 --- a/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/testing/SourceInfoTest.java +++ b/sdk/metrics/src/debugEnabledTest/java/io/opentelemetry/testing/SourceInfoTest.java @@ -11,6 +11,7 @@ import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; import io.opentelemetry.sdk.metrics.internal.state.DebugUtils; @@ -23,10 +24,10 @@ class SourceInfoTest { @Test void sourceInfoFindsStackTrace() { - assertThat(info.shortDebugString()).isEqualTo("SourceInfoTest.java:22"); + assertThat(info.shortDebugString()).isEqualTo("SourceInfoTest.java:23"); assertThat(info.multiLineDebugString()) .startsWith( - "\tat io.opentelemetry.testing.SourceInfoTest.(SourceInfoTest.java:22)\n"); + "\tat io.opentelemetry.testing.SourceInfoTest.(SourceInfoTest.java:23)\n"); } @Test @@ -40,7 +41,8 @@ void testDuplicateExceptionMessage_pureInstruments() { "description", "unit", InstrumentType.OBSERVABLE_COUNTER, - InstrumentValueType.DOUBLE)); + InstrumentValueType.DOUBLE, + Advice.empty())); MetricDescriptor simpleWithNewDescription = MetricDescriptor.create( View.builder().build(), @@ -50,7 +52,8 @@ void testDuplicateExceptionMessage_pureInstruments() { "description2", "unit2", InstrumentType.COUNTER, - InstrumentValueType.LONG)); + InstrumentValueType.LONG, + Advice.empty())); assertThat(DebugUtils.duplicateMetricErrorMessage(simple, simpleWithNewDescription)) .contains("Found duplicate metric definition: name") .contains("- InstrumentDescription [description2] does not match [description]") @@ -76,7 +79,8 @@ void testDuplicateExceptionMessage_viewBasedConflict() { "description", "unit", InstrumentType.HISTOGRAM, - InstrumentValueType.DOUBLE)); + InstrumentValueType.DOUBLE, + Advice.empty())); MetricDescriptor simpleWithNewDescription = MetricDescriptor.create( View.builder().build(), @@ -86,7 +90,8 @@ void testDuplicateExceptionMessage_viewBasedConflict() { "description2", "unit", InstrumentType.HISTOGRAM, - InstrumentValueType.DOUBLE)); + InstrumentValueType.DOUBLE, + Advice.empty())); assertThat(DebugUtils.duplicateMetricErrorMessage(simple, simpleWithNewDescription)) .contains("Found duplicate metric definition: name2") .contains(simple.getSourceInstrument().getSourceInfo().multiLineDebugString()) @@ -111,7 +116,8 @@ void testDuplicateExceptionMessage_viewBasedConflict2() { "description", "unit2", InstrumentType.HISTOGRAM, - InstrumentValueType.DOUBLE)); + InstrumentValueType.DOUBLE, + Advice.empty())); MetricDescriptor simpleWithNewDescription = MetricDescriptor.create( problemView, @@ -121,7 +127,8 @@ void testDuplicateExceptionMessage_viewBasedConflict2() { "description", "unit", InstrumentType.HISTOGRAM, - InstrumentValueType.DOUBLE)); + InstrumentValueType.DOUBLE, + Advice.empty())); assertThat(DebugUtils.duplicateMetricErrorMessage(simple, simpleWithNewDescription)) .contains("Found duplicate metric definition: name") .contains("VIEW defined") diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/ExemplarClockBenchmarks.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/ExemplarClockBenchmarks.java new file mode 100644 index 00000000000..28d0c855134 --- /dev/null +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/ExemplarClockBenchmarks.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.sdk.common.Clock; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Warmup; + +/** + * {@code io.opentelemetry.sdk.metrics.internal.exemplar.ReservoirCell} relies on {@link Clock} to + * obtain the measurement time when storing exemplar values. This benchmark illustrates the + * performance impact of using the higher precision {@link Clock#now()} instead of {@link + * Clock#now(boolean)} with {@code highPrecision=false}. + */ +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 10, time = 1) +@Fork(1) +public class ExemplarClockBenchmarks { + + private static final Clock clock = Clock.getDefault(); + + @SuppressWarnings("ReturnValueIgnored") + @Benchmark + public void now_lowPrecision() { + clock.now(false); + } + + @SuppressWarnings("ReturnValueIgnored") + @Benchmark + public void now_highPrecision() { + clock.now(true); + } +} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricAdviceBenchmark.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricAdviceBenchmark.java new file mode 100644 index 00000000000..674e076705b --- /dev/null +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricAdviceBenchmark.java @@ -0,0 +1,273 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounterBuilder; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +@BenchmarkMode({Mode.AverageTime}) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 10, time = 1) +@Fork(1) +public class MetricAdviceBenchmark { + + static final AttributeKey HTTP_REQUEST_METHOD = + AttributeKey.stringKey("http.request.method"); + static final AttributeKey URL_PATH = AttributeKey.stringKey("url.path"); + static final AttributeKey URL_SCHEME = AttributeKey.stringKey("url.scheme"); + static final AttributeKey HTTP_RESPONSE_STATUS_CODE = + AttributeKey.longKey("http.response.status_code"); + static final AttributeKey HTTP_ROUTE = AttributeKey.stringKey("http.route"); + static final AttributeKey NETWORK_PROTOCOL_NAME = + AttributeKey.stringKey("network.protocol.name"); + static final AttributeKey SERVER_PORT = AttributeKey.longKey("server.port"); + static final AttributeKey URL_QUERY = AttributeKey.stringKey("url.query"); + static final AttributeKey CLIENT_ADDRESS = AttributeKey.stringKey("client.address"); + static final AttributeKey NETWORK_PEER_ADDRESS = + AttributeKey.stringKey("network.peer.address"); + static final AttributeKey NETWORK_PEER_PORT = AttributeKey.longKey("network.peer.port"); + static final AttributeKey NETWORK_PROTOCOL_VERSION = + AttributeKey.stringKey("network.protocol.version"); + static final AttributeKey SERVER_ADDRESS = AttributeKey.stringKey("server.address"); + static final AttributeKey USER_AGENT_ORIGINAL = + AttributeKey.stringKey("user_agent.original"); + + static final List> httpServerMetricAttributeKeys = + Arrays.asList( + HTTP_REQUEST_METHOD, + URL_SCHEME, + HTTP_RESPONSE_STATUS_CODE, + HTTP_ROUTE, + NETWORK_PROTOCOL_NAME, + SERVER_PORT, + NETWORK_PROTOCOL_VERSION, + SERVER_ADDRESS); + + static Attributes httpServerMetricAttributes() { + return Attributes.builder() + .put(HTTP_REQUEST_METHOD, "GET") + .put(URL_SCHEME, "http") + .put(HTTP_RESPONSE_STATUS_CODE, 200) + .put(HTTP_ROUTE, "/v1/users/{id}") + .put(NETWORK_PROTOCOL_NAME, "http") + .put(SERVER_PORT, 8080) + .put(NETWORK_PROTOCOL_VERSION, "1.1") + .put(SERVER_ADDRESS, "localhost") + .build(); + } + + static Attributes httpServerSpanAttributes() { + return Attributes.builder() + .put(HTTP_REQUEST_METHOD, "GET") + .put(URL_PATH, "/v1/users/123") + .put(URL_SCHEME, "http") + .put(HTTP_RESPONSE_STATUS_CODE, 200) + .put(HTTP_ROUTE, "/v1/users/{id}") + .put(NETWORK_PROTOCOL_NAME, "http") + .put(SERVER_PORT, 8080) + .put(URL_QUERY, "with=email") + .put(CLIENT_ADDRESS, "192.168.0.17") + .put(NETWORK_PEER_ADDRESS, "192.168.0.17") + .put(NETWORK_PEER_PORT, 11265) + .put(NETWORK_PROTOCOL_VERSION, "1.1") + .put(SERVER_ADDRESS, "localhost") + .put(USER_AGENT_ORIGINAL, "okhttp/1.27.2") + .build(); + } + + static final Attributes CACHED_HTTP_SERVER_SPAN_ATTRIBUTES = httpServerSpanAttributes(); + + @State(Scope.Benchmark) + public static class ThreadState { + + @Param InstrumentParam instrumentParam; + + SdkMeterProvider meterProvider; + + @Setup(Level.Iteration) + public void setup() { + meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(InMemoryMetricReader.createDelta()) + .build(); + Meter meter = meterProvider.get("meter"); + instrumentParam.instrument().setup(meter); + } + + @TearDown + public void tearDown() { + meterProvider.shutdown().join(10, TimeUnit.SECONDS); + } + } + + @Benchmark + @Threads(1) + public void record(ThreadState threadState) { + threadState.instrumentParam.instrument().record(1); + } + + @SuppressWarnings("ImmutableEnumChecker") + public enum InstrumentParam { + /** + * Record HTTP span attributes without advice. This baseline shows the CPU and memory allocation + * independent of advice. + */ + NO_ADVICE_ALL_ATTRIBUTES( + new Instrument() { + private LongCounter counter; + + @Override + void setup(Meter meter) { + counter = ((ExtendedLongCounterBuilder) meter.counterBuilder("counter")).build(); + } + + @Override + void record(long value) { + counter.add(value, httpServerSpanAttributes()); + } + }), + /** + * Record HTTP metric attributes without advice. This baseline shows the lower bound if + * attribute filtering was done in instrumentation instead of the metrics SDK with advice. It's + * not quite fair though because instrumentation would have to separately allocate attributes + * for spans and metrics, whereas with advice, we can manage to only allocate span attributes + * and a lightweight metrics attributes view derived from span attributes. + */ + NO_ADVICE_FILTERED_ATTRIBUTES( + new Instrument() { + private LongCounter counter; + + @Override + void setup(Meter meter) { + counter = ((ExtendedLongCounterBuilder) meter.counterBuilder("counter")).build(); + } + + @Override + void record(long value) { + counter.add(value, httpServerMetricAttributes()); + } + }), + /** + * Record cached HTTP span attributes without advice. This baseline helps isolate the CPU and + * memory allocation for recording vs. creating attributes. + */ + NO_ADVICE_ALL_ATTRIBUTES_CACHED( + new Instrument() { + private LongCounter counter; + + @Override + void setup(Meter meter) { + counter = ((ExtendedLongCounterBuilder) meter.counterBuilder("counter")).build(); + } + + @Override + void record(long value) { + counter.add(value, CACHED_HTTP_SERVER_SPAN_ATTRIBUTES); + } + }), + /** + * Record HTTP span attributes with advice filtering to HTTP metric attributes. This is meant to + * realistically demonstrate a typical HTTP server instrumentation scenario. + */ + ADVICE_ALL_ATTRIBUTES( + new Instrument() { + private LongCounter counter; + + @Override + void setup(Meter meter) { + counter = + ((ExtendedLongCounterBuilder) meter.counterBuilder("counter")) + .setAttributesAdvice(httpServerMetricAttributeKeys) + .build(); + } + + @Override + void record(long value) { + counter.add(value, httpServerSpanAttributes()); + } + }), + /** + * Record HTTP metric attributes with advice filtering to HTTP metric attributes. This + * demonstrates the overhead of advice when no attributes are filtered. + */ + ADVICE_FILTERED_ATTRIBUTES( + new Instrument() { + private LongCounter counter; + + @Override + void setup(Meter meter) { + counter = + ((ExtendedLongCounterBuilder) meter.counterBuilder("counter")) + .setAttributesAdvice(httpServerMetricAttributeKeys) + .build(); + } + + @Override + void record(long value) { + counter.add(value, httpServerMetricAttributes()); + } + }), + /** + * Record cached HTTP span attributes with advice filtering to HTTP metric attributes. This + * isolates the CPU and memory allocation for applying advice vs. creating attributes. + */ + ADVICE_ALL_ATTRIBUTES_CACHED( + new Instrument() { + private LongCounter counter; + + @Override + void setup(Meter meter) { + counter = + ((ExtendedLongCounterBuilder) meter.counterBuilder("counter")) + .setAttributesAdvice(httpServerMetricAttributeKeys) + .build(); + } + + @Override + void record(long value) { + counter.add(value, CACHED_HTTP_SERVER_SPAN_ATTRIBUTES); + } + }); + + private final Instrument instrument; + + InstrumentParam(Instrument instrument) { + this.instrument = instrument; + } + + private Instrument instrument() { + return instrument; + } + } + + private abstract static class Instrument { + abstract void setup(Meter meter); + + abstract void record(long value); + } +} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricsBenchmarks.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricsBenchmarks.java deleted file mode 100644 index aaf11a16be5..00000000000 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricsBenchmarks.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.Tracer; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Param; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.TearDown; -import org.openjdk.jmh.annotations.Threads; -import org.openjdk.jmh.annotations.Warmup; -import org.openjdk.jmh.infra.ThreadParams; - -@BenchmarkMode({Mode.AverageTime}) -@OutputTimeUnit(TimeUnit.NANOSECONDS) -@Warmup(iterations = 5, time = 1) -@Measurement(iterations = 10, time = 1) -@Fork(1) -public class MetricsBenchmarks { - - @State(Scope.Thread) - public static class ThreadState { - - @Param TestSdk sdk; - - @Param MetricsTestOperationBuilder opBuilder; - - MetricsTestOperationBuilder.Operation op; - Span span; - io.opentelemetry.context.Scope contextScope; - final Attributes sharedLabelSet = Attributes.builder().put("KEY", "VALUE").build(); - Attributes threadUniqueLabelSet; - - @Setup - @SuppressWarnings("MustBeClosedChecker") - public void setup(ThreadParams threadParams) { - Meter meter = sdk.getMeter(); - Tracer tracer = sdk.getTracer(); - span = tracer.spanBuilder("benchmark").startSpan(); - // We suppress warnings on closing here, as we rely on tests to make sure context is closed. - contextScope = span.makeCurrent(); - op = opBuilder.build(meter); - threadUniqueLabelSet = - Attributes.builder().put("KEY", String.valueOf(threadParams.getThreadIndex())).build(); - } - - @TearDown - public void tearDown(ThreadParams threadParams) { - contextScope.close(); - span.end(); - } - } - - @Benchmark - @Threads(1) - public void oneThread(ThreadState threadState) { - threadState.op.perform(threadState.sharedLabelSet); - } - - @Benchmark - @Threads(8) - public void eightThreadsCommonLabelSet(ThreadState threadState) { - threadState.op.perform(threadState.sharedLabelSet); - } - - @Benchmark - @Threads(8) - public void eightThreadsSeparateLabelSets(ThreadState threadState) { - threadState.op.perform(threadState.threadUniqueLabelSet); - } -} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricsTestOperationBuilder.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricsTestOperationBuilder.java deleted file mode 100644 index a810048290b..00000000000 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/MetricsTestOperationBuilder.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.DoubleCounter; -import io.opentelemetry.api.metrics.DoubleHistogram; -import io.opentelemetry.api.metrics.LongCounter; -import io.opentelemetry.api.metrics.LongHistogram; -import io.opentelemetry.api.metrics.Meter; -import java.util.concurrent.ThreadLocalRandom; - -/** - * This enum allows for iteration over all of the operations that we want to benchmark. To ensure - * that the enum cannot change state, each enum holds a builder function- passing a meter in will - * return a wrapper for both bound and unbound versions of that operation which can then be used in - * a benchmark. - */ -@SuppressWarnings("ImmutableEnumChecker") -public enum MetricsTestOperationBuilder { - LongCounterAdd( - meter -> { - return new Operation() { - final LongCounter metric = meter.counterBuilder("long_counter").build(); - - @Override - public void perform(Attributes labels) { - metric.add(5L, labels); - } - }; - }), - DoubleCounterAdd( - meter -> { - return new Operation() { - final DoubleCounter metric = meter.counterBuilder("double_counter").ofDoubles().build(); - - @Override - public void perform(Attributes labels) { - metric.add(5.0d, labels); - } - }; - }), - DoubleHistogramRecord( - meter -> { - return new Operation() { - final DoubleHistogram metric = - meter.histogramBuilder("double_histogram_recorder").build(); - - @Override - public void perform(Attributes labels) { - // We record different values to try to hit more areas of the histogram buckets. - metric.record(ThreadLocalRandom.current().nextDouble(0, 20_000d), labels); - } - }; - }), - LongHistogramRecord( - meter -> { - return new Operation() { - final LongHistogram metric = - meter.histogramBuilder("long_value_recorder").ofLongs().build(); - - @Override - public void perform(Attributes labels) { - metric.record(ThreadLocalRandom.current().nextLong(0, 20_000L), labels); - } - }; - }); - - private final OperationBuilder builder; - - MetricsTestOperationBuilder(OperationBuilder builder) { - this.builder = builder; - } - - public Operation build(Meter meter) { - return this.builder.build(meter); - } - - private interface OperationBuilder { - Operation build(Meter meter); - } - - interface Operation { - void perform(Attributes labels); - } -} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/TestSdk.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/TestSdk.java deleted file mode 100644 index 6100fd61fba..00000000000 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/TestSdk.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.MeterProvider; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import io.opentelemetry.sdk.trace.SdkTracerProvider; -import io.opentelemetry.sdk.trace.samplers.Sampler; - -@SuppressWarnings("ImmutableEnumChecker") -public enum TestSdk { - API_ONLY( - new SdkBuilder() { - @Override - Meter build() { - return MeterProvider.noop().get("io.opentelemetry.sdk.metrics"); - } - }), - SDK_NO_EXEMPLARS( - new SdkBuilder() { - @Override - Meter build() { - return SdkMeterProvider.builder() - .setClock(Clock.getDefault()) - .setResource(Resource.empty()) - // Must register reader for real SDK. - .registerMetricReader(InMemoryMetricReader.create()) - .setExemplarFilter(ExemplarFilter.neverSample()) - .build() - .get("io.opentelemetry.sdk.metrics"); - } - }), - SDK( - new SdkBuilder() { - @Override - Meter build() { - return SdkMeterProvider.builder() - .setClock(Clock.getDefault()) - .setResource(Resource.empty()) - // Must register reader for real SDK. - .registerMetricReader(InMemoryMetricReader.create()) - .build() - .get("io.opentelemetry.sdk.metrics"); - } - }); - - private final SdkBuilder sdkBuilder; - - TestSdk(SdkBuilder sdkBuilder) { - this.sdkBuilder = sdkBuilder; - } - - public Meter getMeter() { - return sdkBuilder.build(); - } - - public Tracer getTracer() { - return SdkBuilder.buildTracer(); - } - - private abstract static class SdkBuilder { - abstract Meter build(); - - protected static Tracer buildTracer() { - return SdkTracerProvider.builder() - .setSampler(Sampler.alwaysOn()) - .build() - .get("io.opentelemetry.sdk.metrics"); - } - } -} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialHistogramIndexerBenchmark.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialHistogramIndexerBenchmark.java new file mode 100644 index 00000000000..304087f734f --- /dev/null +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialHistogramIndexerBenchmark.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import java.util.Random; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Level; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Warmup; + +/** + * Measures runtime cost of computing bucket indexes for exponential histograms. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Measurement(iterations = 5, time = 1) +@Warmup(iterations = 5, time = 1) +@Fork(1) +public class ExponentialHistogramIndexerBenchmark { + + @State(Scope.Thread) + public static class ThreadState { + @Param(value = {"1", "0", "-1"}) + int scale; + + private double[] values; + private final AtomicLong valueIndex = new AtomicLong(); + private Base2ExponentialHistogramIndexer indexer; + + @Setup(Level.Trial) + public final void setup() { + Random random = new Random(); + int numValues = 2000; + values = new double[numValues]; + for (int i = 0; i < numValues; i++) { + values[i] = random.nextDouble() * 1000; + } + indexer = Base2ExponentialHistogramIndexer.get(scale); + } + + public void compute() { + // Compute a number of samples + for (int i = 0; i < 2000; i++) { + indexer.computeIndex(values[(int) (valueIndex.incrementAndGet() % values.length)]); + } + } + } + + @Benchmark + public void computeIndex(ThreadState threadState) { + threadState.compute(); + } +} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramAggregationParam.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramAggregationParam.java index ef6db6fd988..30c78a0500e 100644 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramAggregationParam.java +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramAggregationParam.java @@ -5,8 +5,9 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounterFactory; +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; + +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import java.util.Collections; /** The types of histogram aggregation to benchmark. */ @@ -16,33 +17,29 @@ public enum HistogramAggregationParam { new DoubleExplicitBucketHistogramAggregator( ExplicitBucketHistogramUtils.createBoundaryArray( ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES), - ExemplarReservoir::doubleNoSamples)), + /* recordMinMax= */ true, + ExemplarReservoirFactory.noSamples(), + IMMUTABLE_DATA)), EXPLICIT_SINGLE_BUCKET( new DoubleExplicitBucketHistogramAggregator( ExplicitBucketHistogramUtils.createBoundaryArray(Collections.emptyList()), - ExemplarReservoir::doubleNoSamples)), + /* recordMinMax= */ true, + ExemplarReservoirFactory.noSamples(), + IMMUTABLE_DATA)), EXPONENTIAL_SMALL_CIRCULAR_BUFFER( - new DoubleExponentialHistogramAggregator( - ExemplarReservoir::doubleNoSamples, - ExponentialBucketStrategy.newStrategy( - 20, 20, ExponentialCounterFactory.circularBufferCounter()))), + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.noSamples(), 20, 0, /* recordMinMax= */ true, IMMUTABLE_DATA)), EXPONENTIAL_CIRCULAR_BUFFER( - new DoubleExponentialHistogramAggregator( - ExemplarReservoir::doubleNoSamples, - ExponentialBucketStrategy.newStrategy( - 20, 320, ExponentialCounterFactory.circularBufferCounter()))), - EXPONENTIAL_MAP_COUNTER( - new DoubleExponentialHistogramAggregator( - ExemplarReservoir::doubleNoSamples, - ExponentialBucketStrategy.newStrategy(20, 320, ExponentialCounterFactory.mapCounter()))); + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.noSamples(), 160, 0, /* recordMinMax= */ true, IMMUTABLE_DATA)); - private final Aggregator aggregator; + private final Aggregator aggregator; - private HistogramAggregationParam(Aggregator aggregator) { + HistogramAggregationParam(Aggregator aggregator) { this.aggregator = aggregator; } - public Aggregator getAggregator() { + public Aggregator getAggregator() { return this.aggregator; } } diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramBenchmark.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramBenchmark.java index a86bf733259..34e57de3032 100644 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramBenchmark.java +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramBenchmark.java @@ -5,6 +5,9 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; import java.util.concurrent.TimeUnit; import java.util.function.DoubleSupplier; import org.openjdk.jmh.annotations.Benchmark; @@ -33,19 +36,20 @@ public class HistogramBenchmark { public static class ThreadState { @Param HistogramValueGenerator valueGen; @Param HistogramAggregationParam aggregation; - private AggregatorHandle aggregatorHandle; + private AggregatorHandle aggregatorHandle; private DoubleSupplier valueSupplier; @Setup(Level.Trial) public final void setup() { - aggregatorHandle = aggregation.getAggregator().createHandle(); + aggregatorHandle = aggregation.getAggregator().createHandle(Clock.getDefault().now()); valueSupplier = valueGen.supplier(); } public void record() { // Record a number of samples. for (int i = 0; i < 2000; i++) { - this.aggregatorHandle.recordDouble(valueSupplier.getAsDouble()); + this.aggregatorHandle.recordDouble( + valueSupplier.getAsDouble(), Attributes.empty(), Context.current()); } } } diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramCollectBenchmark.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramCollectBenchmark.java new file mode 100644 index 00000000000..0b44e1a6e92 --- /dev/null +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramCollectBenchmark.java @@ -0,0 +1,162 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions; +import io.opentelemetry.sdk.metrics.ExemplarFilter; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +/** + * Measures the collection path for various histogram aggregations. Should be used primarily to + * compare memory allocation rates. + */ +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Measurement(iterations = 5, batchSize = 100) +@Warmup(iterations = 2, batchSize = 10) +@Fork(1) +public class HistogramCollectBenchmark { + + private static final int cardinality = 100; + private static final int measurementsPerSeries = 10_000; + + @State(Scope.Benchmark) + public static class ThreadState { + @Param private AggregationTemporality aggregationTemporality; + @Param private AggregationGenerator aggregationGenerator; + + private SdkMeterProvider sdkMeterProvider; + private DoubleHistogram histogram; + private Random random; + private List attributesList; + + @Setup + public void setup() { + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .registerMetricReader( + PeriodicMetricReader.builder( + // Configure an exporter that configures the temporality and aggregation + // for the test case, but otherwise drops the data on export + new NoopMetricExporter( + aggregationTemporality, aggregationGenerator.aggregation)) + // Effectively disable periodic reading so reading is only done on #flush() + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .build()) + // Disable exemplars + .setExemplarFilter(ExemplarFilter.alwaysOff()) + .build(); + + histogram = sdkMeterProvider.get("meter").histogramBuilder("histogram").build(); + + random = new Random(); + attributesList = new ArrayList<>(cardinality); + String last = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; + for (int i = 0; i < cardinality; i++) { + char[] chars = last.toCharArray(); + chars[random.nextInt(last.length())] = (char) (random.nextInt(26) + 'a'); + last = new String(chars); + attributesList.add(Attributes.builder().put("key", last).build()); + } + } + + @TearDown + public void tearDown() { + sdkMeterProvider.shutdown().join(10, TimeUnit.SECONDS); + } + } + + @Benchmark + @Threads(value = 1) + public void recordAndCollect(ThreadState threadState) { + for (Attributes attributes : threadState.attributesList) { + for (int i = 0; i < measurementsPerSeries; i++) { + int value = threadState.random.nextInt(10_000); + threadState.histogram.record(value, attributes); + } + } + threadState.sdkMeterProvider.forceFlush().join(10, TimeUnit.SECONDS); + } + + @SuppressWarnings("ImmutableEnumChecker") + public enum AggregationGenerator { + EXPLICIT_BUCKET_HISTOGRAM(Aggregation.explicitBucketHistogram()), + DEFAULT_BASE2_EXPONENTIAL_BUCKET_HISTOGRAM(Aggregation.base2ExponentialBucketHistogram()), + ZERO_MAX_SCALE_BASE2_EXPONENTIAL_BUCKET_HISTOGRAM( + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder().setMaxBuckets(160).setMaxScale(0).build())); + + private final Aggregation aggregation; + + AggregationGenerator(Aggregation aggregation) { + this.aggregation = aggregation; + } + } + + private static class NoopMetricExporter implements MetricExporter { + private final AggregationTemporality aggregationTemporality; + private final Aggregation aggregation; + + private NoopMetricExporter( + AggregationTemporality aggregationTemporality, Aggregation aggregation) { + this.aggregationTemporality = aggregationTemporality; + this.aggregation = aggregation; + } + + @Override + public CompletableResultCode export(Collection metrics) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return aggregation; + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return aggregationTemporality; + } + } +} diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramScaleBenchmark.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramScaleBenchmark.java index e52ca6e88f5..3f22ccca84b 100644 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramScaleBenchmark.java +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramScaleBenchmark.java @@ -5,6 +5,9 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; import java.util.concurrent.TimeUnit; import java.util.function.DoubleSupplier; import org.openjdk.jmh.annotations.Benchmark; @@ -26,7 +29,8 @@ * *

      This benchmark must be interpreted carefully. We're looking for startup costs of histograms * and need to tease out the portion of recorded time from scaling buckets vs. general algorithmic - * performance. + * performance. The difference, compared with HistogramBenchmark, is that setup is called before + * each invocation. */ @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.NANOSECONDS) @@ -38,26 +42,27 @@ public class HistogramScaleBenchmark { public static class ThreadState { @Param HistogramValueGenerator valueGen; @Param HistogramAggregationParam aggregation; - private AggregatorHandle aggregatorHandle; + private AggregatorHandle aggregatorHandle; private DoubleSupplier valueSupplier; @Setup(Level.Invocation) public final void setup() { - aggregatorHandle = aggregation.getAggregator().createHandle(); + aggregatorHandle = aggregation.getAggregator().createHandle(Clock.getDefault().now()); valueSupplier = valueGen.supplier(); } public void record() { // Record a number of samples. for (int i = 0; i < 20000; i++) { - this.aggregatorHandle.recordDouble(valueSupplier.getAsDouble()); + this.aggregatorHandle.recordDouble( + valueSupplier.getAsDouble(), Attributes.empty(), Context.current()); } } } @Benchmark @Threads(value = 1) - public void scaleUp(HistogramBenchmark.ThreadState threadState) { + public void scaleUp(ThreadState threadState) { threadState.record(); } } diff --git a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramValueGenerator.java b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramValueGenerator.java index cbe48550dc6..ab3f972e361 100644 --- a/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramValueGenerator.java +++ b/sdk/metrics/src/jmh/java/io/opentelemetry/sdk/metrics/internal/aggregator/HistogramValueGenerator.java @@ -35,7 +35,7 @@ public enum HistogramValueGenerator { private static final int INITIAL_SEED = 513423236; private final double[] pool; - private HistogramValueGenerator(double[] pool) { + HistogramValueGenerator(double[] pool) { this.pool = pool; } @@ -49,7 +49,7 @@ private static class PoolSupplier implements DoubleSupplier { private final double[] pool; private final AtomicInteger idx = new AtomicInteger(0); - public PoolSupplier(double[] pool) { + private PoolSupplier(double[] pool) { this.pool = pool; } @@ -58,13 +58,12 @@ public double getAsDouble() { return pool[idx.incrementAndGet() % pool.length]; } } + /** Constructs a pool using explicit bucket histogram boundaries. */ private static double[] explicitDefaultBucketPool() { - List fixedBoundaries = new ArrayList(); - // Add minimal recording value. - fixedBoundaries.add(0.0); - // Add the bucket LE bucket boundaries (starts at 5). - fixedBoundaries.addAll(ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES); + // Add the bucket LE bucket boundaries. + List fixedBoundaries = + new ArrayList<>(ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES); // Add Double max value as our other extreme. fixedBoundaries.add(Double.MAX_VALUE); return ExplicitBucketHistogramUtils.createBoundaryArray(fixedBoundaries); diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/AttributesGenerator.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/AttributesGenerator.java new file mode 100644 index 00000000000..3aea1dbd6d6 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/AttributesGenerator.java @@ -0,0 +1,45 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import io.opentelemetry.api.common.Attributes; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Random; + +public class AttributesGenerator { + + private AttributesGenerator() {} + + /** + * Generates a list of unique attributes, with a single attribute key, and random value. + * + * @param uniqueAttributesCount The amount of unique attribute sets to generate + * @return The list of generates {@link Attributes} + */ + public static List generate(int uniqueAttributesCount) { + Random random = new Random(); + HashSet attributeSet = new HashSet<>(); + ArrayList attributesList = new ArrayList<>(uniqueAttributesCount); + String last = "aaaaaaaaaaaaaaaaaaaaaaaaaa"; + for (int i = 0; i < uniqueAttributesCount; i++) { + char[] chars = last.toCharArray(); + int attempts = 0; + do { + chars[random.nextInt(last.length())] = (char) (random.nextInt(26) + 'a'); + } while (attributeSet.contains(new String(chars)) && ++attempts < 1000); + if (attributeSet.contains(new String(chars))) { + throw new IllegalStateException("Couldn't create new random attributes"); + } + last = new String(chars); + attributesList.add(Attributes.builder().put("key", last).build()); + attributeSet.add(last); + } + + return attributesList; + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmark.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmark.java new file mode 100644 index 00000000000..3d3f9174d44 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmark.java @@ -0,0 +1,124 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.ExemplarFilter; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType.InstrumentTester; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType.TestInstrumentsState; +import java.time.Duration; +import java.util.List; +import java.util.Random; +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Param; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.Setup; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.TearDown; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +/** + * Run this through {@link InstrumentGarbageCollectionBenchmarkTest}, as it runs it embedded with + * the GC profiler which what this test designed for (No need for command line run). + * + *

      This test creates 10 asynchronous counters (any asynchronous instrument will do as the code + * path is almost the same for all async instrument types), and 1000 attribute sets. Each time the + * test runs, it calls `flush` which effectively calls the callback for each counter. Each such + * callback records a random number for each of the 1000 attribute sets. The result list ends up in + * {@link NoopMetricExporter} which does nothing with it. + * + *

      This is repeated 100 times, collectively called Operation in the statistics and each such + * operation is repeated 20 times - known as Iteration. + * + *

      Each such test is repeated, with a brand new JVM, for all combinations of {@link MemoryMode} + * and {@link AggregationTemporality}. This is done since each combination has a different code + * path. + */ +@BenchmarkMode(Mode.SingleShotTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Measurement(iterations = 10, batchSize = 10) +@Warmup(iterations = 10, batchSize = 10) +@Fork(1) +public class InstrumentGarbageCollectionBenchmark { + + @State(value = Scope.Benchmark) + public static class ThreadState { + private final int cardinality; + private final int instrumentCount; + @Param public TestInstrumentType testInstrumentType; + @Param public AggregationTemporality aggregationTemporality; + @Param public MemoryMode memoryMode; + SdkMeterProvider sdkMeterProvider; + private final Random random = new Random(); + List attributesList; + private TestInstrumentsState testInstrumentsState; + private InstrumentTester instrumentTester; + + /** Creates a ThreadState. */ + @SuppressWarnings("unused") + public ThreadState() { + cardinality = 1000; + instrumentCount = 10; + } + + @SuppressWarnings("SpellCheckingInspection") + @Setup + public void setup() { + instrumentTester = testInstrumentType.createInstrumentTester(); + PeriodicMetricReader metricReader = + PeriodicMetricReader.builder( + // Configure an exporter that configures the temporality and aggregation + // for the test case, but otherwise drops the data on export + new NoopMetricExporter( + aggregationTemporality, instrumentTester.testedAggregation(), memoryMode)) + // Effectively disable periodic reading so reading is only done on #flush() + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .build(); + SdkMeterProviderBuilder builder = + SdkMeterProvider.builder().registerMetricReader(metricReader, unused -> cardinality + 1); + + attributesList = AttributesGenerator.generate(cardinality); + + // Disable exemplars + builder.setExemplarFilter(ExemplarFilter.alwaysOff()); + + sdkMeterProvider = builder.build(); + testInstrumentsState = + instrumentTester.buildInstruments( + instrumentCount, sdkMeterProvider, attributesList, random); + } + + @TearDown + public void tearDown() { + sdkMeterProvider.shutdown().join(10, TimeUnit.SECONDS); + } + } + + /** + * Collects all asynchronous instruments metric data. + * + * @param threadState thread-state + */ + @Benchmark + @Threads(value = 1) + public void recordAndCollect(ThreadState threadState) { + threadState.instrumentTester.recordValuesInInstruments( + threadState.testInstrumentsState, threadState.attributesList, threadState.random); + threadState.sdkMeterProvider.forceFlush().join(10, TimeUnit.SECONDS); + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java new file mode 100644 index 00000000000..dda107b41ae --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/InstrumentGarbageCollectionBenchmarkTest.java @@ -0,0 +1,132 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import org.assertj.core.data.Offset; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Test; +import org.openjdk.jmh.infra.BenchmarkParams; +import org.openjdk.jmh.results.BenchmarkResult; +import org.openjdk.jmh.results.Result; +import org.openjdk.jmh.results.RunResult; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +public class InstrumentGarbageCollectionBenchmarkTest { + + /** + * This test validates that in {@link MemoryMode#REUSABLE_DATA}, any {@link + * MetricStorage#collect(Resource, InstrumentationScopeInfo, long)} barely allocates memory which + * is then subsequently garbage collected. It is done so comparatively to {@link + * MemoryMode#IMMUTABLE_DATA}, + * + *

      It runs the JMH test {@link InstrumentGarbageCollectionBenchmark} with GC profiler, and + * measures for each parameter combination the garbage collector normalized rate (bytes allocated + * per Operation). + * + *

      Memory allocations can be hidden even at an innocent foreach loop on a collection, which + * under the hood allocates an internal object O(N) times. Someone can accidentally refactor such + * loop, resulting in 30% increase of garbage collected objects during a single collect() run. + */ + @SuppressWarnings("rawtypes") + @Test + public void normalizedAllocationRateTest() throws RunnerException { + // OTel GitHub CI Workflow (see .github/) sets an environment variable + // (RUN_JMH_BASED_TESTS=true). + // We set it only there since it's a lengthy test (roughly 2.5min) + // and we want to run it only in CI. + Assumptions.assumeTrue( + "true".equals(System.getenv("RUN_JMH_BASED_TESTS")), + "This test should only run in GitHub CI since it's long"); + + // Runs InstrumentGarbageCollectionBenchmark + // with garbage collection profiler + Options opt = + new OptionsBuilder() + .include(InstrumentGarbageCollectionBenchmark.class.getSimpleName()) + .addProfiler("gc") + .shouldFailOnError(true) + .jvmArgs("-Xmx1500m") + .build(); + Collection results = new Runner(opt).run(); + + // Collect the normalized GC allocation rate per parameters combination + Map testInstrumentTypeResultsMap = new HashMap<>(); + for (RunResult result : results) { + for (BenchmarkResult benchmarkResult : result.getBenchmarkResults()) { + BenchmarkParams benchmarkParams = benchmarkResult.getParams(); + + String memoryMode = benchmarkParams.getParam("memoryMode"); + String aggregationTemporality = benchmarkParams.getParam("aggregationTemporality"); + String testInstrumentType = benchmarkParams.getParam("testInstrumentType"); + assertThat(memoryMode).isNotNull(); + assertThat(aggregationTemporality).isNotNull(); + assertThat(testInstrumentType).isNotNull(); + + Map secondaryResults = benchmarkResult.getSecondaryResults(); + Result allocRateNorm = secondaryResults.get("gc.alloc.rate.norm"); + assertThat(allocRateNorm) + .describedAs("Allocation rate in secondary results: %s", secondaryResults) + .isNotNull(); + + testInstrumentTypeResultsMap + .computeIfAbsent(testInstrumentType, k -> new TestInstrumentTypeResults()) + .aggregationTemporalityToMemoryModeResult + .computeIfAbsent(aggregationTemporality, k -> new HashMap<>()) + .put(memoryMode, allocRateNorm.getScore()); + } + } + + testInstrumentTypeResultsMap.forEach((testInstrumentTypeString, testInstrumentTypeResults) -> { + Map> resultMap = + testInstrumentTypeResults.aggregationTemporalityToMemoryModeResult; + assertThat(resultMap).hasSameSizeAs(AggregationTemporality.values()); + + // Asserts that reusable data GC allocation rate is a tiny fraction of immutable data + // GC allocation rate + resultMap.forEach((aggregationTemporality, memoryModeToAllocRateMap) -> { + Double immutableDataAllocRate = + memoryModeToAllocRateMap.get(MemoryMode.IMMUTABLE_DATA.toString()); + Double reusableDataAllocRate = + memoryModeToAllocRateMap.get(MemoryMode.REUSABLE_DATA.toString()); + + assertThat(immutableDataAllocRate).isNotNull().isNotZero(); + assertThat(reusableDataAllocRate).isNotNull().isNotZero(); + + TestInstrumentType testInstrumentType = + TestInstrumentType.valueOf(testInstrumentTypeString); + float dataAllocRateReductionPercentage = + testInstrumentType.getDataAllocRateReductionPercentage(); + double allowedOffset = testInstrumentType.getAllowedPercentOffset(); + + // If this test suddenly fails for you this means you have changed the code in a way + // that allocates more memory than before. You can find out where, by running + // ProfileBenchmark class and looking at the flame graph. Make sure to + // set the parameters according to where it failed for. + assertThat(100 - (reusableDataAllocRate / immutableDataAllocRate) * 100) + .describedAs( + "Aggregation temporality = %s, testInstrumentType = %s", + aggregationTemporality, testInstrumentTypeString) + .isCloseTo(dataAllocRateReductionPercentage, Offset.offset(allowedOffset)); + }); + }); + } + + static class TestInstrumentTypeResults { + Map> aggregationTemporalityToMemoryModeResult = new HashMap<>(); + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/NoopMetricExporter.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/NoopMetricExporter.java new file mode 100644 index 00000000000..533a3cc34dc --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/NoopMetricExporter.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricExporter; +import java.util.Collection; + +public class NoopMetricExporter implements MetricExporter { + private final AggregationTemporality aggregationTemporality; + private final Aggregation aggregation; + private final MemoryMode memoryMode; + + /** + * Create a {@link NoopMetricExporter} with aggregationTemporality, aggregation and memory mode. + */ + public NoopMetricExporter( + AggregationTemporality aggregationTemporality, + Aggregation aggregation, + MemoryMode memoryMode) { + this.aggregationTemporality = aggregationTemporality; + this.aggregation = aggregation; + this.memoryMode = memoryMode; + } + + @Override + public CompletableResultCode export(Collection metrics) { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return aggregation; + } + + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return aggregationTemporality; + } + + @Override + public MemoryMode getMemoryMode() { + return memoryMode; + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/ProfileBenchmark.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/ProfileBenchmark.java new file mode 100644 index 00000000000..2d091bfd725 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/ProfileBenchmark.java @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; + +/** + * This benchmark class is used to see memory allocation flame graphs for a single run. + * + *

      Steps: + * + *

        + *
      1. Follow download instructions for async-profiler, located at this location + *
      2. Assuming you have extracted it at /tmp/async-profiler-2.9-macos, add the following to your + * JVM arguments of your run configuration: + *
        + *       -agentpath:/tmp/async-profiler-2.9-macos/build/libasyncProfiler.so=start,event=alloc,flamegraph,file=/tmp/profiled_data.html
        + *       
        + *
      3. Tune the parameters as you see fit (They are marked below with "Parameters") + *
      4. Run the class (its main function) + *
      5. Open /tmp/profiled_data.html with your browser + *
      6. Use the flame graph to see where the allocations are happening the most and fix + *
      7. Run {@link InstrumentGarbageCollectionBenchmark} and see if it passes now + *
      8. If not, repeat + *
      + */ +public class ProfileBenchmark { + + private ProfileBenchmark() {} + + public static void main(String[] args) { + // Parameters + AggregationTemporality aggregationTemporality = AggregationTemporality.DELTA; + MemoryMode memoryMode = MemoryMode.REUSABLE_DATA; + TestInstrumentType testInstrumentType = TestInstrumentType.DOUBLE_LAST_VALUE; + + InstrumentGarbageCollectionBenchmark.ThreadState benchmarkSetup = + new InstrumentGarbageCollectionBenchmark.ThreadState(); + + benchmarkSetup.aggregationTemporality = aggregationTemporality; + benchmarkSetup.memoryMode = memoryMode; + benchmarkSetup.testInstrumentType = testInstrumentType; + + InstrumentGarbageCollectionBenchmark benchmark = new InstrumentGarbageCollectionBenchmark(); + + benchmarkSetup.setup(); + + warmup(benchmark, benchmarkSetup); + + // This is divided explicitly to two methods so you can focus on `measure` in the flame graph + // when trying to decrease the allocations + measure(benchmark, benchmarkSetup); + } + + public static void warmup( + InstrumentGarbageCollectionBenchmark benchmark, + InstrumentGarbageCollectionBenchmark.ThreadState benchmarkSetup) { + for (int i = 0; i < 10; i++) { + benchmark.recordAndCollect(benchmarkSetup); + } + } + + public static void measure( + InstrumentGarbageCollectionBenchmark benchmark, + InstrumentGarbageCollectionBenchmark.ThreadState benchmarkSetup) { + for (int i = 0; i < 200; i++) { + benchmark.recordAndCollect(benchmarkSetup); + } + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/TestInstrumentType.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/TestInstrumentType.java new file mode 100644 index 00000000000..9877d02a945 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/TestInstrumentType.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.tester.AsyncCounterTester; +import io.opentelemetry.sdk.metrics.internal.state.tester.DoubleLastValueTester; +import io.opentelemetry.sdk.metrics.internal.state.tester.DoubleSumTester; +import io.opentelemetry.sdk.metrics.internal.state.tester.ExplicitBucketHistogramTester; +import io.opentelemetry.sdk.metrics.internal.state.tester.ExponentialHistogramTester; +import io.opentelemetry.sdk.metrics.internal.state.tester.LongLastValueTester; +import io.opentelemetry.sdk.metrics.internal.state.tester.LongSumTester; +import java.util.List; +import java.util.Random; +import java.util.function.Supplier; + +@SuppressWarnings("ImmutableEnumChecker") +public enum TestInstrumentType { + ASYNC_COUNTER(AsyncCounterTester::new), + EXPONENTIAL_HISTOGRAM(ExponentialHistogramTester::new), + EXPLICIT_BUCKET(ExplicitBucketHistogramTester::new), + LONG_SUM( + LongSumTester::new, + /* dataAllocRateReductionPercentage= */ 97.3f, + /* allowedPercentOffset= */ 4.0f), + DOUBLE_SUM( + DoubleSumTester::new, + /* dataAllocRateReductionPercentage= */ 97.3f, + /* allowedPercentOffset= */ 4.0f), + LONG_LAST_VALUE( + LongLastValueTester::new, + /* dataAllocRateReductionPercentage= */ 97.3f, + /* allowedPercentOffset= */ 4.0f), + DOUBLE_LAST_VALUE( + DoubleLastValueTester::new, + /* dataAllocRateReductionPercentage= */ 97.3f, + /* allowedPercentOffset= */ 4.0f); + + private final Supplier instrumentTesterInitializer; + private final float dataAllocRateReductionPercentage; + private final double allowedPercentOffset; + + @SuppressWarnings("unused") + TestInstrumentType(Supplier instrumentTesterInitializer) { + this.dataAllocRateReductionPercentage = 99.8f; // default + this.instrumentTesterInitializer = instrumentTesterInitializer; + this.allowedPercentOffset = 2.0f; + } + + // Some instruments have different reduction percentage. + TestInstrumentType( + Supplier instrumentTesterInitializer, + float dataAllocRateReductionPercentage, + float allowedPercentOffset) { + this.instrumentTesterInitializer = instrumentTesterInitializer; + this.dataAllocRateReductionPercentage = dataAllocRateReductionPercentage; + this.allowedPercentOffset = allowedPercentOffset; + } + + float getDataAllocRateReductionPercentage() { + return dataAllocRateReductionPercentage; + } + + public double getAllowedPercentOffset() { + return allowedPercentOffset; + } + + InstrumentTester createInstrumentTester() { + return instrumentTesterInitializer.get(); + } + + public interface InstrumentTester { + Aggregation testedAggregation(); + + TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random); + + void recordValuesInInstruments( + TestInstrumentsState testInstrumentsState, List attributesList, Random random); + } + + public interface TestInstrumentsState {} + + public static class EmptyInstrumentsState implements TestInstrumentsState {} +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java new file mode 100644 index 00000000000..4cc5b1bb4bb --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/AsyncCounterTester.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType.EmptyInstrumentsState; +import java.util.List; +import java.util.Random; + +public class AsyncCounterTester implements TestInstrumentType.InstrumentTester { + @Override + public Aggregation testedAggregation() { + return Aggregation.sum(); + } + + @SuppressWarnings("ForLoopReplaceableByForEach") // This is for GC sensitivity testing: no streams + @Override + public TestInstrumentType.TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + for (int i = 0; i < instrumentCount; i++) { + sdkMeterProvider + .get("meter") + .counterBuilder("counter" + i) + .buildWithCallback(observableLongMeasurement -> { + for (int j = 0; j < attributesList.size(); j++) { + Attributes attributes = attributesList.get(j); + observableLongMeasurement.record(random.nextInt(10_000), attributes); + } + }); + } + return new EmptyInstrumentsState(); + } + + @Override + public void recordValuesInInstruments( + TestInstrumentType.TestInstrumentsState testInstrumentsState, + List attributesList, + Random random) { + // No need, all done via the callbacks + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java new file mode 100644 index 00000000000..ad23b9cc826 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleLastValueTester.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType; +import java.util.List; +import java.util.Random; + +public class DoubleLastValueTester implements TestInstrumentType.InstrumentTester { + + @Override + public Aggregation testedAggregation() { + return Aggregation.lastValue(); + } + + @SuppressWarnings("ForLoopReplaceableByForEach") // This is for GC sensitivity testing: no streams + @Override + public TestInstrumentType.TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + Meter meter = sdkMeterProvider.meterBuilder("meter").build(); + meter + .gaugeBuilder("test.double.last.value") + .buildWithCallback(observableDoubleMeasurement -> { + for (int j = 0; j < attributesList.size(); j++) { + observableDoubleMeasurement.record(1.2f, attributesList.get(j)); + } + }); + + return new TestInstrumentType.EmptyInstrumentsState(); + } + + @Override + public void recordValuesInInstruments( + TestInstrumentType.TestInstrumentsState testInstrumentsState, + List attributesList, + Random random) { + // Recording is done by the callback define above + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleSumTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleSumTester.java new file mode 100644 index 00000000000..47cf4e4023e --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/DoubleSumTester.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType; +import java.util.List; +import java.util.Random; + +public class DoubleSumTester implements TestInstrumentType.InstrumentTester { + private static final int measurementsPerAttributeSet = 1_000; + + static class DoubleSumState implements TestInstrumentType.TestInstrumentsState { + DoubleCounter doubleCounter; + } + + @Override + public Aggregation testedAggregation() { + return Aggregation.sum(); + } + + @Override + public TestInstrumentType.TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + DoubleSumState doubleSumState = new DoubleSumState(); + + Meter meter = sdkMeterProvider.meterBuilder("meter").build(); + doubleSumState.doubleCounter = meter.counterBuilder("test.double.sum").ofDoubles().build(); + + return doubleSumState; + } + + @SuppressWarnings("ForLoopReplaceableByForEach") // This is for GC sensitivity testing: no streams + @Override + public void recordValuesInInstruments( + TestInstrumentType.TestInstrumentsState testInstrumentsState, + List attributesList, + Random random) { + DoubleSumState state = (DoubleSumState) testInstrumentsState; + + for (int j = 0; j < attributesList.size(); j++) { + Attributes attributes = attributesList.get(j); + for (int i = 0; i < measurementsPerAttributeSet; i++) { + state.doubleCounter.add(1.2f, attributes); + } + } + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/ExplicitBucketHistogramTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/ExplicitBucketHistogramTester.java new file mode 100644 index 00000000000..64ef6ca970d --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/ExplicitBucketHistogramTester.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType.InstrumentTester; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType.TestInstrumentsState; +import java.util.List; +import java.util.Random; + +public class ExplicitBucketHistogramTester implements InstrumentTester { + + static class ExplicitHistogramState implements TestInstrumentsState { + public double maxBucketValue; + DoubleHistogram doubleHistogram; + } + + private static final int measurementsPerAttributeSet = 1_000; + + @Override + public Aggregation testedAggregation() { + return Aggregation.explicitBucketHistogram(); + } + + @Override + public TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + ExplicitHistogramState state = new ExplicitHistogramState(); + state.doubleHistogram = + sdkMeterProvider.get("meter").histogramBuilder("test.explicit.histogram").build(); + state.maxBucketValue = + ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES.get( + ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES.size() - 1); + return state; + } + + @SuppressWarnings("ForLoopReplaceableByForEach") // This is for GC sensitivity testing: no streams + @Override + public void recordValuesInInstruments( + TestInstrumentsState testInstrumentsState, List attributesList, Random random) { + + ExplicitHistogramState state = (ExplicitHistogramState) testInstrumentsState; + + for (int j = 0; j < attributesList.size(); j++) { + Attributes attributes = attributesList.get(j); + for (int i = 0; i < measurementsPerAttributeSet; i++) { + state.doubleHistogram.record( + random.nextInt(Double.valueOf(state.maxBucketValue * 1.1).intValue()), attributes); + } + } + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/ExponentialHistogramTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/ExponentialHistogramTester.java new file mode 100644 index 00000000000..6cca5a35bd4 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/ExponentialHistogramTester.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType.InstrumentTester; +import java.util.List; +import java.util.Random; + +public class ExponentialHistogramTester implements InstrumentTester { + + static class ExponentialHistogramState implements TestInstrumentType.TestInstrumentsState { + DoubleHistogram doubleHistogram; + } + + private static final int measurementsPerAttributeSet = 1_000; + + @Override + public Aggregation testedAggregation() { + return Aggregation.base2ExponentialBucketHistogram(); + } + + @Override + public TestInstrumentType.TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + ExponentialHistogramState state = new ExponentialHistogramState(); + state.doubleHistogram = sdkMeterProvider.get("meter").histogramBuilder("testhistogram").build(); + return state; + } + + @SuppressWarnings("ForLoopReplaceableByForEach") // This is for GC sensitivity testing: no streams + @Override + public void recordValuesInInstruments( + TestInstrumentType.TestInstrumentsState testInstrumentsState, + List attributesList, + Random random) { + + ExponentialHistogramState state = (ExponentialHistogramState) testInstrumentsState; + + for (int j = 0; j < attributesList.size(); j++) { + Attributes attributes = attributesList.get(j); + for (int i = 0; i < measurementsPerAttributeSet; i++) { + state.doubleHistogram.record(random.nextInt(10_000), attributes); + } + } + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java new file mode 100644 index 00000000000..0838f7612b3 --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongLastValueTester.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType; +import java.util.List; +import java.util.Random; + +public class LongLastValueTester implements TestInstrumentType.InstrumentTester { + + @Override + public Aggregation testedAggregation() { + return Aggregation.lastValue(); + } + + @SuppressWarnings({"ForLoopReplaceableByForEach", "resource"}) + @Override + public TestInstrumentType.TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + Meter meter = sdkMeterProvider.meterBuilder("meter").build(); + meter + .gaugeBuilder("test.long.last.value") + .ofLongs() + .buildWithCallback(observableLongMeasurement -> { + for (int j = 0; j < attributesList.size(); j++) { + observableLongMeasurement.record(1, attributesList.get(j)); + } + }); + + return new TestInstrumentType.EmptyInstrumentsState(); + } + + @Override + public void recordValuesInInstruments( + TestInstrumentType.TestInstrumentsState testInstrumentsState, + List attributesList, + Random random) { + // Recording is done by the callback define above + } +} diff --git a/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongSumTester.java b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongSumTester.java new file mode 100644 index 00000000000..2477020633e --- /dev/null +++ b/sdk/metrics/src/jmhBasedTest/java/io/opentelemetry/sdk/metrics/internal/state/tester/LongSumTester.java @@ -0,0 +1,58 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state.tester; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.state.TestInstrumentType; +import java.util.List; +import java.util.Random; + +public class LongSumTester implements TestInstrumentType.InstrumentTester { + private static final int measurementsPerAttributeSet = 1_000; + + static class LongSumState implements TestInstrumentType.TestInstrumentsState { + LongCounter longCounter; + } + + @Override + public Aggregation testedAggregation() { + return Aggregation.sum(); + } + + @Override + public TestInstrumentType.TestInstrumentsState buildInstruments( + double instrumentCount, + SdkMeterProvider sdkMeterProvider, + List attributesList, + Random random) { + LongSumState longSumState = new LongSumState(); + + Meter meter = sdkMeterProvider.meterBuilder("meter").build(); + longSumState.longCounter = meter.counterBuilder("test.long.sum").build(); + + return longSumState; + } + + @SuppressWarnings("ForLoopReplaceableByForEach") // This is for GC sensitivity testing: no streams + @Override + public void recordValuesInInstruments( + TestInstrumentType.TestInstrumentsState testInstrumentsState, + List attributesList, + Random random) { + LongSumState state = (LongSumState) testInstrumentsState; + + for (int j = 0; j < attributesList.size(); j++) { + Attributes attributes = attributesList.get(j); + for (int i = 0; i < measurementsPerAttributeSet; i++) { + state.longCounter.add(1, attributes); + } + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrument.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrument.java index cb0c3da9285..9f3d923c2bc 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrument.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrument.java @@ -5,6 +5,7 @@ package io.opentelemetry.sdk.metrics; +import io.opentelemetry.context.Context; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import javax.annotation.Nullable; @@ -12,15 +13,35 @@ abstract class AbstractInstrument { private final InstrumentDescriptor descriptor; + /** + * True when the record-path {@link Context} has no observable effect for this instrument, so + * parameterless record overloads may substitute {@link Context#root()} for {@link + * Context#current()} and skip a thread-local lookup. The exemplar filter and context-scoped + * attributes are the record-path consumers of {@link Context}, so this is true iff both are + * disabled meter-wide. + */ + private final boolean canUseRootContext; + // All arguments cannot be null because they are checked in the abstract builder classes. - AbstractInstrument(InstrumentDescriptor descriptor) { + AbstractInstrument(InstrumentDescriptor descriptor, SdkMeter sdkMeter) { this.descriptor = descriptor; + this.canUseRootContext = + sdkMeter.isExemplarsAlwaysOff() && sdkMeter.getContextScopedAttributesFilter() == null; } final InstrumentDescriptor getDescriptor() { return descriptor; } + /** + * Returns {@link Context#current()}, or {@link Context#root()} when the current context can have + * no observable effect on this instrument's outputs (see {@link #canUseRootContext}). Used by + * parameterless record overloads on synchronous instruments to skip a thread-local lookup. + */ + final Context currentOrRootContext() { + return canUseRootContext ? Context.root() : Context.current(); + } + @Override public boolean equals(@Nullable Object o) { if (this == o) { @@ -39,4 +60,9 @@ public boolean equals(@Nullable Object o) { public int hashCode() { return descriptor.hashCode(); } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "{" + "descriptor=" + getDescriptor() + '}'; + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrumentBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrumentBuilder.java deleted file mode 100644 index 1f7e197626e..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/AbstractInstrumentBuilder.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import io.opentelemetry.api.internal.ValidationUtil; -import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; -import io.opentelemetry.api.metrics.ObservableLongMeasurement; -import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.state.CallbackRegistration; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; -import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; -import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; -import java.util.Collections; -import java.util.function.BiFunction; -import java.util.function.Consumer; - -/** Helper to make implementing builders easier. */ -abstract class AbstractInstrumentBuilder> { - - static final String DEFAULT_UNIT = ""; - - private final MeterProviderSharedState meterProviderSharedState; - private String description; - private String unit; - - protected final MeterSharedState meterSharedState; - protected final String instrumentName; - - AbstractInstrumentBuilder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState meterSharedState, - String name, - String description, - String unit) { - this.instrumentName = name; - this.description = description; - this.unit = unit; - this.meterProviderSharedState = meterProviderSharedState; - this.meterSharedState = meterSharedState; - } - - protected abstract BuilderT getThis(); - - public BuilderT setUnit(String unit) { - if (!ValidationUtil.checkValidInstrumentUnit( - unit, - " Using \"" + DEFAULT_UNIT + "\" for instrument " + this.instrumentName + " instead.")) { - this.unit = DEFAULT_UNIT; - } else { - this.unit = unit; - } - return getThis(); - } - - public BuilderT setDescription(String description) { - this.description = description; - return getThis(); - } - - private InstrumentDescriptor makeDescriptor(InstrumentType type, InstrumentValueType valueType) { - return InstrumentDescriptor.create(instrumentName, description, unit, type, valueType); - } - - protected T swapBuilder(SwapBuilder swapper) { - return swapper.newBuilder( - meterProviderSharedState, meterSharedState, instrumentName, description, unit); - } - - final I buildSynchronousInstrument( - InstrumentType type, - InstrumentValueType valueType, - BiFunction instrumentFactory) { - InstrumentDescriptor descriptor = makeDescriptor(type, valueType); - WriteableMetricStorage storage = - meterSharedState.registerSynchronousMetricStorage(descriptor, meterProviderSharedState); - return instrumentFactory.apply(descriptor, storage); - } - - final CallbackRegistration registerDoubleAsynchronousInstrument( - InstrumentType type, Consumer updater) { - SdkObservableMeasurement sdkObservableMeasurement = - buildObservableMeasurement(type, InstrumentValueType.DOUBLE); - Runnable runnable = () -> updater.accept(sdkObservableMeasurement); - CallbackRegistration callbackRegistration = - CallbackRegistration.create(Collections.singletonList(sdkObservableMeasurement), runnable); - meterSharedState.registerCallback(callbackRegistration); - return callbackRegistration; - } - - final CallbackRegistration registerLongAsynchronousInstrument( - InstrumentType type, Consumer updater) { - SdkObservableMeasurement sdkObservableMeasurement = - buildObservableMeasurement(type, InstrumentValueType.LONG); - Runnable runnable = () -> updater.accept(sdkObservableMeasurement); - CallbackRegistration callbackRegistration = - CallbackRegistration.create(Collections.singletonList(sdkObservableMeasurement), runnable); - meterSharedState.registerCallback(callbackRegistration); - return callbackRegistration; - } - - final SdkObservableMeasurement buildObservableMeasurement( - InstrumentType type, InstrumentValueType valueType) { - InstrumentDescriptor descriptor = makeDescriptor(type, valueType); - return meterSharedState.registerObservableMeasurement(descriptor, meterProviderSharedState); - } - - @FunctionalInterface - protected interface SwapBuilder { - T newBuilder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState meterSharedState, - String name, - String description, - String unit); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Aggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Aggregation.java index 603521d5938..2f64416973e 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Aggregation.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Aggregation.java @@ -5,6 +5,9 @@ package io.opentelemetry.sdk.metrics; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; +import io.opentelemetry.sdk.metrics.internal.view.Base2ExponentialHistogramAggregation; import io.opentelemetry.sdk.metrics.internal.view.DefaultAggregation; import io.opentelemetry.sdk.metrics.internal.view.DropAggregation; import io.opentelemetry.sdk.metrics.internal.view.ExplicitBucketHistogramAggregation; @@ -13,48 +16,117 @@ import java.util.List; /** - * Configures how measurements are combined into metrics. + * Configures how instrument measurements are combined into metrics. * *

      Aggregation provides a set of built-in aggregations via static methods. + * + * @since 1.14.0 */ // TODO(anuraaga): Have methods when custom aggregations are supported. @SuppressWarnings("InterfaceWithOnlyStatics") public interface Aggregation { - /** The drop Aggregation will ignore/drop all Instrument Measurements. */ + /** Drops all measurements and don't export any metric. */ static Aggregation drop() { return DropAggregation.getInstance(); } - /** The default aggregation for an instrument will be chosen. */ + /** Choose the default aggregation for the {@link InstrumentType}. */ static Aggregation defaultAggregation() { return DefaultAggregation.getInstance(); } - /** Instrument measurements will be combined into a metric Sum. */ + /** + * Aggregates measurements into a {@link MetricDataType#DOUBLE_SUM} or {@link + * MetricDataType#LONG_SUM}. + */ static Aggregation sum() { return SumAggregation.getInstance(); } - /** Remembers the last seen measurement and reports as a Gauge. */ + /** + * Records the last seen measurement as a {@link MetricDataType#DOUBLE_GAUGE} or {@link + * MetricDataType#LONG_GAUGE}. + */ static Aggregation lastValue() { return LastValueAggregation.getInstance(); } /** - * Aggregates measurements into an explicit bucket histogram using the default bucket boundaries. + * Aggregates measurements into an explicit bucket {@link MetricDataType#HISTOGRAM} using the + * default bucket boundaries. */ static Aggregation explicitBucketHistogram() { return ExplicitBucketHistogramAggregation.getDefault(); } /** - * Aggregates measurements into an explicit bucket histogram. + * Aggregates measurements into an explicit bucket {@link MetricDataType#HISTOGRAM}. * * @param bucketBoundaries A list of (inclusive) upper bounds for the histogram. Should be in * order from lowest to highest. + * @deprecated Use {@link #explicitBucketHistogram(ExplicitBucketHistogramOptions)} instead. */ + @Deprecated static Aggregation explicitBucketHistogram(List bucketBoundaries) { - return ExplicitBucketHistogramAggregation.create(bucketBoundaries); + return explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder().setBucketBoundaries(bucketBoundaries).build()); + } + + /** + * Aggregates measurements into an explicit bucket {@link MetricDataType#HISTOGRAM}. + * + * @param options histogram options + * @since 1.60.0 + */ + static Aggregation explicitBucketHistogram(ExplicitBucketHistogramOptions options) { + List boundaries = options.getBucketBoundaries(); + if (boundaries == null) { + boundaries = ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES; + } + return ExplicitBucketHistogramAggregation.create(boundaries, options.getRecordMinMax()); + } + + /** + * Aggregates measurements into a base-2 {@link MetricDataType#EXPONENTIAL_HISTOGRAM} using the + * default {@code maxBuckets} and {@code maxScale}. + * + * @since 1.23.0 + */ + static Aggregation base2ExponentialBucketHistogram() { + return Base2ExponentialHistogramAggregation.getDefault(); + } + + /** + * Aggregates measurements into a base-2 {@link MetricDataType#EXPONENTIAL_HISTOGRAM}. + * + * @param maxBuckets the max number of positive buckets and negative buckets (max total buckets is + * 2 * {@code maxBuckets} + 1 zero bucket). + * @param maxScale the maximum and initial scale. If measurements can't fit in a particular scale + * given the {@code maxBuckets}, the scale is reduced until the measurements can be + * accommodated. Setting maxScale may reduce the number of downscales. Additionally, the + * performance of computing bucket index is improved when scale is {@code <= 0}. + * @since 1.23.0 + * @deprecated Use {@link #base2ExponentialBucketHistogram(Base2ExponentialHistogramOptions)} + * instead. + */ + @Deprecated + static Aggregation base2ExponentialBucketHistogram(int maxBuckets, int maxScale) { + return base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(maxBuckets) + .setMaxScale(maxScale) + .build()); + } + + /** + * Aggregates measurements into a base-2 {@link MetricDataType#EXPONENTIAL_HISTOGRAM}. + * + * @param options histogram options + * @since 1.60.0 + */ + static Aggregation base2ExponentialBucketHistogram(Base2ExponentialHistogramOptions options) { + return Base2ExponentialHistogramAggregation.create( + options.getMaxBuckets(), options.getMaxScale(), options.getRecordMinMax()); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Base2ExponentialHistogramOptions.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Base2ExponentialHistogramOptions.java new file mode 100644 index 00000000000..5a7a9588894 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/Base2ExponentialHistogramOptions.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.api.internal.Utils.checkArgument; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Options for configuring base-2 exponential histogram aggregations. + * + * @see Aggregation#base2ExponentialBucketHistogram(Base2ExponentialHistogramOptions) + * @since 1.60.0 + */ +@AutoValue +@Immutable +public abstract class Base2ExponentialHistogramOptions { + + /** The default maximum number of buckets. */ + private static final int DEFAULT_MAX_BUCKETS = 160; + + /** The default maximum scale. */ + private static final int DEFAULT_MAX_SCALE = 20; + + private static final Base2ExponentialHistogramOptions DEFAULT = builder().build(); + + Base2ExponentialHistogramOptions() {} + + /** Returns the default {@link Base2ExponentialHistogramOptions}. */ + public static Base2ExponentialHistogramOptions getDefault() { + return DEFAULT; + } + + /** Returns a new {@link Builder} for {@link Base2ExponentialHistogramOptions}. */ + public static Builder builder() { + return new AutoValue_Base2ExponentialHistogramOptions.Builder() + .setMaxBuckets(DEFAULT_MAX_BUCKETS) + .setMaxScale(DEFAULT_MAX_SCALE) + .setRecordMinMax(true); + } + + /** Returns a {@link Builder} initialized to the same property values as the current instance. */ + public abstract Builder toBuilder(); + + /** + * Returns the max number of positive and negative buckets. Defaults to {@value + * #DEFAULT_MAX_BUCKETS}. + */ + public abstract int getMaxBuckets(); + + /** Returns the maximum and initial scale. Defaults to {@value #DEFAULT_MAX_SCALE}. */ + public abstract int getMaxScale(); + + /** Returns whether min and max values should be recorded. Defaults to {@code true}. */ + public abstract boolean getRecordMinMax(); + + /** + * Builder for {@link Base2ExponentialHistogramOptions}. + * + * @since 1.60.0 + */ + @AutoValue.Builder + public abstract static class Builder { + + Builder() {} + + /** + * Sets the max number of positive buckets and negative buckets (max total buckets is 2 * {@code + * maxBuckets} + 1 zero bucket). + * + * @param maxBuckets the maximum number of buckets + */ + public abstract Builder setMaxBuckets(int maxBuckets); + + /** + * Sets the maximum and initial scale. If measurements can't fit in a particular scale given the + * {@code maxBuckets}, the scale is reduced until the measurements can be accommodated. Setting + * maxScale may reduce the number of downscales. Additionally, the performance of computing + * bucket index is improved when scale is {@code <= 0}. + * + * @param maxScale the maximum scale + */ + public abstract Builder setMaxScale(int maxScale); + + /** + * Sets whether min and max values should be recorded. + * + * @param recordMinMax whether to record min and max values + */ + public abstract Builder setRecordMinMax(boolean recordMinMax); + + abstract Base2ExponentialHistogramOptions autoBuild(); + + /** + * Returns a new {@link Base2ExponentialHistogramOptions} with the configuration of this + * builder. + * + * @throws IllegalArgumentException if {@code maxBuckets} is less than 2, or if {@code maxScale} + * is not between -10 and 20 (inclusive). + */ + public Base2ExponentialHistogramOptions build() { + Base2ExponentialHistogramOptions options = autoBuild(); + checkArgument(options.getMaxBuckets() >= 2, "maxBuckets must be >= 2"); + checkArgument( + options.getMaxScale() >= -10 && options.getMaxScale() <= 20, + "maxScale must be -10 <= x <= 20"); + return options; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExemplarFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExemplarFilter.java new file mode 100644 index 00000000000..d9cc8b61c4c --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExemplarFilter.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.exemplar.AlwaysOffExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.AlwaysOnExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.TraceBasedExemplarFilter; + +/** + * Exemplar filters are used to pre-filter measurements before attempting to store them in a + * reservoir ({@link DoubleExemplarReservoir}, {@link LongExemplarReservoir}. + * + * @see SdkMeterProviderBuilder#setExemplarFilter(ExemplarFilter) + * @since 1.56.0 + */ +// TODO(jack-berg): Have methods when custom filters are supported. +@SuppressWarnings("InterfaceWithOnlyStatics") +public interface ExemplarFilter { + /** + * A filter that only accepts measurements where there is a {@code Span} in {@link Context} that + * is being sampled. + */ + static ExemplarFilter traceBased() { + return TraceBasedExemplarFilter.getInstance(); + } + + /** A filter which makes all measurements eligible for being an exemplar. */ + static ExemplarFilter alwaysOn() { + return AlwaysOnExemplarFilter.getInstance(); + } + + /** A filter which makes no measurements eligible for being an exemplar. */ + static ExemplarFilter alwaysOff() { + return AlwaysOffExemplarFilter.getInstance(); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExplicitBucketHistogramOptions.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExplicitBucketHistogramOptions.java new file mode 100644 index 00000000000..ef4da876800 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExplicitBucketHistogramOptions.java @@ -0,0 +1,79 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import com.google.auto.value.AutoValue; +import java.util.List; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * Options for configuring explicit bucket histogram aggregations. + * + * @see Aggregation#explicitBucketHistogram(ExplicitBucketHistogramOptions) + * @since 1.60.0 + */ +@AutoValue +@Immutable +public abstract class ExplicitBucketHistogramOptions { + + private static final ExplicitBucketHistogramOptions DEFAULT = builder().build(); + + ExplicitBucketHistogramOptions() {} + + /** Returns the default {@link ExplicitBucketHistogramOptions}. */ + public static ExplicitBucketHistogramOptions getDefault() { + return DEFAULT; + } + + /** Returns a new {@link Builder} for {@link ExplicitBucketHistogramOptions}. */ + public static Builder builder() { + return new AutoValue_ExplicitBucketHistogramOptions.Builder().setRecordMinMax(true); + } + + /** Returns a {@link Builder} initialized to the same property values as the current instance. */ + public abstract Builder toBuilder(); + + /** + * Returns the bucket boundaries, or {@code null} if the default OTel bucket boundaries should be + * used. + */ + @Nullable + public abstract List getBucketBoundaries(); + + /** Returns whether min and max values should be recorded. Defaults to {@code true}. */ + public abstract boolean getRecordMinMax(); + + /** + * Builder for {@link ExplicitBucketHistogramOptions}. + * + * @since 1.60.0 + */ + @AutoValue.Builder + public abstract static class Builder { + + Builder() {} + + /** + * Sets the bucket boundaries. If not set, the default OTel bucket boundaries are used. + * + * @param bucketBoundaries a list of (inclusive) upper bounds, in order from lowest to highest + */ + public abstract Builder setBucketBoundaries(@Nullable List bucketBoundaries); + + /** + * Sets whether min and max values should be recorded. + * + * @param recordMinMax whether to record min and max values + */ + public abstract Builder setRecordMinMax(boolean recordMinMax); + + /** + * Returns a new {@link ExplicitBucketHistogramOptions} with the configuration of this builder. + */ + public abstract ExplicitBucketHistogramOptions build(); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleCounter.java new file mode 100644 index 00000000000..f5cf1c75b2f --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleCounter.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounterBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkDoubleCounter extends SdkDoubleCounter + implements ExtendedDoubleCounter, BoundDoubleCounter { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the add() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkDoubleCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkDoubleCounter( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundDoubleCounter bind(Attributes attributes) { + return new ExtendedSdkDoubleCounter( + getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void add(double value) { + add(value, currentOrRootContext()); + } + + @Override + public void add(double value, Context context) { + if (!validateNonNegative(value)) { + return; + } + if (boundHandle != null) { + boundHandle.recordDouble(value, context); + } else { + storage.recordDouble(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkDoubleCounterBuilder extends SdkDoubleCounterBuilder + implements ExtendedDoubleCounterBuilder { + + ExtendedSdkDoubleCounterBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + super(sdkMeter, name, description, unit, adviceBuilder); + } + + @Override + public ExtendedSdkDoubleCounter build() { + return builder.buildSynchronousInstrument(ExtendedSdkDoubleCounter::new); + } + + @Override + public ExtendedDoubleCounterBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleGauge.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleGauge.java new file mode 100644 index 00000000000..36007a926b4 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleGauge.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundDoubleGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGaugeBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGaugeBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkDoubleGauge extends SdkDoubleGauge + implements ExtendedDoubleGauge, BoundDoubleGauge { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the set() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkDoubleGauge( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkDoubleGauge( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundDoubleGauge bind(Attributes attributes) { + return new ExtendedSdkDoubleGauge(getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void set(double value) { + set(value, currentOrRootContext()); + } + + @Override + public void set(double value, Context context) { + if (boundHandle != null) { + boundHandle.recordDouble(value, context); + } else { + storage.recordDouble(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkDoubleGaugeBuilder extends SdkDoubleGaugeBuilder + implements ExtendedDoubleGaugeBuilder { + ExtendedSdkDoubleGaugeBuilder(SdkMeter sdkMeter, String name) { + super(sdkMeter, name); + } + + @Override + public ExtendedSdkDoubleGauge build() { + return builder.buildSynchronousInstrument(ExtendedSdkDoubleGauge::new); + } + + @Override + public ExtendedDoubleGaugeBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + + @Override + public ExtendedLongGaugeBuilder ofLongs() { + return builder.swapBuilder(ExtendedSdkLongGauge.ExtendedSdkLongGaugeBuilder::new); + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleHistogram.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleHistogram.java new file mode 100644 index 00000000000..f8a401ff9ee --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleHistogram.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogramBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogramBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkDoubleHistogram extends SdkDoubleHistogram + implements ExtendedDoubleHistogram, BoundDoubleHistogram { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the record() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + ExtendedSdkDoubleHistogram( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkDoubleHistogram( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundDoubleHistogram bind(Attributes attributes) { + return new ExtendedSdkDoubleHistogram( + getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void record(double value) { + record(value, currentOrRootContext()); + } + + @Override + public void record(double value, Context context) { + if (!validateNonNegative(value)) { + return; + } + if (boundHandle != null) { + boundHandle.recordDouble(value, context); + } else { + storage.recordDouble(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkDoubleHistogramBuilder extends SdkDoubleHistogramBuilder + implements ExtendedDoubleHistogramBuilder { + + ExtendedSdkDoubleHistogramBuilder(SdkMeter sdkMeter, String name) { + super(sdkMeter, name); + } + + @Override + public ExtendedSdkDoubleHistogram build() { + return builder.buildSynchronousInstrument(ExtendedSdkDoubleHistogram::new); + } + + @Override + public ExtendedLongHistogramBuilder ofLongs() { + return builder.swapBuilder(ExtendedSdkLongHistogram.ExtendedSdkLongHistogramBuilder::new); + } + + @Override + public ExtendedDoubleHistogramBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleUpDownCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleUpDownCounter.java new file mode 100644 index 00000000000..99a3972bd3c --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkDoubleUpDownCounter.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounterBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkDoubleUpDownCounter extends SdkDoubleUpDownCounter + implements ExtendedDoubleUpDownCounter, BoundDoubleUpDownCounter { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the add() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkDoubleUpDownCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkDoubleUpDownCounter( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundDoubleUpDownCounter bind(Attributes attributes) { + return new ExtendedSdkDoubleUpDownCounter( + getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void add(double value) { + add(value, currentOrRootContext()); + } + + @Override + public void add(double value, Context context) { + if (boundHandle != null) { + boundHandle.recordDouble(value, context); + } else { + storage.recordDouble(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkDoubleUpDownCounterBuilder extends SdkDoubleUpDownCounterBuilder + implements ExtendedDoubleUpDownCounterBuilder { + + ExtendedSdkDoubleUpDownCounterBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + super(sdkMeter, name, description, unit, adviceBuilder); + } + + @Override + public ExtendedDoubleUpDownCounter build() { + return builder.buildSynchronousInstrument(ExtendedSdkDoubleUpDownCounter::new); + } + + @Override + public ExtendedDoubleUpDownCounterBuilder setAttributesAdvice( + List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongCounter.java new file mode 100644 index 00000000000..877289dde2b --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongCounter.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounterBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounterBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkLongCounter extends SdkLongCounter + implements ExtendedLongCounter, BoundLongCounter { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the add() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkLongCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkLongCounter( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundLongCounter bind(Attributes attributes) { + return new ExtendedSdkLongCounter(getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void add(long value) { + add(value, currentOrRootContext()); + } + + @Override + public void add(long value, Context context) { + if (!validateNonNegative(value)) { + return; + } + if (boundHandle != null) { + boundHandle.recordLong(value, context); + } else { + storage.recordLong(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkLongCounterBuilder extends SdkLongCounterBuilder + implements ExtendedLongCounterBuilder { + + ExtendedSdkLongCounterBuilder(SdkMeter sdkMeter, String name) { + super(sdkMeter, name); + } + + @Override + public ExtendedSdkLongCounter build() { + return builder.buildSynchronousInstrument(ExtendedSdkLongCounter::new); + } + + @Override + public ExtendedDoubleCounterBuilder ofDoubles() { + return builder.swapBuilder(ExtendedSdkDoubleCounter.ExtendedSdkDoubleCounterBuilder::new); + } + + @Override + public ExtendedLongCounterBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongGauge.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongGauge.java new file mode 100644 index 00000000000..c8e4a6f45b5 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongGauge.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundLongGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGaugeBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkLongGauge extends SdkLongGauge implements ExtendedLongGauge, BoundLongGauge { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the set() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkLongGauge( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkLongGauge( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundLongGauge bind(Attributes attributes) { + return new ExtendedSdkLongGauge(getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void set(long value) { + set(value, currentOrRootContext()); + } + + @Override + public void set(long value, Context context) { + if (boundHandle != null) { + boundHandle.recordLong(value, context); + } else { + storage.recordLong(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkLongGaugeBuilder extends SdkLongGaugeBuilder + implements ExtendedLongGaugeBuilder { + + ExtendedSdkLongGaugeBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + super(sdkMeter, name, description, unit, adviceBuilder); + } + + @Override + public ExtendedSdkLongGauge build() { + return builder.buildSynchronousInstrument(ExtendedSdkLongGauge::new); + } + + @Override + public ExtendedLongGaugeBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongHistogram.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongHistogram.java new file mode 100644 index 00000000000..a2ae99a2211 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongHistogram.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundLongHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogramBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkLongHistogram extends SdkLongHistogram + implements ExtendedLongHistogram, BoundLongHistogram { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the record() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkLongHistogram( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkLongHistogram( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundLongHistogram bind(Attributes attributes) { + return new ExtendedSdkLongHistogram( + getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void record(long value) { + record(value, currentOrRootContext()); + } + + @Override + public void record(long value, Context context) { + if (!validateNonNegative(value)) { + return; + } + if (boundHandle != null) { + boundHandle.recordLong(value, context); + } else { + storage.recordLong(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkLongHistogramBuilder extends SdkLongHistogramBuilder + implements ExtendedLongHistogramBuilder { + + ExtendedSdkLongHistogramBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + super(sdkMeter, name, description, unit, adviceBuilder); + } + + @Override + public ExtendedSdkLongHistogram build() { + return builder.buildSynchronousInstrument(ExtendedSdkLongHistogram::new); + } + + @Override + public ExtendedLongHistogramBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongUpDownCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongUpDownCounter.java new file mode 100644 index 00000000000..bea60507fe3 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ExtendedSdkLongUpDownCounter.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundLongUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounterBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounterBuilder; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import javax.annotation.Nullable; + +final class ExtendedSdkLongUpDownCounter extends SdkLongUpDownCounter + implements ExtendedLongUpDownCounter, BoundLongUpDownCounter { + + // Non-null only when this is a bound instance returned from bind(); null for the instrument + // itself. When set, the add() methods record straight to this handle instead of resolving the + // series from the storage on each call. + @Nullable private final BoundStorageHandle boundHandle; + + private ExtendedSdkLongUpDownCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + this(descriptor, sdkMeter, storage, null); + } + + private ExtendedSdkLongUpDownCounter( + InstrumentDescriptor descriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage, + @Nullable BoundStorageHandle boundHandle) { + super(descriptor, sdkMeter, storage); + this.boundHandle = boundHandle; + } + + @Override + public BoundLongUpDownCounter bind(Attributes attributes) { + return new ExtendedSdkLongUpDownCounter( + getDescriptor(), sdkMeter, storage, storage.bind(attributes)); + } + + @Override + public void add(long value) { + add(value, currentOrRootContext()); + } + + @Override + public void add(long value, Context context) { + if (boundHandle != null) { + boundHandle.recordLong(value, context); + } else { + storage.recordLong(value, Attributes.empty(), context); + } + } + + static final class ExtendedSdkLongUpDownCounterBuilder extends SdkLongUpDownCounterBuilder + implements ExtendedLongUpDownCounterBuilder { + + ExtendedSdkLongUpDownCounterBuilder(SdkMeter sdkMeter, String name) { + super(sdkMeter, name); + } + + @Override + public ExtendedLongUpDownCounter build() { + return builder.buildSynchronousInstrument(ExtendedSdkLongUpDownCounter::new); + } + + @Override + public ExtendedDoubleUpDownCounterBuilder ofDoubles() { + return builder.swapBuilder( + ExtendedSdkDoubleUpDownCounter.ExtendedSdkDoubleUpDownCounterBuilder::new); + } + + @Override + public ExtendedLongUpDownCounterBuilder setAttributesAdvice(List> attributes) { + builder.setAdviceAttributes(attributes); + return this; + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/IncubatingUtil.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/IncubatingUtil.java new file mode 100644 index 00000000000..03a88bb9382 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/IncubatingUtil.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.metrics.DoubleGaugeBuilder; +import io.opentelemetry.api.metrics.DoubleHistogramBuilder; +import io.opentelemetry.api.metrics.LongCounterBuilder; +import io.opentelemetry.api.metrics.LongUpDownCounterBuilder; + +/** + * Utilities for interacting with {@code io.opentelemetry:opentelemetry-api-incubator}, which is not + * guaranteed to be present on the classpath. For all methods, callers MUST first separately + * reflectively confirm that the incubator is available on the classpath. + */ +final class IncubatingUtil { + + private IncubatingUtil() {} + + static LongCounterBuilder createExtendedLongCounterBuilder(SdkMeter sdkMeter, String name) { + return new ExtendedSdkLongCounter.ExtendedSdkLongCounterBuilder(sdkMeter, name); + } + + static LongUpDownCounterBuilder createExtendedLongUpDownCounterBuilder( + SdkMeter sdkMeter, String name) { + return new ExtendedSdkLongUpDownCounter.ExtendedSdkLongUpDownCounterBuilder(sdkMeter, name); + } + + static DoubleHistogramBuilder createExtendedDoubleHistogramBuilder( + SdkMeter sdkMeter, String name) { + return new ExtendedSdkDoubleHistogram.ExtendedSdkDoubleHistogramBuilder(sdkMeter, name); + } + + static DoubleGaugeBuilder createExtendedDoubleGaugeBuilder(SdkMeter sdkMeter, String name) { + return new ExtendedSdkDoubleGauge.ExtendedSdkDoubleGaugeBuilder(sdkMeter, name); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentBuilder.java new file mode 100644 index 00000000000..14fd54d7bd1 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentBuilder.java @@ -0,0 +1,131 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; +import io.opentelemetry.api.metrics.ObservableLongMeasurement; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.CallbackRegistration; +import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.Collections; +import java.util.List; +import java.util.function.Consumer; + +/** Helper to make implementing builders easier. */ +final class InstrumentBuilder { + + private final String name; + private final SdkMeter sdkMeter; + private final InstrumentValueType valueType; + private InstrumentType type; + private Advice.AdviceBuilder adviceBuilder = Advice.builder(); + private String description = ""; + private String unit = ""; + + InstrumentBuilder( + String name, InstrumentType type, InstrumentValueType valueType, SdkMeter sdkMeter) { + this.name = name; + this.type = type; + this.valueType = valueType; + this.sdkMeter = sdkMeter; + } + + InstrumentBuilder setUnit(String unit) { + this.unit = unit; + return this; + } + + InstrumentBuilder setAdviceBuilder(Advice.AdviceBuilder adviceBuilder) { + this.adviceBuilder = adviceBuilder; + return this; + } + + InstrumentBuilder setDescription(String description) { + this.description = description; + return this; + } + + T swapBuilder(SwapBuilder swapper) { + return swapper.newBuilder(sdkMeter, name, description, unit, adviceBuilder); + } + + @FunctionalInterface + interface SynchronousInstrumentConstructor { + + I createInstrument( + InstrumentDescriptor instrumentDescriptor, + SdkMeter sdkMeter, + WriteableMetricStorage storage); + } + + I buildSynchronousInstrument( + SynchronousInstrumentConstructor instrumentFactory) { + InstrumentDescriptor descriptor = newDescriptor(); + WriteableMetricStorage storage = sdkMeter.registerSynchronousMetricStorage(descriptor); + return instrumentFactory.createInstrument(descriptor, sdkMeter, storage); + } + + SdkObservableInstrument buildDoubleAsynchronousInstrument( + InstrumentType type, Consumer updater) { + SdkObservableMeasurement sdkObservableMeasurement = buildObservableMeasurement(type); + Runnable runnable = () -> updater.accept(sdkObservableMeasurement); + CallbackRegistration callbackRegistration = + CallbackRegistration.create(Collections.singletonList(sdkObservableMeasurement), runnable); + sdkMeter.registerCallback(callbackRegistration); + return new SdkObservableInstrument(sdkMeter, callbackRegistration); + } + + SdkObservableInstrument buildLongAsynchronousInstrument( + InstrumentType type, Consumer updater) { + SdkObservableMeasurement sdkObservableMeasurement = buildObservableMeasurement(type); + Runnable runnable = () -> updater.accept(sdkObservableMeasurement); + CallbackRegistration callbackRegistration = + CallbackRegistration.create(Collections.singletonList(sdkObservableMeasurement), runnable); + sdkMeter.registerCallback(callbackRegistration); + return new SdkObservableInstrument(sdkMeter, callbackRegistration); + } + + SdkObservableMeasurement buildObservableMeasurement(InstrumentType type) { + this.type = type; + InstrumentDescriptor descriptor = newDescriptor(); + return sdkMeter.registerObservableMeasurement(descriptor); + } + + private InstrumentDescriptor newDescriptor() { + return InstrumentDescriptor.create( + name, description, unit, type, valueType, adviceBuilder.build()); + } + + @Override + public String toString() { + return toStringHelper(getClass().getSimpleName()); + } + + String toStringHelper(String className) { + return className + "{descriptor=" + newDescriptor() + "}"; + } + + @FunctionalInterface + interface SwapBuilder { + T newBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder); + } + + void setAdviceAttributes(List> attributes) { + adviceBuilder.setAttributes(attributes); + } + + void setExplicitBucketBoundaries(List bucketBoundaries) { + adviceBuilder.setExplicitBucketBoundaries(bucketBoundaries); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelector.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelector.java index 5d8dce9a21e..f87eec70633 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelector.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelector.java @@ -11,8 +11,14 @@ import javax.annotation.concurrent.Immutable; /** - * Provides means for selecting one or more instruments. Used for configuring aggregations for the - * specified instruments. + * Instrument selection criteria for applying {@link View}s registered via {@link + * SdkMeterProviderBuilder#registerView(InstrumentSelector, View)}. + * + *

      Properties are ANDed together. For example, if {@link #getInstrumentName()} is + * "http.server.duration" and {@link #getMeterName()} is "my.http.meter", then instruments are + * selected where name is "http.server.duration" AND meter name is "my.http.meter". + * + * @since 1.14.0 */ @AutoValue @Immutable @@ -26,24 +32,22 @@ public static InstrumentSelectorBuilder builder() { static InstrumentSelector create( @Nullable InstrumentType instrumentType, @Nullable String instrumentName, + @Nullable String instrumentUnit, @Nullable String meterName, @Nullable String meterVersion, @Nullable String meterSchemaUrl) { return new AutoValue_InstrumentSelector( - instrumentType, instrumentName, meterName, meterVersion, meterSchemaUrl); + instrumentType, instrumentName, instrumentUnit, meterName, meterVersion, meterSchemaUrl); } InstrumentSelector() {} - /** - * Returns selection criteria for {@link InstrumentType}. If null, select instruments with any - * type. - */ + /** Returns the selected {@link InstrumentType}, or null if this selects all instrument types. */ @Nullable public abstract InstrumentType getInstrumentType(); /** - * Returns the selection criteria for instrument name. If null, select instruments with any name. + * Returns the selected instrument name, or null if this selects all instrument names. * *

      Instrument name may contain the wildcard characters {@code *} and {@code ?} with the * following matching criteria: @@ -57,22 +61,27 @@ static InstrumentSelector create( public abstract String getInstrumentName(); /** - * Returns the selection criteria for meter name. If null, select instruments from meters with any - * name. + * Returns the selected instrument unit, or null if this selects all instrument units. + * + * @since 1.24.0 */ @Nullable + public abstract String getInstrumentUnit(); + + /** Returns the selected meter name, or null if this selects instruments from all meter names. */ + @Nullable public abstract String getMeterName(); /** - * Returns the selection criteria for meter version. If null, select instruments from meters with - * any version. + * Returns the selected meter version, or null if this selects instruments from all meter + * versions. */ @Nullable public abstract String getMeterVersion(); /** - * Returns the selection criteria for meter schema url. If null, select instruments from meters - * with any schema url. + * Returns the selected meter schema url, or null if this selects instruments from all meter + * schema urls. */ @Nullable public abstract String getMeterSchemaUrl(); @@ -86,6 +95,9 @@ public final String toString() { if (getInstrumentName() != null) { joiner.add("instrumentName=" + getInstrumentName()); } + if (getInstrumentUnit() != null) { + joiner.add("instrumentUnit=" + getInstrumentUnit()); + } if (getMeterName() != null) { joiner.add("meterName=" + getMeterName()); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelectorBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelectorBuilder.java index d37c2aaf38d..ae0b548fb8e 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelectorBuilder.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentSelectorBuilder.java @@ -10,18 +10,23 @@ import javax.annotation.Nullable; -/** Builder for {@link InstrumentSelector}. */ +/** + * Builder for {@link InstrumentSelector}. + * + * @since 1.14.0 + */ public final class InstrumentSelectorBuilder { @Nullable private InstrumentType instrumentType; @Nullable private String instrumentName; + @Nullable private String instrumentUnit; @Nullable private String meterName; @Nullable private String meterVersion; @Nullable private String meterSchemaUrl; InstrumentSelectorBuilder() {} - /** Sets a specifier for {@link InstrumentType}. */ + /** Select instruments with the given {@code instrumentType}. */ public InstrumentSelectorBuilder setType(InstrumentType instrumentType) { requireNonNull(instrumentType, "instrumentType"); this.instrumentType = instrumentType; @@ -29,7 +34,7 @@ public InstrumentSelectorBuilder setType(InstrumentType instrumentType) { } /** - * Sets the exact instrument name that will be selected. + * Select instruments with the given {@code name}. * *

      Instrument name may contain the wildcard characters {@code *} and {@code ?} with the * following matching criteria: @@ -46,45 +51,48 @@ public InstrumentSelectorBuilder setName(String name) { } /** - * Sets a specifier for selecting instruments by the name of their associated {@link - * io.opentelemetry.api.metrics.Meter}. + * Select instruments with the given {@code unit}. + * + * @since 1.24.0 */ + public InstrumentSelectorBuilder setUnit(String unit) { + requireNonNull(unit, "unit"); + this.instrumentUnit = unit; + return this; + } + + /** Select instruments associated with the given {@code meterName}. */ public InstrumentSelectorBuilder setMeterName(String meterName) { requireNonNull(meterName, "meterName"); this.meterName = meterName; return this; } - /** - * Sets a specifier for selecting instruments by the version of their associated {@link - * io.opentelemetry.api.metrics.Meter}. - */ + /** Select instruments associated with the given {@code meterVersion}. */ public InstrumentSelectorBuilder setMeterVersion(String meterVersion) { requireNonNull(meterVersion, "meterVersion"); this.meterVersion = meterVersion; return this; } - /** - * Sets a specifier for selecting instruments by the schema URL of their associated {@link - * io.opentelemetry.api.metrics.Meter}. - */ + /** Select instruments associated with the given {@code meterSchemaUrl}. */ public InstrumentSelectorBuilder setMeterSchemaUrl(String meterSchemaUrl) { requireNonNull(meterSchemaUrl, "meterSchemaUrl"); this.meterSchemaUrl = meterSchemaUrl; return this; } - /** Returns an InstrumentSelector instance with the content of this builder. */ + /** Returns an {@link InstrumentSelector} with the configuration of this builder. */ public InstrumentSelector build() { checkArgument( instrumentType != null || instrumentName != null + || instrumentUnit != null || meterName != null || meterVersion != null || meterSchemaUrl != null, "Instrument selector must contain selection criteria"); return InstrumentSelector.create( - instrumentType, instrumentName, meterName, meterVersion, meterSchemaUrl); + instrumentType, instrumentName, instrumentUnit, meterName, meterVersion, meterSchemaUrl); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentType.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentType.java index b19bad273cf..6b87ce20c9c 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentType.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentType.java @@ -5,7 +5,12 @@ package io.opentelemetry.sdk.metrics; -/** All instrument types available in the metric package. */ +/** + * All possible instrument types. + * + * @since 1.14.0 + */ +@SuppressWarnings({"MissingSummary", "SummaryJavadoc"}) public enum InstrumentType { COUNTER, UP_DOWN_COUNTER, @@ -13,4 +18,8 @@ public enum InstrumentType { OBSERVABLE_COUNTER, OBSERVABLE_UP_DOWN_COUNTER, OBSERVABLE_GAUGE, + /** + * @since 1.38.0 + */ + GAUGE, } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentValueType.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentValueType.java index 0af86c90548..c21e0a95656 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentValueType.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/InstrumentValueType.java @@ -5,7 +5,11 @@ package io.opentelemetry.sdk.metrics; -/** All possible types for the values recorded via the instruments. */ +/** + * All possible measurement value types. + * + * @since 1.14.0 + */ public enum InstrumentValueType { LONG, DOUBLE, diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleCounter.java index 2f8fc2ed69c..95e4f8a3478 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleCounter.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleCounter.java @@ -11,36 +11,36 @@ import io.opentelemetry.api.metrics.ObservableDoubleCounter; import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundDoubleCounter; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; -final class SdkDoubleCounter extends AbstractInstrument implements DoubleCounter { +class SdkDoubleCounter extends AbstractInstrument implements DoubleCounter { private static final Logger logger = Logger.getLogger(SdkDoubleCounter.class.getName()); private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final WriteableMetricStorage storage; + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; - private SdkDoubleCounter(InstrumentDescriptor descriptor, WriteableMetricStorage storage) { - super(descriptor); + SdkDoubleCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; this.storage = storage; } + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + @Override public void add(double increment, Attributes attributes, Context context) { - if (increment < 0) { - throttlingLogger.log( - Level.WARNING, - "Counters can only increase. Instrument " - + getDescriptor().getName() - + " has recorded a negative value."); + if (!validateNonNegative(increment)) { return; } storage.recordDouble(increment, attributes, context); @@ -48,7 +48,7 @@ public void add(double increment, Attributes attributes, Context context) { @Override public void add(double increment, Attributes attributes) { - add(increment, attributes, Context.current()); + add(increment, attributes, currentOrRootContext()); } @Override @@ -56,82 +56,70 @@ public void add(double increment) { add(increment, Attributes.empty()); } - BoundDoubleCounter bind(Attributes attributes) { - return new BoundInstrument(getDescriptor(), storage.bind(attributes), attributes); + /** + * Returns true if {@code increment} is non-negative, otherwise logs a warning and returns false. + * Shared by the unbound and bound ({@link ExtendedSdkDoubleCounter}) record paths. + */ + boolean validateNonNegative(double increment) { + if (increment < 0) { + throttlingLogger.log( + Level.WARNING, + "Counters can only increase. Instrument " + + getDescriptor().getName() + + " has recorded a negative value."); + return false; + } + return true; } - static final class BoundInstrument implements BoundDoubleCounter { - private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final InstrumentDescriptor descriptor; - private final BoundStorageHandle handle; - private final Attributes attributes; - - BoundInstrument( - InstrumentDescriptor descriptor, BoundStorageHandle handle, Attributes attributes) { - this.descriptor = descriptor; - this.handle = handle; - this.attributes = attributes; - } + static class SdkDoubleCounterBuilder implements DoubleCounterBuilder { - @Override - public void add(double increment, Context context) { - if (increment < 0) { - throttlingLogger.log( - Level.WARNING, - "Counters can only increase. Instrument " - + descriptor.getName() - + " has recorded a negative value."); - return; - } - handle.recordDouble(increment, attributes, context); - } + final InstrumentBuilder builder; - @Override - public void add(double increment) { - add(increment, Context.current()); + SdkDoubleCounterBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + this.builder = + new InstrumentBuilder(name, InstrumentType.COUNTER, InstrumentValueType.DOUBLE, sdkMeter) + .setUnit(unit) + .setDescription(description) + .setAdviceBuilder(adviceBuilder); } @Override - public void unbind() { - handle.release(); - } - } - - static final class Builder extends AbstractInstrumentBuilder - implements DoubleCounterBuilder { - - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); + public SdkDoubleCounter build() { + return builder.buildSynchronousInstrument(SdkDoubleCounter::new); } @Override - protected Builder getThis() { + public DoubleCounterBuilder setDescription(String description) { + builder.setDescription(description); return this; } @Override - public SdkDoubleCounter build() { - return buildSynchronousInstrument( - InstrumentType.COUNTER, InstrumentValueType.DOUBLE, SdkDoubleCounter::new); + public DoubleCounterBuilder setUnit(String unit) { + builder.setUnit(unit); + return this; } @Override public ObservableDoubleCounter buildWithCallback( Consumer callback) { - return new SdkObservableInstrument( - meterSharedState, - registerDoubleAsynchronousInstrument(InstrumentType.OBSERVABLE_COUNTER, callback)); + return builder.buildDoubleAsynchronousInstrument(InstrumentType.OBSERVABLE_COUNTER, callback); } @Override public ObservableDoubleMeasurement buildObserver() { - return buildObservableMeasurement( - InstrumentType.OBSERVABLE_COUNTER, InstrumentValueType.DOUBLE); + return builder.buildObservableMeasurement(InstrumentType.OBSERVABLE_COUNTER); + } + + @Override + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleGauge.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleGauge.java new file mode 100644 index 00000000000..513e3cd55c8 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleGauge.java @@ -0,0 +1,96 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleGauge; +import io.opentelemetry.api.metrics.DoubleGaugeBuilder; +import io.opentelemetry.api.metrics.LongGaugeBuilder; +import io.opentelemetry.api.metrics.ObservableDoubleGauge; +import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.function.Consumer; + +class SdkDoubleGauge extends AbstractInstrument implements DoubleGauge { + + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; + + SdkDoubleGauge( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; + this.storage = storage; + } + + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + + @Override + public void set(double value, Attributes attributes) { + storage.recordDouble(value, attributes, currentOrRootContext()); + } + + @Override + public void set(double value, Attributes attributes, Context context) { + storage.recordDouble(value, attributes, context); + } + + @Override + public void set(double value) { + set(value, Attributes.empty()); + } + + static class SdkDoubleGaugeBuilder implements DoubleGaugeBuilder { + final InstrumentBuilder builder; + + SdkDoubleGaugeBuilder(SdkMeter sdkMeter, String name) { + builder = + new InstrumentBuilder(name, InstrumentType.GAUGE, InstrumentValueType.DOUBLE, sdkMeter); + } + + @Override + public DoubleGaugeBuilder setDescription(String description) { + builder.setDescription(description); + return this; + } + + @Override + public DoubleGaugeBuilder setUnit(String unit) { + builder.setUnit(unit); + return this; + } + + @Override + public SdkDoubleGauge build() { + return builder.buildSynchronousInstrument(SdkDoubleGauge::new); + } + + @Override + public LongGaugeBuilder ofLongs() { + return builder.swapBuilder(SdkLongGauge.SdkLongGaugeBuilder::new); + } + + @Override + public ObservableDoubleGauge buildWithCallback(Consumer callback) { + return builder.buildDoubleAsynchronousInstrument(InstrumentType.OBSERVABLE_GAUGE, callback); + } + + @Override + public ObservableDoubleMeasurement buildObserver() { + return builder.buildObservableMeasurement(InstrumentType.OBSERVABLE_GAUGE); + } + + @Override + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeBuilder.java deleted file mode 100644 index 2c2066f8877..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeBuilder.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import io.opentelemetry.api.metrics.DoubleGaugeBuilder; -import io.opentelemetry.api.metrics.LongGaugeBuilder; -import io.opentelemetry.api.metrics.ObservableDoubleGauge; -import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; -import java.util.function.Consumer; - -final class SdkDoubleGaugeBuilder extends AbstractInstrumentBuilder - implements DoubleGaugeBuilder { - - SdkDoubleGaugeBuilder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState meterSharedState, - String name) { - this(meterProviderSharedState, meterSharedState, name, "", DEFAULT_UNIT); - } - - SdkDoubleGaugeBuilder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); - } - - @Override - protected SdkDoubleGaugeBuilder getThis() { - return this; - } - - @Override - public LongGaugeBuilder ofLongs() { - return swapBuilder(SdkLongGaugeBuilder::new); - } - - @Override - public ObservableDoubleGauge buildWithCallback(Consumer callback) { - return new SdkObservableInstrument( - meterSharedState, - registerDoubleAsynchronousInstrument(InstrumentType.OBSERVABLE_GAUGE, callback)); - } - - @Override - public ObservableDoubleMeasurement buildObserver() { - return buildObservableMeasurement(InstrumentType.OBSERVABLE_GAUGE, InstrumentValueType.DOUBLE); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogram.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogram.java index 59cdfba372a..fb1e868c056 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogram.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogram.java @@ -10,35 +10,37 @@ import io.opentelemetry.api.metrics.DoubleHistogramBuilder; import io.opentelemetry.api.metrics.LongHistogramBuilder; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundDoubleHistogram; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; -final class SdkDoubleHistogram extends AbstractInstrument implements DoubleHistogram { +class SdkDoubleHistogram extends AbstractInstrument implements DoubleHistogram { private static final Logger logger = Logger.getLogger(SdkDoubleHistogram.class.getName()); private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final WriteableMetricStorage storage; + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; - private SdkDoubleHistogram(InstrumentDescriptor descriptor, WriteableMetricStorage storage) { - super(descriptor); + SdkDoubleHistogram( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; this.storage = storage; } + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + @Override public void record(double value, Attributes attributes, Context context) { - if (value < 0) { - throttlingLogger.log( - Level.WARNING, - "Histograms can only record non-negative values. Instrument " - + getDescriptor().getName() - + " has recorded a negative value."); + if (!validateNonNegative(value)) { return; } storage.recordDouble(value, attributes, context); @@ -46,7 +48,7 @@ public void record(double value, Attributes attributes, Context context) { @Override public void record(double value, Attributes attributes) { - record(value, attributes, Context.current()); + record(value, attributes, currentOrRootContext()); } @Override @@ -54,80 +56,70 @@ public void record(double value) { record(value, Attributes.empty()); } - BoundDoubleHistogram bind(Attributes attributes) { - return new BoundInstrument(getDescriptor(), storage.bind(attributes), attributes); + /** + * Returns true if {@code value} is non-negative, otherwise logs a warning and returns false. + * Shared by the unbound and bound ({@link ExtendedSdkDoubleHistogram}) record paths. + */ + boolean validateNonNegative(double value) { + if (value < 0) { + throttlingLogger.log( + Level.WARNING, + "Histograms can only record non-negative values. Instrument " + + getDescriptor().getName() + + " has recorded a negative value."); + return false; + } + return true; } - static final class BoundInstrument implements BoundDoubleHistogram { - private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final InstrumentDescriptor descriptor; - private final BoundStorageHandle aggregatorHandle; - private final Attributes attributes; - - BoundInstrument( - InstrumentDescriptor descriptor, BoundStorageHandle handle, Attributes attributes) { - this.descriptor = descriptor; - this.aggregatorHandle = handle; - this.attributes = attributes; - } + static class SdkDoubleHistogramBuilder implements DoubleHistogramBuilder { - @Override - public void record(double value, Context context) { - if (value < 0) { - throttlingLogger.log( - Level.WARNING, - "Histograms can only record non-negative values. Instrument " - + descriptor.getName() - + " has recorded a negative value."); - return; - } - aggregatorHandle.recordDouble(value, attributes, context); - } + final InstrumentBuilder builder; - @Override - public void record(double value) { - record(value, Context.current()); + SdkDoubleHistogramBuilder(SdkMeter sdkMeter, String name) { + builder = + new InstrumentBuilder( + name, InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE, sdkMeter); } @Override - public void unbind() { - aggregatorHandle.release(); + public DoubleHistogramBuilder setDescription(String description) { + builder.setDescription(description); + return this; } - } - - static final class Builder extends AbstractInstrumentBuilder - implements DoubleHistogramBuilder { - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState meterSharedState, - String name) { - this(meterProviderSharedState, meterSharedState, name, "", DEFAULT_UNIT); + @Override + public DoubleHistogramBuilder setUnit(String unit) { + builder.setUnit(unit); + return this; } - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); + @Override + public SdkDoubleHistogram build() { + return builder.buildSynchronousInstrument(SdkDoubleHistogram::new); } @Override - protected Builder getThis() { - return this; + public LongHistogramBuilder ofLongs() { + return builder.swapBuilder(SdkLongHistogram.SdkLongHistogramBuilder::new); } @Override - public SdkDoubleHistogram build() { - return buildSynchronousInstrument( - InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE, SdkDoubleHistogram::new); + public DoubleHistogramBuilder setExplicitBucketBoundariesAdvice(List bucketBoundaries) { + try { + Objects.requireNonNull(bucketBoundaries, "bucketBoundaries must not be null"); + ExplicitBucketHistogramUtils.validateBucketBoundaries(bucketBoundaries); + } catch (IllegalArgumentException | NullPointerException e) { + logger.log(Level.WARNING, "Error setting explicit bucket boundaries advice", e); + return this; + } + builder.setExplicitBucketBoundaries(bucketBoundaries); + return this; } @Override - public LongHistogramBuilder ofLongs() { - return swapBuilder(SdkLongHistogram.Builder::new); + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounter.java index 5f80efa36fa..7a0603c80f9 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounter.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounter.java @@ -11,23 +11,28 @@ import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; import io.opentelemetry.api.metrics.ObservableDoubleUpDownCounter; import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundDoubleUpDownCounter; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; import java.util.function.Consumer; -final class SdkDoubleUpDownCounter extends AbstractInstrument implements DoubleUpDownCounter { +class SdkDoubleUpDownCounter extends AbstractInstrument implements DoubleUpDownCounter { - private final WriteableMetricStorage storage; + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; - private SdkDoubleUpDownCounter(InstrumentDescriptor descriptor, WriteableMetricStorage storage) { - super(descriptor); + SdkDoubleUpDownCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; this.storage = storage; } + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + @Override public void add(double increment, Attributes attributes, Context context) { storage.recordDouble(increment, attributes, context); @@ -35,7 +40,7 @@ public void add(double increment, Attributes attributes, Context context) { @Override public void add(double increment, Attributes attributes) { - add(increment, attributes, Context.current()); + add(increment, attributes, currentOrRootContext()); } @Override @@ -43,71 +48,56 @@ public void add(double increment) { add(increment, Attributes.empty()); } - BoundDoubleUpDownCounter bind(Attributes attributes) { - return new BoundInstrument(storage.bind(attributes), attributes); - } - - static final class BoundInstrument implements BoundDoubleUpDownCounter { - private final BoundStorageHandle handle; - private final Attributes attributes; + static class SdkDoubleUpDownCounterBuilder implements DoubleUpDownCounterBuilder { - BoundInstrument(BoundStorageHandle handle, Attributes attributes) { - this.handle = handle; - this.attributes = attributes; - } + final InstrumentBuilder builder; - @Override - public void add(double increment, Context context) { - handle.recordDouble(increment, attributes, context); - } - - @Override - public void add(double increment) { - add(increment, Context.current()); + SdkDoubleUpDownCounterBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + this.builder = + new InstrumentBuilder( + name, InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.DOUBLE, sdkMeter) + .setDescription(description) + .setUnit(unit) + .setAdviceBuilder(adviceBuilder); } @Override - public void unbind() { - handle.release(); - } - } - - static final class Builder extends AbstractInstrumentBuilder - implements DoubleUpDownCounterBuilder { - - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); + public DoubleUpDownCounterBuilder setDescription(String description) { + builder.setDescription(description); + return this; } @Override - protected Builder getThis() { + public DoubleUpDownCounterBuilder setUnit(String unit) { + builder.setUnit(unit); return this; } @Override public DoubleUpDownCounter build() { - return buildSynchronousInstrument( - InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.DOUBLE, SdkDoubleUpDownCounter::new); + return builder.buildSynchronousInstrument(SdkDoubleUpDownCounter::new); } @Override public ObservableDoubleUpDownCounter buildWithCallback( Consumer callback) { - return new SdkObservableInstrument( - meterSharedState, - registerDoubleAsynchronousInstrument( - InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, callback)); + return builder.buildDoubleAsynchronousInstrument( + InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, callback); } @Override public ObservableDoubleMeasurement buildObserver() { - return buildObservableMeasurement( - InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, InstrumentValueType.DOUBLE); + return builder.buildObservableMeasurement(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER); + } + + @Override + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongCounter.java index 7fdeaaff9b8..cf6f1ee08fd 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongCounter.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongCounter.java @@ -12,37 +12,36 @@ import io.opentelemetry.api.metrics.ObservableLongCounter; import io.opentelemetry.api.metrics.ObservableLongMeasurement; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundLongCounter; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; import java.util.function.Consumer; import java.util.logging.Level; import java.util.logging.Logger; -final class SdkLongCounter extends AbstractInstrument implements LongCounter { +class SdkLongCounter extends AbstractInstrument implements LongCounter { private static final Logger logger = Logger.getLogger(SdkLongCounter.class.getName()); private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final WriteableMetricStorage storage; + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; - private SdkLongCounter(InstrumentDescriptor descriptor, WriteableMetricStorage storage) { - super(descriptor); + SdkLongCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; this.storage = storage; } + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + @Override public void add(long increment, Attributes attributes, Context context) { - if (increment < 0) { - throttlingLogger.log( - Level.WARNING, - "Counters can only increase. Instrument " - + getDescriptor().getName() - + " has recorded a negative value."); + if (!validateNonNegative(increment)) { return; } storage.recordLong(increment, attributes, context); @@ -50,7 +49,7 @@ public void add(long increment, Attributes attributes, Context context) { @Override public void add(long increment, Attributes attributes) { - add(increment, attributes, Context.current()); + add(increment, attributes, currentOrRootContext()); } @Override @@ -58,93 +57,66 @@ public void add(long increment) { add(increment, Attributes.empty()); } - BoundLongCounter bind(Attributes attributes) { - return new BoundInstrument(getDescriptor(), storage.bind(attributes), attributes); + /** + * Returns true if {@code increment} is non-negative, otherwise logs a warning and returns false. + * Shared by the unbound and bound ({@link ExtendedSdkLongCounter}) record paths. + */ + boolean validateNonNegative(long increment) { + if (increment < 0) { + throttlingLogger.log( + Level.WARNING, + "Counters can only increase. Instrument " + + getDescriptor().getName() + + " has recorded a negative value."); + return false; + } + return true; } - static final class BoundInstrument implements BoundLongCounter { - private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final InstrumentDescriptor descriptor; - private final BoundStorageHandle handle; - private final Attributes attributes; - - BoundInstrument( - InstrumentDescriptor descriptor, BoundStorageHandle handle, Attributes attributes) { - this.descriptor = descriptor; - this.handle = handle; - this.attributes = attributes; - } + static class SdkLongCounterBuilder implements LongCounterBuilder { - @Override - public void add(long increment, Context context) { - if (increment < 0) { - throttlingLogger.log( - Level.WARNING, - "Counters can only increase. Instrument " - + descriptor.getName() - + " has recorded a negative value."); - return; - } - handle.recordLong(increment, attributes, context); - } + final InstrumentBuilder builder; - @Override - public void add(long increment) { - add(increment, Context.current()); + SdkLongCounterBuilder(SdkMeter sdkMeter, String name) { + this.builder = + new InstrumentBuilder(name, InstrumentType.COUNTER, InstrumentValueType.LONG, sdkMeter); } @Override - public void unbind() { - handle.release(); - } - } - - static final class Builder extends AbstractInstrumentBuilder - implements LongCounterBuilder { - - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState meterSharedState, - String name) { - this(meterProviderSharedState, meterSharedState, name, "", DEFAULT_UNIT); - } - - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); + public LongCounterBuilder setDescription(String description) { + builder.setDescription(description); + return this; } @Override - protected Builder getThis() { + public LongCounterBuilder setUnit(String unit) { + builder.setUnit(unit); return this; } @Override public SdkLongCounter build() { - return buildSynchronousInstrument( - InstrumentType.COUNTER, InstrumentValueType.LONG, SdkLongCounter::new); + return builder.buildSynchronousInstrument(SdkLongCounter::new); } @Override public DoubleCounterBuilder ofDoubles() { - return swapBuilder(SdkDoubleCounter.Builder::new); + return builder.swapBuilder(SdkDoubleCounter.SdkDoubleCounterBuilder::new); } @Override public ObservableLongCounter buildWithCallback(Consumer callback) { - return new SdkObservableInstrument( - meterSharedState, - registerLongAsynchronousInstrument(InstrumentType.OBSERVABLE_COUNTER, callback)); + return builder.buildLongAsynchronousInstrument(InstrumentType.OBSERVABLE_COUNTER, callback); } @Override public ObservableLongMeasurement buildObserver() { - return buildObservableMeasurement( - InstrumentType.OBSERVABLE_COUNTER, InstrumentValueType.LONG); + return builder.buildObservableMeasurement(InstrumentType.OBSERVABLE_COUNTER); + } + + @Override + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongGauge.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongGauge.java new file mode 100644 index 00000000000..2cf3c9f3696 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongGauge.java @@ -0,0 +1,99 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongGauge; +import io.opentelemetry.api.metrics.LongGaugeBuilder; +import io.opentelemetry.api.metrics.ObservableLongGauge; +import io.opentelemetry.api.metrics.ObservableLongMeasurement; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.function.Consumer; + +class SdkLongGauge extends AbstractInstrument implements LongGauge { + + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; + + SdkLongGauge(InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; + this.storage = storage; + } + + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + + @Override + public void set(long value, Attributes attributes) { + storage.recordLong(value, attributes, currentOrRootContext()); + } + + @Override + public void set(long value, Attributes attributes, Context context) { + storage.recordLong(value, attributes, context); + } + + @Override + public void set(long value) { + set(value, Attributes.empty()); + } + + static class SdkLongGaugeBuilder implements LongGaugeBuilder { + + final InstrumentBuilder builder; + + SdkLongGaugeBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + builder = + new InstrumentBuilder(name, InstrumentType.GAUGE, InstrumentValueType.LONG, sdkMeter) + .setDescription(description) + .setUnit(unit) + .setAdviceBuilder(adviceBuilder); + } + + @Override + public LongGaugeBuilder setDescription(String description) { + builder.setDescription(description); + return this; + } + + @Override + public LongGaugeBuilder setUnit(String unit) { + builder.setUnit(unit); + return this; + } + + @Override + public SdkLongGauge build() { + return builder.buildSynchronousInstrument(SdkLongGauge::new); + } + + @Override + public ObservableLongGauge buildWithCallback(Consumer callback) { + return builder.buildLongAsynchronousInstrument(InstrumentType.OBSERVABLE_GAUGE, callback); + } + + @Override + public ObservableLongMeasurement buildObserver() { + return builder.buildObservableMeasurement(InstrumentType.OBSERVABLE_GAUGE); + } + + @Override + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongGaugeBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongGaugeBuilder.java deleted file mode 100644 index add7ea7bd47..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongGaugeBuilder.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import io.opentelemetry.api.metrics.LongGaugeBuilder; -import io.opentelemetry.api.metrics.ObservableLongGauge; -import io.opentelemetry.api.metrics.ObservableLongMeasurement; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; -import java.util.function.Consumer; - -final class SdkLongGaugeBuilder extends AbstractInstrumentBuilder - implements LongGaugeBuilder { - - SdkLongGaugeBuilder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); - } - - @Override - protected SdkLongGaugeBuilder getThis() { - return this; - } - - @Override - public ObservableLongGauge buildWithCallback(Consumer callback) { - return new SdkObservableInstrument( - meterSharedState, - registerLongAsynchronousInstrument(InstrumentType.OBSERVABLE_GAUGE, callback)); - } - - @Override - public ObservableLongMeasurement buildObserver() { - return buildObservableMeasurement(InstrumentType.OBSERVABLE_GAUGE, InstrumentValueType.LONG); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongHistogram.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongHistogram.java index 1efb1644f9d..20641857ce6 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongHistogram.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongHistogram.java @@ -9,35 +9,39 @@ import io.opentelemetry.api.metrics.LongHistogram; import io.opentelemetry.api.metrics.LongHistogramBuilder; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; +import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundLongHistogram; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import java.util.List; +import java.util.Objects; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.stream.Collectors; -final class SdkLongHistogram extends AbstractInstrument implements LongHistogram { +class SdkLongHistogram extends AbstractInstrument implements LongHistogram { private static final Logger logger = Logger.getLogger(SdkLongHistogram.class.getName()); private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final WriteableMetricStorage storage; + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; - private SdkLongHistogram(InstrumentDescriptor descriptor, WriteableMetricStorage storage) { - super(descriptor); + SdkLongHistogram( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; this.storage = storage; } + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + @Override public void record(long value, Attributes attributes, Context context) { - if (value < 0) { - throttlingLogger.log( - Level.WARNING, - "Histograms can only record non-negative values. Instrument " - + getDescriptor().getName() - + " has recorded a negative value."); + if (!validateNonNegative(value)) { return; } storage.recordLong(value, attributes, context); @@ -45,7 +49,7 @@ public void record(long value, Attributes attributes, Context context) { @Override public void record(long value, Attributes attributes) { - record(value, attributes, Context.current()); + record(value, attributes, currentOrRootContext()); } @Override @@ -53,68 +57,74 @@ public void record(long value) { record(value, Attributes.empty()); } - BoundLongHistogram bind(Attributes attributes) { - return new BoundInstrument(getDescriptor(), storage.bind(attributes), attributes); + /** + * Returns true if {@code value} is non-negative, otherwise logs a warning and returns false. + * Shared by the unbound and bound ({@link ExtendedSdkLongHistogram}) record paths. + */ + boolean validateNonNegative(long value) { + if (value < 0) { + throttlingLogger.log( + Level.WARNING, + "Histograms can only record non-negative values. Instrument " + + getDescriptor().getName() + + " has recorded a negative value."); + return false; + } + return true; } - static final class BoundInstrument implements BoundLongHistogram { - private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final InstrumentDescriptor descriptor; - private final BoundStorageHandle handle; - private final Attributes attributes; - - BoundInstrument( - InstrumentDescriptor descriptor, BoundStorageHandle handle, Attributes attributes) { - this.descriptor = descriptor; - this.handle = handle; - this.attributes = attributes; - } + static class SdkLongHistogramBuilder implements LongHistogramBuilder { - @Override - public void record(long value, Context context) { - if (value < 0) { - throttlingLogger.log( - Level.WARNING, - "Histograms can only record non-negative values. Instrument " - + descriptor.getName() - + " has recorded a negative value."); - return; - } - handle.recordLong(value, attributes, context); + final InstrumentBuilder builder; + + SdkLongHistogramBuilder( + SdkMeter sdkMeter, + String name, + String description, + String unit, + Advice.AdviceBuilder adviceBuilder) { + builder = + new InstrumentBuilder(name, InstrumentType.HISTOGRAM, InstrumentValueType.LONG, sdkMeter) + .setDescription(description) + .setUnit(unit) + .setAdviceBuilder(adviceBuilder); } @Override - public void record(long value) { - record(value, Context.current()); + public LongHistogramBuilder setDescription(String description) { + builder.setDescription(description); + return this; } @Override - public void unbind() { - handle.release(); + public LongHistogramBuilder setUnit(String unit) { + builder.setUnit(unit); + return this; } - } - - static final class Builder extends AbstractInstrumentBuilder - implements LongHistogramBuilder { - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); + @Override + public SdkLongHistogram build() { + return builder.buildSynchronousInstrument(SdkLongHistogram::new); } @Override - protected Builder getThis() { + public LongHistogramBuilder setExplicitBucketBoundariesAdvice(List bucketBoundaries) { + List boundaries; + try { + Objects.requireNonNull(bucketBoundaries, "bucketBoundaries must not be null"); + boundaries = bucketBoundaries.stream().map(Long::doubleValue).collect(Collectors.toList()); + ExplicitBucketHistogramUtils.validateBucketBoundaries(boundaries); + } catch (IllegalArgumentException | NullPointerException e) { + logger.log(Level.WARNING, "Error setting explicit bucket boundaries advice", e); + return this; + } + builder.setExplicitBucketBoundaries(boundaries); return this; } @Override - public SdkLongHistogram build() { - return buildSynchronousInstrument( - InstrumentType.HISTOGRAM, InstrumentValueType.LONG, SdkLongHistogram::new); + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounter.java index b9922182b3a..497f7f973fa 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounter.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounter.java @@ -13,22 +13,26 @@ import io.opentelemetry.api.metrics.ObservableLongUpDownCounter; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundLongUpDownCounter; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; -import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; import java.util.function.Consumer; -final class SdkLongUpDownCounter extends AbstractInstrument implements LongUpDownCounter { +class SdkLongUpDownCounter extends AbstractInstrument implements LongUpDownCounter { - private final WriteableMetricStorage storage; + final SdkMeter sdkMeter; + final WriteableMetricStorage storage; - private SdkLongUpDownCounter(InstrumentDescriptor descriptor, WriteableMetricStorage storage) { - super(descriptor); + SdkLongUpDownCounter( + InstrumentDescriptor descriptor, SdkMeter sdkMeter, WriteableMetricStorage storage) { + super(descriptor, sdkMeter); + this.sdkMeter = sdkMeter; this.storage = storage; } + @Override + public boolean isEnabled() { + return sdkMeter.isMeterEnabled() && storage.isEnabled(); + } + @Override public void add(long increment, Attributes attributes, Context context) { storage.recordLong(increment, attributes, context); @@ -36,7 +40,7 @@ public void add(long increment, Attributes attributes, Context context) { @Override public void add(long increment, Attributes attributes) { - add(increment, attributes, Context.current()); + add(increment, attributes, currentOrRootContext()); } @Override @@ -44,82 +48,53 @@ public void add(long increment) { add(increment, Attributes.empty()); } - BoundLongUpDownCounter bind(Attributes attributes) { - return new BoundInstrument(storage.bind(attributes), attributes); - } - - static final class BoundInstrument implements BoundLongUpDownCounter { - private final BoundStorageHandle handle; - private final Attributes attributes; + static class SdkLongUpDownCounterBuilder implements LongUpDownCounterBuilder { - BoundInstrument(BoundStorageHandle handle, Attributes attributes) { - this.handle = handle; - this.attributes = attributes; - } + final InstrumentBuilder builder; - @Override - public void add(long increment, Context context) { - handle.recordLong(increment, attributes, context); - } - - @Override - public void add(long increment) { - add(increment, Context.current()); + SdkLongUpDownCounterBuilder(SdkMeter sdkMeter, String name) { + this.builder = + new InstrumentBuilder( + name, InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.LONG, sdkMeter); } @Override - public void unbind() { - handle.release(); - } - } - - static final class Builder extends AbstractInstrumentBuilder - implements LongUpDownCounterBuilder { - - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState meterSharedState, - String name) { - this(meterProviderSharedState, meterSharedState, name, "", DEFAULT_UNIT); - } - - Builder( - MeterProviderSharedState meterProviderSharedState, - MeterSharedState sharedState, - String name, - String description, - String unit) { - super(meterProviderSharedState, sharedState, name, description, unit); + public LongUpDownCounterBuilder setDescription(String description) { + builder.setDescription(description); + return this; } @Override - protected Builder getThis() { + public LongUpDownCounterBuilder setUnit(String unit) { + builder.setUnit(unit); return this; } @Override public LongUpDownCounter build() { - return buildSynchronousInstrument( - InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.LONG, SdkLongUpDownCounter::new); + return builder.buildSynchronousInstrument(SdkLongUpDownCounter::new); } @Override public DoubleUpDownCounterBuilder ofDoubles() { - return swapBuilder(SdkDoubleUpDownCounter.Builder::new); + return builder.swapBuilder(SdkDoubleUpDownCounter.SdkDoubleUpDownCounterBuilder::new); } @Override public ObservableLongUpDownCounter buildWithCallback( Consumer callback) { - return new SdkObservableInstrument( - meterSharedState, - registerLongAsynchronousInstrument(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, callback)); + return builder.buildLongAsynchronousInstrument( + InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, callback); } @Override public ObservableLongMeasurement buildObserver() { - return buildObservableMeasurement( - InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, InstrumentValueType.LONG); + return builder.buildObservableMeasurement(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER); + } + + @Override + public String toString() { + return builder.toStringHelper(getClass().getSimpleName()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeter.java index 28507cd652b..f59b1f62eb3 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeter.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeter.java @@ -5,7 +5,11 @@ package io.opentelemetry.sdk.metrics; -import io.opentelemetry.api.internal.ValidationUtil; +import static java.util.stream.Collectors.toMap; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.internal.GuardedBy; import io.opentelemetry.api.metrics.BatchCallback; import io.opentelemetry.api.metrics.DoubleGaugeBuilder; import io.opentelemetry.api.metrics.DoubleHistogramBuilder; @@ -14,47 +18,127 @@ import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.api.metrics.ObservableMeasurement; +import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.exemplar.AlwaysOffExemplarFilter; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; +import io.opentelemetry.sdk.metrics.internal.state.AsynchronousMetricStorage; +import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; import io.opentelemetry.sdk.metrics.internal.state.CallbackRegistration; import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorageRegistry; import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; +import io.opentelemetry.sdk.metrics.internal.state.SynchronousMetricStorage; +import io.opentelemetry.sdk.metrics.internal.state.WriteableMetricStorage; +import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.Set; +import java.util.function.BiPredicate; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.regex.Pattern; +import javax.annotation.Nullable; /** {@link SdkMeter} is SDK implementation of {@link Meter}. */ final class SdkMeter implements Meter { private static final Logger logger = Logger.getLogger(SdkMeter.class.getName()); + private static final boolean INCUBATOR_AVAILABLE; + + static { + boolean incubatorAvailable = false; + try { + Class.forName("io.opentelemetry.api.incubator.metrics.ExtendedDefaultMeterProvider"); + incubatorAvailable = true; + } catch (ClassNotFoundException e) { + // Not available + } + INCUBATOR_AVAILABLE = incubatorAvailable; + } /** - * Message appended to warnings when {@link ValidationUtil#checkValidInstrumentName(String, - * String)} is {@code false}. + * Instrument names MUST conform to the following syntax. + * + *

        + *
      • They are not null or empty strings. + *
      • They are case-insensitive, ASCII strings. + *
      • The first character must be an alphabetic character. + *
      • Subsequent characters must belong to the alphanumeric characters, '_', '.', '/', and '-'. + *
      • They can have a maximum length of 255 characters. + *
      */ - private static final String NOOP_INSTRUMENT_WARNING = " Returning noop instrument."; + private static final Pattern VALID_INSTRUMENT_NAME_PATTERN = + Pattern.compile("([A-Za-z]){1}([A-Za-z0-9\\_\\-\\./]){0,254}"); private static final Meter NOOP_METER = MeterProvider.noop().get("noop"); private static final String NOOP_INSTRUMENT_NAME = "noop"; - private final InstrumentationScopeInfo instrumentationScopeInfo; + private final Object collectLock = new Object(); + private final Object callbackLock = new Object(); + + @GuardedBy("callbackLock") + private final List callbackRegistrations = new ArrayList<>(); + private final MeterProviderSharedState meterProviderSharedState; - private final MeterSharedState meterSharedState; + private final InstrumentationScopeInfo instrumentationScopeInfo; + @Nullable private final Predicate> contextScopedAttributesFilter; + private final Map readerStorageRegistries; + + private volatile boolean meterEnabled; SdkMeter( MeterProviderSharedState meterProviderSharedState, InstrumentationScopeInfo instrumentationScopeInfo, - List registeredReaders) { + List registeredReaders, + MeterConfig meterConfig) { this.instrumentationScopeInfo = instrumentationScopeInfo; this.meterProviderSharedState = meterProviderSharedState; - this.meterSharedState = MeterSharedState.create(instrumentationScopeInfo, registeredReaders); + BiPredicate> filter = + meterProviderSharedState.getContextScopedAttributesFilter(); + this.contextScopedAttributesFilter = + filter == null ? null : key -> filter.test(instrumentationScopeInfo, key); + this.readerStorageRegistries = + registeredReaders.stream() + .collect(toMap(Function.identity(), unused -> new MetricStorageRegistry())); + this.meterEnabled = meterConfig.isEnabled(); + } + + /** + * Returns true if the meter provider's exemplar filter samples nothing. Callers can use this to + * skip {@link io.opentelemetry.context.Context#current()} lookups on record paths that only need + * the current context to derive an exemplar span context. + */ + boolean isExemplarsAlwaysOff() { + return meterProviderSharedState.getExemplarFilter() instanceof AlwaysOffExemplarFilter; + } + + @Nullable + Predicate> getContextScopedAttributesFilter() { + return contextScopedAttributesFilter; + } + + void updateMeterConfig(MeterConfig meterConfig) { + meterEnabled = meterConfig.isEnabled(); + + for (RegisteredReader registeredReader : readerStorageRegistries.keySet()) { + Collection storages = + Objects.requireNonNull(readerStorageRegistries.get(registeredReader)).getStorages(); + for (MetricStorage storage : storages) { + storage.setEnabled(meterEnabled); + } + } } // Visible for testing @@ -62,42 +146,88 @@ InstrumentationScopeInfo getInstrumentationScopeInfo() { return instrumentationScopeInfo; } - /** Collects all the metric recordings that changed since the previous call. */ + /** Collect all metrics for the meter. */ Collection collectAll(RegisteredReader registeredReader, long epochNanos) { - return meterSharedState.collectAll(registeredReader, meterProviderSharedState, epochNanos); + List currentRegisteredCallbacks; + synchronized (callbackLock) { + currentRegisteredCallbacks = new ArrayList<>(callbackRegistrations); + } + // Collections across all readers are sequential + synchronized (collectLock) { + // Only invoke callbacks if meter is enabled + if (meterEnabled) { + for (CallbackRegistration callbackRegistration : currentRegisteredCallbacks) { + callbackRegistration.invokeCallback(registeredReader); + } + } + + // Collect even if meter is disabled. Storage is responsible for managing state and returning + // empty metric if disabled. + Collection storages = + Objects.requireNonNull(readerStorageRegistries.get(registeredReader)).getStorages(); + List result = new ArrayList<>(storages.size()); + for (MetricStorage storage : storages) { + MetricData current = + storage.collect( + meterProviderSharedState.getResource(), getInstrumentationScopeInfo(), epochNanos); + // Ignore if the metric data doesn't have any data points, for example when aggregation is + // Aggregation#drop() + if (!current.isEmpty()) { + result.add(current); + } + } + return Collections.unmodifiableList(result); + } } - /** Reset the meter, clearing all registered instruments. */ + /** Reset the meter, clearing all registered callbacks and storages. */ void resetForTest() { - this.meterSharedState.resetForTest(); + synchronized (collectLock) { + synchronized (callbackLock) { + callbackRegistrations.clear(); + } + this.readerStorageRegistries.values().forEach(MetricStorageRegistry::resetForTest); + } } @Override public LongCounterBuilder counterBuilder(String name) { - return !ValidationUtil.checkValidInstrumentName(name, NOOP_INSTRUMENT_WARNING) - ? NOOP_METER.counterBuilder(NOOP_INSTRUMENT_NAME) - : new SdkLongCounter.Builder(meterProviderSharedState, meterSharedState, name); + if (!checkValidInstrumentName(name)) { + return NOOP_METER.counterBuilder(NOOP_INSTRUMENT_NAME); + } + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedLongCounterBuilder(this, name) + : new SdkLongCounter.SdkLongCounterBuilder(this, name); } @Override public LongUpDownCounterBuilder upDownCounterBuilder(String name) { - return !ValidationUtil.checkValidInstrumentName(name, NOOP_INSTRUMENT_WARNING) - ? NOOP_METER.upDownCounterBuilder(NOOP_INSTRUMENT_NAME) - : new SdkLongUpDownCounter.Builder(meterProviderSharedState, meterSharedState, name); + if (!checkValidInstrumentName(name)) { + return NOOP_METER.upDownCounterBuilder(NOOP_INSTRUMENT_NAME); + } + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedLongUpDownCounterBuilder(this, name) + : new SdkLongUpDownCounter.SdkLongUpDownCounterBuilder(this, name); } @Override public DoubleHistogramBuilder histogramBuilder(String name) { - return !ValidationUtil.checkValidInstrumentName(name, NOOP_INSTRUMENT_WARNING) - ? NOOP_METER.histogramBuilder(NOOP_INSTRUMENT_NAME) - : new SdkDoubleHistogram.Builder(meterProviderSharedState, meterSharedState, name); + if (!checkValidInstrumentName(name)) { + return NOOP_METER.histogramBuilder(NOOP_INSTRUMENT_NAME); + } + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedDoubleHistogramBuilder(this, name) + : new SdkDoubleHistogram.SdkDoubleHistogramBuilder(this, name); } @Override public DoubleGaugeBuilder gaugeBuilder(String name) { - return !ValidationUtil.checkValidInstrumentName(name, NOOP_INSTRUMENT_WARNING) - ? NOOP_METER.gaugeBuilder(NOOP_INSTRUMENT_NAME) - : new SdkDoubleGaugeBuilder(meterProviderSharedState, meterSharedState, name); + if (!checkValidInstrumentName(name)) { + return NOOP_METER.gaugeBuilder(NOOP_INSTRUMENT_NAME); + } + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedDoubleGaugeBuilder(this, name) + : new SdkDoubleGauge.SdkDoubleGaugeBuilder(this, name); } @Override @@ -118,9 +248,7 @@ public BatchCallback batchCallback( continue; } SdkObservableMeasurement sdkMeasurement = (SdkObservableMeasurement) measurement; - if (!meterSharedState - .getInstrumentationScopeInfo() - .equals(sdkMeasurement.getInstrumentationScopeInfo())) { + if (!instrumentationScopeInfo.equals(sdkMeasurement.getInstrumentationScopeInfo())) { logger.log( Level.WARNING, "batchCallback called with instruments that belong to a different Meter."); @@ -131,7 +259,185 @@ public BatchCallback batchCallback( CallbackRegistration callbackRegistration = CallbackRegistration.create(sdkMeasurements, callback); - meterSharedState.registerCallback(callbackRegistration); - return new SdkObservableInstrument(meterSharedState, callbackRegistration); + registerCallback(callbackRegistration); + return new SdkObservableInstrument(this, callbackRegistration); + } + + /** + * Unregister the callback. + * + *

      Callbacks are originally registered via {@link #registerCallback(CallbackRegistration)}. + */ + void removeCallback(CallbackRegistration callbackRegistration) { + synchronized (callbackLock) { + this.callbackRegistrations.remove(callbackRegistration); + } + } + + /** + * Register the callback. + * + *

      The callback will be invoked once per collection until unregistered via {@link + * #removeCallback(CallbackRegistration)}. + */ + void registerCallback(CallbackRegistration callbackRegistration) { + synchronized (callbackLock) { + callbackRegistrations.add(callbackRegistration); + } + } + + /** Returns {@code true} if the {@link MeterConfig#enabled()} of the meter is {@code true}. */ + boolean isMeterEnabled() { + return meterEnabled; + } + + /** Registers new synchronous storage associated with a given instrument. */ + @SuppressWarnings("ReferenceEquality") + WriteableMetricStorage registerSynchronousMetricStorage(InstrumentDescriptor instrument) { + + List registeredStorages = new ArrayList<>(); + for (Map.Entry entry : + readerStorageRegistries.entrySet()) { + RegisteredReader reader = entry.getKey(); + MetricStorageRegistry registry = entry.getValue(); + for (RegisteredView registeredView : + reader.getViewRegistry().findViews(instrument, getInstrumentationScopeInfo())) { + if (Aggregation.drop() == registeredView.getView().getAggregation()) { + continue; + } + registeredStorages.add( + registry.register( + SynchronousMetricStorage.create( + reader, + registeredView, + meterProviderSharedState.getClock(), + instrument, + meterProviderSharedState.getExemplarFilter(), + meterEnabled, + getContextScopedAttributesFilter()))); + } + } + + if (registeredStorages.size() == 1) { + return registeredStorages.get(0); + } + + return new MultiWritableMetricStorage(registeredStorages); + } + + /** Register new asynchronous storage associated with a given instrument. */ + @SuppressWarnings("ReferenceEquality") + SdkObservableMeasurement registerObservableMeasurement( + InstrumentDescriptor instrumentDescriptor) { + List> registeredStorages = new ArrayList<>(); + for (Map.Entry entry : + readerStorageRegistries.entrySet()) { + RegisteredReader reader = entry.getKey(); + MetricStorageRegistry registry = entry.getValue(); + for (RegisteredView registeredView : + reader.getViewRegistry().findViews(instrumentDescriptor, getInstrumentationScopeInfo())) { + if (Aggregation.drop() == registeredView.getView().getAggregation()) { + continue; + } + registeredStorages.add( + registry.register( + AsynchronousMetricStorage.create( + reader, + registeredView, + meterProviderSharedState.getClock(), + instrumentDescriptor, + meterProviderSharedState.getExemplarFilter(), + meterEnabled))); + } + } + + return SdkObservableMeasurement.create( + instrumentationScopeInfo, instrumentDescriptor, registeredStorages); + } + + @Override + public String toString() { + return "SdkMeter{instrumentationScopeInfo=" + instrumentationScopeInfo + "}"; + } + + /** Check if the instrument name is valid. If invalid, log a warning. */ + // Visible for testing + static boolean checkValidInstrumentName(String name) { + if (name != null && VALID_INSTRUMENT_NAME_PATTERN.matcher(name).matches()) { + return true; + } + if (logger.isLoggable(Level.WARNING)) { + logger.log( + Level.WARNING, + "Instrument name \"" + + name + + "\" is invalid, returning noop instrument. Instrument names must consist of 255 or fewer characters including alphanumeric, _, ., -, /, and start with a letter.", + new AssertionError()); + } + + return false; + } + + private static class MultiWritableMetricStorage implements WriteableMetricStorage { + private final List storages; + + private MultiWritableMetricStorage(List storages) { + this.storages = storages; + } + + @Override + public void recordLong(long value, Attributes attributes, Context context) { + for (WriteableMetricStorage storage : storages) { + storage.recordLong(value, attributes, context); + } + } + + @Override + public void recordDouble(double value, Attributes attributes, Context context) { + for (WriteableMetricStorage storage : storages) { + storage.recordDouble(value, attributes, context); + } + } + + @Override + public BoundStorageHandle bind(Attributes attributes) { + List handles = new ArrayList<>(storages.size()); + for (WriteableMetricStorage storage : storages) { + handles.add(storage.bind(attributes)); + } + return new MultiBoundStorageHandle(handles); + } + + @Override + public boolean isEnabled() { + for (WriteableMetricStorage storage : storages) { + if (storage.isEnabled()) { + return true; + } + } + return false; + } + } + + private static class MultiBoundStorageHandle implements BoundStorageHandle { + private final List handles; + + private MultiBoundStorageHandle(List handles) { + this.handles = handles; + } + + @Override + public void recordLong(long value, Context context) { + for (BoundStorageHandle handle : handles) { + handle.recordLong(value, context); + } + } + + @Override + public void recordDouble(double value, Context context) { + for (BoundStorageHandle handle : handles) { + handle.recordDouble(value, context); + } + } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterBuilder.java index eef6be97be3..252eb0792b4 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterBuilder.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterBuilder.java @@ -5,9 +5,10 @@ package io.opentelemetry.sdk.metrics; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.MeterBuilder; -import io.opentelemetry.sdk.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.internal.ComponentRegistry; import javax.annotation.Nullable; class SdkMeterBuilder implements MeterBuilder { @@ -36,6 +37,7 @@ public MeterBuilder setInstrumentationVersion(String instrumentationScopeVersion @Override public Meter build() { - return registry.get(instrumentationScopeName, instrumentationScopeVersion, schemaUrl); + return registry.get( + instrumentationScopeName, instrumentationScopeVersion, schemaUrl, Attributes.empty()); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java index 172f1d7dc62..abfd4171b52 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProvider.java @@ -7,70 +7,134 @@ import static java.util.stream.Collectors.toList; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.metrics.MeterBuilder; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.MetricProducer; import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; +import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; import java.io.Closeable; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; +import java.util.IdentityHashMap; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BiPredicate; import java.util.logging.Logger; +import javax.annotation.Nullable; -/** SDK implementation for {@link MeterProvider}. */ +/** + * SDK implementation for {@link MeterProvider}. + * + * @since 1.14.0 + */ public final class SdkMeterProvider implements MeterProvider, Closeable { private static final Logger LOGGER = Logger.getLogger(SdkMeterProvider.class.getName()); static final String DEFAULT_METER_NAME = "unknown"; + private final List registeredViews; private final List registeredReaders; + private final List metricProducers; private final MeterProviderSharedState sharedState; + private final SdkResourceProvider resourceProvider; private final ComponentRegistry registry; private final AtomicBoolean isClosed = new AtomicBoolean(false); - /** - * Returns a new {@link SdkMeterProviderBuilder} for {@link SdkMeterProvider}. - * - * @return a new {@link SdkMeterProviderBuilder} for {@link SdkMeterProvider}. - */ + private ScopeConfigurator meterConfigurator; + + /** Returns a new {@link SdkMeterProviderBuilder} for {@link SdkMeterProvider}. */ public static SdkMeterProviderBuilder builder() { return new SdkMeterProviderBuilder(); } SdkMeterProvider( - List registeredReaders, + List registeredViews, + IdentityHashMap metricReaders, + List metricProducers, Clock clock, - Resource resource, - ViewRegistry viewRegistry, - ExemplarFilter exemplarFilter) { - long startEpochNanos = clock.now(); - this.registeredReaders = registeredReaders; + SdkResourceProvider resourceProvider, + ExemplarFilterInternal exemplarFilter, + ScopeConfigurator meterConfigurator, + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.resourceProvider = resourceProvider; + this.registeredViews = registeredViews; + this.registeredReaders = + metricReaders.entrySet().stream() + .map(entry -> + RegisteredReader.create( + entry.getKey(), + ViewRegistry.create(entry.getKey(), entry.getValue(), registeredViews))) + .collect(toList()); + this.metricProducers = metricProducers; this.sharedState = MeterProviderSharedState.create( - clock, resource, viewRegistry, exemplarFilter, startEpochNanos); + clock, resourceProvider, exemplarFilter, contextScopedAttributesFilter); this.registry = - new ComponentRegistry<>( - instrumentationLibraryInfo -> - new SdkMeter(sharedState, instrumentationLibraryInfo, registeredReaders)); + new ComponentRegistry<>(instrumentationLibraryInfo -> + new SdkMeter( + sharedState, + instrumentationLibraryInfo, + registeredReaders, + getMeterConfig(instrumentationLibraryInfo))); + this.meterConfigurator = meterConfigurator; for (RegisteredReader registeredReader : registeredReaders) { - MetricProducer producer = new LeasedMetricProducer(registry, sharedState, registeredReader); - registeredReader.getReader().register(producer); - registeredReader.setLastCollectEpochNanos(startEpochNanos); + List readerMetricProducers = new ArrayList<>(metricProducers); + readerMetricProducers.add(new LeasedMetricProducer(registry, sharedState, registeredReader)); + MetricReader reader = registeredReader.getReader(); + reader.register(new SdkCollectionRegistration(readerMetricProducers, sharedState)); + if (reader instanceof PeriodicMetricReader) { + setReaderMeterProvider((PeriodicMetricReader) reader, this); + } } } + private MeterConfig getMeterConfig(InstrumentationScopeInfo instrumentationScopeInfo) { + MeterConfig meterConfig = meterConfigurator.apply(instrumentationScopeInfo); + return meterConfig == null ? MeterConfig.defaultConfig() : meterConfig; + } + + /** + * Returns the {@link SdkResourceProvider} used to resolve the {@link Resource} attached to + * metrics. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkMeterProviderUtil#getSdkResourceProvider(SdkMeterProvider)}. + */ + SdkResourceProvider getSdkResourceProvider() { + return resourceProvider; + } + + void setMeterConfigurator(ScopeConfigurator meterConfigurator) { + this.meterConfigurator = meterConfigurator; + this.registry + .getComponents() + .forEach(sdkMeter -> + sdkMeter.updateMeterConfig(getMeterConfig(sdkMeter.getInstrumentationScopeInfo()))); + } + @Override public MeterBuilder meterBuilder(String instrumentationScopeName) { if (registeredReaders.isEmpty()) { @@ -83,7 +147,12 @@ public MeterBuilder meterBuilder(String instrumentationScopeName) { return new SdkMeterBuilder(registry, instrumentationScopeName); } - /** Reset the provider, clearing all registered instruments. */ + /** + * Reset the provider, clearing all registered instruments. + * + *

      Note: not currently stable but available for experimental use via {@link + * SdkMeterProviderUtil#resetForTest(SdkMeterProvider)}. + */ void resetForTest() { registry.getComponents().forEach(SdkMeter::resetForTest); } @@ -137,11 +206,27 @@ public String toString() { + sharedState.getResource() + ", metricReaders=" + registeredReaders.stream().map(RegisteredReader::getReader).collect(toList()) + + ", metricProducers=" + + metricProducers + ", views=" - + sharedState.getViewRegistry().getViews() + + registeredViews + + ", meterConfigurator=" + + meterConfigurator + "}"; } + private static void setReaderMeterProvider( + PeriodicMetricReader metricReader, SdkMeterProvider meterProvider) { + try { + Method method = + PeriodicMetricReader.class.getDeclaredMethod("setMeterProvider", MeterProvider.class); + method.setAccessible(true); + method.invoke(metricReader, meterProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException("Error calling setMeterProvider on PeriodicMetricReader", e); + } + } + /** Helper class to expose registered metric exports. */ private static class LeasedMetricProducer implements MetricProducer { @@ -159,7 +244,7 @@ private static class LeasedMetricProducer implements MetricProducer { } @Override - public Collection collectAllMetrics() { + public Collection produce(Resource unused) { Collection meters = registry.getComponents(); List result = new ArrayList<>(); long collectTime = sharedState.getClock().now(); @@ -170,4 +255,31 @@ public Collection collectAllMetrics() { return Collections.unmodifiableCollection(result); } } + + private static class SdkCollectionRegistration implements CollectionRegistration { + private final List metricProducers; + private final MeterProviderSharedState sharedState; + + private SdkCollectionRegistration( + List metricProducers, MeterProviderSharedState sharedState) { + this.metricProducers = metricProducers; + this.sharedState = sharedState; + } + + @Override + public Collection collectAllMetrics() { + if (metricProducers.isEmpty()) { + return Collections.emptyList(); + } + Resource resource = sharedState.getResource(); + if (metricProducers.size() == 1) { + return metricProducers.get(0).produce(resource); + } + List metricData = new ArrayList<>(); + for (MetricProducer metricProducer : metricProducers) { + metricData.addAll(metricProducer.produce(resource)); + } + return Collections.unmodifiableList(metricData); + } + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilder.java index 9aecdc41316..1dd3a8fca87 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilder.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilder.java @@ -5,19 +5,35 @@ package io.opentelemetry.sdk.metrics; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.MetricProducer; import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; -import io.opentelemetry.sdk.metrics.internal.view.ViewRegistryBuilder; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; +import io.opentelemetry.sdk.metrics.internal.view.AttributesFilters; +import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; import java.util.ArrayList; +import java.util.IdentityHashMap; import java.util.List; import java.util.Objects; +import java.util.function.BiPredicate; +import java.util.function.Predicate; +import javax.annotation.Nullable; -/** Builder class for the {@link SdkMeterProvider}. */ +/** + * Builder class for the {@link SdkMeterProvider}. + * + * @since 1.14.0 + */ public final class SdkMeterProviderBuilder { /** @@ -25,13 +41,23 @@ public final class SdkMeterProviderBuilder { * * @see #setExemplarFilter(ExemplarFilter) */ - private static final ExemplarFilter DEFAULT_EXEMPLAR_FILTER = ExemplarFilter.sampleWithTraces(); + private static final ExemplarFilterInternal DEFAULT_EXEMPLAR_FILTER = + ExemplarFilterInternal.asExemplarFilterInternal(ExemplarFilter.traceBased()); private Clock clock = Clock.getDefault(); private Resource resource = Resource.getDefault(); - private final ViewRegistryBuilder viewRegistryBuilder = ViewRegistry.builder(); - private final List registeredReaders = new ArrayList<>(); - private ExemplarFilter exemplarFilter = DEFAULT_EXEMPLAR_FILTER; + private boolean resourceExplicitlySet = false; + @Nullable private SdkResourceProvider resourceProvider; + private final IdentityHashMap metricReaders = + new IdentityHashMap<>(); + private final List metricProducers = new ArrayList<>(); + private final List registeredViews = new ArrayList<>(); + private ExemplarFilterInternal exemplarFilter = DEFAULT_EXEMPLAR_FILTER; + private ScopeConfiguratorBuilder meterConfiguratorBuilder = + MeterConfig.configuratorBuilder(); + + @Nullable + private BiPredicate> contextScopedAttributesFilter; SdkMeterProviderBuilder() {} @@ -39,7 +65,6 @@ public final class SdkMeterProviderBuilder { * Assign a {@link Clock}. * * @param clock The clock to use for all temporal needs. - * @return this */ public SdkMeterProviderBuilder setClock(Clock clock) { Objects.requireNonNull(clock, "clock"); @@ -48,81 +73,208 @@ public SdkMeterProviderBuilder setClock(Clock clock) { } /** - * Assign a {@link Resource} to be attached to all metrics created by Meters. + * Assign a {@link Resource} to be attached to all metrics. * - * @param resource A Resource implementation. - * @return this + * @throws IllegalStateException if {@link #setSdkResourceProvider(SdkResourceProvider)} was + * already called */ public SdkMeterProviderBuilder setResource(Resource resource) { Objects.requireNonNull(resource, "resource"); + if (resourceProvider != null) { + throw new IllegalStateException( + "Cannot call setResource after setSdkResourceProvider has been called."); + } this.resource = resource; + this.resourceExplicitlySet = true; + return this; + } + + /** + * Merge a {@link Resource} with the current. + * + * @param resource {@link Resource} to merge with current. + * @throws IllegalStateException if {@link #setSdkResourceProvider(SdkResourceProvider)} was + * already called + * @since 1.29.0 + */ + public SdkMeterProviderBuilder addResource(Resource resource) { + Objects.requireNonNull(resource, "resource"); + if (resourceProvider != null) { + throw new IllegalStateException( + "Cannot call addResource after setSdkResourceProvider has been called."); + } + this.resource = this.resource.merge(resource); + this.resourceExplicitlySet = true; + return this; + } + + /** + * Sets the {@link SdkResourceProvider} used to resolve the {@link Resource} attached to all + * metrics. + * + *

      Mutually exclusive with {@link #setResource(Resource)} and {@link #addResource(Resource)}. + * The conflicting setter throws {@link IllegalStateException} if both are configured. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkMeterProviderUtil#setSdkResourceProvider(SdkMeterProviderBuilder, SdkResourceProvider)}. + */ + SdkMeterProviderBuilder setSdkResourceProvider(SdkResourceProvider resourceProvider) { + Objects.requireNonNull(resourceProvider, "resourceProvider"); + if (resourceExplicitlySet) { + throw new IllegalStateException( + "Cannot call setSdkResourceProvider after setResource or addResource has been called."); + } + this.resourceProvider = resourceProvider; return this; } /** - * Assign an {@link ExemplarFilter} for all metrics created by Meters. + * Set the {@link ExemplarFilter} used for all instruments from all meters. * - * @return this + * @since 1.56.0 */ - SdkMeterProviderBuilder setExemplarFilter(ExemplarFilter filter) { - this.exemplarFilter = filter; + public SdkMeterProviderBuilder setExemplarFilter(ExemplarFilter filter) { + this.exemplarFilter = ExemplarFilterInternal.asExemplarFilterInternal(filter); return this; } /** - * Register a view with the given {@link InstrumentSelector}. + * Register a {@link View}. + * + *

      The {@code view} influences how instruments which match the {@code selector} are aggregated + * and exported. * - *

      Example on how to register a view: + *

      For example, the following code registers a view which changes all histogram instruments to + * aggregate with bucket boundaries different from the default: * *

      {@code
          * // create a SdkMeterProviderBuilder
          * SdkMeterProviderBuilder meterProviderBuilder = SdkMeterProvider.builder();
          *
      -   * // create a selector to select which instruments to customize:
      -   * InstrumentSelector instrumentSelector = InstrumentSelector.builder()
      -   *   .setType(InstrumentType.COUNTER)
      -   *   .build();
      -   *
          * // register the view with the SdkMeterProviderBuilder
          * meterProviderBuilder.registerView(
      -   *   instrumentSelector,
      +   *   InstrumentSelector.builder()
      +   *       .setType(InstrumentType.HISTOGRAM)
      +   *       .build(),
          *   View.builder()
          *       .setAggregation(
          *           Aggregation.explicitBucketHistogram(Arrays.asList(10d, 20d, 30d, 40d, 50d)))
      -   *       .setName("my-view-name")
      -   *       .setDescription("my-view-description")
          *       .build());
          * }
      - * - * @since 1.1.0 */ public SdkMeterProviderBuilder registerView(InstrumentSelector selector, View view) { Objects.requireNonNull(selector, "selector"); Objects.requireNonNull(view, "view"); - viewRegistryBuilder.addView( - selector, view, view.getAttributesProcessor(), SourceInfo.fromCurrentStack()); + registeredViews.add( + RegisteredView.create( + selector, + view, + AttributesFilters.byKeyName(view.getAttributeFilter()), + view.getCardinalityLimit(), + SourceInfo.fromCurrentStack())); + return this; + } + + /** Registers a {@link MetricReader}. */ + public SdkMeterProviderBuilder registerMetricReader(MetricReader reader) { + metricReaders.put(reader, CardinalityLimitSelector.defaultCardinalityLimitSelector()); return this; } /** - * Registers a {@link MetricReader} for this SDK. + * Registers a {@link MetricReader} with a {@link CardinalityLimitSelector}. * - *

      Note: custom implementations of {@link MetricReader} are not currently supported. + *

      If {@link #registerMetricReader(MetricReader)} is used, the {@link + * CardinalityLimitSelector#defaultCardinalityLimitSelector()} is used. * - * @param reader The reader. - * @return this + * @since 1.44.0 */ - public SdkMeterProviderBuilder registerMetricReader(MetricReader reader) { - registeredReaders.add(RegisteredReader.create(reader)); + public SdkMeterProviderBuilder registerMetricReader( + MetricReader reader, CardinalityLimitSelector cardinalityLimitSelector) { + metricReaders.put(reader, cardinalityLimitSelector); + return this; + } + + /** + * Registers a {@link MetricProducer}. + * + * @since 1.31.0 + */ + public SdkMeterProviderBuilder registerMetricProducer(MetricProducer metricProducer) { + metricProducers.add(metricProducer); + return this; + } + + /** + * Set the meter configurator, which computes {@link MeterConfig} for each {@link + * InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkMeterProviderUtil#setMeterConfigurator(SdkMeterProviderBuilder, ScopeConfigurator)}. + * + *

      Overrides any matchers added via {@link #addMeterConfiguratorCondition(Predicate, + * MeterConfig)}. + * + * @see MeterConfig#configuratorBuilder() + */ + SdkMeterProviderBuilder setMeterConfigurator(ScopeConfigurator meterConfigurator) { + this.meterConfiguratorBuilder = meterConfigurator.toBuilder(); + return this; + } + + /** + * Adds a condition to the meter configurator, which computes {@link MeterConfig} for each {@link + * InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkMeterProviderUtil#addMeterConfiguratorCondition(SdkMeterProviderBuilder, Predicate, + * MeterConfig)}. + * + *

      Applies after any previously added conditions. + * + *

      If {@link #setMeterConfigurator(ScopeConfigurator)} was previously called, this condition + * will only be applied if the {@link ScopeConfigurator#apply(Object)} returns null for the + * matched {@link InstrumentationScopeInfo}(s). + * + * @see ScopeConfiguratorBuilder#nameEquals(String) + * @see ScopeConfiguratorBuilder#nameMatchesGlob(String) + */ + SdkMeterProviderBuilder addMeterConfiguratorCondition( + Predicate scopeMatcher, MeterConfig meterConfig) { + this.meterConfiguratorBuilder.addCondition(scopeMatcher, meterConfig); return this; } /** - * Returns a new {@link SdkMeterProvider} built with the configuration of this {@link - * SdkMeterProviderBuilder}. + * Sets the filter predicate to determine which context-scoped attributes are inherited by + * synchronous metric measurements. + * + *

      Note: Bound instruments (e.g. {@code BoundLongCounter}) do not inherit context-scoped + * attributes because their attributes are pre-resolved at {@code bind()} time and bound recording + * operations do not receive or evaluate Context. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkMeterProviderUtil#setContextScopedAttributesFilter(SdkMeterProviderBuilder, BiPredicate)}. */ + SdkMeterProviderBuilder setContextScopedAttributesFilter( + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.contextScopedAttributesFilter = contextScopedAttributesFilter; + return this; + } + + /** Returns an {@link SdkMeterProvider} built with the configuration of this builder. */ public SdkMeterProvider build() { + SdkResourceProvider effectiveSdkResourceProvider = + resourceProvider != null ? resourceProvider : SdkResourceProvider.create(resource); return new SdkMeterProvider( - registeredReaders, clock, resource, viewRegistryBuilder.build(), exemplarFilter); + registeredViews, + metricReaders, + metricProducers, + clock, + effectiveSdkResourceProvider, + exemplarFilter, + meterConfiguratorBuilder.build(), + contextScopedAttributesFilter); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkObservableInstrument.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkObservableInstrument.java index 30f94b547cf..fe3ca4775dc 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkObservableInstrument.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/SdkObservableInstrument.java @@ -12,9 +12,8 @@ import io.opentelemetry.api.metrics.ObservableLongCounter; import io.opentelemetry.api.metrics.ObservableLongGauge; import io.opentelemetry.api.metrics.ObservableLongUpDownCounter; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.internal.state.CallbackRegistration; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; @@ -31,13 +30,12 @@ class SdkObservableInstrument private static final Logger logger = Logger.getLogger(SdkObservableInstrument.class.getName()); private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final MeterSharedState meterSharedState; + private final SdkMeter sdkMeter; private final CallbackRegistration callbackRegistration; private final AtomicBoolean removed = new AtomicBoolean(false); - SdkObservableInstrument( - MeterSharedState meterSharedState, CallbackRegistration callbackRegistration) { - this.meterSharedState = meterSharedState; + SdkObservableInstrument(SdkMeter sdkMeter, CallbackRegistration callbackRegistration) { + this.sdkMeter = sdkMeter; this.callbackRegistration = callbackRegistration; } @@ -45,10 +43,14 @@ class SdkObservableInstrument public void close() { if (!removed.compareAndSet(false, true)) { throttlingLogger.log( - Level.WARNING, - callbackRegistration.getCallbackDescription() + " has called close() multiple times."); + Level.WARNING, callbackRegistration + " has called close() multiple times."); return; } - meterSharedState.removeCallback(callbackRegistration); + sdkMeter.removeCallback(callbackRegistration); + } + + @Override + public String toString() { + return "SdkObservableInstrument{callback=" + callbackRegistration + "}"; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/View.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/View.java index b17b53e166f..ada250561d6 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/View.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/View.java @@ -6,12 +6,19 @@ package io.opentelemetry.sdk.metrics; import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; import java.util.StringJoiner; +import java.util.function.Predicate; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; -/** A configuration for a metric stream transformation. */ +/** + * A view configures how measurements are aggregated and exported as metrics. + * + *

      Views are registered with the SDK {@link + * SdkMeterProviderBuilder#registerView(InstrumentSelector, View)}. + * + * @since 1.14.0 + */ @AutoValue @Immutable public abstract class View { @@ -25,29 +32,44 @@ static View create( @Nullable String name, @Nullable String description, Aggregation aggregation, - AttributesProcessor attributesProcessor) { - return new AutoValue_View(name, description, aggregation, attributesProcessor); + Predicate attributeFilter, + int cardinalityLimit) { + return new AutoValue_View(name, description, aggregation, attributeFilter, cardinalityLimit); } View() {} /** - * The name of the resulting metric to generate, or {@code null} if the same as the instrument. + * Returns the name of the resulting metric, or {@code null} if the matched instrument name should + * be used. */ @Nullable public abstract String getName(); /** - * The name of the resulting metric to generate, or {@code null} if the same as the instrument. + * Returns the description of the resulting metric, or {@code null} if the matched instrument + * description should be used. */ @Nullable public abstract String getDescription(); - /** The aggregation used for this view. */ + /** Returns the aggregation of the resulting metric. */ public abstract Aggregation getAggregation(); - /** The attribute processor used for this view. */ - abstract AttributesProcessor getAttributesProcessor(); + /** + * Returns the attribute key filter for this view. Attribute keys for which the predicate returns + * {@code false} are dropped from recorded measurements. + * + * @since 1.67.0 + */ + public abstract Predicate getAttributeFilter(); + + /** + * Returns the cardinality limit for this view. + * + * @since 1.44.0 + */ + public abstract int getCardinalityLimit(); @Override public final String toString() { @@ -59,7 +81,8 @@ public final String toString() { joiner.add("description=" + getDescription()); } joiner.add("aggregation=" + getAggregation()); - joiner.add("attributesProcessor=" + getAttributesProcessor()); + joiner.add("attributeFilter=" + getAttributeFilter()); + joiner.add("cardinalityLimit=" + getCardinalityLimit()); return joiner.toString(); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ViewBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ViewBuilder.java index 661f494c93d..9aa7823f9bd 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ViewBuilder.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/ViewBuilder.java @@ -5,27 +5,36 @@ package io.opentelemetry.sdk.metrics; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.IncludeExcludePredicate; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; +import io.opentelemetry.sdk.metrics.internal.view.StringPredicates; +import java.util.Collections; import java.util.Objects; +import java.util.Set; import java.util.function.Predicate; import javax.annotation.Nullable; -/** A builder for {@link View}. */ +/** + * A builder for {@link View}. + * + * @since 1.14.0 + */ public final class ViewBuilder { @Nullable private String name; @Nullable private String description; private Aggregation aggregation = Aggregation.defaultAggregation(); - private AttributesProcessor processor = AttributesProcessor.noop(); + private Predicate attributeFilter = StringPredicates.ALL; + private int cardinalityLimit = MetricStorage.DEFAULT_MAX_CARDINALITY; ViewBuilder() {} /** * Sets the name of the resulting metric. * - * @param name metric name or {@code null} if the underlying instrument name should be used. - * @return this Builder. + * @param name metric name or {@code null} if the matched instrument name should be used. */ public ViewBuilder setName(String name) { this.name = name; @@ -35,9 +44,8 @@ public ViewBuilder setName(String name) { /** * Sets the description of the resulting metric. * - * @param description metric description or {@code null} if the underlying instrument description + * @param description metric description or {@code null} if the matched instrument description * should be used. - * @return this Builder. */ public ViewBuilder setDescription(String description) { this.description = description; @@ -48,7 +56,6 @@ public ViewBuilder setDescription(String description) { * Sets {@link Aggregation}. * * @param aggregation aggregation to use. - * @return this Builder. */ public ViewBuilder setAggregation(Aggregation aggregation) { if (!(aggregation instanceof AggregatorFactory)) { @@ -61,26 +68,65 @@ public ViewBuilder setAggregation(Aggregation aggregation) { } /** - * Sets a filter for attributes, where only attribute names that pass the supplied {@link - * Predicate} will be included in the output. + * Sets a filter which retains attribute keys included in {@code keysToRetain}. * - *

      Note: This runs after all other attribute processing added so far. + *

      Note: Attributes dropped by this filter may still appear on recorded exemplars. If you need + * to remove sensitive data from exemplars, you must disable exemplars entirely (e.g., using + * {@link SdkMeterProviderBuilder#setExemplarFilter(ExemplarFilter)} with {@link + * ExemplarFilter#alwaysOff()}), filter them using a delegating exporter, or filter them in the + * OpenTelemetry Collector. * - * @param keyFilter filter for key names to include. - * @return this Builder. + * @since 1.30.0 + */ + public ViewBuilder setAttributeFilter(Set keysToRetain) { + Objects.requireNonNull(keysToRetain, "keysToRetain"); + if (keysToRetain.isEmpty()) { + // include/exclude predicate requires to include or exclude at least one + // thus an empty list of keys is effectively equivalent to ignore all of them + return setAttributeFilter( + IncludeExcludePredicate.createPatternMatching(null, Collections.singletonList("*"))); + } + return setAttributeFilter(IncludeExcludePredicate.createExactMatching(keysToRetain, null)); + } + + /** + * Sets a filter for attributes keys. + * + *

      Only attribute keys that pass the supplied {@link Predicate} will be included in the output. + * + *

      Note: Attributes dropped by this filter may still appear on recorded exemplars. If you need + * to remove sensitive data from exemplars, you must disable exemplars entirely (e.g., using + * {@link SdkMeterProviderBuilder#setExemplarFilter(ExemplarFilter)} with {@link + * ExemplarFilter#alwaysOff()}), filter them using a delegating exporter, or filter them in the + * OpenTelemetry Collector. + * + * @param keyFilter filter for attribute keys to include. */ public ViewBuilder setAttributeFilter(Predicate keyFilter) { Objects.requireNonNull(keyFilter, "keyFilter"); - return addAttributesProcessor(AttributesProcessor.filterByKeyName(keyFilter)); + this.attributeFilter = keyFilter; + return this; } - ViewBuilder addAttributesProcessor(AttributesProcessor attributesProcessor) { - this.processor = this.processor.then(attributesProcessor); + /** + * Set the cardinality limit. + * + *

      Read {@link MemoryMode} to understand the memory usage behavior of reaching cardinality + * limit. + * + * @param cardinalityLimit the maximum number of series for a metric + * @since 1.44.0 + */ + public ViewBuilder setCardinalityLimit(int cardinalityLimit) { + if (cardinalityLimit <= 0) { + throw new IllegalArgumentException("cardinalityLimit must be > 0"); + } + this.cardinalityLimit = cardinalityLimit; return this; } /** Returns a {@link View} with the configuration of this builder. */ public View build() { - return View.create(name, description, aggregation, processor); + return View.create(name, description, aggregation, attributeFilter, cardinalityLimit); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/AggregationTemporality.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/AggregationTemporality.java index e421f7965c1..8089646f1aa 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/AggregationTemporality.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/AggregationTemporality.java @@ -5,10 +5,14 @@ package io.opentelemetry.sdk.metrics.data; -/** An enumeration which describes the time period over which metrics should be aggregated. */ +/** + * Describes the time period over which measurements are aggregated. + * + * @since 1.14.0 + */ public enum AggregationTemporality { - /** Metrics will be aggregated only over the most recent collection interval. */ + /** Measurements are aggregated since the previous collection. */ DELTA, - /** Metrics will be aggregated over the lifetime of the associated Instrument. */ + /** Measurements are aggregated over the lifetime of the instrument. */ CUMULATIVE } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/Data.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/Data.java index 031bc198716..58fdc6f0a2c 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/Data.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/Data.java @@ -9,10 +9,9 @@ import javax.annotation.concurrent.Immutable; /** - * A collection of data points associated to a metric. + * A collection of metric {@link PointData}. * - *

      Loosely equivalent with "Metric" message in OTLP. See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#metric-points + * @since 1.14.0 */ @Immutable public interface Data { diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DelegatingMetricData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DelegatingMetricData.java new file mode 100644 index 00000000000..7951267dee1 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DelegatingMetricData.java @@ -0,0 +1,189 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; + +/** + * A {@link MetricData} which delegates all methods to another {@link MetricData}. Extend this class + * to modify the {@link MetricData} that will be exported, for example by creating a delegating + * {@link io.opentelemetry.sdk.metrics.export.MetricExporter} which wraps {@link MetricData} with a + * custom implementation. + * + *

      Example usage: + * + *

      {@code
      + * // class MetricDataWithCustomDescription extends DelegatingMetricData {
      + * //
      + * //   private final String description;
      + * //
      + * //   MetricDataWithCustomDescription(MetricData delegate) {
      + * //     super(delegate);
      + * //     this.description = delegate.getDescription() + " (custom)";
      + * //   }
      + * //
      + * //   @Override
      + * //   public String getDescription() {
      + * //     return description;
      + * //   }
      + * // }
      + * }
      + * + * @since 1.50.0 + */ +public abstract class DelegatingMetricData implements MetricData { + + private final MetricData delegate; + + protected DelegatingMetricData(MetricData delegate) { + this.delegate = requireNonNull(delegate, "delegate"); + } + + /** + * Returns the resource associated with this metric data. + * + * @return the {@link Resource} instance. + */ + @Override + public Resource getResource() { + return delegate.getResource(); + } + + /** + * Returns the instrumentation library information associated with this metric data. + * + * @return the {@link InstrumentationScopeInfo} instance. + */ + @Override + public InstrumentationScopeInfo getInstrumentationScopeInfo() { + return delegate.getInstrumentationScopeInfo(); + } + + /** + * Returns the name of the metric. + * + * @return the name of the metric. + */ + @Override + public String getName() { + return delegate.getName(); + } + + /** + * Returns the description of the metric. + * + * @return the description of the metric. + */ + @Override + public String getDescription() { + return delegate.getDescription(); + } + + /** + * Returns the unit of the metric. + * + * @return the unit of the metric. + */ + @Override + public String getUnit() { + return delegate.getUnit(); + } + + /** + * Returns the type of the metric. + * + * @return the type of the metric. + */ + @Override + public MetricDataType getType() { + return delegate.getType(); + } + + /** + * Returns the data of the metric. + * + * @return the data of the metric. + */ + @Override + public Data getData() { + return delegate.getData(); + } + + /** + * Returns a boolean indicating whether the delegate {@link MetricData} is equal to this {@code + * MetricData}. + * + * @param o the object to compare to. + * @return a boolean indicating whether the delegate {@link MetricData} is equal to this {@code + * MetricData}. + */ + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o instanceof MetricData) { + MetricData that = (MetricData) o; + return getResource().equals(that.getResource()) + && getInstrumentationScopeInfo().equals(that.getInstrumentationScopeInfo()) + && getName().equals(that.getName()) + && getDescription().equals(that.getDescription()) + && getUnit().equals(that.getUnit()) + && getType().equals(that.getType()) + && getData().equals(that.getData()); + } + return false; + } + + /** + * Returns a hash code value for the delegate {@link MetricData}. + * + * @return a hash code value for the delegate {@link MetricData}. + */ + @Override + public int hashCode() { + int code = 1; + code *= 1000003; + code ^= getResource().hashCode(); + code *= 1000003; + code ^= getInstrumentationScopeInfo().hashCode(); + code *= 1000003; + code ^= getName().hashCode(); + code *= 1000003; + code ^= getDescription().hashCode(); + code *= 1000003; + code ^= getUnit().hashCode(); + code *= 1000003; + code ^= getType().hashCode(); + code *= 1000003; + code ^= getData().hashCode(); + return code; + } + + /** Returns a string representation of the delegate {@link MetricData}. */ + @Override + public String toString() { + return "DelegatingMetricData{" + + "resource=" + + getResource() + + ", instrumentationScopeInfo=" + + getInstrumentationScopeInfo() + + ", name=" + + getName() + + ", description=" + + getDescription() + + ", unit=" + + getUnit() + + ", type=" + + getType() + + ", data=" + + getData() + + "}"; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarData.java index 94052524692..de718ab2f4f 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarData.java @@ -5,8 +5,30 @@ package io.opentelemetry.sdk.metrics.data; -/** An {@link ExemplarData} with {@code double} measurements. */ +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import javax.annotation.concurrent.Immutable; + +/** + * Exemplar data for {@code double} measurements. + * + * @since 1.14.0 + */ +@Immutable public interface DoubleExemplarData extends ExemplarData { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static DoubleExemplarData create( + Attributes filteredAttributes, long recordTimeNanos, SpanContext spanContext, double value) { + return ImmutableDoubleExemplarData.create( + filteredAttributes, recordTimeNanos, spanContext, value); + } + /** Numerical value of the measurement that was recorded. */ double getValue(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoublePointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoublePointData.java index 2f00321baa4..3ffa4aa5e69 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoublePointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/DoublePointData.java @@ -5,18 +5,36 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; import java.util.List; -/** A single data point in a timeseries that describes the time-varying value of a double metric. */ +/** + * Point data with a {@code double} aggregation value. + * + * @since 1.14.0 + */ public interface DoublePointData extends PointData { + /** - * Returns the value of the data point. + * Create a record. * - * @return the value of the data point. + * @since 1.50.0 */ + static DoublePointData create( + long startEpochNanos, + long epochNanos, + Attributes attributes, + double value, + List exemplars) { + return ImmutableDoublePointData.create( + startEpochNanos, epochNanos, attributes, value, exemplars); + } + + /** Returns the value of the data point. */ double getValue(); - /** List of exemplars collected from measurements that were used to form the data point. */ + /** List of exemplars collected from measurements aggregated into this point. */ @Override List getExemplars(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExemplarData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExemplarData.java index 9858007f6e6..03be80fc869 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExemplarData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExemplarData.java @@ -10,17 +10,16 @@ import javax.annotation.concurrent.Immutable; /** - * A sample input measurement. + * An example measurement. * - *

      Exemplars also hold information about the environment when the measurement was recorded, for - * example the span and trace ID of the active span when the exemplar was recorded. + *

      Provides details about a measurement that are normally aggregated away, including the + * measurement value, the measurement timestamp, and additional attributes. */ @Immutable public interface ExemplarData { /** - * The set of key/value pairs that were filtered out by the aggregator, but recorded alongside the - * original measurement. Only key/value pairs that were filtered out by the aggregator should be - * included. + * Returns the attributes that were recorded alongside the original measurement but filtered out + * by the aggregator. */ Attributes getFilteredAttributes(); diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramBuckets.java new file mode 100644 index 00000000000..6a0b6f61d31 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramBuckets.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramBuckets; +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * ExponentialHistogramBuckets represents either the positive or negative measurements taken for a + * {@link ExponentialHistogramPointData}. + * + *

      The bucket boundaries are lower-bound exclusive, and are calculated using the {@link + * ExponentialHistogramPointData#getScale()} and the {@link #getOffset()}. + * + *

      For example, assume {@link ExponentialHistogramPointData#getScale()} is 0, the base is 2.0. + * Then, if offset is 0, the bucket lower bounds would be 1.0, 2.0, 4.0, 8.0, etc. If + * offset is -3, the bucket lower bounds would be 0.125, 0.25, 0.5, 1.0, 2,0, etc. If + * offset is +3, the bucket lower bounds would be 8.0, 16.0, 32.0, etc. + * + * @since 1.23.0 + */ +@Immutable +public interface ExponentialHistogramBuckets { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static ExponentialHistogramBuckets create(int scale, int offset, List bucketCounts) { + return ImmutableExponentialHistogramBuckets.create(scale, offset, bucketCounts); + } + + /** The scale of the buckets. Must align with {@link ExponentialHistogramPointData#getScale()}. */ + int getScale(); + + /** + * The offset shifts the bucket boundaries according to lower_bound = base^(offset+i). + * . + * + * @return the offset. + */ + int getOffset(); + + /** + * The bucket counts is a list of counts representing number of measurements that fall into each + * bucket. + * + * @return the bucket counts. + */ + List getBucketCounts(); + + /** + * The total count is the sum of all the values in the buckets. + * + * @return the total count. + */ + long getTotalCount(); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramData.java new file mode 100644 index 00000000000..5cc442965b8 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramData.java @@ -0,0 +1,55 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import java.util.Collection; +import javax.annotation.concurrent.Immutable; + +/** + * A base-2 exponential histogram metric point, as defined by the OpenTelemetry Exponential + * Histogram specification. + * + *

      Note: This is called "ExponentialHistogramData" to reflect which primitives are used to + * record it, however "ExponentialHistogram" is the equivalent OTLP type. + * + * @see Exponential + * Histogram Data Model + * @see ExponentialHistogramPointData + * @since 1.23.0 + */ +@Immutable +public interface ExponentialHistogramData extends Data { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static ExponentialHistogramData create( + AggregationTemporality temporality, Collection points) { + return ImmutableExponentialHistogramData.create(temporality, points); + } + + /** + * Returns the {@code AggregationTemporality} of this metric. + * + *

      AggregationTemporality describes if the aggregator reports delta changes since last report + * time, or cumulative changes since a fixed start time. + * + * @return the {@code AggregationTemporality} of this metric + */ + AggregationTemporality getAggregationTemporality(); + + /** + * Returns the collection of {@link ExponentialHistogramPointData} for this histogram. + * + * @return the collection of data points for this histogram. + */ + @Override + Collection getPoints(); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramPointData.java similarity index 84% rename from sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramPointData.java rename to sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramPointData.java index 6d9bdc1b178..38a4a2b0d60 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramPointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramPointData.java @@ -3,13 +3,11 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram; +package io.opentelemetry.sdk.metrics.data; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; import java.util.List; -import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** @@ -20,27 +18,28 @@ *

      The bucket boundaries are calculated using both the scale {@link #getScale()}, and the offset * {@link ExponentialHistogramBuckets#getOffset()}. * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#exponentialhistogram - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. + * @see Exponential + * Histogram Data Model + * @since 1.23.0 */ @Immutable public interface ExponentialHistogramPointData extends PointData { /** - * Create an ExponentialHistogramPointData. + * Create a record. * - * @return an ExponentialHistogramPointData. + * @since 1.50.0 */ @SuppressWarnings("TooManyParameters") static ExponentialHistogramPointData create( int scale, double sum, long zeroCount, - @Nullable Double min, - @Nullable Double max, + boolean hasMin, + double min, + boolean hasMax, + double max, ExponentialHistogramBuckets positiveBuckets, ExponentialHistogramBuckets negativeBuckets, long startEpochNanos, @@ -52,7 +51,9 @@ static ExponentialHistogramPointData create( scale, sum, zeroCount, + hasMin, min, + hasMax, max, positiveBuckets, negativeBuckets, diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/GaugeData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/GaugeData.java index 67068bb2caf..87902860fea 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/GaugeData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/GaugeData.java @@ -5,13 +5,33 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import java.util.Collection; import javax.annotation.concurrent.Immutable; /** - * A gauge metric point. + * Data for a {@link MetricDataType#LONG_GAUGE} or {@link MetricDataType#DOUBLE_GAUGE} metric. * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#gauge + * @since 1.14.0 */ @Immutable -public interface GaugeData extends Data {} +public interface GaugeData extends Data { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static GaugeData createDoubleGaugeData(Collection points) { + return ImmutableGaugeData.create(points); + } + + /** + * Create a record. + * + * @since 1.50.0 + */ + static GaugeData createLongGaugeData(Collection points) { + return ImmutableGaugeData.create(points); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramData.java index 1560683b452..37068336ed8 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramData.java @@ -5,23 +5,29 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; import java.util.Collection; +import javax.annotation.concurrent.Immutable; /** - * A histogram metric recording. + * Data for a {@link MetricDataType#HISTOGRAM} metric. * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#histogram + * @since 1.14.0 */ +@Immutable public interface HistogramData extends Data { + /** - * Returns the {@code AggregationTemporality} of this metric, - * - *

      AggregationTemporality describes if the aggregator reports delta changes since last report - * time, or cumulative changes since a fixed start time. + * Create a record. * - * @return the {@code AggregationTemporality} of this metric + * @since 1.50.0 */ + static HistogramData create( + AggregationTemporality temporality, Collection points) { + return ImmutableHistogramData.create(temporality, points); + } + + /** Returns the histogram {@link AggregationTemporality}. */ AggregationTemporality getAggregationTemporality(); @Override diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramPointData.java index 3fa592f85de..48002563af8 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramPointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/HistogramPointData.java @@ -5,15 +5,51 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; +import java.util.Collections; import java.util.List; +import javax.annotation.concurrent.Immutable; /** - * A histogram metric point. + * Point data for {@link HistogramData}. * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#histogram + * @since 1.14.0 */ +@Immutable public interface HistogramPointData extends PointData { + + /** + * Create a record. + * + * @since 1.50.0 + */ + @SuppressWarnings("TooManyParameters") + static HistogramPointData create( + long startEpochNanos, + long epochNanos, + Attributes attributes, + double sum, + boolean hasMin, + double min, + boolean hasMax, + double max, + List boundaries, + List counts) { + return ImmutableHistogramPointData.create( + startEpochNanos, + epochNanos, + attributes, + sum, + hasMin, + min, + hasMax, + max, + boundaries, + counts, + Collections.emptyList()); + } + /** * The sum of all measurements recorded. * diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongExemplarData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongExemplarData.java index 53cbff59e95..bd17f75167e 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongExemplarData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongExemplarData.java @@ -5,8 +5,30 @@ package io.opentelemetry.sdk.metrics.data; -/** An {@link ExemplarData} with {@code long} measurements. */ +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongExemplarData; +import javax.annotation.concurrent.Immutable; + +/** + * Exemplar data for {@code long} measurements. + * + * @since 1.14.0 + */ +@Immutable public interface LongExemplarData extends ExemplarData { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static LongExemplarData create( + Attributes filteredAttributes, long recordTimeNanos, SpanContext spanContext, long value) { + return ImmutableLongExemplarData.create( + filteredAttributes, recordTimeNanos, spanContext, value); + } + /** Numerical value of the measurement that was recorded. */ long getValue(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongPointData.java index 811f6ff3bdf..fd2850bdfbc 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongPointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/LongPointData.java @@ -5,17 +5,33 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import java.util.Collections; import java.util.List; +/** + * A point data with a {@code double} aggregation value. + * + * @since 1.14.0 + */ public interface LongPointData extends PointData { + /** - * Returns the value of the data point. + * Create a record. * - * @return the value of the data point. + * @since 1.50.0 */ + static LongPointData create( + long startEpochNanos, long epochNanos, Attributes attributes, long value) { + return ImmutableLongPointData.create( + startEpochNanos, epochNanos, attributes, value, Collections.emptyList()); + } + + /** Returns the value of the data point. */ long getValue(); - /** List of exemplars collected from measurements that were used to form the data point. */ + /** List of exemplars collected from measurements aggregated into this point. */ @Override List getExemplars(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricData.java index 68eabf73854..771854341e6 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricData.java @@ -5,82 +5,95 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterBuilder; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; import io.opentelemetry.sdk.resources.Resource; import javax.annotation.concurrent.Immutable; /** - * A {@link ImmutableMetricData} represents the data exported as part of aggregating one {@code - * Instrument}. + * Metric data represents the aggregated measurements of an instrument. + * + * @since 1.14.0 */ @Immutable public interface MetricData { /** - * Returns the resource of this {@code MetricData}. + * Returns the metric {@link Resource}. * - * @return the resource of this {@code MetricData}. + *

      The {@link Resource} is configured via {@link + * SdkMeterProviderBuilder#setResource(Resource)}. */ Resource getResource(); /** - * Returns the instrumentation scope specified when creating the {@code Meter} which created the - * {@code Instrument} that produces {@code MetricData}. + * Returns the metric {@link InstrumentationScopeInfo}. * - * @return an instance of {@link InstrumentationScopeInfo} + *

      The {@link InstrumentationScopeInfo} is determined from the options used when {@link + * MeterBuilder#build()}ing the {@link Meter}. */ InstrumentationScopeInfo getInstrumentationScopeInfo(); /** * Returns the metric name. * - * @return the metric name. + *

      The metric name is typically the instrument name, but may be optionally overridden by a + * {@link View}. */ String getName(); /** - * Returns the description of this metric. + * Returns the metric description. * - * @return the description of this metric. + *

      The metric name is typically the instrument description, but may be optionally overridden by + * a {@link View}. */ String getDescription(); - /** - * Returns the unit of this metric. - * - * @return the unit of this metric. - */ + /** Returns the metric unit. */ String getUnit(); - /** - * Returns the type of this metric. - * - * @return the type of this metric. - */ + /** Returns the type of this metric. */ MetricDataType getType(); - Data getData(); - /** - * Returns {@code true} if there are no points associated with this metric. + * Returns the unconstrained metric data. * - * @return {@code true} if there are no points associated with this metric. + *

      Most will instead prefer to access the constrained metric data after first checking the + * {@link #getType()}: + * + *

      {@code
      +   * //  if (metricData.getType() == MetricDataType.LONG_SUM) {
      +   * //    SumData sumData = metricData.getLongSumData();
      +   * //    ... // Process long sum data
      +   * //  }
      +   * }
      + * + * @see #getDoubleGaugeData() + * @see #getLongGaugeData() + * @see #getDoubleSumData() + * @see #getLongSumData() + * @see #getHistogramData() + * @see #getSummaryData() */ + Data getData(); + + /** Returns {@code true} if there are no points associated with this metric. */ default boolean isEmpty() { return getData().getPoints().isEmpty(); } /** - * Returns the {@code DoubleGaugeData} if type is {@link MetricDataType#DOUBLE_GAUGE}, otherwise a - * default empty data. - * - * @return the {@code DoubleGaugeData} if type is {@link MetricDataType#DOUBLE_GAUGE}, otherwise a - * default empty data. + * Returns the {@code double} {@link GaugeData} if type is {@link MetricDataType#DOUBLE_GAUGE}, + * otherwise a default empty data. */ @SuppressWarnings("unchecked") default GaugeData getDoubleGaugeData() { @@ -91,11 +104,8 @@ default GaugeData getDoubleGaugeData() { } /** - * Returns the {@code LongGaugeData} if type is {@link MetricDataType#LONG_GAUGE}, otherwise a - * default empty data. - * - * @return the {@code LongGaugeData} if type is {@link MetricDataType#LONG_GAUGE}, otherwise a - * default empty data. + * Returns the {@code long} {@link GaugeData} if type is {@link MetricDataType#LONG_GAUGE}, + * otherwise a default empty data. */ @SuppressWarnings("unchecked") default GaugeData getLongGaugeData() { @@ -106,26 +116,20 @@ default GaugeData getLongGaugeData() { } /** - * Returns the {@code DoubleSumData} if type is {@link MetricDataType#DOUBLE_SUM}, otherwise a - * default empty data. - * - * @return the {@code DoubleSumData} if type is {@link MetricDataType#DOUBLE_SUM}, otherwise a - * default empty data. + * Returns the {@code double} {@link SumData} if type is {@link MetricDataType#DOUBLE_SUM}, + * otherwise a default empty data. */ @SuppressWarnings("unchecked") default SumData getDoubleSumData() { if (getType() == MetricDataType.DOUBLE_SUM) { - return (ImmutableSumData) getData(); + return (SumData) getData(); } return ImmutableSumData.empty(); } /** - * Returns the {@code LongSumData} if type is {@link MetricDataType#LONG_SUM}, otherwise a default - * empty data. - * - * @return the {@code LongSumData} if type is {@link MetricDataType#LONG_SUM}, otherwise a default - * empty data. + * Returns the {@code long} {@link SumData} if type is {@link MetricDataType#LONG_SUM}, otherwise + * a default empty data. */ @SuppressWarnings("unchecked") default SumData getLongSumData() { @@ -136,11 +140,8 @@ default SumData getLongSumData() { } /** - * Returns the {@code DoubleSummaryData} if type is {@link MetricDataType#SUMMARY}, otherwise a - * default empty data. - * - * @return the {@code DoubleSummaryData} if type is {@link MetricDataType#SUMMARY}, otherwise a - * default * empty data. + * Returns the {@link SummaryData} if type is {@link MetricDataType#SUMMARY}, otherwise a default + * empty data. */ default SummaryData getSummaryData() { if (getType() == MetricDataType.SUMMARY) { @@ -150,11 +151,8 @@ default SummaryData getSummaryData() { } /** - * Returns the {@code DoubleHistogramData} if type is {@link MetricDataType#HISTOGRAM}, otherwise - * a default empty data. - * - * @return the {@code DoubleHistogramData} if type is {@link MetricDataType#HISTOGRAM}, otherwise - * a default empty data. + * Returns the {@link HistogramData} if type is {@link MetricDataType#HISTOGRAM}, otherwise a + * default empty data. */ default HistogramData getHistogramData() { if (getType() == MetricDataType.HISTOGRAM) { @@ -162,4 +160,15 @@ default HistogramData getHistogramData() { } return ImmutableHistogramData.empty(); } + + /** + * Returns the {@link ExponentialHistogramData} if type is {@link + * MetricDataType#EXPONENTIAL_HISTOGRAM}, otherwise a default empty data. + */ + default ExponentialHistogramData getExponentialHistogramData() { + if (getType() == MetricDataType.EXPONENTIAL_HISTOGRAM) { + return (ExponentialHistogramData) getData(); + } + return ImmutableExponentialHistogramData.empty(); + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricDataType.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricDataType.java index ea782dafd30..f00d9e32958 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricDataType.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/MetricDataType.java @@ -5,12 +5,13 @@ package io.opentelemetry.sdk.metrics.data; -/** The kind of metric. It describes how the data is reported. */ +/** + * The type of metric {@link PointData}. + * + * @since 1.14.0 + */ public enum MetricDataType { - /** - * A Gauge represents a measurement of a long value at a moment in time. Generally only one - * instance of a given Gauge metric will be reported per reporting interval. - */ + /** A Gauge represents a measurement of a long value at a moment in time. */ LONG_GAUGE, /** @@ -19,15 +20,16 @@ public enum MetricDataType { */ DOUBLE_GAUGE, - /** A sum of non negative long (int64) values. */ + /** A Sum of long (int64) values. */ LONG_SUM, - /** A sum of non negative double values. */ + /** A Sum of double values. */ DOUBLE_SUM, /** - * A Summary of measurements of numeric values, containing the minimum value recorded, the maximum - * value recorded, the sum of all measurements and the total number of measurements recorded. + * A Summary of measurements of numeric values, the sum of all measurements and the total number + * of measurements recorded, and quantiles describing the distribution of measurements (often + * including minimum "0.0" and maximum "1.0" quantiles). */ SUMMARY, diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/PointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/PointData.java index 37096653dde..4e19c603e99 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/PointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/PointData.java @@ -7,39 +7,25 @@ import io.opentelemetry.api.common.Attributes; import java.util.List; -import javax.annotation.concurrent.Immutable; /** - * A point in the "Metric stream" data model. + * A point in the metric data model. * - *

      This is distinguished from {@code Measurement} in that it may have aggregated data, and has - * its type defined by the metric data model (no longer an instrument). + *

      A point represents the aggregation of measurements recorded with a particular set of {@link + * Attributes} over some time interval. + * + * @since 1.14.0 */ -@Immutable public interface PointData { - /** - * Returns the start epoch timestamp in nanos of this {@code Instrument}, usually the time when - * the metric was created or an aggregation was enabled. - * - * @return the start epoch timestamp in nanos. - */ + /** Returns the start time of the aggregation in epoch nanos. */ long getStartEpochNanos(); - /** - * Returns the epoch timestamp in nanos when data were collected, usually it represents the moment - * when {@code Instrument.getData()} was called. - * - * @return the epoch timestamp in nanos. - */ + /** Returns the end time of the aggregation in epoch nanos. */ long getEpochNanos(); - /** - * Returns the attributes associated with this {@code Point}. - * - * @return the attributes associated with this {@code Point}. - */ + /** Returns the attributes of the aggregation. */ Attributes getAttributes(); - /** List of exemplars collected from measurements that were used to form the data point. */ + /** List of exemplars collected from measurements aggregated into this point. */ List getExemplars(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SumData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SumData.java index 369f67ab2ba..ad1553d5e94 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SumData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SumData.java @@ -5,30 +5,41 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import java.util.Collection; import javax.annotation.concurrent.Immutable; /** - * A sum metric point. + * Data for a {@link MetricDataType#LONG_SUM} or {@link MetricDataType#DOUBLE_SUM} metric. * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#sums + * @since 1.14.0 */ @Immutable public interface SumData extends Data { + /** - * Returns "true" if the sum is monotonic. + * Create a record. * - * @return "true" if the sum is monotonic + * @since 1.50.0 */ - boolean isMonotonic(); + static SumData createLongSumData( + boolean isMonotonic, AggregationTemporality temporality, Collection points) { + return ImmutableSumData.create(isMonotonic, temporality, points); + } /** - * Returns the {@code AggregationTemporality} of this metric, - * - *

      AggregationTemporality describes if the aggregator reports delta changes since last report - * time, or cumulative changes since a fixed start time. + * Create a record. * - * @return the {@code AggregationTemporality} of this metric + * @since 1.50.0 */ + static SumData createDoubleSumData( + boolean isMonotonic, AggregationTemporality temporality, Collection points) { + return ImmutableSumData.create(isMonotonic, temporality, points); + } + + /** Returns "true" if the sum is monotonic. */ + boolean isMonotonic(); + + /** Returns the sum {@link AggregationTemporality}. */ AggregationTemporality getAggregationTemporality(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryData.java index 3fad678a180..889a1aeaaa6 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryData.java @@ -5,10 +5,24 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import java.util.Collection; +import javax.annotation.concurrent.Immutable; + /** - * A summary metric. + * Data for a {@link MetricDataType#SUMMARY} metric. * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#summary + * @since 1.14.0 */ -public interface SummaryData extends Data {} +@Immutable +public interface SummaryData extends Data { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static SummaryData create(Collection points) { + return ImmutableSummaryData.create(points); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryPointData.java index 37833dfce3c..4353448d86d 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryPointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/SummaryPointData.java @@ -5,19 +5,46 @@ package io.opentelemetry.sdk.metrics.data; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; import java.util.List; +import javax.annotation.concurrent.Immutable; -/** A single data point that summarizes the values in a time series of numeric values. */ +/** + * Point data for {@link SummaryData}. + * + * @since 1.14.0 + */ +@Immutable public interface SummaryPointData extends PointData { - /** Returns the number of values that are being summarized. */ + + /** + * Create a record. + * + * @since 1.50.0 + */ + static SummaryPointData create( + long startEpochNanos, + long epochNanos, + Attributes attributes, + long count, + double sum, + List percentileValues) { + return ImmutableSummaryPointData.create( + startEpochNanos, epochNanos, attributes, count, sum, percentileValues); + } + + /** Returns the count of measurements. */ long getCount(); - /** Returns the sum of all the values that are being summarized. */ + /** Returns the sum of measurements. */ double getSum(); /** - * Returns the values in the summarization. Note: a quantile 0.0 represents the minimum value in - * the distribution. + * Returns the list of values at different quantiles in the distribution of measurements. + * + *

      Note: a quantile 0.0 represents the minimum value in the distribution; a quantile 1.0 + * represents the maximum value in the distribution. */ List getValues(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantile.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantile.java index 47ea99b6fd7..d0b8a0911bc 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantile.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantile.java @@ -5,11 +5,29 @@ package io.opentelemetry.sdk.metrics.data; -/** A value within a summary. */ +import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; +import javax.annotation.concurrent.Immutable; + +/** + * A quantile value within a {@link SummaryPointData}. + * + * @since 1.14.0 + */ +@Immutable public interface ValueAtQuantile { + + /** + * Create a record. + * + * @since 1.50.0 + */ + static ValueAtQuantile create(double quantile, double value) { + return ImmutableValueAtQuantile.create(quantile, value); + } + /** Returns the quantile of a distribution. Must be in the interval [0.0, 1.0]. */ double getQuantile(); - /** Returns the value at the given percentile of a distribution. */ + /** Returns the value at the given quantile of a distribution. */ double getValue(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/package-info.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/package-info.java index 528673ec436..218a6cb2ad5 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/package-info.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/data/package-info.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -/** The data format to model metrics for export. */ +/** Classes which form the in-memory representation of the OpenTelemetry metrics data model. */ @ParametersAreNonnullByDefault package io.opentelemetry.sdk.metrics.data; diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelector.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelector.java index 5e3023be48c..f50e2bc5676 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelector.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelector.java @@ -7,10 +7,13 @@ import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import java.util.StringJoiner; /** * A functional interface that selects {@link AggregationTemporality} based on {@link * InstrumentType}. + * + * @since 1.14.0 */ @FunctionalInterface public interface AggregationTemporalitySelector { @@ -47,6 +50,45 @@ static AggregationTemporalitySelector deltaPreferred() { }; } + /** + * A common implementation of {@link AggregationTemporalitySelector} which reduces memory. + * + *

      {@link AggregationTemporality#DELTA} is returned for {@link InstrumentType#COUNTER} and + * {@link InstrumentType#HISTOGRAM}. {@link AggregationTemporality#CUMULATIVE} is returned for + * {@link InstrumentType#UP_DOWN_COUNTER}, {@link InstrumentType#OBSERVABLE_UP_DOWN_COUNTER}, and + * {@link InstrumentType#OBSERVABLE_COUNTER}. + * + * @since 1.28.0 + */ + static AggregationTemporalitySelector lowMemory() { + return instrumentType -> { + switch (instrumentType) { + case UP_DOWN_COUNTER: + case OBSERVABLE_UP_DOWN_COUNTER: + case OBSERVABLE_COUNTER: + return AggregationTemporality.CUMULATIVE; + case COUNTER: + case HISTOGRAM: + default: + return AggregationTemporality.DELTA; + } + }; + } + /** Return the aggregation temporality for the {@link InstrumentType}. */ AggregationTemporality getAggregationTemporality(InstrumentType instrumentType); + + /** + * Returns a string representation of this selector, for using in {@link Object#toString()} + * implementations. + * + * @since 1.38.0 + */ + static String asString(AggregationTemporalitySelector selector) { + StringJoiner joiner = new StringJoiner(", ", "AggregationTemporalitySelector{", "}"); + for (InstrumentType type : InstrumentType.values()) { + joiner.add(type.name() + "=" + selector.getAggregationTemporality(type).name()); + } + return joiner.toString(); + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CardinalityLimitSelector.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CardinalityLimitSelector.java new file mode 100644 index 00000000000..43318b2ce0b --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CardinalityLimitSelector.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; + +/** + * Customize the {@link io.opentelemetry.sdk.metrics.export.MetricReader} cardinality limit as a + * function of {@link InstrumentType}. Register via {@link + * SdkMeterProviderBuilder#registerMetricReader(MetricReader, CardinalityLimitSelector)}. + * + * @since 1.44.0 + */ +@FunctionalInterface +public interface CardinalityLimitSelector { + + /** + * The default {@link CardinalityLimitSelector}, allowing each metric to have {@code 2000} points. + */ + static CardinalityLimitSelector defaultCardinalityLimitSelector() { + return unused -> MetricStorage.DEFAULT_MAX_CARDINALITY; + } + + /** + * Return the default cardinality limit for metrics from instruments of type {@code + * instrumentType}. The cardinality limit dictates the maximum number of distinct points (or time + * series) for the metric. + */ + int getCardinalityLimit(InstrumentType instrumentType); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CollectionRegistration.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CollectionRegistration.java index 97793c8fbcc..fbe117aecba 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CollectionRegistration.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/CollectionRegistration.java @@ -5,11 +5,40 @@ package io.opentelemetry.sdk.metrics.export; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.data.MetricData; +import java.util.Collection; +import java.util.Collections; /** * A {@link CollectionRegistration} is passed to each {@link MetricReader} registered with {@link * SdkMeterProvider}, and provides readers the ability to trigger metric collections. + * + * @since 1.14.0 */ -// TODO(jack-berg): Have methods when custom MetricReaders are supported -public interface CollectionRegistration {} +public interface CollectionRegistration { + + /** + * Returns a noop {@link CollectionRegistration}, useful for {@link MetricReader}s to hold before + * {@link MetricReader#register(CollectionRegistration)} is called. + * + * @since 1.31.0 + */ + static CollectionRegistration noop() { + return new CollectionRegistration() {}; + } + + /** + * Collect all metrics, including metrics from the SDK and any registered {@link MetricProducer}s. + * + *

      If {@link MetricReader#getMemoryMode()} is configured to {@link MemoryMode#REUSABLE_DATA} do + * not keep the result or any of its contained objects as they are to be reused to return the + * result for the next call to this method. + * + * @since 1.31.0 + */ + default Collection collectAllMetrics() { + return Collections.emptyList(); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/DefaultAggregationSelector.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/DefaultAggregationSelector.java new file mode 100644 index 00000000000..d6d3058abd9 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/DefaultAggregationSelector.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; +import java.util.StringJoiner; + +/** + * A functional interface that selects default {@link Aggregation} based on {@link InstrumentType}. + * + * @since 1.16.0 + */ +@FunctionalInterface +public interface DefaultAggregationSelector { + + /** + * The default implementation of {@link DefaultAggregationSelector} which returns the default + * aggregation for each instrument. + */ + static DefaultAggregationSelector getDefault() { + return instrumentType -> Aggregation.defaultAggregation(); + } + + /** + * Returns a default aggregation selector which returns the given {@code aggregation} for the + * given {@code instrumentType}, and defers to this for other instrument types. + * + *

      For example, the following produces a selector which drops histograms and uses the default + * aggregation for other instruments: + * + *

      {@code
      +   * // DefaultAggregationSelector selector =
      +   * //   DefaultAggregationSelector.getDefault()
      +   * //     .with(InstrumentType.HISTOGRAM, Aggregation.drop());
      +   * }
      + * + * @since 1.16.0 + */ + default DefaultAggregationSelector with(InstrumentType instrumentType, Aggregation aggregation) { + requireNonNull(instrumentType, "instrumentType"); + requireNonNull(aggregation, "aggregation"); + return instrumentType1 -> { + if (instrumentType1 == instrumentType) { + return aggregation; + } + return getDefaultAggregation(instrumentType1); + }; + } + + /** + * Return the default aggregation for the {@link InstrumentType}. + * + *

      The default aggregation is used when an instrument does not match any views. + */ + Aggregation getDefaultAggregation(InstrumentType instrumentType); + + /** + * Returns a string representation of this selector, for using in {@link Object#toString()} + * implementations. + * + * @since 1.38.0 + */ + static String asString(DefaultAggregationSelector selector) { + StringJoiner joiner = new StringJoiner(", ", "DefaultAggregationSelector{", "}"); + for (InstrumentType type : InstrumentType.values()) { + joiner.add( + type.name() + + "=" + + AggregationUtil.aggregationName(selector.getDefaultAggregation(type))); + } + return joiner.toString(); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExportBatcher.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExportBatcher.java new file mode 100644 index 00000000000..ee2d5320445 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExportBatcher.java @@ -0,0 +1,187 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.HistogramData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.data.SumData; +import io.opentelemetry.sdk.metrics.data.SummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * Batches metric data into multiple batches based on the maximum export batch size. This is used by + * the {@link PeriodicMetricReader} to batch metric data before exporting it. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +class MetricExportBatcher { + + private MetricExportBatcher() {} + + private static void validateMaxExportBatchSize(int maxExportBatchSize) { + if (maxExportBatchSize <= 0) { + throw new IllegalArgumentException("maxExportBatchSize must be positive"); + } + } + + /** + * Batches the given metric data into multiple batches based on the maximum export batch size. + * + * @param metrics The collection of metric data objects to batch based on the number of data + * points they contain. + * @return A collection of batches of metric data. + */ + static Collection> batchMetrics( + Collection metrics, int maxExportBatchSize) { + validateMaxExportBatchSize(maxExportBatchSize); + if (metrics.isEmpty()) { + return Collections.emptyList(); + } + Collection> preparedBatchesForExport = new ArrayList<>(); + List currentBatch = new ArrayList<>(maxExportBatchSize); + int currentPointsInBatch = 0; + for (MetricData metricData : metrics) { + int totalPointsInMetric = metricData.getData().getPoints().size(); + if (currentPointsInBatch + totalPointsInMetric <= maxExportBatchSize) { + currentBatch.add(metricData); + currentPointsInBatch += totalPointsInMetric; + continue; + } + int currentIndex = 0; + List originalPointsList = new ArrayList<>(metricData.getData().getPoints()); + while (currentIndex < totalPointsInMetric) { + if (currentPointsInBatch == maxExportBatchSize) { + preparedBatchesForExport.add(currentBatch); + currentBatch = new ArrayList<>(maxExportBatchSize); + currentPointsInBatch = 0; + } + int pointsToTake = + Math.min(maxExportBatchSize - currentPointsInBatch, totalPointsInMetric - currentIndex); + currentBatch.add( + copyMetricData(metricData, originalPointsList, currentIndex, pointsToTake)); + currentPointsInBatch += pointsToTake; + currentIndex += pointsToTake; + } + } + if (!currentBatch.isEmpty()) { + preparedBatchesForExport.add(currentBatch); + } + return Collections.unmodifiableCollection(preparedBatchesForExport); + } + + private static MetricData copyMetricData( + MetricData original, + List originalPointsList, + int dataPointsOffset, + int dataPointsToTake) { + List points = + Collections.unmodifiableList( + new ArrayList<>( + originalPointsList.subList(dataPointsOffset, dataPointsOffset + dataPointsToTake))); + return createMetricDataWithPoints(original, points); + } + + /** + * Creates a new MetricData with the given points. + * + * @param original The original MetricData. + * @param points The points to use for the new MetricData. + * @return A new MetricData with the given points. + */ + @SuppressWarnings("unchecked") + private static MetricData createMetricDataWithPoints( + MetricData original, Collection points) { + switch (original.getType()) { + case DOUBLE_GAUGE: + return ImmutableMetricData.createDoubleGauge( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableGaugeData.create((Collection) (Collection) points)); + case LONG_GAUGE: + return ImmutableMetricData.createLongGauge( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableGaugeData.create((Collection) (Collection) points)); + case DOUBLE_SUM: + SumData doubleSumData = original.getDoubleSumData(); + return ImmutableMetricData.createDoubleSum( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableSumData.create( + doubleSumData.isMonotonic(), + doubleSumData.getAggregationTemporality(), + (Collection) (Collection) points)); + case LONG_SUM: + SumData longSumData = original.getLongSumData(); + return ImmutableMetricData.createLongSum( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableSumData.create( + longSumData.isMonotonic(), + longSumData.getAggregationTemporality(), + (Collection) (Collection) points)); + case HISTOGRAM: + HistogramData histogramData = original.getHistogramData(); + return ImmutableMetricData.createDoubleHistogram( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableHistogramData.create( + histogramData.getAggregationTemporality(), + (Collection) (Collection) points)); + case EXPONENTIAL_HISTOGRAM: + ExponentialHistogramData expHistogramData = original.getExponentialHistogramData(); + return ImmutableMetricData.createExponentialHistogram( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableExponentialHistogramData.create( + expHistogramData.getAggregationTemporality(), + (Collection) (Collection) points)); + case SUMMARY: + return ImmutableMetricData.createDoubleSummary( + original.getResource(), + original.getInstrumentationScopeInfo(), + original.getName(), + original.getDescription(), + original.getUnit(), + ImmutableSummaryData.create((Collection) (Collection) points)); + } + throw new UnsupportedOperationException("Unsupported metric type: " + original.getType()); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExporter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExporter.java index 96d6ac2c635..685c5f09bf1 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExporter.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricExporter.java @@ -5,41 +5,72 @@ package io.opentelemetry.sdk.metrics.export; +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; + import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.data.MetricData; import java.io.Closeable; import java.util.Collection; import java.util.concurrent.TimeUnit; /** - * {@code MetricExporter} is the interface that all "push based" metric libraries should use to - * export metrics to the OpenTelemetry exporters. + * A Metric Exporter is a push based interface for exporting {@link MetricData} out of {@link + * SdkMeterProvider}. + * + *

      To use, associate an exporter with a {@link PeriodicMetricReader}, and register with the + * metrics SDK via {@link SdkMeterProviderBuilder#registerMetricReader(MetricReader)}. * - *

      All OpenTelemetry exporters should allow access to a {@code MetricExporter} instance. + * @since 1.14.0 */ -public interface MetricExporter extends AggregationTemporalitySelector, Closeable { +public interface MetricExporter + extends AggregationTemporalitySelector, DefaultAggregationSelector, Closeable { + + /** + * Return the default aggregation for the {@link InstrumentType}. + * + * @see DefaultAggregationSelector#getDefaultAggregation(InstrumentType) + * @since 1.16.0 + */ + @Override + default Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return Aggregation.defaultAggregation(); + } /** - * Exports the collection of given {@link MetricData}. Note that export operations can be - * performed simultaneously depending on the type of metric reader being used. However, the caller - * MUST ensure that only one export can occur at a time. + * Returns the memory mode used by this exporter's associated reader. * - * @param metrics the collection of {@link MetricData} to be exported. + * @return The {@link MemoryMode} used by this exporter's associated reader + * @since 1.31.0 + */ + default MemoryMode getMemoryMode() { + return IMMUTABLE_DATA; + } + + /** + * Exports the {@code metrics}. The caller (i.e. {@link PeriodicMetricReader} will not call export + * until the previous call completes. + * + * @param metrics the metrics to export. * @return the result of the export, which is often an asynchronous operation. */ CompletableResultCode export(Collection metrics); /** - * Exports the collection of {@link MetricData} that have not yet been exported. Note that flush - * operations can be performed simultaneously depending on the type of metric reader being used. - * However, the caller MUST ensure that only one export can occur at a time. + * A hint that any metrics previously {@link #export(Collection)}ed should be completed. * * @return the result of the flush, which is often an asynchronous operation. */ CompletableResultCode flush(); /** - * Called when the associated IntervalMetricReader is shutdown. + * Shuts down the exporter. + * + *

      Called when {@link PeriodicMetricReader#shutdown()} of the associated reader is called. * * @return a {@link CompletableResultCode} which is completed when shutdown completes. */ diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricProducer.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricProducer.java new file mode 100644 index 00000000000..c636a187c64 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricProducer.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import javax.annotation.concurrent.ThreadSafe; + +/** + * {@link MetricProducer} is the interface that is used to make metric data available to the {@link + * MetricReader}s. The primary implementation is provided by {@link + * io.opentelemetry.sdk.metrics.SdkMeterProvider}. + * + *

      Alternative {@link MetricProducer} implementations can be used to bridge aggregated metrics + * from other frameworks, and are registered with {@link + * SdkMeterProviderBuilder#registerMetricProducer(MetricProducer)}. NOTE: When possible, metrics + * from other frameworks should be bridged using the metric API, normally with asynchronous + * instruments which observe the aggregated state of the other framework. However, {@link + * MetricProducer} exists to accommodate scenarios where the metric API is insufficient. It should + * be used with caution as it requires the bridge to take a dependency on {@code + * opentelemetry-sdk-metrics}, which is generally not advised. + * + *

      Implementations must be thread-safe. + * + * @since 1.31.0 + */ +@ThreadSafe +public interface MetricProducer { + + /** + * Returns a collection of produced {@link MetricData}s to be exported. This will only be those + * metrics that have been produced since the last time this method was called. + * + * @return a collection of produced {@link MetricData}s to be exported. + */ + Collection produce(Resource resource); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReader.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReader.java index 54e0ee5d6ae..7ddab97dfc1 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReader.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReader.java @@ -5,34 +5,57 @@ package io.opentelemetry.sdk.metrics.export; +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; + import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.SdkMeterProvider; -import java.util.Collection; +import java.io.Closeable; +import java.io.IOException; +import java.util.concurrent.TimeUnit; /** - * A reader of metrics from {@link SdkMeterProvider}. + * A metric reader reads metrics from an {@link SdkMeterProvider}. * - *

      Custom implementations of {@link MetricReader} are not currently supported. Please use one of - * the built-in readers such as {@link PeriodicMetricReader}. + * @since 1.14.0 */ -public interface MetricReader extends AggregationTemporalitySelector { +public interface MetricReader + extends AggregationTemporalitySelector, DefaultAggregationSelector, Closeable { /** - * Called by {@link SdkMeterProvider} and supplies the {@link MetricReader} with a handle to - * collect metrics. - * - *

      {@link CollectionRegistration} is currently an empty interface because custom - * implementations of {@link MetricReader} are not currently supported. + * Called by {@link SdkMeterProvider} on initialization to supply the {@link MetricReader} with + * {@link MetricProducer}s used to collect metrics. {@link MetricReader} implementations call + * {@link CollectionRegistration#collectAllMetrics()} to read metrics. */ void register(CollectionRegistration registration); /** - * Flushes metrics read by this reader. + * Return the default aggregation for the {@link InstrumentType}. * - *

      In all scenarios, the trigger a metrics collection. + * @see DefaultAggregationSelector#getDefaultAggregation(InstrumentType) + * @since 1.16.0 + */ + @Override + default Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return Aggregation.defaultAggregation(); + } + + /** + * Returns the memory mode used by this reader. * - *

      For readers associated with push {@link MetricExporter}s, this should {@link - * MetricExporter#export(Collection)} the collected metrics. + * @return The {@link MemoryMode} used by this instance + * @since 1.31.0 + */ + default MemoryMode getMemoryMode() { + return IMMUTABLE_DATA; + } + + /** + * Read and export the metrics. + * + *

      Called when {@link SdkMeterProvider#forceFlush()} is called. * * @return the result of the flush. */ @@ -41,12 +64,21 @@ public interface MetricReader extends AggregationTemporalitySelector { /** * Shuts down the metric reader. * - *

      For pull endpoints, like prometheus, this should shut down the metric hosting endpoint or + *

      Called when {@link SdkMeterProvider#shutdown()} is called. + * + *

      For pull based readers like prometheus, this should shut down the metric hosting endpoint or * server doing such a job. * - *

      For push endpoints, this should shut down any scheduler threads. + *

      For push based readers like {@link MetricExporter}, this should shut down any scheduler + * threads. * * @return the result of the shutdown. */ CompletableResultCode shutdown(); + + /** Close this {@link MetricReader}, releasing any resources. */ + @Override + default void close() throws IOException { + shutdown().join(10, TimeUnit.SECONDS); + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReaderInstrumentation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReaderInstrumentation.java new file mode 100644 index 00000000000..1d243f7050f --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/MetricReaderInstrumentation.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import java.util.Collections; +import javax.annotation.Nullable; + +final class MetricReaderInstrumentation { + + private final DoubleHistogram collectionDuration; + private final Attributes standardAttrs; + + MetricReaderInstrumentation(ComponentId componentId, MeterProvider meterProvider) { + Meter meter = meterProvider.get("io.opentelemetry.sdk.metrics"); + + standardAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName()); + + collectionDuration = + meter + .histogramBuilder(SemConvConstants.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_NAME) + .setUnit(SemConvConstants.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_METRIC_READER_COLLECTION_DURATION_DESCRIPTION) + .setExplicitBucketBoundariesAdvice(Collections.emptyList()) + .build(); + } + + void recordCollection(double seconds, @Nullable String error) { + Attributes attrs = standardAttrs; + if (error != null) { + attrs = attrs.toBuilder().put(SemConvConstants.ERROR_TYPE, error).build(); + } + + collectionDuration.record(seconds, attrs); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java index 41a81ecff82..eb8668db984 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReader.java @@ -5,13 +5,22 @@ package io.opentelemetry.sdk.metrics.export; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; import java.util.Collection; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @@ -22,25 +31,51 @@ /** * A {@link MetricReader} which wraps a {@link MetricExporter} and automatically reads and exports - * the metrics every export interval. Metrics may also be dropped when it becomes time to export - * again, and there is an export in progress. + * the metrics every export interval. + * + *

      Register with {@link SdkMeterProvider} via {@link + * SdkMeterProviderBuilder#registerMetricReader(MetricReader)}. + * + * @since 1.14.0 */ public final class PeriodicMetricReader implements MetricReader { private static final Logger logger = Logger.getLogger(PeriodicMetricReader.class.getName()); + private static final Clock CLOCK = Clock.getDefault(); + + private static final ComponentId COMPONENT_ID = + ComponentId.generateLazy("periodic_metric_reader"); + private final MetricExporter exporter; private final long intervalNanos; + private final long exporterTimeoutNanos; + private final int maxExportBatchSize; + private final InternalTelemetryVersion internalTelemetryVersion; + + // Fires periodic tick signals. Does not run the actual export. private final ScheduledExecutorService scheduler; - private final Scheduled scheduled; - private final Object lock = new Object(); + // Owns the export loop. Reads Signals from the queue and processes them sequentially. + private final Thread worker; + private final BlockingQueue signals = new LinkedBlockingQueue<>(); + + // True while a periodic tick is queued or being processed. Guards against multiple ticks + // stacking up if the exporter is slower than the interval; matches the pre-refactor behavior of + // dropping ticks while an export is in flight (no catch-up). + private final AtomicBoolean tickPending = new AtomicBoolean(false); + + private final AtomicBoolean started = new AtomicBoolean(false); + private final AtomicBoolean shutdown = new AtomicBoolean(false); + private final Object startLock = new Object(); - private volatile MetricProducer metricProducer = MetricProducer.noop(); + private volatile CollectionRegistration collectionRegistration = CollectionRegistration.noop(); @Nullable private volatile ScheduledFuture scheduledFuture; + private volatile MetricReaderInstrumentation instrumentation = + new MetricReaderInstrumentation(COMPONENT_ID, MeterProvider.noop()); + /** - * Returns a new {@link PeriodicMetricReader} which can be registered to a {@link - * SdkMeterProvider} to start a {@link PeriodicMetricReader} exporting once every minute on a new - * daemon thread. + * Returns a new {@link PeriodicMetricReader} which exports to the {@code exporter} once every + * minute. */ public static PeriodicMetricReader create(MetricExporter exporter) { return builder(exporter).build(); @@ -52,11 +87,20 @@ public static PeriodicMetricReaderBuilder builder(MetricExporter exporter) { } PeriodicMetricReader( - MetricExporter exporter, long intervalNanos, ScheduledExecutorService scheduler) { + MetricExporter exporter, + long intervalNanos, + long exporterTimeoutNanos, + ScheduledExecutorService scheduler, + int maxExportBatchSize, + InternalTelemetryVersion internalTelemetryVersion) { this.exporter = exporter; this.intervalNanos = intervalNanos; + this.exporterTimeoutNanos = exporterTimeoutNanos; this.scheduler = scheduler; - this.scheduled = new Scheduled(); + this.maxExportBatchSize = maxExportBatchSize; + this.internalTelemetryVersion = internalTelemetryVersion; + this.worker = + new DaemonThreadFactory("PeriodicMetricReader-worker").newThread(this::workerLoop); } @Override @@ -64,48 +108,104 @@ public AggregationTemporality getAggregationTemporality(InstrumentType instrumen return exporter.getAggregationTemporality(instrumentType); } + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return exporter.getDefaultAggregation(instrumentType); + } + + @Override + public MemoryMode getMemoryMode() { + return exporter.getMemoryMode(); + } + + /** + * Forces a flush of all metrics. + * + *

      If an export is already in progress, the flush will be queued behind it and completed when + * the requested cycle finishes. + */ @Override public CompletableResultCode forceFlush() { - return scheduled.doRun(); + if (shutdown.get()) { + return CompletableResultCode.ofSuccess(); + } + CompletableResultCode collectExport = new CompletableResultCode(); + signals.offer(Signal.flush(collectExport)); + CompletableResultCode result = new CompletableResultCode(); + collectExport.whenComplete(() -> { + CompletableResultCode flushResult = exporter.flush(); + flushResult.whenComplete(() -> { + if (collectExport.isSuccess() && flushResult.isSuccess()) { + result.succeed(); + } else { + result.fail(); + } + }); + }); + return result; } @Override public CompletableResultCode shutdown() { - CompletableResultCode result = new CompletableResultCode(); - ScheduledFuture scheduledFuture = this.scheduledFuture; - if (scheduledFuture != null) { - scheduledFuture.cancel(false); + if (!shutdown.compareAndSet(false, true)) { + return CompletableResultCode.ofSuccess(); + } + + ScheduledFuture future = this.scheduledFuture; + if (future != null) { + future.cancel(false); } scheduler.shutdown(); + + // Final flush + poison. Worker drains the flush signal, completes it, then exits on POISON. + CompletableResultCode finalFlush = new CompletableResultCode(); + signals.offer(Signal.flush(finalFlush)); + signals.offer(Signal.poison()); + + // Block until the worker drains the final flush and terminates. This preserves the + // pre-refactor semantic that shutdown() does not return until the final export has completed. + finalFlush.join(5, TimeUnit.SECONDS); + try { + worker.join(TimeUnit.SECONDS.toMillis(5)); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } try { scheduler.awaitTermination(5, TimeUnit.SECONDS); - CompletableResultCode flushResult = scheduled.doRun(); - flushResult.join(5, TimeUnit.SECONDS); } catch (InterruptedException e) { - // force a shutdown if the export hasn't finished. scheduler.shutdownNow(); - // reset the interrupted status Thread.currentThread().interrupt(); - } finally { - CompletableResultCode shutdownResult = scheduled.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); } + + CompletableResultCode result = new CompletableResultCode(); + CompletableResultCode exporterShutdown = exporter.shutdown(); + exporterShutdown.whenComplete(() -> { + if (finalFlush.isSuccess() && exporterShutdown.isSuccess()) { + result.succeed(); + } else { + result.fail(); + } + }); return result; } @Override - public void register(CollectionRegistration registration) { - this.metricProducer = MetricProducer.asMetricProducer(registration); + public void register(CollectionRegistration collectionRegistration) { + this.collectionRegistration = collectionRegistration; start(); } + /** + * Sets the {@link MeterProvider} to export metrics about this {@link PeriodicMetricReader} to. + * Automatically called by the meter provider the reader is registered to. + */ + @SuppressWarnings("UnusedMethod") + private void setMeterProvider(MeterProvider meterProvider) { + if (internalTelemetryVersion != InternalTelemetryVersion.LEGACY) { + instrumentation = new MetricReaderInstrumentation(COMPONENT_ID, meterProvider); + } + } + @Override public String toString() { return "PeriodicMetricReader{" @@ -113,66 +213,148 @@ public String toString() { + exporter + ", intervalNanos=" + intervalNanos + + ", maxExportBatchSize=" + + maxExportBatchSize + '}'; } - void start() { - synchronized (lock) { - if (scheduledFuture != null) { + private void start() { + synchronized (startLock) { + if (!started.compareAndSet(false, true)) { return; } + worker.start(); scheduledFuture = scheduler.scheduleAtFixedRate( - scheduled, intervalNanos, intervalNanos, TimeUnit.NANOSECONDS); + this::offerTick, intervalNanos, intervalNanos, TimeUnit.NANOSECONDS); } } - private final class Scheduled implements Runnable { - private final AtomicBoolean exportAvailable = new AtomicBoolean(true); - - private Scheduled() {} - - @Override - public void run() { - // Ignore the CompletableResultCode from doRun() in order to keep run() asynchronous - doRun(); + private void offerTick() { + // Coalesce: only enqueue a tick if none is currently pending or being processed. Matches the + // prior behavior of dropping ticks while an export is in flight. + if (tickPending.compareAndSet(false, true)) { + signals.offer(Signal.tick()); } + } - // Runs a collect + export cycle. - CompletableResultCode doRun() { - CompletableResultCode flushResult = new CompletableResultCode(); - if (exportAvailable.compareAndSet(true, false)) { - try { - Collection metricData = metricProducer.collectAllMetrics(); - if (metricData.isEmpty()) { - logger.log(Level.FINE, "No metric data to export - skipping export."); - flushResult.succeed(); - exportAvailable.set(true); + private void workerLoop() { + while (true) { + Signal signal; + try { + signal = signals.take(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + return; + } + if (signal.poison) { + tickPending.set(false); + return; + } + try { + boolean success = runCycle(); + if (signal.flushResult != null) { + if (success) { + signal.flushResult.succeed(); } else { - CompletableResultCode result = exporter.export(metricData); - result.whenComplete( - () -> { - if (!result.isSuccess()) { - logger.log(Level.FINE, "Exporter failed"); - } - flushResult.succeed(); - exportAvailable.set(true); - }); + signal.flushResult.fail(); } - } catch (Throwable t) { - exportAvailable.set(true); - logger.log(Level.WARNING, "Exporter threw an Exception", t); - flushResult.fail(); } - } else { - logger.log(Level.FINE, "Exporter busy. Dropping metrics."); - flushResult.fail(); + } finally { + if (signal.isTick) { + tickPending.set(false); + } + } + } + } + + /** Collect + export one cycle. Returns true iff collection and all batches succeeded. */ + private boolean runCycle() { + long startNanoTime = CLOCK.nanoTime(); + String error = null; + Collection metricData; + try { + metricData = collectionRegistration.collectAllMetrics(); + } catch (Throwable t) { + error = t.getClass().getName(); + logger.log(Level.WARNING, "Exception thrown by the metric collection", t); + return false; + } finally { + long durationNanos = CLOCK.nanoTime() - startNanoTime; + instrumentation.recordCollection(durationNanos / 1_000_000_000.0, error); + } + + if (metricData.isEmpty()) { + logger.log(Level.FINE, "No metric data to export - skipping export."); + return true; + } + + try { + return doExport(metricData); + } catch (Throwable t) { + logger.log(Level.WARNING, "Exporter threw an Exception", t); + return false; + } + } + + private boolean doExport(Collection metricData) { + if (maxExportBatchSize == 0) { + return exportOne(metricData); + } + boolean anyFailed = false; + for (Collection batch : + MetricExportBatcher.batchMetrics(metricData, maxExportBatchSize)) { + if (!exportOne(batch)) { + anyFailed = true; } - return flushResult; + } + return !anyFailed; + } + + private boolean exportOne(Collection batch) { + CompletableResultCode result = exporter.export(batch); + // Block until the exporter completes or the timeout elapses. Safe because the worker thread + // is dedicated to exports; no scheduler thread is held while we wait. + result.join(exporterTimeoutNanos, TimeUnit.NANOSECONDS); + if (!result.isDone()) { + logger.log(Level.WARNING, "Exporter timed out"); + return false; + } + if (!result.isSuccess()) { + logger.log(Level.WARNING, "Exporter failed"); + return false; + } + return true; + } + + /** + * Worker signal types: periodic tick (from the scheduler), flush request (from forceFlush or + * final flush on shutdown), and poison pill (from shutdown to terminate the worker). + */ + private static final class Signal { + private static final Signal TICK = new Signal(null, /* poison= */ false, /* isTick= */ true); + private static final Signal POISON = new Signal(null, /* poison= */ true, /* isTick= */ false); + + @Nullable final CompletableResultCode flushResult; + final boolean poison; + final boolean isTick; + + private Signal(@Nullable CompletableResultCode flushResult, boolean poison, boolean isTick) { + this.flushResult = flushResult; + this.poison = poison; + this.isTick = isTick; + } + + static Signal tick() { + return TICK; + } + + static Signal flush(CompletableResultCode flushResult) { + return new Signal(flushResult, /* poison= */ false, /* isTick= */ false); } - CompletableResultCode shutdown() { - return exporter.shutdown(); + static Signal poison() { + return POISON; } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderBuilder.java index bdb42b58a9c..e0d7e342425 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderBuilder.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderBuilder.java @@ -8,24 +8,35 @@ import static io.opentelemetry.api.internal.Utils.checkArgument; import static java.util.Objects.requireNonNull; -import io.opentelemetry.sdk.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; import java.time.Duration; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; -/** A builder for {@link PeriodicMetricReader}. */ +/** + * Builder for {@link PeriodicMetricReader}. + * + * @since 1.14.0 + */ public final class PeriodicMetricReaderBuilder { static final long DEFAULT_SCHEDULE_DELAY_MINUTES = 1; private final MetricExporter metricExporter; + private InternalTelemetryVersion internalTelemetryVersion = InternalTelemetryVersion.LATEST; + private long intervalNanos = TimeUnit.MINUTES.toNanos(DEFAULT_SCHEDULE_DELAY_MINUTES); + @Nullable private Long exporterTimeoutNanos; + @Nullable private ScheduledExecutorService executor; + private int maxExportBatchSize; + PeriodicMetricReaderBuilder(MetricExporter metricExporter) { this.metricExporter = metricExporter; } @@ -48,6 +59,37 @@ public PeriodicMetricReaderBuilder setInterval(Duration interval) { return setInterval(interval.toNanos(), TimeUnit.NANOSECONDS); } + /** + * Sets the maximum time an export will be allowed to run before being reported as failed. If + * unset, defaults to the configured interval. A timeout of {@code 0} disables the timeout. + * + *

      When {@link #setMaxExportBatchSize(int)} is configured, the timeout applies to each + * individual export(batch) invocation, not the aggregate export cycle. + * + * @since 1.68.0 + */ + public PeriodicMetricReaderBuilder setExporterTimeout(long timeout, TimeUnit unit) { + requireNonNull(unit, "unit"); + checkArgument(timeout >= 0, "timeout must be non-negative"); + exporterTimeoutNanos = timeout == 0 ? Long.MAX_VALUE : unit.toNanos(timeout); + return this; + } + + /** + * Sets the maximum time an export will be allowed to run before being reported as failed. If + * unset, defaults to the configured interval. A {@link Duration#ZERO zero} timeout disables the + * timeout. + * + *

      When {@link #setMaxExportBatchSize(int)} is configured, the timeout applies to each + * individual export(batch) invocation, not the aggregate export cycle. + * + * @since 1.68.0 + */ + public PeriodicMetricReaderBuilder setExporterTimeout(Duration timeout) { + requireNonNull(timeout, "timeout"); + return setExporterTimeout(timeout.toNanos(), TimeUnit.NANOSECONDS); + } + /** Sets the {@link ScheduledExecutorService} to schedule reads on. */ public PeriodicMetricReaderBuilder setExecutor(ScheduledExecutorService executor) { requireNonNull(executor, "executor"); @@ -56,15 +98,44 @@ public PeriodicMetricReaderBuilder setExecutor(ScheduledExecutorService executor } /** - * Returns a new {@link PeriodicMetricReader} with the configuration of this builder which can be - * registered with a {@link io.opentelemetry.sdk.metrics.SdkMeterProvider}. + * Sets the maximum number of data points to include in a single export batch. If unset, no + * batching will be performed. The maximum number of data points is considered across MetricData + * objects scheduled for export. + * + * @param maxExportBatchSize The maximum number of data points to include in a single export + * batch. + * @since 1.67.0 */ + public PeriodicMetricReaderBuilder setMaxExportBatchSize(int maxExportBatchSize) { + checkArgument(maxExportBatchSize > 0, "maxExportBatchSize must be positive"); + this.maxExportBatchSize = maxExportBatchSize; + return this; + } + + /** Build a {@link PeriodicMetricReader} with the configuration of this builder. */ public PeriodicMetricReader build() { ScheduledExecutorService executor = this.executor; if (executor == null) { executor = Executors.newScheduledThreadPool(1, new DaemonThreadFactory("PeriodicMetricReader")); } - return new PeriodicMetricReader(metricExporter, intervalNanos, executor); + return new PeriodicMetricReader( + metricExporter, + intervalNanos, + exporterTimeoutNanos != null ? exporterTimeoutNanos : intervalNanos, + executor, + maxExportBatchSize, + internalTelemetryVersion); + } + + /** + * Sets the internal telemetry version used to control self-observability metrics. + * + * @since 1.65.0 + */ + public PeriodicMetricReaderBuilder setInternalTelemetryVersion(InternalTelemetryVersion version) { + requireNonNull(version, "version"); + this.internalTelemetryVersion = version; + return this; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/package-info.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/package-info.java index b8e330bb4ec..6a60ff33173 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/package-info.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/export/package-info.java @@ -4,15 +4,8 @@ */ /** - * Utilities that allow to export metrics to the OpenTelemetry exporters. - * - *

      Contents

      - * - *
        - *
      • {@link io.opentelemetry.sdk.metrics.export.MetricExporter} - *
      • {@link io.opentelemetry.sdk.metrics.export.MetricReader} - *
      • {@link io.opentelemetry.sdk.metrics.export.PeriodicMetricReader} - *
      + * Utilities that facilitate exporting metrics out of {@link + * io.opentelemetry.sdk.metrics.SdkMeterProvider}. */ @ParametersAreNonnullByDefault package io.opentelemetry.sdk.metrics.export; diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/MeterConfig.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/MeterConfig.java new file mode 100644 index 00000000000..02326273625 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/MeterConfig.java @@ -0,0 +1,66 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; +import java.util.function.Predicate; +import javax.annotation.concurrent.Immutable; + +/** + * A collection of configuration options which define the behavior of a {@link Meter}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + * + * @see SdkMeterProviderUtil#setMeterConfigurator(SdkMeterProviderBuilder, ScopeConfigurator) + * @see SdkMeterProviderUtil#addMeterConfiguratorCondition(SdkMeterProviderBuilder, Predicate, + * MeterConfig) + */ +@AutoValue +@Immutable +public abstract class MeterConfig { + + private static final MeterConfig DEFAULT_CONFIG = new AutoValue_MeterConfig(/* enabled= */ true); + private static final MeterConfig DISABLED_CONFIG = + new AutoValue_MeterConfig(/* enabled= */ false); + + /** Returns a disabled {@link MeterConfig}. */ + public static MeterConfig disabled() { + return DISABLED_CONFIG; + } + + /** Returns an enabled {@link MeterConfig}. */ + public static MeterConfig enabled() { + return DEFAULT_CONFIG; + } + + /** + * Returns the default {@link MeterConfig}, which is used when no configurator is set or when the + * meter configurator returns {@code null} for a {@link InstrumentationScopeInfo}. + */ + public static MeterConfig defaultConfig() { + return DEFAULT_CONFIG; + } + + /** + * Create a {@link ScopeConfiguratorBuilder} for configuring {@link + * SdkMeterProviderUtil#setMeterConfigurator(SdkMeterProviderBuilder, ScopeConfigurator)}. + */ + public static ScopeConfiguratorBuilder configuratorBuilder() { + return ScopeConfigurator.builder(); + } + + MeterConfig() {} + + /** Returns {@code true} if this meter is enabled. Defaults to {@code true}. */ + public abstract boolean isEnabled(); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/SdkMeterProviderUtil.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/SdkMeterProviderUtil.java index eb89bc35435..9c1c6e11253 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/SdkMeterProviderUtil.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/SdkMeterProviderUtil.java @@ -5,80 +5,103 @@ package io.opentelemetry.sdk.metrics.internal; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; -import io.opentelemetry.sdk.metrics.ViewBuilder; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; -import io.opentelemetry.sdk.metrics.internal.view.StringPredicates; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; +import java.util.function.BiPredicate; import java.util.function.Predicate; +import javax.annotation.Nullable; /** - * This class is internal and is hence not for public use. Its APIs are unstable and can change at - * any time. + * A collection of methods that allow use of experimental features prior to availability in public + * APIs. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. */ public final class SdkMeterProviderUtil { private SdkMeterProviderUtil() {} - /** - * Reflectively assign the {@link ExemplarFilter} to the {@link SdkMeterProviderBuilder}. - * - * @param sdkMeterProviderBuilder the - */ - public static void setExemplarFilter( - SdkMeterProviderBuilder sdkMeterProviderBuilder, ExemplarFilter exemplarFilter) { + /** Reflectively set the {@link SdkResourceProvider} on the {@link SdkMeterProviderBuilder}. */ + public static void setSdkResourceProvider( + SdkMeterProviderBuilder sdkMeterProviderBuilder, SdkResourceProvider resourceProvider) { try { Method method = SdkMeterProviderBuilder.class.getDeclaredMethod( - "setExemplarFilter", ExemplarFilter.class); + "setSdkResourceProvider", SdkResourceProvider.class); method.setAccessible(true); - method.invoke(sdkMeterProviderBuilder, exemplarFilter); + method.invoke(sdkMeterProviderBuilder, resourceProvider); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new IllegalStateException( - "Error calling setExemplarFilter on SdkMeterProviderBuilder", e); + "Error calling setSdkResourceProvider on SdkMeterProviderBuilder", e); } } - /** - * Reflectively add an {@link AttributesProcessor} to the {@link ViewBuilder} which appends - * key-values from baggage to all measurements. - * - *

      Note: This runs after all other attribute processing added so far. - * - * @param viewBuilder the builder - * @param keyFilter Only baggage key values pairs where the key matches this predicate will be - * appended. - */ - public static void appendFilteredBaggageAttributes( - ViewBuilder viewBuilder, Predicate keyFilter) { - addAttributesProcessor(viewBuilder, AttributesProcessor.appendBaggageByKeyName(keyFilter)); + /** Reflectively get the {@link SdkResourceProvider} from the {@link SdkMeterProvider}. */ + public static SdkResourceProvider getSdkResourceProvider(SdkMeterProvider sdkMeterProvider) { + try { + Method method = SdkMeterProvider.class.getDeclaredMethod("getSdkResourceProvider"); + method.setAccessible(true); + return (SdkResourceProvider) method.invoke(sdkMeterProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling getSdkResourceProvider on SdkMeterProvider", e); + } } - /** - * Reflectively add an {@link AttributesProcessor} to the {@link ViewBuilder} which appends all - * key-values from baggage to all measurements. - * - *

      Note: This runs after all other attribute processing added so far. - * - * @param viewBuilder the builder - */ - public static void appendAllBaggageAttributes(ViewBuilder viewBuilder) { - appendFilteredBaggageAttributes(viewBuilder, StringPredicates.ALL); + /** Reflectively set the {@link ScopeConfigurator} to the {@link SdkMeterProvider}. */ + public static void setMeterConfigurator( + SdkMeterProvider sdkMeterProvider, ScopeConfigurator scopeConfigurator) { + try { + Method method = + SdkMeterProvider.class.getDeclaredMethod("setMeterConfigurator", ScopeConfigurator.class); + method.setAccessible(true); + method.invoke(sdkMeterProvider, scopeConfigurator); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException("Error calling setMeterConfigurator on SdkMeterProvider", e); + } } - private static void addAttributesProcessor( - ViewBuilder viewBuilder, AttributesProcessor attributesProcessor) { + /** Reflectively set the {@link ScopeConfigurator} to the {@link SdkMeterProviderBuilder}. */ + public static SdkMeterProviderBuilder setMeterConfigurator( + SdkMeterProviderBuilder sdkMeterProviderBuilder, + ScopeConfigurator meterConfigurator) { try { Method method = - ViewBuilder.class.getDeclaredMethod("addAttributesProcessor", AttributesProcessor.class); + SdkMeterProviderBuilder.class.getDeclaredMethod( + "setMeterConfigurator", ScopeConfigurator.class); method.setAccessible(true); - method.invoke(viewBuilder, attributesProcessor); - } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) { - throw new IllegalStateException("Error adding AttributesProcessor to ViewBuilder", e); + method.invoke(sdkMeterProviderBuilder, meterConfigurator); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setMeterConfigurator on SdkMeterProviderBuilder", e); } + return sdkMeterProviderBuilder; + } + + /** Reflectively add a tracer configurator condition to the {@link SdkMeterProviderBuilder}. */ + public static SdkMeterProviderBuilder addMeterConfiguratorCondition( + SdkMeterProviderBuilder sdkMeterProviderBuilder, + Predicate scopeMatcher, + MeterConfig meterConfig) { + try { + Method method = + SdkMeterProviderBuilder.class.getDeclaredMethod( + "addMeterConfiguratorCondition", Predicate.class, MeterConfig.class); + method.setAccessible(true); + method.invoke(sdkMeterProviderBuilder, scopeMatcher, meterConfig); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling addMeterConfiguratorCondition on SdkMeterProviderBuilder", e); + } + return sdkMeterProviderBuilder; } /** Reflectively reset the {@link SdkMeterProvider}, clearing all registered instruments. */ @@ -91,4 +114,23 @@ public static void resetForTest(SdkMeterProvider sdkMeterProvider) { throw new IllegalStateException("Error calling resetForTest on SdkMeterProvider", e); } } + + /** + * Reflectively set the context-scoped attributes filter on the {@link SdkMeterProviderBuilder}. + */ + public static SdkMeterProviderBuilder setContextScopedAttributesFilter( + SdkMeterProviderBuilder sdkMeterProviderBuilder, + @Nullable BiPredicate> filter) { + try { + Method method = + SdkMeterProviderBuilder.class.getDeclaredMethod( + "setContextScopedAttributesFilter", BiPredicate.class); + method.setAccessible(true); + method.invoke(sdkMeterProviderBuilder, filter); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setContextScopedAttributesFilter on SdkMeterProviderBuilder", e); + } + return sdkMeterProviderBuilder; + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AbstractSumAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AbstractSumAggregator.java index d901277ca4f..a7574254408 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AbstractSumAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AbstractSumAggregator.java @@ -5,14 +5,25 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; +import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -abstract class AbstractSumAggregator implements Aggregator { +abstract class AbstractSumAggregator + implements Aggregator { private final boolean isMonotonic; AbstractSumAggregator(InstrumentDescriptor instrumentDescriptor) { - this.isMonotonic = MetricDataUtils.isMonotonicInstrument(instrumentDescriptor); + this.isMonotonic = isMonotonicInstrument(instrumentDescriptor); + } + + /** Returns true if the instrument does not allow negative measurements. */ + private static boolean isMonotonicInstrument(InstrumentDescriptor descriptor) { + InstrumentType type = descriptor.getType(); + return type == InstrumentType.HISTOGRAM + || type == InstrumentType.COUNTER + || type == InstrumentType.OBSERVABLE_COUNTER; } final boolean isMonotonic() { diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingCircularBufferCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingCircularBufferCounter.java new file mode 100644 index 00000000000..14e165f73a1 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingCircularBufferCounter.java @@ -0,0 +1,149 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +/** + * A circle-buffer-backed exponential counter. + * + *

      The first recorded value becomes the 'baseIndex'. Going backwards leads to start/stop index + * + *

      This expand start/End index as it sees values. + * + *

      This class is NOT thread-safe. It is expected to be behind a synchronized incrementer. + */ +final class AdaptingCircularBufferCounter { + private static final int NULL_INDEX = Integer.MIN_VALUE; + private int endIndex = NULL_INDEX; + private int startIndex = NULL_INDEX; + private int baseIndex = NULL_INDEX; + private final AdaptingIntegerArray backing; + + /** Constructs a circular buffer that will hold at most {@code maxSize} buckets. */ + AdaptingCircularBufferCounter(int maxSize) { + this.backing = new AdaptingIntegerArray(maxSize); + } + + /** (Deep)-Copies the values from another exponential counter. */ + AdaptingCircularBufferCounter(AdaptingCircularBufferCounter toCopy) { + this.backing = toCopy.backing.copy(); + this.startIndex = toCopy.getIndexStart(); + this.endIndex = toCopy.getIndexEnd(); + this.baseIndex = toCopy.baseIndex; + } + + /** + * The first index with a recording. May be negative. + * + *

      Note: the returned value is not meaningful when isEmpty returns true. + * + * @return the first index with a recording. + */ + int getIndexStart() { + return startIndex; + } + + /** + * The last index with a recording. May be negative. + * + *

      Note: the returned value is not meaningful when isEmpty returns true. + * + * @return The last index with a recording. + */ + int getIndexEnd() { + return endIndex; + } + + /** + * Persist new data at index, incrementing by delta amount. + * + * @param index The index of where to perform the incrementation. + * @param delta How much to increment the index by. + * @return success status. + */ + boolean increment(int index, long delta) { + if (baseIndex == NULL_INDEX) { + startIndex = index; + endIndex = index; + baseIndex = index; + backing.increment(0, delta); + return true; + } + + if (index > endIndex) { + // Move end, check max size + if ((long) index - startIndex + 1 > backing.length()) { + return false; + } + endIndex = index; + } else if (index < startIndex) { + // Move end, check max size + if ((long) endIndex - index + 1 > backing.length()) { + return false; + } + startIndex = index; + } + int realIdx = toBufferIndex(index); + backing.increment(realIdx, delta); + return true; + } + + /** + * Get the number of recordings for the given index. + * + * @return the number of recordings for the index, or 0 if the index is out of bounds. + */ + long get(int index) { + if (index < startIndex || index > endIndex) { + return 0; + } + return backing.get(toBufferIndex(index)); + } + + /** + * Boolean denoting if the backing structure has recordings or not. + * + * @return true if no recordings, false if at least one recording. + */ + boolean isEmpty() { + return baseIndex == NULL_INDEX; + } + + /** Returns the maximum number of buckets allowed in this counter. */ + int getMaxSize() { + return backing.length(); + } + + /** Resets all bucket counts to zero and resets index start/end tracking. */ + void clear() { + this.backing.clear(); + this.baseIndex = NULL_INDEX; + this.endIndex = NULL_INDEX; + this.startIndex = NULL_INDEX; + } + + private int toBufferIndex(int index) { + // Figure out the index relative to the start of the circular buffer. + int result = index - baseIndex; + if (result >= backing.length()) { + result -= backing.length(); + } else if (result < 0) { + result += backing.length(); + } + return result; + } + + @Override + public String toString() { + StringBuilder result = new StringBuilder("{"); + for (int i = startIndex; i <= endIndex && startIndex != NULL_INDEX; i++) { + if (i != startIndex) { + result.append(','); + } + result.append(i).append('=').append(get(i)); + } + return result.append("}").toString(); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingIntegerArray.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingIntegerArray.java similarity index 93% rename from sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingIntegerArray.java rename to sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingIntegerArray.java index 37ece0b3837..b5fb863d88d 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingIntegerArray.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingIntegerArray.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.metrics.internal.state; +package io.opentelemetry.sdk.metrics.internal.aggregator; import java.util.Arrays; import javax.annotation.Nullable; @@ -31,11 +31,8 @@ *

    • If cellSize == INT then intBacking is not null *
    • If cellSize == LONG then longBacking is not null * - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. */ -public class AdaptingIntegerArray { +final class AdaptingIntegerArray { @Nullable private byte[] byteBacking; @Nullable private short[] shortBacking; @Nullable private int[] intBacking; @@ -48,11 +45,12 @@ private enum ArrayCellSize { INT, LONG } + /** The current byte size of integer cells in this array. */ private ArrayCellSize cellSize; /** Construct an adapting integer array of a given size. */ - public AdaptingIntegerArray(int size) { + AdaptingIntegerArray(int size) { this.cellSize = ArrayCellSize.BYTE; this.byteBacking = new byte[size]; } @@ -78,13 +76,13 @@ private AdaptingIntegerArray(AdaptingIntegerArray toCopy) { } /** Returns a deep-copy of this array, preserving cell size. */ - public AdaptingIntegerArray copy() { + AdaptingIntegerArray copy() { return new AdaptingIntegerArray(this); } /** Add {@code count} to the value stored at {@code index}. */ @SuppressWarnings("NullAway") - public void increment(int idx, long count) { + void increment(int idx, long count) { // TODO - prevent bad index long result; switch (cellSize) { @@ -124,7 +122,7 @@ public void increment(int idx, long count) { /** Grab the value stored at {@code index}. */ @SuppressWarnings("NullAway") - public long get(int index) { + long get(int index) { long value = 0; switch (this.cellSize) { case BYTE: @@ -145,7 +143,7 @@ public long get(int index) { /** Return the length of this integer array. */ @SuppressWarnings("NullAway") - public int length() { + int length() { int length = 0; switch (this.cellSize) { case BYTE: @@ -163,9 +161,10 @@ public int length() { } return length; } + /** Zeroes out all counts in this array. */ @SuppressWarnings("NullAway") - public void clear() { + void clear() { switch (this.cellSize) { case BYTE: Arrays.fill(this.byteBacking, (byte) 0); @@ -205,6 +204,7 @@ private void resizeToInt() { this.intBacking = intBacking; this.shortBacking = null; } + /** convert from int => long backing array. */ @SuppressWarnings("NullAway") private void resizeToLong() { diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtil.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtil.java index 34bc27b1457..a5071b5370d 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtil.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtil.java @@ -6,8 +6,8 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.internal.view.ExponentialHistogramAggregation; import java.util.HashMap; +import java.util.Locale; import java.util.Map; /** @@ -24,7 +24,8 @@ public class AggregationUtil { private static final String AGGREGATION_LAST_VALUE = "last_value"; private static final String AGGREGATION_DROP = "drop"; private static final String AGGREGATION_EXPLICIT_BUCKET_HISTOGRAM = "explicit_bucket_histogram"; - private static final String AGGREGATION_EXPONENTIAL_HISTOGRAM = "exponential_histogram"; + private static final String AGGREGATION_BASE2_EXPONENTIAL_HISTOGRAM = + "base2_exponential_bucket_histogram"; static { aggregationByName = new HashMap<>(); @@ -34,9 +35,8 @@ public class AggregationUtil { aggregationByName.put(AGGREGATION_DROP, Aggregation.drop()); aggregationByName.put( AGGREGATION_EXPLICIT_BUCKET_HISTOGRAM, Aggregation.explicitBucketHistogram()); - // TODO(jack-berg): Use Aggregation.exponentialHistogram() when available aggregationByName.put( - AGGREGATION_EXPONENTIAL_HISTOGRAM, ExponentialHistogramAggregation.getDefault()); + AGGREGATION_BASE2_EXPONENTIAL_HISTOGRAM, Aggregation.base2ExponentialBucketHistogram()); nameByAggregation = new HashMap<>(); nameByAggregation.put(Aggregation.defaultAggregation().getClass(), AGGREGATION_DEFAULT); @@ -45,9 +45,9 @@ public class AggregationUtil { nameByAggregation.put(Aggregation.drop().getClass(), AGGREGATION_DROP); nameByAggregation.put( Aggregation.explicitBucketHistogram().getClass(), AGGREGATION_EXPLICIT_BUCKET_HISTOGRAM); - // TODO(jack-berg): Use Aggregation.exponentialHistogram() when available nameByAggregation.put( - ExponentialHistogramAggregation.getDefault().getClass(), AGGREGATION_EXPONENTIAL_HISTOGRAM); + Aggregation.base2ExponentialBucketHistogram().getClass(), + AGGREGATION_BASE2_EXPONENTIAL_HISTOGRAM); } private AggregationUtil() {} @@ -60,7 +60,7 @@ private AggregationUtil() {} * @throws IllegalArgumentException if the name is not recognized */ public static Aggregation forName(String name) { - Aggregation aggregation = aggregationByName.get(name); + Aggregation aggregation = aggregationByName.get(name.toLowerCase(Locale.ROOT)); if (aggregation == null) { throw new IllegalArgumentException("Unrecognized aggregation name " + name); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Aggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Aggregator.java index 2097fd144ba..b5c0b28c93f 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Aggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Aggregator.java @@ -5,100 +5,79 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; import io.opentelemetry.sdk.resources.Resource; -import java.util.Map; -import javax.annotation.Nullable; +import java.util.Collection; import javax.annotation.concurrent.Immutable; /** * Aggregator represents the abstract class for all the available aggregations that can be computed - * during the accumulation phase for all the instrument. - * - *

      The synchronous instruments will create an {@link AggregatorHandle} to record individual - * measurements synchronously, and for asynchronous the {@link #accumulateDoubleMeasurement} or - * {@link #accumulateLongMeasurement} will be used when reading values from the instrument - * callbacks. + * during the collection phase for all the instruments. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ @Immutable -public interface Aggregator { +public interface Aggregator { /** Returns the drop aggregator, an aggregator that drops measurements. */ - static Aggregator drop() { + static Aggregator drop() { return DropAggregator.INSTANCE; } /** - * Returns a new {@link AggregatorHandle}. This MUST by used by the synchronous to aggregate - * recorded measurements during the collection cycle. + * Returns a new {@link AggregatorHandle}. Used by both synchronous and asynchronous metric + * storage to aggregate recorded measurements during the collection cycle. * + * @param creationEpochNanos the epoch timestamp (nanos) at which the handle is being created, + * stored via {@link AggregatorHandle#getCreationEpochNanos()}. Whether this value is used as + * the start timestamp of reported data points depends on the instrument and temporality β€” see + * {@link AggregatorHandle#getCreationEpochNanos()} for details. * @return a new {@link AggregatorHandle}. */ - AggregatorHandle createHandle(); + AggregatorHandle createHandle(long creationEpochNanos); /** - * Returns a new {@code Accumulation} for the given value. This MUST be used by the asynchronous - * instruments to create {@code Accumulation} that are passed to the processor. + * Returns a new DELTA point by computing the difference between two cumulative points. * - * @param value the given value to be used to create the {@code Accumulation}. - * @return a new {@code Accumulation} for the given value, or {@code null} if there are no - * recordings. - */ - @Nullable - default T accumulateLongMeasurement(long value, Attributes attributes, Context context) { - AggregatorHandle handle = createHandle(); - handle.recordLong(value, attributes, context); - return handle.accumulateThenReset(attributes); - } - - /** - * Returns a new {@code Accumulation} for the given value. This MUST be used by the asynchronous - * instruments to create {@code Accumulation} that are passed to the processor. + *

      Aggregators MUST implement diff if it can be used with asynchronous instruments. * - * @param value the given value to be used to create the {@code Accumulation}. - * @return a new {@code Accumulation} for the given value, or {@code null} if there are no - * recordings. + * @param previousCumulative the previously captured point. + * @param currentCumulative the newly captured (cumulative) point. + * @return The resulting delta point. */ - @Nullable - default T accumulateDoubleMeasurement(double value, Attributes attributes, Context context) { - AggregatorHandle handle = createHandle(); - handle.recordDouble(value, attributes, context); - return handle.accumulateThenReset(attributes); + default T diff(T previousCumulative, T currentCumulative) { + throw new UnsupportedOperationException("This aggregator does not support diff."); } /** - * Returns the result of the merge of the given accumulations. - * - *

      This should always assume that the accumulations do not overlap and merge together for a new - * cumulative report. + * Resets one reusable point to be a DELTA point by computing the difference between two + * cumulative points. * - * @param previousCumulative the previously captured accumulation - * @param delta the newly captured (delta) accumulation - * @return the result of the merge of the given accumulations. - */ - T merge(T previousCumulative, T delta); - - /** - * Returns a new DELTA aggregation by comparing two cumulative measurements. + *

      The delta between the two points is set on {@code previousCumulativeReusable} * *

      Aggregators MUST implement diff if it can be used with asynchronous instruments. * - * @param previousCumulative the previously captured accumulation. - * @param currentCumulative the newly captured (cumulative) accumulation. - * @return The resulting delta accumulation. + * @param previousCumulativeReusable the previously captured point. + * @param currentCumulative the newly captured (cumulative) point. */ - default T diff(T previousCumulative, T currentCumulative) { - throw new UnsupportedOperationException("This aggregator does not support diff."); + default void diffInPlace(T previousCumulativeReusable, T currentCumulative) { + throw new UnsupportedOperationException("This aggregator does not support diffInPlace."); + } + + /** Creates a new reusable point. */ + default T createReusablePoint() { + throw new UnsupportedOperationException( + "This aggregator does not support createReusablePoint."); + } + + /** Copies {@code point} into {@code toReusablePoint}. */ + default void copyPoint(T point, T toReusablePoint) { + throw new UnsupportedOperationException("This aggregator does not support toPoint."); } /** @@ -107,19 +86,14 @@ default T diff(T previousCumulative, T currentCumulative) { * @param resource the resource producing the metric. * @param instrumentationScopeInfo the scope that instrumented the metric. * @param metricDescriptor the name, description and unit of the metric. - * @param accumulationByLabels the map of Labels to Accumulation. - * @param temporality the temporality of the accumulation. - * @param startEpochNanos the startEpochNanos for the {@code Point}. - * @param epochNanos the epochNanos for the {@code Point}. + * @param points list of points + * @param temporality the temporality of the metric. * @return the {@link MetricDataType} that this {@code Aggregation} will produce. */ MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, MetricDescriptor metricDescriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos); + Collection points, + AggregationTemporality temporality); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorFactory.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorFactory.java index 9054e2e49ff..0d6ba79b0a5 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorFactory.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorFactory.java @@ -5,9 +5,10 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; -import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; /** * An internal interface for returning an Aggregator from an Aggregation. @@ -25,15 +26,18 @@ public interface AggregatorFactory { * @param instrumentDescriptor the descriptor of the {@code Instrument} that will record * measurements. * @param exemplarFilter the filter on which measurements should turn into exemplars + * @param memoryMode The {@link MemoryMode} the aggregator will use * @return a new {@link Aggregator}. {@link Aggregator#drop()} indicates no measurements should be * recorded. */ - Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter); + Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode); /** * Determine if the {@link Aggregator} produced by {@link #createAggregator(InstrumentDescriptor, - * ExemplarFilter)} is compatible with the {@code instrumentDescriptor}. + * ExemplarFilterInternal, MemoryMode)} is compatible with the {@code instrumentDescriptor}. */ boolean isCompatibleWithInstrument(InstrumentDescriptor instrumentDescriptor); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandle.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandle.java index bb1986b9296..454ca707a69 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandle.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandle.java @@ -7,11 +7,13 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; -import io.opentelemetry.sdk.metrics.internal.state.BoundStorageHandle; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; import java.util.List; -import java.util.concurrent.atomic.AtomicLong; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; @@ -20,102 +22,94 @@ * thread-safe and avoid locking when possible, because values are recorded synchronously on the * calling thread. * - *

      An {@link AggregatorHandle} must be created for every unique {@code LabelSet} recorded, and - * can be referenced by the bound instruments. - * - *

      It atomically counts the number of references (usages) while also keeping a state of - * mapped/unmapped into an external map. It uses an atomic value where the least significant bit is - * used to keep the state of mapping ('1' is used for unmapped and '0' is for mapped) and the rest - * of the bits are used for reference (usage) counting. + *

      An {@link AggregatorHandle} must be created for every unique {@link Attributes} recorded. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ @ThreadSafe -public abstract class AggregatorHandle implements BoundStorageHandle { - // Atomically counts the number of references (usages) while also keeping a state of - // mapped/unmapped into a registry map. - private final AtomicLong refCountMapped; - // Note: This is not 100% thread-safe. There is a race condition where recordings can - // be made in the moment between the reset and the setting of this field's value. In those - // cases, it is possible that a recording could be missed in a given recording interval, but - // it should be picked up in the next, assuming that more recordings are being made. - private volatile boolean hasRecordings = false; +public abstract class AggregatorHandle { - // A reservoir of sampled exemplars for this time period. - private final ExemplarReservoir exemplarReservoir; + private static final String UNSUPPORTED_LONG_MESSAGE = + "This aggregator does not support long values."; + private static final String UNSUPPORTED_DOUBLE_MESSAGE = + "This aggregator does not support double values."; - protected AggregatorHandle(ExemplarReservoir exemplarReservoir) { - // Start with this binding already bound. - this.refCountMapped = new AtomicLong(2); - this.exemplarReservoir = exemplarReservoir; + private final long creationEpochNanos; + // A reservoir of sampled exemplars for this time period. + @Nullable private final DoubleExemplarReservoir doubleReservoirFactory; + @Nullable private final LongExemplarReservoir longReservoirFactory; + private final boolean isDoubleType; + private volatile boolean valuesRecorded = false; + + protected AggregatorHandle( + long creationEpochNanos, ExemplarReservoirFactory reservoirFactory, boolean isDoubleType) { + this.creationEpochNanos = creationEpochNanos; + this.isDoubleType = isDoubleType; + if (isDoubleType) { + this.doubleReservoirFactory = reservoirFactory.createDoubleExemplarReservoir(); + this.longReservoirFactory = null; + } else { + this.doubleReservoirFactory = null; + this.longReservoirFactory = reservoirFactory.createLongExemplarReservoir(); + } } /** - * Acquires this {@code Aggregator} for use. Returns {@code true} if the entry is still mapped and - * increases the reference usages, if unmapped returns {@code false}. - * - * @return {@code true} if successful. + * Returns the current value into as {@link T}. If {@code reset} is {@code true}, resets the + * current value in this {@code Aggregator}. */ - public final boolean acquire() { - // Every reference adds/removes 2 instead of 1 to avoid changing the mapping bit. - return (refCountMapped.addAndGet(2L) & 1L) == 0; - } - - /** Release this {@code Aggregator}. It decreases the reference usage. */ - @Override - public final void release() { - // Every reference adds/removes 2 instead of 1 to avoid changing the mapping bit. - refCountMapped.getAndAdd(-2L); - } - - /** - * Flips the mapped bit to "unmapped" state and returns true if both of the following conditions - * are true upon entry to this function: 1) There are no active references; 2) The mapped bit is - * in "mapped" state; otherwise no changes are done to mapped bit and false is returned. - * - * @return {@code true} if successful. - */ - public final boolean tryUnmap() { - if (refCountMapped.get() != 0) { - // Still references (usages) to this bound or already unmapped. - return false; + public final T aggregateThenMaybeReset( + long startEpochNanos, long epochNanos, Attributes attributes, boolean reset) { + if (reset) { + valuesRecorded = false; } - return refCountMapped.compareAndSet(0L, 1L); - } - /** - * Returns the current value into as {@link T} and resets the current value in this {@code - * Aggregator}. - */ - @Nullable - public final T accumulateThenReset(Attributes attributes) { - if (!hasRecordings) { - return null; + if (isDoubleType) { + return doAggregateThenMaybeResetDoubles( + startEpochNanos, + epochNanos, + attributes, + throwUnsupportedIfNull(this.doubleReservoirFactory, UNSUPPORTED_DOUBLE_MESSAGE) + .collectAndResetDoubles(attributes), + reset); } - hasRecordings = false; - return doAccumulateThenReset(exemplarReservoir.collectAndReset(attributes)); + return doAggregateThenMaybeResetLongs( + startEpochNanos, + epochNanos, + attributes, + throwUnsupportedIfNull(this.longReservoirFactory, UNSUPPORTED_LONG_MESSAGE) + .collectAndResetLongs(attributes), + reset); } - /** Implementation of the {@code accumulateThenReset}. */ - protected abstract T doAccumulateThenReset(List exemplars); + /** Implementation of the {@link #aggregateThenMaybeReset(long, long, Attributes, boolean)} . */ + protected T doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + throw new UnsupportedOperationException(UNSUPPORTED_DOUBLE_MESSAGE); + } - @Override - public final void recordLong(long value, Attributes attributes, Context context) { - exemplarReservoir.offerLongMeasurement(value, attributes, context); - recordLong(value); + /** Implementation of the {@link #aggregateThenMaybeReset(long, long, Attributes, boolean)} . */ + protected T doAggregateThenMaybeResetLongs( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + throw new UnsupportedOperationException(UNSUPPORTED_LONG_MESSAGE); } - /** - * Updates the current aggregator with a newly recorded {@code long} value. - * - *

      Visible for Testing - * - * @param value the new {@code long} value to be added. - */ - public final void recordLong(long value) { + public void recordLong(long value, Attributes attributes, Context context) { + throwUnsupportedIfNull(this.longReservoirFactory, UNSUPPORTED_LONG_MESSAGE) + .offerLongMeasurement(value, attributes, context); doRecordLong(value); - hasRecordings = true; + if (!valuesRecorded) { + valuesRecorded = true; + } } /** @@ -123,34 +117,57 @@ public final void recordLong(long value) { * values. */ protected void doRecordLong(long value) { - throw new UnsupportedOperationException( - "This aggregator does not support recording long values."); + throw new UnsupportedOperationException("This aggregator does not support long values."); } - @Override public final void recordDouble(double value, Attributes attributes, Context context) { - exemplarReservoir.offerDoubleMeasurement(value, attributes, context); - recordDouble(value); + throwUnsupportedIfNull(this.doubleReservoirFactory, UNSUPPORTED_DOUBLE_MESSAGE) + .offerDoubleMeasurement(value, attributes, context); + doRecordDouble(value); + if (!valuesRecorded) { + valuesRecorded = true; + } } /** - * Updates the current aggregator with a newly recorded {@code double} value. - * - *

      Visible for Testing + * Concrete Aggregator instances should implement this method in order support recordings of + * double values. + */ + protected void doRecordDouble(double value) { + throw new UnsupportedOperationException(UNSUPPORTED_DOUBLE_MESSAGE); + } + + /** + * Checks whether this handle has values recorded. * - * @param value the new {@code double} value to be added. + * @return True if values has been recorded to it */ - public final void recordDouble(double value) { - doRecordDouble(value); - hasRecordings = true; + public boolean hasRecordedValues() { + return valuesRecorded; + } + + private static S throwUnsupportedIfNull(@Nullable S value, String message) { + if (value == null) { + throw new UnsupportedOperationException(message); + } + return value; } /** - * Concrete Aggregator instances should implement this method in order support recordings of - * double values. + * Returns the epoch timestamp (nanos) at which this handle was created. + * + *

      For cumulative synchronous instruments, this is the time of the first measurement for the + * series and is used as {@link PointData#getStartEpochNanos()}. + * + *

      For cumulative asynchronous instruments, this is either the instrument creation time (if the + * series first appeared during the first collection cycle) or the preceding collection interval's + * timestamp (if the series appeared in a later cycle), and is used as {@link + * PointData#getStartEpochNanos()}. + * + *

      Not used for delta instruments; their start epoch is computed directly from the reader's + * last collection time or instrument creation time. */ - protected void doRecordDouble(double value) { - throw new UnsupportedOperationException( - "This aggregator does not support recording double values."); + public long getCreationEpochNanos() { + return creationEpochNanos; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Base2ExponentialHistogramIndexer.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Base2ExponentialHistogramIndexer.java new file mode 100644 index 00000000000..a0b1acb52a4 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/Base2ExponentialHistogramIndexer.java @@ -0,0 +1,110 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +final class Base2ExponentialHistogramIndexer { + + private static final Map cache = + new ConcurrentHashMap<>(); + + /** Bit mask used to isolate exponent of IEEE 754 double precision number. */ + private static final long EXPONENT_BIT_MASK = 0x7FF0000000000000L; + + /** Bit mask used to isolate the significand of IEEE 754 double precision number. */ + private static final long SIGNIFICAND_BIT_MASK = 0xFFFFFFFFFFFFFL; + + /** Bias used in representing the exponent of IEEE 754 double precision number. */ + private static final int EXPONENT_BIAS = 1023; + + /** + * The number of bits used to represent the significand of IEEE 754 double precision number, + * excluding the implicit bit. + */ + private static final int SIGNIFICAND_WIDTH = 52; + + /** The number of bits used to represent the exponent of IEEE 754 double precision number. */ + private static final int EXPONENT_WIDTH = 11; + + private static final double LOG_BASE2_E = 1D / Math.log(2); + + private final int scale; + private final double scaleFactor; + + private Base2ExponentialHistogramIndexer(int scale) { + this.scale = scale; + this.scaleFactor = computeScaleFactor(scale); + } + + /** Get an indexer for the given scale. Indexers are cached and reused for performance. */ + static Base2ExponentialHistogramIndexer get(int scale) { + return cache.computeIfAbsent(scale, Base2ExponentialHistogramIndexer::new); + } + + /** + * Compute the index for the given value. + * + *

      The algorithm to retrieve the index is specified in the OpenTelemetry + * specification. + * + * @param value Measured value (must be non-zero). + * @return the index of the bucket which the value maps to. + */ + int computeIndex(double value) { + double absValue = Math.abs(value); + // For positive scales, compute the index by logarithm, which is simpler but may be + // inaccurate near bucket boundaries + if (scale > 0) { + return getIndexByLogarithm(absValue); + } + // For scale zero, compute the exact index by extracting the exponent + if (scale == 0) { + return mapToIndexScaleZero(absValue); + } + // For negative scales, compute the exact index by extracting the exponent and shifting it to + // the right by -scale + return mapToIndexScaleZero(absValue) >> -scale; + } + + /** + * Compute the bucket index using a logarithm based approach. + * + * @see All + * Scales: Use the Logarithm Function + */ + private int getIndexByLogarithm(double value) { + return (int) Math.ceil(Math.log(value) * scaleFactor) - 1; + } + + /** + * Compute the exact bucket index for scale zero by extracting the exponent. + * + * @see Scale + * Zero: Extract the Exponent + */ + private static int mapToIndexScaleZero(double value) { + long rawBits = Double.doubleToLongBits(value); + long rawExponent = (rawBits & EXPONENT_BIT_MASK) >> SIGNIFICAND_WIDTH; + long rawSignificand = rawBits & SIGNIFICAND_BIT_MASK; + if (rawExponent == 0) { + rawExponent -= Long.numberOfLeadingZeros(rawSignificand - 1) - EXPONENT_WIDTH - 1; + } + int ieeeExponent = (int) (rawExponent - EXPONENT_BIAS); + if (rawSignificand == 0) { + return ieeeExponent - 1; + } + return ieeeExponent; + } + + private static double computeScaleFactor(int scale) { + return Math.scalb(LOG_BASE2_E, scale); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleAccumulation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleAccumulation.java deleted file mode 100644 index 2f64e4b9ead..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleAccumulation.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import java.util.Collections; -import java.util.List; -import javax.annotation.concurrent.Immutable; - -/** - * An accumulation representing {@code long} values and exemplars. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - * - *

      Visible for testing. - */ -@Immutable -@AutoValue -public abstract class DoubleAccumulation { - - static DoubleAccumulation create(double value, List exemplars) { - return new AutoValue_DoubleAccumulation(value, exemplars); - } - - public static DoubleAccumulation create(double value) { - return create(value, Collections.emptyList()); - } - - DoubleAccumulation() {} - - /** The current value. */ - public abstract double getValue(); - - /** Sampled measurements recorded during this accumulation. */ - abstract List getExemplars(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregator.java new file mode 100644 index 00000000000..fe5c301f1fe --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregator.java @@ -0,0 +1,296 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.data.EmptyExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.MutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.MutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import java.util.List; +import javax.annotation.Nullable; + +/** + * Aggregator that generates base2 exponential histograms. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class DoubleBase2ExponentialHistogramAggregator + implements Aggregator { + + private final ExemplarReservoirFactory reservoirFactory; + private final int maxBuckets; + private final int maxScale; + private final boolean recordMinMax; + private final MemoryMode memoryMode; + + /** + * Constructs an exponential histogram aggregator. + * + * @param reservoirFactory Supplier of exemplar reservoirs per-stream. + * @param maxBuckets maximum number of buckets in each of the positive and negative ranges + * @param maxScale maximum scale factor + * @param recordMinMax whether to record min and max values + * @param memoryMode The {@link MemoryMode} to use in this aggregator. + */ + public DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory reservoirFactory, + int maxBuckets, + int maxScale, + boolean recordMinMax, + MemoryMode memoryMode) { + this.reservoirFactory = reservoirFactory; + this.maxBuckets = maxBuckets; + this.maxScale = maxScale; + this.recordMinMax = recordMinMax; + this.memoryMode = memoryMode; + } + + @Override + public AggregatorHandle createHandle(long creationEpochNanos) { + return new Handle( + creationEpochNanos, reservoirFactory, maxBuckets, maxScale, recordMinMax, memoryMode); + } + + @Override + public MetricData toMetricData( + Resource resource, + InstrumentationScopeInfo instrumentationScopeInfo, + MetricDescriptor metricDescriptor, + Collection points, + AggregationTemporality temporality) { + return ImmutableMetricData.createExponentialHistogram( + resource, + instrumentationScopeInfo, + metricDescriptor.getName(), + metricDescriptor.getDescription(), + metricDescriptor.getSourceInstrument().getUnit(), + ImmutableExponentialHistogramData.create(temporality, points)); + } + + static final class Handle extends AggregatorHandle { + private final int maxBuckets; + private final int maxScale; + private final boolean recordMinMax; + @Nullable private DoubleBase2ExponentialHistogramBuckets positiveBuckets; + @Nullable private DoubleBase2ExponentialHistogramBuckets negativeBuckets; + private long zeroCount; + private double sum; + private double min; + private double max; + private long count; + private int currentScale; + private final MemoryMode memoryMode; + + // Used only when MemoryMode = REUSABLE_DATA + @Nullable private final MutableExponentialHistogramPointData reusablePoint; + + Handle( + long creationEpochNanos, + ExemplarReservoirFactory reservoirFactory, + int maxBuckets, + int maxScale, + boolean recordMinMax, + MemoryMode memoryMode) { + super(creationEpochNanos, reservoirFactory, /* isDoubleType= */ true); + this.maxBuckets = maxBuckets; + this.maxScale = maxScale; + this.recordMinMax = recordMinMax; + this.sum = 0; + this.zeroCount = 0; + this.min = Double.MAX_VALUE; + this.max = -1; + this.count = 0; + this.currentScale = maxScale; + this.reusablePoint = + (memoryMode == MemoryMode.REUSABLE_DATA) + ? new MutableExponentialHistogramPointData() + : null; + this.memoryMode = memoryMode; + } + + @Override + protected synchronized ExponentialHistogramPointData doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + + ExponentialHistogramPointData point; + if (reusablePoint == null) { + point = + ImmutableExponentialHistogramPointData.create( + currentScale, + sum, + zeroCount, + recordMinMax && this.count > 0, + recordMinMax ? this.min : 0, + recordMinMax && this.count > 0, + recordMinMax ? this.max : 0, + resolveBuckets( + this.positiveBuckets, currentScale, reset, /* reusableBuckets= */ null), + resolveBuckets( + this.negativeBuckets, currentScale, reset, /* reusableBuckets= */ null), + startEpochNanos, + epochNanos, + attributes, + exemplars); + } else /* REUSABLE_DATA */ { + point = + reusablePoint.set( + currentScale, + sum, + zeroCount, + recordMinMax && this.count > 0, + recordMinMax ? this.min : 0, + recordMinMax && this.count > 0, + recordMinMax ? this.max : 0, + resolveBuckets( + this.positiveBuckets, currentScale, reset, reusablePoint.getPositiveBuckets()), + resolveBuckets( + this.negativeBuckets, currentScale, reset, reusablePoint.getNegativeBuckets()), + startEpochNanos, + epochNanos, + attributes, + exemplars); + } + + if (reset) { + this.sum = 0; + this.zeroCount = 0; + this.min = Double.MAX_VALUE; + this.max = -1; + this.count = 0; + this.currentScale = maxScale; + } + return point; + } + + private ExponentialHistogramBuckets resolveBuckets( + @Nullable DoubleBase2ExponentialHistogramBuckets buckets, + int scale, + boolean reset, + @Nullable ExponentialHistogramBuckets reusableBuckets) { + if (buckets == null) { + return EmptyExponentialHistogramBuckets.get(scale); + } + + ExponentialHistogramBuckets copy; + if (reusableBuckets == null) { + copy = buckets.copy(); + } else { + MutableExponentialHistogramBuckets mutableExponentialHistogramBuckets; + if (reusableBuckets instanceof MutableExponentialHistogramBuckets) { + mutableExponentialHistogramBuckets = (MutableExponentialHistogramBuckets) reusableBuckets; + } else /* EmptyExponentialHistogramBuckets */ { + mutableExponentialHistogramBuckets = new MutableExponentialHistogramBuckets(); + } + + DynamicPrimitiveLongList reusableBucketCountsList = + mutableExponentialHistogramBuckets.getReusableBucketCountsList(); + buckets.getBucketCountsIntoReusableList(reusableBucketCountsList); + + mutableExponentialHistogramBuckets.set( + buckets.getScale(), + buckets.getOffset(), + buckets.getTotalCount(), + reusableBucketCountsList); + + copy = mutableExponentialHistogramBuckets; + } + + if (reset) { + buckets.clear(maxScale); + } + return copy; + } + + @Override + protected synchronized void doRecordDouble(double value) { + // ignore NaN and infinity + if (!Double.isFinite(value)) { + return; + } + + sum += value; + + if (recordMinMax) { + this.min = Math.min(this.min, value); + this.max = Math.max(this.max, value); + } + count++; + + int c = Double.compare(value, 0); + DoubleBase2ExponentialHistogramBuckets buckets; + if (c == 0) { + zeroCount++; + return; + } else if (c > 0) { + // Initialize positive buckets at current scale, if needed + if (positiveBuckets == null) { + positiveBuckets = + new DoubleBase2ExponentialHistogramBuckets(currentScale, maxBuckets, memoryMode); + } + buckets = positiveBuckets; + } else { + // Initialize negative buckets at current scale, if needed + if (negativeBuckets == null) { + negativeBuckets = + new DoubleBase2ExponentialHistogramBuckets(currentScale, maxBuckets, memoryMode); + } + buckets = negativeBuckets; + } + + // Record; If recording fails, calculate scale reduction and scale down to fit new value. + // 2nd attempt at recording should work with new scale + // TODO: We should experiment with downscale on demand during sync execution and only + // unifying scale factor between positive/negative at collection time + // (doAggregateThenMaybeReset). + if (!buckets.record(value)) { + // getScaleReduction() used with downScale() will scale down as required to record value, + // fit inside max allowed buckets, and make sure index can be represented by int. + downScale(buckets.getScaleReduction(value)); + buckets.record(value); + } + } + + @Override + public void recordLong(long value, Attributes attributes, Context context) { + // Since there is no LongExplicitBucketHistogramAggregator and we need to support measurements + // from LongHistogram, we redirect calls from #recordLong to #recordDouble. Without this, the + // base AggregatorHandle implementation of #recordLong throws. + super.recordDouble((double) value, attributes, context); + } + + void downScale(int by) { + if (positiveBuckets != null) { + positiveBuckets.downscale(by); + currentScale = positiveBuckets.getScale(); + } + if (negativeBuckets != null) { + negativeBuckets.downscale(by); + currentScale = negativeBuckets.getScale(); + } + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramBuckets.java new file mode 100644 index 00000000000..6b7cedebc5b --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramBuckets.java @@ -0,0 +1,293 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; +import static io.opentelemetry.sdk.common.export.MemoryMode.REUSABLE_DATA; + +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.common.internal.PrimitiveLongList; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; + +/** + * This class handles the operations for recording, scaling, and exposing data related to the base2 + * exponential histogram. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class DoubleBase2ExponentialHistogramBuckets implements ExponentialHistogramBuckets { + + private final MemoryMode memoryMode; + private AdaptingCircularBufferCounter counts; + private int scale; + private Base2ExponentialHistogramIndexer base2ExponentialHistogramIndexer; + private long totalCount; + + // Only used when memory mode is REUSABLE_DATA + @Nullable private AdaptingCircularBufferCounter reusableCounts; + + DoubleBase2ExponentialHistogramBuckets(int scale, int maxBuckets, MemoryMode memoryMode) { + this.memoryMode = memoryMode; + this.counts = new AdaptingCircularBufferCounter(maxBuckets); + this.scale = scale; + this.base2ExponentialHistogramIndexer = Base2ExponentialHistogramIndexer.get(this.scale); + this.totalCount = 0; + } + + // For copying + DoubleBase2ExponentialHistogramBuckets(DoubleBase2ExponentialHistogramBuckets buckets) { + this.counts = new AdaptingCircularBufferCounter(buckets.counts); + this.scale = buckets.scale; + this.base2ExponentialHistogramIndexer = buckets.base2ExponentialHistogramIndexer; + this.totalCount = buckets.totalCount; + this.memoryMode = buckets.memoryMode; + this.reusableCounts = buckets.reusableCounts; + } + + /** Returns a copy of this bucket. */ + DoubleBase2ExponentialHistogramBuckets copy() { + return new DoubleBase2ExponentialHistogramBuckets(this); + } + + /** Resets all counters in this bucket set to zero and resets the scale to {@code scale}. */ + void clear(int scale) { + this.totalCount = 0; + this.scale = scale; + this.base2ExponentialHistogramIndexer = Base2ExponentialHistogramIndexer.get(this.scale); + this.counts.clear(); + } + + boolean record(double value) { + if (value == 0.0) { + // Guarded by caller. If passed 0 it would be a bug in the SDK. + throw new IllegalStateException("Illegal attempted recording of zero at bucket level."); + } + int index = base2ExponentialHistogramIndexer.computeIndex(value); + boolean recordingSuccessful = this.counts.increment(index, 1); + if (recordingSuccessful) { + totalCount++; + } + return recordingSuccessful; + } + + @Override + public int getOffset() { + // We need to unify the behavior of empty buckets. + // Unfortunately, getIndexStart is not meaningful for empty counters, so we default to + // returning 0 for offset and an empty list. + if (counts.isEmpty()) { + return 0; + } + return counts.getIndexStart(); + } + + @Override + public List getBucketCounts() { + if (counts.isEmpty()) { + return Collections.emptyList(); + } + int length = counts.getIndexEnd() - counts.getIndexStart() + 1; + long[] countsArr = new long[length]; + for (int i = 0; i < length; i++) { + countsArr[i] = counts.get(i + counts.getIndexStart()); + } + return PrimitiveLongList.wrap(countsArr); + } + + /** + * Fills the given reusable list with the bucket counts. + * + *

      NOTE: This is the same as {@link #getBucketCounts()} but instead of returning a List with + * the values is fill the values into {@code reusableLongList} + * + * @param reusableLongList The list to fill with the bucket counts + */ + void getBucketCountsIntoReusableList(DynamicPrimitiveLongList reusableLongList) { + if (counts.isEmpty()) { + reusableLongList.resizeAndClear(0); + return; + } + + int length = counts.getIndexEnd() - counts.getIndexStart() + 1; + + if (reusableLongList.size() != length) { + reusableLongList.resizeAndClear(length); + } + + for (int i = 0; i < length; i++) { + reusableLongList.setLong(i, counts.get(i + counts.getIndexStart())); + } + } + + @Override + public long getTotalCount() { + return totalCount; + } + + void downscale(int by) { + if (by == 0) { + return; + } else if (by < 0) { + // This should never happen without an SDK bug + throw new IllegalStateException("Cannot downscale by negative amount. Was given " + by + "."); + } + + if (!counts.isEmpty()) { + // We want to preserve other optimisations here as well, e.g. integer size. + // Instead of creating a new counter, we copy the existing one (for bucket size + // optimisations), and clear the values before writing the new ones. + AdaptingCircularBufferCounter newCounts; + if (memoryMode == IMMUTABLE_DATA) { + newCounts = new AdaptingCircularBufferCounter(counts); + } else { + if (reusableCounts == null) { + reusableCounts = new AdaptingCircularBufferCounter(counts); + } + newCounts = reusableCounts; + } + + newCounts.clear(); + + for (int i = counts.getIndexStart(); i <= counts.getIndexEnd(); i++) { + long count = counts.get(i); + if (count > 0) { + if (!newCounts.increment(i >> by, count)) { + // Theoretically won't happen unless there's an overflow on index + throw new IllegalStateException("Failed to create new downscaled buckets."); + } + } + } + + if (memoryMode == REUSABLE_DATA) { + AdaptingCircularBufferCounter existingCounts = this.counts; + this.counts = newCounts; + reusableCounts = existingCounts; + } else { + this.counts = newCounts; + } + } + + this.scale = this.scale - by; + this.base2ExponentialHistogramIndexer = Base2ExponentialHistogramIndexer.get(this.scale); + } + + @Override + public int getScale() { + return scale; + } + + /** + * Returns the minimum scale reduction required to record the given value in these buckets, by + * calculating the new required window to allow the new value to be recorded. To be used with + * downScale(). + * + * @param value The proposed value to be recorded. + * @return The required scale reduction in order to fit the value in these buckets. + */ + int getScaleReduction(double value) { + long index = base2ExponentialHistogramIndexer.computeIndex(value); + long newStart = Math.min(index, counts.getIndexStart()); + long newEnd = Math.max(index, counts.getIndexEnd()); + return getScaleReduction(newStart, newEnd); + } + + int getScaleReduction(long newStart, long newEnd) { + int scaleReduction = 0; + + while (newEnd - newStart + 1 > counts.getMaxSize()) { + newStart >>= 1; + newEnd >>= 1; + scaleReduction++; + } + return scaleReduction; + } + + @Override + public boolean equals(@Nullable Object obj) { + if (!(obj instanceof DoubleBase2ExponentialHistogramBuckets)) { + return false; + } + DoubleBase2ExponentialHistogramBuckets other = (DoubleBase2ExponentialHistogramBuckets) obj; + // Don't need to compare getTotalCount() because equivalent bucket counts + // imply equivalent overall count. + // Additionally, we compare the "semantics" of bucket counts, that is + // it's ok for getOffset() to diverge as long as the populated counts remain + // the same. This is because we don't "normalize" buckets after doing + // difference/subtraction operations. + return this.scale == other.scale && sameBucketCounts(other); + } + + /** + * Tests if two bucket counts are equivalent semantically. + * + *

      Semantic equivalence means: + * + *

        + *
      • All counts are stored between indexStart/indexEnd. + *
      • Offset does NOT need to be the same + *
      + */ + private boolean sameBucketCounts(DoubleBase2ExponentialHistogramBuckets other) { + if (this.totalCount != other.totalCount) { + return false; + } + int min = Math.min(this.counts.getIndexStart(), other.counts.getIndexStart()); + + // This check is so we avoid iterating from Integer.MIN_VALUE. + // In this case, we can assume that those buckets are empty. + // We start iterating from the other bucket index instead. + // They still may be equal as it is possible for another set of buckets + // to be empty but have a higher start index. + if (min == Integer.MIN_VALUE) { + min = Math.max(this.counts.getIndexStart(), other.counts.getIndexStart()); + } + + int max = Math.max(this.counts.getIndexEnd(), other.counts.getIndexEnd()); + for (int idx = min; idx <= max; idx++) { + if (this.counts.get(idx) != other.counts.get(idx)) { + return false; + } + } + return true; + } + + @Override + public int hashCode() { + int hash = 1; + hash *= 1000003; + // We need a new algorithm here that lines up w/ equals, so we only use non-zero counts. + for (int idx = this.counts.getIndexStart(); idx <= this.counts.getIndexEnd(); idx++) { + long count = this.counts.get(idx); + if (count != 0) { + hash ^= idx; + hash *= 1000003; + hash = (int) (hash ^ count); + hash *= 1000003; + } + } + hash ^= scale; + // Don't need to hash getTotalCount() because equivalent bucket + // counts imply equivalent overall count. + return hash; + } + + @Override + public String toString() { + return "DoubleExponentialHistogramBuckets{" + + "scale: " + + scale + + ", offset: " + + getOffset() + + ", counts: " + + counts + + " }"; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregator.java index f638bdc6709..176d1bbfa6c 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregator.java @@ -6,23 +6,32 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.GuardedBy; +import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.PrimitiveLongList; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.concurrent.AdderUtil; +import io.opentelemetry.sdk.metrics.internal.concurrent.DoubleAdder; +import io.opentelemetry.sdk.metrics.internal.concurrent.LongAdder; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.MutableHistogramPointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.concurrent.locks.ReentrantLock; -import java.util.function.Supplier; +import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; +import javax.annotation.Nullable; /** * Aggregator that generates explicit bucket histograms. @@ -31,69 +40,45 @@ * at any time. */ public final class DoubleExplicitBucketHistogramAggregator - implements Aggregator { + implements Aggregator { private final double[] boundaries; + private final boolean recordMinMax; + private final MemoryMode memoryMode; // a cache for converting to MetricData private final List boundaryList; - private final Supplier> reservoirSupplier; + private final ExemplarReservoirFactory reservoirFactory; /** * Constructs an explicit bucket histogram aggregator. * * @param boundaries Bucket boundaries, in-order. - * @param reservoirSupplier Supplier of exemplar reservoirs per-stream. + * @param recordMinMax whether to record min and max values + * @param reservoirFactory Supplier of exemplar reservoirs per-stream. + * @param memoryMode The {@link MemoryMode} to use in this aggregator. */ public DoubleExplicitBucketHistogramAggregator( - double[] boundaries, Supplier> reservoirSupplier) { + double[] boundaries, + boolean recordMinMax, + ExemplarReservoirFactory reservoirFactory, + MemoryMode memoryMode) { this.boundaries = boundaries; + this.recordMinMax = recordMinMax; + this.memoryMode = memoryMode; List boundaryList = new ArrayList<>(this.boundaries.length); for (double v : this.boundaries) { boundaryList.add(v); } this.boundaryList = Collections.unmodifiableList(boundaryList); - this.reservoirSupplier = reservoirSupplier; + this.reservoirFactory = reservoirFactory; } @Override - public AggregatorHandle createHandle() { - return new Handle(this.boundaries, reservoirSupplier.get()); - } - - /** - * Return the result of the merge of two histogram accumulations. As long as one Aggregator - * instance produces all Accumulations with constant boundaries we don't need to worry about - * merging accumulations with different boundaries. - */ - @Override - public ExplicitBucketHistogramAccumulation merge( - ExplicitBucketHistogramAccumulation previous, ExplicitBucketHistogramAccumulation current) { - long[] previousCounts = previous.getCounts(); - long[] mergedCounts = new long[previousCounts.length]; - for (int i = 0; i < previousCounts.length; ++i) { - mergedCounts[i] = previousCounts[i] + current.getCounts()[i]; - } - double min = -1; - double max = -1; - if (previous.hasMinMax() && current.hasMinMax()) { - min = Math.min(previous.getMin(), current.getMin()); - max = Math.max(previous.getMax(), current.getMax()); - } else if (previous.hasMinMax()) { - min = previous.getMin(); - max = previous.getMax(); - } else if (current.hasMinMax()) { - min = current.getMin(); - max = current.getMax(); - } - return ExplicitBucketHistogramAccumulation.create( - previous.getSum() + current.getSum(), - previous.hasMinMax() || current.hasMinMax(), - min, - max, - mergedCounts, - current.getExemplars()); + public AggregatorHandle createHandle(long creationEpochNanos) { + return new Handle( + creationEpochNanos, boundaryList, boundaries, recordMinMax, reservoirFactory, memoryMode); } @Override @@ -101,103 +86,264 @@ public MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, MetricDescriptor metricDescriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos) { + Collection pointData, + AggregationTemporality temporality) { return ImmutableMetricData.createDoubleHistogram( resource, instrumentationScopeInfo, metricDescriptor.getName(), metricDescriptor.getDescription(), metricDescriptor.getSourceInstrument().getUnit(), - ImmutableHistogramData.create( - temporality, - MetricDataUtils.toExplicitBucketHistogramPointList( - accumulationByLabels, - (temporality == AggregationTemporality.CUMULATIVE) - ? startEpochNanos - : lastCollectionEpoch, - epochNanos, - boundaryList))); + ImmutableHistogramData.create(temporality, pointData)); } - static final class Handle - extends AggregatorHandle { - // read-only + /** + * Lock-free histogram handle inspired by prometheus/client_java. + * + *

      Bucket counts and running sum use {@link LongAdder} / {@link DoubleAdder}. Min and max use + * CAS loops on volatile long bit patterns with a fast-exit for non-extremes. Total count is + * derived from bucket counts at collect. + * + *

      A thread-striped {@link AtomicLong} array coordinates record and collect. Its sign bit + * signals "collect in progress". Recorders back out and spin when they observe it. This prevents + * an observation's writes from being split across collections. + * + *

      Within {@link #doRecordDouble} the bucket increment is the last write. Its internal volatile + * write publishes the prior sum/min/max writes, so the collector's wait for {@code + * sum(bucketCounts) >= expected} doubles as a barrier for the whole observation. + */ + static final class Handle extends AggregatorHandle { + private static final long COLLECT_BIT = 1L << 63; + private static final long MIN_INIT_BITS = Double.doubleToRawLongBits(Double.POSITIVE_INFINITY); + private static final long MAX_INIT_BITS = Double.doubleToRawLongBits(Double.NEGATIVE_INFINITY); + private static final AtomicLongFieldUpdater MIN_BITS = + AtomicLongFieldUpdater.newUpdater(Handle.class, "minBits"); + private static final AtomicLongFieldUpdater MAX_BITS = + AtomicLongFieldUpdater.newUpdater(Handle.class, "maxBits"); + + private final List boundaryList; private final double[] boundaries; + private final boolean recordMinMax; + + private final LongAdder[] bucketCounts; + private final DoubleAdder sum = AdderUtil.createDoubleAdder(); - @GuardedBy("lock") - private double sum; + // Min / max as raw double bits so they can be CAS-updated via AtomicLongFieldUpdater. Updated + // via CAS loops that fast-exit when the observation isn't a new extreme β€” the common + // steady-state case has no memory write. + @SuppressWarnings("UnusedVariable") + private volatile long minBits = MIN_INIT_BITS; - @GuardedBy("lock") - private double min; + @SuppressWarnings("UnusedVariable") + private volatile long maxBits = MAX_INIT_BITS; - @GuardedBy("lock") - private double max; + // Power-of-2 length so the stripe probe is a bitwise AND with stripeMask. + private final AtomicLong[] stripedStartedCounter; + private final int stripeMask; - @GuardedBy("lock") - private long count; + // Observations that have made it into buckets across all time (current + previously + // drained). Reconciles bucketCounts (drained on delta reset) with cumulativeStarted (never + // resets). Cumulative: stays 0. Delta: += drained totalCount each cycle. Collector-only. + private long cumulativeDrainedCount; - @GuardedBy("lock") - private final long[] counts; + private final long[] countsScratch; - private final ReentrantLock lock = new ReentrantLock(); + // Non-null only when MemoryMode == REUSABLE_DATA. + @Nullable private final MutableHistogramPointData reusablePoint; - Handle(double[] boundaries, ExemplarReservoir reservoir) { - super(reservoir); + Handle( + long creationEpochNanos, + List boundaryList, + double[] boundaries, + boolean recordMinMax, + ExemplarReservoirFactory reservoirFactory, + MemoryMode memoryMode) { + super(creationEpochNanos, reservoirFactory, /* isDoubleType= */ true); + this.boundaryList = boundaryList; this.boundaries = boundaries; - this.counts = new long[this.boundaries.length + 1]; - this.sum = 0; - this.min = Double.MAX_VALUE; - this.max = -1; - this.count = 0; + this.recordMinMax = recordMinMax; + int bucketCount = boundaries.length + 1; + this.bucketCounts = new LongAdder[bucketCount]; + for (int i = 0; i < bucketCount; i++) { + this.bucketCounts[i] = AdderUtil.createLongAdder(); + } + // Sized to NCPUS (rounded up to a power of 2 so the probe mask compiles to a bitwise AND). + // NCPUS is an upper bound on threads simultaneously executing, which bounds the useful + // stripe count for handling per-handle contention. + int stripes = roundUpToPowerOfTwo(Runtime.getRuntime().availableProcessors()); + this.stripedStartedCounter = new AtomicLong[stripes]; + for (int i = 0; i < stripes; i++) { + this.stripedStartedCounter[i] = new AtomicLong(); + } + this.stripeMask = stripes - 1; + this.countsScratch = new long[bucketCount]; + if (memoryMode == MemoryMode.REUSABLE_DATA) { + this.reusablePoint = new MutableHistogramPointData(bucketCount); + } else { + this.reusablePoint = null; + } } @Override - protected ExplicitBucketHistogramAccumulation doAccumulateThenReset( - List exemplars) { - lock.lock(); - try { - ExplicitBucketHistogramAccumulation acc = - ExplicitBucketHistogramAccumulation.create( - sum, - this.count > 0, - this.count > 0 ? this.min : -1, - this.count > 0 ? this.max : -1, - Arrays.copyOf(counts, counts.length), - exemplars); - this.sum = 0; - this.min = Double.MAX_VALUE; - this.max = -1; - this.count = 0; - Arrays.fill(this.counts, 0); - return acc; - } finally { - lock.unlock(); - } + public void recordLong(long value, Attributes attributes, Context context) { + // There is no LongExplicitBucketHistogramAggregator. Redirect to recordDouble so + // LongHistogram measurements route through this handle. + super.recordDouble((double) value, attributes, context); } @Override + @SuppressWarnings("ThreadPriorityCheck") protected void doRecordDouble(double value) { int bucketIndex = ExplicitBucketHistogramUtils.findBucketIndex(this.boundaries, value); - lock.lock(); - try { - this.sum += value; - this.min = Math.min(this.min, value); - this.max = Math.max(this.max, value); - this.count++; - this.counts[bucketIndex]++; - } finally { - lock.unlock(); + // Reserve a pre-flip slot on our stripe via CAS. Increment only when the bit is clear at + // the time of the CAS, otherwise spin until the collector's Phase 4 clears the bit and + // retry. + AtomicLong stripe = + stripedStartedCounter[System.identityHashCode(Thread.currentThread()) & stripeMask]; + while (true) { + long current = stripe.get(); + if ((current & COLLECT_BIT) != 0) { + while ((stripe.get() & COLLECT_BIT) != 0) { + Thread.yield(); + } + continue; + } + if (stripe.compareAndSet(current, current + 1)) { + break; + } + // CAS lost the race (either the bit was just set or another recorder incremented); + // loop and reevaluate. + } + + sum.add(value); + if (recordMinMax) { + updateMin(value); + updateMax(value); } + bucketCounts[bucketIndex].increment(); + } + + /** Fast-exits without a CAS when {@code value} is not smaller than the current min. */ + private void updateMin(double value) { + long newBits = Double.doubleToRawLongBits(value); + long cur; + do { + cur = minBits; + if (value >= Double.longBitsToDouble(cur)) { + return; + } + } while (!MIN_BITS.compareAndSet(this, cur, newBits)); + } + + /** Fast-exits without a CAS when {@code value} is not larger than the current max. */ + private void updateMax(double value) { + long newBits = Double.doubleToRawLongBits(value); + long cur; + do { + cur = maxBits; + if (value <= Double.longBitsToDouble(cur)) { + return; + } + } while (!MAX_BITS.compareAndSet(this, cur, newBits)); } @Override - protected void doRecordLong(long value) { - doRecordDouble((double) value); + @SuppressWarnings("ThreadPriorityCheck") + protected HistogramPointData doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + // Phase 1: set the collect bit on every stripe. Capture the pre-flip cumulative count. + long cumulativeStarted = 0; + for (AtomicLong stripe : stripedStartedCounter) { + cumulativeStarted += stripe.getAndAdd(COLLECT_BIT) & ~COLLECT_BIT; + } + + // Phase 2: wait for pre-flip recorders to publish their bucket increments. Post-flip + // recorders are spinning on the collect bit, so nothing new arrives. + while (bucketSumTotal() + cumulativeDrainedCount < cumulativeStarted) { + Thread.yield(); + } + + // Phase 3: snapshot (and reset if delta) with recorders quiescent. + long totalCount = 0; + for (int i = 0; i < bucketCounts.length; i++) { + long c = reset ? bucketCounts[i].sumThenReset() : bucketCounts[i].sum(); + countsScratch[i] = c; + totalCount += c; + } + if (reset) { + cumulativeDrainedCount += totalCount; + } + double totalSum = reset ? sum.sumThenReset() : sum.sum(); + + double snapshotMin = Double.POSITIVE_INFINITY; + double snapshotMax = Double.NEGATIVE_INFINITY; + if (recordMinMax) { + long minSnapshot = reset ? MIN_BITS.getAndSet(this, MIN_INIT_BITS) : minBits; + long maxSnapshot = reset ? MAX_BITS.getAndSet(this, MAX_INIT_BITS) : maxBits; + snapshotMin = Double.longBitsToDouble(minSnapshot); + snapshotMax = Double.longBitsToDouble(maxSnapshot); + } + + // Phase 4: clear the collect bit. addAndGet(COLLECT_BIT) toggles the sign bit off via + // two's-complement overflow. Spinning recorders resume. + for (AtomicLong stripe : stripedStartedCounter) { + stripe.addAndGet(COLLECT_BIT); + } + + HistogramPointData pointData; + if (reusablePoint == null) { + pointData = + ImmutableHistogramPointData.create( + startEpochNanos, + epochNanos, + attributes, + totalSum, + recordMinMax && totalCount > 0, + recordMinMax ? snapshotMin : 0, + recordMinMax && totalCount > 0, + recordMinMax ? snapshotMax : 0, + boundaryList, + PrimitiveLongList.wrap(Arrays.copyOf(countsScratch, countsScratch.length)), + exemplars); + } else /* REUSABLE_DATA */ { + pointData = + reusablePoint.set( + startEpochNanos, + epochNanos, + attributes, + totalSum, + recordMinMax && totalCount > 0, + recordMinMax ? snapshotMin : 0, + recordMinMax && totalCount > 0, + recordMinMax ? snapshotMax : 0, + boundaryList, + countsScratch, + exemplars); + } + return pointData; + } + + private long bucketSumTotal() { + long total = 0; + for (LongAdder adder : bucketCounts) { + total += adder.sum(); + } + return total; + } + + /** Smallest power of 2 >= {@code n}, with a floor of 1. */ + private static int roundUpToPowerOfTwo(int n) { + if (n <= 1) { + return 1; + } + int highest = Integer.highestOneBit(n); + return highest == n ? highest : highest << 1; } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramAggregator.java deleted file mode 100644 index 4667f0385c4..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramAggregator.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounterFactory; -import io.opentelemetry.sdk.resources.Resource; -import java.util.List; -import java.util.Map; -import java.util.function.Supplier; - -/** - * Aggregator that generates exponential histograms. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class DoubleExponentialHistogramAggregator - implements Aggregator { - - private final Supplier> reservoirSupplier; - private final ExponentialBucketStrategy bucketStrategy; - - /** - * Constructs an exponential histogram aggregator. - * - * @param scale the starting scale. - * @param maxBuckets the maximum number of buckets that will be used for positive or negative - * recordings. - * @param reservoirSupplier Supplier of exemplar reservoirs per-stream. - */ - public DoubleExponentialHistogramAggregator( - Supplier> reservoirSupplier, - int scale, - int maxBuckets) { - this( - reservoirSupplier, - ExponentialBucketStrategy.newStrategy( - scale, maxBuckets, ExponentialCounterFactory.circularBufferCounter())); - } - - DoubleExponentialHistogramAggregator( - Supplier> reservoirSupplier, - ExponentialBucketStrategy bucketStrategy) { - this.reservoirSupplier = reservoirSupplier; - this.bucketStrategy = bucketStrategy; - } - - @Override - public AggregatorHandle createHandle() { - return new Handle(reservoirSupplier.get(), this.bucketStrategy); - } - - /** - * This function is an immutable merge. It firstly combines the sum and zero count. Then it - * performs a merge using the buckets from both accumulations, without modifying those - * accumulations. - * - * @param previous the previously captured accumulation - * @param current the newly captured (delta) accumulation - * @return the result of the merge of the given accumulations. - */ - @Override - public ExponentialHistogramAccumulation merge( - ExponentialHistogramAccumulation previous, ExponentialHistogramAccumulation current) { - - // Create merged buckets - DoubleExponentialHistogramBuckets posBuckets = - DoubleExponentialHistogramBuckets.merge( - previous.getPositiveBuckets(), current.getPositiveBuckets()); - DoubleExponentialHistogramBuckets negBuckets = - DoubleExponentialHistogramBuckets.merge( - previous.getNegativeBuckets(), current.getNegativeBuckets()); - - // resolve possible scale difference due to merge - int commonScale = Math.min(posBuckets.getScale(), negBuckets.getScale()); - posBuckets.downscale(posBuckets.getScale() - commonScale); - negBuckets.downscale(negBuckets.getScale() - commonScale); - double min = -1; - double max = -1; - if (previous.hasMinMax() && current.hasMinMax()) { - min = Math.min(previous.getMin(), current.getMin()); - max = Math.max(previous.getMax(), current.getMax()); - } else if (previous.hasMinMax()) { - min = previous.getMin(); - max = previous.getMax(); - } else if (current.hasMinMax()) { - min = current.getMin(); - max = current.getMax(); - } - return ExponentialHistogramAccumulation.create( - posBuckets.getScale(), - previous.getSum() + current.getSum(), - previous.hasMinMax() || current.hasMinMax(), - min, - max, - posBuckets, - negBuckets, - previous.getZeroCount() + current.getZeroCount(), - current.getExemplars()); - } - - @Override - public MetricData toMetricData( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - MetricDescriptor metricDescriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos) { - return ImmutableMetricData.createExponentialHistogram( - resource, - instrumentationScopeInfo, - metricDescriptor.getName(), - metricDescriptor.getDescription(), - metricDescriptor.getSourceInstrument().getUnit(), - ExponentialHistogramData.create( - temporality, - MetricDataUtils.toExponentialHistogramPointList( - accumulationByLabels, - (temporality == AggregationTemporality.CUMULATIVE) - ? startEpochNanos - : lastCollectionEpoch, - epochNanos))); - } - - static final class Handle - extends AggregatorHandle { - private final DoubleExponentialHistogramBuckets positiveBuckets; - private final DoubleExponentialHistogramBuckets negativeBuckets; - private long zeroCount; - private double sum; - private double min; - private double max; - private long count; - - Handle( - ExemplarReservoir reservoir, ExponentialBucketStrategy bucketStrategy) { - super(reservoir); - this.sum = 0; - this.zeroCount = 0; - this.min = Double.MAX_VALUE; - this.max = -1; - this.count = 0; - this.positiveBuckets = bucketStrategy.newBuckets(); - this.negativeBuckets = bucketStrategy.newBuckets(); - } - - @Override - protected synchronized ExponentialHistogramAccumulation doAccumulateThenReset( - List exemplars) { - ExponentialHistogramAccumulation acc = - ExponentialHistogramAccumulation.create( - this.positiveBuckets.getScale(), - sum, - this.count > 0, - this.count > 0 ? this.min : -1, - this.count > 0 ? this.max : -1, - positiveBuckets.copy(), - negativeBuckets.copy(), - zeroCount, - exemplars); - this.sum = 0; - this.zeroCount = 0; - this.min = Double.MAX_VALUE; - this.max = -1; - this.count = 0; - this.positiveBuckets.clear(); - this.negativeBuckets.clear(); - return acc; - } - - @Override - protected synchronized void doRecordDouble(double value) { - - // ignore NaN and infinity - if (!Double.isFinite(value)) { - return; - } - - sum += value; - - this.min = Math.min(this.min, value); - this.max = Math.max(this.max, value); - count++; - - int c = Double.compare(value, 0); - if (c == 0) { - zeroCount++; - return; - } - - // Record; If recording fails, calculate scale reduction and scale down to fit new value. - // 2nd attempt at recording should work with new scale - DoubleExponentialHistogramBuckets buckets = (c > 0) ? positiveBuckets : negativeBuckets; - // TODO: We should experiment with downscale on demand during sync execution and only - // unifying scale factor between positive/negative at collection time (doAccumulate). - if (!buckets.record(value)) { - // getScaleReduction() used with downScale() will scale down as required to record value, - // fit inside max allowed buckets, and make sure index can be represented by int. - downScale(buckets.getScaleReduction(value)); - buckets.record(value); - } - } - - @Override - protected void doRecordLong(long value) { - doRecordDouble((double) value); - } - - void downScale(int by) { - positiveBuckets.downscale(by); - negativeBuckets.downscale(by); - } - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramBuckets.java deleted file mode 100644 index 8c133129296..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramBuckets.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import io.opentelemetry.sdk.internal.PrimitiveLongList; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramBuckets; -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounter; -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounterFactory; -import java.util.Collections; -import java.util.List; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -/** - * This class handles the operations for recording, scaling, and exposing data related to the - * exponential histogram. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -final class DoubleExponentialHistogramBuckets implements ExponentialHistogramBuckets { - - private static final double LOG_BASE2_E = 1D / Math.log(2); - - private final ExponentialCounterFactory counterFactory; - private ExponentialCounter counts; - private int scale; - private double scaleFactor; - private long totalCount; - - DoubleExponentialHistogramBuckets( - int scale, int maxBuckets, ExponentialCounterFactory counterFactory) { - this.counterFactory = counterFactory; - this.counts = counterFactory.newCounter(maxBuckets); - this.scale = scale; - this.scaleFactor = computeScaleFactor(scale); - this.totalCount = 0; - } - - // For copying - DoubleExponentialHistogramBuckets(DoubleExponentialHistogramBuckets buckets) { - this.counterFactory = buckets.counterFactory; - this.counts = counterFactory.copy(buckets.counts); - this.scale = buckets.scale; - this.scaleFactor = buckets.scaleFactor; - this.totalCount = buckets.totalCount; - } - - /** Returns a copy of this bucket. */ - DoubleExponentialHistogramBuckets copy() { - return new DoubleExponentialHistogramBuckets(this); - } - - /** Resets all counters in this bucket set to zero, but preserves scale. */ - public void clear() { - this.totalCount = 0; - this.counts.clear(); - } - - boolean record(double value) { - if (value == 0.0) { - // Guarded by caller. If passed 0 it would be a bug in the SDK. - throw new IllegalStateException("Illegal attempted recording of zero at bucket level."); - } - int index = valueToIndex(value); - boolean recordingSuccessful = this.counts.increment(index, 1); - if (recordingSuccessful) { - totalCount++; - } - return recordingSuccessful; - } - - @Override - public int getOffset() { - // We need to unify the behavior of empty buckets. - // Unfortunately, getIndexStart is not meaningful for empty counters, so we default to - // returning 0 for offset and an empty list. - if (counts.isEmpty()) { - return 0; - } - return counts.getIndexStart(); - } - - @Nonnull - @Override - public List getBucketCounts() { - if (counts.isEmpty()) { - return Collections.emptyList(); - } - int length = counts.getIndexEnd() - counts.getIndexStart() + 1; - long[] countsArr = new long[length]; - for (int i = 0; i < length; i++) { - countsArr[i] = counts.get(i + counts.getIndexStart()); - } - return PrimitiveLongList.wrap(countsArr); - } - - @Override - public long getTotalCount() { - return totalCount; - } - - void downscale(int by) { - if (by == 0) { - return; - } else if (by < 0) { - // This should never happen without an SDK bug - throw new IllegalStateException("Cannot downscale by negative amount. Was given " + by + "."); - } - - if (!counts.isEmpty()) { - // We want to preserve other optimisations here as well, e.g. integer size. - // Instead of creating a new counter, we copy the existing one (for bucket size - // optimisations), and clear the values before writing the new ones. - ExponentialCounter newCounts = counterFactory.copy(counts); - newCounts.clear(); - - for (int i = counts.getIndexStart(); i <= counts.getIndexEnd(); i++) { - long count = counts.get(i); - if (count > 0) { - if (!newCounts.increment(i >> by, count)) { - // Theoretically won't happen unless there's an overflow on index - throw new IllegalStateException("Failed to create new downscaled buckets."); - } - } - } - this.counts = newCounts; - } - - this.scale = this.scale - by; - this.scaleFactor = computeScaleFactor(this.scale); - } - - /** - * Immutable method for merging. This method copies the first set of buckets, performs the merge - * on the copy, and returns the copy. - * - * @param a first buckets - * @param b second buckets - * @return A new set of buckets, the result - */ - static DoubleExponentialHistogramBuckets merge( - DoubleExponentialHistogramBuckets a, DoubleExponentialHistogramBuckets b) { - if (b.counts.isEmpty()) { - return a; - } else if (a.counts.isEmpty()) { - return b; - } - DoubleExponentialHistogramBuckets copy = a.copy(); - copy.mergeWith(b, /* additive= */ true); - return copy; - } - - /** - * This method merges this instance with another set of buckets. It alters the underlying bucket - * counts and scale of this instance only, so it is to be used with caution. For immutability, use - * the static merge() method. - * - *

      The bucket counts of this instance will be added to or subtracted from depending on the - * additive parameter. - * - *

      This algorithm for merging is adapted from NrSketch. - * - * @param other the histogram that will be merged into this one - * @param additive whether the bucket counts will be added or subtracted (diff vs merge). - */ - private void mergeWith(DoubleExponentialHistogramBuckets other, boolean additive) { - if (other.counts.isEmpty()) { - return; - } - - // Find the common scale, and the extended window required to merge the two bucket sets - int commonScale = Math.min(this.scale, other.scale); - - // Deltas are changes in scale - int deltaThis = this.scale - commonScale; - int deltaOther = other.scale - commonScale; - - long newWindowStart; - long newWindowEnd; - if (this.counts.isEmpty()) { - newWindowStart = other.getOffset() >> deltaOther; - newWindowEnd = other.counts.getIndexEnd() >> deltaOther; - } else { - newWindowStart = Math.min(this.getOffset() >> deltaThis, other.getOffset() >> deltaOther); - newWindowEnd = - Math.max( - (this.counts.getIndexEnd() >> deltaThis), (other.counts.getIndexEnd() >> deltaOther)); - } - - // downscale to fit new window - deltaThis += getScaleReduction(newWindowStart, newWindowEnd); - this.downscale(deltaThis); - - // since we changed scale of this, we need to know the new difference between the two scales - deltaOther = other.scale - this.scale; - - // do actual merging of other into this. Will decrement or increment depending on sign. - int sign = additive ? 1 : -1; - for (int i = other.getOffset(); i <= other.counts.getIndexEnd(); i++) { - if (!this.counts.increment(i >> deltaOther, sign * other.counts.get(i))) { - // This should never occur if scales and windows are calculated without bugs - throw new IllegalStateException("Failed to merge exponential histogram buckets."); - } - } - this.totalCount += sign * other.totalCount; - } - - int getScale() { - return scale; - } - - /** - * Returns the minimum scale reduction required to record the given value in these buckets, by - * calculating the new required window to allow the new value to be recorded. To be used with - * downScale(). - * - * @param value The proposed value to be recorded. - * @return The required scale reduction in order to fit the value in these buckets. - */ - int getScaleReduction(double value) { - long index = valueToIndex(value); - long newStart = Math.min(index, counts.getIndexStart()); - long newEnd = Math.max(index, counts.getIndexEnd()); - return getScaleReduction(newStart, newEnd); - } - - int getScaleReduction(long newStart, long newEnd) { - int scaleReduction = 0; - - while (newEnd - newStart + 1 > counts.getMaxSize()) { - newStart >>= 1; - newEnd >>= 1; - scaleReduction++; - } - return scaleReduction; - } - - private int getIndexByLogarithm(double value) { - return (int) Math.floor(Math.log(value) * scaleFactor); - } - - private int getIndexByExponent(double value) { - return Math.getExponent(value) >> -scale; - } - - private static double computeScaleFactor(int scale) { - return Math.scalb(LOG_BASE2_E, scale); - } - - /** - * Maps a recorded double value to a bucket index. - * - *

      The strategy to retrieve the index is specified in the OpenTelemetry specification: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#exponential-buckets - * - * @param value Measured value (must be non-zero). - * @return the index of the bucket which the value maps to. - */ - private int valueToIndex(double value) { - double absValue = Math.abs(value); - if (scale > 0) { - return getIndexByLogarithm(absValue); - } - return getIndexByExponent(absValue); - } - - @Override - public boolean equals(@Nullable Object obj) { - if (!(obj instanceof DoubleExponentialHistogramBuckets)) { - return false; - } - DoubleExponentialHistogramBuckets other = (DoubleExponentialHistogramBuckets) obj; - // Don't need to compare getTotalCount() because equivalent bucket counts - // imply equivalent overall count. - // Additionally, we compare the "semantics" of bucket counts, that is - // it's ok for getOffset() to diverge as long as the populated counts remain - // the same. This is because we don't "normalize" buckets after doing - // difference/subtraction operations. - return this.scale == other.scale && sameBucketCounts(other); - } - - /** - * Tests if two bucket counts are equivalent semantically. - * - *

      Semantic equivalence means: - * - *

        - *
      • All counts are stored between indexStart/indexEnd. - *
      • Offset does NOT need to be the same - *
      - */ - private boolean sameBucketCounts(DoubleExponentialHistogramBuckets other) { - if (this.totalCount != other.totalCount) { - return false; - } - int min = Math.min(this.counts.getIndexStart(), other.counts.getIndexStart()); - - // This check is so we avoid iterating from Integer.MIN_VALUE. - // In this case, we can assume that those buckets are empty. - // We start iterating from the other bucket index instead. - // They still may be equal as it is possible for another set of buckets - // to be empty but have a higher start index. - if (min == Integer.MIN_VALUE) { - min = Math.max(this.counts.getIndexStart(), other.counts.getIndexStart()); - } - - int max = Math.max(this.counts.getIndexEnd(), other.counts.getIndexEnd()); - for (int idx = min; idx <= max; idx++) { - if (this.counts.get(idx) != other.counts.get(idx)) { - return false; - } - } - return true; - } - - @Override - public int hashCode() { - int hash = 1; - hash *= 1000003; - // We need a new algorithm here that lines up w/ equals, so we only use non-zero counts. - for (int idx = this.counts.getIndexStart(); idx <= this.counts.getIndexEnd(); idx++) { - long count = this.counts.get(idx); - if (count != 0) { - hash ^= idx; - hash *= 1000003; - hash = (int) (hash ^ count); - hash *= 1000003; - } - } - hash ^= scale; - // Don't need to hash getTotalCount() because equivalent bucket - // counts imply equivalent overall count. - return hash; - } - - @Override - public String toString() { - return "DoubleExponentialHistogramBuckets{" - + "scale: " - + scale - + ", offset: " - + getOffset() - + ", counts: " - + counts - + " }"; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregator.java index f28109dc0dc..f0c16c7f4c4 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregator.java @@ -7,18 +7,20 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.MutableDoublePointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Supplier; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; @@ -34,28 +36,39 @@ * at any time. */ @ThreadSafe -public final class DoubleLastValueAggregator - implements Aggregator { - private final Supplier> reservoirSupplier; +public final class DoubleLastValueAggregator implements Aggregator { + private final ExemplarReservoirFactory reservoirFactory; + private final MemoryMode memoryMode; public DoubleLastValueAggregator( - Supplier> reservoirSupplier) { - this.reservoirSupplier = reservoirSupplier; + ExemplarReservoirFactory reservoirFactory, MemoryMode memoryMode) { + this.reservoirFactory = reservoirFactory; + this.memoryMode = memoryMode; } @Override - public AggregatorHandle createHandle() { - return new Handle(reservoirSupplier.get()); + public AggregatorHandle createHandle(long creationEpochNanos) { + return new Handle(creationEpochNanos, reservoirFactory, memoryMode); } @Override - public DoubleAccumulation merge(DoubleAccumulation previous, DoubleAccumulation current) { + public DoublePointData diff(DoublePointData previous, DoublePointData current) { return current; } @Override - public DoubleAccumulation diff(DoubleAccumulation previous, DoubleAccumulation current) { - return current; + public void diffInPlace(DoublePointData previousReusable, DoublePointData current) { + ((MutableDoublePointData) previousReusable).set(current); + } + + @Override + public DoublePointData createReusablePoint() { + return new MutableDoublePointData(); + } + + @Override + public void copyPoint(DoublePointData point, DoublePointData toReusablePoint) { + ((MutableDoublePointData) toReusablePoint).set(point); } @Override @@ -63,11 +76,8 @@ public MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, MetricDescriptor descriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpochNanos, - long epochNanos) { + Collection points, + AggregationTemporality temporality) { // Gauge does not need a start time, but we send one as advised by the data model // for identifying resets. return ImmutableMetricData.createDoubleGauge( @@ -76,31 +86,47 @@ public MetricData toMetricData( descriptor.getName(), descriptor.getDescription(), descriptor.getSourceInstrument().getUnit(), - ImmutableGaugeData.create( - MetricDataUtils.toDoublePointList( - accumulationByLabels, - (temporality == AggregationTemporality.CUMULATIVE) - ? startEpochNanos - : lastCollectionEpochNanos, - epochNanos))); + ImmutableGaugeData.create(points)); } - static final class Handle extends AggregatorHandle { - @Nullable private static final Double DEFAULT_VALUE = null; - private final AtomicReference current = new AtomicReference<>(DEFAULT_VALUE); + static final class Handle extends AggregatorHandle { + // AggregatorHandle#valuesRecorded records whether any values have been recorded so this field + // never needs to be reset on collect. Stale values are never observed. + private volatile double currentValue; + + // Only used when memoryMode is REUSABLE_DATA + @Nullable private final MutableDoublePointData reusablePoint; - private Handle(ExemplarReservoir reservoir) { - super(reservoir); + private Handle( + long creationEpochNanos, ExemplarReservoirFactory reservoirFactory, MemoryMode memoryMode) { + super(creationEpochNanos, reservoirFactory, /* isDoubleType= */ true); + if (memoryMode == MemoryMode.REUSABLE_DATA) { + reusablePoint = new MutableDoublePointData(); + } else { + reusablePoint = null; + } } @Override - protected DoubleAccumulation doAccumulateThenReset(List exemplars) { - return DoubleAccumulation.create(this.current.getAndSet(DEFAULT_VALUE), exemplars); + protected DoublePointData doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + double value = this.currentValue; + if (reusablePoint != null) { + reusablePoint.set(startEpochNanos, epochNanos, attributes, value, exemplars); + return reusablePoint; + } else { + return ImmutableDoublePointData.create( + startEpochNanos, epochNanos, attributes, value, exemplars); + } } @Override protected void doRecordDouble(double value) { - current.set(value); + this.currentValue = value; } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregator.java index 7fd5324d9fb..b22be360364 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregator.java @@ -6,22 +6,25 @@ package io.opentelemetry.sdk.metrics.internal.aggregator; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.concurrent.AdderUtil; import io.opentelemetry.sdk.metrics.internal.concurrent.DoubleAdder; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.metrics.internal.data.MutableDoublePointData; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.function.Supplier; +import javax.annotation.Nullable; /** * Sum aggregator that keeps values as {@code double}s. @@ -30,46 +33,61 @@ * at any time. */ public final class DoubleSumAggregator - extends AbstractSumAggregator { - private final Supplier> reservoirSupplier; + extends AbstractSumAggregator { + private final ExemplarReservoirFactory reservoirFactory; + private final MemoryMode memoryMode; /** * Constructs a sum aggregator. * * @param instrumentDescriptor The instrument being recorded, used to compute monotonicity. - * @param reservoirSupplier Supplier of exemplar reservoirs per-stream. + * @param reservoirFactory Supplier of exemplar reservoirs per-stream. + * @param memoryMode The memory mode to use. */ public DoubleSumAggregator( InstrumentDescriptor instrumentDescriptor, - Supplier> reservoirSupplier) { + ExemplarReservoirFactory reservoirFactory, + MemoryMode memoryMode) { super(instrumentDescriptor); - this.reservoirSupplier = reservoirSupplier; + this.reservoirFactory = reservoirFactory; + this.memoryMode = memoryMode; } @Override - public AggregatorHandle createHandle() { - return new Handle(reservoirSupplier.get()); + public AggregatorHandle createHandle(long creationEpochNanos) { + return new Handle(creationEpochNanos, reservoirFactory, memoryMode); } @Override - public DoubleAccumulation accumulateDoubleMeasurement( - double value, Attributes attributes, Context context) { - return DoubleAccumulation.create(value); + public DoublePointData diff(DoublePointData previousPoint, DoublePointData currentPoint) { + return ImmutableDoublePointData.create( + currentPoint.getStartEpochNanos(), + currentPoint.getEpochNanos(), + currentPoint.getAttributes(), + currentPoint.getValue() - previousPoint.getValue(), + currentPoint.getExemplars()); } @Override - public DoubleAccumulation merge( - DoubleAccumulation previousAccumulation, DoubleAccumulation accumulation) { - return DoubleAccumulation.create( - previousAccumulation.getValue() + accumulation.getValue(), accumulation.getExemplars()); + public void diffInPlace(DoublePointData previousReusablePoint, DoublePointData currentPoint) { + ((MutableDoublePointData) previousReusablePoint) + .set( + currentPoint.getStartEpochNanos(), + currentPoint.getEpochNanos(), + currentPoint.getAttributes(), + currentPoint.getValue() - previousReusablePoint.getValue(), + currentPoint.getExemplars()); } @Override - public DoubleAccumulation diff( - DoubleAccumulation previousAccumulation, DoubleAccumulation accumulation) { - return DoubleAccumulation.create( - accumulation.getValue() - previousAccumulation.getValue(), accumulation.getExemplars()); + public DoublePointData createReusablePoint() { + return new MutableDoublePointData(); + } + + @Override + public void copyPoint(DoublePointData point, DoublePointData toReusablePoint) { + ((MutableDoublePointData) toReusablePoint).set(point); } @Override @@ -77,38 +95,44 @@ public MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, MetricDescriptor descriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos) { + Collection points, + AggregationTemporality temporality) { return ImmutableMetricData.createDoubleSum( resource, instrumentationScopeInfo, descriptor.getName(), descriptor.getDescription(), descriptor.getSourceInstrument().getUnit(), - ImmutableSumData.create( - isMonotonic(), - temporality, - MetricDataUtils.toDoublePointList( - accumulationByLabels, - temporality == AggregationTemporality.CUMULATIVE - ? startEpochNanos - : lastCollectionEpoch, - epochNanos))); + ImmutableSumData.create(isMonotonic(), temporality, points)); } - static final class Handle extends AggregatorHandle { + static final class Handle extends AggregatorHandle { private final DoubleAdder current = AdderUtil.createDoubleAdder(); - Handle(ExemplarReservoir exemplarReservoir) { - super(exemplarReservoir); + // Only used if memoryMode == MemoryMode.REUSABLE_DATA + @Nullable private final MutableDoublePointData reusablePoint; + + Handle( + long creationEpochNanos, ExemplarReservoirFactory reservoirFactory, MemoryMode memoryMode) { + super(creationEpochNanos, reservoirFactory, /* isDoubleType= */ true); + reusablePoint = memoryMode == MemoryMode.REUSABLE_DATA ? new MutableDoublePointData() : null; } @Override - protected DoubleAccumulation doAccumulateThenReset(List exemplars) { - return DoubleAccumulation.create(this.current.sumThenReset(), exemplars); + protected DoublePointData doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + double value = reset ? this.current.sumThenReset() : this.current.sum(); + if (reusablePoint != null) { + reusablePoint.set(startEpochNanos, epochNanos, attributes, value, exemplars); + return reusablePoint; + } else { + return ImmutableDoublePointData.create( + startEpochNanos, epochNanos, attributes, value, exemplars); + } } @Override diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DropAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DropAggregator.java index 43d682ff4bb..21feaf80c26 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DropAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/DropAggregator.java @@ -9,12 +9,15 @@ import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; +import java.util.Collections; import java.util.List; -import java.util.Map; /** * A "null object" Aggregator which denotes no aggregation should occur. @@ -22,48 +25,71 @@ *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ -public final class DropAggregator implements Aggregator { +public final class DropAggregator implements Aggregator { - private static final Object ACCUMULATION = new Object(); + private static final PointData POINT_DATA = + new PointData() { + @Override + public long getStartEpochNanos() { + return 0; + } - public static final Aggregator INSTANCE = new DropAggregator(); + @Override + public long getEpochNanos() { + return 0; + } - private static final AggregatorHandle HANDLE = - new AggregatorHandle(ExemplarReservoir.doubleNoSamples()) { @Override - protected void doRecordLong(long value) {} + public Attributes getAttributes() { + return Attributes.empty(); + } @Override - protected void doRecordDouble(double value) {} + public List getExemplars() { + return Collections.emptyList(); + } + }; + + public static final Aggregator INSTANCE = new DropAggregator(); + // creationEpochNanos is 0 because DropAggregator never produces data points, so + // the start timestamp is irrelevant. A single shared HANDLE is safe to use. + private static final AggregatorHandle HANDLE = + new AggregatorHandle( + /* creationEpochNanos= */ 0, + ExemplarReservoirFactory.noSamples(), + /* isDoubleType= */ true) { @Override - protected Object doAccumulateThenReset(List exemplars) { - return ACCUMULATION; + protected PointData doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + return POINT_DATA; } + + @Override + protected void doRecordLong(long value) {} + + @Override + protected void doRecordDouble(double value) {} }; private DropAggregator() {} @Override - public AggregatorHandle createHandle() { + public AggregatorHandle createHandle(long creationEpochNanos) { return HANDLE; } - @Override - public Object merge(Object previousAccumulation, Object accumulation) { - return ACCUMULATION; - } - @Override public MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, - MetricDescriptor descriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos) { + MetricDescriptor metricDescriptor, + Collection points, + AggregationTemporality temporality) { return EmptyMetricData.getInstance(); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramAccumulation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramAccumulation.java deleted file mode 100644 index 204582b9d33..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramAccumulation.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import java.util.Collections; -import java.util.List; -import javax.annotation.concurrent.Immutable; - -@Immutable -@AutoValue -abstract class ExplicitBucketHistogramAccumulation { - /** - * Creates a new {@link ExplicitBucketHistogramAccumulation} with the given values. Assume - * `counts` is read-only so we don't need a defensive-copy here. - * - * @return a new {@link ExplicitBucketHistogramAccumulation} with the given values. - */ - static ExplicitBucketHistogramAccumulation create( - double sum, boolean hasMinMax, double min, double max, long[] counts) { - return create(sum, hasMinMax, min, max, counts, Collections.emptyList()); - } - - static ExplicitBucketHistogramAccumulation create( - double sum, - boolean hasMinMax, - double min, - double max, - long[] counts, - List exemplars) { - return new AutoValue_ExplicitBucketHistogramAccumulation( - sum, hasMinMax, min, max, counts, exemplars); - } - - ExplicitBucketHistogramAccumulation() {} - - /** - * The sum of all measurements recorded. - * - * @return the sum of recorded measurements. - */ - abstract double getSum(); - - /** Return {@code true} if {@link #getMin()} and {@link #getMax()} is set. */ - abstract boolean hasMinMax(); - - /** - * The min of all measurements recorded, if {@link #hasMinMax()} is {@code true}. If {@link - * #hasMinMax()} is {@code false}, the response should be ignored. - */ - abstract double getMin(); - - /** - * The max of all measurements recorded, if {@link #hasMinMax()} is {@code true}. If {@link - * #hasMinMax()} is {@code false}, the response should be ignored. - */ - abstract double getMax(); - - /** - * The counts in each bucket. The returned type is a mutable object, but it should be fine because - * the class is only used internally. - * - * @return the counts in each bucket. do not mutate the returned object. - */ - @SuppressWarnings("mutable") - abstract long[] getCounts(); - - /** Exemplars accumulated during this period. */ - abstract List getExemplars(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramUtils.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramUtils.java index c0e0123f054..4d25b873f5a 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramUtils.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExplicitBucketHistogramUtils.java @@ -21,12 +21,13 @@ private ExplicitBucketHistogramUtils() {} public static final List DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES = Collections.unmodifiableList( Arrays.asList( - 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, 2_500d, 5_000d, 7_500d, + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, 2_500d, 5_000d, 7_500d, 10_000d)); /** Converts bucket boundary "convenient" configuration into the "more efficient" array. */ public static double[] createBoundaryArray(List boundaries) { - return validateBucketBoundaries(boundaries.stream().mapToDouble(i -> i).toArray()); + validateBucketBoundaries(boundaries); + return boundaries.stream().mapToDouble(i -> i).toArray(); } /** @@ -51,32 +52,30 @@ public static int findBucketIndex(double[] boundaries, double value) { * Validates errors in boundary configuration. * * @param boundaries The array of bucket boundaries. - * @return The original boundaries. * @throws IllegalArgumentException if boundaries are not specified correctly. */ - public static double[] validateBucketBoundaries(double[] boundaries) { + public static void validateBucketBoundaries(List boundaries) { for (double v : boundaries) { if (Double.isNaN(v)) { throw new IllegalArgumentException("invalid bucket boundary: NaN"); } } - for (int i = 1; i < boundaries.length; ++i) { - if (boundaries[i - 1] >= boundaries[i]) { + for (int i = 1; i < boundaries.size(); ++i) { + if (boundaries.get(i - 1) >= boundaries.get(i)) { throw new IllegalArgumentException( "Bucket boundaries must be in increasing order: " - + boundaries[i - 1] + + boundaries.get(i - 1) + " >= " - + boundaries[i]); + + boundaries.get(i)); } } - if (boundaries.length > 0) { - if (boundaries[0] == Double.NEGATIVE_INFINITY) { + if (!boundaries.isEmpty()) { + if (boundaries.get(0) == Double.NEGATIVE_INFINITY) { throw new IllegalArgumentException("invalid bucket boundary: -Inf"); } - if (boundaries[boundaries.length - 1] == Double.POSITIVE_INFINITY) { + if (boundaries.get(boundaries.size() - 1) == Double.POSITIVE_INFINITY) { throw new IllegalArgumentException("invalid bucket boundary: +Inf"); } } - return boundaries; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialBucketStrategy.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialBucketStrategy.java deleted file mode 100644 index 9af45e99155..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialBucketStrategy.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounterFactory; - -/** The configuration for how to create exponential histogram buckets. */ -final class ExponentialBucketStrategy { - /** Starting scale of exponential buckets. */ - private final int scale; - /** The maximum number of buckets that will be used for positive or negative recordings. */ - private final int maxBuckets; - /** The mechanism of constructing and copying buckets. */ - private final ExponentialCounterFactory counterFactory; - - private ExponentialBucketStrategy( - int scale, int maxBuckets, ExponentialCounterFactory counterFactory) { - this.scale = scale; - this.maxBuckets = maxBuckets; - this.counterFactory = counterFactory; - } - - /** Constructs fresh new buckets with default settings. */ - DoubleExponentialHistogramBuckets newBuckets() { - return new DoubleExponentialHistogramBuckets(scale, maxBuckets, counterFactory); - } - - /** Create a new strategy for generating Exponential Buckets. */ - static ExponentialBucketStrategy newStrategy( - int scale, int maxBuckets, ExponentialCounterFactory counterFactory) { - return new ExponentialBucketStrategy(scale, maxBuckets, counterFactory); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialHistogramAccumulation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialHistogramAccumulation.java deleted file mode 100644 index 49892ebc111..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/ExponentialHistogramAccumulation.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import java.util.List; - -@AutoValue -abstract class ExponentialHistogramAccumulation { - ExponentialHistogramAccumulation() {} - - /** Creates a new {@link ExponentialHistogramAccumulation} with the given values. */ - static ExponentialHistogramAccumulation create( - int scale, - double sum, - boolean hasMinMax, - double min, - double max, - DoubleExponentialHistogramBuckets positiveBuckets, - DoubleExponentialHistogramBuckets negativeBuckets, - long zeroCount, - List exemplars) { - return new AutoValue_ExponentialHistogramAccumulation( - scale, sum, hasMinMax, min, max, positiveBuckets, negativeBuckets, zeroCount, exemplars); - } - - abstract int getScale(); - - abstract double getSum(); - - abstract boolean hasMinMax(); - - abstract double getMin(); - - abstract double getMax(); - - abstract DoubleExponentialHistogramBuckets getPositiveBuckets(); - - abstract DoubleExponentialHistogramBuckets getNegativeBuckets(); - - abstract long getZeroCount(); - - abstract List getExemplars(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongAccumulation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongAccumulation.java deleted file mode 100644 index e08fc99de3c..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongAccumulation.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; -import java.util.Collections; -import java.util.List; -import javax.annotation.concurrent.Immutable; - -/** An accumulation representing {@code long} values and exemplars. */ -@Immutable -@AutoValue -abstract class LongAccumulation { - - static LongAccumulation create(long value, List exemplars) { - return new AutoValue_LongAccumulation(value, exemplars); - } - - static LongAccumulation create(long value) { - return create(value, Collections.emptyList()); - } - - LongAccumulation() {} - - /** The current value. */ - abstract long getValue(); - - /** Sampled measurements recorded during this accumulation. */ - abstract List getExemplars(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregator.java index e9c780975a5..56f42ffbb7e 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregator.java @@ -7,18 +7,20 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.MutableLongPointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.Supplier; import javax.annotation.Nullable; /** @@ -32,27 +34,38 @@ *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ -public final class LongLastValueAggregator - implements Aggregator { - private final Supplier> reservoirSupplier; +public final class LongLastValueAggregator implements Aggregator { + private final ExemplarReservoirFactory reservoirFactory; + private final MemoryMode memoryMode; - public LongLastValueAggregator(Supplier> reservoirSupplier) { - this.reservoirSupplier = reservoirSupplier; + public LongLastValueAggregator(ExemplarReservoirFactory reservoirFactory, MemoryMode memoryMode) { + this.reservoirFactory = reservoirFactory; + this.memoryMode = memoryMode; } @Override - public AggregatorHandle createHandle() { - return new Handle(reservoirSupplier.get()); + public AggregatorHandle createHandle(long creationEpochNanos) { + return new Handle(creationEpochNanos, reservoirFactory, memoryMode); } @Override - public LongAccumulation merge(LongAccumulation previous, LongAccumulation current) { + public LongPointData diff(LongPointData previous, LongPointData current) { return current; } @Override - public LongAccumulation diff(LongAccumulation previous, LongAccumulation current) { - return current; + public void diffInPlace(LongPointData previousReusablePoint, LongPointData currentPoint) { + ((MutableLongPointData) previousReusablePoint).set(currentPoint); + } + + @Override + public LongPointData createReusablePoint() { + return new MutableLongPointData(); + } + + @Override + public void copyPoint(LongPointData point, LongPointData toReusablePoint) { + ((MutableLongPointData) toReusablePoint).set(point); } @Override @@ -60,11 +73,8 @@ public MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, MetricDescriptor descriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos) { + Collection points, + AggregationTemporality temporality) { // Last-Value ignores temporality generally, but we can set a start time on the gauge. return ImmutableMetricData.createLongGauge( resource, @@ -72,31 +82,47 @@ public MetricData toMetricData( descriptor.getName(), descriptor.getDescription(), descriptor.getSourceInstrument().getUnit(), - ImmutableGaugeData.create( - MetricDataUtils.toLongPointList( - accumulationByLabels, - (temporality == AggregationTemporality.CUMULATIVE) - ? startEpochNanos - : lastCollectionEpoch, - epochNanos))); + ImmutableGaugeData.create(points)); } - static final class Handle extends AggregatorHandle { - @Nullable private static final Long DEFAULT_VALUE = null; - private final AtomicReference current = new AtomicReference<>(DEFAULT_VALUE); + static final class Handle extends AggregatorHandle { + // AggregatorHandle#valuesRecorded records whether any values have been recorded so this field + // never needs to be reset on collect. Stale values are never observed. + private volatile long currentValue; + + // Only used when memoryMode is REUSABLE_DATA + @Nullable private final MutableLongPointData reusablePoint; - Handle(ExemplarReservoir exemplarReservoir) { - super(exemplarReservoir); + Handle( + long creationEpochNanos, ExemplarReservoirFactory reservoirFactory, MemoryMode memoryMode) { + super(creationEpochNanos, reservoirFactory, /* isDoubleType= */ false); + if (memoryMode == MemoryMode.REUSABLE_DATA) { + reusablePoint = new MutableLongPointData(); + } else { + reusablePoint = null; + } } @Override - protected LongAccumulation doAccumulateThenReset(List exemplars) { - return LongAccumulation.create(this.current.getAndSet(DEFAULT_VALUE), exemplars); + protected LongPointData doAggregateThenMaybeResetLongs( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + long value = this.currentValue; + if (reusablePoint != null) { + reusablePoint.set(startEpochNanos, epochNanos, attributes, value, exemplars); + return reusablePoint; + } else { + return ImmutableLongPointData.create( + startEpochNanos, epochNanos, attributes, value, exemplars); + } } @Override protected void doRecordLong(long value) { - current.set(value); + this.currentValue = value; } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregator.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregator.java index be1b9fad499..b2e44e6bef2 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregator.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregator.java @@ -7,20 +7,24 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.concurrent.AdderUtil; import io.opentelemetry.sdk.metrics.internal.concurrent.LongAdder; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.metrics.internal.data.MutableLongPointData; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; +import java.util.Collection; import java.util.List; -import java.util.Map; -import java.util.function.Supplier; +import javax.annotation.Nullable; /** * Sum aggregator that keeps values as {@code long}s. @@ -29,34 +33,54 @@ * at any time. */ public final class LongSumAggregator - extends AbstractSumAggregator { + extends AbstractSumAggregator { - private final Supplier> reservoirSupplier; + private final ExemplarReservoirFactory reservoirFactory; + private final MemoryMode memoryMode; public LongSumAggregator( InstrumentDescriptor instrumentDescriptor, - Supplier> reservoirSupplier) { + ExemplarReservoirFactory reservoirFactory, + MemoryMode memoryMode) { super(instrumentDescriptor); - this.reservoirSupplier = reservoirSupplier; + this.reservoirFactory = reservoirFactory; + this.memoryMode = memoryMode; } @Override - public AggregatorHandle createHandle() { - return new Handle(reservoirSupplier.get()); + public AggregatorHandle createHandle(long creationEpochNanos) { + return new Handle(creationEpochNanos, reservoirFactory, memoryMode); } @Override - public LongAccumulation merge( - LongAccumulation previousAccumulation, LongAccumulation accumulation) { - return LongAccumulation.create( - previousAccumulation.getValue() + accumulation.getValue(), accumulation.getExemplars()); + public LongPointData diff(LongPointData previousPoint, LongPointData currentPoint) { + return ImmutableLongPointData.create( + currentPoint.getStartEpochNanos(), + currentPoint.getEpochNanos(), + currentPoint.getAttributes(), + currentPoint.getValue() - previousPoint.getValue(), + currentPoint.getExemplars()); } @Override - public LongAccumulation diff( - LongAccumulation previousAccumulation, LongAccumulation accumulation) { - return LongAccumulation.create( - accumulation.getValue() - previousAccumulation.getValue(), accumulation.getExemplars()); + public void diffInPlace(LongPointData previousReusablePoint, LongPointData currentPoint) { + ((MutableLongPointData) previousReusablePoint) + .set( + currentPoint.getStartEpochNanos(), + currentPoint.getEpochNanos(), + currentPoint.getAttributes(), + currentPoint.getValue() - previousReusablePoint.getValue(), + currentPoint.getExemplars()); + } + + @Override + public LongPointData createReusablePoint() { + return new MutableLongPointData(); + } + + @Override + public void copyPoint(LongPointData point, LongPointData toReusablePoint) { + ((MutableLongPointData) toReusablePoint).set(point); } @Override @@ -64,42 +88,49 @@ public MetricData toMetricData( Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, MetricDescriptor descriptor, - Map accumulationByLabels, - AggregationTemporality temporality, - long startEpochNanos, - long lastCollectionEpoch, - long epochNanos) { + Collection points, + AggregationTemporality temporality) { return ImmutableMetricData.createLongSum( resource, instrumentationScopeInfo, descriptor.getName(), descriptor.getDescription(), descriptor.getSourceInstrument().getUnit(), - ImmutableSumData.create( - isMonotonic(), - temporality, - MetricDataUtils.toLongPointList( - accumulationByLabels, - temporality == AggregationTemporality.CUMULATIVE - ? startEpochNanos - : lastCollectionEpoch, - epochNanos))); + ImmutableSumData.create(isMonotonic(), temporality, points)); } - static final class Handle extends AggregatorHandle { + static final class Handle extends AggregatorHandle { private final LongAdder current = AdderUtil.createLongAdder(); - Handle(ExemplarReservoir exemplarReservoir) { - super(exemplarReservoir); + // Only used if memoryMode == MemoryMode.REUSABLE_DATA + @Nullable private final MutableLongPointData reusablePointData; + + Handle( + long creationEpochNanos, ExemplarReservoirFactory reservoirFactory, MemoryMode memoryMode) { + super(creationEpochNanos, reservoirFactory, /* isDoubleType= */ false); + reusablePointData = + memoryMode == MemoryMode.REUSABLE_DATA ? new MutableLongPointData() : null; } @Override - protected LongAccumulation doAccumulateThenReset(List exemplars) { - return LongAccumulation.create(this.current.sumThenReset(), exemplars); + protected LongPointData doAggregateThenMaybeResetLongs( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + long value = reset ? this.current.sumThenReset() : this.current.sum(); + if (reusablePointData != null) { + reusablePointData.set(startEpochNanos, epochNanos, attributes, value, exemplars); + return reusablePointData; + } else { + return ImmutableLongPointData.create( + startEpochNanos, epochNanos, attributes, value, exemplars); + } } @Override - public void doRecordLong(long value) { + protected void doRecordLong(long value) { current.add(value); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/MetricDataUtils.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/MetricDataUtils.java deleted file mode 100644 index 39968fc7b24..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/aggregator/MetricDataUtils.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.internal.PrimitiveLongList; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.DoublePointData; -import io.opentelemetry.sdk.metrics.data.HistogramPointData; -import io.opentelemetry.sdk.metrics.data.LongPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramPointData; -import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -final class MetricDataUtils { - private MetricDataUtils() {} - - /** Returns true if the instrument does not allow negative measurements. */ - static boolean isMonotonicInstrument(InstrumentDescriptor descriptor) { - InstrumentType type = descriptor.getType(); - return type == InstrumentType.HISTOGRAM - || type == InstrumentType.COUNTER - || type == InstrumentType.OBSERVABLE_COUNTER; - } - - static List toLongPointList( - Map accumulationMap, long startEpochNanos, long epochNanos) { - List points = new ArrayList<>(accumulationMap.size()); - accumulationMap.forEach( - (labels, accumulation) -> - points.add( - ImmutableLongPointData.create( - startEpochNanos, - epochNanos, - labels, - accumulation.getValue(), - accumulation.getExemplars()))); - return points; - } - - static List toDoublePointList( - Map accumulationMap, long startEpochNanos, long epochNanos) { - List points = new ArrayList<>(accumulationMap.size()); - accumulationMap.forEach( - (labels, accumulation) -> - points.add( - ImmutableDoublePointData.create( - startEpochNanos, - epochNanos, - labels, - accumulation.getValue(), - accumulation.getExemplars()))); - return points; - } - - static List toExplicitBucketHistogramPointList( - Map accumulationMap, - long startEpochNanos, - long epochNanos, - List boundaries) { - List points = new ArrayList<>(accumulationMap.size()); - accumulationMap.forEach( - (labels, aggregator) -> { - List counts = PrimitiveLongList.wrap(aggregator.getCounts().clone()); - points.add( - ImmutableHistogramPointData.create( - startEpochNanos, - epochNanos, - labels, - aggregator.getSum(), - aggregator.getMin(), - aggregator.getMax(), - boundaries, - counts, - aggregator.getExemplars())); - }); - return points; - } - - static List toExponentialHistogramPointList( - Map accumulationMap, - long startEpochNanos, - long epochNanos) { - List points = new ArrayList<>(accumulationMap.size()); - accumulationMap.forEach( - (attributes, aggregator) -> - points.add( - ExponentialHistogramPointData.create( - aggregator.getScale(), - aggregator.getSum(), - aggregator.getZeroCount(), - aggregator.getMin(), - aggregator.getMax(), - aggregator.getPositiveBuckets(), - aggregator.getNegativeBuckets(), - startEpochNanos, - epochNanos, - attributes, - aggregator.getExemplars()))); - return points; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/EmptyExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/EmptyExponentialHistogramBuckets.java new file mode 100644 index 00000000000..76d4fa4f2fc --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/EmptyExponentialHistogramBuckets.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import java.util.Collections; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * An empty {@link ExponentialHistogramBuckets}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@AutoValue +public abstract class EmptyExponentialHistogramBuckets implements ExponentialHistogramBuckets { + + private static final Map ZERO_BUCKETS = + new ConcurrentHashMap<>(); + + EmptyExponentialHistogramBuckets() {} + + public static ExponentialHistogramBuckets get(int scale) { + return ZERO_BUCKETS.computeIfAbsent( + scale, + scale1 -> + new AutoValue_EmptyExponentialHistogramBuckets(scale1, 0, Collections.emptyList(), 0)); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/HistogramPointDataValidations.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/HistogramPointDataValidations.java new file mode 100644 index 00000000000..02534dd138f --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/HistogramPointDataValidations.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import java.util.List; + +/** + * Validations for {@link HistogramPointData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +final class HistogramPointDataValidations { + + private HistogramPointDataValidations() {} + + static void validateIsStrictlyIncreasing(List xs) { + for (int i = 0; i < xs.size() - 1; i++) { + if (xs.get(i).compareTo(xs.get(i + 1)) >= 0) { + throw new IllegalArgumentException("invalid boundaries: " + xs); + } + } + } + + static void validateFiniteBoundaries(List boundaries) { + if (!boundaries.isEmpty() + && (boundaries.get(0).isInfinite() || boundaries.get(boundaries.size() - 1).isInfinite())) { + throw new IllegalArgumentException("invalid boundaries: contains explicit +/-Inf"); + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramBuckets.java new file mode 100644 index 00000000000..8006e4f3f0a --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramBuckets.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link ExponentialHistogramBuckets}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@AutoValue +@Immutable +public abstract class ImmutableExponentialHistogramBuckets implements ExponentialHistogramBuckets { + + ImmutableExponentialHistogramBuckets() {} + + /** + * Create a ExponentialHistogramBuckets. + * + * @return a ExponentialHistogramBuckets. + */ + @SuppressWarnings("TooManyParameters") + public static ExponentialHistogramBuckets create(int scale, int offset, List bucketCounts) { + return new AutoValue_ImmutableExponentialHistogramBuckets( + scale, offset, bucketCounts, bucketCounts.stream().mapToLong(l -> l).sum()); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramData.java new file mode 100644 index 00000000000..6690c207dc5 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramData.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import java.util.Collection; +import java.util.Collections; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link ExponentialHistogramData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +public abstract class ImmutableExponentialHistogramData implements ExponentialHistogramData { + + private static final ExponentialHistogramData EMPTY = + create(AggregationTemporality.CUMULATIVE, Collections.emptyList()); + + public static ExponentialHistogramData empty() { + return EMPTY; + } + + /** Returns a new {@link ExponentialHistogramData}. */ + public static ExponentialHistogramData create( + AggregationTemporality temporality, Collection points) { + return new AutoValue_ImmutableExponentialHistogramData(temporality, points); + } + + ImmutableExponentialHistogramData() {} +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramPointData.java new file mode 100644 index 00000000000..4d9ac87adcc --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableExponentialHistogramPointData.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link ExponentialHistogramPointData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@AutoValue +@Immutable +public abstract class ImmutableExponentialHistogramPointData + implements ExponentialHistogramPointData { + + ImmutableExponentialHistogramPointData() {} + + /** + * Create a DoubleExponentialHistogramPointData. + * + * @return a DoubleExponentialHistogramPointData. + */ + @SuppressWarnings("TooManyParameters") + public static ExponentialHistogramPointData create( + int scale, + double sum, + long zeroCount, + boolean hasMin, + double min, + boolean hasMax, + double max, + ExponentialHistogramBuckets positiveBuckets, + ExponentialHistogramBuckets negativeBuckets, + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars) { + + long count = zeroCount + positiveBuckets.getTotalCount() + negativeBuckets.getTotalCount(); + + return new AutoValue_ImmutableExponentialHistogramPointData( + startEpochNanos, + epochNanos, + attributes, + scale, + sum, + count, + zeroCount, + hasMin, + min, + hasMax, + max, + positiveBuckets, + negativeBuckets, + exemplars); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramData.java index 20a7dc2a848..952371d4ef7 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramData.java @@ -17,7 +17,7 @@ * A histogram metric point. * *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#histogram + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md#histogram * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramPointData.java index 7611059cd5a..06699d78645 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramPointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableHistogramPointData.java @@ -5,15 +5,17 @@ package io.opentelemetry.sdk.metrics.internal.data; +import static io.opentelemetry.sdk.metrics.internal.data.HistogramPointDataValidations.validateFiniteBoundaries; +import static io.opentelemetry.sdk.metrics.internal.data.HistogramPointDataValidations.validateIsStrictlyIncreasing; + import com.google.auto.value.AutoValue; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.internal.PrimitiveLongList; +import io.opentelemetry.sdk.common.internal.PrimitiveLongList; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.HistogramPointData; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** @@ -33,13 +35,16 @@ public abstract class ImmutableHistogramPointData implements HistogramPointData * @return a HistogramPointData. * @throws IllegalArgumentException if the given boundaries/counts were invalid */ + @SuppressWarnings("TooManyParameters") public static ImmutableHistogramPointData create( long startEpochNanos, long epochNanos, Attributes attributes, double sum, - @Nullable Double min, - @Nullable Double max, + boolean hasMin, + double min, + boolean hasMax, + double max, List boundaries, List counts) { return create( @@ -47,7 +52,9 @@ public static ImmutableHistogramPointData create( epochNanos, attributes, sum, + hasMin, min, + hasMax, max, boundaries, counts, @@ -61,13 +68,16 @@ public static ImmutableHistogramPointData create( * @return a HistogramPointData. * @throws IllegalArgumentException if the given boundaries/counts were invalid */ + @SuppressWarnings("TooManyParameters") public static ImmutableHistogramPointData create( long startEpochNanos, long epochNanos, Attributes attributes, double sum, - @Nullable Double min, - @Nullable Double max, + boolean hasMin, + double min, + boolean hasMax, + double max, List boundaries, List counts, List exemplars) { @@ -78,13 +88,8 @@ public static ImmutableHistogramPointData create( + " instead of " + counts.size()); } - if (!isStrictlyIncreasing(boundaries)) { - throw new IllegalArgumentException("invalid boundaries: " + boundaries); - } - if (!boundaries.isEmpty() - && (boundaries.get(0).isInfinite() || boundaries.get(boundaries.size() - 1).isInfinite())) { - throw new IllegalArgumentException("invalid boundaries: contains explicit +/-Inf"); - } + validateIsStrictlyIncreasing(boundaries); + validateFiniteBoundaries(boundaries); long totalCount = 0; for (long c : PrimitiveLongList.toArray(counts)) { @@ -96,23 +101,14 @@ public static ImmutableHistogramPointData create( attributes, sum, totalCount, - min != null, - min != null ? min : -1, - max != null, - max != null ? max : -1, + hasMin, + min, + hasMax, + max, Collections.unmodifiableList(new ArrayList<>(boundaries)), Collections.unmodifiableList(new ArrayList<>(counts)), exemplars); } ImmutableHistogramPointData() {} - - private static boolean isStrictlyIncreasing(List xs) { - for (int i = 0; i < xs.size() - 1; i++) { - if (xs.get(i).compareTo(xs.get(i + 1)) >= 0) { - return false; - } - } - return true; - } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableMetricData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableMetricData.java index 070673180ce..037aba8867e 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableMetricData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableMetricData.java @@ -9,6 +9,7 @@ import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.data.Data; import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; import io.opentelemetry.sdk.metrics.data.GaugeData; import io.opentelemetry.sdk.metrics.data.HistogramData; import io.opentelemetry.sdk.metrics.data.LongPointData; @@ -16,7 +17,6 @@ import io.opentelemetry.sdk.metrics.data.MetricDataType; import io.opentelemetry.sdk.metrics.data.SumData; import io.opentelemetry.sdk.metrics.data.SummaryData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; import io.opentelemetry.sdk.resources.Resource; import javax.annotation.concurrent.Immutable; diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryData.java index 7f145269341..bf5cc390727 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryData.java @@ -16,7 +16,7 @@ * A summary metric point. * *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#summary + * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md#summary * *

      Note: This is called "DoubleSummary" to reflect which primitives are used to record it, * however "Summary" is the equivalent OTLP type. @@ -25,7 +25,7 @@ * instruments. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time + * at any time. */ @Immutable @AutoValue diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryPointData.java index 447ad45963d..54597c1acb9 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryPointData.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableSummaryPointData.java @@ -17,7 +17,7 @@ * A single data point that summarizes the values in a time series of numeric values. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time + * at any time. */ @Immutable @AutoValue diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableValueAtQuantile.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableValueAtQuantile.java index 01995b28aa4..d8f31391cb8 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableValueAtQuantile.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/ImmutableValueAtQuantile.java @@ -13,7 +13,7 @@ * A summary metric value. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time + * at any time. */ @Immutable @AutoValue diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableDoublePointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableDoublePointData.java new file mode 100644 index 00000000000..80063956445 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableDoublePointData.java @@ -0,0 +1,138 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** + * A mutable {@link DoublePointData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public class MutableDoublePointData implements DoublePointData { + + private long startEpochNanos; + private long epochNanos; + + private Attributes attributes = Attributes.empty(); + + private double value; + private List exemplars = Collections.emptyList(); + + @Override + public double getValue() { + return value; + } + + @Override + public long getStartEpochNanos() { + return startEpochNanos; + } + + @Override + public long getEpochNanos() { + return epochNanos; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public List getExemplars() { + return exemplars; + } + + /** + * Sets all {@link MutableDoublePointData} values based on {@code point}. + * + * @param point The point to take the values from + */ + public void set(DoublePointData point) { + set( + point.getStartEpochNanos(), + point.getEpochNanos(), + point.getAttributes(), + point.getValue(), + point.getExemplars()); + } + + /** Sets all {@link MutableDoublePointData} values , besides exemplars which are set to empty. */ + public void set(long startEpochNanos, long epochNanos, Attributes attributes, double value) { + set(startEpochNanos, epochNanos, attributes, value, Collections.emptyList()); + } + + /** Sets all {@link MutableDoublePointData} values. */ + public void set( + long startEpochNanos, + long epochNanos, + Attributes attributes, + double value, + List exemplars) { + this.startEpochNanos = startEpochNanos; + this.epochNanos = epochNanos; + this.attributes = attributes; + this.value = value; + this.exemplars = exemplars; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof DoublePointData)) { + return false; + } + DoublePointData pointData = (DoublePointData) o; + return startEpochNanos == pointData.getStartEpochNanos() + && epochNanos == pointData.getEpochNanos() + && Double.doubleToLongBits(value) == Double.doubleToLongBits(pointData.getValue()) + && Objects.equals(attributes, pointData.getAttributes()) + && Objects.equals(exemplars, pointData.getExemplars()); + } + + @Override + public int hashCode() { + int hashcode = 1; + hashcode *= 1000003; + hashcode ^= (int) ((startEpochNanos >>> 32) ^ startEpochNanos); + hashcode *= 1000003; + hashcode ^= (int) ((epochNanos >>> 32) ^ epochNanos); + hashcode *= 1000003; + hashcode ^= attributes.hashCode(); + hashcode *= 1000003; + hashcode ^= (int) ((Double.doubleToLongBits(value) >>> 32) ^ Double.doubleToLongBits(value)); + hashcode *= 1000003; + hashcode ^= exemplars.hashCode(); + return hashcode; + } + + @Override + public String toString() { + return "MutableDoublePointData{" + + "startEpochNanos=" + + startEpochNanos + + ", epochNanos=" + + epochNanos + + ", attributes=" + + attributes + + ", value=" + + value + + ", exemplars=" + + exemplars + + '}'; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramBuckets.java new file mode 100644 index 00000000000..31f066d7766 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramBuckets.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import java.util.List; +import java.util.Objects; + +/** + * A mutable {@link ExponentialHistogramBuckets}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public final class MutableExponentialHistogramBuckets implements ExponentialHistogramBuckets { + + private int scale; + private int offset; + private long totalCount; + private DynamicPrimitiveLongList bucketCounts = DynamicPrimitiveLongList.empty(); + + @Override + public int getScale() { + return scale; + } + + @Override + public int getOffset() { + return offset; + } + + @Override + public List getBucketCounts() { + return bucketCounts; + } + + public DynamicPrimitiveLongList getReusableBucketCountsList() { + return bucketCounts; + } + + @Override + public long getTotalCount() { + return totalCount; + } + + public MutableExponentialHistogramBuckets set( + int scale, int offset, long totalCount, DynamicPrimitiveLongList bucketCounts) { + this.scale = scale; + this.offset = offset; + this.totalCount = totalCount; + this.bucketCounts = bucketCounts; + + return this; + } + + @Override + public String toString() { + return "MutableExponentialHistogramBuckets{" + + "scale=" + + scale + + ", " + + "offset=" + + offset + + ", " + + "bucketCounts=" + + bucketCounts + + ", " + + "totalCount=" + + totalCount + + "}"; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o instanceof ExponentialHistogramBuckets) { + ExponentialHistogramBuckets that = (ExponentialHistogramBuckets) o; + return this.scale == that.getScale() + && this.offset == that.getOffset() + && this.totalCount == that.getTotalCount() + && Objects.equals(this.bucketCounts, that.getBucketCounts()); + } + return false; + } + + @Override + public int hashCode() { + int result = scale; + result = 31 * result + offset; + result = 31 * result + (int) (totalCount ^ (totalCount >>> 32)); + result = 31 * result + (bucketCounts != null ? bucketCounts.hashCode() : 0); + return result; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramPointData.java new file mode 100644 index 00000000000..6cdd209dfdd --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramPointData.java @@ -0,0 +1,248 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import java.util.Collections; +import java.util.List; + +/** + * A mutable {@link ExponentialHistogramPointData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public final class MutableExponentialHistogramPointData implements ExponentialHistogramPointData { + + private long startEpochNanos; + private long epochNanos; + private Attributes attributes = Attributes.empty(); + private int scale; + private double sum; + private long count; + private long zeroCount; + private boolean hasMin; + private double min; + private boolean hasMax; + private double max; + private ExponentialHistogramBuckets positiveBuckets = EmptyExponentialHistogramBuckets.get(0); + private ExponentialHistogramBuckets negativeBuckets = EmptyExponentialHistogramBuckets.get(0); + private List exemplars = Collections.emptyList(); + + @Override + public int getScale() { + return scale; + } + + @Override + public double getSum() { + return sum; + } + + @Override + public long getCount() { + return count; + } + + @Override + public long getZeroCount() { + return zeroCount; + } + + @Override + public boolean hasMin() { + return hasMin; + } + + @Override + public double getMin() { + return min; + } + + @Override + public boolean hasMax() { + return hasMax; + } + + @Override + public double getMax() { + return max; + } + + @Override + public ExponentialHistogramBuckets getPositiveBuckets() { + return positiveBuckets; + } + + @Override + public ExponentialHistogramBuckets getNegativeBuckets() { + return negativeBuckets; + } + + @Override + public long getStartEpochNanos() { + return startEpochNanos; + } + + @Override + public long getEpochNanos() { + return epochNanos; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public List getExemplars() { + return exemplars; + } + + @SuppressWarnings("TooManyParameters") + public ExponentialHistogramPointData set( + int scale, + double sum, + long zeroCount, + boolean hasMin, + double min, + boolean hasMax, + double max, + ExponentialHistogramBuckets positiveBuckets, + ExponentialHistogramBuckets negativeBuckets, + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars) { + this.count = zeroCount + positiveBuckets.getTotalCount() + negativeBuckets.getTotalCount(); + this.scale = scale; + this.sum = sum; + this.zeroCount = zeroCount; + this.hasMin = hasMin; + this.min = min; + this.hasMax = hasMax; + this.max = max; + this.positiveBuckets = positiveBuckets; + this.negativeBuckets = negativeBuckets; + this.startEpochNanos = startEpochNanos; + this.epochNanos = epochNanos; + this.attributes = attributes; + this.exemplars = exemplars; + + return this; + } + + @Override + public String toString() { + return "MutableExponentialHistogramPointData{" + + "startEpochNanos=" + + startEpochNanos + + ", " + + "epochNanos=" + + epochNanos + + ", " + + "attributes=" + + attributes + + ", " + + "scale=" + + scale + + ", " + + "sum=" + + sum + + ", " + + "count=" + + count + + ", " + + "zeroCount=" + + zeroCount + + ", " + + "hasMin=" + + hasMin + + ", " + + "min=" + + min + + ", " + + "hasMax=" + + hasMax + + ", " + + "max=" + + max + + ", " + + "positiveBuckets=" + + positiveBuckets + + ", " + + "negativeBuckets=" + + negativeBuckets + + ", " + + "exemplars=" + + exemplars + + "}"; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o instanceof ExponentialHistogramPointData) { + ExponentialHistogramPointData that = (ExponentialHistogramPointData) o; + return this.startEpochNanos == that.getStartEpochNanos() + && this.epochNanos == that.getEpochNanos() + && this.attributes.equals(that.getAttributes()) + && this.scale == that.getScale() + && Double.doubleToLongBits(this.sum) == Double.doubleToLongBits(that.getSum()) + && this.count == that.getCount() + && this.zeroCount == that.getZeroCount() + && this.hasMin == that.hasMin() + && Double.doubleToLongBits(this.min) == Double.doubleToLongBits(that.getMin()) + && this.hasMax == that.hasMax() + && Double.doubleToLongBits(this.max) == Double.doubleToLongBits(that.getMax()) + && this.positiveBuckets.equals(that.getPositiveBuckets()) + && this.negativeBuckets.equals(that.getNegativeBuckets()) + && this.exemplars.equals(that.getExemplars()); + } + return false; + } + + @Override + public int hashCode() { + int hash = 1; + hash *= 1000003; + hash ^= (int) ((startEpochNanos >>> 32) ^ startEpochNanos); + hash *= 1000003; + hash ^= (int) ((epochNanos >>> 32) ^ epochNanos); + hash *= 1000003; + hash ^= attributes.hashCode(); + hash *= 1000003; + hash ^= scale; + hash *= 1000003; + hash ^= (int) ((Double.doubleToLongBits(sum) >>> 32) ^ Double.doubleToLongBits(sum)); + hash *= 1000003; + hash ^= (int) ((count >>> 32) ^ count); + hash *= 1000003; + hash ^= (int) ((zeroCount >>> 32) ^ zeroCount); + hash *= 1000003; + hash ^= hasMin ? 1231 : 1237; + hash *= 1000003; + hash ^= (int) ((Double.doubleToLongBits(min) >>> 32) ^ Double.doubleToLongBits(min)); + hash *= 1000003; + hash ^= hasMax ? 1231 : 1237; + hash *= 1000003; + hash ^= (int) ((Double.doubleToLongBits(max) >>> 32) ^ Double.doubleToLongBits(max)); + hash *= 1000003; + hash ^= positiveBuckets.hashCode(); + hash *= 1000003; + hash ^= negativeBuckets.hashCode(); + hash *= 1000003; + hash ^= exemplars.hashCode(); + return hash; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointData.java new file mode 100644 index 00000000000..8823296a207 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointData.java @@ -0,0 +1,249 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import static io.opentelemetry.sdk.metrics.internal.data.HistogramPointDataValidations.validateFiniteBoundaries; +import static io.opentelemetry.sdk.metrics.internal.data.HistogramPointDataValidations.validateIsStrictlyIncreasing; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import java.util.Collections; +import java.util.List; + +/** + * A mutable {@link HistogramPointData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public final class MutableHistogramPointData implements HistogramPointData { + private long startEpochNanos; + private long epochNanos; + private Attributes attributes = Attributes.empty(); + private double sum; + private long count; + private boolean hasMin; + private double min; + private boolean hasMax; + private double max; + private List boundaries = Collections.emptyList(); + private final DynamicPrimitiveLongList counts; + private List exemplars = Collections.emptyList(); + + public MutableHistogramPointData(int buckets) { + this.counts = DynamicPrimitiveLongList.ofSubArrayCapacity(buckets); + this.counts.resizeAndClear(buckets); + } + + @SuppressWarnings({"TooManyParameters", "ForLoopReplaceableByForEach"}) + public MutableHistogramPointData set( + long startEpochNanos, + long epochNanos, + Attributes attributes, + double sum, + boolean hasMin, + double min, + boolean hasMax, + double max, + List boundaries, + long[] counts, + List exemplars) { + + if (this.counts.size() != boundaries.size() + 1) { + throw new IllegalArgumentException( + "invalid boundaries: size should be " + + (this.counts.size() - 1) + + " but was " + + boundaries.size()); + } + if (this.counts.size() != counts.length) { + throw new IllegalArgumentException( + "invalid counts: size should be " + this.counts.size() + " but was " + counts.length); + } + validateIsStrictlyIncreasing(boundaries); + validateFiniteBoundaries(boundaries); + + long totalCount = 0; + for (int i = 0; i < counts.length; i++) { + totalCount += counts[i]; + } + + this.startEpochNanos = startEpochNanos; + this.epochNanos = epochNanos; + this.attributes = attributes; + this.sum = sum; + this.count = totalCount; + this.hasMin = hasMin; + this.min = min; + this.hasMax = hasMax; + this.max = max; + this.boundaries = boundaries; + for (int i = 0; i < counts.length; i++) { + this.counts.setLong(i, counts[i]); + } + this.exemplars = exemplars; + + return this; + } + + @Override + public long getStartEpochNanos() { + return startEpochNanos; + } + + @Override + public long getEpochNanos() { + return epochNanos; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public double getSum() { + return sum; + } + + @Override + public long getCount() { + return count; + } + + @Override + public boolean hasMin() { + return hasMin; + } + + @Override + public double getMin() { + return min; + } + + @Override + public boolean hasMax() { + return hasMax; + } + + @Override + public double getMax() { + return max; + } + + @Override + public List getBoundaries() { + return boundaries; + } + + @Override + public List getCounts() { + return counts; + } + + @Override + public List getExemplars() { + return exemplars; + } + + @Override + public String toString() { + return "MutableHistogramPointData{" + + "startEpochNanos=" + + startEpochNanos + + ", " + + "epochNanos=" + + epochNanos + + ", " + + "attributes=" + + attributes + + ", " + + "sum=" + + sum + + ", " + + "count=" + + count + + ", " + + "hasMin=" + + hasMin + + ", " + + "min=" + + min + + ", " + + "hasMax=" + + hasMax + + ", " + + "max=" + + max + + ", " + + "boundaries=" + + boundaries + + ", " + + "counts=" + + counts + + ", " + + "exemplars=" + + exemplars + + "}"; + } + + @Override + public boolean equals(Object o) { + if (o == this) { + return true; + } + if (o instanceof HistogramPointData) { + HistogramPointData that = (HistogramPointData) o; + return this.startEpochNanos == that.getStartEpochNanos() + && this.epochNanos == that.getEpochNanos() + && this.attributes.equals(that.getAttributes()) + && Double.doubleToLongBits(this.sum) == Double.doubleToLongBits(that.getSum()) + && this.count == that.getCount() + && this.hasMin == that.hasMin() + && Double.doubleToLongBits(this.min) == Double.doubleToLongBits(that.getMin()) + && this.hasMax == that.hasMax() + && Double.doubleToLongBits(this.max) == Double.doubleToLongBits(that.getMax()) + && this.boundaries.equals(that.getBoundaries()) + && this.counts.equals(that.getCounts()) + && this.exemplars.equals(that.getExemplars()); + } + return false; + } + + @Override + public int hashCode() { + int hashcode = 1; + hashcode *= 1000003; + hashcode ^= (int) ((startEpochNanos >>> 32) ^ startEpochNanos); + hashcode *= 1000003; + hashcode ^= (int) ((epochNanos >>> 32) ^ epochNanos); + hashcode *= 1000003; + hashcode ^= attributes.hashCode(); + hashcode *= 1000003; + hashcode ^= (int) ((Double.doubleToLongBits(sum) >>> 32) ^ Double.doubleToLongBits(sum)); + hashcode *= 1000003; + hashcode ^= (int) ((count >>> 32) ^ count); + hashcode *= 1000003; + hashcode ^= hasMin ? 1231 : 1237; + hashcode *= 1000003; + hashcode ^= (int) ((Double.doubleToLongBits(min) >>> 32) ^ Double.doubleToLongBits(min)); + hashcode *= 1000003; + hashcode ^= hasMax ? 1231 : 1237; + hashcode *= 1000003; + hashcode ^= (int) ((Double.doubleToLongBits(max) >>> 32) ^ Double.doubleToLongBits(max)); + hashcode *= 1000003; + hashcode ^= boundaries.hashCode(); + hashcode *= 1000003; + hashcode ^= counts.hashCode(); + hashcode *= 1000003; + hashcode ^= exemplars.hashCode(); + return hashcode; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableLongPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableLongPointData.java new file mode 100644 index 00000000000..82fc91b4bcc --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/MutableLongPointData.java @@ -0,0 +1,136 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** + * A mutable {@link LongPointData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public class MutableLongPointData implements LongPointData { + + private long value; + private long startEpochNanos; + private long epochNanos; + private Attributes attributes = Attributes.empty(); + private List exemplars = Collections.emptyList(); + + @Override + public long getValue() { + return value; + } + + @Override + public long getStartEpochNanos() { + return startEpochNanos; + } + + @Override + public long getEpochNanos() { + return epochNanos; + } + + @Override + public Attributes getAttributes() { + return attributes; + } + + @Override + public List getExemplars() { + return exemplars; + } + + /** + * Sets all {@link MutableDoublePointData} based on {@code point}. + * + * @param point The point to set values upon + */ + public void set(LongPointData point) { + set( + point.getStartEpochNanos(), + point.getEpochNanos(), + point.getAttributes(), + point.getValue(), + point.getExemplars()); + } + + /** Sets all {@link MutableDoublePointData} values besides exemplars which are set to be empty. */ + public void set(long startEpochNanos, long epochNanos, Attributes attributes, long value) { + set(startEpochNanos, epochNanos, attributes, value, Collections.emptyList()); + } + + /** Sets all {@link MutableDoublePointData} values. */ + public void set( + long startEpochNanos, + long epochNanos, + Attributes attributes, + long value, + List exemplars) { + this.startEpochNanos = startEpochNanos; + this.epochNanos = epochNanos; + this.attributes = attributes; + this.value = value; + this.exemplars = exemplars; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (!(o instanceof LongPointData)) { + return false; + } + LongPointData that = (LongPointData) o; + return value == that.getValue() + && startEpochNanos == that.getStartEpochNanos() + && epochNanos == that.getEpochNanos() + && Objects.equals(attributes, that.getAttributes()) + && Objects.equals(exemplars, that.getExemplars()); + } + + @Override + public int hashCode() { + int hashcode = 1; + hashcode *= 1000003; + hashcode ^= (int) ((startEpochNanos >>> 32) ^ startEpochNanos); + hashcode *= 1000003; + hashcode ^= (int) ((epochNanos >>> 32) ^ epochNanos); + hashcode *= 1000003; + hashcode ^= attributes.hashCode(); + hashcode *= 1000003; + hashcode ^= (int) ((value >>> 32) ^ value); + hashcode *= 1000003; + hashcode ^= exemplars.hashCode(); + return hashcode; + } + + @Override + public String toString() { + return "MutableLongPointData{" + + "value=" + + value + + ", startEpochNanos=" + + startEpochNanos + + ", epochNanos=" + + epochNanos + + ", attributes=" + + attributes + + ", exemplars=" + + exemplars + + '}'; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramBuckets.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramBuckets.java deleted file mode 100644 index be87d2ad82c..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramBuckets.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram; - -import java.util.List; -import javax.annotation.concurrent.Immutable; - -/** - * ExponentialHistogramBuckets represents either the positive or negative measurements taken for a - * {@link ExponentialHistogramPointData}. - * - *

      The bucket boundaries are lower-bound inclusive, and are calculated using the {@link - * ExponentialHistogramPointData#getScale()} and the {@link #getOffset()}. - * - *

      For example, assume {@link ExponentialHistogramPointData#getScale()} is 0, the base is 2.0. - * Then, if offset is 0, the bucket lower bounds would be 1.0, 2.0, 4.0, 8.0, etc. If - * offset is -3, the bucket lower bounds would be 0.125, 0.25, 0.5, 1.0, 2,0, etc. If - * offset is +3, the bucket lower bounds would be 8.0, 16.0, 32.0, etc. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@Immutable -public interface ExponentialHistogramBuckets { - - /** - * The offset shifts the bucket boundaries according to lower_bound = base^(offset+i). - * . - * - * @return the offset. - */ - int getOffset(); - - /** - * The bucket counts is a of counts representing number of measurements that fall into each - * bucket. - * - * @return the bucket counts. - */ - List getBucketCounts(); - - /** - * The total count is the sum of all the values in the buckets. - * - * @return the total count. - */ - long getTotalCount(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramData.java deleted file mode 100644 index 2cc0ff2826f..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ExponentialHistogramData.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram; - -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.Data; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.data.MetricDataType; -import java.util.Collection; -import javax.annotation.concurrent.Immutable; - -/** - * A base-2 exponential histogram metric point, as defined by the OpenTelemetry Exponential - * Histogram specification. - * - *

      See {@link ExponentialHistogramPointData} for more information. - * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#exponentialhistogram - * - *

      Note: This is called "ExponentialHistogramData" to reflect which primitives are used to - * record it, however "ExponentialHistogram" is the equivalent OTLP type. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@Immutable -public interface ExponentialHistogramData extends Data { - - /** - * Create a DoubleExponentialHistogramData. - * - * @return a DoubleExponentialHistogramData - */ - static ExponentialHistogramData create( - AggregationTemporality temporality, Collection points) { - return ImmutableExponentialHistogramData.create(temporality, points); - } - - /** - * Returns the {@link ExponentialHistogramData} if type is {@link - * MetricDataType#EXPONENTIAL_HISTOGRAM}, otherwise a default empty data. - * - * @return the {@link ExponentialHistogramData} if type is {@link - * MetricDataType#EXPONENTIAL_HISTOGRAM}, otherwise a default empty data. - */ - static ExponentialHistogramData fromMetricData(MetricData data) { - if (data.getType() == MetricDataType.EXPONENTIAL_HISTOGRAM) { - return (ExponentialHistogramData) data.getData(); - } - return ImmutableExponentialHistogramData.empty(); - } - - /** - * Returns the {@code AggregationTemporality} of this metric. - * - *

      AggregationTemporality describes if the aggregator reports delta changes since last report - * time, or cumulative changes since a fixed start time. - * - * @return the {@code AggregationTemporality} of this metric - */ - AggregationTemporality getAggregationTemporality(); - - /** - * Returns the collection of {@link ExponentialHistogramPointData} for this histogram. - * - * @return the collection of data points for this histogram. - */ - @Override - Collection getPoints(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ImmutableExponentialHistogramData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ImmutableExponentialHistogramData.java deleted file mode 100644 index 08264d22f9b..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ImmutableExponentialHistogramData.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import java.util.Collection; -import java.util.Collections; - -/** - * A simple, autovalue implementation of {@link ExponentialHistogramData}. For more detailed javadoc - * on the type, see {@link ExponentialHistogramData}. - * - *

      See: - * https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/datamodel.md#exponentialhistogram - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@AutoValue -public abstract class ImmutableExponentialHistogramData implements ExponentialHistogramData { - - private static final ExponentialHistogramData EMPTY = - ExponentialHistogramData.create(AggregationTemporality.CUMULATIVE, Collections.emptyList()); - - public static ExponentialHistogramData empty() { - return EMPTY; - } - - /** Returns a new {@link ExponentialHistogramData}. */ - public static ExponentialHistogramData create( - AggregationTemporality temporality, Collection points) { - return new AutoValue_ImmutableExponentialHistogramData(temporality, points); - } - - ImmutableExponentialHistogramData() {} - - @Override - public abstract AggregationTemporality getAggregationTemporality(); - - @Override - public abstract Collection getPoints(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ImmutableExponentialHistogramPointData.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ImmutableExponentialHistogramPointData.java deleted file mode 100644 index 1026410ccea..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/ImmutableExponentialHistogramPointData.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram; - -import com.google.auto.value.AutoValue; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import java.util.List; -import javax.annotation.Nullable; -import javax.annotation.concurrent.Immutable; - -/** - * Simple auto value implementation of {@link ExponentialHistogramPointData}. For detailed javadoc - * on the type, see {@link ExponentialHistogramPointData}. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@AutoValue -@Immutable -abstract class ImmutableExponentialHistogramPointData implements ExponentialHistogramPointData { - - ImmutableExponentialHistogramPointData() {} - - /** - * Create a DoubleExponentialHistogramPointData. - * - * @return a DoubleExponentialHistogramPointData. - */ - static ImmutableExponentialHistogramPointData create( - int scale, - double sum, - long zeroCount, - @Nullable Double min, - @Nullable Double max, - ExponentialHistogramBuckets positiveBuckets, - ExponentialHistogramBuckets negativeBuckets, - long startEpochNanos, - long epochNanos, - Attributes attributes, - List exemplars) { - - long count = zeroCount + positiveBuckets.getTotalCount() + negativeBuckets.getTotalCount(); - - return new AutoValue_ImmutableExponentialHistogramPointData( - startEpochNanos, - epochNanos, - attributes, - scale, - sum, - count, - zeroCount, - min != null, - min != null ? min : -1, - max != null, - max != null ? max : -1, - positiveBuckets, - negativeBuckets, - exemplars); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/package-info.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/package-info.java deleted file mode 100644 index fe1f2bd69b0..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/data/exponentialhistogram/package-info.java +++ /dev/null @@ -1,10 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** The data format to model exponential histograms for export. */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/DebugConfig.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/DebugConfig.java index e66d361a89c..282dcfe4063 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/DebugConfig.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/DebugConfig.java @@ -5,7 +5,7 @@ package io.opentelemetry.sdk.metrics.internal.debug; -import java.util.Locale; +import io.opentelemetry.common.impl.ConfigUtil; /** * Determines if the SDK is in debugging mode (captures stack traces) or not. @@ -15,18 +15,14 @@ */ public final class DebugConfig { private static final String ENABLE_METRICS_DEBUG_PROPERTY = "otel.experimental.sdk.metrics.debug"; + + @SuppressWarnings("NonFinalStaticField") private static boolean enabled; private DebugConfig() {} static { - // Attempt to mirror the logic in DefaultConfigProperties here... - enabled = - "true".equalsIgnoreCase(System.getProperty(ENABLE_METRICS_DEBUG_PROPERTY)) - || "true" - .equalsIgnoreCase( - System.getenv( - ENABLE_METRICS_DEBUG_PROPERTY.toLowerCase(Locale.ROOT).replace('.', '_'))); + enabled = Boolean.parseBoolean(ConfigUtil.getString(ENABLE_METRICS_DEBUG_PROPERTY, "false")); } /** diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/StackTraceSourceInfo.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/StackTraceSourceInfo.java index a8b43be5fd2..64a18ad6736 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/StackTraceSourceInfo.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/debug/StackTraceSourceInfo.java @@ -5,6 +5,8 @@ package io.opentelemetry.sdk.metrics.internal.debug; +import java.util.Locale; + /** Diagnostic information derived from stack traces. */ final class StackTraceSourceInfo implements SourceInfo { @@ -19,7 +21,7 @@ public String shortDebugString() { if (stackTraceElements.length > 0) { for (StackTraceElement e : stackTraceElements) { if (isInterestingStackTrace(e)) { - return String.format("%s:%d", e.getFileName(), e.getLineNumber()); + return String.format(Locale.ROOT, "%s:%d", e.getFileName(), e.getLineNumber()); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/Advice.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/Advice.java new file mode 100644 index 00000000000..768b3afc297 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/Advice.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.descriptor; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.AttributeKey; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ +@AutoValue +@Immutable +public abstract class Advice { + + private static final Advice EMPTY_ADVICE = builder().build(); + + public static Advice empty() { + return EMPTY_ADVICE; + } + + public static AdviceBuilder builder() { + return new AutoValue_Advice.Builder(); + } + + Advice() {} + + @Nullable + public abstract List getExplicitBucketBoundaries(); + + @Nullable + public abstract List> getAttributes(); + + public boolean hasAttributes() { + return getAttributes() != null; + } + + /** + * This class is internal and is hence not for public use. Its APIs are unstable and can change at + * any time. + */ + @AutoValue.Builder + public abstract static class AdviceBuilder { + + AdviceBuilder() {} + + abstract AdviceBuilder explicitBucketBoundaries( + @Nullable List explicitBucketBoundaries); + + /** + * Sets the explicit bucket histogram boundaries. + * + * @param explicitBucketBoundaries the explicit bucket histogram boundaries. + */ + public AdviceBuilder setExplicitBucketBoundaries( + @Nullable List explicitBucketBoundaries) { + if (explicitBucketBoundaries != null) { + explicitBucketBoundaries = + Collections.unmodifiableList(new ArrayList<>(explicitBucketBoundaries)); + } + return explicitBucketBoundaries(explicitBucketBoundaries); + } + + abstract AdviceBuilder attributes(@Nullable List> attributes); + + /** + * Sets the list of the attribute keys to be used for the resulting instrument. + * + * @param attributes the list of the attribute keys. + */ + public AdviceBuilder setAttributes(@Nullable List> attributes) { + if (attributes != null) { + attributes = Collections.unmodifiableList(new ArrayList<>(attributes)); + } + return attributes(attributes); + } + + public abstract Advice build(); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptor.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptor.java index c3d74cc004a..78cfbe25ba6 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptor.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/InstrumentDescriptor.java @@ -6,10 +6,10 @@ package io.opentelemetry.sdk.metrics.internal.descriptor; import com.google.auto.value.AutoValue; -import com.google.auto.value.extension.memoized.Memoized; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import java.util.Locale; import javax.annotation.concurrent.Immutable; /** @@ -23,14 +23,16 @@ public abstract class InstrumentDescriptor { private final SourceInfo sourceInfo = SourceInfo.fromCurrentStack(); + private int hashcode; public static InstrumentDescriptor create( String name, String description, String unit, InstrumentType type, - InstrumentValueType valueType) { - return new AutoValue_InstrumentDescriptor(name, description, unit, type, valueType); + InstrumentValueType valueType, + Advice advice) { + return new AutoValue_InstrumentDescriptor(name, description, unit, type, valueType, advice); } InstrumentDescriptor() {} @@ -45,6 +47,11 @@ public static InstrumentDescriptor create( public abstract InstrumentValueType getValueType(); + /** + * Not part of instrument identity. Ignored from {@link #hashCode()} and {@link #equals(Object)}. + */ + public abstract Advice getAdvice(); + /** * Debugging information for this instrument. Ignored from {@link #equals(Object)} and {@link * #toString()}. @@ -53,7 +60,47 @@ public final SourceInfo getSourceInfo() { return sourceInfo; } - @Memoized + /** + * Uses case-insensitive version of {@link #getName()}, ignores {@link #getAdvice()} (not part of + * instrument identity}, ignores {@link #getSourceInfo()}. + */ @Override - public abstract int hashCode(); + public final int hashCode() { + int result = hashcode; + if (result == 0) { + result = 1; + result *= 1000003; + result ^= getName().toLowerCase(Locale.ROOT).hashCode(); + result *= 1000003; + result ^= getDescription().hashCode(); + result *= 1000003; + result ^= getUnit().hashCode(); + result *= 1000003; + result ^= getType().hashCode(); + result *= 1000003; + result ^= getValueType().hashCode(); + hashcode = result; + } + return result; + } + + /** + * Uses case-insensitive version of {@link #getName()}, ignores {@link #getAdvice()} (not part of + * instrument identity}, ignores {@link #getSourceInfo()}. + */ + @Override + public final boolean equals(Object o) { + if (o == this) { + return true; + } + if (o instanceof InstrumentDescriptor) { + InstrumentDescriptor that = (InstrumentDescriptor) o; + return this.getName().equalsIgnoreCase(that.getName()) + && this.getDescription().equals(that.getDescription()) + && this.getUnit().equals(that.getUnit()) + && this.getType().equals(that.getType()) + && this.getValueType().equals(that.getValueType()); + } + return false; + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptor.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptor.java index 9c883319139..02af3bd2bba 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptor.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptor.java @@ -6,13 +6,13 @@ package io.opentelemetry.sdk.metrics.internal.descriptor; import com.google.auto.value.AutoValue; -import com.google.auto.value.extension.memoized.Memoized; import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import java.util.Locale; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.concurrent.Immutable; @@ -29,6 +29,7 @@ public abstract class MetricDescriptor { private final AtomicReference viewSourceInfo = new AtomicReference<>(); + private int hashcode; /** * Constructs a metric descriptor with no instrument and default view. @@ -40,7 +41,12 @@ public static MetricDescriptor create(String name, String description, String un View.builder().build(), SourceInfo.fromCurrentStack(), InstrumentDescriptor.create( - name, description, unit, InstrumentType.OBSERVABLE_GAUGE, InstrumentValueType.DOUBLE)); + name, + description, + unit, + InstrumentType.OBSERVABLE_GAUGE, + InstrumentValueType.DOUBLE, + Advice.empty())); } /** Constructs a metric descriptor for a given View + instrument. */ @@ -89,36 +95,38 @@ public String getAggregationName() { return AggregationUtil.aggregationName(getView().getAggregation()); } - @Memoized + /** Uses case-insensitive version of {@link #getName()}. */ @Override - public abstract int hashCode(); + public final int hashCode() { + int result = hashcode; + if (result == 0) { + result = 1; + result *= 1000003; + result ^= getName().toLowerCase(Locale.ROOT).hashCode(); + result *= 1000003; + result ^= getDescription().hashCode(); + result *= 1000003; + result ^= getView().hashCode(); + result *= 1000003; + result ^= getSourceInstrument().hashCode(); + hashcode = result; + } + return result; + } - /** - * Returns true if another metric descriptor is compatible with this one. - * - *

      A metric descriptor is compatible with another if the following are true: - * - *

        - *
      • {@link #getName()} is equal - *
      • {@link #getDescription()} is equal - *
      • {@link #getAggregationName()} is equal - *
      • {@link InstrumentDescriptor#getName()} is equal - *
      • {@link InstrumentDescriptor#getDescription()} is equal - *
      • {@link InstrumentDescriptor#getUnit()} is equal - *
      • {@link InstrumentDescriptor#getType()} is equal - *
      • {@link InstrumentDescriptor#getValueType()} is equal - *
      - */ - public boolean isCompatibleWith(MetricDescriptor other) { - return getName().equals(other.getName()) - && getDescription().equals(other.getDescription()) - && getAggregationName().equals(other.getAggregationName()) - && getSourceInstrument().getName().equals(other.getSourceInstrument().getName()) - && getSourceInstrument() - .getDescription() - .equals(other.getSourceInstrument().getDescription()) - && getSourceInstrument().getUnit().equals(other.getSourceInstrument().getUnit()) - && getSourceInstrument().getType().equals(other.getSourceInstrument().getType()) - && getSourceInstrument().getValueType().equals(other.getSourceInstrument().getValueType()); + /** Uses case-insensitive version of {@link #getName()}. */ + @Override + public final boolean equals(Object o) { + if (o == this) { + return true; + } + if (o instanceof MetricDescriptor) { + MetricDescriptor that = (MetricDescriptor) o; + return this.getName().equalsIgnoreCase(that.getName()) + && this.getDescription().equals(that.getDescription()) + && this.getView().equals(that.getView()) + && this.getSourceInstrument().equals(that.getSourceInstrument()); + } + return false; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysOffExemplarFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysOffExemplarFilter.java new file mode 100644 index 00000000000..1b34c7b266d --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysOffExemplarFilter.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; + +/** + * A filter which makes no measurements eligible for being an exemplar. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AlwaysOffExemplarFilter implements ExemplarFilterInternal { + private static final ExemplarFilterInternal INSTANCE = new AlwaysOffExemplarFilter(); + + private AlwaysOffExemplarFilter() {} + + public static ExemplarFilterInternal getInstance() { + return INSTANCE; + } + + @Override + public boolean shouldSampleMeasurement(long value, Attributes attributes, Context context) { + return false; + } + + @Override + public boolean shouldSampleMeasurement(double value, Attributes attributes, Context context) { + return false; + } + + @Override + public String toString() { + return "AlwaysOffExemplarFilter"; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysOnExemplarFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysOnExemplarFilter.java new file mode 100644 index 00000000000..aa3a7c56f31 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysOnExemplarFilter.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; + +/** + * A filter which makes all measurements eligible for being an exemplar. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AlwaysOnExemplarFilter implements ExemplarFilterInternal { + private static final ExemplarFilterInternal INSTANCE = new AlwaysOnExemplarFilter(); + + private AlwaysOnExemplarFilter() {} + + public static ExemplarFilterInternal getInstance() { + return INSTANCE; + } + + @Override + public boolean shouldSampleMeasurement(long value, Attributes attributes, Context context) { + return true; + } + + @Override + public boolean shouldSampleMeasurement(double value, Attributes attributes, Context context) { + return true; + } + + @Override + public String toString() { + return "AlwaysOnExemplarFilter"; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysSampleFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysSampleFilter.java deleted file mode 100644 index 9b6e4a986a6..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/AlwaysSampleFilter.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; - -class AlwaysSampleFilter implements ExemplarFilter { - static final ExemplarFilter INSTANCE = new AlwaysSampleFilter(); - - private AlwaysSampleFilter() {} - - @Override - public boolean shouldSampleMeasurement(long value, Attributes attributes, Context context) { - return true; - } - - @Override - public boolean shouldSampleMeasurement(double value, Attributes attributes, Context context) { - return true; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleExemplarReservoir.java new file mode 100644 index 00000000000..9cf6084b55a --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleExemplarReservoir.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExemplarData; +import java.util.List; + +/** + * An interface for an exemplar reservoir of double samples. + * + *

      This represents a reservoir for a specific "point" of metric data. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @see LongExemplarReservoir + * @see ExemplarReservoirFactory + */ +public interface DoubleExemplarReservoir { + + /** Offers a measurement to be sampled. */ + void offerDoubleMeasurement(double value, Attributes attributes, Context context); + + /** + * Returns an immutable list of exemplars for exporting from the current reservoir. + * + *

      Additionally, clears the reservoir for the next sampling period. + * + * @param pointAttributes the {@link Attributes} associated with the metric point. {@link + * ExemplarData}s should filter these out of their final data state. + * @return An (immutable) list of sampled exemplars for this point. Implementers are expected to + * filter out {@code pointAttributes} from the original recorded attributes. + */ + List collectAndResetDoubles(Attributes pointAttributes); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleFilteredExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleFilteredExemplarReservoir.java new file mode 100644 index 00000000000..884453a3959 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleFilteredExemplarReservoir.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import java.util.List; + +/** A reservoir that has a pre-filter on measurements. */ +class DoubleFilteredExemplarReservoir implements DoubleExemplarReservoir { + private final ExemplarFilterInternal filter; + private final DoubleExemplarReservoir reservoir; + + DoubleFilteredExemplarReservoir( + ExemplarFilterInternal filter, DoubleExemplarReservoir reservoir) { + this.filter = filter; + this.reservoir = reservoir; + } + + @Override + public void offerDoubleMeasurement(double value, Attributes attributes, Context context) { + if (filter.shouldSampleMeasurement(value, attributes, context)) { + reservoir.offerDoubleMeasurement(value, attributes, context); + } + } + + @Override + public List collectAndResetDoubles(Attributes pointAttributes) { + return reservoir.collectAndResetDoubles(pointAttributes); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilter.java deleted file mode 100644 index 2d6d109a515..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; - -/** - * Exemplar filters are used to pre-filter measurements before attempting to store them in a - * reservoir. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface ExemplarFilter { - /** Returns whether or not a reservoir should attempt to filter a measurement. */ - boolean shouldSampleMeasurement(long value, Attributes attributes, Context context); - - /** Returns whether or not a reservoir should attempt to filter a measurement. */ - boolean shouldSampleMeasurement(double value, Attributes attributes, Context context); - - /** - * A filter that only accepts measurements where there is a {@code Span} in {@link Context} that - * is being sampled. - */ - static ExemplarFilter sampleWithTraces() { - return WithTraceExemplarFilter.INSTANCE; - } - - /** A filter that accepts any measurement. */ - static ExemplarFilter alwaysSample() { - return AlwaysSampleFilter.INSTANCE; - } - - /** A filter that accepts no measurements. */ - static ExemplarFilter neverSample() { - return NeverSampleFilter.INSTANCE; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterInternal.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterInternal.java new file mode 100644 index 00000000000..aa3858d670a --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterInternal.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.ExemplarFilter; + +/** + * Exemplar filters are used to pre-filter measurements before attempting to store them in a + * reservoir. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ExemplarFilterInternal extends ExemplarFilter { + + /** + * Utility for casting {@link ExemplarFilter} to {@link ExemplarFilterInternal}, throwing if + * {@code filter} does not implement {@link ExemplarFilterInternal}. + */ + static ExemplarFilterInternal asExemplarFilterInternal(ExemplarFilter filter) { + if (!(filter instanceof ExemplarFilterInternal)) { + throw new IllegalArgumentException( + "Custom ExemplarFilter implementations are currently not supported. " + + "Use one of the standard implementations returned by the static factories in the ExemplarFilter class."); + } + return (ExemplarFilterInternal) filter; + } + + /** Returns whether or not a reservoir should attempt to filter a measurement. */ + boolean shouldSampleMeasurement(long value, Attributes attributes, Context context); + + /** Returns whether or not a reservoir should attempt to filter a measurement. */ + boolean shouldSampleMeasurement(double value, Attributes attributes, Context context); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarReservoir.java deleted file mode 100644 index cebd4683fbb..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarReservoir.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; -import java.util.List; -import java.util.Random; -import java.util.function.Supplier; - -/** - * An interface for an exemplar reservoir of samples. - * - *

      This represents a reservoir for a specific "point" of metric data. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface ExemplarReservoir { - - /** Wraps a {@link ExemplarReservoir} with a measurement pre-filter. */ - static ExemplarReservoir filtered( - ExemplarFilter filter, ExemplarReservoir original) { - return new FilteredExemplarReservoir<>(filter, original); - } - - /** A double exemplar reservoir that stores no exemplars. */ - static ExemplarReservoir doubleNoSamples() { - return NoopExemplarReservoir.DOUBLE_INSTANCE; - } - - /** A long exemplar reservoir that stores no exemplars. */ - static ExemplarReservoir longNoSamples() { - return NoopExemplarReservoir.LONG_INSTANCE; - } - - /** - * A double reservoir with fixed size that stores the given number of exemplars. - * - * @param clock The clock to use when annotating measurements with time. - * @param size The maximum number of exemplars to preserve. - * @param randomSupplier The random number generator to use for sampling. - */ - static ExemplarReservoir doubleFixedSizeReservoir( - Clock clock, int size, Supplier randomSupplier) { - return RandomFixedSizeExemplarReservoir.createDouble(clock, size, randomSupplier); - } - - /** - * A long reservoir with fixed size that stores the given number of exemplars. - * - * @param clock The clock to use when annotating measurements with time. - * @param size The maximum number of exemplars to preserve. - * @param randomSupplier The random number generator to use for sampling. - */ - static ExemplarReservoir longFixedSizeReservoir( - Clock clock, int size, Supplier randomSupplier) { - return RandomFixedSizeExemplarReservoir.createLong(clock, size, randomSupplier); - } - - /** - * A Reservoir sampler that preserves the latest seen measurement per-histogram bucket. - * - * @param clock The clock to use when annotating measurements with time. - * @param boundaries A list of (inclusive) upper bounds for the histogram. Should be in order from - * lowest to highest. - */ - static ExemplarReservoir histogramBucketReservoir( - Clock clock, List boundaries) { - return new HistogramExemplarReservoir(clock, boundaries); - } - - /** Offers a {@code double} measurement to be sampled. */ - void offerDoubleMeasurement(double value, Attributes attributes, Context context); - - /** Offers a {@code long} measurement to be sampled. */ - void offerLongMeasurement(long value, Attributes attributes, Context context); - - /** - * Returns an immutable list of Exemplars for exporting from the current reservoir. - * - *

      Additionally, clears the reservoir for the next sampling period. - * - * @param pointAttributes the {@link Attributes} associated with the metric point. {@link - * ExemplarData}s should filter these out of their final data state. - * @return An (immutable) list of sampled exemplars for this point. Implementers are expected to - * filter out {@code pointAttributes} from the original recorded attributes. - */ - List collectAndReset(Attributes pointAttributes); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarReservoirFactory.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarReservoirFactory.java new file mode 100644 index 00000000000..2c6b74aa7f7 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarReservoirFactory.java @@ -0,0 +1,105 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.sdk.common.Clock; +import java.util.List; +import java.util.Random; +import java.util.function.Supplier; + +/** + * An exemplar reservoir factory is responsible for creating exemplar reservoir instances (i.e. + * {@link DoubleExemplarReservoir} or {@link LongExemplarReservoir}) for aggregation handles. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ExemplarReservoirFactory { + + /** + * Wraps exemplar reservoirs returned by a {@link ExemplarReservoirFactory} with a measurement + * pre-filter. + */ + static ExemplarReservoirFactory filtered( + ExemplarFilterInternal filter, ExemplarReservoirFactory original) { + return new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return new DoubleFilteredExemplarReservoir( + filter, original.createDoubleExemplarReservoir()); + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + return new LongFilteredExemplarReservoir(filter, original.createLongExemplarReservoir()); + } + }; + } + + /** An exemplar reservoir that stores no exemplars. */ + static ExemplarReservoirFactory noSamples() { + return new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return NoopExemplarReservoir.INSTANCE; + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + return NoopExemplarReservoir.INSTANCE; + } + }; + } + + /** + * A reservoir with fixed size that stores the given number of exemplars. + * + * @param clock The clock to use when annotating measurements with time. + * @param size The maximum number of exemplars to preserve. + * @param randomSupplier The random number generator to use for sampling. + */ + static ExemplarReservoirFactory fixedSizeReservoir( + Clock clock, int size, Supplier randomSupplier) { + return new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return RandomFixedSizeExemplarReservoir.create(clock, size, randomSupplier); + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + return RandomFixedSizeExemplarReservoir.create(clock, size, randomSupplier); + } + }; + } + + /** + * A Reservoir sampler that preserves the latest seen measurement per-histogram bucket. + * + * @param clock The clock to use when annotating measurements with time. + * @param boundaries A list of (inclusive) upper bounds for the histogram. Should be in order from + * lowest to highest. + */ + static ExemplarReservoirFactory histogramBucketReservoir(Clock clock, List boundaries) { + return new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return new HistogramExemplarReservoir(clock, boundaries); + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + return new HistogramExemplarReservoir(clock, boundaries); + } + }; + } + + /** Create an exemplar reservoir for double measurements. */ + DoubleExemplarReservoir createDoubleExemplarReservoir(); + + /** Create an exemplar reservoir for long measurements. */ + LongExemplarReservoir createLongExemplarReservoir(); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoir.java deleted file mode 100644 index 17415f9d06e..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoir.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import java.util.List; - -/** A reservoir that has a pre-filter on measurements. */ -class FilteredExemplarReservoir implements ExemplarReservoir { - private final ExemplarFilter filter; - private final ExemplarReservoir reservoir; - - FilteredExemplarReservoir(ExemplarFilter filter, ExemplarReservoir reservoir) { - this.filter = filter; - this.reservoir = reservoir; - } - - @Override - public void offerDoubleMeasurement(double value, Attributes attributes, Context context) { - if (filter.shouldSampleMeasurement(value, attributes, context)) { - reservoir.offerDoubleMeasurement(value, attributes, context); - } - } - - @Override - public void offerLongMeasurement(long value, Attributes attributes, Context context) { - if (filter.shouldSampleMeasurement(value, attributes, context)) { - reservoir.offerLongMeasurement(value, attributes, context); - } - } - - @Override - public List collectAndReset(Attributes pointAttributes) { - return reservoir.collectAndReset(pointAttributes); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FixedSizeExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FixedSizeExemplarReservoir.java index a5b65382b59..34f5a33f266 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FixedSizeExemplarReservoir.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/FixedSizeExemplarReservoir.java @@ -8,61 +8,102 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; +import javax.annotation.Nullable; /** Base for fixed-size reservoir sampling of Exemplars. */ -abstract class FixedSizeExemplarReservoir implements ExemplarReservoir { +class FixedSizeExemplarReservoir implements DoubleExemplarReservoir, LongExemplarReservoir { - private final ReservoirCell[] storage; + @Nullable private volatile ReservoirCell[] storage; private final ReservoirCellSelector reservoirCellSelector; - private final BiFunction mapAndResetCell; + private final int size; + private final Clock clock; + private final Object storageLock = new Object(); + private volatile boolean hasMeasurements = false; /** Instantiates an exemplar reservoir of fixed size. */ - FixedSizeExemplarReservoir( - Clock clock, - int size, - ReservoirCellSelector reservoirCellSelector, - BiFunction mapAndResetCell) { - this.storage = new ReservoirCell[size]; - for (int i = 0; i < size; ++i) { - this.storage[i] = new ReservoirCell(clock); - } + FixedSizeExemplarReservoir(Clock clock, int size, ReservoirCellSelector reservoirCellSelector) { + this.storage = null; // lazily initialize to avoid allocations + this.size = size; + this.clock = clock; this.reservoirCellSelector = reservoirCellSelector; - this.mapAndResetCell = mapAndResetCell; } @Override public void offerLongMeasurement(long value, Attributes attributes, Context context) { + ReservoirCell[] storage = getOrInitStorage(); int bucket = reservoirCellSelector.reservoirCellIndexFor(storage, value, attributes, context); if (bucket != -1) { - this.storage[bucket].recordLongMeasurement(value, attributes, context); + storage[bucket].recordLongMeasurement(value, attributes, context); + this.hasMeasurements = true; } } + @Override + public List collectAndResetDoubles(Attributes pointAttributes) { + return doCollectAndReset(pointAttributes, ReservoirCell::getAndResetDouble); + } + + @Override + public List collectAndResetLongs(Attributes pointAttributes) { + return doCollectAndReset(pointAttributes, ReservoirCell::getAndResetLong); + } + @Override public void offerDoubleMeasurement(double value, Attributes attributes, Context context) { + ReservoirCell[] storage = getOrInitStorage(); int bucket = reservoirCellSelector.reservoirCellIndexFor(storage, value, attributes, context); if (bucket != -1) { - this.storage[bucket].recordDoubleMeasurement(value, attributes, context); + storage[bucket].recordDoubleMeasurement(value, attributes, context); + this.hasMeasurements = true; } } - @Override - public List collectAndReset(Attributes pointAttributes) { + private ReservoirCell[] getOrInitStorage() { + ReservoirCell[] storage = this.storage; + if (storage == null) { + synchronized (storageLock) { + storage = this.storage; + if (storage == null) { + storage = initStorage(); + this.storage = storage; + } + } + } + return storage; + } + + private ReservoirCell[] initStorage() { + ReservoirCell[] storage = new ReservoirCell[this.size]; + for (int i = 0; i < size; ++i) { + storage[i] = new ReservoirCell(this.clock); + } + return storage; + } + + public List doCollectAndReset( + Attributes pointAttributes, BiFunction mapAndResetCell) { + ReservoirCell[] storage = this.storage; + if (!hasMeasurements || storage == null) { + return Collections.emptyList(); + } // Note: we are collecting exemplars from buckets piecemeal, but we // could still be sampling exemplars during this process. List results = new ArrayList<>(); - for (ReservoirCell reservoirCell : this.storage) { + for (ReservoirCell reservoirCell : storage) { T result = mapAndResetCell.apply(reservoirCell, pointAttributes); if (result != null) { results.add(result); } } reservoirCellSelector.reset(); + this.hasMeasurements = false; return Collections.unmodifiableList(results); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoir.java index f86d67fbec8..8b5ae4f97e0 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoir.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoir.java @@ -8,19 +8,19 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; import java.util.List; /** A reservoir that records the latest measurement for each histogram bucket. */ -class HistogramExemplarReservoir extends FixedSizeExemplarReservoir { +class HistogramExemplarReservoir extends FixedSizeExemplarReservoir { HistogramExemplarReservoir(Clock clock, List boundaries) { - super( - clock, - boundaries.size() + 1, - new HistogramCellSelector(boundaries), - ReservoirCell::getAndResetDouble); + super(clock, boundaries.size() + 1, new HistogramCellSelector(boundaries)); + } + + @Override + public void offerLongMeasurement(long value, Attributes attributes, Context context) { + super.offerDoubleMeasurement((double) value, attributes, context); } static class HistogramCellSelector implements ReservoirCellSelector { diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongExemplarReservoir.java new file mode 100644 index 00000000000..47f2172c0cf --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongExemplarReservoir.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import java.util.List; + +/** + * An interface for an exemplar reservoir of long samples. + * + *

      This represents a reservoir for a specific "point" of metric data. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + * @see DoubleExemplarReservoir + * @see ExemplarReservoirFactory + */ +public interface LongExemplarReservoir { + + /** Offers a measurement to be sampled. */ + void offerLongMeasurement(long value, Attributes attributes, Context context); + + /** + * Returns an immutable list of exemplars for exporting from the current reservoir. + * + *

      Additionally, clears the reservoir for the next sampling period. + * + * @param pointAttributes the {@link Attributes} associated with the metric point. {@link + * ExemplarData}s should filter these out of their final data state. + * @return An (immutable) list of sampled exemplars for this point. Implementers are expected to + * filter out {@code pointAttributes} from the original recorded attributes. + */ + List collectAndResetLongs(Attributes pointAttributes); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongFilteredExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongFilteredExemplarReservoir.java new file mode 100644 index 00000000000..db7a8291687 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongFilteredExemplarReservoir.java @@ -0,0 +1,34 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import java.util.List; + +/** A reservoir that has a pre-filter on measurements. */ +class LongFilteredExemplarReservoir implements LongExemplarReservoir { + private final ExemplarFilterInternal filter; + private final LongExemplarReservoir reservoir; + + LongFilteredExemplarReservoir(ExemplarFilterInternal filter, LongExemplarReservoir reservoir) { + this.filter = filter; + this.reservoir = reservoir; + } + + @Override + public void offerLongMeasurement(long value, Attributes attributes, Context context) { + if (filter.shouldSampleMeasurement(value, attributes, context)) { + reservoir.offerLongMeasurement(value, attributes, context); + } + } + + @Override + public List collectAndResetLongs(Attributes pointAttributes) { + return reservoir.collectAndResetLongs(pointAttributes); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NeverSampleFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NeverSampleFilter.java deleted file mode 100644 index c0cb537250b..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NeverSampleFilter.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; - -class NeverSampleFilter implements ExemplarFilter { - static final ExemplarFilter INSTANCE = new NeverSampleFilter(); - - private NeverSampleFilter() {} - - @Override - public boolean shouldSampleMeasurement(long value, Attributes attributes, Context context) { - return false; - } - - @Override - public boolean shouldSampleMeasurement(double value, Attributes attributes, Context context) { - return false; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NoopExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NoopExemplarReservoir.java index ec08dd7db42..b501d9cf548 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NoopExemplarReservoir.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/NoopExemplarReservoir.java @@ -8,18 +8,14 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.LongExemplarData; import java.util.Collections; import java.util.List; /** A reservoir that keeps no exemplars. */ -class NoopExemplarReservoir implements ExemplarReservoir { +class NoopExemplarReservoir implements LongExemplarReservoir, DoubleExemplarReservoir { - static final NoopExemplarReservoir LONG_INSTANCE = - new NoopExemplarReservoir<>(); - static final NoopExemplarReservoir DOUBLE_INSTANCE = - new NoopExemplarReservoir<>(); + static final NoopExemplarReservoir INSTANCE = new NoopExemplarReservoir(); private NoopExemplarReservoir() {} @@ -34,7 +30,12 @@ public void offerLongMeasurement(long value, Attributes attributes, Context cont } @Override - public List collectAndReset(Attributes pointAttributes) { + public List collectAndResetDoubles(Attributes pointAttributes) { + return Collections.emptyList(); + } + + @Override + public List collectAndResetLongs(Attributes pointAttributes) { return Collections.emptyList(); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoir.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoir.java index 5880394b37f..86e0c6a0ec4 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoir.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoir.java @@ -8,13 +8,9 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; import io.opentelemetry.sdk.metrics.internal.concurrent.AdderUtil; import io.opentelemetry.sdk.metrics.internal.concurrent.LongAdder; import java.util.Random; -import java.util.function.BiFunction; import java.util.function.Supplier; /** @@ -22,30 +18,19 @@ * where the probability of sampling decrease as the number of observations continue. * *

      When measurements are collected via {@link - * FixedSizeExemplarReservoir#collectAndReset(Attributes)}, the observation count is reset, making - * the probability of samplings effectively 1.0. + * FixedSizeExemplarReservoir#collectAndResetDoubles(Attributes)} (Attributes)} and {@link + * FixedSizeExemplarReservoir#collectAndResetLongs(Attributes)}, the observation count is reset, + * making the probability of samplings effectively 1.0. */ -class RandomFixedSizeExemplarReservoir - extends FixedSizeExemplarReservoir { +class RandomFixedSizeExemplarReservoir extends FixedSizeExemplarReservoir { - private RandomFixedSizeExemplarReservoir( - Clock clock, - int size, - Supplier randomSupplier, - BiFunction mapAndResetCell) { - super(clock, size, new RandomCellSelector(randomSupplier), mapAndResetCell); + private RandomFixedSizeExemplarReservoir(Clock clock, int size, Supplier randomSupplier) { + super(clock, size, new RandomCellSelector(randomSupplier)); } - static RandomFixedSizeExemplarReservoir createLong( + static RandomFixedSizeExemplarReservoir create( Clock clock, int size, Supplier randomSupplier) { - return new RandomFixedSizeExemplarReservoir<>( - clock, size, randomSupplier, ReservoirCell::getAndResetLong); - } - - static RandomFixedSizeExemplarReservoir createDouble( - Clock clock, int size, Supplier randomSupplier) { - return new RandomFixedSizeExemplarReservoir<>( - clock, size, randomSupplier, ReservoirCell::getAndResetDouble); + return new RandomFixedSizeExemplarReservoir(clock, size, randomSupplier); } static class RandomCellSelector implements ReservoirCellSelector { diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCell.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCell.java index 1adf684531a..b4f2a27093f 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCell.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCell.java @@ -68,12 +68,9 @@ synchronized void recordDoubleMeasurement(double value, Attributes attributes, C private void offerMeasurement(Attributes attributes, Context context) { this.attributes = attributes; - // Note: It may make sense in the future to attempt to pull this from an active span. - this.recordTime = clock.now(); - Span current = Span.fromContext(context); - if (current.getSpanContext().isValid()) { - this.spanContext = current.getSpanContext(); - } + // High precision time is not worth the additional performance expense it incurs for exemplars + this.recordTime = clock.now(/* highPrecision= */ false); + this.spanContext = Span.fromContext(context).getSpanContext(); } /** diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCellSelector.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCellSelector.java index ed500088576..b5290c92e22 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCellSelector.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/ReservoirCellSelector.java @@ -7,6 +7,7 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; +import java.util.function.BiFunction; /** Selects which {@link FixedSizeExemplarReservoir} {@link ReservoirCell} receives measurements. */ interface ReservoirCellSelector { @@ -19,6 +20,6 @@ int reservoirCellIndexFor( int reservoirCellIndexFor( ReservoirCell[] cells, double value, Attributes attributes, Context context); - /** Called when {@link FixedSizeExemplarReservoir#collectAndReset(Attributes)}. */ + /** Called when {@link FixedSizeExemplarReservoir#doCollectAndReset(Attributes, BiFunction)}. */ void reset(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/TraceBasedExemplarFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/TraceBasedExemplarFilter.java new file mode 100644 index 00000000000..c172548de33 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/TraceBasedExemplarFilter.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.context.Context; + +/** + * Exemplar sampler that only samples measurements with associated sampled traces. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class TraceBasedExemplarFilter implements ExemplarFilterInternal { + + private static final ExemplarFilterInternal INSTANCE = new TraceBasedExemplarFilter(); + + private TraceBasedExemplarFilter() {} + + public static ExemplarFilterInternal getInstance() { + return INSTANCE; + } + + @Override + public boolean shouldSampleMeasurement(long value, Attributes attributes, Context context) { + return hasSampledTrace(context); + } + + @Override + public boolean shouldSampleMeasurement(double value, Attributes attributes, Context context) { + return hasSampledTrace(context); + } + + private static boolean hasSampledTrace(Context context) { + return Span.fromContext(context).getSpanContext().isSampled(); + } + + @Override + public String toString() { + return "TraceBasedExemplarFilter"; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/WithTraceExemplarFilter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/WithTraceExemplarFilter.java deleted file mode 100644 index 9b14001cba3..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/exemplar/WithTraceExemplarFilter.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.context.Context; - -/** Exemplar sampler that only samples measurements with associated sampled traces. */ -final class WithTraceExemplarFilter implements ExemplarFilter { - - static final ExemplarFilter INSTANCE = new WithTraceExemplarFilter(); - - private WithTraceExemplarFilter() {} - - @Override - public boolean shouldSampleMeasurement(long value, Attributes attributes, Context context) { - return hasSampledTrace(context); - } - - @Override - public boolean shouldSampleMeasurement(double value, Attributes attributes, Context context) { - return hasSampledTrace(context); - } - - private static boolean hasSampledTrace(Context context) { - return Span.fromContext(context).getSpanContext().isSampled(); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/MetricProducer.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/MetricProducer.java deleted file mode 100644 index 32e036b9d10..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/MetricProducer.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.export; - -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.CollectionRegistration; -import io.opentelemetry.sdk.metrics.export.MetricReader; -import java.util.Collection; -import java.util.Collections; -import javax.annotation.concurrent.ThreadSafe; - -/** - * {@code MetricProducer} is the interface that is used to make metric data available to the {@link - * MetricReader}s. Implementations should be stateful, in that each call to {@link - * #collectAllMetrics()} will return any metric generated since the last call was made. - * - *

      Implementations must be thread-safe. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface MetricProducer extends CollectionRegistration { - - /** Cast the registration to a {@link MetricProducer}. */ - static MetricProducer asMetricProducer(CollectionRegistration registration) { - if (!(registration instanceof MetricProducer)) { - throw new IllegalArgumentException( - "unrecognized CollectionRegistration, custom MetricReader implementations are not currently supported"); - } - return (MetricProducer) registration; - } - - /** Return a noop {@link MetricProducer}. */ - static MetricProducer noop() { - return Collections::emptyList; - } - - /** - * Returns a collection of produced {@link MetricData}s to be exported. This will only be those - * metrics that have been produced since the last time this method was called. - * - * @return a collection of produced {@link MetricData}s to be exported. - */ - Collection collectAllMetrics(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReader.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReader.java index 16e3e7d15e9..bf414655695 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReader.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReader.java @@ -8,7 +8,9 @@ import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.export.MetricProducer; import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; @@ -23,15 +25,17 @@ public class RegisteredReader { private static final AtomicInteger ID_COUNTER = new AtomicInteger(1); private final int id = ID_COUNTER.incrementAndGet(); private final MetricReader metricReader; - private volatile long lastCollectEpochNanos; + private final ViewRegistry viewRegistry; + private volatile long lastCollectEpochNanos = -1; /** Construct a new collection info object storing information for collection against a reader. */ - public static RegisteredReader create(MetricReader reader) { - return new RegisteredReader(reader); + public static RegisteredReader create(MetricReader reader, ViewRegistry viewRegistry) { + return new RegisteredReader(reader, viewRegistry); } - private RegisteredReader(MetricReader metricReader) { + private RegisteredReader(MetricReader metricReader, ViewRegistry viewRegistry) { this.metricReader = metricReader; + this.viewRegistry = viewRegistry; } public MetricReader getReader() { @@ -48,13 +52,19 @@ public void setLastCollectEpochNanos(long epochNanos) { } /** - * Get the time of the last collection for the reader. + * Get the time of the last collection for the reader, or {@code defaultEpochNanos} if not set. * *

      Used to compute the {@link PointData#getStartEpochNanos()} for instruments aggregations with * {@link AggregationTemporality#DELTA} temporality. */ - public long getLastCollectEpochNanos() { - return lastCollectEpochNanos; + public long getLastCollectEpochNanosOrDefault(long defaultEpochNanos) { + long lastCollectEpochNanos = this.lastCollectEpochNanos; + return lastCollectEpochNanos == -1 ? defaultEpochNanos : lastCollectEpochNanos; + } + + /** Get the {@link ViewRegistry} for the reader. */ + public ViewRegistry getViewRegistry() { + return viewRegistry; } @Override diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleCounter.java deleted file mode 100644 index 2aa9bf79d8a..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleCounter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.instrument; - -import io.opentelemetry.api.metrics.DoubleCounter; -import io.opentelemetry.context.Context; -import javax.annotation.concurrent.ThreadSafe; - -/** - * A counter instrument that records {@code double} values with pre-associated attributes. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface BoundDoubleCounter { - /** - * Records a value with pre-bound attributes. - * - *

      Note: This may use {@code Context.current()} to pull the context associated with this - * measurement. - * - * @param value The increment amount. MUST be non-negative. - */ - void add(double value); - - /** - * Records a value with pre-bound attributes. - * - * @param value The increment amount. MUST be non-negative. - * @param context The explicit context to associate with this measurement. - */ - void add(double value, Context context); - - /** - * Unbinds the current bound instance from the {@link DoubleCounter}. - * - *

      After this method returns the current instance is considered invalid (not being managed by - * the instrument). This frees any reserved memory. - */ - void unbind(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleHistogram.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleHistogram.java deleted file mode 100644 index 3e8a489013e..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleHistogram.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.instrument; - -import io.opentelemetry.api.metrics.DoubleHistogram; -import io.opentelemetry.context.Context; -import javax.annotation.concurrent.ThreadSafe; - -/** - * A histogram instrument that records {@code long} values with pre-associated attributes. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface BoundDoubleHistogram { - /** - * Records a value with a pre-bound set of attributes. - * - *

      Note: This may use {@code Context.current()} to pull the context associated with this - * measurement. - * - * @param value The amount of the measurement. - */ - void record(double value); - - /** - * Records a value with a pre-bound set of attributes. - * - * @param value The amount of the measurement. - * @param context The explicit context to associate with this measurement. - */ - void record(double value, Context context); - - /** - * Unbinds the current bound instance from the {@link DoubleHistogram}. - * - *

      After this method returns the current instance is considered invalid (not being managed by - * the instrument). This frees any reserved memory. - */ - void unbind(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleUpDownCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleUpDownCounter.java deleted file mode 100644 index c851164ef57..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundDoubleUpDownCounter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.instrument; - -import io.opentelemetry.api.metrics.DoubleUpDownCounter; -import io.opentelemetry.context.Context; -import javax.annotation.concurrent.ThreadSafe; - -/** - * An up-down-counter instrument with pre-bound attributes. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface BoundDoubleUpDownCounter { - /** - * Records a value with pre-bound attributes. - * - *

      Note: This may use {@code Context.current()} to pull the context associated with this - * measurement. - * - * @param value The increment amount. May be positive, negative or zero. - */ - void add(double value); - - /** - * Records a value with a pre-bound attributes. - * - * @param value The increment amount. May be positive, negative or zero. - * @param context The explicit context to associate with this measurement. - */ - void add(double value, Context context); - - /** - * Unbinds the current bound instance from the {@link DoubleUpDownCounter}. - * - *

      After this method returns the current instance is considered invalid (not being managed by - * the instrument). This frees any reserved memory. - */ - void unbind(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongCounter.java deleted file mode 100644 index 7621ab08e87..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongCounter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.instrument; - -import io.opentelemetry.api.metrics.LongCounter; -import io.opentelemetry.context.Context; -import javax.annotation.concurrent.ThreadSafe; - -/** - * A counter instrument that records {@code long} values with pre-associated attributes. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface BoundLongCounter { - /** - * Records a value with pre-bound attributes. - * - *

      Note: This may use {@code Context.current()} to pull the context associated with this - * measurement. - * - * @param value The increment amount. MUST be non-negative. - */ - void add(long value); - - /** - * Records a value with pre-bound attributes. - * - * @param value The increment amount. MUST be non-negative. - * @param context The explicit context to associate with this measurement. - */ - void add(long value, Context context); - - /** - * Unbinds the current bound instance from the {@link LongCounter}. - * - *

      After this method returns the current instance is considered invalid (not being managed by - * the instrument). This frees any reserved memory. - */ - void unbind(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongHistogram.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongHistogram.java deleted file mode 100644 index b0f2a4ba4f9..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongHistogram.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.instrument; - -import io.opentelemetry.api.metrics.LongHistogram; -import io.opentelemetry.context.Context; -import javax.annotation.concurrent.ThreadSafe; - -/** - * A histogram instrument that records {@code long} values with pre-associated attributes. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface BoundLongHistogram { - /** - * Records a value with a pre-bound set of attributes. - * - *

      Note: This may use {@code Context.current()} to pull the context associated with this - * measurement. - * - * @param value The amount of the measurement. - */ - void record(long value); - - /** - * Records a value with a pre-bound set of attributes. - * - * @param value The amount of the measurement. - * @param context The explicit context to associate with this measurement. - */ - void record(long value, Context context); - - /** - * Unbinds the current bound instance from the {@link LongHistogram}. - * - *

      After this method returns the current instance is considered invalid (not being managed by - * the instrument). This frees any reserved memory. - */ - void unbind(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongUpDownCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongUpDownCounter.java deleted file mode 100644 index 68b753517ad..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/instrument/BoundLongUpDownCounter.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.instrument; - -import io.opentelemetry.api.metrics.LongUpDownCounter; -import io.opentelemetry.context.Context; -import javax.annotation.concurrent.ThreadSafe; - -/** - * An up-down-counter instrument with pre-bound attributes. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@ThreadSafe -public interface BoundLongUpDownCounter { - /** - * Records a value with pre-bound attributes. - * - *

      Note: This may use {@code Context.current()} to pull the context associated with this - * measurement. - * - * @param value The increment amount. May be positive, negative or zero. - */ - void add(long value); - - /** - * Records a value with a pre-bound attributes. - * - * @param value The increment amount. May be positive, negative or zero. - * @param context The explicit context to associate with this measurement. - */ - void add(long value, Context context); - - /** - * Unbinds the current bound instance from the {@link LongUpDownCounter}. - * - *

      After this method returns the current instance is considered invalid (not being managed by - * the instrument). This frees any reserved memory. - */ - void unbind(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/package-info.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/package-info.java new file mode 100644 index 00000000000..13b7ee33253 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/package-info.java @@ -0,0 +1,10 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** Internal SDK implementation classes. */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.metrics.internal; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingCircularBufferCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingCircularBufferCounter.java deleted file mode 100644 index fc0c347c722..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingCircularBufferCounter.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -/** - * A circle-buffer-backed exponential counter. - * - *

      The first recorded value becomes the 'baseIndex'. Going backwards leads to start/stop index - * - *

      This expand start/End index as it sees values. - * - *

      This class is NOT thread-safe. It is expected to be behind a synchronized incrementer. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time - */ -public class AdaptingCircularBufferCounter implements ExponentialCounter { - private static final int NULL_INDEX = Integer.MIN_VALUE; - private int endIndex = NULL_INDEX; - private int startIndex = NULL_INDEX; - private int baseIndex = NULL_INDEX; - private final AdaptingIntegerArray backing; - - /** Constructs a circular buffer that will hold at most {@code maxSize} buckets. */ - public AdaptingCircularBufferCounter(int maxSize) { - this.backing = new AdaptingIntegerArray(maxSize); - } - - /** (Deep)-Copies the values from another exponential counter. */ - public AdaptingCircularBufferCounter(ExponentialCounter toCopy) { - // If toCopy is an AdaptingCircularBuffer, just do a copy of the underlying array - // and baseIndex. - if (toCopy instanceof AdaptingCircularBufferCounter) { - this.backing = ((AdaptingCircularBufferCounter) toCopy).backing.copy(); - this.startIndex = toCopy.getIndexStart(); - this.endIndex = toCopy.getIndexEnd(); - this.baseIndex = ((AdaptingCircularBufferCounter) toCopy).baseIndex; - } else { - // Copy values from some other implementation of ExponentialCounter. - this.backing = new AdaptingIntegerArray(toCopy.getMaxSize()); - this.startIndex = NULL_INDEX; - this.baseIndex = NULL_INDEX; - this.endIndex = NULL_INDEX; - for (int i = toCopy.getIndexStart(); i <= toCopy.getIndexEnd(); i++) { - long val = toCopy.get(i); - this.increment(i, val); - } - } - } - - @Override - public int getIndexStart() { - return startIndex; - } - - @Override - public int getIndexEnd() { - return endIndex; - } - - @Override - public boolean increment(int index, long delta) { - if (baseIndex == NULL_INDEX) { - startIndex = index; - endIndex = index; - baseIndex = index; - backing.increment(0, delta); - return true; - } - - if (index > endIndex) { - // Move end, check max size - if ((long) index - startIndex + 1 > backing.length()) { - return false; - } - endIndex = index; - } else if (index < startIndex) { - // Move end, check max size - if ((long) endIndex - index + 1 > backing.length()) { - return false; - } - startIndex = index; - } - int realIdx = toBufferIndex(index); - backing.increment(realIdx, delta); - return true; - } - - @Override - public long get(int index) { - if (index < startIndex || index > endIndex) { - return 0; - } - return backing.get(toBufferIndex(index)); - } - - @Override - public boolean isEmpty() { - return baseIndex == NULL_INDEX; - } - - @Override - public int getMaxSize() { - return backing.length(); - } - - @Override - public void clear() { - this.backing.clear(); - this.baseIndex = NULL_INDEX; - this.endIndex = NULL_INDEX; - this.startIndex = NULL_INDEX; - } - - private int toBufferIndex(int index) { - // Figure out the index relative to the start of the circular buffer. - int result = index - baseIndex; - if (result >= backing.length()) { - result -= backing.length(); - } else if (result < 0) { - result += backing.length(); - } - return result; - } - - @Override - public String toString() { - StringBuilder result = new StringBuilder("{"); - for (int i = startIndex; i <= endIndex && startIndex != NULL_INDEX; i++) { - if (i != startIndex) { - result.append(','); - } - result.append(i).append('=').append(get(i)); - } - return result.append("}").toString(); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ArrayBasedStack.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ArrayBasedStack.java new file mode 100644 index 00000000000..9472276cb4e --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ArrayBasedStack.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static java.util.Objects.requireNonNull; + +import javax.annotation.Nullable; + +/** + * Array-based Stack. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public final class ArrayBasedStack { + // Visible for test + static final int DEFAULT_CAPACITY = 10; + + // NOTE (asafm): Using native array instead of ArrayList since I plan to add eviction + // if the initial portion of the stack is not used for several cycles of collection + private T[] array; + + private int size; + + @SuppressWarnings("unchecked") + public ArrayBasedStack() { + array = (T[]) new Object[DEFAULT_CAPACITY]; + size = 0; + } + + /** + * Add {@code element} to the top of the stack (LIFO). + * + * @param element The element to add + * @throws NullPointerException if {@code element} is null + */ + public void push(T element) { + requireNonNull(element, "Null is not permitted as element in the stack"); + if (size == array.length) { + resizeArray(array.length * 2); + } + array[size++] = element; + } + + /** + * Removes and returns an element from the top of the stack (LIFO). + * + * @return the top most element in the stack (last one added) + */ + @Nullable + public T pop() { + if (isEmpty()) { + return null; + } + T element = array[size - 1]; + array[size - 1] = null; + size--; + return element; + } + + public boolean isEmpty() { + return size == 0; + } + + public int size() { + return size; + } + + @SuppressWarnings("unchecked") + private void resizeArray(int newCapacity) { + T[] newArray = (T[]) new Object[newCapacity]; + System.arraycopy(array, 0, newArray, 0, size); + array = newArray; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java index cc2442ef305..1b28be543f1 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorage.java @@ -5,29 +5,40 @@ package io.opentelemetry.sdk.metrics.internal.state; +import static io.opentelemetry.sdk.common.export.MemoryMode.REUSABLE_DATA; + import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; import io.opentelemetry.api.metrics.ObservableLongMeasurement; import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorHandle; +import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Collection; import java.util.HashMap; +import java.util.List; import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.UnaryOperator; import java.util.logging.Level; import java.util.logging.Logger; +import javax.annotation.Nullable; /** * Stores aggregated {@link MetricData} for asynchronous instruments. @@ -35,127 +46,364 @@ *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ -final class AsynchronousMetricStorage implements MetricStorage { +public abstract class AsynchronousMetricStorage implements MetricStorage { private static final Logger logger = Logger.getLogger(AsynchronousMetricStorage.class.getName()); private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); - private final RegisteredReader registeredReader; + protected final RegisteredReader registeredReader; private final MetricDescriptor metricDescriptor; - private final TemporalMetricStorage metricStorage; - private final Aggregator aggregator; - private final AttributesProcessor attributesProcessor; - private Map accumulations = new HashMap<>(); + private final AggregationTemporality aggregationTemporality; + protected final Aggregator aggregator; + private final UnaryOperator attributesFilter; + protected final long instrumentCreationEpochNanos; + + protected final MemoryMode memoryMode; + + /** + * This field is set to 1 less than the actual intended cardinality limit, allowing the last slot + * to be filled by the {@link MetricStorage#CARDINALITY_OVERFLOW} series. + */ + private final int maxCardinality; + + // Handles responsible for aggregating data recorded during callbacks + protected final Map> aggregatorHandles; + + protected final List reusablePointsList = new ArrayList<>(); + + private volatile boolean enabled; private AsynchronousMetricStorage( RegisteredReader registeredReader, MetricDescriptor metricDescriptor, - Aggregator aggregator, - AttributesProcessor attributesProcessor) { + AggregationTemporality aggregationTemporality, + Aggregator aggregator, + UnaryOperator attributesFilter, + int maxCardinality, + Clock clock, + boolean enabled) { this.registeredReader = registeredReader; this.metricDescriptor = metricDescriptor; - AggregationTemporality aggregationTemporality = - registeredReader - .getReader() - .getAggregationTemporality(metricDescriptor.getSourceInstrument().getType()); - this.metricStorage = - new TemporalMetricStorage<>( - aggregator, - /* isSynchronous= */ false, - registeredReader, - aggregationTemporality, - metricDescriptor); + this.aggregationTemporality = aggregationTemporality; + this.memoryMode = registeredReader.getReader().getMemoryMode(); this.aggregator = aggregator; - this.attributesProcessor = attributesProcessor; + this.attributesFilter = attributesFilter; + this.instrumentCreationEpochNanos = clock.now(); + this.maxCardinality = maxCardinality - 1; + this.enabled = enabled; + + // Concurrent hashmap only used to allow for removal during iteration during collection. + this.aggregatorHandles = + memoryMode == REUSABLE_DATA ? new PooledHashMap<>() : new ConcurrentHashMap<>(); } /** * Create an asynchronous storage instance for the {@link View} and {@link InstrumentDescriptor}. */ // TODO(anuraaga): The cast to generic type here looks suspicious. - static AsynchronousMetricStorage create( + public static AsynchronousMetricStorage create( RegisteredReader registeredReader, RegisteredView registeredView, - InstrumentDescriptor instrumentDescriptor) { + Clock clock, + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + boolean enabled) { View view = registeredView.getView(); MetricDescriptor metricDescriptor = MetricDescriptor.create(view, registeredView.getViewSourceInfo(), instrumentDescriptor); - Aggregator aggregator = + AggregationTemporality aggregationTemporality = + registeredReader + .getReader() + .getAggregationTemporality(metricDescriptor.getSourceInstrument().getType()); + Aggregator aggregator = ((AggregatorFactory) view.getAggregation()) - .createAggregator(instrumentDescriptor, ExemplarFilter.neverSample()); - return new AsynchronousMetricStorage<>( - registeredReader, - metricDescriptor, - aggregator, - registeredView.getViewAttributesProcessor()); + .createAggregator( + instrumentDescriptor, exemplarFilter, registeredReader.getReader().getMemoryMode()); + UnaryOperator attributesFilter = registeredView.getAttributesFilter(); + int cardinalityLimit = registeredView.getCardinalityLimit(); + return aggregationTemporality == AggregationTemporality.DELTA + ? new DeltaAsynchronousMetricStorage<>( + registeredReader, + metricDescriptor, + aggregator, + attributesFilter, + cardinalityLimit, + clock, + enabled) + : new CumulativeAsynchronousMetricStorage<>( + registeredReader, + metricDescriptor, + aggregator, + attributesFilter, + cardinalityLimit, + clock, + enabled); } - /** Record callback long measurements from {@link ObservableLongMeasurement}. */ - void recordLong(long value, Attributes attributes) { - T accumulation = aggregator.accumulateLongMeasurement(value, attributes, Context.current()); - if (accumulation != null) { - recordAccumulation(accumulation, attributes); - } + /** Record callback measurement from {@link ObservableLongMeasurement}. */ + void record(Attributes attributes, long value) { + AggregatorHandle handle = getAggregatorHandle(attributes); + handle.recordLong(value, attributes, Context.current()); } - /** Record callback double measurements from {@link ObservableDoubleMeasurement}. */ - void recordDouble(double value, Attributes attributes) { - T accumulation = aggregator.accumulateDoubleMeasurement(value, attributes, Context.current()); - if (accumulation != null) { - recordAccumulation(accumulation, attributes); - } + /** Record callback measurement from {@link ObservableDoubleMeasurement}. */ + void record(Attributes attributes, double value) { + AggregatorHandle handle = getAggregatorHandle(attributes); + handle.recordDouble(value, attributes, Context.current()); } - private void recordAccumulation(T accumulation, Attributes attributes) { - Attributes processedAttributes = attributesProcessor.process(attributes, Context.current()); - - if (accumulations.size() >= MetricStorageUtils.MAX_ACCUMULATIONS) { + private AggregatorHandle getAggregatorHandle(Attributes attributes) { + attributes = attributesFilter.apply(attributes); + AggregatorHandle handle = aggregatorHandles.get(attributes); + if (handle != null) { + return handle; + } + if (aggregatorHandles.size() >= maxCardinality) { throttlingLogger.log( Level.WARNING, "Instrument " + metricDescriptor.getSourceInstrument().getName() - + " has exceeded the maximum allowed accumulations (" - + MetricStorageUtils.MAX_ACCUMULATIONS + + " has exceeded the maximum allowed cardinality (" + + maxCardinality + ")."); - return; + attributes = MetricStorage.CARDINALITY_OVERFLOW; + // Return handle for overflow series, first checking if a handle already exists for it + handle = aggregatorHandles.get(attributes); + if (handle != null) { + return handle; + } } - - // Check there is not already a recording for the attributes - if (accumulations.containsKey(attributes)) { - throttlingLogger.log( - Level.WARNING, - "Instrument " - + metricDescriptor.getSourceInstrument().getName() - + " has recorded multiple values for the same attributes."); - return; + // Get handle from pool if available, else create a new one. + // Note: pooled handles (used only for delta temporality) retain their original + // creationEpochNanos, but delta storage does not use the handle's creation epoch for the + // start epoch β€” it uses the reader's last collect time directly in doCollect(). So the stale + // creation epoch on a recycled handle does not affect correctness. + AggregatorHandle newHandle = maybeGetPooledAggregatorHandle(); + if (newHandle == null) { + newHandle = createAggregatorHandle(); } + handle = aggregatorHandles.putIfAbsent(attributes, newHandle); + return handle != null ? handle : newHandle; + } - accumulations.put(processedAttributes, accumulation); + protected AggregatorHandle createAggregatorHandle() { + return aggregator.createHandle( + registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos)); } + @Nullable + abstract AggregatorHandle maybeGetPooledAggregatorHandle(); + @Override public MetricDescriptor getMetricDescriptor() { return metricDescriptor; } - @Override + /** Returns the registered reader this storage is associated with. */ public RegisteredReader getRegisteredReader() { return registeredReader; } @Override - public MetricData collectAndReset( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - long startEpochNanos, - long epochNanos) { - Map currentAccumulations = accumulations; - accumulations = new HashMap<>(); - return metricStorage.buildMetricFor( - resource, instrumentationScopeInfo, currentAccumulations, startEpochNanos, epochNanos); + public void setEnabled(boolean enabled) { + this.enabled = enabled; } @Override - public boolean isEmpty() { - return aggregator == Aggregator.drop(); + public MetricData collect( + Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long epochNanos) { + Collection result = doCollect(epochNanos); + + return enabled + ? aggregator.toMetricData( + resource, instrumentationScopeInfo, metricDescriptor, result, aggregationTemporality) + : EmptyMetricData.getInstance(); + } + + abstract Collection doCollect(long epochNanos); + + private static final class DeltaAsynchronousMetricStorage + extends AsynchronousMetricStorage { + // This reference and lastPoints will be swapped at every collection + private Map reusablePointsMap = new PooledHashMap<>(); + private Map lastPoints; + + private final ObjectPool reusablePointsPool; + private final ObjectPool> reusableHandlesPool; + + DeltaAsynchronousMetricStorage( + RegisteredReader registeredReader, + MetricDescriptor metricDescriptor, + Aggregator aggregator, + UnaryOperator attributesFilter, + int maxCardinality, + Clock clock, + boolean enabled) { + super( + registeredReader, + metricDescriptor, + AggregationTemporality.DELTA, + aggregator, + attributesFilter, + maxCardinality, + clock, + enabled); + + this.reusablePointsPool = new ObjectPool<>(aggregator::createReusablePoint); + this.reusableHandlesPool = new ObjectPool<>(this::createAggregatorHandle); + // Concurrent hashmap only used to allow for removal during iteration during collection. + this.lastPoints = + memoryMode == REUSABLE_DATA ? new PooledHashMap<>() : new ConcurrentHashMap<>(); + } + + @Nullable + @Override + AggregatorHandle maybeGetPooledAggregatorHandle() { + return reusableHandlesPool.borrowObject(); + } + + @Override + Collection doCollect(long epochNanos) { + Map currentPoints; + if (memoryMode == REUSABLE_DATA) { + // deltaPoints computed in the previous collection can be released + reusablePointsList.forEach(reusablePointsPool::returnObject); + reusablePointsList.clear(); + + currentPoints = reusablePointsMap; + } else { + currentPoints = new HashMap<>(); + } + + // Start time for asynchronous delta instruments is the time of the last collection, or if no + // collection has yet taken place, the time the instrument was created. + long startEpochNanos = + registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos); + + aggregatorHandles.forEach((attributes, handle) -> { + T point = + handle.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + + T pointForCurrentPoints; + if (memoryMode == REUSABLE_DATA) { + // AggregatorHandle is going to modify the point eventually, but we must persist its + // value to used it at the next collection (within lastPoints). Thus, we make a copy. + pointForCurrentPoints = reusablePointsPool.borrowObject(); + aggregator.copyPoint(point, pointForCurrentPoints); + } else { + pointForCurrentPoints = point; + } + currentPoints.put(attributes, pointForCurrentPoints); + }); + + List deltaPoints = memoryMode == REUSABLE_DATA ? reusablePointsList : new ArrayList<>(); + currentPoints.forEach((attributes, currentPoint) -> { + T lastPoint = lastPoints.remove(attributes); + + T deltaPoint; + if (lastPoint == null) { + if (memoryMode == REUSABLE_DATA) { + // All deltaPoints are released at the end of the collection. Thus, we need a copy + // to make sure currentPoint can still be used within lastPoints during the next + // collection. + deltaPoint = reusablePointsPool.borrowObject(); + aggregator.copyPoint(currentPoint, deltaPoint); + } else { + deltaPoint = currentPoint; + } + } else { + if (memoryMode == REUSABLE_DATA) { + aggregator.diffInPlace(lastPoint, currentPoint); + deltaPoint = lastPoint; + } else { + deltaPoint = aggregator.diff(lastPoint, currentPoint); + } + } + deltaPoints.add(deltaPoint); + }); + + if (memoryMode == REUSABLE_DATA) { + // - If the point was used to compute a delta, it's now in deltaPoints (and thus in + // reusablePointsList) + // - If the point hasn't been used, it's still in lastPoints and can be returned + lastPoints.forEach((attributes, point) -> reusablePointsPool.returnObject(point)); + lastPoints.clear(); + + Map tmp = lastPoints; + lastPoints = reusablePointsMap; + reusablePointsMap = tmp; + } else { + lastPoints = currentPoints; + } + + aggregatorHandles.forEach( + (unused, aggregatorHandle) -> reusableHandlesPool.returnObject(aggregatorHandle)); + aggregatorHandles.clear(); + + return deltaPoints; + } + } + + private static final class CumulativeAsynchronousMetricStorage + extends AsynchronousMetricStorage { + CumulativeAsynchronousMetricStorage( + RegisteredReader registeredReader, + MetricDescriptor metricDescriptor, + Aggregator aggregator, + UnaryOperator attributesFilter, + int maxCardinality, + Clock clock, + boolean enabled) { + super( + registeredReader, + metricDescriptor, + AggregationTemporality.CUMULATIVE, + aggregator, + attributesFilter, + maxCardinality, + clock, + enabled); + } + + @Nullable + @Override + AggregatorHandle maybeGetPooledAggregatorHandle() { + return null; + } + + @Override + Collection doCollect(long epochNanos) { + List currentPoints; + if (memoryMode == REUSABLE_DATA) { + // We should not return the points in this list to the pool, they belong to the + // AggregatorHandle + reusablePointsList.clear(); + currentPoints = reusablePointsList; + } else { + currentPoints = new ArrayList<>(); + } + + // Asynchronous instruments manage their own state. If they stop reporting a measurement for a + // collection, the series ends. We retain aggregator handles across collections to allow + // series to report a consistent start time for their lifetime. While collecting, remove any + // series without measurements this collection. + // Start time for cumulative asynchronous instruments is: + // - The instrument creation time if the series first appeared during the first collection + // cycle + // - Otherwise, the preceding collection interval's timestamp + // This logic is handled in AggregatorHandle creation via #createAggregatorHandle() + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.hasRecordedValues()) { + aggregatorHandles.remove(attributes); + return; + } + T value = + handle.aggregateThenMaybeReset( + handle.getCreationEpochNanos(), epochNanos, attributes, /* reset= */ true); + currentPoints.add(value); + }); + + return currentPoints; + } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/BoundStorageHandle.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/BoundStorageHandle.java index 4cf7fb83676..387b091f99b 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/BoundStorageHandle.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/BoundStorageHandle.java @@ -5,20 +5,27 @@ package io.opentelemetry.sdk.metrics.internal.state; -import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; /** - * A bound handle for recording measurements against a particular set of attributes. + * A record target for a single timeseries, resolved once via {@link + * WriteableMetricStorage#bind(io.opentelemetry.api.common.Attributes)}. + * + *

      Records bypass the per-recording attribute processing and series lookup that {@link + * WriteableMetricStorage#recordLong} / {@link WriteableMetricStorage#recordDouble} perform, since + * the series is resolved at bind time. Backs bound instruments. Bound handles record strictly + * against their bound attributes and do not inherit dynamic context-scoped attributes. + * + *

      TODO: review whether bound handles should optionally inherit context-scoped attributes. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ public interface BoundStorageHandle { - /** Records a measurement. */ - void recordLong(long value, Attributes attributes, Context context); - /** Records a measurement. */ - void recordDouble(double value, Attributes attributes, Context context); - /** Release this handle back to the storage. */ - void release(); + + /** Records a long measurement against the bound series. */ + void recordLong(long value, Context context); + + /** Records a double measurement against the bound series. */ + void recordDouble(double value, Context context); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistration.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistration.java index 92a63ab1396..5eb7f0b1eb6 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistration.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistration.java @@ -5,16 +5,16 @@ package io.opentelemetry.sdk.metrics.internal.state; -import static io.opentelemetry.sdk.internal.ThrowableUtil.propagateIfFatal; +import static io.opentelemetry.sdk.common.internal.ThrowableUtil.propagateIfFatal; import static java.util.stream.Collectors.toList; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; -import java.util.stream.Collectors; +import javax.annotation.Nullable; /** * A registered callback. @@ -28,18 +28,22 @@ public final class CallbackRegistration { private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); private final List observableMeasurements; private final Runnable callback; - private final String callbackDescription; + private final List instrumentDescriptors; private final boolean hasStorages; + @Nullable private final ClassLoader contextClassLoader; private CallbackRegistration( List observableMeasurements, Runnable callback) { this.observableMeasurements = observableMeasurements; this.callback = callback; - List instrumentDescriptors = + this.contextClassLoader = Thread.currentThread().getContextClassLoader(); + this.instrumentDescriptors = observableMeasurements.stream() .map(SdkObservableMeasurement::getInstrumentDescriptor) .collect(toList()); - this.callbackDescription = callbackDescription(instrumentDescriptors); + if (instrumentDescriptors.size() == 0) { + throw new IllegalStateException("Callback with no instruments is not allowed"); + } this.hasStorages = observableMeasurements.stream() .flatMap(measurement -> measurement.getStorages().stream()) @@ -64,27 +68,12 @@ public static CallbackRegistration create( return new CallbackRegistration(observableMeasurements, runnable); } - // Visible for test - static String callbackDescription(List instrumentDescriptors) { - if (instrumentDescriptors.size() == 0) { - throw new IllegalStateException("Callback with no instruments is not allowed"); - } - if (instrumentDescriptors.size() == 1) { - return "Instrument " + instrumentDescriptors.get(0).getName(); - } - StringBuilder description = new StringBuilder("BatchCallback("); - description.append( - instrumentDescriptors.stream() - .map(InstrumentDescriptor::getName) - .collect(Collectors.joining(",", "[", "]"))); - return description.append(")").toString(); - } - - public String getCallbackDescription() { - return callbackDescription; + @Override + public String toString() { + return "CallbackRegistration{instrumentDescriptors=" + instrumentDescriptors + "}"; } - void invokeCallback(RegisteredReader reader) { + public void invokeCallback(RegisteredReader reader) { // Return early if no storages are registered if (!hasStorages) { return; @@ -93,17 +82,19 @@ void invokeCallback(RegisteredReader reader) { // to relevant storages observableMeasurements.forEach( observableMeasurement -> observableMeasurement.setActiveReader(reader)); + // Restore the context class loader that was active when the callback was registered. + Thread currentThread = Thread.currentThread(); + ClassLoader previousContextClassLoader = currentThread.getContextClassLoader(); + currentThread.setContextClassLoader(contextClassLoader); try { callback.run(); } catch (Throwable e) { propagateIfFatal(e); throttlingLogger.log( - Level.WARNING, - "An exception occurred invoking callback for " + callbackDescription + ".", - e); + Level.WARNING, "An exception occurred invoking callback for " + this + ".", e); } finally { - observableMeasurements.forEach( - observableMeasurement -> observableMeasurement.setActiveReader(null)); + currentThread.setContextClassLoader(previousContextClassLoader); + observableMeasurements.forEach(SdkObservableMeasurement::unsetActiveReader); } } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java new file mode 100644 index 00000000000..bd30afd707f --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/CumulativeSynchronousMetricStorage.java @@ -0,0 +1,168 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static io.opentelemetry.sdk.common.export.MemoryMode.REUSABLE_DATA; +import static io.opentelemetry.sdk.metrics.data.AggregationTemporality.CUMULATIVE; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorHandle; +import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; +import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; +import java.util.logging.Level; +import javax.annotation.Nullable; + +class CumulativeSynchronousMetricStorage + extends DefaultSynchronousMetricStorage { + private final MemoryMode memoryMode; + private final ConcurrentHashMap> aggregatorHandles = + new ConcurrentHashMap<>(); + // Only populated if memoryMode == REUSABLE_DATA + private final ArrayList reusableResultList = new ArrayList<>(); + + CumulativeSynchronousMetricStorage( + MetricDescriptor metricDescriptor, + Aggregator aggregator, + UnaryOperator attributesFilter, + Clock clock, + int maxCardinality, + boolean enabled, + @Nullable Predicate> contextScopedAttributesFilter, + MemoryMode memoryMode) { + super( + metricDescriptor, + aggregator, + attributesFilter, + clock, + maxCardinality, + enabled, + contextScopedAttributesFilter); + this.memoryMode = memoryMode; + } + + @Override + void doRecordLong(long value, Attributes attributes, Context context) { + getAggregatorHandle(attributes).recordLong(value, attributes, context); + } + + @Override + void doRecordDouble(double value, Attributes attributes, Context context) { + getAggregatorHandle(attributes).recordDouble(value, attributes, context); + } + + @Override + public BoundStorageHandle bind(Attributes attributes) { + // Cumulative handles are stable for the instrument's lifetime (the map is never swapped and + // handles are never reset/pooled), so resolve the handle once here and record straight onto it. + AggregatorHandle handle = getAggregatorHandle(attributes); + return new CumulativeBoundHandle(handle, attributes); + } + + private final class CumulativeBoundHandle implements BoundStorageHandle { + private final AggregatorHandle handle; + // Original (unprocessed) attributes, passed to the handle for exemplar sampling, matching the + // unbound record path. + private final Attributes attributes; + + CumulativeBoundHandle(AggregatorHandle handle, Attributes attributes) { + this.handle = handle; + this.attributes = attributes; + } + + @Override + public void recordLong(long value, Context context) { + if (!isEnabled()) { + return; + } + handle.recordLong(value, attributes, context); + } + + @Override + public void recordDouble(double value, Context context) { + if (!shouldRecordDouble(value, attributes)) { + return; + } + handle.recordDouble(value, attributes, context); + } + } + + private AggregatorHandle getAggregatorHandle(Attributes attributes) { + Objects.requireNonNull(attributes, "attributes"); + attributes = attributesFilter.apply(attributes); + AggregatorHandle handle = aggregatorHandles.get(attributes); + if (handle != null) { + return handle; + } + if (aggregatorHandles.size() >= maxCardinality) { + logger.log( + Level.WARNING, + "Instrument " + + metricDescriptor.getSourceInstrument().getName() + + " has exceeded the maximum allowed cardinality (" + + maxCardinality + + ")."); + // Return handle for overflow series, first checking if a handle already exists for it + attributes = MetricStorage.CARDINALITY_OVERFLOW; + handle = aggregatorHandles.get(attributes); + if (handle != null) { + return handle; + } + } + AggregatorHandle newHandle = aggregator.createHandle(clock.now()); + handle = aggregatorHandles.putIfAbsent(attributes, newHandle); + return handle != null ? handle : newHandle; + } + + @Override + public MetricData collect( + Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long epochNanos) { + List points; + if (memoryMode == REUSABLE_DATA) { + reusableResultList.clear(); + points = reusableResultList; + } else { + points = new ArrayList<>(aggregatorHandles.size()); + } + + // Grab aggregated points. + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.hasRecordedValues()) { + return; + } + // Start time for cumulative synchronous instruments is the time the first series + // measurement was recorded. I.e. the time the AggregatorHandle was created. + T point = + handle.aggregateThenMaybeReset( + handle.getCreationEpochNanos(), epochNanos, attributes, /* reset= */ false); + + if (point != null) { + points.add(point); + } + }); + + if (points.isEmpty() || !enabled) { + return EmptyMetricData.getInstance(); + } + + return aggregator.toMetricData( + resource, instrumentationScopeInfo, metricDescriptor, points, CUMULATIVE); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DebugUtils.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DebugUtils.java index d52ef4f5ce9..0145740221f 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DebugUtils.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DebugUtils.java @@ -22,7 +22,7 @@ private DebugUtils() {} * Creates a detailed error message comparing two {@link MetricDescriptor}s. * *

      Called when the metrics with the descriptors have the same name, but {@link - * MetricDescriptor#isCompatibleWith(MetricDescriptor)} is {@code false}. + * MetricDescriptor#equals(Object)} is {@code false}. * *

      This should identify all issues between the descriptor and log information on where they are * defined. Users should be able to find/fix issues based on this error. diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DefaultSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DefaultSynchronousMetricStorage.java index aa7ced9ee45..92974bfd8b3 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DefaultSynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DefaultSynchronousMetricStorage.java @@ -5,27 +5,25 @@ package io.opentelemetry.sdk.metrics.internal.state; -import static io.opentelemetry.sdk.metrics.internal.state.MetricStorageUtils.MAX_ACCUMULATIONS; +import static io.opentelemetry.sdk.metrics.data.AggregationTemporality.CUMULATIVE; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; -import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorHandle; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; -import io.opentelemetry.sdk.resources.Resource; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.concurrent.ConcurrentHashMap; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; import java.util.logging.Level; import java.util.logging.Logger; +import javax.annotation.Nullable; /** * Stores aggregated {@link MetricData} for synchronous instruments. @@ -33,178 +31,174 @@ *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. */ -public final class DefaultSynchronousMetricStorage +public abstract class DefaultSynchronousMetricStorage implements SynchronousMetricStorage { - private static final ThrottlingLogger logger = - new ThrottlingLogger(Logger.getLogger(DefaultSynchronousMetricStorage.class.getName())); - private static final BoundStorageHandle NOOP_STORAGE_HANDLE = new NoopBoundHandle(); + private static final Logger internalLogger = + Logger.getLogger(DefaultSynchronousMetricStorage.class.getName()); + private static final boolean INCUBATOR_AVAILABLE; - private final RegisteredReader registeredReader; - private final MetricDescriptor metricDescriptor; - private final Aggregator aggregator; - private final ConcurrentHashMap> activeCollectionStorage = - new ConcurrentHashMap<>(); - private final TemporalMetricStorage temporalMetricStorage; - private final AttributesProcessor attributesProcessor; + static { + boolean incubatorAvailable = false; + try { + Class.forName("io.opentelemetry.api.incubator.common.ContextAttributes"); + incubatorAvailable = true; + } catch (ClassNotFoundException e) { + // Not available + } + INCUBATOR_AVAILABLE = incubatorAvailable; + } + + final ThrottlingLogger logger = new ThrottlingLogger(internalLogger); + final UnaryOperator attributesFilter; + @Nullable private final Predicate> contextScopedAttributesFilter; + protected final Clock clock; + protected final MetricDescriptor metricDescriptor; + protected final Aggregator aggregator; + + /** + * This field is set to 1 less than the actual intended cardinality limit, allowing the last slot + * to be filled by the {@link MetricStorage#CARDINALITY_OVERFLOW} series. + */ + protected final int maxCardinality; + + protected volatile boolean enabled; DefaultSynchronousMetricStorage( - RegisteredReader registeredReader, MetricDescriptor metricDescriptor, - Aggregator aggregator, - AttributesProcessor attributesProcessor) { - this.registeredReader = registeredReader; + Aggregator aggregator, + UnaryOperator attributesFilter, + Clock clock, + int maxCardinality, + boolean enabled, + @Nullable Predicate> contextScopedAttributesFilter) { this.metricDescriptor = metricDescriptor; - AggregationTemporality aggregationTemporality = - registeredReader - .getReader() - .getAggregationTemporality(metricDescriptor.getSourceInstrument().getType()); this.aggregator = aggregator; - this.temporalMetricStorage = - new TemporalMetricStorage<>( - aggregator, - /* isSynchronous= */ true, - registeredReader, - aggregationTemporality, - metricDescriptor); - this.attributesProcessor = attributesProcessor; + this.attributesFilter = attributesFilter; + this.clock = clock; + this.maxCardinality = maxCardinality - 1; + this.enabled = enabled; + this.contextScopedAttributesFilter = contextScopedAttributesFilter; } - // This is a storage handle to use when the attributes processor requires - private final BoundStorageHandle lateBoundStorageHandle = - new BoundStorageHandle() { - @Override - public void release() {} - - @Override - public void recordLong(long value, Attributes attributes, Context context) { - DefaultSynchronousMetricStorage.this.recordLong(value, attributes, context); - } - - @Override - public void recordDouble(double value, Attributes attributes, Context context) { - DefaultSynchronousMetricStorage.this.recordDouble(value, attributes, context); - } - }; - - @Override - public BoundStorageHandle bind(Attributes attributes) { - Objects.requireNonNull(attributes, "attributes"); - if (attributesProcessor.usesContext()) { - // We cannot pre-bind attributes because we need to pull attributes from context. - return lateBoundStorageHandle; - } - return doBind(attributesProcessor.process(attributes, Context.current())); + static DefaultSynchronousMetricStorage create( + RegisteredReader reader, + MetricDescriptor descriptor, + Aggregator aggregator, + UnaryOperator attributesFilter, + int maxCardinality, + Clock clock, + boolean enabled, + @Nullable Predicate> contextScopedAttributesFilter) { + AggregationTemporality aggregationTemporality = + reader.getReader().getAggregationTemporality(descriptor.getSourceInstrument().getType()); + return aggregationTemporality == CUMULATIVE + ? new CumulativeSynchronousMetricStorage<>( + descriptor, + aggregator, + attributesFilter, + clock, + maxCardinality, + enabled, + contextScopedAttributesFilter, + reader.getReader().getMemoryMode()) + : new DeltaSynchronousMetricStorage<>( + reader, + descriptor, + aggregator, + attributesFilter, + clock, + maxCardinality, + enabled, + contextScopedAttributesFilter); } - private BoundStorageHandle doBind(Attributes attributes) { - AggregatorHandle aggregatorHandle = activeCollectionStorage.get(attributes); - if (aggregatorHandle != null && aggregatorHandle.acquire()) { - // At this moment it is guaranteed that the Bound is in the map and will not be removed. - return aggregatorHandle; + @SuppressWarnings({"rawtypes", "unchecked"}) + private Attributes getMergedContextAttributes(Attributes attributes, Context context) { + if (contextScopedAttributesFilter == null || !INCUBATOR_AVAILABLE) { + return attributes; } - - // Missing entry or no longer mapped. Try to add a new one if not exceeded cardinality limits. - aggregatorHandle = aggregator.createHandle(); - while (true) { - if (activeCollectionStorage.size() >= MAX_ACCUMULATIONS) { - logger.log( - Level.WARNING, - "Instrument " - + metricDescriptor.getSourceInstrument().getName() - + " has exceeded the maximum allowed accumulations (" - + MAX_ACCUMULATIONS - + ")."); - return NOOP_STORAGE_HANDLE; - } - AggregatorHandle boundAggregatorHandle = - activeCollectionStorage.putIfAbsent(attributes, aggregatorHandle); - if (boundAggregatorHandle != null) { - if (boundAggregatorHandle.acquire()) { - // At this moment it is guaranteed that the Bound is in the map and will not be removed. - return boundAggregatorHandle; + Attributes contextAttributes = StateIncubatingUtil.getContextAttributes(context); + if (contextAttributes.isEmpty()) { + return attributes; + } + AttributesBuilder[] builderRef = new AttributesBuilder[1]; + contextAttributes.forEach((key, value) -> { + if (contextScopedAttributesFilter.test(key)) { + if (builderRef[0] == null) { + builderRef[0] = Attributes.builder(); } - // Try to remove the boundAggregator. This will race with the collect method, but only one - // will succeed. - activeCollectionStorage.remove(attributes, boundAggregatorHandle); - continue; + builderRef[0].put((AttributeKey) key, value); } - return aggregatorHandle; + }); + AttributesBuilder builder = builderRef[0]; + if (builder == null) { + return attributes; + } + if (attributes.isEmpty()) { + return builder.build(); } + return builder.putAll(attributes).build(); } - // Overridden to make sure attributes processor can pull baggage. @Override public void recordLong(long value, Attributes attributes, Context context) { - Objects.requireNonNull(attributes, "attributes"); - attributes = attributesProcessor.process(attributes, context); - BoundStorageHandle handle = doBind(attributes); - try { - handle.recordLong(value, attributes, context); - } finally { - handle.release(); + if (!enabled) { + return; } + doRecordLong(value, getMergedContextAttributes(attributes, context), context); } - // Overridden to make sure attributes processor can pull baggage. @Override public void recordDouble(double value, Attributes attributes, Context context) { - Objects.requireNonNull(attributes, "attributes"); - attributes = attributesProcessor.process(attributes, context); - BoundStorageHandle handle = doBind(attributes); - try { - handle.recordDouble(value, attributes, context); - } finally { - handle.release(); + if (!enabled) { + return; + } + attributes = getMergedContextAttributes(attributes, context); + if (!shouldRecordDouble(value, attributes)) { + return; } + doRecordDouble(value, attributes, context); } - @Override - public MetricData collectAndReset( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - long startEpochNanos, - long epochNanos) { - // Grab accumulated measurements. - Map accumulations = new HashMap<>(); - for (Map.Entry> entry : activeCollectionStorage.entrySet()) { - boolean unmappedEntry = entry.getValue().tryUnmap(); - if (unmappedEntry) { - // If able to unmap then remove the record from the current Map. This can race with the - // acquire but because we requested a specific value only one will succeed. - activeCollectionStorage.remove(entry.getKey(), entry.getValue()); - } - T accumulation = entry.getValue().accumulateThenReset(entry.getKey()); - if (accumulation == null) { - continue; - } - accumulations.put(entry.getKey(), accumulation); + /** + * Returns true if a double {@code value} should be recorded. Returns false (dropping the + * measurement) when recording is disabled, or when {@code value} is NaN, logging in the latter + * case. Shared by the unbound and bound record paths. + */ + final boolean shouldRecordDouble(double value, Attributes attributes) { + if (!enabled) { + return false; } - - return temporalMetricStorage.buildMetricFor( - resource, instrumentationScopeInfo, accumulations, startEpochNanos, epochNanos); + if (Double.isNaN(value)) { + logger.log( + Level.FINE, + "Instrument " + + metricDescriptor.getSourceInstrument().getName() + + " has recorded measurement Not-a-Number (NaN) value with attributes " + + attributes + + ". Dropping measurement."); + return false; + } + return true; } + abstract void doRecordLong(long value, Attributes attributes, Context context); + + abstract void doRecordDouble(double value, Attributes attributes, Context context); + @Override - public MetricDescriptor getMetricDescriptor() { - return metricDescriptor; + public void setEnabled(boolean enabled) { + this.enabled = enabled; } @Override - public RegisteredReader getRegisteredReader() { - return registeredReader; + public boolean isEnabled() { + return enabled; } - /** An implementation of {@link BoundStorageHandle} that does not record. */ - private static class NoopBoundHandle implements BoundStorageHandle { - - @Override - public void recordLong(long value, Attributes attributes, Context context) {} - - @Override - public void recordDouble(double value, Attributes attributes, Context context) {} - - @Override - public void release() {} + @Override + public MetricDescriptor getMetricDescriptor() { + return metricDescriptor; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java new file mode 100644 index 00000000000..9830ca50c49 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/DeltaSynchronousMetricStorage.java @@ -0,0 +1,590 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; +import static io.opentelemetry.sdk.common.export.MemoryMode.REUSABLE_DATA; +import static io.opentelemetry.sdk.metrics.data.AggregationTemporality.DELTA; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorHandle; +import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; +import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; +import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; +import java.util.logging.Level; +import javax.annotation.Nullable; + +class DeltaSynchronousMetricStorage + extends DefaultSynchronousMetricStorage { + private final long instrumentCreationEpochNanos; + private final RegisteredReader registeredReader; + private final MemoryMode memoryMode; + + private volatile AggregatorHolder aggregatorHolder = new AggregatorHolder<>(); + // Only populated if memoryMode == REUSABLE_DATA + private volatile ConcurrentHashMap> + previousCollectionAggregatorHandles = new ConcurrentHashMap<>(); + // Only populated if memoryMode == REUSABLE_DATA + private final ArrayList reusableResultList = new ArrayList<>(); + private final ConcurrentLinkedQueue> aggregatorHandlePool = + new ConcurrentLinkedQueue<>(); + + DeltaSynchronousMetricStorage( + RegisteredReader registeredReader, + MetricDescriptor metricDescriptor, + Aggregator aggregator, + UnaryOperator attributesFilter, + Clock clock, + int maxCardinality, + boolean enabled, + @Nullable Predicate> contextScopedAttributesFilter) { + super( + metricDescriptor, + aggregator, + attributesFilter, + clock, + maxCardinality, + enabled, + contextScopedAttributesFilter); + this.instrumentCreationEpochNanos = clock.now(); + this.registeredReader = registeredReader; + this.memoryMode = registeredReader.getReader().getMemoryMode(); + } + + @Override + void doRecordLong(long value, Attributes attributes, Context context) { + DeltaAggregatorHandle handle = acquireHandleForRecord(attributes); + try { + handle.handle.recordLong(value, attributes, context); + } finally { + handle.releaseRecord(); + } + } + + @Override + void doRecordDouble(double value, Attributes attributes, Context context) { + DeltaAggregatorHandle handle = acquireHandleForRecord(attributes); + try { + handle.handle.recordDouble(value, attributes, context); + } finally { + handle.releaseRecord(); + } + } + + @SuppressWarnings("ThreadPriorityCheck") + private DeltaAggregatorHandle acquireHandleForRecord(Attributes attributes) { + while (true) { + DeltaAggregatorHandle handle = + tryAcquireHandleForRecord(this.aggregatorHolder, attributes); + if (handle != null) { + return handle; + } + // Holder or handle is locked for collection; yield to let the collector advance + Thread.yield(); + } + } + + @Nullable + private DeltaAggregatorHandle tryAcquireHandleForRecord( + AggregatorHolder holder, Attributes attributes) { + Objects.requireNonNull(attributes, "attributes"); + attributes = attributesFilter.apply(attributes); + ConcurrentHashMap> aggregatorHandles = + holder.aggregatorHandles; + DeltaAggregatorHandle handle = aggregatorHandles.get(attributes); + if (handle == null && aggregatorHandles.size() >= maxCardinality) { + logger.log( + Level.WARNING, + "Instrument " + + metricDescriptor.getSourceInstrument().getName() + + " has exceeded the maximum allowed cardinality (" + + maxCardinality + + ")."); + attributes = MetricStorage.CARDINALITY_OVERFLOW; + handle = aggregatorHandles.get(attributes); + } + if (handle != null) { + // Existing series: try to acquire a recording slot. Returns false if the collector has + // locked this handle (odd state), meaning we should retry with the new holder. + if (!handle.tryAcquireForRecord()) { + return null; + } + // Also check the holder-level gate. The collect thread sets it to locked (odd) and never + // resets it. This catches the window after the collect thread's awaitRecordersAndUnlock() + // decrements the per-handle state back to even but before collection finishes: a stale + // thread that read the old holder can still reach here with an even per-handle state. The + // hb chain (CT's holder lock β†’ CT's awaitRecordersAndUnlock() decrement β†’ this + // tryAcquireForRecord) guarantees we see the holder gate as locked at that point. + if (holder.isLockedForCollect()) { + handle.releaseRecord(); + return null; + } + return handle; + } + // New series: acquire the holder gate to coordinate with the collect thread. + // The gate ensures (a) we don't insert into a holder whose lock pass has already run, + // and (b) the per-handle pre-increment below is visible to the collect thread's lock pass. + if (!holder.tryAcquireForNewSeries()) { + return null; + } + try { + // Get handle from pool if available, else create a new one. + // Note: pooled handles retain their original creationEpochNanos, but delta storage does not + // use the handle's creation time for the start epoch β€” it uses the reader's last collect time + // directly in collect(). So the stale creation time on a recycled handle does not affect + // correctness. + DeltaAggregatorHandle newDeltaHandle = aggregatorHandlePool.poll(); + if (newDeltaHandle == null) { + newDeltaHandle = new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); + } + handle = aggregatorHandles.putIfAbsent(attributes, newDeltaHandle); + if (handle == null) { + handle = newDeltaHandle; + } + // Pre-increment per-handle state while the holder gate is still held. The collect + // thread's lock pass cannot start until all threads release the holder gate, so this + // increment is guaranteed to be observed by the lock pass before it runs. + handle.acquireForRecord(); + return handle; + } finally { + holder.releaseNewSeries(); + } + } + + @Override + public BoundStorageHandle bind(Attributes attributes) { + Attributes processed = attributesFilter.apply(attributes); + return new DeltaBoundHandle<>(bindHandle(processed), attributes); + } + + @SuppressWarnings("ThreadPriorityCheck") + private DeltaAggregatorHandle bindHandle(Attributes attributes) { + while (true) { + AggregatorHolder holder = this.aggregatorHolder; + // Always coordinate through the holder gate, even for an existing series: this serializes the + // bound flag write with collect()'s bound-handle scan (which runs while the gate is locked), + // guaranteeing the handle is carried into the new holder rather than abandoned/pooled. + if (!holder.tryAcquireForNewSeries()) { + // Holder is locked for collection. Retry; once the collector installs the new holder this + // loop re-reads it and succeeds. + Thread.yield(); + continue; + } + try { + ConcurrentHashMap> aggregatorHandles = + holder.aggregatorHandles; + DeltaAggregatorHandle handle = aggregatorHandles.get(attributes); + if (handle == null && aggregatorHandles.size() >= maxCardinality) { + logger.log( + Level.WARNING, + "Instrument " + + metricDescriptor.getSourceInstrument().getName() + + " has exceeded the maximum allowed cardinality (" + + maxCardinality + + ")."); + attributes = MetricStorage.CARDINALITY_OVERFLOW; + handle = aggregatorHandles.get(attributes); + } + if (handle == null) { + DeltaAggregatorHandle newDeltaHandle = aggregatorHandlePool.poll(); + if (newDeltaHandle == null) { + newDeltaHandle = + new DeltaAggregatorHandle<>(this, aggregator.createHandle(clock.now())); + } + DeltaAggregatorHandle existing = + aggregatorHandles.putIfAbsent(attributes, newDeltaHandle); + handle = existing != null ? existing : newDeltaHandle; + } + handle.bound = true; + return handle; + } finally { + holder.releaseNewSeries(); + } + } + } + + @Override + public MetricData collect( + Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long epochNanos) { + AggregatorHolder holder = this.aggregatorHolder; + + // Lock out new series creation (and bind()) in the old holder and wait for any in-flight + // operations to complete. Done before scanning for bound handles and before installing the new + // holder, so the bound-handle scan below sees a stable set and no bind() can land in the holder + // we are about to stop recording into. + holder.lockForCollectAndAwait(); + + // Seed the new holder with the bound handles, so that (a) the bound wrappers survive the swap + // (their bound instruments hold direct references), (b) a series recorded both bound and + // unbound continues to share one wrapper, and (c) bound series are collected every interval. + // In REUSABLE_DATA we ping-pong between two maps, so the bound wrappers are copied into the + // next + // map; in IMMUTABLE_DATA the old map is abandoned and the new map starts with only the bound + // wrappers. + ConcurrentHashMap> newHolderHandles = + (memoryMode == REUSABLE_DATA) + ? previousCollectionAggregatorHandles + : new ConcurrentHashMap<>(); + holder.aggregatorHandles.forEach((attributes, handle) -> { + if (handle.bound) { + newHolderHandles.put(attributes, handle); + } + }); + this.aggregatorHolder = new AggregatorHolder<>(newHolderHandles); + + ConcurrentHashMap> aggregatorHandles = + holder.aggregatorHandles; + + // Lock and drain unbound handles (unchanged from the unbound-only path). Bound handles are + // handled separately below with a tight per-handle lock window so that recording to a bound + // series never blocks for the duration of the whole collection. + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.bound) { + handle.lockForCollect(); + } + }); + aggregatorHandles.forEach((attributes, handle) -> { + if (!handle.bound) { + handle.awaitRecordersAndUnlock(); + } + }); + + List points; + if (memoryMode == REUSABLE_DATA) { + reusableResultList.clear(); + points = reusableResultList; + } else { + points = new ArrayList<>(aggregatorHandles.size()); + } + + // In DELTA aggregation temporality each Attributes is reset to 0 + // every time we perform a collection (by definition of DELTA). + // In IMMUTABLE_DATA MemoryMode, this is accomplished by swapping in a new empty holder, + // abandoning the old map so each new recording in the next interval starts fresh from 0. + // In REUSABLE_DATA MemoryMode, we strive for zero allocations. Since even removing + // a key-value from a map and putting it again on next recording will cost an allocation, + // we are keeping the aggregator handles in their map, and only reset their value once + // we finish collecting the aggregated value from each one. + // The SDK must adhere to keeping no more than maxCardinality unique Attributes in memory, + // hence during collect(), when the map is at full capacity, we try to clear away unused + // aggregator handles, so on next recording cycle using this map, there will be room for newly + // recorded Attributes. This comes at the expanse of memory allocations. This can be avoided + // if the user chooses to increase the maxCardinality. + // Bound handles are kept unconditionally since their bound instruments hold direct references. + if (memoryMode == REUSABLE_DATA) { + if (aggregatorHandles.size() >= maxCardinality) { + aggregatorHandles.forEach((attribute, handle) -> { + if (!handle.bound && !handle.handle.hasRecordedValues()) { + aggregatorHandles.remove(attribute); + } + }); + } + } + + // Start time for synchronous delta instruments is the time of the last collection, or if no + // collection has yet taken place, the time the instrument was created. + long startEpochNanos = + registeredReader.getLastCollectEpochNanosOrDefault(instrumentCreationEpochNanos); + + // Grab aggregated points. + aggregatorHandles.forEach((attributes, handle) -> { + if (handle.bound) { + collectBound(handle, attributes, startEpochNanos, epochNanos, points); + return; + } + if (!handle.handle.hasRecordedValues()) { + return; + } + T point = + handle.handle.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + + if (memoryMode == IMMUTABLE_DATA) { + // Return the handle to the pool. + // Only in IMMUTABLE_DATA memory mode: in REUSABLE_DATA we avoid using the pool + // since ConcurrentLinkedQueue.offer() allocates memory internally. + aggregatorHandlePool.offer(handle); + } + + if (point != null) { + points.add(point); + } + }); + + if (memoryMode == REUSABLE_DATA) { + previousCollectionAggregatorHandles = aggregatorHandles; + } + + if (points.isEmpty() || !enabled) { + return EmptyMetricData.getInstance(); + } + + return aggregator.toMetricData( + resource, instrumentationScopeInfo, metricDescriptor, points, DELTA); + } + + /** + * Collects a bound handle by rotation: drain in-flight recorders, swap in a fresh (already-zero) + * accumulator while locked, unlock so recorders resume on the fresh accumulator, then aggregate + * the drained accumulator off the lock (no recorders reference it anymore). The two accumulators + * are ping-ponged via {@link DeltaAggregatorHandle#spare} so steady-state collection allocates + * nothing. + */ + private void collectBound( + DeltaAggregatorHandle handle, + Attributes attributes, + long startEpochNanos, + long epochNanos, + List points) { + handle.lockForCollect(); + handle.awaitRecorders(); + if (!handle.handle.hasRecordedValues()) { + // Nothing recorded this interval; no rotation needed. + handle.unlockAfterCollect(); + return; + } + AggregatorHandle collected = handle.handle; + AggregatorHandle next = handle.spare; + if (next == null) { + next = aggregator.createHandle(clock.now()); + } + handle.handle = next; // recorders resuming after unlock see the zero accumulator + handle.spare = collected; + handle.unlockAfterCollect(); + // Aggregate (and reset) the drained accumulator off the lock; it becomes the spare for the next + // rotation. + T point = + collected.aggregateThenMaybeReset( + startEpochNanos, epochNanos, attributes, /* reset= */ true); + if (point != null) { + points.add(point); + } + } + + private static class AggregatorHolder { + private final ConcurrentHashMap> aggregatorHandles; + // Guards new-series creation using an even/odd protocol: + // - Threads creating a new series increment by 2 (keeping the value even while unlocked) + // and decrement by 2 on release. + // - The collect thread increments by 1 (making the value odd) to lock out new-series + // creation, then waits for the value to return to 1 (no threads in-flight). + private final AtomicInteger newSeriesGate = new AtomicInteger(0); + + private AggregatorHolder() { + aggregatorHandles = new ConcurrentHashMap<>(); + } + + private AggregatorHolder( + ConcurrentHashMap> aggregatorHandles) { + this.aggregatorHandles = aggregatorHandles; + } + + /** Returns true and acquires the gate if not locked for collection. */ + boolean tryAcquireForNewSeries() { + int s = newSeriesGate.addAndGet(2); + if ((s & 1) != 0) { + newSeriesGate.addAndGet(-2); + return false; + } + return true; + } + + /** Releases the gate acquired via {@link #tryAcquireForNewSeries()}. */ + void releaseNewSeries() { + newSeriesGate.addAndGet(-2); + } + + /** Returns true if the collector has locked this holder against new-series creation. */ + boolean isLockedForCollect() { + return (newSeriesGate.get() & 1) != 0; + } + + /** Locks new-series creation and waits for any in-flight new-series operations to complete. */ + @SuppressWarnings("ThreadPriorityCheck") + void lockForCollectAndAwait() { + int s = newSeriesGate.addAndGet(1); + while (s != 1) { + Thread.yield(); + s = newSeriesGate.get(); + } + } + } + + /** + * Holds each binding's own attributes and delegates to the shared {@link DeltaAggregatorHandle}. + * Distinct bindings can collapse to the same handle (e.g. a view drops an attribute, or + * cardinality overflow), so attributes are kept per-bind here rather than on the shared handle, + * where a later binding would overwrite them. + */ + private static final class DeltaBoundHandle implements BoundStorageHandle { + private final DeltaAggregatorHandle handle; + private final Attributes attributes; + + DeltaBoundHandle(DeltaAggregatorHandle handle, Attributes attributes) { + this.handle = handle; + this.attributes = attributes; + } + + @Override + public void recordLong(long value, Context context) { + handle.recordLong(value, attributes, context); + } + + @Override + public void recordDouble(double value, Context context) { + handle.recordDouble(value, attributes, context); + } + } + + private static final class DeltaAggregatorHandle { + // The storage this handle belongs to. Used by the bound record path (via DeltaBoundHandle) to + // reach the storage-level enabled / NaN checks. Kept as an explicit back-reference rather than + // making this a non-static inner class, which would force AggregatorHolder to be non-static + // too. + private final DeltaSynchronousMetricStorage storage; + // Rotated by the collector for bound series (a fresh, already-zero handle swapped in while + // recorders are drained); write-once for unbound series. Not volatile: the per-handle `state` + // gate carries visibility β€” every read is preceded by a `state` acquire and every rotation + // write + // followed by a `state` release. INVARIANT: never read `handle` outside the gate. + AggregatorHandle handle; + // The off-duty accumulator used for bound rotation, ping-ponged with {@link #handle} each + // collect. Touched only by the (serialized) collector; volatile to publish across collect + // cycles. Always null for unbound handles. + @Nullable private volatile AggregatorHandle spare; + // True once this series has been bound. Bound wrappers are carried across holder swaps (never + // pooled) and rotated rather than reset in place. Written under the holder gate by bind(), read + // by the collector. + private volatile boolean bound; + // Guards per-handle recording using the same even/odd protocol as + // AggregatorHolder.newSeriesGate, + // but scoped to a single series: + // - Recording threads increment by 2 before recording, decrement by 2 when done. + // - The collect thread increments by 1 (making the count odd) as a signal that this + // handle is being collected; recorders that observe an odd count release and retry. + // - Once all in-flight recordings finish the count returns to 1, and the collect + // thread decrements by 1 to restore it to even for the next cycle. + private final AtomicInteger state = new AtomicInteger(0); + + DeltaAggregatorHandle(DeltaSynchronousMetricStorage storage, AggregatorHandle handle) { + this.storage = storage; + this.handle = handle; + } + + /** + * The bound record path, called by {@link DeltaBoundHandle} with its per-bind attributes. + * Records onto the current accumulator via the per-handle gate β€” no map lookup and no holder + * coordination, since the handle already exists and is carried across holders. Spins if the + * collector currently holds the lock. + */ + @SuppressWarnings("ThreadPriorityCheck") + void recordLong(long value, Attributes attributes, Context context) { + if (!storage.isEnabled()) { + return; + } + while (!tryAcquireForRecord()) { + Thread.yield(); + } + try { + handle.recordLong(value, attributes, context); + } finally { + releaseRecord(); + } + } + + @SuppressWarnings("ThreadPriorityCheck") + void recordDouble(double value, Attributes attributes, Context context) { + if (!storage.shouldRecordDouble(value, attributes)) { + return; + } + while (!tryAcquireForRecord()) { + Thread.yield(); + } + try { + handle.recordDouble(value, attributes, context); + } finally { + releaseRecord(); + } + } + + /** + * Tries to acquire a recording slot. Returns false if the collector has locked this handle (odd + * state); the caller should retry with a fresh holder. + */ + boolean tryAcquireForRecord() { + int s = state.addAndGet(2); + if ((s & 1) != 0) { + state.addAndGet(-2); + return false; + } + return true; + } + + /** + * Acquires a recording slot unconditionally. Only safe to call while the holder gate is held, + * which prevents the collector from starting its lock pass. + */ + void acquireForRecord() { + state.addAndGet(2); + } + + /** + * Releases a recording slot acquired via {@link #tryAcquireForRecord()} or {@link + * #acquireForRecord()}. + */ + void releaseRecord() { + state.addAndGet(-2); + } + + /** Signals that collection is starting. Recorders that observe this will abort and retry. */ + void lockForCollect() { + state.addAndGet(1); + } + + /** Waits for all in-flight recorders to finish, then clears the collection lock. */ + @SuppressWarnings("ThreadPriorityCheck") + void awaitRecordersAndUnlock() { + while (state.get() > 1) { + Thread.yield(); + } + state.addAndGet(-1); + } + + /** + * Waits for all in-flight recorders to finish but leaves the handle locked. Used by the bound + * rotation path, which swaps the accumulator before unlocking via {@link + * #unlockAfterCollect()}. + */ + @SuppressWarnings("ThreadPriorityCheck") + void awaitRecorders() { + while (state.get() > 1) { + Thread.yield(); + } + } + + /** Clears the collection lock set by {@link #lockForCollect()}. */ + void unlockAfterCollect() { + state.addAndGet(-1); + } + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/EmptyMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/EmptyMetricStorage.java index 15ba0fd4afc..857b911119e 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/EmptyMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/EmptyMetricStorage.java @@ -7,16 +7,10 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.CollectionRegistration; -import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import io.opentelemetry.sdk.resources.Resource; final class EmptyMetricStorage implements SynchronousMetricStorage { @@ -25,38 +19,6 @@ final class EmptyMetricStorage implements SynchronousMetricStorage { private EmptyMetricStorage() {} private final MetricDescriptor descriptor = MetricDescriptor.create("", "", ""); - private final BoundStorageHandle emptyHandle = - new BoundStorageHandle() { - @Override - public void recordLong(long value, Attributes attributes, Context context) {} - - @Override - public void recordDouble(double value, Attributes attributes, Context context) {} - - @Override - public void release() {} - }; - private final MetricReader emptyReader = - new MetricReader() { - @Override - public void register(CollectionRegistration registration) {} - - @Override - public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return AggregationTemporality.CUMULATIVE; - } - - @Override - public CompletableResultCode forceFlush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - return CompletableResultCode.ofFailure(); - } - }; - private final RegisteredReader registeredReader = RegisteredReader.create(emptyReader); @Override public MetricDescriptor getMetricDescriptor() { @@ -64,21 +26,38 @@ public MetricDescriptor getMetricDescriptor() { } @Override - public RegisteredReader getRegisteredReader() { - return registeredReader; + public MetricData collect( + Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long epochNanos) { + return EmptyMetricData.getInstance(); } + @Override + public void recordLong(long value, Attributes attributes, Context context) {} + + @Override + public void recordDouble(double value, Attributes attributes, Context context) {} + @Override public BoundStorageHandle bind(Attributes attributes) { - return emptyHandle; + return NOOP_BOUND_HANDLE; } + private static final BoundStorageHandle NOOP_BOUND_HANDLE = + new BoundStorageHandle() { + @Override + public void recordLong(long value, Context context) {} + + @Override + public void recordDouble(double value, Context context) {} + }; + @Override - public MetricData collectAndReset( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - long startEpochNanos, - long epochNanos) { - return EmptyMetricData.getInstance(); + public boolean isEnabled() { + return false; + } + + @Override + public void setEnabled(boolean enabled) { + // do nothing } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounter.java deleted file mode 100644 index 4b89f53ef2d..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -/** - * Interface for use as backing data structure for exponential histogram buckets. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface ExponentialCounter { - /** - * The first index with a recording. May be negative. - * - *

      Note: the returned value is not meaningful when isEmpty returns true. - * - * @return the first index with a recording. - */ - int getIndexStart(); - - /** - * The last index with a recording. May be negative. - * - *

      Note: the returned value is not meaningful when isEmpty returns true. - * - * @return The last index with a recording. - */ - int getIndexEnd(); - - /** - * Persist new data at index, incrementing by delta amount. - * - * @param index The index of where to perform the incrementation. - * @param delta How much to increment the index by. - * @return success status. - */ - boolean increment(int index, long delta); - - /** - * Get the number of recordings for the given index. - * - * @return the number of recordings for the index, or 0 if the index is out of bounds. - */ - long get(int index); - - /** - * Boolean denoting if the backing structure has recordings or not. - * - * @return true if no recordings, false if at least one recording. - */ - boolean isEmpty(); - - /** Returns the maximum number of buckets allowed in this counter. */ - int getMaxSize(); - - /** Resets all bucket counts to zero and resets index start/end tracking. */ - void clear(); -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounterFactory.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounterFactory.java deleted file mode 100644 index 9c649eed748..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounterFactory.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -/** - * Interface for constructing backing data structure for exponential histogram buckets. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface ExponentialCounterFactory { - /** - * Constructs a new {@link io.opentelemetry.sdk.metrics.internal.state.ExponentialCounter} with - * maximum bucket size. - * - * @param maxSize The maximum number of buckets allowed in the counter. - */ - ExponentialCounter newCounter(int maxSize); - - /** Returns a deep-copy of an ExponentialCounter. */ - ExponentialCounter copy(ExponentialCounter other); - - /** Constructs exponential counters using {@link MapCounter}. */ - static ExponentialCounterFactory mapCounter() { - return new ExponentialCounterFactory() { - @Override - public ExponentialCounter newCounter(int maxSize) { - return new MapCounter(maxSize); - } - - @Override - public ExponentialCounter copy(ExponentialCounter other) { - return new MapCounter(other); - } - - @Override - public String toString() { - return "mapCounter"; - } - }; - } - /** Constructs exponential counters using {@link AdaptingCircularBufferCounter}. */ - static ExponentialCounterFactory circularBufferCounter() { - return new ExponentialCounterFactory() { - @Override - public ExponentialCounter newCounter(int maxSize) { - return new AdaptingCircularBufferCounter(maxSize); - } - - @Override - public ExponentialCounter copy(ExponentialCounter other) { - return new AdaptingCircularBufferCounter(other); - } - - @Override - public String toString() { - return "circularBufferCounter"; - } - }; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MapCounter.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MapCounter.java deleted file mode 100644 index 7c6c99b12c9..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MapCounter.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import java.util.Collections; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicLong; - -/** - * Simple-as-possible backing structure for exponential histogram buckets. Can be used as a baseline - * against other data structures. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time - */ -public class MapCounter implements ExponentialCounter { - private static final int NULL_INDEX = Integer.MIN_VALUE; - - private final int maxSize; - private final Map backing; - private int indexStart; - private int indexEnd; - - /** Instantiate a MapCounter. */ - public MapCounter(int maxSize) { - this.maxSize = maxSize; - this.backing = new ConcurrentHashMap<>((int) Math.ceil(maxSize / 0.75) + 1); - this.indexEnd = NULL_INDEX; - this.indexStart = NULL_INDEX; - } - - /** - * Create an independent copy of another ExponentialCounter. - * - * @param otherCounter another exponential counter to make a deep copy of. - */ - public MapCounter(ExponentialCounter otherCounter) { - this.maxSize = otherCounter.getMaxSize(); - this.backing = new ConcurrentHashMap<>((int) Math.ceil(maxSize / 0.75) + 1); - this.indexStart = otherCounter.getIndexStart(); - this.indexEnd = otherCounter.getIndexEnd(); - - // copy values - for (int i = indexStart; i <= indexEnd; i++) { - long val = otherCounter.get(i); - if (val != 0) { - this.backing.put(i, new AtomicLong(val)); - } - } - } - - @Override - public int getIndexStart() { - return indexStart; - } - - @Override - public int getIndexEnd() { - return indexEnd; - } - - @Override - public boolean increment(int index, long delta) { - if (indexStart == NULL_INDEX) { - indexStart = index; - indexEnd = index; - doIncrement(index, delta); - return true; - } - - // Extend window if possible. if it would exceed maxSize, then return false. - if (index > indexEnd) { - if ((long) index - indexStart + 1 > maxSize) { - return false; - } - indexEnd = index; - } else if (index < indexStart) { - if ((long) indexEnd - index + 1 > maxSize) { - return false; - } - indexStart = index; - } - - doIncrement(index, delta); - return true; - } - - @Override - public long get(int index) { - if (index < indexStart || index > indexEnd) { - return 0; - } - AtomicLong result = backing.get(index); - if (result == null) { - return 0; - } - return result.longValue(); - } - - @Override - public boolean isEmpty() { - return backing.isEmpty(); - } - - @Override - public int getMaxSize() { - return maxSize; - } - - @Override - public void clear() { - this.backing.clear(); - this.indexStart = NULL_INDEX; - this.indexEnd = NULL_INDEX; - } - - private synchronized void doIncrement(int index, long delta) { - long prevValue = backing.computeIfAbsent(index, k -> new AtomicLong(0)).getAndAdd(delta); - - // in the case of a decrement result may be 0, so we remove the entry - if (prevValue + delta == 0) { - backing.remove(index); - if (isEmpty()) { - indexStart = NULL_INDEX; - indexEnd = NULL_INDEX; - } else { - // find largest and smallest index to remap window - indexStart = Collections.min(backing.keySet()); - indexEnd = Collections.max(backing.keySet()); - } - } - } - - @Override - public String toString() { - return backing.toString(); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterProviderSharedState.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterProviderSharedState.java index 28353e87763..990b5c12ccd 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterProviderSharedState.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterProviderSharedState.java @@ -6,14 +6,19 @@ package io.opentelemetry.sdk.metrics.internal.state; import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.util.function.BiPredicate; +import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; /** - * State for a {@code MeterProvider}. + * State for a {@link SdkMeterProvider}. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. @@ -21,33 +26,38 @@ @AutoValue @Immutable public abstract class MeterProviderSharedState { + public static MeterProviderSharedState create( Clock clock, - Resource resource, - ViewRegistry viewRegistry, - ExemplarFilter exemplarFilter, - long startEpochNanos) { + SdkResourceProvider resourceProvider, + ExemplarFilterInternal exemplarFilter, + @Nullable + BiPredicate> contextScopedAttributesFilter) { return new AutoValue_MeterProviderSharedState( - clock, resource, viewRegistry, startEpochNanos, exemplarFilter); + clock, resourceProvider, exemplarFilter, contextScopedAttributesFilter); } MeterProviderSharedState() {} - /** Returns the clock used for measurements. */ + /** Returns the {@link Clock} used for measurements. */ public abstract Clock getClock(); + /** Returns the {@link SdkResourceProvider} used to resolve the attached {@link Resource}. */ + public abstract SdkResourceProvider getSdkResourceProvider(); + /** Returns the {@link Resource} to attach telemetry to. */ - public abstract Resource getResource(); + public Resource getResource() { + return getSdkResourceProvider().getResource(); + } - /** Returns the {@link ViewRegistry} for custom aggregation and metric definitions. */ - public abstract ViewRegistry getViewRegistry(); + /** Returns the {@link ExemplarFilterInternal} for remembering measurements. */ + public abstract ExemplarFilterInternal getExemplarFilter(); /** - * Returns the timestamp when this {@code MeterProvider} was started, in nanoseconds since Unix - * epoch time. + * Returns the filter predicate to determine which context-scoped attributes are inherited by + * synchronous metric measurements, or {@code null} if disabled. */ - public abstract long getStartEpochNanos(); - - /** Returns the {@link ExemplarFilter} for remembering synchronous measurements. */ - abstract ExemplarFilter getExemplarFilter(); + @Nullable + public abstract BiPredicate> + getContextScopedAttributesFilter(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterSharedState.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterSharedState.java deleted file mode 100644 index d174504e98f..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MeterSharedState.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import static java.util.stream.Collectors.toMap; - -import io.opentelemetry.api.internal.GuardedBy; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.function.Function; - -/** - * State for a {@code Meter}. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public class MeterSharedState { - - private final Object collectLock = new Object(); - private final Object callbackLock = new Object(); - - @GuardedBy("callbackLock") - private final List callbackRegistrations = new ArrayList<>(); - - private final Map readerStorageRegistries; - - private final InstrumentationScopeInfo instrumentationScopeInfo; - - private MeterSharedState( - InstrumentationScopeInfo instrumentationScopeInfo, List registeredReaders) { - this.instrumentationScopeInfo = instrumentationScopeInfo; - this.readerStorageRegistries = - registeredReaders.stream() - .collect(toMap(Function.identity(), unused -> new MetricStorageRegistry())); - } - - public static MeterSharedState create( - InstrumentationScopeInfo instrumentationScopeInfo, List registeredReaders) { - return new MeterSharedState(instrumentationScopeInfo, registeredReaders); - } - - /** - * Unregister the callback. - * - *

      Callbacks are originally registered via {@link #registerCallback(CallbackRegistration)}. - */ - public void removeCallback(CallbackRegistration callbackRegistration) { - synchronized (callbackLock) { - this.callbackRegistrations.remove(callbackRegistration); - } - } - - /** - * Register the callback. - * - *

      The callback will be invoked once per collection until unregistered via {@link - * #removeCallback(CallbackRegistration)}. - */ - public final void registerCallback(CallbackRegistration callbackRegistration) { - synchronized (callbackLock) { - callbackRegistrations.add(callbackRegistration); - } - } - - // only visible for testing. - /** Returns the {@link InstrumentationScopeInfo} for this {@code Meter}. */ - public InstrumentationScopeInfo getInstrumentationScopeInfo() { - return instrumentationScopeInfo; - } - - /** Collects all accumulated metric stream points. */ - public List collectAll( - RegisteredReader registeredReader, - MeterProviderSharedState meterProviderSharedState, - long epochNanos) { - List currentRegisteredCallbacks; - synchronized (callbackLock) { - currentRegisteredCallbacks = new ArrayList<>(callbackRegistrations); - } - // Collections across all readers are sequential - synchronized (collectLock) { - for (CallbackRegistration callbackRegistration : currentRegisteredCallbacks) { - callbackRegistration.invokeCallback(registeredReader); - } - - Collection storages = - Objects.requireNonNull(readerStorageRegistries.get(registeredReader)).getStorages(); - List result = new ArrayList<>(storages.size()); - for (MetricStorage storage : storages) { - MetricData current = - storage.collectAndReset( - meterProviderSharedState.getResource(), - getInstrumentationScopeInfo(), - meterProviderSharedState.getStartEpochNanos(), - epochNanos); - // Ignore if the metric data doesn't have any data points, for example when aggregation is - // Aggregation#drop() - if (!current.isEmpty()) { - result.add(current); - } - } - return result; - } - } - - /** Reset the meter state, clearing all registered callbacks and storages. */ - public void resetForTest() { - synchronized (collectLock) { - synchronized (callbackLock) { - callbackRegistrations.clear(); - } - this.readerStorageRegistries.values().forEach(MetricStorageRegistry::resetForTest); - } - } - - /** Registers new synchronous storage associated with a given instrument. */ - public final WriteableMetricStorage registerSynchronousMetricStorage( - InstrumentDescriptor instrument, MeterProviderSharedState meterProviderSharedState) { - - List registeredStorages = new ArrayList<>(); - for (RegisteredView registeredView : - meterProviderSharedState - .getViewRegistry() - .findViews(instrument, getInstrumentationScopeInfo())) { - if (Aggregation.drop() == registeredView.getView().getAggregation()) { - continue; - } - for (Map.Entry entry : - readerStorageRegistries.entrySet()) { - RegisteredReader reader = entry.getKey(); - MetricStorageRegistry registry = entry.getValue(); - registeredStorages.add( - registry.register( - SynchronousMetricStorage.create( - reader, - registeredView, - instrument, - meterProviderSharedState.getExemplarFilter()))); - } - } - - if (registeredStorages.size() == 1) { - return registeredStorages.get(0); - } - - return new MultiWritableMetricStorage(registeredStorages); - } - - /** Register new asynchronous storage associated with a given instrument. */ - public final SdkObservableMeasurement registerObservableMeasurement( - InstrumentDescriptor instrumentDescriptor, - MeterProviderSharedState meterProviderSharedState) { - - List> registeredStorages = new ArrayList<>(); - for (RegisteredView registeredView : - meterProviderSharedState - .getViewRegistry() - .findViews(instrumentDescriptor, getInstrumentationScopeInfo())) { - if (Aggregation.drop() == registeredView.getView().getAggregation()) { - continue; - } - for (Map.Entry entry : - readerStorageRegistries.entrySet()) { - RegisteredReader reader = entry.getKey(); - MetricStorageRegistry registry = entry.getValue(); - registeredStorages.add( - registry.register( - AsynchronousMetricStorage.create(reader, registeredView, instrumentDescriptor))); - } - } - - return SdkObservableMeasurement.create( - instrumentationScopeInfo, instrumentDescriptor, registeredStorages); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorage.java index 86d9aa201b0..b4ff10922fc 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorage.java @@ -5,10 +5,11 @@ package io.opentelemetry.sdk.metrics.internal.state; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import io.opentelemetry.sdk.resources.Resource; /** @@ -19,38 +20,29 @@ */ public interface MetricStorage { + /** The default max number of distinct metric points for a particular {@link MetricStorage}. */ + int DEFAULT_MAX_CARDINALITY = 2000; + + /** Attributes capturing overflow measurements recorded when cardinality limit is exceeded. */ + Attributes CARDINALITY_OVERFLOW = Attributes.builder().put("otel.metric.overflow", true).build(); + /** Returns a description of the metric produced in this storage. */ MetricDescriptor getMetricDescriptor(); - /** Returns the registered reader this storage is associated with. */ - RegisteredReader getRegisteredReader(); - /** - * Collects the metrics from this storage and resets for the next collection period. + * Collects the metrics from this storage. If storing {@link AggregationTemporality#DELTA} + * metrics, reset for the next collection period. * *

      Note: This is a stateful operation and will reset any interval-related state for the {@code * collector}. * * @param resource The resource associated with the metrics. * @param instrumentationScopeInfo The instrumentation scope generating the metrics. - * @param startEpochNanos The start timestamp for this SDK. * @param epochNanos The timestamp for this collection. * @return The {@link MetricData} from this collection period. */ - MetricData collectAndReset( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - long startEpochNanos, - long epochNanos); + MetricData collect( + Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long epochNanos); - /** - * Determines whether this storage is an empty metric storage. - * - *

      Uses the reference comparison since {@link EmptyMetricStorage} is singleton. - * - * @return true if is empty. - */ - default boolean isEmpty() { - return this == EmptyMetricStorage.INSTANCE; - } + void setEnabled(boolean enabled); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistry.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistry.java index 62684c27a5c..9ebb3538f47 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistry.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistry.java @@ -22,9 +22,10 @@ * *

      Each descriptor in the registry results in an exported metric stream. Under normal * circumstances each descriptor shares a unique {@link MetricDescriptor#getName()}. When multiple - * descriptors share the same name, an identity conflict has occurred. The registry detects identity - * conflicts on {@link #register(MetricStorage)} and logs diagnostic information when they occur. - * See {@link MetricDescriptor#isCompatibleWith(MetricDescriptor)} for definition of compatibility. + * descriptors share the same name, but have some difference in identifying fields, an identity + * conflict has occurred. The registry detects identity conflicts on {@link + * #register(MetricStorage)} and logs diagnostic information when they occur. See {@link + * MetricDescriptor#equals(Object)} for definition of identity equality. * *

      This class is internal and is hence not for public use. Its APIs are unstable and can change * at any time. @@ -54,7 +55,7 @@ public Collection getStorages() { * @return the {@code newStorage} if no compatible metric is already registered, otherwise the * previously registered storage. */ - @SuppressWarnings("unchecked") + @SuppressWarnings({"unchecked", "ReferenceEquality"}) public I register(I newStorage) { MetricDescriptor descriptor = newStorage.getMetricDescriptor(); I oldOrNewStorage; @@ -75,9 +76,9 @@ public I register(I newStorage) { continue; } MetricDescriptor existing = storage.getMetricDescriptor(); + // TODO: consider this alternative // Check compatibility of metrics which share the same case-insensitive name - if (existing.getName().equalsIgnoreCase(descriptor.getName()) - && !existing.isCompatibleWith(descriptor)) { + if (existing.getName().equalsIgnoreCase(descriptor.getName())) { logger.log(Level.WARNING, DebugUtils.duplicateMetricErrorMessage(existing, descriptor)); break; // Only log information about the first conflict found to reduce noise } @@ -87,7 +88,7 @@ public I register(I newStorage) { } /** Reset the storage registry, clearing all storages. */ - void resetForTest() { + public void resetForTest() { synchronized (lock) { registry.clear(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageUtils.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageUtils.java deleted file mode 100644 index 3c8f1f32e2d..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageUtils.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; -import java.util.Map; -import java.util.function.BiFunction; - -/** Utilities to help deal w/ {@code Map} in metric storage. */ -final class MetricStorageUtils { - /** The max number of metric accumulations for a particular {@link MetricStorage}. */ - static final int MAX_ACCUMULATIONS = 2000; - - private MetricStorageUtils() {} - - /** - * Merges accumulations from {@code toMerge} into {@code result}. Keys from {@code result} which - * don't appear in {@code toMerge} are removed. - * - *

      Note: This mutates the result map. - */ - static void mergeInPlace( - Map result, Map toMerge, Aggregator aggregator) { - blend(result, toMerge, /* preserve= */ false, aggregator::merge); - } - - /** - * Merges accumulations from {@code toMerge} into {@code result}. Keys from {@code result} which - * don't appear in {@code toMerge} are preserved as-is. - * - *

      Note: This mutates the result map. - */ - static void mergeAndPreserveInPlace( - Map result, Map toMerge, Aggregator aggregator) { - blend(result, toMerge, /* preserve= */ true, aggregator::merge); - } - - /** - * Diffs accumulations from {@code toMerge} into {@code result}. Keys from {@code result} which - * don't appear in {@code toMerge} are removed. - * - *

      If no prior value is found, then the value from {@code toDiff} is used. - * - *

      Note: This mutates the result map. - */ - static void diffInPlace( - Map result, Map toDiff, Aggregator aggregator) { - blend(result, toDiff, /* preserve= */ false, aggregator::diff); - } - - private static void blend( - Map result, - Map toMerge, - boolean preserve, - BiFunction blendFunction) { - if (!preserve) { - removeUnseen(result, toMerge); - } - toMerge.forEach( - (k, v) -> result.compute(k, (k2, v2) -> (v2 != null) ? blendFunction.apply(v2, v) : v)); - } - - /** - * Removes all keys in {@code result} that do not exist in {@code latest}. - * - *

      Note: This mutates the result map. - */ - public static void removeUnseen(Map result, Map latest) { - result.entrySet().removeIf(entry -> !latest.containsKey(entry.getKey())); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MultiBoundStorageHandle.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MultiBoundStorageHandle.java deleted file mode 100644 index 0d374eab89c..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MultiBoundStorageHandle.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import java.util.List; - -/** Storage handle that aggregates across several instances. */ -class MultiBoundStorageHandle implements BoundStorageHandle { - private final List underlyingHandles; - - MultiBoundStorageHandle(List handles) { - this.underlyingHandles = handles; - } - - @Override - public void recordLong(long value, Attributes attributes, Context context) { - for (BoundStorageHandle handle : underlyingHandles) { - handle.recordLong(value, attributes, context); - } - } - - @Override - public void recordDouble(double value, Attributes attributes, Context context) { - for (BoundStorageHandle handle : underlyingHandles) { - handle.recordDouble(value, attributes, context); - } - } - - @Override - public void release() { - for (BoundStorageHandle handle : underlyingHandles) { - handle.release(); - } - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MultiWritableMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MultiWritableMetricStorage.java deleted file mode 100644 index 9046c9b66d5..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/MultiWritableMetricStorage.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import io.opentelemetry.api.common.Attributes; -import java.util.ArrayList; -import java.util.List; - -class MultiWritableMetricStorage implements WriteableMetricStorage { - private final List underlyingMetrics; - - MultiWritableMetricStorage(List metrics) { - this.underlyingMetrics = metrics; - } - - @Override - public BoundStorageHandle bind(Attributes attributes) { - List handles = new ArrayList<>(underlyingMetrics.size()); - for (WriteableMetricStorage metric : underlyingMetrics) { - handles.add(metric.bind(attributes)); - } - return new MultiBoundStorageHandle(handles); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ObjectPool.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ObjectPool.java new file mode 100644 index 00000000000..8be6abcb5dd --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/ObjectPool.java @@ -0,0 +1,53 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import java.util.function.Supplier; + +/** + * A pool of objects of type {@code T}. + * + *

      When an object is borrowed from an empty pool, an object will be created by the supplied + * {@code objectCreator} and returned immediately. When the pool is not empty, an object is removed + * from the pool and returned. The user is expected to return the object to the pool when it is no + * longer used. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + */ +public final class ObjectPool { + private final ArrayBasedStack pool; + private final Supplier objectCreator; + + /** + * Constructs an object pool. + * + * @param objectCreator Supplier used to create an object when the pool is empty + */ + public ObjectPool(Supplier objectCreator) { + this.pool = new ArrayBasedStack<>(); + this.objectCreator = objectCreator; + } + + /** + * Gets an object from the pool. + * + * @return An object from the pool, or a new object if the pool is empty + */ + public T borrowObject() { + T object = pool.pop(); + if (object == null) { + object = objectCreator.get(); + } + return object; + } + + public void returnObject(T object) { + pool.push(object); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMap.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMap.java new file mode 100644 index 00000000000..ceb5878c79c --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMap.java @@ -0,0 +1,269 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static java.util.Objects.requireNonNull; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; + +/** + * A bucket-based hash map with an internal re-usable map entry objects pool. + * + *

      The goal of this map is to minimize memory allocation, leading to reduced time spent in + * garbage collection. + * + *

      This map avoids allocating a new map entry on each put operation by maintaining a pool of + * reusable (mutable) map entries and borrowing a map entry object from the pool to hold the given + * key-value of the put operation. The borrowed object is returned to the pool when the map entry + * key is removed from the map. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + * + *

      This class is not thread-safe. + * + * @param The map key type + * @param The map value type + */ +@SuppressWarnings("ForLoopReplaceableByForEach") +public final class PooledHashMap implements Map { + private static final int DEFAULT_CAPACITY = 16; + private static final float LOAD_FACTOR = 0.75f; + + private ArrayList>[] table; + private final ObjectPool> entryPool; + private int size; + + /** + * Creates a {@link PooledHashMap} with {@code capacity} buckets. + * + *

      The hashmap contains an array of buckets, each is an array-list of items. The number of + * buckets expands over time to avoid having too many items in one bucket, otherwise accessing an + * item by key won't be a constant time complexity. + * + * @param capacity The initial number of buckets to start with + */ + @SuppressWarnings({"unchecked"}) + public PooledHashMap(int capacity) { + this.table = (ArrayList>[]) new ArrayList[capacity]; + this.entryPool = new ObjectPool<>(Entry::new); + this.size = 0; + } + + /** + * Creates a new {@link PooledHashMap} with a default amount of buckets (capacity). + * + * @see PooledHashMap#PooledHashMap(int) + */ + public PooledHashMap() { + this(DEFAULT_CAPACITY); + } + + /** + * Add a key, value pair to the map. + * + *

      Internally it uses a MapEntry from a pool of entries, to store this mapping + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + * @return Null if the was no previous mapping for this key, or the value of the previous mapping + * of this key + */ + @Override + @Nullable + public V put(K key, V value) { + requireNonNull(key, "This map does not support null keys"); + requireNonNull(value, "This map does not support null values"); + if (size > LOAD_FACTOR * table.length) { + rehash(); + } + + int bucket = getBucket(key); + ArrayList> entries = table[bucket]; + if (entries == null) { + entries = new ArrayList<>(); + table[bucket] = entries; + } else { + // Don't optimize to enhanced for-loop since implicit iterator used allocated memory in O(n) + for (int i = 0; i < entries.size(); i++) { + Entry entry = entries.get(i); + if (Objects.equals(entry.key, key)) { + V oldValue = entry.value; + entry.value = value; + return oldValue; + } + } + } + Entry entry = entryPool.borrowObject(); + entry.key = key; + entry.value = value; + entries.add(entry); + size++; + return null; + } + + @SuppressWarnings({"unchecked"}) + private void rehash() { + ArrayList>[] oldTable = table; + table = (ArrayList>[]) new ArrayList[2 * oldTable.length]; + + // put() to new table below will reset size back to correct number + size = 0; + + for (int i = 0; i < oldTable.length; i++) { + ArrayList> bucket = oldTable[i]; + if (bucket != null) { + for (Entry entry : bucket) { + put(requireNonNull(entry.key), requireNonNull(entry.value)); + entryPool.returnObject(entry); + } + bucket.clear(); + } + } + } + + /** + * Retrieves the mapped value for {@code key}. + * + * @param key the key whose associated value is to be returned + * @return The mapped value for {@code key} or null if there is no such mapping + */ + @Override + @Nullable + @SuppressWarnings("unchecked") + public V get(Object key) { + requireNonNull(key, "This map does not support null keys"); + + int bucket = getBucket((K) key); + ArrayList> entries = table[bucket]; + if (entries != null) { + for (int i = 0; i < entries.size(); i++) { + Entry entry = entries.get(i); + if (Objects.equals(entry.key, key)) { + return entry.value; + } + } + } + return null; + } + + /** + * Removes the mapping for the given {@code key}. + * + * @param key key whose mapping is to be removed from the map + * @return The value mapped to this key, if the mapping exists, or null otherwise + */ + @Override + @Nullable + @SuppressWarnings("unchecked") + public V remove(Object key) { + requireNonNull(key, "This map does not support null keys"); + + int bucket = getBucket((K) key); + ArrayList> entries = table[bucket]; + if (entries != null) { + for (int i = 0; i < entries.size(); i++) { + Entry entry = entries.get(i); + if (Objects.equals(entry.key, key)) { + V oldValue = entry.value; + entries.remove(i); + entryPool.returnObject(entry); + size--; + return oldValue; + } + } + } + return null; + } + + @Override + public int size() { + return size; + } + + @Override + public boolean isEmpty() { + return size == 0; + } + + @Override + public boolean containsKey(Object key) { + requireNonNull(key, "This map does not support null keys"); + + return get(key) != null; + } + + @Override + public boolean containsValue(Object value) { + throw new UnsupportedOperationException(); + } + + @Override + public void clear() { + for (int i = 0; i < table.length; i++) { + ArrayList> bucket = table[i]; + if (bucket != null) { + for (int j = 0; j < bucket.size(); j++) { + Entry entry = bucket.get(j); + entryPool.returnObject(entry); + } + bucket.clear(); + } + } + size = 0; + } + + // Walks each bucket back-to-front so the action can remove the entry it's currently on (as metric + // collection does to drop stale series) without the next entry being skipped. + @Override + public void forEach(BiConsumer action) { + for (int j = 0; j < table.length; j++) { + ArrayList> bucket = table[j]; + if (bucket != null) { + for (int i = bucket.size() - 1; i >= 0; i--) { + Entry entry = bucket.get(i); + action.accept(entry.key, entry.value); + } + } + } + } + + private int getBucket(K key) { + return Math.abs(key.hashCode() % table.length); + } + + @Override + public Set> entrySet() { + throw new UnsupportedOperationException(); + } + + @Override + public Collection values() { + throw new UnsupportedOperationException(); + } + + @Override + public void putAll(Map m) { + throw new UnsupportedOperationException(); + } + + @Override + public Set keySet() { + throw new UnsupportedOperationException(); + } + + private static class Entry { + @Nullable K key; + + @Nullable V value; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurement.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurement.java index cf34781e428..db8ef8c5bb1 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurement.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurement.java @@ -9,7 +9,7 @@ import io.opentelemetry.api.metrics.ObservableDoubleMeasurement; import io.opentelemetry.api.metrics.ObservableLongMeasurement; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import java.util.List; @@ -31,13 +31,16 @@ public final class SdkObservableMeasurement private final ThrottlingLogger throttlingLogger = new ThrottlingLogger(logger); private final InstrumentationScopeInfo instrumentationScopeInfo; private final InstrumentDescriptor instrumentDescriptor; - private final List> storages; + private final List> storages; + + // These fields are set before invoking callbacks. They allow measurements to be recorded to the + // storages for correct reader, and with the correct time. @Nullable private volatile RegisteredReader activeReader; private SdkObservableMeasurement( InstrumentationScopeInfo instrumentationScopeInfo, InstrumentDescriptor instrumentDescriptor, - List> storages) { + List> storages) { this.instrumentationScopeInfo = instrumentationScopeInfo; this.instrumentDescriptor = instrumentDescriptor; this.storages = storages; @@ -54,7 +57,7 @@ private SdkObservableMeasurement( public static SdkObservableMeasurement create( InstrumentationScopeInfo instrumentationScopeInfo, InstrumentDescriptor instrumentDescriptor, - List> storages) { + List> storages) { return new SdkObservableMeasurement(instrumentationScopeInfo, instrumentDescriptor, storages); } @@ -63,15 +66,24 @@ public InstrumentationScopeInfo getInstrumentationScopeInfo() { return instrumentationScopeInfo; } - public void setActiveReader(@Nullable RegisteredReader registeredReader) { + /** + * Set the active reader, and clock information. {@link #unsetActiveReader()} MUST be called + * after. + */ + public void setActiveReader(RegisteredReader registeredReader) { this.activeReader = registeredReader; } + /** Unset the active reader. Called after {@link #setActiveReader(RegisteredReader)}. */ + public void unsetActiveReader() { + this.activeReader = null; + } + InstrumentDescriptor getInstrumentDescriptor() { return instrumentDescriptor; } - List> getStorages() { + List> getStorages() { return storages; } @@ -84,16 +96,13 @@ public void record(long value) { public void record(long value, Attributes attributes) { RegisteredReader activeReader = this.activeReader; if (activeReader == null) { - throttlingLogger.log( - Level.FINE, - "Measurement recorded for instrument " - + instrumentDescriptor.getName() - + " outside callback registered to instrument. Dropping measurement."); + logNoActiveReader(); return; } - for (AsynchronousMetricStorage storage : storages) { + + for (AsynchronousMetricStorage storage : storages) { if (storage.getRegisteredReader().equals(activeReader)) { - storage.recordLong(value, attributes); + storage.record(attributes, value); } } } @@ -107,17 +116,33 @@ public void record(double value) { public void record(double value, Attributes attributes) { RegisteredReader activeReader = this.activeReader; if (activeReader == null) { - throttlingLogger.log( + logNoActiveReader(); + return; + } + + if (Double.isNaN(value)) { + logger.log( Level.FINE, - "Measurement recorded for instrument " + "Instrument " + instrumentDescriptor.getName() - + " outside callback registered to instrument. Dropping measurement."); + + " has recorded measurement Not-a-Number (NaN) value with attributes " + + attributes + + ". Dropping measurement."); return; } - for (AsynchronousMetricStorage storage : storages) { + + for (AsynchronousMetricStorage storage : storages) { if (storage.getRegisteredReader().equals(activeReader)) { - storage.recordDouble(value, attributes); + storage.record(attributes, value); } } } + + private void logNoActiveReader() { + throttlingLogger.log( + Level.FINE, + "Measurement recorded for instrument " + + instrumentDescriptor.getName() + + " outside callback registered to instrument. Dropping measurement."); + } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/StateIncubatingUtil.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/StateIncubatingUtil.java new file mode 100644 index 00000000000..f89af4a1368 --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/StateIncubatingUtil.java @@ -0,0 +1,19 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.common.ContextAttributes; +import io.opentelemetry.context.Context; + +final class StateIncubatingUtil { + + static Attributes getContextAttributes(Context context) { + return ContextAttributes.get(context); + } + + private StateIncubatingUtil() {} +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorage.java index ba54bb0752d..da8cf4e6b39 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorage.java @@ -5,16 +5,20 @@ package io.opentelemetry.sdk.metrics.internal.state; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.metrics.View; -import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; +import java.util.function.Predicate; +import javax.annotation.Nullable; /** * Stores aggregated {@link MetricData} for synchronous instruments. @@ -35,25 +39,34 @@ static SynchronousMetricStorage empty() { * @return The storage, or {@link EmptyMetricStorage#empty()} if the instrument should not be * recorded. */ - static SynchronousMetricStorage create( + @SuppressWarnings("ReferenceEquality") + static SynchronousMetricStorage create( RegisteredReader registeredReader, RegisteredView registeredView, + Clock clock, InstrumentDescriptor instrumentDescriptor, - ExemplarFilter exemplarFilter) { + ExemplarFilterInternal exemplarFilter, + boolean enabled, + @Nullable Predicate> contextScopedAttributesFilter) { View view = registeredView.getView(); MetricDescriptor metricDescriptor = MetricDescriptor.create(view, registeredView.getViewSourceInfo(), instrumentDescriptor); - Aggregator aggregator = + Aggregator aggregator = ((AggregatorFactory) view.getAggregation()) - .createAggregator(instrumentDescriptor, exemplarFilter); + .createAggregator( + instrumentDescriptor, exemplarFilter, registeredReader.getReader().getMemoryMode()); // We won't be storing this metric. if (Aggregator.drop() == aggregator) { return empty(); } - return new DefaultSynchronousMetricStorage<>( + return DefaultSynchronousMetricStorage.create( registeredReader, metricDescriptor, aggregator, - registeredView.getViewAttributesProcessor()); + registeredView.getAttributesFilter(), + registeredView.getCardinalityLimit(), + clock, + enabled, + contextScopedAttributesFilter); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/TemporalMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/TemporalMetricStorage.java deleted file mode 100644 index 1d5544ec35c..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/TemporalMetricStorage.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; -import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; -import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.resources.Resource; -import java.util.HashMap; -import java.util.Map; -import javax.annotation.concurrent.ThreadSafe; - -/** Stores last reported time and (optional) accumulation for metrics. */ -@ThreadSafe -class TemporalMetricStorage { - private final Aggregator aggregator; - private final boolean isSynchronous; - private final RegisteredReader registeredReader; - private Map lastAccumulation = new HashMap<>(); - private final AggregationTemporality temporality; - private final MetricDescriptor metricDescriptor; - - TemporalMetricStorage( - Aggregator aggregator, - boolean isSynchronous, - RegisteredReader registeredReader, - AggregationTemporality aggregationTemporality, - MetricDescriptor metricDescriptor) { - this.aggregator = aggregator; - this.isSynchronous = isSynchronous; - this.registeredReader = registeredReader; - this.temporality = aggregationTemporality; - this.metricDescriptor = metricDescriptor; - } - - /** - * Builds the {@link MetricData} for the {@code currentAccumulation}. - * - * @param resource The resource to attach these metrics against. - * @param instrumentationScopeInfo The instrumentation scope that generated these metrics. - * @param currentAccumulation The current accumulation of metric data from instruments. This might - * be delta (for synchronous) or cumulative (for asynchronous). - * @param startEpochNanos The timestamp when the metrics SDK started. - * @param epochNanos The current collection timestamp. - * @return The {@link MetricData} points. - */ - synchronized MetricData buildMetricFor( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - Map currentAccumulation, - long startEpochNanos, - long epochNanos) { - - Map result = currentAccumulation; - long lastCollectionEpoch = registeredReader.getLastCollectEpochNanos(); - // Use aggregation temporality + instrument to determine if we do a merge or a diff of - // previous. We have the following four scenarios: - // 1. Delta Aggregation (temporality) + Cumulative recording (async instrument). - // Here we diff with last cumulative to get a delta. - // 2. Cumulative Aggregation + Delta recording (sync instrument). - // Here we merge with our last record to get a cumulative aggregation. - // 3. Cumulative Aggregation + Cumulative recording - do nothing - // 4. Delta Aggregation + Delta recording - do nothing. - if (temporality == AggregationTemporality.DELTA && !isSynchronous) { - MetricStorageUtils.diffInPlace(lastAccumulation, currentAccumulation, aggregator); - result = lastAccumulation; - } else if (temporality == AggregationTemporality.CUMULATIVE && isSynchronous) { - // We need to make sure the current delta recording gets merged into the previous cumulative - // for the next cumulative measurement. - MetricStorageUtils.mergeAndPreserveInPlace(lastAccumulation, currentAccumulation, aggregator); - // Note: We allow going over our hard limit on attribute streams when first merging, but - // preserve after this point. - if (lastAccumulation.size() > MetricStorageUtils.MAX_ACCUMULATIONS) { - MetricStorageUtils.removeUnseen(lastAccumulation, currentAccumulation); - } - result = lastAccumulation; - } - - // Update last reported (cumulative) accumulation. - // For synchronous instruments, we need the merge result. - // For asynchronous instruments, we need the recorded value. - // This assumes aggregation remains consistent for the lifetime of a collector, and - // could be optimised to not record results for cases 3+4 listed above. - if (isSynchronous) { - // Sync instruments remember the full recording. - lastAccumulation = result; - } else { - // Async instruments record the raw measurement. - lastAccumulation = currentAccumulation; - } - if (result.isEmpty()) { - return EmptyMetricData.getInstance(); - } - return aggregator.toMetricData( - resource, - instrumentationScopeInfo, - metricDescriptor, - result, - temporality, - startEpochNanos, - lastCollectionEpoch, - epochNanos); - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/WriteableMetricStorage.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/WriteableMetricStorage.java index c1d8fa49c6a..6e8b42302f5 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/WriteableMetricStorage.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/state/WriteableMetricStorage.java @@ -16,25 +16,23 @@ * at any time. */ public interface WriteableMetricStorage { - /** Bind an efficient storage handle for a set of attributes. */ - BoundStorageHandle bind(Attributes attributes); /** Records a measurement. */ - default void recordLong(long value, Attributes attributes, Context context) { - BoundStorageHandle handle = bind(attributes); - try { - handle.recordLong(value, attributes, context); - } finally { - handle.release(); - } - } + void recordLong(long value, Attributes attributes, Context context); + /** Records a measurement. */ - default void recordDouble(double value, Attributes attributes, Context context) { - BoundStorageHandle handle = bind(attributes); - try { - handle.recordDouble(value, attributes, context); - } finally { - handle.release(); - } - } + void recordDouble(double value, Attributes attributes, Context context); + + /** + * Binds the given {@code attributes}, returning a {@link BoundStorageHandle} that records to the + * corresponding timeseries directly. The series is resolved once here, so subsequent records via + * the returned handle skip per-recording attribute processing and series lookup. + */ + BoundStorageHandle bind(Attributes attributes); + + /** + * Returns {@code true} if the storage is actively recording measurements, and {@code false} + * otherwise (i.e. noop / empty metric storage is installed). + */ + boolean isEnabled(); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AttributesFilters.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AttributesFilters.java new file mode 100644 index 00000000000..a92ce97720c --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AttributesFilters.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.view; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Predicate; +import java.util.function.UnaryOperator; + +/** + * Factories for {@link UnaryOperator} instances that filter {@link Attributes}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class AttributesFilters { + + /** A filter that returns the input attributes unchanged. */ + public static final UnaryOperator ALLOW_ALL = attrs -> attrs; + + private AttributesFilters() {} + + /** + * Returns a filter that retains only attributes whose key name passes {@code keyFilter}. Returns + * {@link #ALLOW_ALL} when {@code keyFilter} is {@link StringPredicates#ALL}. + */ + @SuppressWarnings("ReferenceEquality") + public static UnaryOperator byKeyName(Predicate keyFilter) { + if (keyFilter == StringPredicates.ALL) { + return ALLOW_ALL; + } + return attrs -> attrs.toBuilder().removeIf(k -> !keyFilter.test(k.getKey())).build(); + } + + /** + * Returns a filter that retains only attributes whose key matches one of {@code adviceKeys} (by + * both name and type). Uses {@link FilteredAttributes} to avoid rebuilding the attributes map. + */ + public static UnaryOperator byAdvice(List> adviceKeys) { + Set> keys = new HashSet<>(adviceKeys); + return attrs -> FilteredAttributes.create(attrs, keys); + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AttributesProcessor.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AttributesProcessor.java deleted file mode 100644 index 18da0c5cd44..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/AttributesProcessor.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.view; - -import static io.opentelemetry.sdk.metrics.internal.view.NoopAttributesProcessor.NOOP; - -import io.opentelemetry.api.baggage.Baggage; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.context.Context; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; -import java.util.function.BiFunction; -import java.util.function.Predicate; -import java.util.function.UnaryOperator; -import javax.annotation.concurrent.Immutable; - -/** - * An AttributesProcessor is used to define the actual set of attributes that will be used in a - * Metric vs. the inbound set of attributes from a measurement. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -@Immutable -public abstract class AttributesProcessor { - - AttributesProcessor() {} - - /** - * Manipulates a set of attributes, returning the desired set. - * - * @param incoming Attributes associated with an incoming measurement. - * @param context The context associated with the measurement. - */ - public abstract Attributes process(Attributes incoming, Context context); - - /** - * If true, this ensures the `Context` argument of the attributes processor is always accurate. - * This will prevents bound instruments from pre-locking their metric-attributes and defer until - * context is available. - */ - public abstract boolean usesContext(); - - /** Joins this attribute processor with another that operates after this one. */ - public AttributesProcessor then(AttributesProcessor other) { - if (other == NOOP) { - return this; - } - if (this == NOOP) { - return other; - } - - if (other instanceof JoinedAttributesProcessor) { - return ((JoinedAttributesProcessor) other).prepend(this); - } - return new JoinedAttributesProcessor(Arrays.asList(this, other)); - } - - /** No-op version of attributes processor, returns what it gets. */ - public static AttributesProcessor noop() { - return NOOP; - } - - /** - * Creates a processor which filters down attributes from a measurement. - * - * @param nameFilter a filter for which attribute keys to preserve. - */ - public static AttributesProcessor filterByKeyName(Predicate nameFilter) { - return simple( - incoming -> - incoming.toBuilder() - .removeIf(attributeKey -> !nameFilter.test(attributeKey.getKey())) - .build()); - } - - /** - * Creates a processor which appends values from {@link Baggage}. - * - *

      These attributes will not override those attributes provided by instrumentation. - * - * @param nameFilter a filter for which baggage keys to select. - */ - public static AttributesProcessor appendBaggageByKeyName(Predicate nameFilter) { - return onBaggage( - (incoming, baggage) -> { - AttributesBuilder result = Attributes.builder(); - baggage.forEach( - (k, v) -> { - if (nameFilter.test(k)) { - result.put(k, v.getValue()); - } - }); - // Override any baggage keys with existing keys. - result.putAll(incoming); - return result.build(); - }); - } - - /** - * Creates a processor which appends (exactly) the given attributes. - * - *

      These attributes will not override those attributes provided by instrumentation. - * - * @param attributes Attributes to append to measurements. - */ - public static AttributesProcessor append(Attributes attributes) { - return simple(incoming -> attributes.toBuilder().putAll(incoming).build()); - } - - /** Creates a simple attributes processor with no access to context. */ - static AttributesProcessor simple(UnaryOperator processor) { - return new AttributesProcessor() { - - @Override - public Attributes process(Attributes incoming, Context context) { - return processor.apply(incoming); - } - - @Override - public boolean usesContext() { - return false; - } - }; - } - - /** Creates an Attributes processor that has access to baggage. */ - static AttributesProcessor onBaggage(BiFunction processor) { - return new AttributesProcessor() { - @Override - public Attributes process(Attributes incoming, Context context) { - return processor.apply(incoming, Baggage.fromContext(context)); - } - - @Override - public boolean usesContext() { - return true; - } - }; - } - - /** A {@link AttributesProcessor} that runs a sequence of processors. */ - @Immutable - static final class JoinedAttributesProcessor extends AttributesProcessor { - private final Collection processors; - private final boolean usesContextCache; - - JoinedAttributesProcessor(Collection processors) { - this.processors = processors; - this.usesContextCache = - processors.stream().map(AttributesProcessor::usesContext).reduce(false, (l, r) -> l || r); - } - - @Override - public Attributes process(Attributes incoming, Context context) { - Attributes result = incoming; - for (AttributesProcessor processor : processors) { - result = processor.process(result, context); - } - return result; - } - - @Override - public boolean usesContext() { - return usesContextCache; - } - - @Override - public AttributesProcessor then(AttributesProcessor other) { - List newList = new ArrayList<>(processors); - if (other instanceof JoinedAttributesProcessor) { - newList.addAll(((JoinedAttributesProcessor) other).processors); - } else { - newList.add(other); - } - return new JoinedAttributesProcessor(newList); - } - - AttributesProcessor prepend(AttributesProcessor other) { - List newList = new ArrayList<>(processors.size() + 1); - newList.add(other); - newList.addAll(processors); - return new JoinedAttributesProcessor(newList); - } - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/Base2ExponentialHistogramAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/Base2ExponentialHistogramAggregation.java new file mode 100644 index 00000000000..41455b0b1ac --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/Base2ExponentialHistogramAggregation.java @@ -0,0 +1,107 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.view; + +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.RandomSupplier; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; +import io.opentelemetry.sdk.metrics.internal.aggregator.DoubleBase2ExponentialHistogramAggregator; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; + +/** + * Exponential bucket histogram aggregation configuration. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class Base2ExponentialHistogramAggregation implements Aggregation, AggregatorFactory { + + private static final int DEFAULT_MAX_BUCKETS = 160; + private static final int DEFAULT_MAX_SCALE = 20; + + private static final Aggregation DEFAULT = + new Base2ExponentialHistogramAggregation( + DEFAULT_MAX_BUCKETS, DEFAULT_MAX_SCALE, /* recordMinMax= */ true); + + private final int maxBuckets; + private final int maxScale; + private final boolean recordMinMax; + + private Base2ExponentialHistogramAggregation(int maxBuckets, int maxScale, boolean recordMinMax) { + this.maxBuckets = maxBuckets; + this.maxScale = maxScale; + this.recordMinMax = recordMinMax; + } + + public static Aggregation getDefault() { + return DEFAULT; + } + + /** + * Aggregations measurements into an {@link MetricDataType#EXPONENTIAL_HISTOGRAM}. + * + * @param maxBuckets the max number of positive buckets and negative buckets (max total buckets is + * 2 * {@code maxBuckets} + 1 zero bucket). + * @param maxScale the maximum and initial scale. If measurements can't fit in a particular scale + * given the {@code maxBuckets}, the scale is reduced until the measurements can be + * accommodated. Setting maxScale may reduce the number of downscales. Additionally, the + * performance of computing bucket index is improved when scale is <= 0. + * @param recordMinMax whether to record min and max values + * @return the aggregation + */ + public static Aggregation create(int maxBuckets, int maxScale, boolean recordMinMax) { + return new Base2ExponentialHistogramAggregation(maxBuckets, maxScale, recordMinMax); + } + + @Override + @SuppressWarnings("unchecked") + public Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode) { + return (Aggregator) + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.filtered( + exemplarFilter, + ExemplarReservoirFactory.fixedSizeReservoir( + Clock.getDefault(), + Runtime.getRuntime().availableProcessors(), + RandomSupplier.platformDefault())), + maxBuckets, + maxScale, + recordMinMax, + memoryMode); + } + + @Override + public boolean isCompatibleWithInstrument(InstrumentDescriptor instrumentDescriptor) { + switch (instrumentDescriptor.getType()) { + case COUNTER: + case HISTOGRAM: + return true; + default: + return false; + } + } + + @Override + public String toString() { + return "Base2ExponentialHistogramAggregation{maxBuckets=" + + maxBuckets + + ",maxScale=" + + maxScale + + ",recordMinMax=" + + recordMinMax + + "}"; + } +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DefaultAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DefaultAggregation.java index 9b7263e92c1..dac425543c2 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DefaultAggregation.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DefaultAggregation.java @@ -5,13 +5,14 @@ package io.opentelemetry.sdk.metrics.internal.view; -import io.opentelemetry.sdk.internal.ThrottlingLogger; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.ThrottlingLogger; import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; import java.util.logging.Level; import java.util.logging.Logger; @@ -34,7 +35,7 @@ public static Aggregation getInstance() { private DefaultAggregation() {} - private static Aggregation resolve(InstrumentDescriptor instrument) { + private static Aggregation resolve(InstrumentDescriptor instrument, boolean withAdvice) { switch (instrument.getType()) { case COUNTER: case UP_DOWN_COUNTER: @@ -42,8 +43,13 @@ private static Aggregation resolve(InstrumentDescriptor instrument) { case OBSERVABLE_UP_DOWN_COUNTER: return SumAggregation.getInstance(); case HISTOGRAM: + if (withAdvice && instrument.getAdvice().getExplicitBucketBoundaries() != null) { + return ExplicitBucketHistogramAggregation.create( + instrument.getAdvice().getExplicitBucketBoundaries(), /* recordMinMax= */ true); + } return ExplicitBucketHistogramAggregation.getDefault(); case OBSERVABLE_GAUGE: + case GAUGE: return LastValueAggregation.getInstance(); } logger.log(Level.WARNING, "Unable to find default aggregation for instrument: " + instrument); @@ -51,16 +57,18 @@ private static Aggregation resolve(InstrumentDescriptor instrument) { } @Override - public Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter) { - return ((AggregatorFactory) resolve(instrumentDescriptor)) - .createAggregator(instrumentDescriptor, exemplarFilter); + public Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode) { + return ((AggregatorFactory) resolve(instrumentDescriptor, /* withAdvice= */ true)) + .createAggregator(instrumentDescriptor, exemplarFilter, memoryMode); } @Override public boolean isCompatibleWithInstrument(InstrumentDescriptor instrumentDescriptor) { // This should always return true - return ((AggregatorFactory) resolve(instrumentDescriptor)) + return ((AggregatorFactory) resolve(instrumentDescriptor, /* withAdvice= */ false)) .isCompatibleWithInstrument(instrumentDescriptor); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DropAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DropAggregation.java index 35f189037fc..592c74f013a 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DropAggregation.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/DropAggregation.java @@ -5,12 +5,13 @@ package io.opentelemetry.sdk.metrics.internal.view; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; /** * Configuration representing no aggregation. @@ -30,9 +31,11 @@ private DropAggregation() {} @Override @SuppressWarnings("unchecked") - public Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter) { - return (Aggregator) Aggregator.drop(); + public Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode) { + return (Aggregator) Aggregator.drop(); } @Override diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregation.java index 1e108944aa5..0a9f13f2f1f 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregation.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregation.java @@ -6,15 +6,16 @@ package io.opentelemetry.sdk.metrics.internal.view; import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.aggregator.DoubleExplicitBucketHistogramAggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import java.util.List; /** @@ -27,37 +28,43 @@ public final class ExplicitBucketHistogramAggregation implements Aggregation, Ag private static final Aggregation DEFAULT = new ExplicitBucketHistogramAggregation( - ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES); + ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES, + /* recordMinMax= */ true); public static Aggregation getDefault() { return DEFAULT; } - public static Aggregation create(List bucketBoundaries) { - return new ExplicitBucketHistogramAggregation(bucketBoundaries); + public static Aggregation create(List bucketBoundaries, boolean recordMinMax) { + return new ExplicitBucketHistogramAggregation(bucketBoundaries, recordMinMax); } private final List bucketBoundaries; private final double[] bucketBoundaryArray; + private final boolean recordMinMax; - private ExplicitBucketHistogramAggregation(List bucketBoundaries) { + private ExplicitBucketHistogramAggregation(List bucketBoundaries, boolean recordMinMax) { this.bucketBoundaries = bucketBoundaries; // We need to fail here if our bucket boundaries are ill-configured. this.bucketBoundaryArray = ExplicitBucketHistogramUtils.createBoundaryArray(bucketBoundaries); + this.recordMinMax = recordMinMax; } @Override @SuppressWarnings("unchecked") - public Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter) { - return (Aggregator) + public Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode) { + return (Aggregator) new DoubleExplicitBucketHistogramAggregator( bucketBoundaryArray, - () -> - ExemplarReservoir.filtered( - exemplarFilter, - ExemplarReservoir.histogramBucketReservoir( - Clock.getDefault(), bucketBoundaries))); + recordMinMax, + ExemplarReservoirFactory.filtered( + exemplarFilter, + ExemplarReservoirFactory.histogramBucketReservoir( + Clock.getDefault(), bucketBoundaries)), + memoryMode); } @Override @@ -73,6 +80,11 @@ public boolean isCompatibleWithInstrument(InstrumentDescriptor instrumentDescrip @Override public String toString() { - return "ExplicitBucketHistogramAggregation(" + bucketBoundaries.toString() + ")"; + return "ExplicitBucketHistogramAggregation{" + + "bucketBoundaries=" + + bucketBoundaries + + ",recordMinMax=" + + recordMinMax + + "}"; } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExponentialHistogramAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExponentialHistogramAggregation.java deleted file mode 100644 index 0952ef7f452..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ExponentialHistogramAggregation.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.view; - -import static io.opentelemetry.api.internal.Utils.checkArgument; - -import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.internal.RandomSupplier; -import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; -import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; -import io.opentelemetry.sdk.metrics.internal.aggregator.DoubleExponentialHistogramAggregator; -import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; - -/** - * Exponential bucket histogram aggregation configuration. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public final class ExponentialHistogramAggregation implements Aggregation, AggregatorFactory { - - private static final Aggregation DEFAULT = new ExponentialHistogramAggregation(20, 320); - - private final int startingScale; - private final int maxBuckets; - - private ExponentialHistogramAggregation(int startingScale, int maxBuckets) { - this.startingScale = startingScale; - this.maxBuckets = maxBuckets; - } - - public static Aggregation getDefault() { - return DEFAULT; - } - - public static Aggregation create(int scale, int maxBuckets) { - checkArgument(maxBuckets >= 0, "maxBuckets must be >= 0"); - return new ExponentialHistogramAggregation(scale, maxBuckets); - } - - @Override - @SuppressWarnings("unchecked") - public Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter) { - return (Aggregator) - new DoubleExponentialHistogramAggregator( - () -> - ExemplarReservoir.filtered( - exemplarFilter, - ExemplarReservoir.doubleFixedSizeReservoir( - Clock.getDefault(), - Runtime.getRuntime().availableProcessors(), - RandomSupplier.platformDefault())), - startingScale, - maxBuckets); - } - - @Override - public boolean isCompatibleWithInstrument(InstrumentDescriptor instrumentDescriptor) { - switch (instrumentDescriptor.getType()) { - case COUNTER: - case HISTOGRAM: - return true; - default: - return false; - } - } - - @Override - public String toString() { - return "ExponentialHistogramAggregation{startingScale=" - + startingScale - + ",maxBuckets=" - + maxBuckets - + "}"; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributes.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributes.java new file mode 100644 index 00000000000..a06ca741fba --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributes.java @@ -0,0 +1,284 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.view; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.internal.ImmutableKeyValuePairs; +import java.util.BitSet; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.StringJoiner; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; + +/** + * Filtered attributes is a filtered view of a {@link ImmutableKeyValuePairs} backed {@link + * Attributes} instance. Rather than creating an entirely new attributes instance, it keeps track of + * which source attributes are excluded while implementing the {@link Attributes} interface. + * + *

      Notably, the {@link FilteredAttributes#equals(Object)} and {@link + * FilteredAttributes#hashCode()} depend on comparison against other {@link FilteredAttributes} + * instances. This means that where {@link FilteredAttributes} is used for things like map keys, it + * must be used for all keys in that map. You cannot mix {@link Attributes} implementations. This is + * also true for the default attributes implementation. + */ +@SuppressWarnings("unchecked") +abstract class FilteredAttributes implements Attributes { + + // Backing source data from ImmutableKeyValuePairs.data. This array MUST NOT be mutated. + private final Object[] sourceData; + private final int hashcode; + private final int size; + + private FilteredAttributes(Object[] sourceData, int hashcode, int size) { + this.sourceData = sourceData; + this.hashcode = hashcode; + this.size = size; + } + + /** + * Create a {@link FilteredAttributes} instance. + * + * @param source the source attributes, which should be based on the standard {@link + * ImmutableKeyValuePairs}. If not, the source will first be converted to the standard + * implementation. + * @param includedKeys the set of attribute keys to include in the output. + */ + @SuppressWarnings("NullAway") + static Attributes create(Attributes source, Set> includedKeys) { + // Convert alternative implementations of Attributes to standard implementation. + // This is required for proper functioning of equals and hashcode. + if (!(source instanceof ImmutableKeyValuePairs)) { + source = convertToStandardImplementation(source); + } + if (!(source instanceof ImmutableKeyValuePairs)) { + throw new IllegalStateException( + "Expected ImmutableKeyValuePairs based implementation of Attributes. This is a programming error."); + } + // Compute filteredIndices (and filteredIndicesBitSet if needed) during initialization. Compute + // hashcode at the same time to avoid iteration later. + Object[] sourceData = ((ImmutableKeyValuePairs) source).getData(); + int filteredIndices = 0; + BitSet filteredIndicesBitSet = + source.size() > SmallFilteredAttributes.BITS_PER_INTEGER ? new BitSet(source.size()) : null; + int hashcode = 1; + int size = 0; + for (int i = 0; i < sourceData.length; i += 2) { + int filterIndex = i / 2; + // If the sourceData key isn't present in includedKeys, record the exclusion in + // filteredIndices or filteredIndicesBitSet (depending on size) + if (!includedKeys.contains(sourceData[i])) { + // Record + if (filteredIndicesBitSet != null) { + filteredIndicesBitSet.set(filterIndex); + } else { + filteredIndices = filteredIndices | (1 << filterIndex); + } + } else { // The key-value is included in the output, record in the hashcode and size. + hashcode = 31 * hashcode + sourceData[i].hashCode(); + hashcode = 31 * hashcode + sourceData[i + 1].hashCode(); + size++; + } + } + // If size is 0, short circuit and return Attributes.empty() + if (size == 0) { + return Attributes.empty(); + } + return filteredIndicesBitSet != null + ? new RegularFilteredAttributes(sourceData, hashcode, size, filteredIndicesBitSet) + : new SmallFilteredAttributes(sourceData, hashcode, size, filteredIndices); + } + + /** + * Implementation that relies on the source having less than {@link #BITS_PER_INTEGER} attributes, + * and storing entry filter status in the bits of an integer. + */ + private static class SmallFilteredAttributes extends FilteredAttributes { + + private static final int BITS_PER_INTEGER = 32; + + private final int filteredIndices; + + private SmallFilteredAttributes( + Object[] sourceData, int hashcode, int size, int filteredIndices) { + super(sourceData, hashcode, size); + this.filteredIndices = filteredIndices; + } + + @Override + boolean includeIndexInOutput(int sourceIndex) { + return (filteredIndices & (1 << (sourceIndex / 2))) == 0; + } + } + + /** + * Implementation that can handle attributes of arbitrary size by storing filter status in a + * {@link BitSet}. + */ + private static class RegularFilteredAttributes extends FilteredAttributes { + + private final BitSet bitSet; + + private RegularFilteredAttributes(Object[] sourceData, int hashcode, int size, BitSet bitSet) { + super(sourceData, hashcode, size); + this.bitSet = bitSet; + } + + @Override + boolean includeIndexInOutput(int sourceIndex) { + return !bitSet.get(sourceIndex / 2); + } + } + + private static Attributes convertToStandardImplementation(Attributes source) { + AttributesBuilder builder = Attributes.builder(); + source.forEach( + (key, value) -> putInBuilder(builder, (AttributeKey) key, value)); + return builder.build(); + } + + @Nullable + @Override + public T get(AttributeKey key) { + if (key == null) { + return null; + } + for (int i = 0; i < sourceData.length; i += 2) { + if (key.equals(sourceData[i]) && includeIndexInOutput(i)) { + return (T) sourceData[i + 1]; + } + } + return null; + } + + @Override + public void forEach(BiConsumer, ? super Object> consumer) { + for (int i = 0; i < sourceData.length; i += 2) { + if (includeIndexInOutput(i)) { + consumer.accept((AttributeKey) sourceData[i], sourceData[i + 1]); + } + } + } + + @Override + public int size() { + return size; + } + + @Override + public boolean isEmpty() { + // #create short circuits and returns Attributes.empty() if empty, so FilteredAttributes is + // never empty + return false; + } + + @Override + public Map, Object> asMap() { + Map, Object> result = new LinkedHashMap<>(size); + for (int i = 0; i < sourceData.length; i += 2) { + if (includeIndexInOutput(i)) { + result.put((AttributeKey) sourceData[i], sourceData[i + 1]); + } + } + return Collections.unmodifiableMap(result); + } + + @Override + public AttributesBuilder toBuilder() { + AttributesBuilder builder = Attributes.builder(); + for (int i = 0; i < sourceData.length; i += 2) { + if (includeIndexInOutput(i)) { + putInBuilder(builder, (AttributeKey) sourceData[i], sourceData[i + 1]); + } + } + return builder; + } + + private static void putInBuilder(AttributesBuilder builder, AttributeKey key, T value) { + builder.put(key, value); + } + + @Override + public boolean equals(Object object) { + if (this == object) { + return true; + } + // We require other object to also be instances of FilteredAttributes. In other words, where one + // FilteredAttributes is used for a key in a map, it must be used for all the keys. Note, this + // same requirement exists for the default Attributes implementation - you can not mix + // implementations. + if (object == null || !(object instanceof FilteredAttributes)) { + return false; + } + + FilteredAttributes that = (FilteredAttributes) object; + // exit early if sizes are not equal + if (size() != that.size()) { + return false; + } + // Compare each non-filtered key / value pair from this to that. + // Depends on the entries from the backing ImmutableKeyValuePairs being sorted. + int thisIndex = 0; + int thatIndex = 0; + boolean thisDone; + boolean thatDone; + do { + thisDone = thisIndex >= this.sourceData.length; + thatDone = thatIndex >= that.sourceData.length; + // advance to next unfiltered key value pair for this and that + if (!thisDone && !this.includeIndexInOutput(thisIndex)) { + thisIndex += 2; + continue; + } + if (!thatDone && !that.includeIndexInOutput(thatIndex)) { + thatIndex += 2; + continue; + } + // if we're done iterating both this and that, we exit and return true since these are equal + if (thisDone && thatDone) { + break; + } + // if either this or that is done iterating, but not both, these are not equal + if (thisDone != thatDone) { + return false; + } + // if we make it here, both thisIndex and thatIndex within bounds and are included in the + // output. the current + // key and value and this and that must be equal for this and that to be equal. + if (!Objects.equals(this.sourceData[thisIndex], that.sourceData[thatIndex]) + || !Objects.equals(this.sourceData[thisIndex + 1], that.sourceData[thatIndex + 1])) { + return false; + } + thisIndex += 2; + thatIndex += 2; + } while (true); + // if we make it here without exiting early, all elements of this and that are equal + return true; + } + + @Override + public int hashCode() { + return hashcode; + } + + @Override + public String toString() { + StringJoiner joiner = new StringJoiner(",", "FilteredAttributes{", "}"); + for (int i = 0; i < sourceData.length; i += 2) { + if (includeIndexInOutput(i)) { + joiner.add(((AttributeKey) sourceData[i]).getKey() + "=" + sourceData[i + 1]); + } + } + return joiner.toString(); + } + + abstract boolean includeIndexInOutput(int sourceIndex); +} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/LastValueAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/LastValueAggregation.java index 6ac871d0c42..fb671eb2ffc 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/LastValueAggregation.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/LastValueAggregation.java @@ -5,16 +5,19 @@ package io.opentelemetry.sdk.metrics.internal.view; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.RandomSupplier; import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.data.ExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.aggregator.DoubleLastValueAggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.LongLastValueAggregator; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; /** * Last-value aggregation configuration. @@ -34,22 +37,33 @@ private LastValueAggregation() {} @Override @SuppressWarnings("unchecked") - public Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter) { + public Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode) { + + ExemplarReservoirFactory reservoirFactory = + ExemplarReservoirFactory.filtered( + exemplarFilter, + ExemplarReservoirFactory.fixedSizeReservoir( + Clock.getDefault(), + Runtime.getRuntime().availableProcessors(), + RandomSupplier.platformDefault())); - // For the initial version we do not sample exemplars on gauges. switch (instrumentDescriptor.getValueType()) { case LONG: - return (Aggregator) new LongLastValueAggregator(ExemplarReservoir::longNoSamples); + return (Aggregator) new LongLastValueAggregator(reservoirFactory, memoryMode); case DOUBLE: - return (Aggregator) new DoubleLastValueAggregator(ExemplarReservoir::doubleNoSamples); + return (Aggregator) new DoubleLastValueAggregator(reservoirFactory, memoryMode); } throw new IllegalArgumentException("Invalid instrument value type"); } @Override public boolean isCompatibleWithInstrument(InstrumentDescriptor instrumentDescriptor) { - return instrumentDescriptor.getType() == InstrumentType.OBSERVABLE_GAUGE; + InstrumentType instrumentType = instrumentDescriptor.getType(); + return instrumentType == InstrumentType.OBSERVABLE_GAUGE + || instrumentType == InstrumentType.GAUGE; } @Override diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/NoopAttributesProcessor.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/NoopAttributesProcessor.java deleted file mode 100644 index 184bd98d18b..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/NoopAttributesProcessor.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.view; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; - -class NoopAttributesProcessor extends AttributesProcessor { - - static final NoopAttributesProcessor NOOP = new NoopAttributesProcessor(); - - private NoopAttributesProcessor() {} - - @Override - public Attributes process(Attributes incoming, Context context) { - return incoming; - } - - @Override - public boolean usesContext() { - return false; - } - - @Override - public String toString() { - return "NoopAttributesProcessor{}"; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredView.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredView.java index 43384eaaa62..296fdadc609 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredView.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredView.java @@ -6,9 +6,11 @@ package io.opentelemetry.sdk.metrics.internal.view; import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import java.util.function.UnaryOperator; import javax.annotation.concurrent.Immutable; /** @@ -24,9 +26,11 @@ public abstract class RegisteredView { public static RegisteredView create( InstrumentSelector selector, View view, - AttributesProcessor viewAttributesProcessor, + UnaryOperator attributesFilter, + int cardinalityLimit, SourceInfo viewSourceInfo) { - return new AutoValue_RegisteredView(selector, view, viewAttributesProcessor, viewSourceInfo); + return new AutoValue_RegisteredView( + selector, view, attributesFilter, cardinalityLimit, viewSourceInfo); } RegisteredView() {} @@ -37,8 +41,15 @@ public static RegisteredView create( /** The view to apply. */ public abstract View getView(); - /** The view's {@link AttributesProcessor}. */ - public abstract AttributesProcessor getViewAttributesProcessor(); + /** + * The attributes filter applied to recorded measurements. Built from the view's {@link + * View#getAttributeFilter()} or, for the instrument-default view with attribute advice, from the + * advice's attribute keys. + */ + public abstract UnaryOperator getAttributesFilter(); + + /** The view's cardinality limit. */ + public abstract int getCardinalityLimit(); /** The {@link SourceInfo} from where the view was registered. */ public abstract SourceInfo getViewSourceInfo(); diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/SumAggregation.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/SumAggregation.java index 1b6f63a1a28..3d1d8bd1ab0 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/SumAggregation.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/SumAggregation.java @@ -6,19 +6,17 @@ package io.opentelemetry.sdk.metrics.internal.view; import io.opentelemetry.sdk.common.Clock; -import io.opentelemetry.sdk.internal.RandomSupplier; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.RandomSupplier; import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.ExemplarData; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.aggregator.DoubleSumAggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.LongSumAggregator; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; -import java.util.function.Supplier; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; /** * A sum aggregation configuration. @@ -37,33 +35,24 @@ private SumAggregation() {} @Override @SuppressWarnings("unchecked") - public Aggregator createAggregator( - InstrumentDescriptor instrumentDescriptor, ExemplarFilter exemplarFilter) { + public Aggregator createAggregator( + InstrumentDescriptor instrumentDescriptor, + ExemplarFilterInternal exemplarFilter, + MemoryMode memoryMode) { + ExemplarReservoirFactory reservoirFactory = + ExemplarReservoirFactory.filtered( + exemplarFilter, + ExemplarReservoirFactory.fixedSizeReservoir( + Clock.getDefault(), + Runtime.getRuntime().availableProcessors(), + RandomSupplier.platformDefault())); switch (instrumentDescriptor.getValueType()) { case LONG: - { - Supplier> reservoirFactory = - () -> - ExemplarReservoir.filtered( - exemplarFilter, - ExemplarReservoir.longFixedSizeReservoir( - Clock.getDefault(), - Runtime.getRuntime().availableProcessors(), - RandomSupplier.platformDefault())); - return (Aggregator) new LongSumAggregator(instrumentDescriptor, reservoirFactory); - } + return (Aggregator) + new LongSumAggregator(instrumentDescriptor, reservoirFactory, memoryMode); case DOUBLE: - { - Supplier> reservoirFactory = - () -> - ExemplarReservoir.filtered( - exemplarFilter, - ExemplarReservoir.doubleFixedSizeReservoir( - Clock.getDefault(), - Runtime.getRuntime().availableProcessors(), - RandomSupplier.platformDefault())); - return (Aggregator) new DoubleSumAggregator(instrumentDescriptor, reservoirFactory); - } + return (Aggregator) + new DoubleSumAggregator(instrumentDescriptor, reservoirFactory, memoryMode); } throw new IllegalArgumentException("Invalid instrument value type"); } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistry.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistry.java index d61f77a500c..671b7ab3276 100644 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistry.java +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistry.java @@ -5,23 +5,30 @@ package io.opentelemetry.sdk.metrics.internal.view; -import static io.opentelemetry.sdk.metrics.internal.view.NoopAttributesProcessor.NOOP; +import static java.util.Objects.requireNonNull; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.GlobUtil; +import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentSelector; +import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregationUtil; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; -import java.util.function.Predicate; +import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; -import java.util.regex.Pattern; import javax.annotation.concurrent.Immutable; /** @@ -38,37 +45,62 @@ public final class ViewRegistry { RegisteredView.create( InstrumentSelector.builder().setName("*").build(), DEFAULT_VIEW, - NOOP, + AttributesFilters.ALLOW_ALL, + MetricStorage.DEFAULT_MAX_CARDINALITY, SourceInfo.noSourceInfo()); private static final Logger logger = Logger.getLogger(ViewRegistry.class.getName()); - private final List reverseRegistration; - - ViewRegistry(List reverseRegistration) { - this.reverseRegistration = reverseRegistration; + private final Map instrumentDefaultRegisteredView; + private final List registeredViews; + + ViewRegistry( + DefaultAggregationSelector defaultAggregationSelector, + CardinalityLimitSelector cardinalityLimitSelector, + List registeredViews) { + instrumentDefaultRegisteredView = new HashMap<>(); + for (InstrumentType instrumentType : InstrumentType.values()) { + instrumentDefaultRegisteredView.put( + instrumentType, + RegisteredView.create( + InstrumentSelector.builder().setName("*").build(), + View.builder() + .setAggregation(defaultAggregationSelector.getDefaultAggregation(instrumentType)) + .build(), + AttributesFilters.ALLOW_ALL, + cardinalityLimitSelector.getCardinalityLimit(instrumentType), + SourceInfo.noSourceInfo())); + } + this.registeredViews = registeredViews; } - /** Returns a builder of {@link ViewRegistry}. */ - public static ViewRegistryBuilder builder() { - return new ViewRegistryBuilder(); + /** Returns a {@link ViewRegistry}. */ + public static ViewRegistry create( + DefaultAggregationSelector defaultAggregationSelector, + CardinalityLimitSelector cardinalityLimitSelector, + List registeredViews) { + return new ViewRegistry( + defaultAggregationSelector, cardinalityLimitSelector, new ArrayList<>(registeredViews)); } - /** Return a list of all registered views. */ - public List getViews() { - return new ArrayList<>(reverseRegistration); + /** Return a {@link ViewRegistry} using the default aggregation and no views registered. */ + public static ViewRegistry create() { + return create( + unused -> Aggregation.defaultAggregation(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.emptyList()); } /** * Returns the metric {@link View} for a given instrument. * * @param descriptor description of the instrument. - * @return The list of {@link View}s for this instrument in registered order, or a default - * aggregation view. + * @return The list of {@link View}s for this instrument, or a default view. */ public List findViews( InstrumentDescriptor descriptor, InstrumentationScopeInfo meterScope) { List result = new ArrayList<>(); - for (RegisteredView entry : reverseRegistration) { + // Find matching views for the instrument + for (RegisteredView entry : registeredViews) { if (matchesSelector(entry.getInstrumentSelector(), descriptor, meterScope)) { AggregatorFactory viewAggregatorFactory = (AggregatorFactory) entry.getView().getAggregation(); @@ -87,10 +119,39 @@ public List findViews( } } - if (result.isEmpty()) { - return Collections.singletonList(DEFAULT_REGISTERED_VIEW); + // If a view matched, return it + if (!result.isEmpty()) { + return Collections.unmodifiableList(result); + } + + // No views matched, use default view + RegisteredView instrumentDefaultView = + requireNonNull(instrumentDefaultRegisteredView.get(descriptor.getType())); + + AggregatorFactory viewAggregatorFactory = + (AggregatorFactory) instrumentDefaultView.getView().getAggregation(); + + if (!viewAggregatorFactory.isCompatibleWithInstrument(descriptor)) { + // The aggregation from default aggregation selector was incompatible with instrument, use + // default aggregation instead + logger.log( + Level.WARNING, + "Instrument default aggregation " + + AggregationUtil.aggregationName(instrumentDefaultView.getView().getAggregation()) + + " is incompatible with instrument " + + descriptor.getName() + + " of type " + + descriptor.getType()); + instrumentDefaultView = DEFAULT_REGISTERED_VIEW; } - return Collections.unmodifiableList(result); + + // if the user defined an attributes advice, use it + if (descriptor.getAdvice().hasAttributes()) { + instrumentDefaultView = + applyAdviceToDefaultView(instrumentDefaultView, descriptor.getAdvice()); + } + + return Collections.singletonList(instrumentDefaultView); } // Matches an instrument selector against an instrument + meter. @@ -102,8 +163,13 @@ private static boolean matchesSelector( && selector.getInstrumentType() != descriptor.getType()) { return false; } + if (selector.getInstrumentUnit() != null + && !selector.getInstrumentUnit().equals(descriptor.getUnit())) { + return false; + } if (selector.getInstrumentName() != null - && !toGlobPatternPredicate(selector.getInstrumentName()).test(descriptor.getName())) { + && !GlobUtil.createGlobPatternPredicate(selector.getInstrumentName()) + .test(descriptor.getName())) { return false; } return matchesMeter(selector, meterScope); @@ -123,66 +189,13 @@ private static boolean matchesMeter( || selector.getMeterSchemaUrl().equals(meterScope.getSchemaUrl()); } - /** - * Return a predicate that returns {@code true} if a string matches the {@code globPattern}. - * - *

      {@code globPattern} may contain the wildcard characters {@code *} and {@code ?} with the - * following matching criteria: - * - *

        - *
      • {@code *} matches 0 or more instances of any character - *
      • {@code ?} matches exactly one instance of any character - *
      - */ - // Visible for testing - static Predicate toGlobPatternPredicate(String globPattern) { - // Match all - if (globPattern.equals("*")) { - return unused -> true; - } - - // If globPattern contains '*' or '?', convert it to a regex and return corresponding predicate - for (int i = 0; i < globPattern.length(); i++) { - char c = globPattern.charAt(i); - if (c == '*' || c == '?') { - Pattern pattern = toRegexPattern(globPattern); - return string -> pattern.matcher(string).matches(); - } - } - - // Exact match, ignoring case - return globPattern::equalsIgnoreCase; - } - - /** - * Transform the {@code globPattern} to a regex by converting {@code *} to {@code .*}, {@code ?} - * to {@code .}, and escaping other regex special characters. - */ - private static Pattern toRegexPattern(String globPattern) { - int tokenStart = -1; - StringBuilder patternBuilder = new StringBuilder(); - for (int i = 0; i < globPattern.length(); i++) { - char c = globPattern.charAt(i); - if (c == '*' || c == '?') { - if (tokenStart != -1) { - patternBuilder.append(Pattern.quote(globPattern.substring(tokenStart, i))); - tokenStart = -1; - } - if (c == '*') { - patternBuilder.append(".*"); - } else { - // c == '?' - patternBuilder.append("."); - } - } else { - if (tokenStart == -1) { - tokenStart = i; - } - } - } - if (tokenStart != -1) { - patternBuilder.append(Pattern.quote(globPattern.substring(tokenStart))); - } - return Pattern.compile(patternBuilder.toString()); + private static RegisteredView applyAdviceToDefaultView( + RegisteredView instrumentDefaultView, Advice advice) { + return RegisteredView.create( + instrumentDefaultView.getInstrumentSelector(), + instrumentDefaultView.getView(), + AttributesFilters.byAdvice(requireNonNull(advice.getAttributes())), + instrumentDefaultView.getCardinalityLimit(), + instrumentDefaultView.getViewSourceInfo()); } } diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryBuilder.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryBuilder.java deleted file mode 100644 index 6cb273ee3ee..00000000000 --- a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryBuilder.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.view; - -import io.opentelemetry.sdk.metrics.InstrumentSelector; -import io.opentelemetry.sdk.metrics.View; -import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Builder for {@link ViewRegistry}. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public class ViewRegistryBuilder { - private final List orderedViews = new ArrayList<>(); - - ViewRegistryBuilder() {} - - /** Returns the {@link ViewRegistry}. */ - public ViewRegistry build() { - return new ViewRegistry(Collections.unmodifiableList(orderedViews)); - } - - /** - * Adds a new view to the registry. - * - * @param selector The instruments that should have their defaults altered. - * @param view The {@link View} metric definition. - * @param viewSourceInfo The {@link SourceInfo} from where the source was registered. - * @return this - */ - public ViewRegistryBuilder addView( - InstrumentSelector selector, - View view, - AttributesProcessor viewAttributeProcessor, - SourceInfo viewSourceInfo) { - orderedViews.add(RegisteredView.create(selector, view, viewAttributeProcessor, viewSourceInfo)); - return this; - } -} diff --git a/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/package-info.java b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/package-info.java new file mode 100644 index 00000000000..2cd6165107b --- /dev/null +++ b/sdk/metrics/src/main/java/io/opentelemetry/sdk/metrics/internal/view/package-info.java @@ -0,0 +1,10 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** View related internal classes. */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.metrics.internal.view; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AbstractInstrumentTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AbstractInstrumentTest.java index 63ca658c971..dc8cb23cad8 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AbstractInstrumentTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AbstractInstrumentTest.java @@ -6,7 +6,9 @@ package io.opentelemetry.sdk.metrics; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import org.junit.jupiter.api.Test; @@ -14,7 +16,14 @@ class AbstractInstrumentTest { private static final InstrumentDescriptor INSTRUMENT_DESCRIPTOR = InstrumentDescriptor.create( - "name", "description", "1", InstrumentType.COUNTER, InstrumentValueType.LONG); + "name", + "description", + "1", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()); + + private static final SdkMeter SDK_METER = mock(SdkMeter.class); @Test void getValues() { @@ -22,9 +31,16 @@ void getValues() { assertThat(testInstrument.getDescriptor()).isSameAs(INSTRUMENT_DESCRIPTOR); } + @Test + void stringRepresentation() { + TestInstrument testInstrument = new TestInstrument(INSTRUMENT_DESCRIPTOR); + assertThat(testInstrument) + .hasToString("TestInstrument{descriptor=" + INSTRUMENT_DESCRIPTOR + "}"); + } + private static final class TestInstrument extends AbstractInstrument { TestInstrument(InstrumentDescriptor descriptor) { - super(descriptor); + super(descriptor, SDK_METER); } } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AggregationTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AggregationTest.java index 45d5fadf1ca..f907d090093 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AggregationTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/AggregationTest.java @@ -8,8 +8,8 @@ import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.view.ExponentialHistogramAggregation; import java.util.Collections; import org.junit.jupiter.api.Test; @@ -25,21 +25,27 @@ void haveToString() { assertThat(Aggregation.explicitBucketHistogram()) .asString() .contains("ExplicitBucketHistogramAggregation"); - assertThat(Aggregation.explicitBucketHistogram(Collections.singletonList(1.0d))) + assertThat( + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.singletonList(1.0d)) + .build())) .asString() .contains("ExplicitBucketHistogramAggregation"); - // TODO(jack-berg): Use Aggregation.exponentialHistogram() when available - assertThat(ExponentialHistogramAggregation.getDefault()) + assertThat(Aggregation.base2ExponentialBucketHistogram()) .asString() - .isEqualTo("ExponentialHistogramAggregation{startingScale=20,maxBuckets=320}"); - assertThat(ExponentialHistogramAggregation.create(1, 1)) + .isEqualTo( + "Base2ExponentialHistogramAggregation{maxBuckets=160,maxScale=20,recordMinMax=true}"); + assertThat( + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder().setMaxBuckets(2).setMaxScale(0).build())) .asString() - .isEqualTo("ExponentialHistogramAggregation{startingScale=1,maxBuckets=1}"); + .isEqualTo( + "Base2ExponentialHistogramAggregation{maxBuckets=2,maxScale=0,recordMinMax=true}"); } @Test void histogramUsesExplicitBucket() { - // Note: This will change when exponential histograms are launched. assertThat(Aggregation.explicitBucketHistogram()) .asString() .contains("ExplicitBucketHistogram"); @@ -53,11 +59,13 @@ void aggregationIsCompatible() { InstrumentDescriptor observableUpDownCounter = descriptorForType(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER); InstrumentDescriptor observableGauge = descriptorForType(InstrumentType.OBSERVABLE_GAUGE); + InstrumentDescriptor gauge = descriptorForType(InstrumentType.GAUGE); InstrumentDescriptor histogram = descriptorForType(InstrumentType.HISTOGRAM); AggregatorFactory defaultAggregation = ((AggregatorFactory) Aggregation.defaultAggregation()); assertThat(defaultAggregation.isCompatibleWithInstrument(counter)).isTrue(); assertThat(defaultAggregation.isCompatibleWithInstrument(observableCounter)).isTrue(); + assertThat(defaultAggregation.isCompatibleWithInstrument(gauge)).isTrue(); assertThat(defaultAggregation.isCompatibleWithInstrument(upDownCounter)).isTrue(); assertThat(defaultAggregation.isCompatibleWithInstrument(observableUpDownCounter)).isTrue(); assertThat(defaultAggregation.isCompatibleWithInstrument(observableGauge)).isTrue(); @@ -66,6 +74,7 @@ void aggregationIsCompatible() { AggregatorFactory drop = ((AggregatorFactory) Aggregation.drop()); assertThat(drop.isCompatibleWithInstrument(counter)).isTrue(); assertThat(drop.isCompatibleWithInstrument(observableCounter)).isTrue(); + assertThat(drop.isCompatibleWithInstrument(gauge)).isTrue(); assertThat(drop.isCompatibleWithInstrument(upDownCounter)).isTrue(); assertThat(drop.isCompatibleWithInstrument(observableUpDownCounter)).isTrue(); assertThat(drop.isCompatibleWithInstrument(observableGauge)).isTrue(); @@ -77,6 +86,7 @@ void aggregationIsCompatible() { assertThat(sum.isCompatibleWithInstrument(upDownCounter)).isTrue(); assertThat(sum.isCompatibleWithInstrument(observableUpDownCounter)).isTrue(); assertThat(sum.isCompatibleWithInstrument(observableGauge)).isFalse(); + assertThat(sum.isCompatibleWithInstrument(gauge)).isFalse(); assertThat(sum.isCompatibleWithInstrument(histogram)).isTrue(); AggregatorFactory explicitHistogram = @@ -86,16 +96,17 @@ void aggregationIsCompatible() { assertThat(explicitHistogram.isCompatibleWithInstrument(upDownCounter)).isFalse(); assertThat(explicitHistogram.isCompatibleWithInstrument(observableUpDownCounter)).isFalse(); assertThat(explicitHistogram.isCompatibleWithInstrument(observableGauge)).isFalse(); + assertThat(explicitHistogram.isCompatibleWithInstrument(gauge)).isFalse(); assertThat(explicitHistogram.isCompatibleWithInstrument(histogram)).isTrue(); - // TODO(jack-berg): Use Aggregation.exponentialHistogram() when available AggregatorFactory exponentialHistogram = - ((AggregatorFactory) ExponentialHistogramAggregation.getDefault()); + ((AggregatorFactory) Aggregation.base2ExponentialBucketHistogram()); assertThat(exponentialHistogram.isCompatibleWithInstrument(counter)).isTrue(); assertThat(exponentialHistogram.isCompatibleWithInstrument(observableCounter)).isFalse(); assertThat(exponentialHistogram.isCompatibleWithInstrument(upDownCounter)).isFalse(); assertThat(exponentialHistogram.isCompatibleWithInstrument(observableUpDownCounter)).isFalse(); assertThat(exponentialHistogram.isCompatibleWithInstrument(observableGauge)).isFalse(); + assertThat(exponentialHistogram.isCompatibleWithInstrument(gauge)).isFalse(); assertThat(exponentialHistogram.isCompatibleWithInstrument(histogram)).isTrue(); AggregatorFactory lastValue = ((AggregatorFactory) Aggregation.lastValue()); @@ -104,11 +115,12 @@ void aggregationIsCompatible() { assertThat(lastValue.isCompatibleWithInstrument(upDownCounter)).isFalse(); assertThat(lastValue.isCompatibleWithInstrument(observableUpDownCounter)).isFalse(); assertThat(lastValue.isCompatibleWithInstrument(observableGauge)).isTrue(); + assertThat(lastValue.isCompatibleWithInstrument(gauge)).isTrue(); assertThat(lastValue.isCompatibleWithInstrument(histogram)).isFalse(); } private static InstrumentDescriptor descriptorForType(InstrumentType instrumentType) { return InstrumentDescriptor.create( - "name", "description", "unit", instrumentType, InstrumentValueType.DOUBLE); + "name", "description", "unit", instrumentType, InstrumentValueType.DOUBLE, Advice.empty()); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java index ca1b4ddec63..d6a6de929f4 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/CardinalityTest.java @@ -5,19 +5,29 @@ package io.opentelemetry.sdk.metrics; +import static io.opentelemetry.sdk.metrics.internal.state.MetricStorage.DEFAULT_MAX_CARDINALITY; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongHistogram; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.ObservableLongMeasurement; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.metrics.data.Data; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.data.SumData; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.metrics.internal.state.DefaultSynchronousMetricStorage; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import java.util.concurrent.atomic.AtomicLong; import java.util.function.Consumer; +import java.util.function.Function; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -26,9 +36,6 @@ @SuppressLogger(DefaultSynchronousMetricStorage.class) class CardinalityTest { - /** Traces {@code MetricStorageUtils#MAX_ACCUMULATIONS}. */ - private static final int MAX_ACCUMULATIONS = 2000; - private InMemoryMetricReader deltaReader; private InMemoryMetricReader cumulativeReader; private Meter meter; @@ -50,75 +57,67 @@ void setup() { * are dropped for delta and cumulative readers. Stale metrics are those with attributes that did * not receive recordings in the most recent collection. * - *

      Effectively, we make sure we cap-out at attribute size = 2000 (constant in - * MetricStorageutils). + *

      Effectively, we make sure we cap-out at attribute size = {@link + * MetricStorage#DEFAULT_MAX_CARDINALITY}. */ @Test void staleMetricsDropped_synchronousInstrument() { LongCounter syncCounter = meter.counterBuilder("sync-counter").build(); // Note: This constant comes from MetricStorageUtils, but it's package-private. - for (int i = 1; i <= 2000; i++) { + for (int i = 1; i <= DEFAULT_MAX_CARDINALITY; i++) { syncCounter.add(1, Attributes.builder().put("key", "num_" + i).build()); // DELTA reader only has latest assertThat(deltaReader.collectAllMetrics()) .as("Delta collection " + i) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); // Make sure we preserve previous cumulatives int currentSize = i; assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection " + i) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(currentSize)))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(currentSize)))); } // Now punch the limit and ONLY metrics we just recorded stay, due to simplistic GC. - for (int i = 2001; i <= 2010; i++) { + for (int i = DEFAULT_MAX_CARDINALITY + 1; i <= DEFAULT_MAX_CARDINALITY + 10; i++) { syncCounter.add(1, Attributes.builder().put("key", "num_" + i).build()); } assertThat(deltaReader.collectAllMetrics()) .as("Delta collection - post limit @ 10") - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(10)))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()).isEqualTo(10)))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection - post limit @ 10") - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasName("sync-counter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(10)))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasName("sync-counter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); } /** @@ -132,40 +131,37 @@ void staleMetricsDropped_asynchronousInstrument() { meter .counterBuilder("async-counter") - .buildWithCallback( - measurement -> - measurement.record( - 1, Attributes.builder().put("key", "num_" + count.incrementAndGet()).build())); + .buildWithCallback(measurement -> + measurement.record( + 1, Attributes.builder().put("key", "num_" + count.incrementAndGet()).build())); for (int i = 1; i <= 5; i++) { assertThat(deltaReader.collectAllMetrics()) .as("Delta collection " + i) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasName("async-counter") - .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("async-counter") + .hasLongSumSatisfying(sum -> sum.isDelta().hasPointsSatisfying(point -> {}))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection " + i) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasName("async-counter") - .hasLongSumSatisfying( - sum -> sum.isCumulative().hasPointsSatisfying(point -> {}))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("async-counter") + .hasLongSumSatisfying( + sum -> sum.isCumulative().hasPointsSatisfying(point -> {}))); } } /** * Records to sync instruments, many distinct attributes. Validates that the {@code - * MetricStorageUtils#MAX_ACCUMULATIONS} is enforced for each instrument. + * MetricStorageUtils#MAX_CARDINALITY} is enforced for each instrument. */ @Test - void cardinalityLimits_synchronousInstrument() { + void defaultCardinalityLimits_synchronousInstrument() { LongCounter syncCounter1 = meter.counterBuilder("sync-counter1").build(); LongCounter syncCounter2 = meter.counterBuilder("sync-counter2").build(); - for (int i = 0; i < MAX_ACCUMULATIONS + 1; i++) { + for (int i = 0; i < DEFAULT_MAX_CARDINALITY + 1; i++) { syncCounter1.add(1, Attributes.builder().put("key", "value" + i).build()); syncCounter2.add(1, Attributes.builder().put("key", "value" + i).build()); } @@ -176,25 +172,23 @@ void cardinalityLimits_synchronousInstrument() { metricData -> assertThat(metricData) .hasName("sync-counter1") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("sync-counter2") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS)))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection") @@ -202,36 +196,34 @@ void cardinalityLimits_synchronousInstrument() { metricData -> assertThat(metricData) .hasName("sync-counter1") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("sync-counter2") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS)))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); } /** * Records to sync instruments, many distinct attributes. Validates that the {@code - * MetricStorageUtils#MAX_ACCUMULATIONS} is enforced for each instrument. + * MetricStorageUtils#MAX_CARDINALITY} is enforced for each instrument. */ @Test - void cardinalityLimits_asynchronousInstrument() { + void defaultCardinalityLimits_asynchronousInstrument() { Consumer callback = measurement -> { - for (int i = 0; i < MAX_ACCUMULATIONS + 1; i++) { + for (int i = 0; i < DEFAULT_MAX_CARDINALITY + 1; i++) { measurement.record(1, Attributes.builder().put("key", "value" + i).build()); } }; @@ -244,25 +236,23 @@ void cardinalityLimits_asynchronousInstrument() { metricData -> assertThat(metricData) .hasName("async-counter1") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS))), + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("async-counter2") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS)))); + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); assertThat(cumulativeReader.collectAllMetrics()) .as("Cumulative collection") @@ -270,24 +260,352 @@ void cardinalityLimits_asynchronousInstrument() { metricData -> assertThat(metricData) .hasName("async-counter1") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS))), + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY))), metricData -> assertThat(metricData) .hasName("async-counter2") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - (Consumer>) - sumPointData -> - assertThat(sumPointData.getPoints().size()) - .isEqualTo(MAX_ACCUMULATIONS)))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies( + (Consumer>) + sumPointData -> + assertThat(sumPointData.getPoints().size()) + .isEqualTo(DEFAULT_MAX_CARDINALITY)))); + } + + /** + * Validate ability to customize metric reader cardinality limits via {@link + * SdkMeterProviderBuilder#registerMetricReader(MetricReader, CardinalityLimitSelector)}, and view + * cardinality limits via {@link ViewBuilder#setCardinalityLimit(int)}. + */ + @Test + void readerAndViewCardinalityConfiguration() { + int counterLimit = 10; + int generalLimit = 20; + int counter2Limit = 30; + int asyncCounterLimit = 40; + + // Define a cardinality selector which has one limit for counters, and another general limit for + // other instrument kinds + CardinalityLimitSelector cardinalityLimitSelector = + instrumentType -> instrumentType == InstrumentType.COUNTER ? counterLimit : generalLimit; + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + // Register both the delta and cumulative reader with the customized cardinality + // selector + .registerMetricReader(deltaReader, cardinalityLimitSelector) + .registerMetricReader(cumulativeReader, cardinalityLimitSelector) + // Register a view which defines a custom cardinality limit for instrumented named + // "counter2" + .registerView( + InstrumentSelector.builder().setName("counter2").build(), + View.builder().setCardinalityLimit(counter2Limit).build()) + // Register a view which defines a custom cardinality limit for instrumented named + // "asyncCounter" + .registerView( + InstrumentSelector.builder().setName("asyncCounter").build(), + View.builder().setCardinalityLimit(asyncCounterLimit).build()) + .build(); + + meter = sdkMeterProvider.get(CardinalityTest.class.getName()); + + LongCounter counter1 = meter.counterBuilder("counter1").build(); + LongCounter counter2 = meter.counterBuilder("counter2").build(); + LongHistogram histogram = meter.histogramBuilder("histogram").ofLongs().build(); + meter + .counterBuilder("asyncCounter") + .buildWithCallback(observableMeasurement -> { + // Record enough measurements to exceed cardinality threshold + for (int i = 0; i < DEFAULT_MAX_CARDINALITY; i++) { + observableMeasurement.record(1, Attributes.builder().put("key", i).build()); + } + }); + + // Record enough measurements to exceed cardinality threshold + for (int i = 0; i < DEFAULT_MAX_CARDINALITY; i++) { + counter1.add(1, Attributes.builder().put("key", i).build()); + counter2.add(1, Attributes.builder().put("key", i).build()); + histogram.record(1, Attributes.builder().put("key", i).build()); + } + + // Assert that each instrument has the appropriate number of points based on cardinality limits: + // - counter1 should have counterLimit points + // - counter2 should have counter2Limit points + // - histogram should have generalLimit points + assertThat(deltaReader.collectAllMetrics()) + .as("delta collection") + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + 0, + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("counter2") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + 0, + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), + metricData -> + assertThat(metricData) + .hasName("histogram") + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isDelta() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + 0, + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("asyncCounter") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); + assertThat(cumulativeReader.collectAllMetrics()) + .as("cumulative collection") + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + 0, + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("counter2") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + 0, + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), + metricData -> + assertThat(metricData) + .hasName("histogram") + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isCumulative() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + 0, + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("asyncCounter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); + + // Record another round of measurements, again exceeding cardinality limits + for (int i = DEFAULT_MAX_CARDINALITY; i < DEFAULT_MAX_CARDINALITY * 2; i++) { + counter1.add(1, Attributes.builder().put("key", i).build()); + counter2.add(1, Attributes.builder().put("key", i).build()); + histogram.record(1, Attributes.builder().put("key", i).build()); + } + + // Delta reader should have new points, forgetting the points with measurements recorded prior + // to last collection + assertThat(deltaReader.collectAllMetrics()) + .as("delta collection") + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + DEFAULT_MAX_CARDINALITY, + DEFAULT_MAX_CARDINALITY + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counterLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("counter2") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + DEFAULT_MAX_CARDINALITY, + DEFAULT_MAX_CARDINALITY + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (counter2Limit - 1)))), + metricData -> + assertThat(metricData) + .hasName("histogram") + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isDelta() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + DEFAULT_MAX_CARDINALITY, + DEFAULT_MAX_CARDINALITY + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY - (generalLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("asyncCounter") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + 0)))); + + // Cumulative reader should retain old points, dropping the new measurements + assertThat(cumulativeReader.collectAllMetrics()) + .as("cumulative collection") + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counterLimit, + 0, + counterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY * 2 - (counterLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("counter2") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + counter2Limit, + 0, + counter2Limit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY * 2 - (counter2Limit - 1)))), + metricData -> + assertThat(metricData) + .hasName("histogram") + .hasHistogramSatisfying(histogramMetric -> + histogramMetric + .isCumulative() + .satisfies(data -> + pointsAssert( + data, + generalLimit, + 0, + generalLimit, + HistogramPointData::getCount, + DEFAULT_MAX_CARDINALITY * 2 - (generalLimit - 1)))), + metricData -> + assertThat(metricData) + .hasName("asyncCounter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .satisfies(data -> + pointsAssert( + data, + asyncCounterLimit, + 0, + asyncCounterLimit, + LongPointData::getValue, + DEFAULT_MAX_CARDINALITY - (asyncCounterLimit - 1))))); + } + + /** + * Helper function for {@link #readerAndViewCardinalityConfiguration()}. Asserts that the {@code + * data} contains the {@code expectedNumPoints}, and has the attribute "key" values in the range + * [{@code minAttributeValueInclusive}, {@code maxAttributeValueExclusive}). Additionally, asserts + * that the {@link MetricStorage#CARDINALITY_OVERFLOW} series has a value equal of {@code + * expectedOverflowValue}. + */ + private static void pointsAssert( + Data data, + int expectedNumPoints, + int minAttributeValueInclusive, + int maxAttributeValueExclusive, + Function overflowValueProvider, + long expectedOverflowValue) { + assertThat(data.getPoints()) + .hasSize(expectedNumPoints) + .allSatisfy(point -> { + boolean isOverflowSeries = + point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW); + Long keyValue = point.getAttributes().get(AttributeKey.longKey("key")); + boolean isKeySeries = keyValue != null; + assertThat(isOverflowSeries || isKeySeries).isTrue(); + if (isOverflowSeries) { + assertThat(overflowValueProvider.apply(point)).isEqualTo(expectedOverflowValue); + } + if (isKeySeries) { + assertThat(keyValue) + .isGreaterThanOrEqualTo(minAttributeValueInclusive) + .isLessThan(maxAttributeValueExclusive); + } + }); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java new file mode 100644 index 00000000000..cfe1d05d089 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ExplicitBucketBoundariesAdviceTest.java @@ -0,0 +1,286 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Arrays; +import java.util.Collections; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Stream; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ExplicitBucketBoundariesAdviceTest { + + private SdkMeterProvider meterProvider = SdkMeterProvider.builder().build(); + + @RegisterExtension + LogCapturer logCapturer = + LogCapturer.create() + .captureForLogger(SdkLongHistogram.class.getName()) + .captureForLogger(SdkDoubleHistogram.class.getName()); + + @AfterEach + void cleanup() { + meterProvider.close(); + } + + @ParameterizedTest + @MethodSource("histogramsWithoutAdvice") + void histogramWithoutAdvice(Function> histogramBuilder) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Consumer histogramRecorder = histogramBuilder.apply(meterProvider); + histogramRecorder.accept(5L); + histogramRecorder.accept(15L); + histogramRecorder.accept(25L); + histogramRecorder.accept(35L); + + // Should use default bucket bounds + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(0, 1, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries( + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, 2_500d, + 5_000d, 7_500d, 10_000d)))); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("histogramsWithAdvice") + void histogramWithAdvice(Function> histogramBuilder) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Consumer histogramRecorder = histogramBuilder.apply(meterProvider); + histogramRecorder.accept(5L); + histogramRecorder.accept(15L); + histogramRecorder.accept(25L); + histogramRecorder.accept(35L); + + // Bucket bounds from advice should be used + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point.hasBucketCounts(1, 1, 1, 1).hasBucketBoundaries(10.0, 20.0, 30.0)))); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("histogramsWithAdvice") + void histogramWithAdviceAndViews(Function> histogramBuilder) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(reader) + .registerView( + InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), + View.builder() + .setAggregation( + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.singletonList(50.0)) + .build())) + .build()) + .build(); + + Consumer histogramRecorder = histogramBuilder.apply(meterProvider); + histogramRecorder.accept(5L); + histogramRecorder.accept(15L); + histogramRecorder.accept(25L); + histogramRecorder.accept(35L); + + // View should take priority over bucket bounds from advice + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> point.hasBucketCounts(4, 0).hasBucketBoundaries(50.0)))); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("histogramsWithAdvice") + void histogramWithAdviceAndReaderAggregationPreference( + Function> histogramBuilder) { + InMemoryMetricReader reader = + InMemoryMetricReader.create( + AggregationTemporalitySelector.alwaysCumulative(), + DefaultAggregationSelector.getDefault() + .with( + InstrumentType.HISTOGRAM, + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.singletonList(50.0)) + .build()))); + meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Consumer histogramRecorder = histogramBuilder.apply(meterProvider); + histogramRecorder.accept(5L); + histogramRecorder.accept(15L); + histogramRecorder.accept(25L); + histogramRecorder.accept(35L); + + // Reader aggregation preference should take priority over bucket bounds from advice + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> point.hasBucketCounts(4, 0).hasBucketBoundaries(50.0)))); + + assertThat(logCapturer.getEvents()).isEmpty(); + } + + @ParameterizedTest + @MethodSource("histogramsWithInvalidAdvice") + @SuppressLogger(SdkDoubleHistogram.class) + @SuppressLogger(SdkLongHistogram.class) + void histogramWithInvalidAdvice( + Function> histogramBuilder, String expectedErrorMessage) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Consumer histogramRecorder = histogramBuilder.apply(meterProvider); + histogramRecorder.accept(5L); + histogramRecorder.accept(15L); + histogramRecorder.accept(25L); + histogramRecorder.accept(35L); + + // Should use default bucket bounds + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(0, 1, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries( + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, 2_500d, + 5_000d, 7_500d, 10_000d)))); + + logCapturer.assertContains(expectedErrorMessage); + } + + private static Stream histogramsWithoutAdvice() { + return Stream.of( + Arguments.argumentSet( + "double histogram", + (Function>) + meterProvider -> { + DoubleHistogram histogram = + meterProvider.get("meter").histogramBuilder("histogram").build(); + return histogram::record; + }), + Arguments.argumentSet( + "long histogram", + (Function>) + meterProvider -> { + LongHistogram histogram = + meterProvider.get("meter").histogramBuilder("histogram").ofLongs().build(); + return histogram::record; + })); + } + + private static Stream histogramsWithAdvice() { + return Stream.of( + Arguments.argumentSet( + "double histogram with advice", + (Function>) + meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("meter") + .histogramBuilder("histogram") + .setExplicitBucketBoundariesAdvice(Arrays.asList(10.0, 20.0, 30.0)) + .build(); + return histogram::record; + }), + Arguments.argumentSet( + "long histogram with advice", + (Function>) + meterProvider -> { + LongHistogram histogram = + meterProvider + .get("meter") + .histogramBuilder("histogram") + .ofLongs() + .setExplicitBucketBoundariesAdvice(Arrays.asList(10L, 20L, 30L)) + .build(); + return histogram::record; + })); + } + + private static Stream histogramsWithInvalidAdvice() { + return Stream.of( + Arguments.argumentSet( + "double histogram unsorted advice", + (Function>) + meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("meter") + .histogramBuilder("histogram") + .setExplicitBucketBoundariesAdvice(Arrays.asList(10.0, 9.0, 8.0)) + .build(); + return histogram::record; + }, + "Error setting explicit bucket boundaries advice"), + Arguments.argumentSet( + "long histogram unsorted advice", + (Function>) + meterProvider -> { + LongHistogram histogram = + meterProvider + .get("meter") + .histogramBuilder("histogram") + .ofLongs() + .setExplicitBucketBoundariesAdvice(Arrays.asList(10L, 9L, 8L)) + .build(); + return histogram::record; + }, + "Error setting explicit bucket boundaries advice"), + Arguments.argumentSet( + "double histogram null advice", + (Function>) + meterProvider -> { + DoubleHistogram histogram = + meterProvider + .get("meter") + .histogramBuilder("histogram") + .setExplicitBucketBoundariesAdvice(null) + .build(); + return histogram::record; + }, + "Error setting explicit bucket boundaries advice")); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java index f9e76215f34..00cb18f6dc3 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/IdentityTest.java @@ -8,11 +8,13 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.internal.state.MetricStorageRegistry; import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,6 +29,8 @@ class IdentityTest { @RegisterExtension LogCapturer viewRegistryLogs = LogCapturer.create().captureForType(ViewRegistry.class); + @RegisterExtension LogCapturer sdkMeterLogs = LogCapturer.create().captureForType(SdkMeter.class); + private InMemoryMetricReader reader; private SdkMeterProviderBuilder builder; @@ -46,25 +50,22 @@ void sameMeterSameInstrumentNoViews() { meterProvider.get("meter1").counterBuilder("counter1").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter1")) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); meterProvider.get("meter2").counterBuilder("counter2").ofDoubles().build().add(10); meterProvider.get("meter2").counterBuilder("counter2").ofDoubles().build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter2")) - .hasName("counter2") - .hasDoubleSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter2")) + .hasName("counter2") + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); meterProvider .get("meter3") @@ -80,33 +81,29 @@ void sameMeterSameInstrumentNoViews() { .add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter3")) - .hasName("counter3") - .hasDescription("description3") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter3")) + .hasName("counter3") + .hasDescription("description3") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); meterProvider.get("meter4").counterBuilder("counter4").setUnit("unit4").build().add(10); meterProvider.get("meter4").counterBuilder("counter4").setUnit("unit4").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter4")) - .hasName("counter4") - .hasUnit("unit4") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter4")) + .hasName("counter4") + .hasUnit("unit4") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } @Test - void sameMeterDifferentInstrumentNoViews() { + void sameMeterDifferentInstrumentNameNoViews() { SdkMeterProvider meterProvider = builder.build(); meterProvider.get("meter1").counterBuilder("counter1").build().add(10); @@ -130,6 +127,134 @@ void sameMeterDifferentInstrumentNoViews() { assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } + @Test + void sameMeterDifferentInstrumentNameCaseNoViews() { + SdkMeterProvider meterProvider = builder.build(); + + meterProvider.get("meter1").counterBuilder("Counter1").build().add(10); + meterProvider.get("meter1").counterBuilder("counter1").build().add(10); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("Counter1") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + + assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); + } + + @Test + @SuppressLogger(MetricStorageRegistry.class) + void sameMeterSameInstrumentNameDifferentIdentifyingFieldsNoViews() { + SdkMeterProvider meterProvider = builder.build(); + + meterProvider.get("meter1").counterBuilder("counter1").build().add(10); + // Same name, different unit + meterProvider.get("meter1").counterBuilder("counter1").setUnit("unit1").build().add(10); + // Same name, different description + meterProvider + .get("meter1") + .counterBuilder("counter1") + .setDescription("description1") + .build() + .add(10); + // Same name, different value type + meterProvider.get("meter1").counterBuilder("counter1").ofDoubles().build().add(10); + // Same name, different instrument type + meterProvider.get("meter1").upDownCounterBuilder("counter1").build().add(10); + + // When name is the same, but some identifying field is different (unit, description, value + // type, instrument type) we produce different metric streams are produced and log a warning + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasUnit("unit1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasDescription("description1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasDoubleSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10)))); + + assertThat(metricStorageRegistryLogs.getEvents()) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .hasSize(4); + } + + @Test + void sameMeterSameInstrumentNameDifferentNonIdentifyingFieldsNoViews() { + SdkMeterProvider meterProvider = builder.build(); + + // Register histogram1, with and without advice. First registration without advice wins. + meterProvider.get("meter1").histogramBuilder("histogram1").build().record(8); + meterProvider + .get("meter1") + .histogramBuilder("histogram1") + .setExplicitBucketBoundariesAdvice(Arrays.asList(10.0, 20.0, 30.0)) + .build() + .record(8); + + // Register histogram2, with and without advice. First registration with advice wins. + meterProvider + .get("meter1") + .histogramBuilder("histogram2") + .setExplicitBucketBoundariesAdvice(Arrays.asList(10.0, 20.0, 30.0)) + .build() + .record(8); + meterProvider.get("meter1").histogramBuilder("histogram2").build().record(8); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("histogram1") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasBucketBoundaries( + 0d, 5d, 10d, 25d, 50d, 75d, 100d, 250d, 500d, 750d, 1_000d, + 2_500d, 5_000d, 7_500d, 10_000d))), + metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("histogram2") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasBucketCounts(2, 0, 0, 0) + .hasBucketBoundaries(10.0, 20.0, 30.0)))); + + assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); + } + @Test void differentMeterSameInstrumentNoViews() { // Meters are the same if their name, version, and scope are all equals @@ -173,7 +298,7 @@ void differentMeterSameInstrumentNoViews() { metricData -> assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", "version1", null)) + InstrumentationScopeInfo.builder("meter1").setVersion("version1").build()) .hasName("counter1") .hasLongSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); @@ -199,14 +324,17 @@ void differentMeterSameInstrumentNoViews() { metricData -> assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", "version1", null)) + InstrumentationScopeInfo.builder("meter1").setVersion("version1").build()) .hasName("counter1") .hasLongSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(10))), metricData -> assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", "version1", "schema1")) + InstrumentationScopeInfo.builder("meter1") + .setVersion("version1") + .setSchemaUrl("schema1") + .build()) .hasName("counter1") .hasLongSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); @@ -247,9 +375,8 @@ void sameMeterConflictingInstrumentDescriptionNoViews() { }); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -280,9 +407,8 @@ void sameMeterConflictingInstrumentUnitNoViews() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -301,9 +427,8 @@ void sameMeterConflictingInstrumentTypeNoViews() { assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic().hasPointsSatisfying(point -> point.hasValue(10))), metricData -> assertThat(metricData) .hasInstrumentationScope(forMeter("meter1")) @@ -312,9 +437,8 @@ void sameMeterConflictingInstrumentTypeNoViews() { sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -343,9 +467,8 @@ void sameMeterConflictingInstrumentValueTypeNoViews() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -362,14 +485,12 @@ void sameMeterSameInstrumentSingleView() { meterProvider.get("meter1").counterBuilder("counter1").build().add(10); assertThat(reader.collectAllMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(forMeter("meter1")) - .hasName("counter1") - .hasDescription("description1") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("counter1") + .hasDescription("description1") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); } @@ -566,7 +687,7 @@ void differentMeterSameInstrumentViewSelectingMeterVersion() { metricData -> assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", "version1", null)) + InstrumentationScopeInfo.builder("meter1").setVersion("version1").build()) .hasName("counter1") .hasDescription("description1") .hasLongSumSatisfying( @@ -574,7 +695,7 @@ void differentMeterSameInstrumentViewSelectingMeterVersion() { metricData -> { assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", "version2", null)) + InstrumentationScopeInfo.builder("meter1").setVersion("version2").build()) .hasName("counter1") .hasLongSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(10))); @@ -613,7 +734,7 @@ void differentMeterSameInstrumentViewSelectingMeterSchema() { metricData -> assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", null, "schema1")) + InstrumentationScopeInfo.builder("meter1").setSchemaUrl("schema1").build()) .hasName("counter1") .hasDescription("description1") .hasLongSumSatisfying( @@ -621,7 +742,7 @@ void differentMeterSameInstrumentViewSelectingMeterSchema() { metricData -> { assertThat(metricData) .hasInstrumentationScope( - InstrumentationScopeInfo.create("meter1", null, "schema2")) + InstrumentationScopeInfo.builder("meter1").setSchemaUrl("schema2").build()) .hasName("counter1") .hasLongSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(10))); @@ -711,9 +832,8 @@ void sameMeterSameInstrumentConflictingViewDescriptions() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(20)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -751,9 +871,8 @@ void sameMeterSameInstrumentConflictingViewAggregations() { histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(20)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); assertThat(viewRegistryLogs.getEvents()).hasSize(0); } @@ -789,9 +908,8 @@ void sameMeterDifferentInstrumentConflictingViewName() { sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); assertThat(metricStorageRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()).contains("Found duplicate metric definition")) .hasSize(1); } @@ -943,11 +1061,56 @@ void sameMeterDifferentInstrumentIncompatibleViewAggregation() { assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); assertThat(viewRegistryLogs.getEvents()) - .allSatisfy( - logEvent -> - assertThat(logEvent.getMessage()) - .contains( - "View aggregation explicit_bucket_histogram is incompatible with instrument counter1 of type OBSERVABLE_COUNTER")) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()) + .contains( + "View aggregation explicit_bucket_histogram is incompatible with instrument counter1 of type OBSERVABLE_COUNTER")) + .hasSize(1); + } + + @Test + void viewNameNotValidated() { + // View names are not validated against the instrument name pattern. When a view sets a name + // that would be rejected if used directly as an instrument name (e.g. starts with a digit), + // the SDK accepts it and produces a metric with the invalid name without logging a warning. + SdkMeterProvider meterProvider = + builder + .registerView( + InstrumentSelector.builder().setType(InstrumentType.COUNTER).build(), + View.builder().setName("1invalid-name").build()) + .build(); + + LongCounter counter = meterProvider.get("meter1").counterBuilder("counter1").build(); + counter.add(10); + + assertThat(counter.isEnabled()).isTrue(); + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasInstrumentationScope(forMeter("meter1")) + .hasName("1invalid-name") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(10)))); + + assertThat(metricStorageRegistryLogs.getEvents()).hasSize(0); + assertThat(viewRegistryLogs.getEvents()).hasSize(0); + } + + @Test + @SuppressLogger(SdkMeter.class) + void instrumentWithInvalidName() { + // When an instrument is initialized with an invalid name, a noop instrument is returned + // and a warning is logged. No metric data is produced. + SdkMeterProvider meterProvider = builder.build(); + + LongCounter counter = meterProvider.get("meter1").counterBuilder("1invalid-name").build(); + counter.add(10); + + assertThat(counter.isEnabled()).isFalse(); + assertThat(reader.collectAllMetrics()).isEmpty(); + assertThat(sdkMeterLogs.getEvents()) + .allSatisfy(logEvent -> + assertThat(logEvent.getMessage()) + .contains("Instrument name \"1invalid-name\" is invalid")) .hasSize(1); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentBuilderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentBuilderTest.java new file mode 100644 index 00000000000..f2b8db0c2a1 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentBuilderTest.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal.asExemplarFilterInternal; +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.state.MeterProviderSharedState; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.testing.time.TestClock; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class InstrumentBuilderTest { + + public static final MeterProviderSharedState PROVIDER_SHARED_STATE = + MeterProviderSharedState.create( + TestClock.create(), + SdkResourceProvider.create(Resource.getDefault()), + asExemplarFilterInternal(ExemplarFilter.alwaysOff()), + /* contextScopedAttributesFilter= */ null); + static final InstrumentationScopeInfo SCOPE = InstrumentationScopeInfo.create("scope-name"); + public static final SdkMeter SDK_METER = + new SdkMeter( + PROVIDER_SHARED_STATE, SCOPE, Collections.emptyList(), MeterConfig.defaultConfig()); + + @Test + void stringRepresentation() { + InstrumentBuilder builder = + new InstrumentBuilder( + "instrument-name", InstrumentType.COUNTER, InstrumentValueType.LONG, SDK_METER) + .setDescription("instrument-description") + .setUnit("instrument-unit") + .setAdviceBuilder(Advice.builder()); + assertThat(builder.toString()) + .isEqualTo( + "InstrumentBuilder{" + + "descriptor=" + + "InstrumentDescriptor{" + + "name=instrument-name, " + + "description=instrument-description, " + + "unit=instrument-unit, " + + "type=COUNTER, " + + "valueType=LONG, " + + "advice=Advice{explicitBucketBoundaries=null, attributes=null}" + + "}}"); + } + + @Test + void toStringHelper() { + InstrumentBuilder builder = + new InstrumentBuilder( + "instrument-name", InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE, SDK_METER) + .setDescription("instrument-description") + .setUnit("instrument-unit") + .setAdviceBuilder(Advice.builder()); + + assertThat(builder.toStringHelper("FooBuilder")) + .isEqualTo( + "FooBuilder{" + + "descriptor=" + + "InstrumentDescriptor{" + + "name=instrument-name, " + + "description=instrument-description, " + + "unit=instrument-unit, " + + "type=HISTOGRAM, " + + "valueType=DOUBLE, " + + "advice=Advice{explicitBucketBoundaries=null, attributes=null}" + + "}}"); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentSelectorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentSelectorTest.java index 68afed0c9c6..d89c946c903 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentSelectorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/InstrumentSelectorTest.java @@ -20,6 +20,9 @@ void invalidArgs() { assertThatThrownBy(() -> InstrumentSelector.builder().setName(null)) .isInstanceOf(NullPointerException.class) .hasMessage("name"); + assertThatThrownBy(() -> InstrumentSelector.builder().setUnit(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); assertThatThrownBy(() -> InstrumentSelector.builder().setMeterName(null)) .isInstanceOf(NullPointerException.class) .hasMessage("meterName"); @@ -51,6 +54,12 @@ void instrumentName() { assertThat(selector.getInstrumentName()).isEqualTo("bar"); } + @Test + void instrumentUnit() { + InstrumentSelector selector = InstrumentSelector.builder().setName("ms").setName("s").build(); + assertThat(selector.getInstrumentName()).isEqualTo("s"); + } + @Test void meterName() { InstrumentSelector selector = @@ -83,6 +92,7 @@ void stringRepresentation() { InstrumentSelector.builder() .setType(InstrumentType.COUNTER) .setName("name") + .setUnit("unit") .setMeterName("meter") .setMeterVersion("version") .setMeterSchemaUrl("http://url.com") @@ -92,6 +102,7 @@ void stringRepresentation() { "InstrumentSelector{" + "instrumentType=COUNTER, " + "instrumentName=name, " + + "instrumentUnit=unit, " + "meterName=meter, " + "meterVersion=version, " + "meterSchemaUrl=http://url.com" diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java index 29c68e239fd..dffeaea887e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkBatchCallbackTest.java @@ -84,77 +84,53 @@ void collectAllMetrics() { .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("longCounter") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("key", "val1")))), + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("key", "val1")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("doubleCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1.1) - .hasAttributes(attributeEntry("key", "val2")))), + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(1.1).hasAttributes(attributeEntry("key", "val2")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("longUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(2) - .hasAttributes(attributeEntry("key", "val3")))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(2).hasAttributes(attributeEntry("key", "val3")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("doubleUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(2.2) - .hasAttributes(attributeEntry("key", "val4")))), + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(2.2).hasAttributes(attributeEntry("key", "val4")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("longGauge") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(3) - .hasAttributes(attributeEntry("key", "val5")))), + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasValue(3).hasAttributes(attributeEntry("key", "val5")))), metric -> assertThat(metric) .hasResource(RESOURCE) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("doubleGauge") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(3.3) - .hasAttributes(attributeEntry("key", "val6"))))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasValue(3.3).hasAttributes(attributeEntry("key", "val6"))))); // Should not be called after closed batchCallback.close(); @@ -175,14 +151,13 @@ void collectAllMetrics_RecordToUnregisteredInstrument() { // counter2 is not registered and measurements should be ignored assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); observableMeasurementLogs.assertContains( "Measurement recorded for instrument counter2 outside callback registered to instrument. Dropping measurement."); @@ -199,20 +174,15 @@ void collectAllMetrics_RecordOutsideCallback() { () -> counter1.record(1, Attributes.builder().put("key", "value2").build()), counter1); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(1) - .hasAttributes(attributeEntry("key", "value2"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .hasPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("key", "value2"))))); observableMeasurementLogs.assertContains( "Measurement recorded for instrument counter1 outside callback registered to instrument. Dropping measurement."); @@ -235,14 +205,13 @@ void collectAllMetrics_InstrumentFromAnotherMeter() { // counter2 belongs to another meter and measurements should be ignored assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); sdkMeterLogs.assertContains( "batchCallback called with instruments that belong to a different Meter."); @@ -271,14 +240,13 @@ public void record(long value, Attributes attributes) {} // counter2 was not obtained from the sdk and its measurements should be ignored. assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("counter1") - .hasLongSumSatisfying( - sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("counter1") + .hasLongSumSatisfying( + sum -> sum.isMonotonic().hasPointsSatisfying(point -> point.hasValue(1)))); sdkMeterLogs.assertContains( "batchCallback called with instruments that were not created by the SDK."); diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java index 43bf889d236..1f738e59285 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleCounterTest.java @@ -16,8 +16,7 @@ import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.StressTestRunner.OperationUpdater; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundDoubleCounter; +import io.opentelemetry.sdk.metrics.internal.state.DefaultSynchronousMetricStorage; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; @@ -52,26 +51,10 @@ void add_PreventNullAttributes() { .hasMessage("attributes"); } - @Test - void bound_PreventNullAttributes() { - assertThatThrownBy( - () -> - ((SdkDoubleCounter) sdkMeter.counterBuilder("testCounter").ofDoubles().build()) - .bind(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("attributes"); - } - @Test void collectMetrics_NoRecords() { - DoubleCounter doubleCounter = sdkMeter.counterBuilder("testCounter").ofDoubles().build(); - BoundDoubleCounter bound = - ((SdkDoubleCounter) doubleCounter).bind(Attributes.builder().put("foo", "bar").build()); - try { - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } finally { - bound.unbind(); - } + sdkMeter.counterBuilder("testCounter").ofDoubles().build(); + assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); } @Test @@ -86,98 +69,85 @@ void collectMetrics_WithEmptyAttributes() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleCounter.add(12d, Attributes.empty()); doubleCounter.add(12d); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDescription("description") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasDescription("description") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test void collectMetrics_WithMultipleCollects() { long startTime = testClock.now(); DoubleCounter doubleCounter = sdkMeter.counterBuilder("testCounter").ofDoubles().build(); - BoundDoubleCounter bound = - ((SdkDoubleCounter) doubleCounter).bind(Attributes.builder().put("K", "V").build()); - try { - // Do some records using bounds and direct calls and bindings. - doubleCounter.add(12.1d, Attributes.empty()); - bound.add(123.3d); - doubleCounter.add(21.4d, Attributes.empty()); - // Advancing time here should not matter. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(321.5d); - doubleCounter.add(111.1d, Attributes.builder().put("K", "V").build()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDescription("") - .hasUnit("") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(555.9) - .hasAttributes(attributeEntry("K", "V"))))); - - // Repeat to prove we keep previous values. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(222d); - doubleCounter.add(11d, Attributes.empty()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(777.9) - .hasAttributes(attributeEntry("K", "V"))))); - } finally { - bound.unbind(); - } + doubleCounter.add(12.1d, Attributes.empty()); + doubleCounter.add(123.3d, Attributes.builder().put("K", "V").build()); + doubleCounter.add(21.4d, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleCounter.add(321.5d, Attributes.builder().put("K", "V").build()); + doubleCounter.add(111.1d, Attributes.builder().put("K", "V").build()); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasDescription("") + .hasUnit("") + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(555.9) + .hasAttributes(attributeEntry("K", "V"))))); + + // Repeat to prove we keep previous values. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleCounter.add(222d, Attributes.builder().put("K", "V").build()); + doubleCounter.add(11d, Attributes.empty()); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(777.9) + .hasAttributes(attributeEntry("K", "V"))))); } @Test @@ -191,162 +161,10 @@ void doubleCounterAdd_Monotonicity() { } @Test - @SuppressLogger(SdkDoubleCounter.class) - void boundDoubleCounterAdd_Monotonicity() { + @SuppressLogger(DefaultSynchronousMetricStorage.class) + void doubleCounterAdd_NaN() { DoubleCounter doubleCounter = sdkMeter.counterBuilder("testCounter").ofDoubles().build(); - BoundDoubleCounter bound = ((SdkDoubleCounter) doubleCounter).bind(Attributes.empty()); - try { - bound.add(-9.3); - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); - logs.assertContains( - "Counters can only increase. Instrument testCounter has recorded a negative value."); - } finally { - bound.unbind(); - } - } - - @Test - void stressTest() { - DoubleCounter doubleCounter = sdkMeter.counterBuilder("testCounter").ofDoubles().build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkDoubleCounter) doubleCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, 2, new OperationUpdaterDirectCall(doubleCounter, "K", "V"))); - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new OperationUpdaterWithBinding( - ((SdkDoubleCounter) doubleCounter) - .bind(Attributes.builder().put("K", "V").build())))); - } - - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(80_000) - .hasAttributes(attributeEntry("K", "V"))))); - } - - @Test - void stressTest_WithDifferentLabelSet() { - String[] keys = {"Key_1", "Key_2", "Key_3", "Key_4"}; - String[] values = {"Value_1", "Value_2", "Value_3", "Value_4"}; - DoubleCounter doubleCounter = sdkMeter.counterBuilder("testCounter").ofDoubles().build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkDoubleCounter) doubleCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, 1, new OperationUpdaterDirectCall(doubleCounter, keys[i], values[i]))); - - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new OperationUpdaterWithBinding( - ((SdkDoubleCounter) doubleCounter) - .bind(Attributes.builder().put(keys[i], values[i]).build())))); - } - - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[0], values[0])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[1], values[1])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[2], values[2])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[3], values[3]))))); - } - - private static class OperationUpdaterWithBinding extends OperationUpdater { - private final BoundDoubleCounter boundDoubleCounter; - - private OperationUpdaterWithBinding(BoundDoubleCounter boundDoubleCounter) { - this.boundDoubleCounter = boundDoubleCounter; - } - - @Override - void update() { - boundDoubleCounter.add(9.0); - } - - @Override - void cleanup() { - boundDoubleCounter.unbind(); - } - } - - private static class OperationUpdaterDirectCall extends OperationUpdater { - - private final DoubleCounter doubleCounter; - private final String key; - private final String value; - - private OperationUpdaterDirectCall(DoubleCounter doubleCounter, String key, String value) { - this.doubleCounter = doubleCounter; - this.key = key; - this.value = value; - } - - @Override - void update() { - doubleCounter.add(11.0, Attributes.builder().put(key, value).build()); - } - - @Override - void cleanup() {} + doubleCounter.add(Double.NaN); + assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeBuilderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeBuilderTest.java deleted file mode 100644 index ec98c2c0f64..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeBuilderTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableDoubleGauge; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import io.opentelemetry.sdk.testing.time.TestClock; -import java.time.Duration; -import org.junit.jupiter.api.Test; - -/** Unit tests for SDK {@link ObservableDoubleGauge}. */ -class SdkDoubleGaugeBuilderTest { - private static final Resource RESOURCE = - Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); - private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create(SdkDoubleGaugeBuilderTest.class.getName()); - private final TestClock testClock = TestClock.create(); - private final InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); - private final SdkMeterProvider sdkMeterProvider = - SdkMeterProvider.builder() - .setClock(testClock) - .setResource(RESOURCE) - .registerMetricReader(sdkMeterReader) - .build(); - private final Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); - - @Test - void removeCallback() { - ObservableDoubleGauge gauge = - sdkMeter.gaugeBuilder("testGauge").buildWithCallback(measurement -> measurement.record(10)); - - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasDoubleGaugeSatisfying( - doubleGauge -> doubleGauge.hasPointsSatisfying(poit -> {}))); - - gauge.close(); - - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); - } - - @Test - void collectMetrics_NoRecords() { - sdkMeter - .gaugeBuilder("testObserver") - .setDescription("My own DoubleValueObserver") - .setUnit("ms") - .buildWithCallback(result -> {}); - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } - - @Test - void collectMetrics_WithOneRecord() { - sdkMeter - .gaugeBuilder("testObserver") - .setDescription("My own DoubleValueObserver") - .setUnit("ms") - .buildWithCallback( - result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); - testClock.advance(Duration.ofSeconds(1)); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleValueObserver") - .hasUnit("ms") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000L) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("k", "v")) - .hasValue(12.1d)))); - testClock.advance(Duration.ofSeconds(1)); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleValueObserver") - .hasUnit("ms") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2000000000L) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("k", "v")) - .hasValue(12.1d)))); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java new file mode 100644 index 00000000000..d3f9e40e0d0 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleGaugeTest.java @@ -0,0 +1,313 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.DoubleGauge; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.ObservableDoubleGauge; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Scope; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.internal.state.DefaultSynchronousMetricStorage; +import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.time.Duration; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link SdkDoubleGauge}. */ +class SdkDoubleGaugeTest { + private static final long SECOND_NANOS = 1_000_000_000; + private static final Resource RESOURCE = + Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.create(SdkDoubleGaugeTest.class.getName()); + private final TestClock testClock = TestClock.create(); + private final InMemoryMetricReader cumulativeReader = InMemoryMetricReader.create(); + private final InMemoryMetricReader deltaReader = InMemoryMetricReader.createDelta(); + private final SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .registerMetricReader(cumulativeReader) + .registerMetricReader(deltaReader) + .setResource(RESOURCE) + .build(); + private final Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + + @Test + void set_PreventNullAttributes() { + assertThatThrownBy(() -> sdkMeter.gaugeBuilder("testGauge").build().set(1.0, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("attributes"); + } + + @Test + @SuppressLogger(DefaultSynchronousMetricStorage.class) + void set_NaN() { + DoubleGauge gauge = sdkMeter.gaugeBuilder("testGauge").build(); + gauge.set(Double.NaN); + assertThat(cumulativeReader.collectAllMetrics()).hasSize(0); + } + + @Test + void observable_RemoveCallback() { + ObservableDoubleGauge gauge = + sdkMeter.gaugeBuilder("testGauge").buildWithCallback(measurement -> measurement.record(10)); + + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasDoubleGaugeSatisfying( + doubleGauge -> doubleGauge.hasPointsSatisfying(point -> {}))); + + gauge.close(); + + assertThat(cumulativeReader.collectAllMetrics()).hasSize(0); + } + + @Test + @SuppressLogger(SdkObservableMeasurement.class) + void observable_NaN() { + sdkMeter + .gaugeBuilder("testGauge") + .buildWithCallback(measurement -> measurement.record(Double.NaN)); + assertThat(cumulativeReader.collectAllMetrics()).hasSize(0); + } + + @Test + void collectMetrics_NoRecords() { + sdkMeter.gaugeBuilder("testGauge").build(); + assertThat(cumulativeReader.collectAllMetrics()).isEmpty(); + } + + @Test + void collectMetrics_WithEmptyAttributes() { + DoubleGauge doubleGauge = + sdkMeter.gaugeBuilder("testGauge").setDescription("description").setUnit("K").build(); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleGauge.set(12d, Attributes.empty()); + doubleGauge.set(13d); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(13d)))); + } + + @Test + void collectMetrics_WithExemplars() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerView( + InstrumentSelector.builder().setName("*").build(), + View.builder().setAttributeFilter(Collections.emptySet()).build()) + .registerMetricReader(reader) + .build(); + Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + DoubleGauge doubleGauge = + sdkMeter.gaugeBuilder("testGauge").setDescription("description").setUnit("K").build(); + + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); + Tracer tracer = tracerProvider.get("foo"); + + Span span = tracer.spanBuilder("span").startSpan(); + try (Scope unused = span.makeCurrent()) { + doubleGauge.set(12d, Attributes.builder().put("key", "value").build()); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12d) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(12d) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); + } + + @Test + void observable_CollectMetrics_DefaultExemplarFilter_NoExemplars() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerMetricReader(reader) + .build(); + + sdkMeterProvider + .get(getClass().getName()) + .gaugeBuilder("testGauge") + .buildWithCallback(measurement -> measurement.record(12d, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasValue(12d).hasExemplars()))); + } + + @Test + void observable_CollectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(reader) + .build(); + + sdkMeterProvider + .get(getClass().getName()) + .gaugeBuilder("testGauge") + .buildWithCallback(measurement -> measurement.record(12d, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12d) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12d))))); + } + + @Test + void collectMetrics_WithMultipleCollects() { + long startTime = testClock.now(); + DoubleGauge doubleGauge = sdkMeter.gaugeBuilder("testGauge").build(); + doubleGauge.set(12.1d, Attributes.empty()); + doubleGauge.set(123.3d, Attributes.builder().put("K", "V").build()); + doubleGauge.set(21.4d, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleGauge.set(321.5d, Attributes.builder().put("K", "V").build()); + doubleGauge.set(111.1d, Attributes.builder().put("K", "V").build()); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21.4d), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111.1d) + .hasAttributes(attributeEntry("K", "V"))))); + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21.4d), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111.1d) + .hasAttributes(attributeEntry("K", "V"))))); + + // Repeat to prove we keep previous values. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleGauge.set(222d, Attributes.builder().put("K", "V").build()); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21.4d), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(222d) + .hasAttributes(attributeEntry("K", "V"))))); + // Delta reader should only have point for {K=V} series, since the {} did not have any + // measurements + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(startTime + SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(222d) + .hasAttributes(attributeEntry("K", "V"))))); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java index dedeba46a2f..7058ae02210 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleHistogramTest.java @@ -8,22 +8,27 @@ import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.DoubleHistogram; import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Scope; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.StressTestRunner.OperationUpdater; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundDoubleHistogram; -import io.opentelemetry.sdk.metrics.internal.view.ExponentialHistogramAggregation; +import io.opentelemetry.sdk.metrics.internal.state.DefaultSynchronousMetricStorage; import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; import java.time.Duration; +import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -55,27 +60,10 @@ void record_PreventNullAttributes() { .hasMessage("attributes"); } - @Test - void bound_PreventNullAttributes() { - assertThatThrownBy( - () -> - ((SdkDoubleHistogram) sdkMeter.histogramBuilder("testHistogram").build()) - .bind(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("attributes"); - } - @Test void collectMetrics_NoRecords() { - DoubleHistogram doubleHistogram = sdkMeter.histogramBuilder("testHistogram").build(); - BoundDoubleHistogram bound = - ((SdkDoubleHistogram) doubleHistogram) - .bind(Attributes.builder().put("key", "value").build()); - try { - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } finally { - bound.unbind(); - } + sdkMeter.histogramBuilder("testHistogram").build(); + assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); } @Test @@ -89,113 +77,95 @@ void collectMetrics_WithEmptyAttributes() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleHistogram.record(12d, Attributes.empty()); doubleHistogram.record(12d); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("ms") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(24) - .hasBucketBoundaries( - 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, - 5_000, 7_500, 10_000) - .hasBucketCounts( - 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("ms") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(24) + .hasBucketBoundaries( + 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, 5_000, + 7_500, 10_000) + .hasBucketCounts(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); } @Test void collectMetrics_WithMultipleCollects() { long startTime = testClock.now(); DoubleHistogram doubleHistogram = sdkMeter.histogramBuilder("testHistogram").build(); - BoundDoubleHistogram bound = - ((SdkDoubleHistogram) doubleHistogram).bind(Attributes.builder().put("K", "V").build()); - try { - // Do some records using bounds and direct calls and bindings. - doubleHistogram.record(9.1d, Attributes.empty()); - bound.record(123.3d); - doubleHistogram.record(13.1d, Attributes.empty()); - // Advancing time here should not matter. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.record(321.5d); - doubleHistogram.record(121.5d, Attributes.builder().put("K", "V").build()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(566.3d) - .hasBucketCounts( - 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(2) - .hasSum(22.2d) - .hasBucketCounts( - 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); + doubleHistogram.record(9.1d, Attributes.empty()); + doubleHistogram.record(123.3d, Attributes.builder().put("K", "V").build()); + doubleHistogram.record(13.1d, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleHistogram.record(321.5d, Attributes.builder().put("K", "V").build()); + doubleHistogram.record(121.5d, Attributes.builder().put("K", "V").build()); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(566.3d) + .hasBucketCounts(0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(2) + .hasSum(22.2d) + .hasBucketCounts(0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); - // Histograms are cumulative by default. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.record(222d); - doubleHistogram.record(17d, Attributes.empty()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(4) - .hasSum(788.3) - .hasBucketCounts( - 0, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(39.2) - .hasBucketCounts( - 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); - } finally { - bound.unbind(); - } + // Histograms are cumulative by default. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleHistogram.record(222d, Attributes.builder().put("K", "V").build()); + doubleHistogram.record(17d, Attributes.empty()); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(4) + .hasSum(788.3) + .hasBucketCounts(0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(39.2) + .hasBucketCounts(0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); } @Test @@ -208,7 +178,12 @@ void collectMetrics_ExponentialHistogramAggregation() { .registerView( InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), View.builder() - .setAggregation(ExponentialHistogramAggregation.create(-1, 5)) + .setAggregation( + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(5) + .setMaxScale(20) + .build())) .build()) .build(); DoubleHistogram doubleHistogram = @@ -220,57 +195,56 @@ void collectMetrics_ExponentialHistogramAggregation() { .build(); testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleHistogram.record(12d, Attributes.builder().put("key", "value").build()); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleHistogram.record(12d); doubleHistogram.record(13d); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - MetricAssertions.assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("ms") - .hasExponentialHistogram() - .isCumulative() - .points() - .satisfiesExactlyInAnyOrder( - point -> { - MetricAssertions.assertThat(point) - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(25) - .hasMin(12) - .hasMax(13) - .hasScale(-1) - .hasZeroCount(0); - MetricAssertions.assertThat(point.getPositiveBuckets()) - .hasOffset(1) - .hasCounts(Collections.singletonList(2L)); - MetricAssertions.assertThat(point.getNegativeBuckets()) - .hasOffset(0) - .hasCounts(Collections.emptyList()); - }, - point -> { - MetricAssertions.assertThat(point) - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.builder().put("key", "value").build()) - .hasCount(1) - .hasSum(12) - .hasMin(12) - .hasMax(12) - .hasScale(-1) - .hasZeroCount(0); - MetricAssertions.assertThat(point.getPositiveBuckets()) - .hasOffset(1) - .hasCounts(Collections.singletonList(1L)); - MetricAssertions.assertThat(point.getNegativeBuckets()) - .hasOffset(0) - .hasCounts(Collections.emptyList()); - })); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("ms") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(25) + .hasMin(12) + .hasMax(13) + .hasScale(5) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(114) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList())), + point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.builder().put("key", "value").build()) + .hasCount(1) + .hasSum(12) + .hasMin(12) + .hasMax(12) + .hasScale(20) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(3759105) + .hasCounts(Collections.singletonList(1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList()))))); } @Test @@ -284,176 +258,95 @@ void doubleHistogramRecord_NonNegativeCheck() { } @Test - @SuppressLogger(SdkDoubleHistogram.class) - void boundDoubleHistogramRecord_MonotonicityCheck() { + @SuppressLogger(DefaultSynchronousMetricStorage.class) + void doubleHistogramRecord_NaN() { DoubleHistogram histogram = sdkMeter.histogramBuilder("testHistogram").build(); - BoundDoubleHistogram bound = ((SdkDoubleHistogram) histogram).bind(Attributes.empty()); - try { - bound.record(-9); - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); - logs.assertContains( - "Histograms can only record non-negative values. Instrument testHistogram has recorded a negative value."); - } finally { - bound.unbind(); - } + histogram.record(Double.NaN); + assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); } @Test - void stressTest() { - DoubleHistogram doubleHistogram = sdkMeter.histogramBuilder("testHistogram").build(); + void collectMetrics_ExemplarsWithExponentialHistogram() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerView( + InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), + View.builder() + .setAggregation(Aggregation.base2ExponentialBucketHistogram()) + .setAttributeFilter(Collections.emptySet()) + .build()) + .registerMetricReader(reader) + .build(); + Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + DoubleHistogram histogram = sdkMeter.histogramBuilder("testHistogram").build(); - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkDoubleHistogram) doubleHistogram) - .setCollectionIntervalMs(100); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); + Tracer tracer = tracerProvider.get("foo"); - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new SdkDoubleHistogramTest.OperationUpdaterDirectCall(doubleHistogram, "K", "V"))); - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new OperationUpdaterWithBinding( - ((SdkDoubleHistogram) doubleHistogram) - .bind(Attributes.builder().put("K", "V").build())))); + Span span = tracer.spanBuilder("span").startSpan(); + try (Scope unused = span.makeCurrent()) { + histogram.record(10, Attributes.builder().put("key", "value").build()); } - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasCount(8_000) - .hasSum(80_000)))); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasExponentialHistogramSatisfying(exponentialHistogram -> + exponentialHistogram.hasPointsSatisfying(point -> + point + .hasSum(10.0) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } @Test - void stressTest_WithDifferentLabelSet() { - String[] keys = {"Key_1", "Key_2", "Key_3", "Key_4"}; - String[] values = {"Value_1", "Value_2", "Value_3", "Value_4"}; - DoubleHistogram doubleHistogram = sdkMeter.histogramBuilder("testHistogram").build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkDoubleHistogram) doubleHistogram) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new SdkDoubleHistogramTest.OperationUpdaterDirectCall( - doubleHistogram, keys[i], values[i]))); - - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new OperationUpdaterWithBinding( - ((SdkDoubleHistogram) doubleHistogram) - .bind(Attributes.builder().put(keys[i], values[i]).build())))); - } - - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(4_000) - .hasSum(40_000) - .hasBucketCounts( - 0, 2000, 2000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[0], values[0])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(4_000) - .hasSum(40_000) - .hasBucketCounts( - 0, 2000, 2000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[1], values[1])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(4_000) - .hasSum(40_000) - .hasBucketCounts( - 0, 2000, 2000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[2], values[2])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(4_000) - .hasSum(40_000) - .hasBucketCounts( - 0, 2000, 2000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[3], values[3]))))); - } - - private static class OperationUpdaterWithBinding extends OperationUpdater { - private final BoundDoubleHistogram boundDoubleHistogram; - - private OperationUpdaterWithBinding(BoundDoubleHistogram boundDoubleHistogram) { - this.boundDoubleHistogram = boundDoubleHistogram; - } - - @Override - void update() { - boundDoubleHistogram.record(11.0); - } - - @Override - void cleanup() { - boundDoubleHistogram.unbind(); - } - } - - private static class OperationUpdaterDirectCall extends OperationUpdater { - private final DoubleHistogram doubleHistogram; - private final String key; - private final String value; + void collectMetrics_ExemplarsWithExplicitBucketHistogram() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerView( + InstrumentSelector.builder().setName("*").build(), + View.builder().setAttributeFilter(Collections.emptySet()).build()) + .registerMetricReader(reader) + .build(); + Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + DoubleHistogram histogram = sdkMeter.histogramBuilder("testHistogram").build(); - private OperationUpdaterDirectCall(DoubleHistogram doubleHistogram, String key, String value) { - this.doubleHistogram = doubleHistogram; - this.key = key; - this.value = value; - } + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); + Tracer tracer = tracerProvider.get("foo"); - @Override - void update() { - doubleHistogram.record(9.0, Attributes.builder().put(key, value).build()); + Span span = tracer.spanBuilder("span").startSpan(); + try (Scope unused = span.makeCurrent()) { + histogram.record(10, Attributes.builder().put("key", "value").build()); } - @Override - void cleanup() {} + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(explicitHistogram -> + explicitHistogram.hasPointsSatisfying(point -> + point + .hasSum(10) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java index a71d9da26e3..45d559adc0f 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkDoubleUpDownCounterTest.java @@ -14,8 +14,6 @@ import io.opentelemetry.api.metrics.DoubleUpDownCounter; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.StressTestRunner.OperationUpdater; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundDoubleUpDownCounter; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; @@ -41,40 +39,16 @@ class SdkDoubleUpDownCounterTest { @Test void add_PreventNullAttributes() { - assertThatThrownBy( - () -> - sdkMeter - .upDownCounterBuilder("testUpDownCounter") - .ofDoubles() - .build() - .add(1.0, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("attributes"); - } - - @Test - void bound_PreventNullAttributes() { - assertThatThrownBy( - () -> - ((SdkDoubleUpDownCounter) - sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build()) - .bind(null)) + assertThatThrownBy(() -> + sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build().add(1.0, null)) .isInstanceOf(NullPointerException.class) .hasMessage("attributes"); } @Test void collectMetrics_NoRecords() { - DoubleUpDownCounter doubleUpDownCounter = - sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build(); - BoundDoubleUpDownCounter bound = - ((SdkDoubleUpDownCounter) doubleUpDownCounter) - .bind(Attributes.builder().put("foo", "bar").build()); - try { - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } finally { - bound.unbind(); - } + sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build(); + assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); } @Test @@ -89,26 +63,24 @@ void collectMetrics_WithEmptyAttributes() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); doubleUpDownCounter.add(12d, Attributes.empty()); doubleUpDownCounter.add(12d); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDescription("description") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDescription("description") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test @@ -116,222 +88,75 @@ void collectMetrics_WithMultipleCollects() { long startTime = testClock.now(); DoubleUpDownCounter doubleUpDownCounter = sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build(); - BoundDoubleUpDownCounter bound = - ((SdkDoubleUpDownCounter) doubleUpDownCounter) - .bind(Attributes.builder().put("K", "V").build()); - try { - // Do some records using bounds and direct calls and bindings. - doubleUpDownCounter.add(12.1d, Attributes.empty()); - bound.add(123.3d); - doubleUpDownCounter.add(21.4d, Attributes.empty()); - // Advancing time here should not matter. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(321.5d); - doubleUpDownCounter.add(111.1d, Attributes.builder().put("K", "V").build()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(555.9) - .hasAttributes(attributeEntry("K", "V"))))); - - // Repeat to prove we keep previous values. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(222d); - doubleUpDownCounter.add(11d, Attributes.empty()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44.5), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(777.9)))); - } finally { - bound.unbind(); - } - } - - @Test - void stressTest() { - DoubleUpDownCounter doubleUpDownCounter = - sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkDoubleUpDownCounter) doubleUpDownCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, 2, new OperationUpdaterDirectCall(doubleUpDownCounter, "K", "V"))); - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new OperationUpdaterWithBinding( - ((SdkDoubleUpDownCounter) doubleUpDownCounter) - .bind(Attributes.builder().put("K", "V").build())))); - } - - stressTestBuilder.build().run(); + doubleUpDownCounter.add(12.1d, Attributes.empty()); + doubleUpDownCounter.add(123.3d, Attributes.builder().put("K", "V").build()); + doubleUpDownCounter.add(21.4d, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleUpDownCounter.add(321.5d, Attributes.builder().put("K", "V").build()); + doubleUpDownCounter.add(111.1d, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(80_000) - .hasAttributes(attributeEntry("K", "V"))))); - } - - @Test - void stressTest_WithDifferentLabelSet() { - String[] keys = {"Key_1", "Key_2", "Key_3", "Key_4"}; - String[] values = {"Value_1", "Value_2", "Value_3", "Value_4"}; - DoubleUpDownCounter doubleUpDownCounter = - sdkMeter.upDownCounterBuilder("testUpDownCounter").ofDoubles().build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkDoubleUpDownCounter) doubleUpDownCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, 1, new OperationUpdaterDirectCall(doubleUpDownCounter, keys[i], values[i]))); - - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new OperationUpdaterWithBinding( - ((SdkDoubleUpDownCounter) doubleUpDownCounter) - .bind(Attributes.builder().put(keys[i], values[i]).build())))); - } - - stressTestBuilder.build().run(); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(555.9) + .hasAttributes(attributeEntry("K", "V"))))); + + // Repeat to prove we keep previous values. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + doubleUpDownCounter.add(222d, Attributes.builder().put("K", "V").build()); + doubleUpDownCounter.add(11d, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[0], values[0])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[1], values[1])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[2], values[2])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(40_000) - .hasAttributes(attributeEntry(keys[3], values[3]))))); - } - - private static class OperationUpdaterWithBinding extends OperationUpdater { - private final BoundDoubleUpDownCounter boundDoubleUpDownCounter; - - private OperationUpdaterWithBinding(BoundDoubleUpDownCounter boundDoubleUpDownCounter) { - this.boundDoubleUpDownCounter = boundDoubleUpDownCounter; - } - - @Override - void update() { - boundDoubleUpDownCounter.add(9.0); - } - - @Override - void cleanup() { - boundDoubleUpDownCounter.unbind(); - } + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44.5), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(777.9)))); } - private static class OperationUpdaterDirectCall extends OperationUpdater { - - private final DoubleUpDownCounter doubleUpDownCounter; - private final String key; - private final String value; - - private OperationUpdaterDirectCall( - DoubleUpDownCounter doubleUpDownCounter, String key, String value) { - this.doubleUpDownCounter = doubleUpDownCounter; - this.key = key; - this.value = value; - } - - @Override - void update() { - doubleUpDownCounter.add(11.0, Attributes.builder().put(key, value).build()); - } - - @Override - void cleanup() {} + @Test + void testToString() { + String expected = + "SdkDoubleUpDownCounter{descriptor=InstrumentDescriptor{name=testUpDownCounter, description=description, unit=ms, type=UP_DOWN_COUNTER, valueType=DOUBLE, advice=Advice{explicitBucketBoundaries=null, attributes=null}}}"; + DoubleUpDownCounter counter = + sdkMeter + .upDownCounterBuilder("testUpDownCounter") + .ofDoubles() + .setDescription("description") + .setUnit("ms") + .build(); + assertThat(counter).hasToString(expected); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java index f372ca4ee82..02f3f43b4ce 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongCounterTest.java @@ -16,8 +16,6 @@ import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.StressTestRunner.OperationUpdater; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundLongCounter; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; @@ -51,24 +49,10 @@ void add_PreventNullAttributes() { .hasMessage("attributes"); } - @Test - void bound_PreventNullAttributes() { - assertThatThrownBy( - () -> ((SdkLongCounter) sdkMeter.counterBuilder("testCounter").build()).bind(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("attributes"); - } - @Test void collectMetrics_NoRecords() { - LongCounter longCounter = sdkMeter.counterBuilder("Counter").build(); - BoundLongCounter bound = - ((SdkLongCounter) longCounter).bind(Attributes.builder().put("foo", "bar").build()); - try { - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } finally { - bound.unbind(); - } + sdkMeter.counterBuilder("Counter").build(); + assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); } @Test @@ -78,102 +62,89 @@ void collectMetrics_WithEmptyAttributes() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); longCounter.add(12, Attributes.empty()); longCounter.add(12); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasDescription("description") - .hasUnit("By") - .hasLongSumSatisfying( - longSum -> - longSum - .isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasDescription("description") + .hasUnit("By") + .hasLongSumSatisfying(longSum -> + longSum + .isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test void collectMetrics_WithMultipleCollects() { long startTime = testClock.now(); LongCounter longCounter = sdkMeter.counterBuilder("testCounter").build(); - BoundLongCounter bound = - ((SdkLongCounter) longCounter).bind(Attributes.builder().put("K", "V").build()); - try { - // Do some records using bounds and direct calls and bindings. - longCounter.add(12, Attributes.empty()); - bound.add(123); - longCounter.add(21, Attributes.empty()); - // Advancing time here should not matter. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(321); - longCounter.add(111, Attributes.builder().put("K", "V").build()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasLongSumSatisfying( - longSum -> - longSum - .isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(555)))); - - // Repeat to prove we keep previous values. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(222); - longCounter.add(11, Attributes.empty()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasLongSumSatisfying( - longSum -> - longSum - .isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(777)))); - } finally { - bound.unbind(); - } + longCounter.add(12, Attributes.empty()); + longCounter.add(123, Attributes.builder().put("K", "V").build()); + longCounter.add(21, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longCounter.add(321, Attributes.builder().put("K", "V").build()); + longCounter.add(111, Attributes.builder().put("K", "V").build()); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasLongSumSatisfying(longSum -> + longSum + .isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(555)))); + + // Repeat to prove we keep previous values. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longCounter.add(222, Attributes.builder().put("K", "V").build()); + longCounter.add(11, Attributes.empty()); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testCounter") + .hasLongSumSatisfying(longSum -> + longSum + .isMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(777)))); } @Test @@ -185,167 +156,4 @@ void longCounterAdd_Monotonicity() { logs.assertContains( "Counters can only increase. Instrument testCounter has recorded a negative value."); } - - @Test - @SuppressLogger(SdkLongCounter.class) - void boundLongCounterAdd_Monotonicity() { - LongCounter longCounter = sdkMeter.counterBuilder("testCounter").build(); - BoundLongCounter bound = ((SdkLongCounter) longCounter).bind(Attributes.empty()); - try { - bound.add(-9); - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); - logs.assertContains( - "Counters can only increase. Instrument testCounter has recorded a negative value."); - } finally { - bound.unbind(); - } - } - - @Test - void stressTest() { - LongCounter longCounter = sdkMeter.counterBuilder("testCounter").build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkLongCounter) longCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, 1, new OperationUpdaterDirectCall(longCounter, "K", "V"))); - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new OperationUpdaterWithBinding( - ((SdkLongCounter) longCounter) - .bind(Attributes.builder().put("K", "V").build())))); - } - - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasLongSumSatisfying( - longSum -> - longSum - .isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(160_000) - .hasAttributes(attributeEntry("K", "V"))))); - } - - @Test - void stressTest_WithDifferentLabelSet() { - String[] keys = {"Key_1", "Key_2", "Key_3", "Key_4"}; - String[] values = {"Value_1", "Value_2", "Value_3", "Value_4"}; - LongCounter longCounter = sdkMeter.counterBuilder("testCounter").build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkLongCounter) longCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, 2, new OperationUpdaterDirectCall(longCounter, keys[i], values[i]))); - - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new OperationUpdaterWithBinding( - ((SdkLongCounter) longCounter) - .bind(Attributes.builder().put(keys[i], values[i]).build())))); - } - - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testCounter") - .hasLongSumSatisfying( - longSum -> - longSum - .isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[0], values[0])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[1], values[1])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[2], values[2])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[3], values[3]))))); - } - - private static class OperationUpdaterWithBinding extends OperationUpdater { - private final BoundLongCounter boundLongCounter; - - private OperationUpdaterWithBinding(BoundLongCounter boundLongCounter) { - this.boundLongCounter = boundLongCounter; - } - - @Override - void update() { - boundLongCounter.add(9); - } - - @Override - void cleanup() { - boundLongCounter.unbind(); - } - } - - private static class OperationUpdaterDirectCall extends OperationUpdater { - - private final LongCounter longCounter; - private final String key; - private final String value; - - private OperationUpdaterDirectCall(LongCounter longCounter, String key, String value) { - this.longCounter = longCounter; - this.key = key; - this.value = value; - } - - @Override - void update() { - longCounter.add(11, Attributes.builder().put(key, value).build()); - } - - @Override - void cleanup() {} - } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeBuilderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeBuilderTest.java deleted file mode 100644 index c3c5d3d05b3..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeBuilderTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import static io.opentelemetry.api.common.AttributeKey.stringKey; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.Meter; -import io.opentelemetry.api.metrics.ObservableLongGauge; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; -import io.opentelemetry.sdk.testing.time.TestClock; -import java.time.Duration; -import org.junit.jupiter.api.Test; - -/** Unit tests for SDK {@link ObservableLongGauge}. */ -class SdkLongGaugeBuilderTest { - private static final Resource RESOURCE = - Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); - private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create(SdkLongGaugeBuilderTest.class.getName()); - private final TestClock testClock = TestClock.create(); - private final InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); - private final SdkMeterProvider sdkMeterProvider = - SdkMeterProvider.builder() - .setClock(testClock) - .setResource(RESOURCE) - .registerMetricReader(sdkMeterReader) - .build(); - private final Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); - - @Test - void removeCallback() { - ObservableLongGauge gauge = - sdkMeter - .gaugeBuilder("testGauge") - .ofLongs() - .buildWithCallback(measurement -> measurement.record(10)); - - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testGauge") - .hasLongGaugeSatisfying( - longGauge -> longGauge.hasPointsSatisfying(point -> {}))); - - gauge.close(); - - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); - } - - @Test - void collectMetrics_NoRecords() { - sdkMeter - .gaugeBuilder("testObserver") - .ofLongs() - .setDescription("My own LongValueObserver") - .setUnit("ms") - .buildWithCallback(result -> {}); - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } - - @Test - void collectMetrics_WithOneRecord() { - sdkMeter - .gaugeBuilder("testObserver") - .ofLongs() - .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); - testClock.advance(Duration.ofSeconds(1)); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000L) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("k", "v")) - .hasValue(12)))); - testClock.advance(Duration.ofSeconds(1)); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2000000000L) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("k", "v")) - .hasValue(12)))); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java new file mode 100644 index 00000000000..ee1054400e1 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongGaugeTest.java @@ -0,0 +1,308 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongGauge; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.ObservableLongGauge; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import java.time.Duration; +import java.util.Collections; +import org.assertj.core.api.Assertions; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link SdkLongGauge}. */ +class SdkLongGaugeTest { + private static final long SECOND_NANOS = 1_000_000_000; + private static final Resource RESOURCE = + Resource.create(Attributes.of(stringKey("resource_key"), "resource_value")); + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.create(SdkLongGaugeTest.class.getName()); + private final TestClock testClock = TestClock.create(); + private final InMemoryMetricReader cumulativeReader = InMemoryMetricReader.create(); + private final InMemoryMetricReader deltaReader = InMemoryMetricReader.createDelta(); + private final SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .registerMetricReader(cumulativeReader) + .registerMetricReader(deltaReader) + .setResource(RESOURCE) + .build(); + private final Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + + @Test + void set_PreventNullAttributes() { + assertThatThrownBy(() -> sdkMeter.gaugeBuilder("testGauge").ofLongs().build().set(1, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("attributes"); + } + + @Test + void observable_RemoveCallback() { + ObservableLongGauge gauge = + sdkMeter + .gaugeBuilder("testGauge") + .ofLongs() + .buildWithCallback(measurement -> measurement.record(10)); + + Assertions.assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasLongGaugeSatisfying(longGauge -> longGauge.hasPointsSatisfying(point -> {}))); + + gauge.close(); + + Assertions.assertThat(cumulativeReader.collectAllMetrics()).hasSize(0); + } + + @Test + void collectMetrics_NoRecords() { + sdkMeter.gaugeBuilder("testGauge").ofLongs().build(); + assertThat(cumulativeReader.collectAllMetrics()).isEmpty(); + } + + @Test + void collectMetrics_WithEmptyAttributes() { + LongGauge longGauge = + sdkMeter + .gaugeBuilder("testGauge") + .ofLongs() + .setDescription("description") + .setUnit("K") + .build(); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longGauge.set(12, Attributes.empty()); + longGauge.set(13); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(13)))); + } + + @Test + void collectMetrics_WithExemplars() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerView( + InstrumentSelector.builder().setName("*").build(), + View.builder().setAttributeFilter(Collections.emptySet()).build()) + .registerMetricReader(reader) + .build(); + Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + LongGauge longGauge = + sdkMeter + .gaugeBuilder("testGauge") + .setDescription("description") + .setUnit("K") + .ofLongs() + .build(); + + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); + Tracer tracer = tracerProvider.get("foo"); + + Span span = tracer.spanBuilder("span").startSpan(); + try (Scope unused = span.makeCurrent()) { + longGauge.set(12L, Attributes.builder().put("key", "value").build()); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("description") + .hasUnit("K") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12L) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(12L) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); + } + + @Test + void observable_CollectMetrics_DefaultExemplarFilter_NoExemplars() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerMetricReader(reader) + .build(); + + sdkMeterProvider + .get(getClass().getName()) + .gaugeBuilder("testGauge") + .ofLongs() + .buildWithCallback(measurement -> measurement.record(12, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); + } + + @Test + void observable_CollectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(reader) + .build(); + + sdkMeterProvider + .get(getClass().getName()) + .gaugeBuilder("testGauge") + .ofLongs() + .buildWithCallback(measurement -> measurement.record(12, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testGauge") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasValue(12) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12))))); + } + + @Test + void collectMetrics_WithMultipleCollects() { + long startTime = testClock.now(); + LongGauge longGauge = sdkMeter.gaugeBuilder("testGauge").ofLongs().build(); + longGauge.set(12, Attributes.empty()); + longGauge.set(12, Attributes.builder().put("K", "V").build()); + longGauge.set(21, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longGauge.set(321, Attributes.builder().put("K", "V").build()); + longGauge.set(111, Attributes.builder().put("K", "V").build()); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111) + .hasAttributes(attributeEntry("K", "V"))))); + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testGauge") + .hasDescription("") + .hasUnit("") + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(111) + .hasAttributes(attributeEntry("K", "V"))))); + + // Repeat to prove we keep previous values. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longGauge.set(222, Attributes.builder().put("K", "V").build()); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(21), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(222) + .hasAttributes(attributeEntry("K", "V"))))); + // Delta reader should only have point for {K=V} series, since the {} did not have any + // measurements + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(startTime + SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(222) + .hasAttributes(attributeEntry("K", "V"))))); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java index e3ed5ed74b3..36e8e16f832 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongHistogramTest.java @@ -8,22 +8,26 @@ import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.LongHistogram; import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Scope; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.StressTestRunner.OperationUpdater; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundLongHistogram; -import io.opentelemetry.sdk.metrics.internal.view.ExponentialHistogramAggregation; import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; import java.time.Duration; +import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -36,12 +40,12 @@ class SdkLongHistogramTest { private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = InstrumentationScopeInfo.create(SdkLongHistogramTest.class.getName()); private final TestClock testClock = TestClock.create(); - private final InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + private final InMemoryMetricReader reader = InMemoryMetricReader.create(); private final SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder() .setClock(testClock) .setResource(RESOURCE) - .registerMetricReader(sdkMeterReader) + .registerMetricReader(reader) .build(); private final Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); @@ -55,26 +59,10 @@ void record_PreventNullAttributes() { .hasMessage("attributes"); } - @Test - void bound_PreventNullAttributes() { - assertThatThrownBy( - () -> - ((SdkLongHistogram) sdkMeter.histogramBuilder("testHistogram").ofLongs().build()) - .bind(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("attributes"); - } - @Test void collectMetrics_NoRecords() { - LongHistogram longHistogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); - BoundLongHistogram bound = - ((SdkLongHistogram) longHistogram).bind(Attributes.builder().put("key", "value").build()); - try { - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } finally { - bound.unbind(); - } + sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); + assertThat(reader.collectAllMetrics()).isEmpty(); } @Test @@ -89,113 +77,244 @@ void collectMetrics_WithEmptyAttributes() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); longHistogram.record(12, Attributes.empty()); longHistogram.record(12); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("By") - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(24) - .hasBucketBoundaries( - 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, - 5_000, 7_500, 10_000) - .hasBucketCounts( - 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("By") + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(24) + .hasBucketBoundaries( + 0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1_000, 2_500, 5_000, + 7_500, 10_000) + .hasBucketCounts(0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)))); } @Test void collectMetrics_WithMultipleCollects() { long startTime = testClock.now(); LongHistogram longHistogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); - BoundLongHistogram bound = - ((SdkLongHistogram) longHistogram).bind(Attributes.builder().put("K", "V").build()); - try { - // Do some records using bounds and direct calls and bindings. - longHistogram.record(9, Attributes.empty()); - bound.record(123); - longHistogram.record(14, Attributes.empty()); - // Advancing time here should not matter. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.record(321); - longHistogram.record(1, Attributes.builder().put("K", "V").build()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(445) - .hasBucketCounts( - 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(2) - .hasSum(23) - .hasBucketCounts( - 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); + longHistogram.record(9, Attributes.empty()); + longHistogram.record(123, Attributes.builder().put("K", "V").build()); + longHistogram.record(14, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longHistogram.record(321, Attributes.builder().put("K", "V").build()); + longHistogram.record(1, Attributes.builder().put("K", "V").build()); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(445) + .hasBucketCounts(0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(2) + .hasSum(23) + .hasBucketCounts(0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); + + // Histograms are cumulative by default. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longHistogram.record(222, Attributes.builder().put("K", "V").build()); + longHistogram.record(17, Attributes.empty()); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(4) + .hasSum(667) + .hasBucketCounts(0, 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(attributeEntry("K", "V")), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasCount(3) + .hasSum(40) + .hasBucketCounts(0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + .hasAttributes(Attributes.empty())))); + } - // Histograms are cumulative by default. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.record(222); - longHistogram.record(17, Attributes.empty()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(4) - .hasSum(667) - .hasBucketCounts( - 1, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry("K", "V")), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasCount(3) - .hasSum(40) - .hasBucketCounts( - 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(Attributes.empty())))); - } finally { - bound.unbind(); - } + /** + * Verify that the exponential histogram scale behaves properly after collection with delta and + * cumulative readers. + */ + @Test + void collectMetrics_ExponentialHistogramScaleResets() { + InMemoryMetricReader deltaReader = InMemoryMetricReader.createDelta(); + InMemoryMetricReader cumulativeReader = InMemoryMetricReader.create(); + + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .registerMetricReader(cumulativeReader) + .registerMetricReader(deltaReader) + .registerView( + InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), + View.builder() + .setAggregation( + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(5) + .setMaxScale(20) + .build())) + .build()) + .build(); + + Meter meter = sdkMeterProvider.get(getClass().getName()); + + LongHistogram histogram = meter.histogramBuilder("histogram").ofLongs().build(); + Attributes attributes1 = Attributes.builder().put("key", "value1").build(); + Attributes attributes2 = Attributes.builder().put("key", "value2").build(); + + // Record 2 measurement to attributes1 such that scale changes, 1 measurement to attributes2 + // such that scale doesn't change. + histogram.record(1, attributes1); + histogram.record(10, attributes1); + histogram.record(1, attributes2); + + // Both deltaReader and cumulativeReader should read out the same values, with the attributes1 + // point having a scale that accommodates the range of measurements. + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isDelta() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(20) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Collections.singletonList(1L)))))); + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(20) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Collections.singletonList(1L)))))); + + // Record 1 measurement to attributes1 such that scale doesn't change, 2 measurement to + // attributes2 such that scale changes. + histogram.record(1, attributes1); + histogram.record(1, attributes2); + histogram.record(10, attributes2); + + // The deltaReader should have points reflecting a reset to the maxScale. The attributes1 point + // now has scale 20, the attributes2 point now has scale 0 to accommodate the range of + // measurements. + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isDelta() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(20) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Collections.singletonList(1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L)))))); + // The cumulativeReader does not reset after collection, so both attributes1 and attributes2 + // points should now have scale 0. + assertThat(cumulativeReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("histogram") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasAttributes(attributes1) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(2L, 0L, 0L, 0L, 1L))), + point -> + point + .hasAttributes(attributes2) + .hasScale(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(-1) + .hasCounts(Arrays.asList(2L, 0L, 0L, 0L, 1L)))))); } @Test @@ -204,11 +323,16 @@ void collectMetrics_ExponentialHistogramAggregation() { SdkMeterProvider.builder() .setResource(RESOURCE) .setClock(testClock) - .registerMetricReader(sdkMeterReader) + .registerMetricReader(reader) .registerView( InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), View.builder() - .setAggregation(ExponentialHistogramAggregation.create(-1, 5)) + .setAggregation( + Aggregation.base2ExponentialBucketHistogram( + Base2ExponentialHistogramOptions.builder() + .setMaxBuckets(5) + .setMaxScale(20) + .build())) .build()) .build(); LongHistogram longHistogram = @@ -221,57 +345,56 @@ void collectMetrics_ExponentialHistogramAggregation() { .build(); testClock.advance(Duration.ofNanos(SECOND_NANOS)); longHistogram.record(12L, Attributes.builder().put("key", "value").build()); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); longHistogram.record(12L); longHistogram.record(13L); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - MetricAssertions.assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasDescription("description") - .hasUnit("ms") - .hasExponentialHistogram() - .isCumulative() - .points() - .satisfiesExactlyInAnyOrder( - point -> { - MetricAssertions.assertThat(point) - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(2) - .hasSum(25) - .hasMin(12) - .hasMax(13) - .hasScale(-1) - .hasZeroCount(0); - MetricAssertions.assertThat(point.getPositiveBuckets()) - .hasOffset(1) - .hasCounts(Collections.singletonList(2L)); - MetricAssertions.assertThat(point.getNegativeBuckets()) - .hasOffset(0) - .hasCounts(Collections.emptyList()); - }, - point -> { - MetricAssertions.assertThat(point) - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.builder().put("key", "value").build()) - .hasCount(1) - .hasSum(12) - .hasMin(12) - .hasMax(12) - .hasScale(-1) - .hasZeroCount(0); - MetricAssertions.assertThat(point.getPositiveBuckets()) - .hasOffset(1) - .hasCounts(Collections.singletonList(1L)); - MetricAssertions.assertThat(point.getNegativeBuckets()) - .hasOffset(0) - .hasCounts(Collections.emptyList()); - })); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testHistogram") + .hasDescription("description") + .hasUnit("ms") + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(2) + .hasSum(25) + .hasMin(12) + .hasMax(13) + .hasScale(5) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(114) + .hasCounts(Arrays.asList(1L, 0L, 0L, 0L, 1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList())), + point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.builder().put("key", "value").build()) + .hasCount(1) + .hasSum(12) + .hasMin(12) + .hasMax(12) + .hasScale(20) + .hasZeroCount(0) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasOffset(3759105) + .hasCounts(Collections.singletonList(1L))) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasOffset(0).hasCounts(Collections.emptyList()))))); } @Test @@ -279,183 +402,93 @@ void collectMetrics_ExponentialHistogramAggregation() { void longHistogramRecord_NonNegativeCheck() { LongHistogram histogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); histogram.record(-45); - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); + assertThat(reader.collectAllMetrics()).hasSize(0); logs.assertContains( "Histograms can only record non-negative values. Instrument testHistogram has recorded a negative value."); } @Test - @SuppressLogger(SdkLongHistogram.class) - void boundLongHistogramRecord_MonotonicityCheck() { + void collectMetrics_ExemplarsWithExponentialHistogram() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerView( + InstrumentSelector.builder().setType(InstrumentType.HISTOGRAM).build(), + View.builder() + .setAggregation(Aggregation.base2ExponentialBucketHistogram()) + .setAttributeFilter(Collections.emptySet()) + .build()) + .registerMetricReader(reader) + .build(); + Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); LongHistogram histogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); - BoundLongHistogram bound = ((SdkLongHistogram) histogram).bind(Attributes.empty()); - try { - bound.record(-9); - assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); - logs.assertContains( - "Histograms can only record non-negative values. Instrument testHistogram has recorded a negative value."); - } finally { - bound.unbind(); - } - } - @Test - void stressTest() { - LongHistogram longHistogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkLongHistogram) longHistogram) - .setCollectionIntervalMs(100); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); + Tracer tracer = tracerProvider.get("foo"); - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new SdkLongHistogramTest.OperationUpdaterDirectCall(longHistogram, "K", "V"))); - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new SdkLongHistogramTest.OperationUpdaterWithBinding( - ((SdkLongHistogram) longHistogram) - .bind(Attributes.builder().put("K", "V").build())))); + Span span = tracer.spanBuilder("span").startSpan(); + try (Scope unused = span.makeCurrent()) { + histogram.record(10, Attributes.builder().put("key", "value").build()); } - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasCount(16_000) - .hasSum(160_000)))); + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasExponentialHistogramSatisfying(exponentialHistogram -> + exponentialHistogram.hasPointsSatisfying(point -> + point + .hasSum(10.0) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } @Test - void stressTest_WithDifferentLabelSet() { - String[] keys = {"Key_1", "Key_2", "Key_3", "Key_4"}; - String[] values = {"Value_1", "Value_2", "Value_3", "Value_4"}; - LongHistogram longHistogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkLongHistogram) longHistogram) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new SdkLongHistogramTest.OperationUpdaterDirectCall( - longHistogram, keys[i], values[i]))); - - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new SdkLongHistogramTest.OperationUpdaterWithBinding( - ((SdkLongHistogram) longHistogram) - .bind(Attributes.builder().put(keys[i], values[i]).build())))); - } - - stressTestBuilder.build().run(); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(2_000) - .hasSum(20_000) - .hasBucketCounts( - 0, 1000, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[0], values[0])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(2_000) - .hasSum(20_000) - .hasBucketCounts( - 0, 1000, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[1], values[1])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(2_000) - .hasSum(20_000) - .hasBucketCounts( - 0, 1000, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[2], values[2])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasCount(2_000) - .hasSum(20_000) - .hasBucketCounts( - 0, 1000, 1000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) - .hasAttributes(attributeEntry(keys[3], values[3]))))); - } - - private static class OperationUpdaterWithBinding extends OperationUpdater { - private final BoundLongHistogram boundLongHistogram; - - private OperationUpdaterWithBinding(BoundLongHistogram boundLongHistogram) { - this.boundLongHistogram = boundLongHistogram; - } - - @Override - void update() { - boundLongHistogram.record(9); - } - - @Override - void cleanup() { - boundLongHistogram.unbind(); - } - } - - private static class OperationUpdaterDirectCall extends OperationUpdater { - - private final LongHistogram longHistogram; - private final String key; - private final String value; + void collectMetrics_ExemplarsWithExplicitBucketHistogram() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .setClock(testClock) + .setResource(RESOURCE) + .registerView( + InstrumentSelector.builder().setName("*").build(), + View.builder().setAttributeFilter(Collections.emptySet()).build()) + .registerMetricReader(reader) + .build(); + Meter sdkMeter = sdkMeterProvider.get(getClass().getName()); + LongHistogram histogram = sdkMeter.histogramBuilder("testHistogram").ofLongs().build(); - private OperationUpdaterDirectCall(LongHistogram longHistogram, String key, String value) { - this.longHistogram = longHistogram; - this.key = key; - this.value = value; - } + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(SpanExporter.noop())) + .build(); + Tracer tracer = tracerProvider.get("foo"); - @Override - void update() { - longHistogram.record(11, Attributes.builder().put(key, value).build()); + Span span = tracer.spanBuilder("span").startSpan(); + try (Scope unused = span.makeCurrent()) { + histogram.record(10, Attributes.builder().put("key", "value").build()); } - @Override - void cleanup() {} + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasHistogramSatisfying(explicitHistogram -> + explicitHistogram.hasPointsSatisfying(point -> + point + .hasSum(10) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(10.0) + .hasFilteredAttributes( + Attributes.builder().put("key", "value").build()))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java index b97212d38d9..64b486934a4 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkLongUpDownCounterTest.java @@ -14,8 +14,6 @@ import io.opentelemetry.api.metrics.LongUpDownCounter; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.StressTestRunner.OperationUpdater; -import io.opentelemetry.sdk.metrics.internal.instrument.BoundLongUpDownCounter; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; @@ -46,28 +44,10 @@ void add_PreventNullAttributes() { .hasMessage("attributes"); } - @Test - void bound_PreventNullAttributes() { - assertThatThrownBy( - () -> - ((SdkLongUpDownCounter) sdkMeter.upDownCounterBuilder("testUpDownCounter").build()) - .bind(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("attributes"); - } - @Test void collectMetrics_NoRecords() { - LongUpDownCounter longUpDownCounter = - sdkMeter.upDownCounterBuilder("testUpDownCounter").build(); - BoundLongUpDownCounter bound = - ((SdkLongUpDownCounter) longUpDownCounter) - .bind(Attributes.builder().put("foo", "bar").build()); - try { - assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); - } finally { - bound.unbind(); - } + sdkMeter.upDownCounterBuilder("testUpDownCounter").build(); + assertThat(sdkMeterReader.collectAllMetrics()).isEmpty(); } @Test @@ -81,26 +61,24 @@ void collectMetrics_WithEmptyAttributes() { testClock.advance(Duration.ofNanos(SECOND_NANOS)); longUpDownCounter.add(12, Attributes.empty()); longUpDownCounter.add(12); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasDescription("description") - .hasUnit("By") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(24)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasDescription("description") + .hasUnit("By") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(24)))); } @Test @@ -108,221 +86,61 @@ void collectMetrics_WithMultipleCollects() { long startTime = testClock.now(); LongUpDownCounter longUpDownCounter = sdkMeter.upDownCounterBuilder("testUpDownCounter").build(); - BoundLongUpDownCounter bound = - ((SdkLongUpDownCounter) longUpDownCounter).bind(Attributes.builder().put("K", "V").build()); - try { - // Do some records using bounds and direct calls and bindings. - longUpDownCounter.add(12, Attributes.empty()); - bound.add(123); - longUpDownCounter.add(21, Attributes.empty()); - // Advancing time here should not matter. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(321); - longUpDownCounter.add(111, Attributes.builder().put("K", "V").build()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(33), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(555)))); - - // Repeat to prove we keep previous values. - testClock.advance(Duration.ofNanos(SECOND_NANOS)); - bound.add(222); - longUpDownCounter.add(11, Attributes.empty()); - assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(44), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasAttributes(attributeEntry("K", "V")) - .hasValue(777)))); - } finally { - bound.unbind(); - } - } - - @Test - void stressTest() { - LongUpDownCounter longUpDownCounter = - sdkMeter.upDownCounterBuilder("testUpDownCounter").build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkLongUpDownCounter) longUpDownCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, 1, new OperationUpdaterDirectCall(longUpDownCounter, "K", "V"))); - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 2_000, - 1, - new OperationUpdaterWithBinding( - ((SdkLongUpDownCounter) longUpDownCounter) - .bind(Attributes.builder().put("K", "V").build())))); - } - - stressTestBuilder.build().run(); + longUpDownCounter.add(12, Attributes.empty()); + longUpDownCounter.add(123, Attributes.builder().put("K", "V").build()); + longUpDownCounter.add(21, Attributes.empty()); + // Advancing time here should not matter. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longUpDownCounter.add(321, Attributes.builder().put("K", "V").build()); + longUpDownCounter.add(111, Attributes.builder().put("K", "V").build()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(160_000) - .hasAttributes(attributeEntry("K", "V"))))); - } - - @Test - void stressTest_WithDifferentLabelSet() { - String[] keys = {"Key_1", "Key_2", "Key_3", "Key_4"}; - String[] values = {"Value_1", "Value_2", "Value_3", "Value_4"}; - LongUpDownCounter longUpDownCounter = - sdkMeter.upDownCounterBuilder("testUpDownCounter").build(); - - StressTestRunner.Builder stressTestBuilder = - StressTestRunner.builder() - .setInstrument((SdkLongUpDownCounter) longUpDownCounter) - .setCollectionIntervalMs(100); - - for (int i = 0; i < 4; i++) { - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, 2, new OperationUpdaterDirectCall(longUpDownCounter, keys[i], values[i]))); - - stressTestBuilder.addOperation( - StressTestRunner.Operation.create( - 1_000, - 2, - new OperationUpdaterWithBinding( - ((SdkLongUpDownCounter) longUpDownCounter) - .bind(Attributes.builder().put(keys[i], values[i]).build())))); - } - - stressTestBuilder.build().run(); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(33), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(555)))); + + // Repeat to prove we keep previous values. + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + longUpDownCounter.add(222, Attributes.builder().put("K", "V").build()); + longUpDownCounter.add(11, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[0], values[0])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[1], values[1])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[2], values[2])), - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasValue(20_000) - .hasAttributes(attributeEntry(keys[3], values[3]))))); - } - - private static class OperationUpdaterWithBinding extends OperationUpdater { - private final BoundLongUpDownCounter boundLongUpDownCounter; - - private OperationUpdaterWithBinding(BoundLongUpDownCounter boundLongUpDownCounter) { - this.boundLongUpDownCounter = boundLongUpDownCounter; - } - - @Override - void update() { - boundLongUpDownCounter.add(9); - } - - @Override - void cleanup() { - boundLongUpDownCounter.unbind(); - } - } - - private static class OperationUpdaterDirectCall extends OperationUpdater { - - private final LongUpDownCounter longUpDownCounter; - private final String key; - private final String value; - - private OperationUpdaterDirectCall( - LongUpDownCounter longUpDownCounter, String key, String value) { - this.longUpDownCounter = longUpDownCounter; - this.key = key; - this.value = value; - } - - @Override - void update() { - longUpDownCounter.add(11, Attributes.builder().put(key, value).build()); - } - - @Override - void cleanup() {} + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testUpDownCounter") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(44), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasAttributes(attributeEntry("K", "V")) + .hasValue(777)))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilderTest.java index 74e5e5dcc12..1abc9a350a9 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilderTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderBuilderTest.java @@ -6,10 +6,19 @@ package io.opentelemetry.sdk.metrics; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; class SdkMeterProviderBuilderTest { @@ -23,4 +32,102 @@ void defaultResource() { .extracting("sharedState") .hasFieldOrPropertyWithValue("resource", Resource.getDefault()); } + + @Test + void addResource() { + Resource customResource = + Resource.create( + Attributes.of( + AttributeKey.stringKey("custom_attribute_key"), "custom_attribute_value")); + + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder() + .registerMetricReader(InMemoryMetricReader.create()) + .addResource(customResource) + .build(); + + assertThat(sdkMeterProvider) + .extracting("sharedState") + .hasFieldOrPropertyWithValue("resource", Resource.getDefault().merge(customResource)); + } + + @Test + void resourceProvider_defaultsToAutoWrappedStaticResource() { + SdkMeterProvider provider = + SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()).build(); + + assertThat(SdkMeterProviderUtil.getSdkResourceProvider(provider).getResource()) + .isEqualTo(Resource.getDefault()); + } + + @Test + void setSdkResourceProvider_usedForResource() { + Resource customResource = + Resource.create(Attributes.of(AttributeKey.stringKey("key"), "value")); + SdkResourceProvider resourceProvider = SdkResourceProvider.create(customResource); + + SdkMeterProviderBuilder builder = + SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()); + SdkMeterProviderUtil.setSdkResourceProvider(builder, resourceProvider); + SdkMeterProvider provider = builder.build(); + + assertThat(SdkMeterProviderUtil.getSdkResourceProvider(provider)).isSameAs(resourceProvider); + assertThat(provider) + .extracting("sharedState") + .hasFieldOrPropertyWithValue("resource", customResource); + } + + @ParameterizedTest + @MethodSource("resourceConfigurations") + void setSdkResourceProvider_afterResource_throws(boolean addResource, Resource resource) { + SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); + if (addResource) { + builder.addResource(resource); + } else { + builder.setResource(resource); + } + + assertThatThrownBy(() -> builder.setSdkResourceProvider(SdkResourceProvider.create(resource))) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Cannot call setSdkResourceProvider after setResource or addResource has been called."); + assertThat(SdkMeterProviderUtil.getSdkResourceProvider(builder.build()).getResource()) + .isEqualTo(addResource ? Resource.getDefault().merge(resource) : resource); + } + + @ParameterizedTest + @MethodSource("resourceConfigurations") + void resource_afterSetSdkResourceProvider_throws(boolean addResource, Resource resource) { + SdkResourceProvider resourceProvider = SdkResourceProvider.create(resource); + SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); + SdkMeterProviderUtil.setSdkResourceProvider(builder, resourceProvider); + + assertThatThrownBy( + () -> { + if (addResource) { + builder.addResource(resource); + } else { + builder.setResource(resource); + } + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Cannot call " + + (addResource ? "addResource" : "setResource") + + " after setSdkResourceProvider has been called."); + assertThat(SdkMeterProviderUtil.getSdkResourceProvider(builder.build())) + .isSameAs(resourceProvider); + } + + private static Stream resourceConfigurations() { + Resource customResource = + Resource.create(Attributes.of(AttributeKey.stringKey("key"), "value")); + return Stream.of( + Arguments.argumentSet("setResource(custom)", false, customResource), + Arguments.argumentSet("setResource(default)", false, Resource.getDefault()), + Arguments.argumentSet("setResource(empty)", false, Resource.empty()), + Arguments.argumentSet("addResource(custom)", true, customResource), + Arguments.argumentSet("addResource(default)", true, Resource.getDefault()), + Arguments.argumentSet("addResource(empty)", true, Resource.empty())); + } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java new file mode 100644 index 00000000000..f7f4efb32e7 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderMetricsTest.java @@ -0,0 +1,102 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; + +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.MetricProducer; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricExporter; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import org.junit.jupiter.api.Test; + +class SdkMeterProviderMetricsTest { + @Test + void simple() { + InMemoryMetricExporter metricExporter = InMemoryMetricExporter.create(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) + .build()) { + Meter meter = meterProvider.get("test"); + + LongCounter counter = meter.counterBuilder("counter").build(); + + counter.add(1); + + meterProvider.forceFlush().join(10, TimeUnit.SECONDS); + metricExporter.reset(); + // Export again to export the metric reader's metric. + meterProvider.forceFlush().join(10, TimeUnit.SECONDS); + + List metrics = metricExporter.getFinishedMetricItems(); + assertThat(metrics) + .satisfiesExactlyInAnyOrder( + m -> assertThat(m).hasName("counter"), + m -> { + assertThat(m) + .hasName("otel.sdk.metric_reader.collection.duration") + .hasHistogramSatisfying(h -> + h.hasPointsSatisfying(p -> + p.hasCount(1) + .hasAttributesSatisfying( + equalTo( + SemConvConstants.OTEL_COMPONENT_TYPE, + "periodic_metric_reader"), + equalTo( + SemConvConstants.OTEL_COMPONENT_NAME, + "periodic_metric_reader/0")))); + }); + } + } + + @Test + @SuppressLogger(PeriodicMetricReader.class) + void collectionFailureIsRecordedWithErrorType() { + InMemoryMetricExporter metricExporter = InMemoryMetricExporter.create(); + AtomicBoolean shouldFail = new AtomicBoolean(true); + // Fail the first collection, then succeed so the recorded self-observability sample can be + // exported on the following flush. + MetricProducer failingProducer = + resource -> { + if (shouldFail.getAndSet(false)) { + throw new IllegalStateException("boom"); + } + return Collections.emptyList(); + }; + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(PeriodicMetricReader.create(metricExporter)) + .registerMetricProducer(failingProducer) + .build()) { + + meterProvider.forceFlush().join(10, TimeUnit.SECONDS); + metricExporter.reset(); + // Export again to export the metric reader's self-observability metric. + meterProvider.forceFlush().join(10, TimeUnit.SECONDS); + + assertThat(metricExporter.getFinishedMetricItems()) + .anySatisfy(m -> + assertThat(m) + .hasName("otel.sdk.metric_reader.collection.duration") + .hasHistogramSatisfying(h -> + h.hasPointsSatisfying(p -> + p.hasAttributesSatisfying( + equalTo( + SemConvConstants.ERROR_TYPE, + "java.lang.IllegalStateException"))))); + } + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java index 406b65ef4ff..e71204f4bd0 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterProviderTest.java @@ -7,10 +7,10 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; import io.github.netmikey.logunit.api.LogCapturer; -import io.opentelemetry.api.baggage.Baggage; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.DoubleCounter; @@ -23,12 +23,12 @@ import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.api.metrics.ObservableLongCounter; import io.opentelemetry.api.metrics.ObservableLongMeasurement; -import io.opentelemetry.context.Context; -import io.opentelemetry.context.Scope; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import io.opentelemetry.sdk.resources.Resource; @@ -46,13 +46,17 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class SdkMeterProviderTest { private static final Resource RESOURCE = Resource.create(Attributes.of(AttributeKey.stringKey("resource_key"), "resource_value")); @@ -108,100 +112,85 @@ void collectAllSyncInstruments() { doubleValueRecorder.record(10.1, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("")) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("")) .satisfiesExactlyInAnyOrder( metric -> assertThat(metric) .hasName("testDoubleHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(1) - .hasSum(10.1) - .hasBucketCounts( - 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(1) + .hasSum(10.1) + .hasBucketCounts(0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), metric -> assertThat(metric) .hasName("testDoubleCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10.1))), + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10.1))), metric -> assertThat(metric) .hasName("testLongHistogram") - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasCount(1) - .hasSum(10) - .hasBucketCounts( - 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasCount(1) + .hasSum(10) + .hasBucketCounts(0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))), metric -> assertThat(metric) .hasName("testLongUpDownCounter") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10))), metric -> assertThat(metric) .hasName("testLongCounter") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10))), + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10))), metric -> assertThat(metric) .hasName("testDoubleUpDownCounter") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10.1)))); + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10.1)))); } @Test @@ -209,7 +198,11 @@ void collectAllSyncInstruments_OverwriteTemporality() { sdkMeterProviderBuilder.registerView( InstrumentSelector.builder().setType(InstrumentType.COUNTER).build(), View.builder() - .setAggregation(Aggregation.explicitBucketHistogram(Collections.emptyList())) + .setAggregation( + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.emptyList()) + .build())) .build()); InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.createDelta(); SdkMeterProvider sdkMeterProvider = @@ -221,50 +214,48 @@ void collectAllSyncInstruments_OverwriteTemporality() { testClock.advance(Duration.ofSeconds(1)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testLongCounter") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testLongCounter") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))); longCounter.add(10, Attributes.empty()); testClock.advance(Duration.ofSeconds(1)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))); } @Test void collectAllSyncInstruments_DeltaHistogram() { registerViewForAllTypes( - sdkMeterProviderBuilder, Aggregation.explicitBucketHistogram(Collections.emptyList())); + sdkMeterProviderBuilder, + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.emptyList()) + .build())); InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.createDelta(); SdkMeterProvider sdkMeterProvider = sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); @@ -281,24 +272,21 @@ void collectAllSyncInstruments_DeltaHistogram() { testClock.advance(Duration.ofSeconds(1)); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))) .extracting(MetricData::getName) .containsExactlyInAnyOrder( "testLongCounter", "testDoubleCounter", "testLongHistogram", "testDoubleHistogram"); @@ -311,24 +299,21 @@ void collectAllSyncInstruments_DeltaHistogram() { doubleHistogram.record(10, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("") - .hasHistogramSatisfying( - histogram -> - histogram - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 1000000000) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasBucketCounts(1)))) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("") + .hasHistogramSatisfying(histogram -> + histogram + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 1000000000) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasBucketCounts(1)))) .extracting(MetricData::getName) .containsExactlyInAnyOrder( "testLongCounter", "testDoubleCounter", "testLongHistogram", "testDoubleHistogram"); @@ -364,94 +349,81 @@ void collectAllAsyncInstruments() { .buildWithCallback(doubleResult -> doubleResult.record(10.1, Attributes.empty())); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasDescription("") - .hasUnit("")) + .allSatisfy(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasDescription("") + .hasUnit("")) .satisfiesExactlyInAnyOrder( metric -> assertThat(metric) .hasName("testLongSumObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10))), + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10))), metric -> assertThat(metric) .hasName("testDoubleSumObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10.1))), + .hasDoubleSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10.1))), metric -> assertThat(metric) .hasName("testLongUpDownSumObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10))), + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10))), metric -> assertThat(metric) .hasName("testDoubleUpDownSumObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(-10.1))), + .hasDoubleSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(-10.1))), metric -> assertThat(metric) .hasName("testLongValueObserver") - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10))), + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10))), metric -> assertThat(metric) .hasName("testDoubleValueObserver") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now()) - .hasAttributes(Attributes.empty()) - .hasValue(10.1)))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now()) + .hasAttributes(Attributes.empty()) + .hasValue(10.1)))); } @Test @@ -463,38 +435,32 @@ void removeAsyncInstrument() { ObservableLongCounter observableCounter1 = meter .counterBuilder("foo") - .buildWithCallback( - measurement -> - measurement.record(10, Attributes.builder().put("callback", "one").build())); + .buildWithCallback(measurement -> + measurement.record(10, Attributes.builder().put("callback", "one").build())); ObservableLongCounter observableCounter2 = meter .counterBuilder("foo") - .buildWithCallback( - measurement -> - measurement.record(10, Attributes.builder().put("callback", "two").build())); + .buildWithCallback(measurement -> + measurement.record(10, Attributes.builder().put("callback", "two").build())); assertThat(reader.collectAllMetrics()) .hasSize(1) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasAttributes(attributeEntry("callback", "one")), - point -> point.hasAttributes(attributeEntry("callback", "two"))))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasAttributes(attributeEntry("callback", "one")), + point -> point.hasAttributes(attributeEntry("callback", "two"))))); observableCounter1.close(); assertThat(reader.collectAllMetrics()) .hasSize(1) - .satisfiesExactly( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> point.hasAttributes(attributeEntry("callback", "two"))))); + .satisfiesExactly(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasAttributes(attributeEntry("callback", "two"))))); observableCounter2.close(); assertThat(reader.collectAllMetrics()).hasSize(0); @@ -538,12 +504,11 @@ void collectAllMetrics_NoConcurrentCalls() // If callback is in invoked concurrently, only one metric data will be reported assertThat(allMetricData) .hasSize(4) - .allSatisfy( - metricData -> - assertThat(metricData) - .hasInstrumentationScope(InstrumentationScopeInfo.create("meter")) - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .allSatisfy(metricData -> + assertThat(metricData) + .hasInstrumentationScope(InstrumentationScopeInfo.create("meter")) + .hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } finally { executorService.shutdown(); } @@ -564,19 +529,15 @@ void viewSdk_filterAttributes() { .gaugeBuilder("test") .setDescription("desc") .setUnit("unit") - .buildWithCallback( - o -> - o.record( - 1, - Attributes.builder().put("allowed", "bear").put("not allowed", "dog").build())); + .buildWithCallback(o -> + o.record( + 1, Attributes.builder().put("allowed", "bear").put("not allowed", "dog").build())); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(attributeEntry("allowed", "bear"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(attributeEntry("allowed", "bear"))))); } @Test @@ -600,13 +561,12 @@ void viewSdk_AllowRenames() { .setUnit("unit") .buildWithCallback(o -> o.record(1)); assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("not_test") - .hasDescription("not_desc") - .hasUnit("unit") - .hasDoubleGaugeSatisfying(gauge -> {})); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("not_test") + .hasDescription("not_desc") + .hasUnit("unit") + .hasDoubleGaugeSatisfying(gauge -> {})); } @Test @@ -621,7 +581,11 @@ void viewSdk_AllowMultipleViewsPerSynchronousInstrument() { View.builder() .setName("not_test") .setDescription("not_desc") - .setAggregation(Aggregation.explicitBucketHistogram(Collections.emptyList())) + .setAggregation( + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.emptyList()) + .build())) .build()) .registerView( selector, @@ -695,44 +659,6 @@ void viewSdk_AllowMultipleViewsPerAsynchronousInstrument() { .hasDoubleGaugeSatisfying(gauge -> {})); } - @Test - void viewSdk_capturesBaggageFromContext() { - InstrumentSelector selector = - InstrumentSelector.builder().setType(InstrumentType.COUNTER).setName("test").build(); - InMemoryMetricReader reader = InMemoryMetricReader.create(); - ViewBuilder viewBuilder = View.builder().setAggregation(Aggregation.sum()); - SdkMeterProviderUtil.appendAllBaggageAttributes(viewBuilder); - SdkMeterProvider provider = - sdkMeterProviderBuilder - .registerMetricReader(reader) - .registerView(selector, viewBuilder.build()) - .build(); - Meter meter = provider.get(SdkMeterProviderTest.class.getName()); - Baggage baggage = Baggage.builder().put("baggage", "value").build(); - Context context = Context.root().with(baggage); - LongCounter counter = meter.counterBuilder("test").build(); - - // Make sure whether or not we explicitly pass baggage, all values have it appended. - counter.add(1, Attributes.empty(), context); - // Also check implicit context - try (Scope ignored = context.makeCurrent()) { - counter.add(1, Attributes.empty()); - } - // Now make sure all metrics have baggage appended. - // Implicitly we should have ONLY ONE metric data point that has baggage appended. - assertThat(reader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("test") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point.hasAttributes(attributeEntry("baggage", "value"))))); - } - @Test void sdkMeterProvider_supportsMultipleReadersCumulative() { InMemoryMetricReader reader1 = InMemoryMetricReader.create(); @@ -749,78 +675,72 @@ void sdkMeterProvider_supportsMultipleReadersCumulative() { testClock.advance(Duration.ofSeconds(1)); assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); counter.add(1L); testClock.advance(Duration.ofSeconds(1)); // Reader 2 should see the measurements of Reader 1 plus the additional measurement assertThat(reader2.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(2) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(2) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); // Reader 1 should see updated cumulative values assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(2) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(2) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); } @Test @@ -839,27 +759,25 @@ void sdkMeterProvider_supportsMultipleReadersDelta() { testClock.advance(Duration.ofSeconds(1)); assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); long collectorOneTimeOne = testClock.now(); counter.add(1L); @@ -867,44 +785,39 @@ void sdkMeterProvider_supportsMultipleReadersDelta() { // Reader 2 should see the measurements of Reader 1 plus the additional measurement assertThat(reader2.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(2) - .hasAttributes(Attributes.empty()), - point -> - point - .hasStartEpochNanos(startTime) - .hasEpochNanos(testClock.now()) - .hasValue(1) - .hasAttributes(attributes)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(2) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(startTime) + .hasEpochNanos(testClock.now()) + .hasValue(1) + .hasAttributes(attributes)))); // Reader 1 should only see diff since its last collect assertThat(reader1.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasName("testSum") - .hasLongSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(collectorOneTimeOne) - .hasEpochNanos(testClock.now()) - .hasValue(1)))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("testSum") + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(collectorOneTimeOne) + .hasEpochNanos(testClock.now()) + .hasValue(1)))); } @Test @@ -926,8 +839,36 @@ void collectAll_DropAggregator() { metric -> assertThat(metric).hasResource(RESOURCE).hasName("async-counter")); } + @Test + void collectAll_AsyncInstrumentAlwaysOnExemplars() { + InMemoryMetricReader collector = InMemoryMetricReader.create(); + Meter meter = + sdkMeterProviderBuilder + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(collector) + .build() + .get("my-meter"); + + meter + .counterBuilder("async-counter") + .buildWithCallback(measurement -> measurement.record(1, Attributes.empty())); + + assertThat(collector.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasName("async-counter") + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(1) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(1))))); + } + @Test void shutdown() { + when(metricReader.getDefaultAggregation(any())).thenCallRealMethod(); when(metricReader.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); CompletableResultCode result = @@ -1025,6 +966,34 @@ void resetForTest() { sum -> sum.isCumulative().hasPointsSatisfying(point -> point.hasValue(1)))); } + private static ScopeConfigurator flipConfigurator(boolean enabled) { + return scopeInfo -> enabled ? MeterConfig.disabled() : MeterConfig.enabled(); + } + + @Test + void propagatesEnablementToMeterDirectly() { + SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()).build(); + SdkMeter meter = (SdkMeter) meterProvider.get("test"); + boolean isEnabled = meter.isMeterEnabled(); + + meterProvider.setMeterConfigurator(flipConfigurator(isEnabled)); + + Assertions.assertThat(meter.isMeterEnabled()).isEqualTo(!isEnabled); + } + + @Test + void propagatesEnablementToMeterByUtil() { + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()).build(); + SdkMeter sdkMeter = (SdkMeter) sdkMeterProvider.get("test"); + boolean isEnabled = sdkMeter.isMeterEnabled(); + + SdkMeterProviderUtil.setMeterConfigurator(sdkMeterProvider, flipConfigurator(isEnabled)); + + Assertions.assertThat(sdkMeter.isMeterEnabled()).isEqualTo(!isEnabled); + } + private static void registerViewForAllTypes( SdkMeterProviderBuilder meterProviderBuilder, Aggregation aggregation) { for (InstrumentType instrumentType : InstrumentType.values()) { diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java index 1edc76dca1d..2c4c1ccdb4b 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterRegistryTest.java @@ -91,7 +91,10 @@ void getSameInstanceForSameName_WithVersionAndSchema() { @Test void propagatesInstrumentationScopeInfoToMeter() { InstrumentationScopeInfo expected = - InstrumentationScopeInfo.create("theName", "theVersion", "http://theschema"); + InstrumentationScopeInfo.builder("theName") + .setVersion("theVersion") + .setSchemaUrl("http://theschema") + .build(); SdkMeter meter = (SdkMeter) meterProvider @@ -112,20 +115,17 @@ void metricProducer_GetAllMetrics() { longCounter2.add(10, Attributes.empty()); assertThat(sdkMeterReader.collectAllMetrics()) - .allSatisfy( - metric -> - assertThat(metric) - .hasName("testLongCounter") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasValue(10) - .hasStartEpochNanos(testClock.now()) - .hasEpochNanos(testClock.now())))) + .allSatisfy(metric -> + assertThat(metric) + .hasName("testLongCounter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasValue(10) + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(testClock.now())))) .extracting(MetricData::getInstrumentationScopeInfo) .containsExactlyInAnyOrder( ((SdkMeter) sdkMeter1).getInstrumentationScopeInfo(), diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterTest.java index 10e2767e410..bd02509d9bd 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkMeterTest.java @@ -5,7 +5,7 @@ package io.opentelemetry.sdk.metrics; -import static io.opentelemetry.api.internal.ValidationUtil.API_USAGE_LOGGER_NAME; +import static io.opentelemetry.sdk.metrics.SdkMeter.checkValidInstrumentName; import static org.assertj.core.api.Assertions.assertThat; import io.github.netmikey.logunit.api.LogCapturer; @@ -18,14 +18,15 @@ import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; import io.opentelemetry.sdk.metrics.internal.state.MetricStorageRegistry; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Locale; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; -import org.slf4j.event.LoggingEvent; -@SuppressLogger(loggerName = API_USAGE_LOGGER_NAME) @SuppressLogger(MetricStorageRegistry.class) +@SuppressLogger(SdkMeter.class) class SdkMeterTest { private static final Meter NOOP_METER = MeterProvider.noop().get("noop"); @@ -34,13 +35,13 @@ class SdkMeterTest { // Meter must have an exporter configured to actual run. private final SdkMeterProvider testMeterProvider = SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()).build(); - private final Meter sdkMeter = testMeterProvider.get(getClass().getName()); @RegisterExtension - LogCapturer logs = LogCapturer.create().captureForType(MetricStorageRegistry.class); + LogCapturer metricStorageLogs = LogCapturer.create().captureForType(MetricStorageRegistry.class); - @RegisterExtension - LogCapturer apiUsageLogs = LogCapturer.create().captureForLogger(API_USAGE_LOGGER_NAME); + @RegisterExtension LogCapturer sdkMeterLogs = LogCapturer.create().captureForType(SdkMeter.class); + + private final Meter sdkMeter = testMeterProvider.get(getClass().getName()); @Test void builder_InvalidName() { @@ -79,7 +80,7 @@ void builder_InvalidName() { assertThat(sdkMeter.histogramBuilder("1").ofLongs().build()) .isSameAs(NOOP_METER.histogramBuilder(NOOP_INSTRUMENT_NAME).ofLongs().build()); - // Gauage + // Gauge assertThat(sdkMeter.gaugeBuilder("1").buildWithCallback(unused -> {})) .isSameAs(NOOP_METER.gaugeBuilder(NOOP_INSTRUMENT_NAME).buildWithCallback(unused -> {})); assertThat(sdkMeter.gaugeBuilder("1").ofLongs().buildWithCallback(unused -> {})) @@ -88,54 +89,61 @@ void builder_InvalidName() { .gaugeBuilder(NOOP_INSTRUMENT_NAME) .ofLongs() .buildWithCallback(unused -> {})); - - assertThat(apiUsageLogs.getEvents()) - .extracting(LoggingEvent::getMessage) - .hasSize(12) - .allMatch( - log -> - log.equals( - "Instrument name \"1\" is invalid, returning noop instrument. Instrument names must consist of 63 or less characters including alphanumeric, _, ., -, and start with a letter. Returning noop instrument.")); } @Test - void builder_InvalidUnit() { - String unit = "ζ—₯"; - // Counter - sdkMeter.counterBuilder("my-instrument").setUnit(unit).build(); - sdkMeter.counterBuilder("my-instrument").setUnit(unit).buildWithCallback(unused -> {}); - sdkMeter.counterBuilder("my-instrument").setUnit(unit).ofDoubles().build(); - sdkMeter - .counterBuilder("my-instrument") - .setUnit(unit) - .ofDoubles() - .buildWithCallback(unused -> {}); - - // UpDownCounter - sdkMeter.upDownCounterBuilder("my-instrument").setUnit(unit).build(); - sdkMeter.upDownCounterBuilder("my-instrument").setUnit(unit).buildWithCallback(unused -> {}); - sdkMeter.upDownCounterBuilder("my-instrument").setUnit(unit).ofDoubles().build(); - sdkMeter - .upDownCounterBuilder("my-instrument") - .setUnit(unit) - .ofDoubles() - .buildWithCallback(unused -> {}); - - // Histogram - sdkMeter.histogramBuilder("my-instrument").setUnit(unit).build(); - sdkMeter.histogramBuilder("my-instrument").setUnit(unit).ofLongs().build(); + void checkValidInstrumentName_InvalidNameLogs() { + assertThat(checkValidInstrumentName("1")).isFalse(); + sdkMeterLogs.assertContains( + "Instrument name \"1\" is invalid, returning noop instrument. Instrument names must consist of 255 or fewer characters including alphanumeric, _, ., -, /, and start with a letter."); + } - // Gauge - sdkMeter.gaugeBuilder("my-instrument").setUnit(unit).buildWithCallback(unused -> {}); - sdkMeter.gaugeBuilder("my-instrument").setUnit(unit).ofLongs().buildWithCallback(unused -> {}); - - assertThat(apiUsageLogs.getEvents()) - .hasSize(12) - .extracting(LoggingEvent::getMessage) - .allMatch( - log -> - log.equals( - "Unit \"ζ—₯\" is invalid. Instrument unit must be 63 or less ASCII characters. Using \"\" for instrument my-instrument instead.")); + @Test + void checkValidInstrumentNameTest() { + // Valid names + assertThat(checkValidInstrumentName("f")).isTrue(); + assertThat(checkValidInstrumentName("F")).isTrue(); + assertThat(checkValidInstrumentName("foo")).isTrue(); + assertThat(checkValidInstrumentName("a1")).isTrue(); + assertThat(checkValidInstrumentName("a.")).isTrue(); + assertThat(checkValidInstrumentName("abcdefghijklmnopqrstuvwxyz")).isTrue(); + assertThat(checkValidInstrumentName("ABCDEFGHIJKLMNOPQRSTUVWXYZ")).isTrue(); + assertThat(checkValidInstrumentName("a1234567890")).isTrue(); + assertThat(checkValidInstrumentName("a_-.")).isTrue(); + assertThat(checkValidInstrumentName(new String(new char[255]).replace('\0', 'a'))).isTrue(); + assertThat(checkValidInstrumentName("a/b")).isTrue(); + + // Empty and null not allowed + assertThat(checkValidInstrumentName(null)).isFalse(); + assertThat(checkValidInstrumentName("")).isFalse(); + // Must start with a letter + assertThat(checkValidInstrumentName("1")).isFalse(); + assertThat(checkValidInstrumentName(".")).isFalse(); + // Illegal characters + assertThat(checkValidInstrumentName("a~")).isFalse(); + assertThat(checkValidInstrumentName("a!")).isFalse(); + assertThat(checkValidInstrumentName("a@")).isFalse(); + assertThat(checkValidInstrumentName("a#")).isFalse(); + assertThat(checkValidInstrumentName("a$")).isFalse(); + assertThat(checkValidInstrumentName("a%")).isFalse(); + assertThat(checkValidInstrumentName("a^")).isFalse(); + assertThat(checkValidInstrumentName("a&")).isFalse(); + assertThat(checkValidInstrumentName("a*")).isFalse(); + assertThat(checkValidInstrumentName("a(")).isFalse(); + assertThat(checkValidInstrumentName("a)")).isFalse(); + assertThat(checkValidInstrumentName("a=")).isFalse(); + assertThat(checkValidInstrumentName("a+")).isFalse(); + assertThat(checkValidInstrumentName("a{")).isFalse(); + assertThat(checkValidInstrumentName("a}")).isFalse(); + assertThat(checkValidInstrumentName("a[")).isFalse(); + assertThat(checkValidInstrumentName("a]")).isFalse(); + assertThat(checkValidInstrumentName("a\\")).isFalse(); + assertThat(checkValidInstrumentName("a|")).isFalse(); + assertThat(checkValidInstrumentName("a<")).isFalse(); + assertThat(checkValidInstrumentName("a>")).isFalse(); + assertThat(checkValidInstrumentName("a?")).isFalse(); + // Must be 255 characters or fewer + assertThat(checkValidInstrumentName(new String(new char[256]).replace('\0', 'a'))).isFalse(); } @Test @@ -155,10 +163,10 @@ void testLongCounter() { .setDescription("My very own counter") .setUnit("metric tonnes") .build(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.counterBuilder("testLongCounter").build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -170,8 +178,8 @@ void testLongCounter_upperCaseConflict() { .setUnit("metric tonnes") .build(); assertThat(longCounter).isNotNull(); - sdkMeter.counterBuilder("testLongCounter".toUpperCase()).build(); - logs.assertContains("Found duplicate metric definition"); + sdkMeter.counterBuilder("testLongCounter".toUpperCase(Locale.getDefault())).build(); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -192,10 +200,10 @@ void testLongUpDownCounter() { .setDescription("My very own counter") .setUnit("metric tonnes") .build(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.upDownCounterBuilder("testLongUpDownCounter").build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -207,9 +215,9 @@ void testLongUpDownCounter_upperCaseConflict() { .setUnit("metric tonnes") .build(); assertThat(longUpDownCounter).isNotNull(); - assertThat(logs.getEvents()).isEmpty(); - sdkMeter.upDownCounterBuilder("testLongUpDownCounter".toUpperCase()).build(); - logs.assertContains("Found duplicate metric definition"); + assertThat(metricStorageLogs.getEvents()).isEmpty(); + sdkMeter.upDownCounterBuilder("testLongUpDownCounter".toUpperCase(Locale.getDefault())).build(); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -222,7 +230,7 @@ void testLongHistogram() { .setUnit("metric tonnes") .build(); assertThat(longHistogram).isNotNull(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); // Note: We no longer get the same instrument instance as these instances are lightweight // objects backed by storage now. Here we just make sure it doesn't log an error. @@ -232,10 +240,10 @@ void testLongHistogram() { .setDescription("My very own counter") .setUnit("metric tonnes") .build(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.histogramBuilder("testLongValueRecorder").ofLongs().build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -248,10 +256,13 @@ void testLongHistogram_upperCaseConflict() { .setUnit("metric tonnes") .build(); assertThat(longHistogram).isNotNull(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); - sdkMeter.histogramBuilder("testLongValueRecorder".toUpperCase()).ofLongs().build(); - logs.assertContains("Found duplicate metric definition"); + sdkMeter + .histogramBuilder("testLongValueRecorder".toUpperCase(Locale.getDefault())) + .ofLongs() + .build(); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -262,10 +273,10 @@ void testLongGauge_conflicts() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(obs -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.gaugeBuilder("longValueObserver").ofLongs().buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -276,10 +287,13 @@ void testLongGauge_upperCaseConflicts() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(obs -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); - sdkMeter.gaugeBuilder("longValueObserver".toUpperCase()).ofLongs().buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + sdkMeter + .gaugeBuilder("longValueObserver".toUpperCase(Locale.getDefault())) + .ofLongs() + .buildWithCallback(x -> {}); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -289,10 +303,10 @@ void testLongSumObserver_conflicts() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.counterBuilder("testLongSumObserver").buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -302,10 +316,12 @@ void testLongSumObserver_upperCaseConflicts() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); - sdkMeter.counterBuilder("testLongSumObserver".toUpperCase()).buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + sdkMeter + .counterBuilder("testLongSumObserver".toUpperCase(Locale.getDefault())) + .buildWithCallback(x -> {}); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -315,10 +331,10 @@ void testLongUpDownSumObserver_conflicts() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.upDownCounterBuilder("testLongUpDownSumObserver").buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -328,12 +344,12 @@ void testLongUpDownSumObserver_upperCaseConflicts() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter - .upDownCounterBuilder("testLongUpDownSumObserver".toUpperCase()) + .upDownCounterBuilder("testLongUpDownSumObserver".toUpperCase(Locale.getDefault())) .buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -355,10 +371,10 @@ void testDoubleCounter() { .setDescription("My very own counter") .setUnit("metric tonnes") .build(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.counterBuilder("testDoubleCounter").ofDoubles().build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -380,10 +396,10 @@ void testDoubleUpDownCounter() { .setDescription("My very own counter") .setUnit("metric tonnes") .build(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.upDownCounterBuilder("testDoubleUpDownCounter").ofDoubles().build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -403,10 +419,10 @@ void testDoubleHistogram() { .setDescription("My very own ValueRecorder") .setUnit("metric tonnes") .build(); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.histogramBuilder("testDoubleValueRecorder").build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -417,10 +433,10 @@ void testDoubleSumObserver() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.counterBuilder("testDoubleSumObserver").ofDoubles().buildWithCallback(x -> {}); sdkMeter.histogramBuilder("testDoubleValueRecorder").build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -431,14 +447,14 @@ void testDoubleUpDownSumObserver() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter .upDownCounterBuilder("testDoubleUpDownSumObserver") .ofDoubles() .buildWithCallback(x -> {}); sdkMeter.histogramBuilder("testDoubleValueRecorder").build(); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); } @Test @@ -448,9 +464,34 @@ void testDoubleGauge() { .setDescription("My very own counter") .setUnit("metric tonnes") .buildWithCallback(x -> {}); - assertThat(logs.getEvents()).isEmpty(); + assertThat(metricStorageLogs.getEvents()).isEmpty(); sdkMeter.gaugeBuilder("doubleValueObserver").buildWithCallback(x -> {}); - logs.assertContains("Found duplicate metric definition"); + metricStorageLogs.assertContains("Found duplicate metric definition"); + } + + @Test + void stringRepresentation() { + assertThat(sdkMeter.toString()) + .isEqualTo( + "SdkMeter{" + + "instrumentationScopeInfo=InstrumentationScopeInfo{" + + "name=io.opentelemetry.sdk.metrics.SdkMeterTest, " + + "version=null, " + + "schemaUrl=null, " + + "attributes={}" + + "}}"); + } + + @Test + void updateEnabled() { + SdkMeterProvider sdkMeterProvider = + SdkMeterProvider.builder().registerMetricReader(InMemoryMetricReader.create()).build(); + SdkMeter meter = (SdkMeter) sdkMeterProvider.get("test"); + + meter.updateMeterConfig(MeterConfig.disabled()); + assertThat(meter.isMeterEnabled()).isFalse(); + meter.updateMeterConfig(MeterConfig.enabled()); + assertThat(meter.isMeterEnabled()).isTrue(); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java index a568a3ffb2d..67bd6abb66a 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleCounterTest.java @@ -8,10 +8,13 @@ import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.ObservableDoubleCounter; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; @@ -42,17 +45,30 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); } + @Test + @SuppressLogger(SdkObservableMeasurement.class) + void observable_NaN() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); + sdkMeterProvider + .get(getClass().getName()) + .counterBuilder("testObserver") + .ofDoubles() + .buildWithCallback(measurement -> measurement.record(Double.NaN)); + assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); + } + @Test void collectMetrics_NoRecords() { InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); @@ -83,44 +99,38 @@ void collectMetrics_WithOneRecord() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleSumObserver") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDescription("My own DoubleSumObserver") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -143,46 +153,85 @@ void collectMetrics_DeltaSumAggregator() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleSumObserver") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes( - Attributes.builder().put("k", "v").build())))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDescription("My own DoubleSumObserver") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(Attributes.builder().put("k", "v").build())))); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDescription("My own DoubleSumObserver") + .hasUnit("ms") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); + } + + @Test + void collectMetrics_DefaultExemplarFilter_NoExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); + sdkMeterProvider + .get(getClass().getName()) + .counterBuilder("testObserver") + .ofDoubles() + .buildWithCallback(result -> result.record(12.1d, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12.1d).hasExemplars()))); + } + + @Test + void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(sdkMeterReader) + .build(); + sdkMeterProvider + .get(getClass().getName()) + .counterBuilder("testObserver") + .ofDoubles() + .buildWithCallback(result -> result.record(12.1d, Attributes.empty())); + testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDescription("My own DoubleSumObserver") - .hasUnit("ms") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12.1d) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12.1d))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java index daf0dc0f18e..457c5e943a1 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableDoubleUpDownCounterTest.java @@ -8,12 +8,15 @@ import static io.opentelemetry.api.common.AttributeKey.stringKey; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.metrics.ObservableDoubleUpDownCounter; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; @@ -44,17 +47,30 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); } + @Test + @SuppressLogger(SdkObservableMeasurement.class) + void observable_NaN() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); + sdkMeterProvider + .get(getClass().getName()) + .upDownCounterBuilder("testCounter") + .ofDoubles() + .buildWithCallback(measurement -> measurement.record(Double.NaN)); + assertThat(sdkMeterReader.collectAllMetrics()).hasSize(0); + } + @Test void collectMetrics_NoRecords() { InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); @@ -83,42 +99,36 @@ void collectMetrics_WithOneRecord() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -141,42 +151,36 @@ void collectMetrics_DeltaSumAggregator() { result -> result.record(12.1d, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12.1) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12.1) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .isNotMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .isNotMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -185,4 +189,50 @@ void customAggregationThrows() { .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Custom Aggregation implementations are currently not supported."); } + + @Test + void collectMetrics_DefaultExemplarFilter_NoExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); + sdkMeterProvider + .get(getClass().getName()) + .upDownCounterBuilder("testObserver") + .ofDoubles() + .buildWithCallback(result -> result.record(12.1d, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12.1d).hasExemplars()))); + } + + @Test + void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(sdkMeterReader) + .build(); + sdkMeterProvider + .get(getClass().getName()) + .upDownCounterBuilder("testObserver") + .ofDoubles() + .buildWithCallback(result -> result.record(12.1d, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12.1d) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12.1d))))); + } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableInstrumentTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableInstrumentTest.java index 816a7234f2c..385e6f65a8c 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableInstrumentTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableInstrumentTest.java @@ -5,18 +5,20 @@ package io.opentelemetry.sdk.metrics; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; -import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.state.CallbackRegistration; -import io.opentelemetry.sdk.metrics.internal.state.MeterSharedState; import io.opentelemetry.sdk.metrics.internal.state.SdkObservableMeasurement; import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mockito; @@ -26,12 +28,14 @@ class SdkObservableInstrumentTest { @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(SdkObservableInstrument.class); - @Test - @SuppressLogger(SdkObservableInstrument.class) - void close() { - MeterSharedState meterSharedState = - spy(MeterSharedState.create(InstrumentationScopeInfo.empty(), Collections.emptyList())); - CallbackRegistration callbackRegistration = + private CallbackRegistration callbackRegistration; + private SdkMeter sdkMeter; + private SdkObservableInstrument observableInstrument; + + @BeforeEach + void setup() { + sdkMeter = mock(SdkMeter.class); + callbackRegistration = CallbackRegistration.create( Collections.singletonList( SdkObservableMeasurement.create( @@ -41,22 +45,43 @@ void close() { "description", "unit", InstrumentType.COUNTER, - InstrumentValueType.DOUBLE), + InstrumentValueType.DOUBLE, + Advice.empty()), Collections.emptyList())), () -> {}); - SdkObservableInstrument observableInstrument = - new SdkObservableInstrument(meterSharedState, callbackRegistration); + observableInstrument = new SdkObservableInstrument(sdkMeter, callbackRegistration); + } + @Test + @SuppressLogger(SdkObservableInstrument.class) + void close() { // First call to close should trigger remove from meter shared state observableInstrument.close(); - verify(meterSharedState).removeCallback(callbackRegistration); - logs.assertDoesNotContain("Instrument my-instrument has called close() multiple times."); + verify(sdkMeter).removeCallback(callbackRegistration); + logs.assertDoesNotContain("has called close() multiple times."); // Close a second time should not trigger remove from meter shared state - Mockito.reset(meterSharedState); + Mockito.reset(sdkMeter); observableInstrument.close(); - verify(meterSharedState, never()).removeCallback(callbackRegistration); - logs.assertContains("Instrument my-instrument has called close() multiple times."); + verify(sdkMeter, never()).removeCallback(callbackRegistration); + logs.assertContains("has called close() multiple times."); + } + + @Test + void stringRepresentation() { + assertThat(observableInstrument.toString()) + .isEqualTo( + "SdkObservableInstrument{" + + "callback=CallbackRegistration{" + + "instrumentDescriptors=[" + + "InstrumentDescriptor{" + + "name=my-instrument, " + + "description=description, " + + "unit=unit, " + + "type=COUNTER, " + + "valueType=DOUBLE, " + + "advice=Advice{explicitBucketBoundaries=null, attributes=null}}" + + "]}}"); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java index f4208b1c26d..78afd4c4f1b 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongCounterTest.java @@ -41,11 +41,10 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); @@ -77,42 +76,36 @@ void collectMetrics_WithOneRecord() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -131,41 +124,79 @@ void collectMetrics_DeltaSumAggregator() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); + } + + @Test + void collectMetrics_DefaultExemplarFilter_NoExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); + sdkMeterProvider + .get(getClass().getName()) + .counterBuilder("testObserver") + .buildWithCallback(result -> result.record(12, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); + } + + @Test + void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(sdkMeterReader) + .build(); + sdkMeterProvider + .get(getClass().getName()) + .counterBuilder("testObserver") + .buildWithCallback(result -> result.record(12, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java index 33c3c17167d..3f1efcbad09 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/SdkObservableLongUpDownCounterTest.java @@ -41,11 +41,10 @@ void removeCallback() { .buildWithCallback(measurement -> measurement.record(10)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasName("testCounter") - .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testCounter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> {}))); counter.close(); @@ -77,42 +76,36 @@ void collectMetrics_WithOneRecord() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - 2 * SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); } @Test @@ -133,41 +126,79 @@ void collectMetrics_DeltaSumAggregator() { .buildWithCallback(result -> result.record(12, Attributes.builder().put("k", "v").build())); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(12) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(12) + .hasAttributes(attributeEntry("k", "v"))))); testClock.advance(Duration.ofNanos(SECOND_NANOS)); assertThat(sdkMeterReader.collectAllMetrics()) - .satisfiesExactly( - metric -> - assertThat(metric) - .hasResource(RESOURCE) - .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) - .hasName("testObserver") - .hasLongSumSatisfying( - sum -> - sum.isNotMonotonic() - .isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(testClock.now() - SECOND_NANOS) - .hasEpochNanos(testClock.now()) - .hasValue(0) - .hasAttributes(attributeEntry("k", "v"))))); + .satisfiesExactly(metric -> + assertThat(metric) + .hasResource(RESOURCE) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.isNotMonotonic() + .isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now() - SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(0) + .hasAttributes(attributeEntry("k", "v"))))); + } + + @Test + void collectMetrics_DefaultExemplarFilter_NoExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder.registerMetricReader(sdkMeterReader).build(); + sdkMeterProvider + .get(getClass().getName()) + .upDownCounterBuilder("testObserver") + .buildWithCallback(result -> result.record(12, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(point -> point.hasValue(12).hasExemplars()))); + } + + @Test + void collectMetrics_AlwaysOnExemplarFilter_CollectsExemplars() { + InMemoryMetricReader sdkMeterReader = InMemoryMetricReader.create(); + SdkMeterProvider sdkMeterProvider = + sdkMeterProviderBuilder + .setExemplarFilter(ExemplarFilter.alwaysOn()) + .registerMetricReader(sdkMeterReader) + .build(); + sdkMeterProvider + .get(getClass().getName()) + .upDownCounterBuilder("testObserver") + .buildWithCallback(result -> result.record(12, Attributes.empty())); + + testClock.advance(Duration.ofNanos(SECOND_NANOS)); + assertThat(sdkMeterReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("testObserver") + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(12) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(12))))); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/StressTestRunner.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/StressTestRunner.java deleted file mode 100644 index 18d97ee7aac..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/StressTestRunner.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics; - -import com.google.auto.value.AutoValue; -import com.google.common.collect.ImmutableList; -import com.google.common.util.concurrent.Uninterruptibles; -import java.time.Duration; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import javax.annotation.concurrent.Immutable; - -@AutoValue -@Immutable -abstract class StressTestRunner { - abstract ImmutableList getOperations(); - - abstract AbstractInstrument getInstrument(); - - abstract int getCollectionIntervalMs(); - - final void run() { - List operations = getOperations(); - int numThreads = operations.size(); - CountDownLatch countDownLatch = new CountDownLatch(numThreads); - Thread collectionThread = - new Thread( - () -> { - // While workers still work, do collections. - while (countDownLatch.getCount() != 0) { - Uninterruptibles.sleepUninterruptibly(Duration.ofMillis(getCollectionIntervalMs())); - } - }); - List operationThreads = new ArrayList<>(numThreads); - for (Operation operation : operations) { - operationThreads.add( - new Thread( - () -> { - for (int i = 0; i < operation.getNumOperations(); i++) { - operation.getUpdater().update(); - Uninterruptibles.sleepUninterruptibly( - Duration.ofMillis(operation.getOperationDelayMs())); - } - countDownLatch.countDown(); - })); - } - - // Start collection thread then the rest of the worker threads. - collectionThread.start(); - for (Thread thread : operationThreads) { - thread.start(); - } - - // Wait for all the thread to finish. - for (Thread thread : operationThreads) { - Uninterruptibles.joinUninterruptibly(thread); - } - Uninterruptibles.joinUninterruptibly(collectionThread); - } - - static Builder builder() { - return new AutoValue_StressTestRunner.Builder(); - } - - @AutoValue.Builder - abstract static class Builder { - // TODO: Change this to MeterSdk when collect is available for the entire Meter. - abstract Builder setInstrument(AbstractInstrument meterSdk); - - abstract ImmutableList.Builder operationsBuilder(); - - abstract Builder setCollectionIntervalMs(int collectionInterval); - - Builder addOperation(Operation operation) { - operationsBuilder().add(operation); - return this; - } - - public abstract StressTestRunner build(); - } - - @AutoValue - @Immutable - abstract static class Operation { - - abstract int getNumOperations(); - - abstract int getOperationDelayMs(); - - abstract OperationUpdater getUpdater(); - - static Operation create(int numOperations, int operationDelayMs, OperationUpdater updater) { - return new AutoValue_StressTestRunner_Operation(numOperations, operationDelayMs, updater); - } - } - - abstract static class OperationUpdater { - - /** Called every operation. */ - abstract void update(); - - /** Called after all operations are completed. */ - abstract void cleanup(); - } - - StressTestRunner() {} -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ViewTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ViewTest.java index b81b46cba13..00ec42c6f7c 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ViewTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/ViewTest.java @@ -7,6 +7,8 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.Arrays; +import java.util.HashSet; import org.junit.jupiter.api.Test; class ViewTest { @@ -14,13 +16,15 @@ class ViewTest { @Test void stringRepresentation() { assertThat(View.builder().build().toString()) - .isEqualTo( - "View{aggregation=DefaultAggregation, attributesProcessor=NoopAttributesProcessor{}}"); + .startsWith("View{aggregation=DefaultAggregation, attributeFilter=") + .endsWith(", cardinalityLimit=2000}"); assertThat( View.builder() .setName("name") .setDescription("description") .setAggregation(Aggregation.sum()) + .setCardinalityLimit(10) + .setAttributeFilter(new HashSet<>(Arrays.asList("key1", "key2"))) .build() .toString()) .isEqualTo( @@ -28,7 +32,8 @@ void stringRepresentation() { + "name=name, " + "description=description, " + "aggregation=SumAggregation, " - + "attributesProcessor=NoopAttributesProcessor{}" + + "attributeFilter=IncludeExcludePredicate{globMatchingEnabled=false, included=[key1, key2]}, " + + "cardinalityLimit=10" + "}"); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DelegatingMetricDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DelegatingMetricDataTest.java new file mode 100644 index 00000000000..3b3763ca6f5 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DelegatingMetricDataTest.java @@ -0,0 +1,212 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.metrics.TestMetricData; +import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; +import org.junit.jupiter.api.Test; + +class DelegatingMetricDataTest { + + @Test + void delegates() { + MetricData metricData = createBasicMetricBuilder().build(); + MetricData noOpWrapper = new NoOpDelegatingMetricData(metricData); + + assertThat(noOpWrapper) + .usingRecursiveComparison( + RecursiveComparisonConfiguration.builder().withIgnoredFields("delegate").build()) + .isEqualTo(metricData); + } + + @Test + void overrideDelegate() { + MetricData metricData = createBasicMetricBuilder().build(); + MetricData withCustomDescription = new MetricDataWithCustomDescription(metricData); + + assertThat(withCustomDescription.getDescription()).isEqualTo("test"); + } + + @Test + void equals() { + MetricData metricData = createBasicMetricBuilder().build(); + MetricData noOpWrapper = new NoOpDelegatingMetricData(metricData); + MetricData withCustomDescription = new MetricDataWithCustomDescription(metricData); + + assertThat(noOpWrapper).isEqualTo(metricData); + assertThat(metricData).isNotEqualTo(withCustomDescription); + } + + @Test + void equals_sameInstance() { + MetricData metricData = createBasicMetricBuilder().build(); + MetricData noOpWrapper = new NoOpDelegatingMetricData(metricData); + + assertThat(noOpWrapper.equals(noOpWrapper)).isTrue(); + } + + @Test + void equals_differentResource() { + MetricData metricData1 = + createBasicMetricBuilder() + .setResource(Resource.create(Attributes.builder().put("key", "value1").build())) + .build(); + MetricData metricData2 = + createBasicMetricBuilder() + .setResource(Resource.create(Attributes.builder().put("key", "value2").build())) + .build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1).isNotEqualTo(noOpWrapper2); + } + + @Test + void equals_differentInstrumentationScopeInfo() { + MetricData metricData1 = + createBasicMetricBuilder() + .setInstrumentationScopeInfo(InstrumentationScopeInfo.create("scope1")) + .build(); + MetricData metricData2 = + createBasicMetricBuilder() + .setInstrumentationScopeInfo(InstrumentationScopeInfo.create("scope2")) + .build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1).isNotEqualTo(noOpWrapper2); + } + + @Test + void equals_differentName() { + MetricData metricData1 = createBasicMetricBuilder().setName("name1").build(); + MetricData metricData2 = createBasicMetricBuilder().setName("name2").build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1).isNotEqualTo(noOpWrapper2); + } + + @Test + void equals_differentUnit() { + MetricData metricData1 = createBasicMetricBuilder().setUnit("unit1").build(); + MetricData metricData2 = createBasicMetricBuilder().setUnit("unit2").build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1).isNotEqualTo(noOpWrapper2); + } + + @Test + void equals_differentType() { + MetricData metricData1 = + createBasicMetricBuilder().setHistogramData(ImmutableHistogramData.empty()).build(); + MetricData metricData2 = + createBasicMetricBuilder().setSummaryData(ImmutableSummaryData.empty()).build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1).isNotEqualTo(noOpWrapper2); + } + + @Test + void equals_differentData() { + MetricData metricData1 = + createBasicMetricBuilder().setSummaryData(ImmutableSummaryData.empty()).build(); + MetricData metricData2 = + createBasicMetricBuilder().setSummaryData(ImmutableSummaryData.empty()).build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1).isEqualTo(noOpWrapper2); + } + + @Test + void equals_nonMetricDataObject_returnsFalse() { + MetricData metricData = createBasicMetricBuilder().build(); + MetricData noOpWrapper = new NoOpDelegatingMetricData(metricData); + + // Compare with a String object (non-MetricData) + Object nonMetricData = "not a metric data"; + + assertThat(noOpWrapper.equals(nonMetricData)).isFalse(); + } + + @Test + void testToString() { + MetricData metricData = createBasicMetricBuilder().build(); + MetricData noOpWrapper = new NoOpDelegatingMetricData(metricData); + + String expectedString = + "DelegatingMetricData{" + + "resource=" + + metricData.getResource() + + ", instrumentationScopeInfo=" + + metricData.getInstrumentationScopeInfo() + + ", name=" + + metricData.getName() + + ", description=" + + metricData.getDescription() + + ", unit=" + + metricData.getUnit() + + ", type=" + + metricData.getType() + + ", data=" + + metricData.getData() + + "}"; + + assertThat(noOpWrapper.toString()).isEqualTo(expectedString); + } + + @Test + void testHashCode() { + MetricData metricData1 = createBasicMetricBuilder().build(); + MetricData metricData2 = createBasicMetricBuilder().build(); + MetricData noOpWrapper1 = new NoOpDelegatingMetricData(metricData1); + MetricData noOpWrapper2 = new NoOpDelegatingMetricData(metricData2); + + assertThat(noOpWrapper1.hashCode()).isEqualTo(metricData1.hashCode()); + assertThat(noOpWrapper2.hashCode()).isEqualTo(metricData2.hashCode()); + assertThat(noOpWrapper1.hashCode()).isEqualTo(noOpWrapper2.hashCode()); + } + + private static TestMetricData.Builder createBasicMetricBuilder() { + return TestMetricData.builder() + .setResource(Resource.empty()) + .setInstrumentationScopeInfo(InstrumentationScopeInfo.empty()) + .setDescription("") + .setUnit("1") + .setName("name") + .setSummaryData(ImmutableSummaryData.empty()); + } + + private static final class NoOpDelegatingMetricData extends DelegatingMetricData { + private NoOpDelegatingMetricData(MetricData delegate) { + super(delegate); + } + } + + private static final class MetricDataWithCustomDescription extends DelegatingMetricData { + private final String description; + + private MetricDataWithCustomDescription(MetricData delegate) { + super(delegate); + this.description = "test"; + } + + @Override + public String getDescription() { + return description; + } + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarDataTest.java new file mode 100644 index 00000000000..ec3d8d31d03 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DoubleExemplarDataTest.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.internal.ImmutableSpanContext; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import org.junit.jupiter.api.Test; + +class DoubleExemplarDataTest { + + private static final String TRACE_ID = "00000000000000000000000000000061"; + private static final String SPAN_ID = "0000000000000061"; + + @Test + void create() { + SpanContext spanContext = + ImmutableSpanContext.create( + TRACE_ID, + SPAN_ID, + TraceFlags.getDefault(), + TraceState.getDefault(), + /* remote= */ false, + /* skipIdValidation= */ false); + DoubleExemplarData exemplarData = + DoubleExemplarData.create( + Attributes.builder().put("key", "value1").build(), // attributes + 1, // epochNanos + /* spanContext= */ spanContext, + /* value= */ 2.0); + assertThat(exemplarData.getValue()).isEqualTo(2.0); + assertThat(exemplarData.getEpochNanos()).isEqualTo(1); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DoublePointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DoublePointDataTest.java new file mode 100644 index 00000000000..c44c0dde2a3 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/DoublePointDataTest.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class DoublePointDataTest { + + @Test + void create() { + DoublePointData pointData = + DoublePointData.create( + 1, 2, Attributes.builder().put("key", "value1").build(), 3, Collections.emptyList()); + assertThat(pointData.getStartEpochNanos()).isEqualTo(1); + assertThat(pointData.getEpochNanos()).isEqualTo(2); + assertThat(pointData.getAttributes()) + .isEqualTo(Attributes.builder().put("key", "value1").build()); + assertThat(pointData.getValue()).isEqualTo(3); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramBucketsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramBucketsTest.java new file mode 100644 index 00000000000..f496ec04548 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramBucketsTest.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import org.junit.jupiter.api.Test; + +class ExponentialHistogramBucketsTest { + + @Test + void create() { + ExponentialHistogramBuckets buckets = + ExponentialHistogramBuckets.create(1, 2, Arrays.asList(3L, 4L)); + assertThat(buckets.getBucketCounts()).containsExactly(3L, 4L); + assertThat(buckets.getScale()).isEqualTo(1); + assertThat(buckets.getOffset()).isEqualTo(2); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramDataTest.java new file mode 100644 index 00000000000..28664f07cbd --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramDataTest.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class ExponentialHistogramDataTest { + + @Test + void create() { + ExponentialHistogramData histogramData = + ExponentialHistogramData.create(AggregationTemporality.CUMULATIVE, Collections.emptyList()); + assertThat(histogramData.getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(histogramData.getPoints()).isEmpty(); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramPointDataTest.java new file mode 100644 index 00000000000..2e066af2e0a --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ExponentialHistogramPointDataTest.java @@ -0,0 +1,68 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramBuckets; +import java.util.Arrays; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class ExponentialHistogramPointDataTest { + + @Test + void create() { + DoubleExemplarData doubleExemplarOne = + ImmutableDoubleExemplarData.create( + Attributes.empty(), + 0, + SpanContext.create( + "TraceId", "SpanId", TraceFlags.getDefault(), TraceState.getDefault()), + 1.0); + + DoubleExemplarData doubleExemplarTwo = + ImmutableDoubleExemplarData.create( + Attributes.empty(), + 2, + SpanContext.create( + "TraceId", "SpanId", TraceFlags.getDefault(), TraceState.getDefault()), + 2.0); + ExponentialHistogramPointData pointData = + ExponentialHistogramPointData.create( + 1, + 10.0, + 1, + /* hasMin= */ true, + 2.0, + /* hasMax= */ true, + 4.0, + ImmutableExponentialHistogramBuckets.create(1, 10, Arrays.asList(1L, 2L)), + ImmutableExponentialHistogramBuckets.create(1, 0, Collections.emptyList()), + 1, + 2, + Attributes.empty(), + Arrays.asList(doubleExemplarOne, doubleExemplarTwo)); + assertThat(pointData.getStartEpochNanos()).isEqualTo(1); + assertThat(pointData.getEpochNanos()).isEqualTo(2); + assertThat(pointData.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(pointData.getSum()).isEqualTo(10.0); + assertThat(pointData.getCount()).isEqualTo(4); + assertThat(pointData.hasMin()).isTrue(); + assertThat(pointData.getMin()).isEqualTo(2.0); + assertThat(pointData.hasMax()).isTrue(); + assertThat(pointData.getMax()).isEqualTo(4.0); + assertThat(pointData.getPositiveBuckets().getTotalCount()).isEqualTo(3); + assertThat(pointData.getNegativeBuckets().getTotalCount()).isEqualTo(0); + assertThat(pointData.getPositiveBuckets().getBucketCounts()).containsExactly(1L, 2L); + assertThat(pointData.getNegativeBuckets().getBucketCounts()).isEmpty(); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/GaugeDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/GaugeDataTest.java new file mode 100644 index 00000000000..85e3c73e3d7 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/GaugeDataTest.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class GaugeDataTest { + + @Test + void createLongGaugeData() { + LongPointData point = LongPointData.create(0, 0, Attributes.empty(), 1); + GaugeData gaugeData = + GaugeData.createLongGaugeData(Collections.singleton(point)); + assertThat(gaugeData.getPoints()).containsExactly(point); + } + + @Test + void createDoubleGaugeData() { + DoublePointData point = + DoublePointData.create(0, 0, Attributes.empty(), 1.0, Collections.emptyList()); + GaugeData gaugeData = + GaugeData.createDoubleGaugeData(Collections.singleton(point)); + assertThat(gaugeData.getPoints()).containsExactly(point); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/HistogramDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/HistogramDataTest.java new file mode 100644 index 00000000000..ca131e125bc --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/HistogramDataTest.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class HistogramDataTest { + + @Test + void create() { + HistogramData histogramData = + HistogramData.create(AggregationTemporality.CUMULATIVE, Collections.emptyList()); + assertThat(histogramData.getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(histogramData.getPoints()).isEmpty(); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/HistogramPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/HistogramPointDataTest.java new file mode 100644 index 00000000000..72b132fbc88 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/HistogramPointDataTest.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableList; +import io.opentelemetry.api.common.Attributes; +import java.util.ArrayList; +import org.junit.jupiter.api.Test; + +class HistogramPointDataTest { + + @Test + void create() { + HistogramPointData pointData = + HistogramPointData.create( + 0, + 0, + Attributes.empty(), + 3.0, + /* hasMin= */ false, + 1.0, + /* hasMax= */ false, + 2.0, + new ArrayList<>(), + ImmutableList.of(0L)); + assertThat(pointData.getStartEpochNanos()).isEqualTo(0); + assertThat(pointData.getEpochNanos()).isEqualTo(0); + assertThat(pointData.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(pointData.getSum()).isEqualTo(3.0); + assertThat(pointData.getCount()).isEqualTo(0); + assertThat(pointData.hasMin()).isFalse(); + assertThat(pointData.getMin()).isEqualTo(1.0); + assertThat(pointData.hasMax()).isFalse(); + assertThat(pointData.getMax()).isEqualTo(2.0); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java index 14ffe4d3680..b0690c2ffa2 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ImmutableMetricDataTest.java @@ -63,7 +63,9 @@ class ImmutableMetricDataTest { EPOCH_NANOS, Attributes.of(KEY, "value"), DOUBLE_VALUE, + /* hasMin= */ true, DOUBLE_VALUE_MIN, + /* hasMax= */ true, DOUBLE_VALUE_MAX, ImmutableList.of(1.0), ImmutableList.of(1L, 1L)); @@ -196,41 +198,44 @@ void metricData_HistogramPoints() { AggregationTemporality.DELTA, Collections.singleton(HISTOGRAM_POINT))); assertThat(metricData.getHistogramData().getPoints()).containsExactly(HISTOGRAM_POINT); - assertThatThrownBy( - () -> - ImmutableHistogramPointData.create( - 0, - 0, - Attributes.empty(), - 0.0, - 0.0, - 0.0, - ImmutableList.of(), - ImmutableList.of())) + assertThatThrownBy(() -> + ImmutableHistogramPointData.create( + 0, + 0, + Attributes.empty(), + 0.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + ImmutableList.of(), + ImmutableList.of())) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - ImmutableHistogramPointData.create( - 0, - 0, - Attributes.empty(), - 0.0, - 0.0, - 0.0, - ImmutableList.of(1.0, 1.0), - ImmutableList.of(0L, 0L, 0L))) + assertThatThrownBy(() -> + ImmutableHistogramPointData.create( + 0, + 0, + Attributes.empty(), + 0.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + ImmutableList.of(1.0, 1.0), + ImmutableList.of(0L, 0L, 0L))) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy( - () -> - ImmutableHistogramPointData.create( - 0, - 0, - Attributes.empty(), - 0.0, - 0.0, - 0.0, - ImmutableList.of(Double.NEGATIVE_INFINITY), - ImmutableList.of(0L, 0L))) + assertThatThrownBy(() -> + ImmutableHistogramPointData.create( + 0, + 0, + Attributes.empty(), + 0.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + ImmutableList.of(Double.NEGATIVE_INFINITY), + ImmutableList.of(0L, 0L))) .isInstanceOf(IllegalArgumentException.class); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/LongExemplarDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/LongExemplarDataTest.java new file mode 100644 index 00000000000..25da1c9e24e --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/LongExemplarDataTest.java @@ -0,0 +1,35 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import org.junit.jupiter.api.Test; + +class LongExemplarDataTest { + + @Test + void create() { + Attributes attributes = Attributes.builder().put("test", "value").build(); + LongExemplarData exemplar = + LongExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1); + assertThat(exemplar.getFilteredAttributes()).isEqualTo(attributes); + assertThat(exemplar.getValue()).isEqualTo(1L); + assertThat(exemplar.getSpanContext()).isNotNull(); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/LongPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/LongPointDataTest.java new file mode 100644 index 00000000000..7685ff2968e --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/LongPointDataTest.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import org.junit.jupiter.api.Test; + +class LongPointDataTest { + + @Test + void create() { + LongPointData pointData = LongPointData.create(0, 0, Attributes.empty(), 0); + assertThat(pointData.getStartEpochNanos()).isEqualTo(0); + assertThat(pointData.getEpochNanos()).isEqualTo(0); + assertThat(pointData.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(pointData.getValue()).isEqualTo(0); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SumDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SumDataTest.java new file mode 100644 index 00000000000..96f959d52ab --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SumDataTest.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class SumDataTest { + + @Test + void createLongSumData() { + LongPointData point = LongPointData.create(0, 0, Attributes.empty(), 1); + SumData sumData = + SumData.createLongSumData( + /* isMonotonic= */ false, + AggregationTemporality.CUMULATIVE, + Collections.singletonList(point)); + assertThat(sumData.getPoints()).containsExactly(point); + } + + @Test + void createDoubleSumData() { + DoublePointData point = + DoublePointData.create(0, 0, Attributes.empty(), 1.0, Collections.emptyList()); + SumData sumData = + SumData.createDoubleSumData( + /* isMonotonic= */ false, + AggregationTemporality.CUMULATIVE, + Collections.singletonList(point)); + assertThat(sumData.getPoints()).containsExactly(point); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SummaryDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SummaryDataTest.java new file mode 100644 index 00000000000..729b3bf5119 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SummaryDataTest.java @@ -0,0 +1,31 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +class SummaryDataTest { + + @Test + void create() { + List percentileValues = + Collections.singletonList(ImmutableValueAtQuantile.create(3.0, 4.0)); + List points = + Collections.singletonList( + ImmutableSummaryPointData.create( + 12345, 12346, Attributes.empty(), 1, 2.0, percentileValues)); + SummaryData summary = ImmutableSummaryData.create(points); + assertThat(summary.getPoints()).isEqualTo(points); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SummaryPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SummaryPointDataTest.java new file mode 100644 index 00000000000..08ba69bac55 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/SummaryPointDataTest.java @@ -0,0 +1,38 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.util.Collections; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +class SummaryPointDataTest { + + @Test + void create() { + AttributeKey kvAttr = AttributeKey.stringKey("key"); + long startEpochNanos = TimeUnit.MILLISECONDS.toNanos(1000); + long epochNanos = TimeUnit.MILLISECONDS.toNanos(2000); + double sum = 10.0; + long count = 5; + SummaryPointData summaryPoint = + SummaryPointData.create( + startEpochNanos, + epochNanos, + Attributes.of(kvAttr, "value"), + count, + sum, + Collections.emptyList()); + assertThat(summaryPoint.getStartEpochNanos()).isEqualTo(startEpochNanos); + assertThat(summaryPoint.getEpochNanos()).isEqualTo(epochNanos); + assertThat(summaryPoint.getSum()).isEqualTo(sum); + assertThat(summaryPoint.getCount()).isEqualTo(count); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantileTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantileTest.java new file mode 100644 index 00000000000..ffcd37cc5da --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/data/ValueAtQuantileTest.java @@ -0,0 +1,20 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class ValueAtQuantileTest { + + @Test + void create() { + ValueAtQuantile valueAtQuantile = ValueAtQuantile.create(0.0, 1.1); + assertThat(valueAtQuantile.getQuantile()).isEqualTo(0.0); + assertThat(valueAtQuantile.getValue()).isEqualTo(1.1); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelectorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelectorTest.java index b767ff25e5c..fb821ce388e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelectorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/AggregationTemporalitySelectorTest.java @@ -28,6 +28,8 @@ void alwaysCumulative() { .isEqualTo(AggregationTemporality.CUMULATIVE); assertThat(selector.getAggregationTemporality(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER)) .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(selector.getAggregationTemporality(InstrumentType.GAUGE)) + .isEqualTo(AggregationTemporality.CUMULATIVE); } @Test @@ -45,5 +47,56 @@ void deltaPreferred() { .isEqualTo(AggregationTemporality.CUMULATIVE); assertThat(selector.getAggregationTemporality(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER)) .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(selector.getAggregationTemporality(InstrumentType.GAUGE)) + .isEqualTo(AggregationTemporality.DELTA); + } + + @Test + void lowMemory() { + AggregationTemporalitySelector selector = AggregationTemporalitySelector.lowMemory(); + assertThat(selector.getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat(selector.getAggregationTemporality(InstrumentType.OBSERVABLE_COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(selector.getAggregationTemporality(InstrumentType.HISTOGRAM)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat(selector.getAggregationTemporality(InstrumentType.OBSERVABLE_GAUGE)) + .isEqualTo(AggregationTemporality.DELTA); + assertThat(selector.getAggregationTemporality(InstrumentType.UP_DOWN_COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(selector.getAggregationTemporality(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(selector.getAggregationTemporality(InstrumentType.GAUGE)) + .isEqualTo(AggregationTemporality.DELTA); + } + + @Test + void stringRepresentation() { + assertThat( + AggregationTemporalitySelector.asString( + AggregationTemporalitySelector.alwaysCumulative())) + .isEqualTo( + "AggregationTemporalitySelector{" + + "COUNTER=CUMULATIVE, " + + "UP_DOWN_COUNTER=CUMULATIVE, " + + "HISTOGRAM=CUMULATIVE, " + + "OBSERVABLE_COUNTER=CUMULATIVE, " + + "OBSERVABLE_UP_DOWN_COUNTER=CUMULATIVE, " + + "OBSERVABLE_GAUGE=CUMULATIVE, " + + "GAUGE=CUMULATIVE" + + "}"); + assertThat( + AggregationTemporalitySelector.asString( + AggregationTemporalitySelector.deltaPreferred())) + .isEqualTo( + "AggregationTemporalitySelector{" + + "COUNTER=DELTA, " + + "UP_DOWN_COUNTER=CUMULATIVE, " + + "HISTOGRAM=DELTA, " + + "OBSERVABLE_COUNTER=DELTA, " + + "OBSERVABLE_UP_DOWN_COUNTER=CUMULATIVE, " + + "OBSERVABLE_GAUGE=DELTA, " + + "GAUGE=DELTA" + + "}"); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/DefaultAggregationSelectorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/DefaultAggregationSelectorTest.java new file mode 100644 index 00000000000..1cbf0649c7a --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/DefaultAggregationSelectorTest.java @@ -0,0 +1,97 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.InstrumentType; +import org.junit.jupiter.api.Test; + +class DefaultAggregationSelectorTest { + + @Test + void getDefault() { + DefaultAggregationSelector selector = DefaultAggregationSelector.getDefault(); + for (InstrumentType instrumentType : InstrumentType.values()) { + assertThat(selector.getDefaultAggregation(instrumentType)) + .isEqualTo(Aggregation.defaultAggregation()); + } + } + + @Test + void with() { + assertThatThrownBy(() -> DefaultAggregationSelector.getDefault().with(null, Aggregation.drop())) + .hasMessage("instrumentType"); + assertThatThrownBy( + () -> DefaultAggregationSelector.getDefault().with(InstrumentType.HISTOGRAM, null)) + .hasMessage("aggregation"); + + DefaultAggregationSelector selector1 = + DefaultAggregationSelector.getDefault().with(InstrumentType.HISTOGRAM, Aggregation.drop()); + assertThat(selector1.getDefaultAggregation(InstrumentType.COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector1.getDefaultAggregation(InstrumentType.UP_DOWN_COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector1.getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.drop()); + assertThat(selector1.getDefaultAggregation(InstrumentType.OBSERVABLE_COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector1.getDefaultAggregation(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector1.getDefaultAggregation(InstrumentType.OBSERVABLE_GAUGE)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector1.getDefaultAggregation(InstrumentType.GAUGE)) + .isEqualTo(Aggregation.defaultAggregation()); + + DefaultAggregationSelector selector2 = + selector1.with(InstrumentType.COUNTER, Aggregation.drop()); + assertThat(selector2.getDefaultAggregation(InstrumentType.COUNTER)) + .isEqualTo(Aggregation.drop()); + assertThat(selector2.getDefaultAggregation(InstrumentType.UP_DOWN_COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector2.getDefaultAggregation(InstrumentType.HISTOGRAM)) + .isEqualTo(Aggregation.drop()); + assertThat(selector2.getDefaultAggregation(InstrumentType.OBSERVABLE_COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector2.getDefaultAggregation(InstrumentType.OBSERVABLE_UP_DOWN_COUNTER)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector2.getDefaultAggregation(InstrumentType.OBSERVABLE_GAUGE)) + .isEqualTo(Aggregation.defaultAggregation()); + assertThat(selector2.getDefaultAggregation(InstrumentType.GAUGE)) + .isEqualTo(Aggregation.defaultAggregation()); + } + + @Test + void stringRepresentation() { + assertThat(DefaultAggregationSelector.asString(DefaultAggregationSelector.getDefault())) + .isEqualTo( + "DefaultAggregationSelector{" + + "COUNTER=default, " + + "UP_DOWN_COUNTER=default, " + + "HISTOGRAM=default, " + + "OBSERVABLE_COUNTER=default, " + + "OBSERVABLE_UP_DOWN_COUNTER=default, " + + "OBSERVABLE_GAUGE=default, " + + "GAUGE=default" + + "}"); + assertThat( + DefaultAggregationSelector.asString( + DefaultAggregationSelector.getDefault() + .with(InstrumentType.HISTOGRAM, Aggregation.base2ExponentialBucketHistogram()))) + .isEqualTo( + "DefaultAggregationSelector{" + + "COUNTER=default, " + + "UP_DOWN_COUNTER=default, " + + "HISTOGRAM=base2_exponential_bucket_histogram, " + + "OBSERVABLE_COUNTER=default, " + + "OBSERVABLE_UP_DOWN_COUNTER=default, " + + "OBSERVABLE_GAUGE=default, " + + "GAUGE=default" + + "}"); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/MetricExportBatcherTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/MetricExportBatcherTest.java new file mode 100644 index 00000000000..0a99b03fc92 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/MetricExportBatcherTest.java @@ -0,0 +1,753 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.export; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.data.SummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSummaryPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableValueAtQuantile; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.Test; + +class MetricExportBatcherTest { + + @Test + void batchMetrics_InvalidMaxExportBatchSize() { + assertThatThrownBy(() -> MetricExportBatcher.batchMetrics(Collections.emptyList(), 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxExportBatchSize must be positive"); + assertThatThrownBy(() -> MetricExportBatcher.batchMetrics(Collections.emptyList(), -1)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxExportBatchSize must be positive"); + } + + @Test + void batchMetrics_EmptyMetrics() { + assertThat(MetricExportBatcher.batchMetrics(Collections.emptyList(), 10)).isEmpty(); + } + + @Test + void batchMetrics_MetricFitsIntact() { + LongPointData p1 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 1L); + MetricData metric = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableGaugeData.create(Collections.singletonList(p1))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 10); + assertThat(batches).hasSize(1); + assertThat(batches.iterator().next()).containsExactly(metric); + } + + @Test + void batchMetrics_SplitsDoubleGauge_LastBatchPartiallyFilled() { + DoublePointData p1 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 1.0); + DoublePointData p2 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 2.0); + DoublePointData p3 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 3.0); + DoublePointData p4 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 4.0); + DoublePointData p5 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 5.0); + + MetricData metric = + ImmutableMetricData.createDoubleGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p1, p2, p3, p4, p5))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 2); + List> batchesList = new ArrayList<>(batches); + + assertThat(batchesList.size()).isEqualTo(3); + Collection firstBatch = batchesList.get(0); + Collection secondBatch = batchesList.get(1); + Collection thirdBatch = batchesList.get(2); + + assertThat(firstBatch.size()).isEqualTo(1); + assertThat(secondBatch.size()).isEqualTo(1); + assertThat(thirdBatch.size()).isEqualTo(1); + + MetricData b1m1 = firstBatch.iterator().next(); + assertThat(b1m1.getType()).isEqualByComparingTo(MetricDataType.DOUBLE_GAUGE); + assertThat(b1m1.getName()).isEqualTo("name"); + assertThat(b1m1.getDescription()).isEqualTo("desc"); + assertThat(b1m1.getUnit()).isEqualTo("1"); + assertThat(b1m1.getDoubleGaugeData().getPoints()).containsExactly(p1, p2); + + MetricData b2m1 = secondBatch.iterator().next(); + assertThat(b2m1.getType()).isEqualByComparingTo(MetricDataType.DOUBLE_GAUGE); + assertThat(b2m1.getName()).isEqualTo("name"); + assertThat(b2m1.getDescription()).isEqualTo("desc"); + assertThat(b2m1.getUnit()).isEqualTo("1"); + assertThat(b2m1.getDoubleGaugeData().getPoints()).containsExactly(p3, p4); + + // Last batch is partially filled. + MetricData b3m1 = thirdBatch.iterator().next(); + assertThat(b3m1.getType()).isEqualByComparingTo(MetricDataType.DOUBLE_GAUGE); + assertThat(b3m1.getName()).isEqualTo("name"); + assertThat(b3m1.getDescription()).isEqualTo("desc"); + assertThat(b3m1.getUnit()).isEqualTo("1"); + assertThat(b3m1.getDoubleGaugeData().getPoints()).containsExactly(p5); + } + + @Test + void batchMetrics_SplitsLongGauge_SingleBatchPartiallyFilled() { + LongPointData p1 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 1L); + LongPointData p2 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 2L); + LongPointData p3 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 3L); + + MetricData metric = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p1, p2, p3))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 4); + + assertThat(batches).hasSize(1); + Collection firstBatch = batches.iterator().next(); + assertThat(firstBatch).hasSize(1); // There is only 1 MetricData + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.LONG_GAUGE); + assertThat(m1.getName()).isEqualTo("name"); + assertThat(m1.getDescription()).isEqualTo("desc"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getLongGaugeData().getPoints()).containsExactly(p1, p2, p3); + } + + @Test + void batchMetrics_SplitsDoubleSum_SingleBatchCompletelyFilled() { + DoublePointData p1 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 1.0); + DoublePointData p2 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 2.0); + + MetricData metric = + ImmutableMetricData.createDoubleSum( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableSumData.create( + /* isMonotonic= */ true, AggregationTemporality.CUMULATIVE, Arrays.asList(p1, p2))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 2); + + Collection firstBatch = batches.iterator().next(); + assertThat(firstBatch).hasSize(1); // There is only 1 MetricData + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.DOUBLE_SUM); + assertThat(m1.getName()).isEqualTo("name"); + assertThat(m1.getDescription()).isEqualTo("desc"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getDoubleSumData().getPoints()).containsExactly(p1, p2); + assertThat(m1.getDoubleSumData().isMonotonic()).isTrue(); + assertThat(m1.getDoubleSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + } + + @Test + void batchMetrics_SplitsLongSum_MultipleBatchesCompletelyFilled_MultipleMetrics() { + Attributes attrs1 = Attributes.builder().put("key1", "val1").build(); + Attributes attrs2 = Attributes.builder().put("key2", "val2").build(); + LongPointData p1 = ImmutableLongPointData.create(1, 2, attrs1, 1L); + LongPointData p2 = ImmutableLongPointData.create(1, 2, attrs2, 2L); + + MetricData metric1 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_1", + "desc_1", + "1", + ImmutableSumData.create( + /* isMonotonic= */ false, AggregationTemporality.DELTA, Arrays.asList(p1, p2))); + + MetricData metric2 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_2", + "desc_2", + "1", + ImmutableSumData.create( + /* isMonotonic= */ false, AggregationTemporality.DELTA, Arrays.asList(p1, p2))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Arrays.asList(metric1, metric2), 1); + + assertThat(batches).hasSize(4); + Collection firstBatch = batches.iterator().next(); + Collection secondBatch = batches.stream().skip(1).findFirst().get(); + Collection thirdBatch = batches.stream().skip(2).findFirst().get(); + Collection fourthBatch = batches.stream().skip(3).findFirst().get(); + + assertThat(firstBatch).hasSize(1); + assertThat(secondBatch).hasSize(1); + assertThat(thirdBatch).hasSize(1); + assertThat(fourthBatch).hasSize(1); + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.LONG_SUM); + assertThat(m1.getName()).isEqualTo("name_1"); + assertThat(m1.getDescription()).isEqualTo("desc_1"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getLongSumData().getPoints()).containsExactly(p1); + assertThat(m1.getLongSumData().getPoints().iterator().next().getAttributes()).isEqualTo(attrs1); + assertThat(m1.getLongSumData().isMonotonic()).isFalse(); + assertThat(m1.getLongSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.DELTA); + + MetricData m2 = secondBatch.iterator().next(); + assertThat(m2.getType()).isEqualTo(MetricDataType.LONG_SUM); + assertThat(m2.getName()).isEqualTo("name_1"); + assertThat(m2.getDescription()).isEqualTo("desc_1"); + assertThat(m2.getUnit()).isEqualTo("1"); + assertThat(m2.getLongSumData().getPoints()).containsExactly(p2); + assertThat(m2.getLongSumData().getPoints().iterator().next().getAttributes()).isEqualTo(attrs2); + assertThat(m2.getLongSumData().isMonotonic()).isFalse(); + assertThat(m2.getLongSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.DELTA); + + MetricData m3 = thirdBatch.iterator().next(); + assertThat(m3.getType()).isEqualTo(MetricDataType.LONG_SUM); + assertThat(m3.getName()).isEqualTo("name_2"); + assertThat(m3.getDescription()).isEqualTo("desc_2"); + assertThat(m3.getUnit()).isEqualTo("1"); + assertThat(m3.getLongSumData().getPoints()).containsExactly(p1); + assertThat(m3.getLongSumData().getPoints().iterator().next().getAttributes()).isEqualTo(attrs1); + assertThat(m3.getLongSumData().isMonotonic()).isFalse(); + assertThat(m3.getLongSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.DELTA); + + MetricData m4 = fourthBatch.iterator().next(); + assertThat(m4.getType()).isEqualTo(MetricDataType.LONG_SUM); + assertThat(m4.getName()).isEqualTo("name_2"); + assertThat(m4.getDescription()).isEqualTo("desc_2"); + assertThat(m4.getUnit()).isEqualTo("1"); + assertThat(m4.getLongSumData().getPoints()).containsExactly(p2); + assertThat(m4.getLongSumData().getPoints().iterator().next().getAttributes()).isEqualTo(attrs2); + assertThat(m4.getLongSumData().isMonotonic()).isFalse(); + assertThat(m4.getLongSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.DELTA); + } + + @Test + void batchMetrics_SplitsHistogram_MultipleBatchesCompletelyFilled_SingleMetric() { + ImmutableHistogramPointData p1 = + ImmutableHistogramPointData.create( + 1, + 2, + Attributes.empty(), + 1.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + Collections.emptyList(), + Collections.singletonList(1L)); + ImmutableHistogramPointData p2 = + ImmutableHistogramPointData.create( + 1, + 2, + Attributes.empty(), + 2.0, + /* hasMin= */ false, + 0.0, + /* hasMax= */ false, + 0.0, + Collections.emptyList(), + Collections.singletonList(2L)); + + MetricData metric = + ImmutableMetricData.createDoubleHistogram( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableHistogramData.create( + AggregationTemporality.CUMULATIVE, Arrays.asList(p1, p2))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 1); + + assertThat(batches).hasSize(2); + Collection firstBatch = batches.iterator().next(); + Collection secondBatch = batches.stream().skip(1).findFirst().get(); + assertThat(firstBatch).hasSize(1); + assertThat(secondBatch).hasSize(1); + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.HISTOGRAM); + assertThat(m1.getName()).isEqualTo("name"); + assertThat(m1.getDescription()).isEqualTo("desc"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getHistogramData().getPoints()).containsExactly(p1); + assertThat(m1.getHistogramData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + MetricData m2 = secondBatch.iterator().next(); + assertThat(m2.getType()).isEqualTo(MetricDataType.HISTOGRAM); + assertThat(m2.getName()).isEqualTo("name"); + assertThat(m2.getDescription()).isEqualTo("desc"); + assertThat(m2.getUnit()).isEqualTo("1"); + assertThat(m2.getHistogramData().getPoints()).containsExactly(p2); + assertThat(m2.getHistogramData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + } + + @Test + void batchMetrics_MultipleMetricsExactCapacityMatch() { + Attributes attrs1 = Attributes.builder().put("k", "v1").build(); + Attributes attrs2 = Attributes.builder().put("k", "v2").build(); + Attributes attrs3 = Attributes.builder().put("k", "v3").build(); + Attributes attrs4 = Attributes.builder().put("k", "v4").build(); + LongPointData p1 = ImmutableLongPointData.create(1, 2, attrs1, 1L); + LongPointData p2 = ImmutableLongPointData.create(1, 2, attrs2, 2L); + LongPointData p3 = ImmutableLongPointData.create(1, 2, attrs3, 3L); + LongPointData p4 = ImmutableLongPointData.create(1, 2, attrs4, 4L); + + MetricData m1 = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_1", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p1, p2))); + MetricData m2 = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_2", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p3, p4))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Arrays.asList(m1, m2), 4); + assertThat(batches).hasSize(1); + Collection firstBatch = batches.iterator().next(); + assertThat(firstBatch).containsExactly(m1, m2); + + MetricData res1 = firstBatch.iterator().next(); + MetricData res2 = firstBatch.stream().skip(1).findFirst().get(); + + assertThat(res1.getName()).isEqualTo("name_1"); + assertThat(res1.getLongGaugeData().getPoints()).containsExactly(p1, p2); + assertThat(res2.getName()).isEqualTo("name_2"); + assertThat(res2.getLongGaugeData().getPoints()).containsExactly(p3, p4); + } + + @Test + void batchMetrics_SplitsLongGauge_MultipleMetrics_ExceedsCapacity() { + LongPointData p1 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 1L); + LongPointData p2 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 2L); + LongPointData p3 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 3L); + LongPointData p4 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 4L); + LongPointData p5 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 5L); + LongPointData p6 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 6L); + + MetricData m1 = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_1", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p1, p2, p3))); + MetricData m2 = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_2", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p4, p5, p6))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Arrays.asList(m1, m2), 4); + + assertThat(batches).hasSize(2); + + Collection firstBatch = batches.iterator().next(); + assertThat(firstBatch).hasSize(2); + MetricData b1m1 = firstBatch.iterator().next(); + MetricData b1m2 = firstBatch.stream().skip(1).findFirst().get(); + assertThat(b1m1.getName()).isEqualTo("name_1"); + assertThat(b1m1.getDescription()).isEqualTo("desc"); + assertThat(b1m1.getUnit()).isEqualTo("1"); + assertThat(b1m1.getLongGaugeData().getPoints()).containsExactly(p1, p2, p3); + + assertThat(b1m2.getName()).isEqualTo("name_2"); + assertThat(b1m2.getDescription()).isEqualTo("desc"); + assertThat(b1m2.getUnit()).isEqualTo("1"); + assertThat(b1m2.getLongGaugeData().getPoints()).containsExactly(p4); + + Collection secondBatch = batches.stream().skip(1).findFirst().get(); + assertThat(secondBatch).hasSize(1); + MetricData b2m1 = secondBatch.iterator().next(); + assertThat(b2m1.getName()).isEqualTo("name_2"); + assertThat(b2m1.getDescription()).isEqualTo("desc"); + assertThat(b2m1.getUnit()).isEqualTo("1"); + assertThat(b2m1.getLongGaugeData().getPoints()).containsExactly(p5, p6); + } + + @Test + void batchMetrics_SplitsLongGauge_MultipleMetrics_PerfectFillThenSplit() { + // m1 fills the batch completely (remaining capacity becomes 0). + // m2 has 3 points, which forces it to split from the start of a fully-exhausted + // previous pass. + // This test case fails if there is an empty batch + LongPointData p1 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 1L); + LongPointData p2 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 2L); + LongPointData p3 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 3L); + LongPointData p4 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 4L); + LongPointData p5 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 5L); + + MetricData m1 = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_1", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p1, p2))); + MetricData m2 = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name_2", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p3, p4, p5))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Arrays.asList(m1, m2), 2); + + assertThat(batches).hasSize(3); + + // Batch 1 should contain exactly m1 (p1, p2) + Collection firstBatch = batches.iterator().next(); + assertThat(firstBatch).hasSize(1); + MetricData b1m1 = firstBatch.iterator().next(); + assertThat(b1m1.getName()).isEqualTo("name_1"); + assertThat(b1m1.getLongGaugeData().getPoints()).containsExactly(p1, p2); + + // Batch 2 should contain the first part of m2 (p3, p4) + Collection secondBatch = batches.stream().skip(1).findFirst().get(); + assertThat(secondBatch).hasSize(1); + MetricData b2m1 = secondBatch.iterator().next(); + assertThat(b2m1.getName()).isEqualTo("name_2"); + assertThat(b2m1.getLongGaugeData().getPoints()).containsExactly(p3, p4); + + // Batch 3 should contain the rest of m2 (p5) + Collection thirdBatch = batches.stream().skip(2).findFirst().get(); + assertThat(thirdBatch).hasSize(1); + MetricData b3m1 = thirdBatch.iterator().next(); + assertThat(b3m1.getName()).isEqualTo("name_2"); + assertThat(b3m1.getLongGaugeData().getPoints()).containsExactly(p5); + } + + @Test + void batchMetrics_SplitsExponentialHistogram_MultipleBatchesCompletelyFilled_SingleMetric() { + ExponentialHistogramBuckets buckets = + ImmutableExponentialHistogramBuckets.create( + /* scale= */ 20, /* offset= */ 0, /* bucketCounts= */ Collections.singletonList(1L)); + ExponentialHistogramPointData p1 = + ImmutableExponentialHistogramPointData.create( + /* scale= */ 20, + /* sum= */ 1.0, + /* zeroCount= */ 0, + /* hasMin= */ false, + /* min= */ 0.0, + /* hasMax= */ false, + /* max= */ 0.0, + /* positiveBuckets= */ buckets, + /* negativeBuckets= */ buckets, + /* startEpochNanos= */ 1, + /* epochNanos= */ 2, + /* attributes= */ Attributes.empty(), + /* exemplars= */ Collections.emptyList()); + ExponentialHistogramPointData p2 = + ImmutableExponentialHistogramPointData.create( + /* scale= */ 20, + /* sum= */ 2.0, + /* zeroCount= */ 0, + /* hasMin= */ false, + /* min= */ 0.0, + /* hasMax= */ false, + /* max= */ 0.0, + /* positiveBuckets= */ buckets, + /* negativeBuckets= */ buckets, + /* startEpochNanos= */ 1, + /* epochNanos= */ 2, + /* attributes= */ Attributes.empty(), + /* exemplars= */ Collections.emptyList()); + + MetricData metric = + ImmutableMetricData.createExponentialHistogram( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableExponentialHistogramData.create( + AggregationTemporality.CUMULATIVE, Arrays.asList(p1, p2))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 1); + + assertThat(batches).hasSize(2); + Collection firstBatch = batches.iterator().next(); + Collection secondBatch = batches.stream().skip(1).findFirst().get(); + assertThat(firstBatch).hasSize(1); + assertThat(secondBatch).hasSize(1); + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.EXPONENTIAL_HISTOGRAM); + assertThat(m1.getName()).isEqualTo("name"); + assertThat(m1.getDescription()).isEqualTo("desc"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getExponentialHistogramData().getPoints()).containsExactly(p1); + assertThat(m1.getExponentialHistogramData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + MetricData m2 = secondBatch.iterator().next(); + assertThat(m2.getType()).isEqualTo(MetricDataType.EXPONENTIAL_HISTOGRAM); + assertThat(m2.getName()).isEqualTo("name"); + assertThat(m2.getDescription()).isEqualTo("desc"); + assertThat(m2.getUnit()).isEqualTo("1"); + assertThat(m2.getExponentialHistogramData().getPoints()).containsExactly(p2); + assertThat(m2.getExponentialHistogramData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + } + + @Test + void batchMetrics_SplitsSummary_MultipleBatchesCompletelyFilled_SingleMetric() { + SummaryPointData p1 = + ImmutableSummaryPointData.create( + /* startEpochNanos= */ 1, + /* epochNanos= */ 2, + /* attributes= */ Attributes.empty(), + /* count= */ 1, + /* sum= */ 1.0, + /* percentileValues= */ Collections.singletonList( + ImmutableValueAtQuantile.create(0.5, 1.0))); + SummaryPointData p2 = + ImmutableSummaryPointData.create( + /* startEpochNanos= */ 1, + /* epochNanos= */ 2, + /* attributes= */ Attributes.empty(), + /* count= */ 1, + /* sum= */ 2.0, + /* percentileValues= */ Collections.singletonList( + ImmutableValueAtQuantile.create(0.5, 2.0))); + + MetricData metric = + ImmutableMetricData.createDoubleSummary( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableSummaryData.create(Arrays.asList(p1, p2))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 1); + + assertThat(batches).hasSize(2); + Collection firstBatch = batches.iterator().next(); + Collection secondBatch = batches.stream().skip(1).findFirst().get(); + assertThat(firstBatch).hasSize(1); + assertThat(secondBatch).hasSize(1); + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.SUMMARY); + assertThat(m1.getName()).isEqualTo("name"); + assertThat(m1.getDescription()).isEqualTo("desc"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getSummaryData().getPoints()).containsExactly(p1); + + MetricData m2 = secondBatch.iterator().next(); + assertThat(m2.getType()).isEqualTo(MetricDataType.SUMMARY); + assertThat(m2.getName()).isEqualTo("name"); + assertThat(m2.getDescription()).isEqualTo("desc"); + assertThat(m2.getUnit()).isEqualTo("1"); + assertThat(m2.getSummaryData().getPoints()).containsExactly(p2); + } + + @Test + void batchMetrics_SplitsLongGauge_MultipleBatches() { + LongPointData p1 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 1L); + LongPointData p2 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 2L); + LongPointData p3 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 3L); + LongPointData p4 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 4L); + LongPointData p5 = ImmutableLongPointData.create(1, 2, Attributes.empty(), 5L); + + MetricData metric = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableGaugeData.create(Arrays.asList(p1, p2, p3, p4, p5))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 2); + List> batchesList = new ArrayList<>(batches); + + assertThat(batchesList).hasSize(3); + Collection firstBatch = batchesList.get(0); + Collection secondBatch = batchesList.get(1); + Collection thirdBatch = batchesList.get(2); + + assertThat(firstBatch).hasSize(1); + assertThat(secondBatch).hasSize(1); + assertThat(thirdBatch).hasSize(1); + + MetricData firstBatchMetricData = firstBatch.iterator().next(); + assertThat(firstBatchMetricData.getType()).isEqualTo(MetricDataType.LONG_GAUGE); + assertThat(firstBatchMetricData.getName()).isEqualTo("name"); + assertThat(firstBatchMetricData.getDescription()).isEqualTo("desc"); + assertThat(firstBatchMetricData.getUnit()).isEqualTo("1"); + assertThat(firstBatchMetricData.getLongGaugeData().getPoints()).containsExactly(p1, p2); + + MetricData secondBatchMetricData = secondBatch.iterator().next(); + assertThat(secondBatchMetricData.getType()).isEqualTo(MetricDataType.LONG_GAUGE); + assertThat(secondBatchMetricData.getName()).isEqualTo("name"); + assertThat(secondBatchMetricData.getDescription()).isEqualTo("desc"); + assertThat(secondBatchMetricData.getUnit()).isEqualTo("1"); + assertThat(secondBatchMetricData.getLongGaugeData().getPoints()).containsExactly(p3, p4); + + MetricData thirdBatchMetricData = thirdBatch.iterator().next(); + assertThat(thirdBatchMetricData.getType()).isEqualTo(MetricDataType.LONG_GAUGE); + assertThat(thirdBatchMetricData.getName()).isEqualTo("name"); + assertThat(thirdBatchMetricData.getDescription()).isEqualTo("desc"); + assertThat(thirdBatchMetricData.getUnit()).isEqualTo("1"); + assertThat(thirdBatchMetricData.getLongGaugeData().getPoints()).containsExactly(p5); + } + + @Test + void batchMetrics_SplitsDoubleSum_MultipleBatches() { + DoublePointData p1 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 1.0); + DoublePointData p2 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 2.0); + DoublePointData p3 = ImmutableDoublePointData.create(1, 2, Attributes.empty(), 3.0); + + MetricData metric = + ImmutableMetricData.createDoubleSum( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + Arrays.asList(p1, p2, p3))); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 1); + List> batchesList = new ArrayList<>(batches); + + assertThat(batchesList).hasSize(3); + Collection firstBatch = batchesList.get(0); + Collection secondBatch = batchesList.get(1); + Collection thirdBatch = batchesList.get(2); + + assertThat(firstBatch).hasSize(1); + assertThat(secondBatch).hasSize(1); + assertThat(thirdBatch).hasSize(1); + + MetricData m1 = firstBatch.iterator().next(); + assertThat(m1.getType()).isEqualTo(MetricDataType.DOUBLE_SUM); + assertThat(m1.getName()).isEqualTo("name"); + assertThat(m1.getDescription()).isEqualTo("desc"); + assertThat(m1.getUnit()).isEqualTo("1"); + assertThat(m1.getDoubleSumData().getPoints()).containsExactly(p1); + assertThat(m1.getDoubleSumData().isMonotonic()).isTrue(); + assertThat(m1.getDoubleSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + MetricData m2 = secondBatch.iterator().next(); + assertThat(m2.getType()).isEqualTo(MetricDataType.DOUBLE_SUM); + assertThat(m2.getName()).isEqualTo("name"); + assertThat(m2.getDescription()).isEqualTo("desc"); + assertThat(m2.getUnit()).isEqualTo("1"); + assertThat(m2.getDoubleSumData().getPoints()).containsExactly(p2); + assertThat(m2.getDoubleSumData().isMonotonic()).isTrue(); + assertThat(m2.getDoubleSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + + MetricData m3 = thirdBatch.iterator().next(); + assertThat(m3.getType()).isEqualTo(MetricDataType.DOUBLE_SUM); + assertThat(m3.getName()).isEqualTo("name"); + assertThat(m3.getDescription()).isEqualTo("desc"); + assertThat(m3.getUnit()).isEqualTo("1"); + assertThat(m3.getDoubleSumData().getPoints()).containsExactly(p3); + assertThat(m3.getDoubleSumData().isMonotonic()).isTrue(); + assertThat(m3.getDoubleSumData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.CUMULATIVE); + } + + @Test + void batchMetrics_EmptyPointsInMetricData() { + MetricData metric = + ImmutableMetricData.createLongGauge( + Resource.empty(), + InstrumentationScopeInfo.empty(), + "name", + "desc", + "1", + ImmutableGaugeData.create(Collections.emptyList())); + + Collection> batches = + MetricExportBatcher.batchMetrics(Collections.singletonList(metric), 2); + assertThat(batches).hasSize(1); + assertThat(batches.iterator().next()).containsExactly(metric); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java index 6f12941f867..4b99e18e7b7 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/export/PeriodicMetricReaderTest.java @@ -9,15 +9,20 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.after; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.LongPointData; @@ -25,24 +30,28 @@ import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; import io.opentelemetry.sdk.resources.Resource; +import java.io.IOException; import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; @@ -52,8 +61,13 @@ @MockitoSettings(strictness = Strictness.LENIENT) class PeriodicMetricReaderTest { private static final List LONG_POINT_LIST = - Collections.singletonList( - ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 1234567)); + Arrays.asList( + ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 1L), + ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 2L), + ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 3L), + ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 4L), + ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 5L), + ImmutableLongPointData.create(1000, 3000, Attributes.empty(), 6L)); private static final MetricData METRIC_DATA = ImmutableMetricData.createLongSum( @@ -65,17 +79,23 @@ class PeriodicMetricReaderTest { ImmutableSumData.create( /* isMonotonic= */ true, AggregationTemporality.CUMULATIVE, LONG_POINT_LIST)); - @Mock private MetricProducer metricProducer; + @Mock private CollectionRegistration collectionRegistration; @Mock private MetricExporter metricExporter; + @RegisterExtension + LogCapturer logCapturer = + LogCapturer.create().captureForLogger(PeriodicMetricReader.class.getName()); + @BeforeEach void setup() { - when(metricProducer.collectAllMetrics()).thenReturn(Collections.singletonList(METRIC_DATA)); + when(collectionRegistration.collectAllMetrics()) + .thenReturn(Collections.singletonList(METRIC_DATA)); } @Test @SuppressWarnings({"rawtypes", "unchecked"}) void startOnlyOnce() { + ScheduledExecutorService scheduler = mock(ScheduledExecutorService.class); ScheduledFuture mock = mock(ScheduledFuture.class); @@ -87,11 +107,36 @@ void startOnlyOnce() { .setExecutor(scheduler) .build(); - reader.register(metricProducer); + reader.register(collectionRegistration); verify(scheduler, times(1)).scheduleAtFixedRate(any(), anyLong(), anyLong(), any()); } + @Test + void build_withInternalTelemetryVersion() { + WaitingMetricExporter exporter = new WaitingMetricExporter(); + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(exporter) + .setInternalTelemetryVersion(InternalTelemetryVersion.LATEST) + .build(); + + assertThat(reader).isNotNull(); + } + + @Test + void build_WithIllegalMaxExportSize() { + assertThatThrownBy( + () -> PeriodicMetricReader.builder(metricExporter).setMaxExportBatchSize(0).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxExportBatchSize must be positive"); + + assertThatThrownBy( + () -> PeriodicMetricReader.builder(metricExporter).setMaxExportBatchSize(-1).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxExportBatchSize must be positive"); + } + @Test void periodicExport() throws Exception { WaitingMetricExporter waitingMetricExporter = new WaitingMetricExporter(); @@ -100,7 +145,7 @@ void periodicExport() throws Exception { .setInterval(Duration.ofMillis(100)) .build(); - reader.register(metricProducer); + reader.register(collectionRegistration); try { assertThat(waitingMetricExporter.waitForNumberOfExports(1)) .containsExactly(Collections.singletonList(METRIC_DATA)); @@ -113,6 +158,103 @@ void periodicExport() throws Exception { } } + @Test + void periodicExport_WithMaxExportBatchSize_PartiallyFilledBatch() throws Exception { + WaitingMetricExporter waitingMetricExporter = new WaitingMetricExporter(); + PeriodicMetricReader reader = + PeriodicMetricReader.builder(waitingMetricExporter) + .setInterval(Duration.ofMillis(100)) + .setMaxExportBatchSize(4) + .build(); + + reader.register(collectionRegistration); + MetricData expectedMetricDataBatch1 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("PeriodicMetricReaderTest"), + "my metric", + "my metric description", + "us", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + LONG_POINT_LIST.subList(0, 4))); + MetricData expectedMetricDataBatch2 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("PeriodicMetricReaderTest"), + "my metric", + "my metric description", + "us", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + LONG_POINT_LIST.subList(4, 6))); + try { + assertThat(waitingMetricExporter.waitForNumberOfExports(2)) + .containsExactly( + Collections.singletonList(expectedMetricDataBatch1), + Collections.singletonList(expectedMetricDataBatch2)); + } finally { + reader.shutdown(); + } + } + + @Test + void periodicExport_WithMaxExportBatchSize_CompletelyFilledBatch() throws Exception { + WaitingMetricExporter waitingMetricExporter = new WaitingMetricExporter(); + PeriodicMetricReader reader = + PeriodicMetricReader.builder(waitingMetricExporter) + .setInterval(Duration.ofMillis(100)) + .setMaxExportBatchSize(2) + .build(); + + reader.register(collectionRegistration); + MetricData expectedMetricDataBatch1 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("PeriodicMetricReaderTest"), + "my metric", + "my metric description", + "us", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + LONG_POINT_LIST.subList(0, 2))); + MetricData expectedMetricDataBatch2 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("PeriodicMetricReaderTest"), + "my metric", + "my metric description", + "us", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + LONG_POINT_LIST.subList(2, 4))); + + MetricData expectedMetricDataBatch3 = + ImmutableMetricData.createLongSum( + Resource.empty(), + InstrumentationScopeInfo.create("PeriodicMetricReaderTest"), + "my metric", + "my metric description", + "us", + ImmutableSumData.create( + /* isMonotonic= */ true, + AggregationTemporality.CUMULATIVE, + LONG_POINT_LIST.subList(4, 6))); + try { + assertThat(waitingMetricExporter.waitForNumberOfExports(3)) + .containsExactly( + Collections.singletonList(expectedMetricDataBatch1), + Collections.singletonList(expectedMetricDataBatch2), + Collections.singletonList(expectedMetricDataBatch3)); + } finally { + reader.shutdown(); + } + } + @Test void periodicExport_NoMetricsSkipsExport() { WaitingMetricExporter waitingMetricExporter = new WaitingMetricExporter(); @@ -120,12 +262,12 @@ void periodicExport_NoMetricsSkipsExport() { PeriodicMetricReader.builder(waitingMetricExporter) .setInterval(Duration.ofMillis(100)) .build(); - when(metricProducer.collectAllMetrics()).thenReturn(Collections.emptyList()); - reader.register(metricProducer); + when(collectionRegistration.collectAllMetrics()).thenReturn(Collections.emptyList()); + reader.register(collectionRegistration); try { assertThat(reader.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); - verify(metricProducer).collectAllMetrics(); + verify(collectionRegistration).collectAllMetrics(); assertThat(waitingMetricExporter.exportTimes.size()).isEqualTo(0); } finally { reader.shutdown(); @@ -140,7 +282,7 @@ void flush() throws Exception { .setInterval(Duration.ofNanos(Long.MAX_VALUE)) .build(); - reader.register(metricProducer); + reader.register(collectionRegistration); assertThat(reader.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); try { @@ -151,17 +293,48 @@ void flush() throws Exception { } } + @Test + @SuppressLogger(PeriodicMetricReader.class) + void forceflush_callsFlush() { + MetricExporter metricExporter = mock(MetricExporter.class); + when(metricExporter.export(any())) + .thenReturn(CompletableResultCode.ofSuccess()) + .thenReturn(CompletableResultCode.ofSuccess()) + .thenThrow(new RuntimeException("Export Failed!")); + when(metricExporter.flush()) + .thenReturn(CompletableResultCode.ofSuccess()) + .thenReturn(CompletableResultCode.ofFailure()) + .thenReturn(CompletableResultCode.ofSuccess()); + when(metricExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(metricExporter) + .setInterval(Duration.ofNanos(Long.MAX_VALUE)) + .build(); + + try { + reader.register(collectionRegistration); + assertThat(reader.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(reader.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + assertThat(reader.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()).isFalse(); + } finally { + reader.shutdown(); + } + verify(metricExporter, times(3)).flush(); + } + @Test @Timeout(2) @SuppressLogger(PeriodicMetricReader.class) public void intervalExport_exporterThrowsException() throws Exception { - WaitingMetricExporter waitingMetricExporter = new WaitingMetricExporter(/* shouldThrow=*/ true); + WaitingMetricExporter waitingMetricExporter = + new WaitingMetricExporter(/* shouldThrow= */ true); PeriodicMetricReader reader = PeriodicMetricReader.builder(waitingMetricExporter) .setInterval(Duration.ofMillis(100)) .build(); - reader.register(metricProducer); + reader.register(collectionRegistration); try { assertThat(waitingMetricExporter.waitForNumberOfExports(2)) .containsExactly( @@ -172,14 +345,13 @@ public void intervalExport_exporterThrowsException() throws Exception { } @Test - void oneLastExportAfterShutdown() throws Exception { + void shutdown_ExportsOneLastTime() throws Exception { WaitingMetricExporter waitingMetricExporter = new WaitingMetricExporter(); PeriodicMetricReader reader = PeriodicMetricReader.builder(waitingMetricExporter) - .setInterval(Duration.ofSeconds(100)) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) .build(); - reader.register(metricProducer); - // Assume that this will be called in less than 100 seconds. + reader.register(collectionRegistration); reader.shutdown(); // This export was called during shutdown. @@ -189,15 +361,107 @@ void oneLastExportAfterShutdown() throws Exception { assertThat(waitingMetricExporter.hasShutdown.get()).isTrue(); } + @Test + void close_CallsShutdown() throws IOException { + PeriodicMetricReader reader = + spy( + PeriodicMetricReader.builder(new WaitingMetricExporter()) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .build()); + reader.register(collectionRegistration); + reader.close(); + + verify(reader, times(1)).shutdown(); + } + + @Test + @Timeout(10) + void shutdown_whileExportInFlight_waitsThenPerformsFinalExport() throws Exception { + CompletableResultCode inflightExportResult = new CompletableResultCode(); + CountDownLatch exportStarted = new CountDownLatch(1); + AtomicInteger exportCount = new AtomicInteger(); + AtomicBoolean shutdownCalledWhileExportPending = new AtomicBoolean(); + + MetricExporter blockingExporter = + new MetricExporter() { + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + + @Override + public CompletableResultCode export(Collection metrics) { + if (exportCount.incrementAndGet() == 1) { + exportStarted.countDown(); + return inflightExportResult; + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + if (!inflightExportResult.isDone()) { + shutdownCalledWhileExportPending.set(true); + } + return CompletableResultCode.ofSuccess(); + } + }; + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(blockingExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .build(); + reader.register(collectionRegistration); + + // Trigger an export that blocks + CompletableResultCode flushResult = reader.forceFlush(); + assertThat(exportStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + // Shutdown in background β€” should block waiting for in-flight export + CountDownLatch shutdownDone = new CountDownLatch(1); + Thread shutdownThread = + new Thread(() -> { + reader.shutdown(); + shutdownDone.countDown(); + }); + shutdownThread.setDaemon(true); + shutdownThread.start(); + + // Give shutdown() time to reach the flushInProgress.join() wait. + // Even if this executes before shutdown enters the wait, the assertions below + // still + // validate correctness β€” they just won't exercise the concurrent case. + Thread.sleep(200); + + // Release the in-flight export + inflightExportResult.succeed(); + + // Shutdown completes + assertThat(shutdownDone.await(5, TimeUnit.SECONDS)).isTrue(); + + // In-flight export succeeded + flushResult.join(5, TimeUnit.SECONDS); + assertThat(flushResult.isSuccess()).isTrue(); + // Final shutdown export also ran (in-flight + final = 2) + assertThat(exportCount.get()).isEqualTo(2); + // Exporter.shutdown() was not called while the in-flight export was still + // pending + assertThat(shutdownCalledWhileExportPending.get()).isFalse(); + } + @Test @SuppressWarnings("PreferJavaTimeOverload") // Testing the overload void invalidConfig() { assertThatThrownBy(() -> PeriodicMetricReader.builder(metricExporter).setInterval(1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("unit"); - assertThatThrownBy( - () -> - PeriodicMetricReader.builder(metricExporter).setInterval(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + PeriodicMetricReader.builder(metricExporter).setInterval(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("interval must be positive"); assertThatThrownBy(() -> PeriodicMetricReader.builder(metricExporter).setInterval(null)) @@ -208,18 +472,373 @@ void invalidConfig() { .hasMessage("executor"); } + @Test + void periodicExport_SequentialBatches() throws Exception { + MetricExporter mockExporter = mock(MetricExporter.class); + when(mockExporter.getAggregationTemporality(any())) + .thenReturn(AggregationTemporality.CUMULATIVE); + when(mockExporter.flush()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + CompletableResultCode batch1Result = new CompletableResultCode(); + CompletableResultCode batch2Result = CompletableResultCode.ofSuccess(); + + // Configure mock to return pending for 1st call, success for 2nd + when(mockExporter.export(any())).thenReturn(batch1Result).thenReturn(batch2Result); + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(mockExporter) + .setInterval( + Duration.ofSeconds(Integer.MAX_VALUE)) // Long interval to prevent auto-trigger + .setMaxExportBatchSize(3) + .build(); + // Setup metrics that will result in 2 batches (we have 6 points in + // LONG_POINT_LIST) + when(collectionRegistration.collectAllMetrics()) + .thenReturn(Collections.singletonList(METRIC_DATA)); + reader.register(collectionRegistration); + + // Trigger manual flush + CompletableResultCode flushResult = reader.forceFlush(); + // Batch 1 is exported and stuck waiting on batch1Result. Batch 2 must not start yet. + verify(mockExporter, timeout(2000).times(1)).export(any()); + verify(mockExporter, after(100).times(1)).export(any()); + // Complete batch 1; batch 2 should now be exported. + batch1Result.succeed(); + verify(mockExporter, timeout(2000).times(2)).export(any()); + // Ensure the flush operation completes successfully + assertThat(flushResult.join(5, TimeUnit.SECONDS).isSuccess()).isTrue(); + reader.shutdown(); + } + + @Test + @SuppressLogger(PeriodicMetricReader.class) + void periodicExport_SequentialBatches_PartialFailure() throws Exception { + MetricExporter mockExporter = mock(MetricExporter.class); + when(mockExporter.getAggregationTemporality(any())) + .thenReturn(AggregationTemporality.CUMULATIVE); + when(mockExporter.flush()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + CompletableResultCode batch1Result = new CompletableResultCode(); + CompletableResultCode batch2Result = new CompletableResultCode(); + CompletableResultCode batch3Result = new CompletableResultCode(); + + when(mockExporter.export(any())) + .thenReturn(batch1Result) + .thenReturn(batch2Result) + .thenReturn(batch3Result); + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(mockExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .setMaxExportBatchSize(2) // 6 points / 2 = 3 batches + .build(); + + when(collectionRegistration.collectAllMetrics()) + .thenReturn(Collections.singletonList(METRIC_DATA)); + reader.register(collectionRegistration); + + CompletableResultCode flushResult = reader.forceFlush(); + + verify(mockExporter, timeout(2000).times(1)).export(any()); + verify(mockExporter, after(100).times(1)).export(any()); + + batch1Result.succeed(); + verify(mockExporter, timeout(2000).times(2)).export(any()); + verify(mockExporter, after(100).times(2)).export(any()); + + batch2Result.fail(); + verify(mockExporter, timeout(2000).times(3)).export(any()); + + batch3Result.succeed(); + + // forceFlush fails if any batch failed. + flushResult.join(5, TimeUnit.SECONDS); + assertThat(flushResult.isSuccess()).isFalse(); + + logCapturer.assertContains("Exporter failed"); + + reader.shutdown(); + } + + @Test + void periodicExport_SequentialBatches_PurelySynchronous() throws Exception { + MetricExporter mockExporter = mock(MetricExporter.class); + when(mockExporter.getAggregationTemporality(any())) + .thenReturn(AggregationTemporality.CUMULATIVE); + when(mockExporter.flush()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + when(mockExporter.export(any())) + .thenReturn(CompletableResultCode.ofSuccess()) + .thenReturn(CompletableResultCode.ofSuccess()) + .thenReturn(CompletableResultCode.ofSuccess()); + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(mockExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .setMaxExportBatchSize(2) // 6 points / 2 = 3 batches + .build(); + + when(collectionRegistration.collectAllMetrics()) + .thenReturn(Collections.singletonList(METRIC_DATA)); + reader.register(collectionRegistration); + + CompletableResultCode flushResult = reader.forceFlush(); + + // All 3 batches are exported. + verify(mockExporter, timeout(2000).times(3)).export(any()); + + assertThat(flushResult.join(5, TimeUnit.SECONDS).isSuccess()).isTrue(); + + reader.shutdown(); + } + + @Test + void periodicExport_SequentialBatches_PurelyAsynchronous() throws Exception { + MetricExporter mockExporter = mock(MetricExporter.class); + when(mockExporter.getAggregationTemporality(any())) + .thenReturn(AggregationTemporality.CUMULATIVE); + when(mockExporter.flush()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + CompletableResultCode batch1Result = new CompletableResultCode(); + CompletableResultCode batch2Result = new CompletableResultCode(); + CompletableResultCode batch3Result = new CompletableResultCode(); + + when(mockExporter.export(any())) + .thenReturn(batch1Result) + .thenReturn(batch2Result) + .thenReturn(batch3Result); + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(mockExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .setMaxExportBatchSize(2) // 6 points / 2 = 3 batches + .build(); + + when(collectionRegistration.collectAllMetrics()) + .thenReturn(Collections.singletonList(METRIC_DATA)); + reader.register(collectionRegistration); + + CompletableResultCode flushResult = reader.forceFlush(); + + verify(mockExporter, timeout(2000).times(1)).export(any()); + verify(mockExporter, after(100).times(1)).export(any()); + + batch1Result.succeed(); + verify(mockExporter, timeout(2000).times(2)).export(any()); + verify(mockExporter, after(100).times(2)).export(any()); + + batch2Result.succeed(); + verify(mockExporter, timeout(2000).times(3)).export(any()); + + batch3Result.succeed(); + + assertThat(flushResult.join(5, TimeUnit.SECONDS).isSuccess()).isTrue(); + logCapturer.assertDoesNotContain("Exporter failed"); + + reader.shutdown(); + } + + @Test + @Timeout(10) + void forceFlush_whileExportInFlight_queuesBehindIt() throws Exception { + CompletableResultCode inflightExportResult = new CompletableResultCode(); + CountDownLatch exportStarted = new CountDownLatch(1); + AtomicInteger exportCount = new AtomicInteger(); + + MetricExporter blockingExporter = + new MetricExporter() { + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + + @Override + public CompletableResultCode export(Collection metrics) { + if (exportCount.incrementAndGet() == 1) { + exportStarted.countDown(); + return inflightExportResult; + } + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + }; + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(blockingExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .build(); + reader.register(collectionRegistration); + + // Start a flush that blocks + CompletableResultCode firstFlush = reader.forceFlush(); + assertThat(exportStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + // Second forceFlush while first is in flight queues behind it and does not fail. + CompletableResultCode secondFlush = reader.forceFlush(); + assertThat(secondFlush.isDone()).isFalse(); + + // Release the in-flight export; both flushes complete successfully and both exports ran. + inflightExportResult.succeed(); + firstFlush.join(5, TimeUnit.SECONDS); + secondFlush.join(5, TimeUnit.SECONDS); + assertThat(firstFlush.isSuccess()).isTrue(); + assertThat(secondFlush.isSuccess()).isTrue(); + assertThat(exportCount.get()).isEqualTo(2); + + reader.shutdown(); + } + + @Test + void setExporterTimeout_negativeThrows() { + assertThatThrownBy(() -> + PeriodicMetricReader.builder(metricExporter).setExporterTimeout(Duration.ofSeconds(-1))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("timeout must be non-negative"); + } + + @Test + void setExporterTimeout_nullUnitThrows() { + assertThatThrownBy( + () -> PeriodicMetricReader.builder(metricExporter).setExporterTimeout(1L, null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("unit"); + } + + @Test + void setExporterTimeout_nullDurationThrows() { + assertThatThrownBy( + () -> PeriodicMetricReader.builder(metricExporter).setExporterTimeout((Duration) null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("timeout"); + } + + @Test + @SuppressLogger(PeriodicMetricReader.class) + void exporterTimeout_slowExporterReportedAsFailed() throws Exception { + CompletableResultCode neverCompletes = new CompletableResultCode(); + CountDownLatch exportStarted = new CountDownLatch(1); + MetricExporter slowExporter = + new MetricExporter() { + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + + @Override + public CompletableResultCode export(Collection metrics) { + exportStarted.countDown(); + return neverCompletes; + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + }; + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(slowExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .setExporterTimeout(Duration.ofMillis(50)) + .build(); + reader.register(collectionRegistration); + + CompletableResultCode flush = reader.forceFlush(); + assertThat(exportStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + flush.join(5, TimeUnit.SECONDS); + assertThat(flush.isSuccess()).isFalse(); + logCapturer.assertContains("Exporter timed out"); + + neverCompletes.succeed(); + reader.shutdown(); + } + + @Test + @SuppressLogger(PeriodicMetricReader.class) + void exporterTimeout_appliesPerBatch() throws Exception { + // Each batch's export takes ~40ms; per-batch timeout is 200ms; 3 batches total elapsed ~120ms + // which would exceed a cycle-level timeout of 100ms but stays within a per-batch timeout. + CountDownLatch allBatchesExported = new CountDownLatch(3); + MetricExporter perBatchSlowExporter = + new MetricExporter() { + @Override + public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { + return AggregationTemporality.CUMULATIVE; + } + + @Override + public CompletableResultCode export(Collection metrics) { + try { + Thread.sleep(40); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + allBatchesExported.countDown(); + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + }; + + PeriodicMetricReader reader = + PeriodicMetricReader.builder(perBatchSlowExporter) + .setInterval(Duration.ofSeconds(Integer.MAX_VALUE)) + .setMaxExportBatchSize(2) // 6 points / 2 = 3 batches + .setExporterTimeout(Duration.ofMillis(200)) + .build(); + reader.register(collectionRegistration); + + CompletableResultCode flush = reader.forceFlush(); + flush.join(5, TimeUnit.SECONDS); + + assertThat(allBatchesExported.await(0, TimeUnit.MILLISECONDS)).isTrue(); + assertThat(flush.isSuccess()).isTrue(); + logCapturer.assertDoesNotContain("Exporter timed out"); + + reader.shutdown(); + } + @Test void stringRepresentation() { when(metricExporter.toString()).thenReturn("MockMetricExporter{}"); assertThat( PeriodicMetricReader.builder(metricExporter) .setInterval(Duration.ofSeconds(1)) + .setMaxExportBatchSize(200) .build() .toString()) .isEqualTo( "PeriodicMetricReader{" + "exporter=MockMetricExporter{}, " - + "intervalNanos=1000000000" + + "intervalNanos=1000000000, " + + "maxExportBatchSize=200" + "}"); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingCircularBufferCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingCircularBufferCounterTest.java new file mode 100644 index 00000000000..d96d85585f0 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingCircularBufferCounterTest.java @@ -0,0 +1,80 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class AdaptingCircularBufferCounterTest { + + @Test + void returnsZeroOutsidePopulatedRange() { + AdaptingCircularBufferCounter counter = newCounter(10); + assertThat(counter.get(0)).isEqualTo(0); + assertThat(counter.get(100)).isEqualTo(0); + counter.increment(2, 1); + counter.increment(99, 1); + assertThat(counter.get(0)).isEqualTo(0); + assertThat(counter.get(100)).isEqualTo(0); + } + + @Test + void expandLower() { + AdaptingCircularBufferCounter counter = newCounter(160); + assertThat(counter.increment(10, 1)).isTrue(); + // Add BEFORE the initial see (array index 0) and make sure we wrap around the datastructure. + assertThat(counter.increment(0, 1)).isTrue(); + assertThat(counter.get(10)).isEqualTo(1); + assertThat(counter.get(0)).isEqualTo(1); + assertThat(counter.getIndexStart()).as("index start").isEqualTo(0); + assertThat(counter.getIndexEnd()).as("index end").isEqualTo(10); + // Add AFTER initial entry and just push back end. + assertThat(counter.increment(20, 1)).isTrue(); + assertThat(counter.get(20)).isEqualTo(1); + assertThat(counter.get(10)).isEqualTo(1); + assertThat(counter.get(0)).isEqualTo(1); + assertThat(counter.getIndexStart()).isEqualTo(0); + assertThat(counter.getIndexEnd()).isEqualTo(20); + } + + @Test + void shouldFailAtLimit() { + AdaptingCircularBufferCounter counter = newCounter(160); + assertThat(counter.increment(0, 1)).isTrue(); + assertThat(counter.increment(120, 1)).isTrue(); + // Check state + assertThat(counter.getIndexStart()).as("index start").isEqualTo(0); + assertThat(counter.getIndexEnd()).as("index start").isEqualTo(120); + assertThat(counter.get(0)).as("counter[0]").isEqualTo(1); + assertThat(counter.get(120)).as("counter[120]").isEqualTo(1); + // Adding over the maximum # of buckets + assertThat(counter.increment(3000, 1)).isFalse(); + } + + @Test + void shouldCopyCounters() { + AdaptingCircularBufferCounter counter = newCounter(2); + assertThat(counter.increment(2, 1)).isTrue(); + assertThat(counter.increment(1, 1)).isTrue(); + assertThat(counter.increment(3, 1)).isFalse(); + + AdaptingCircularBufferCounter copy = new AdaptingCircularBufferCounter(counter); + assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); + assertThat(copy.get(2)).as("copy[2]").isEqualTo(1); + assertThat(copy.getMaxSize()).isEqualTo(counter.getMaxSize()); + assertThat(copy.getIndexStart()).isEqualTo(counter.getIndexStart()); + assertThat(copy.getIndexEnd()).isEqualTo(counter.getIndexEnd()); + // Mutate copy and make sure original is unchanged. + assertThat(copy.increment(2, 1)).isTrue(); + assertThat(copy.get(2)).as("copy[2]").isEqualTo(2); + assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); + } + + private static AdaptingCircularBufferCounter newCounter(int maxBuckets) { + return new AdaptingCircularBufferCounter(maxBuckets); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingIntegerArrayTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingIntegerArrayTest.java similarity index 97% rename from sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingIntegerArrayTest.java rename to sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingIntegerArrayTest.java index f168f2abaae..f6609544bb8 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AdaptingIntegerArrayTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AdaptingIntegerArrayTest.java @@ -3,7 +3,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -package io.opentelemetry.sdk.metrics.internal.state; +package io.opentelemetry.sdk.metrics.internal.aggregator; import static org.assertj.core.api.Assertions.assertThat; diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtilTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtilTest.java index 99f0dfc4db7..1f9c2607d6f 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtilTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregationUtilTest.java @@ -9,7 +9,6 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.internal.view.ExponentialHistogramAggregation; import org.junit.jupiter.api.Test; class AggregationUtilTest { @@ -20,9 +19,11 @@ void forName() { assertThat(AggregationUtil.forName("last_value")).isEqualTo(Aggregation.lastValue()); assertThat(AggregationUtil.forName("explicit_bucket_histogram")) .isEqualTo(Aggregation.explicitBucketHistogram()); + assertThat(AggregationUtil.forName("EXplicit_BUCKet_HISTOGRAM")) + .isEqualTo(Aggregation.explicitBucketHistogram()); assertThat(AggregationUtil.forName("drop")).isEqualTo(Aggregation.drop()); - assertThat(AggregationUtil.forName("exponential_histogram")) - .isEqualTo(ExponentialHistogramAggregation.getDefault()); + assertThat(AggregationUtil.forName("base2_exponential_bucket_histogram")) + .isEqualTo(Aggregation.base2ExponentialBucketHistogram()); assertThatThrownBy(() -> AggregationUtil.forName("foo")) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unrecognized aggregation name foo"); @@ -37,8 +38,8 @@ void aggregationName() { assertThat(AggregationUtil.aggregationName(Aggregation.drop())).isEqualTo("drop"); assertThat(AggregationUtil.aggregationName(Aggregation.explicitBucketHistogram())) .isEqualTo("explicit_bucket_histogram"); - assertThat(AggregationUtil.aggregationName(ExponentialHistogramAggregation.getDefault())) - .isEqualTo("exponential_histogram"); + assertThat(AggregationUtil.aggregationName(Aggregation.base2ExponentialBucketHistogram())) + .isEqualTo("base2_exponential_bucket_histogram"); assertThatThrownBy(() -> AggregationUtil.aggregationName(new Aggregation() {})) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Unrecognized aggregation"); diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandleTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandleTest.java index 79832c9f408..778aa5fd375 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandleTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/AggregatorHandleTest.java @@ -16,10 +16,14 @@ import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.ExemplarData; import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; import java.util.Collections; import java.util.List; +import java.util.Objects; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nullable; @@ -32,88 +36,40 @@ @ExtendWith(MockitoExtension.class) class AggregatorHandleTest { - @Mock ExemplarReservoir doubleReservoir; - @Mock ExemplarReservoir longReservoir; + @Mock DoubleExemplarReservoir doubleReservoir; + @Mock LongExemplarReservoir longReservoir; @Test - void acquireMapped() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(doubleReservoir); - assertThat(testAggregator.acquire()).isTrue(); - testAggregator.release(); - assertThat(testAggregator.acquire()).isTrue(); - assertThat(testAggregator.acquire()).isTrue(); - testAggregator.release(); - assertThat(testAggregator.acquire()).isTrue(); - testAggregator.release(); - testAggregator.release(); - } - - @Test - void tryUnmap_AcquiredHandler() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(doubleReservoir); - assertThat(testAggregator.acquire()).isTrue(); - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - // The aggregator is by default acquired, so need an extra release. - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - assertThat(testAggregator.tryUnmap()).isTrue(); - } - - @Test - void tryUnmap_AcquiredHandler_MultipleTimes() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(doubleReservoir); - assertThat(testAggregator.acquire()).isTrue(); - assertThat(testAggregator.acquire()).isTrue(); - assertThat(testAggregator.acquire()).isTrue(); - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - assertThat(testAggregator.acquire()).isTrue(); - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - // The aggregator is by default acquired, so need an extra release. - assertThat(testAggregator.tryUnmap()).isFalse(); - testAggregator.release(); - assertThat(testAggregator.tryUnmap()).isTrue(); - } - - @Test - void bind_ThenUnmap_ThenTryToBind() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(doubleReservoir); - testAggregator.release(); - assertThat(testAggregator.tryUnmap()).isTrue(); - assertThat(testAggregator.acquire()).isFalse(); - testAggregator.release(); + void testCreationTimeEpochNanos() { + long creationEpochNanos = 12345L; + TestDoubleAggregatorHandle handle = + new TestDoubleAggregatorHandle(doubleReservoir, creationEpochNanos); + assertThat(handle.getCreationEpochNanos()).isEqualTo(creationEpochNanos); } @Test void testRecordings() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(doubleReservoir); + TestLongAggregatorHandle testLongAggregator = new TestLongAggregatorHandle(longReservoir); - testAggregator.recordLong(22); - assertThat(testAggregator.recordedLong.get()).isEqualTo(22); - assertThat(testAggregator.recordedDouble.get()).isEqualTo(0); + testLongAggregator.recordLong(22, Attributes.empty(), Context.current()); + assertThat(testLongAggregator.recordedLong.get()).isEqualTo(22); - testAggregator.accumulateThenReset(Attributes.empty()); - assertThat(testAggregator.recordedLong.get()).isEqualTo(0); - assertThat(testAggregator.recordedDouble.get()).isEqualTo(0); + testLongAggregator.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(testLongAggregator.recordedLong.get()).isEqualTo(0); - testAggregator.recordDouble(33.55); - assertThat(testAggregator.recordedLong.get()).isEqualTo(0); - assertThat(testAggregator.recordedDouble.get()).isEqualTo(33.55); + TestDoubleAggregatorHandle testDoubleAggregator = + new TestDoubleAggregatorHandle(doubleReservoir); - testAggregator.accumulateThenReset(Attributes.empty()); - assertThat(testAggregator.recordedLong.get()).isEqualTo(0); - assertThat(testAggregator.recordedDouble.get()).isEqualTo(0); + testDoubleAggregator.recordDouble(33.55, Attributes.empty(), Context.current()); + assertThat(testDoubleAggregator.recordedDouble.get()).isEqualTo(33.55); + + testDoubleAggregator.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(testDoubleAggregator.recordedDouble.get()).isEqualTo(0); } @Test void testOfferMeasurementLongToExemplar() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(longReservoir); + TestLongAggregatorHandle testAggregator = new TestLongAggregatorHandle(longReservoir); Attributes attributes = Attributes.builder().put("test", "value").build(); Context context = Context.root(); testAggregator.recordLong(1L, attributes, context); @@ -122,7 +78,7 @@ void testOfferMeasurementLongToExemplar() { @Test void testOfferMeasurementDoubleToExemplar() { - TestAggregatorHandle testAggregator = new TestAggregatorHandle<>(doubleReservoir); + TestDoubleAggregatorHandle testAggregator = new TestDoubleAggregatorHandle(doubleReservoir); Attributes attributes = Attributes.builder().put("test", "value").build(); Context context = Context.root(); testAggregator.recordDouble(1.0d, attributes, context); @@ -131,8 +87,7 @@ void testOfferMeasurementDoubleToExemplar() { @Test void testGenerateExemplarsOnCollect() { - TestAggregatorHandle testAggregator = - new TestAggregatorHandle<>(doubleReservoir); + TestDoubleAggregatorHandle testAggregator = new TestDoubleAggregatorHandle(doubleReservoir); Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData result = ImmutableDoubleExemplarData.create( @@ -146,25 +101,78 @@ void testGenerateExemplarsOnCollect() { 1); // We need to first record a value so that collect and reset does something. testAggregator.recordDouble(1.0, Attributes.empty(), Context.root()); - Mockito.when(doubleReservoir.collectAndReset(attributes)) + Mockito.when(doubleReservoir.collectAndResetDoubles(attributes)) .thenReturn(Collections.singletonList(result)); - testAggregator.accumulateThenReset(attributes); - assertThat(testAggregator.recordedExemplars.get()).containsExactly(result); + testAggregator.aggregateThenMaybeReset(0, 1, attributes, /* reset= */ true); + assertThat(testAggregator.recordedExemplars.get()).isEqualTo(Collections.singletonList(result)); } - private static class TestAggregatorHandle - extends AggregatorHandle { + private static class TestDoubleAggregatorHandle extends TestAggregatorHandle { + + TestDoubleAggregatorHandle(DoubleExemplarReservoir reservoir) { + super(reservoir, null, /* isDoubleType= */ true, /* creationEpochNanos= */ 0); + } + + TestDoubleAggregatorHandle(DoubleExemplarReservoir reservoir, long creationEpochNanos) { + super(reservoir, null, /* isDoubleType= */ true, creationEpochNanos); + } + } + + private static class TestLongAggregatorHandle extends TestAggregatorHandle { + + TestLongAggregatorHandle(LongExemplarReservoir reservoir) { + super(null, reservoir, /* isDoubleType= */ false, /* creationEpochNanos= */ 0); + } + } + + private abstract static class TestAggregatorHandle extends AggregatorHandle { final AtomicLong recordedLong = new AtomicLong(); final AtomicDouble recordedDouble = new AtomicDouble(); - final AtomicReference> recordedExemplars = new AtomicReference<>(); + final AtomicReference> recordedExemplars = new AtomicReference<>(); + + TestAggregatorHandle( + @Nullable DoubleExemplarReservoir doubleReservoir, + @Nullable LongExemplarReservoir longReservoir, + boolean isDoubleType, + long creationEpochNanos) { + super( + creationEpochNanos, + new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return Objects.requireNonNull(doubleReservoir); + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + return Objects.requireNonNull(longReservoir); + } + }, + isDoubleType); + } - TestAggregatorHandle(ExemplarReservoir reservoir) { - super(reservoir); + @Nullable + @Override + protected PointData doAggregateThenMaybeResetDoubles( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { + recordedLong.set(0); + recordedDouble.set(0); + recordedExemplars.set(exemplars); + return null; } @Nullable @Override - protected Void doAccumulateThenReset(List exemplars) { + protected PointData doAggregateThenMaybeResetLongs( + long startEpochNanos, + long epochNanos, + Attributes attributes, + List exemplars, + boolean reset) { recordedLong.set(0); recordedDouble.set(0); recordedExemplars.set(exemplars); diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/Base2ExponentialHistogramIndexerTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/Base2ExponentialHistogramIndexerTest.java new file mode 100644 index 00000000000..1aaef8f6387 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/Base2ExponentialHistogramIndexerTest.java @@ -0,0 +1,226 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Arrays; +import java.util.function.Consumer; +import org.assertj.core.api.AssertionsForClassTypes; +import org.junit.jupiter.api.Test; + +class Base2ExponentialHistogramIndexerTest { + + @Test + void get_Caches() { + assertThat(Base2ExponentialHistogramIndexer.get(1)) + .isSameAs(Base2ExponentialHistogramIndexer.get(1)); + assertThat(Base2ExponentialHistogramIndexer.get(2)) + .isSameAs(Base2ExponentialHistogramIndexer.get(2)); + assertThat(Base2ExponentialHistogramIndexer.get(1)) + .isNotSameAs(Base2ExponentialHistogramIndexer.get(2)); + } + + @Test + void computeIndex_ScaleOne() { + Base2ExponentialHistogramIndexer indexer = Base2ExponentialHistogramIndexer.get(1); + + Arrays.asList( + // Near +Inf + of(Double.MAX_VALUE, 2047), + of(0x1p1023, 2045), + of(0x1.1p1023, 2046), + of(0x1p1022, 2043), + of(0x1.1p1022, 2044), + // Near 0 + of(0x1p-1022, -2045), + of(0x1.1p-1022, -2044), + of(0x1p-1021, -2043), + of(0x1.1p-1021, -2042), + of(Double.MIN_NORMAL, -2045), + of(Double.MIN_VALUE, -2149), + // Near 1 + of(15d, 7), + of(9d, 6), + of(7d, 5), + of(5d, 4), + of(3d, 3), + of(2.5d, 2), + of(1.5d, 1), + of(1.2d, 0), + of(1d, -1), + of(0.75d, -1), + of(0.55d, -2), + of(0.45d, -3)) + .forEach(test(indexer)); + } + + @Test + void computeIndex_ScaleZero() { + Base2ExponentialHistogramIndexer indexer = Base2ExponentialHistogramIndexer.get(0); + + Arrays.asList( + // Near +Inf + of(Double.MAX_VALUE, Double.MAX_EXPONENT), + of(0x1p1023, 1022), + of(0x1.1p1023, 1023), + of(0x1p1022, 1021), + of(0x1.1p1022, 1022), + // Near 0 + of(0x1p-1022, -1023), + of(0x1.1p-1022, -1022), + of(0x1p-1021, -1022), + of(0x1.1p-1021, -1021), + of(Double.MIN_NORMAL, -1023), + of(Double.MIN_VALUE, -1075), + // Near 1 + of(4, 1), + of(3, 1), + of(2, 0), + of(1.5, 0), + of(1, -1), + of(0.75, -1), + of(0.51, -1), + of(0.5, -2), + of(0.26, -2), + of(0.25, -3), + of(0.126, -3), + of(0.125, -4)) + .forEach(test(indexer)); + } + + @Test + void computeIndex_ScaleNegOne() { + Base2ExponentialHistogramIndexer indexer = Base2ExponentialHistogramIndexer.get(-1); + + Arrays.asList( + of(17d, 2), + of(16d, 1), + of(15d, 1), + of(9d, 1), + of(8d, 1), + of(5d, 1), + of(4d, 0), + of(3d, 0), + of(2d, 0), + of(1.5d, 0), + of(1d, -1), + of(0.75d, -1), + of(0.5d, -1), + of(0.25d, -2), + of(0.20d, -2), + of(0.13d, -2), + of(0.125d, -2), + of(0.10d, -2), + of(0.0625d, -3), + of(0.06d, -3)) + .forEach(test(indexer)); + } + + @Test + void valueToIndex_ScaleNegFour() { + Base2ExponentialHistogramIndexer indexer = Base2ExponentialHistogramIndexer.get(-4); + + Arrays.asList( + of(0x1p0, -1), + of(0x10p0, 0), + of(0x100p0, 0), + of(0x1000p0, 0), + of(0x10000p0, 0), // Base == 2**16 + of(0x100000p0, 1), + of(0x1000000p0, 1), + of(0x10000000p0, 1), + of(0x100000000p0, 1), // == 2**32 + of(0x1000000000p0, 2), + of(0x10000000000p0, 2), + of(0x100000000000p0, 2), + of(0x1000000000000p0, 2), // 2**48 + of(0x10000000000000p0, 3), + of(0x100000000000000p0, 3), + of(0x1000000000000000p0, 3), + of(0x10000000000000000p0, 3), // 2**64 + of(0x100000000000000000p0, 4), + of(0x1000000000000000000p0, 4), + of(0x10000000000000000000p0, 4), + of(0x100000000000000000000p0, 4), + of(0x1000000000000000000000p0, 5), + of(1 / 0x1p0, -1), + of(1 / 0x10p0, -1), + of(1 / 0x100p0, -1), + of(1 / 0x1000p0, -1), + of(1 / 0x10000p0, -2), // 2**-16 + of(1 / 0x100000p0, -2), + of(1 / 0x1000000p0, -2), + of(1 / 0x10000000p0, -2), + of(1 / 0x100000000p0, -3), // 2**-32 + of(1 / 0x1000000000p0, -3), + of(1 / 0x10000000000p0, -3), + of(1 / 0x100000000000p0, -3), + of(1 / 0x1000000000000p0, -4), // 2**-48 + of(1 / 0x10000000000000p0, -4), + of(1 / 0x100000000000000p0, -4), + of(1 / 0x1000000000000000p0, -4), + of(1 / 0x10000000000000000p0, -5), // 2**-64 + of(1 / 0x100000000000000000p0, -5), + + // Max values + of(0x1.FFFFFFFFFFFFFp1023, 63), + of(0x1p1023, 63), + of(0x1p1019, 63), + of(0x1p1009, 63), + of(0x1p1008, 62), + of(0x1p1007, 62), + of(0x1p1000, 62), + of(0x1p0993, 62), + of(0x1p0992, 61), + of(0x1p0991, 61), + + // Min and subnormal values + of(0x1p-1074, -68), + of(0x1p-1073, -68), + of(0x1p-1072, -68), + of(0x1p-1057, -67), + of(0x1p-1056, -67), + of(0x1p-1041, -66), + of(0x1p-1040, -66), + of(0x1p-1025, -65), + of(0x1p-1024, -65), + of(0x1p-1023, -64), + of(0x1p-1022, -64), + of(0x1p-1009, -64), + of(0x1p-1008, -64), + of(0x1p-1007, -63), + of(0x1p-0993, -63), + of(0x1p-0992, -63), + of(0x1p-0991, -62), + of(0x1p-0977, -62), + of(0x1p-0976, -62), + of(0x1p-0975, -61)) + .forEach(test(indexer)); + } + + private static Consumer test(Base2ExponentialHistogramIndexer indexer) { + return testCase -> + AssertionsForClassTypes.assertThat(indexer.computeIndex(testCase.value)) + .describedAs( + "value " + Double.toHexString(testCase.value) + " (" + testCase.value + ")") + .isEqualTo(testCase.expectedBucket); + } + + private static TestCase of(double value, int expectedBucket) { + return new TestCase(value, expectedBucket); + } + + private static class TestCase { + private final double value; + private final int expectedBucket; + + private TestCase(double value, int expectedBucket) { + this.value = value; + this.expectedBucket = expectedBucket; + } + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java new file mode 100644 index 00000000000..2100f3dccb6 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramAggregatorTest.java @@ -0,0 +1,592 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import com.google.common.collect.ImmutableList; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.internal.data.EmptyExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.MutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.MutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.assertj.core.data.Offset; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class DoubleBase2ExponentialHistogramAggregatorTest { + + @Mock DoubleExemplarReservoir reservoir; + private final ExemplarReservoirFactory reservoirFactory = + new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return reservoir; + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + throw new UnsupportedOperationException(); + } + }; + + private DoubleBase2ExponentialHistogramAggregator aggregator; + + private static final int MAX_SCALE = 20; + private static final Resource RESOURCE = Resource.getDefault(); + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.empty(); + private static final MetricDescriptor METRIC_DESCRIPTOR = + MetricDescriptor.create("name", "description", "unit"); + + private static Stream provideAggregator() { + List parameters = new ArrayList<>(); + for (MemoryMode memoryMode : MemoryMode.values()) { + parameters.add( + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.noSamples(), 160, 20, /* recordMinMax= */ true, memoryMode)); + parameters.add( + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.noSamples(), + 160, + MAX_SCALE, + /* recordMinMax= */ true, + memoryMode)); + } + return parameters.stream(); + } + + private static int valueToIndex(int scale, double value) { + double scaleFactor = Math.scalb(1D / Math.log(2), scale); + return (int) Math.ceil(Math.log(value) * scaleFactor) - 1; + } + + private void initialize(MemoryMode memoryMode) { + aggregator = + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.noSamples(), 160, 20, /* recordMinMax= */ true, memoryMode); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void createHandle(MemoryMode memoryMode) { + initialize(memoryMode); + + AggregatorHandle handle = aggregator.createHandle(0); + assertThat(handle).isInstanceOf(DoubleBase2ExponentialHistogramAggregator.Handle.class); + ExponentialHistogramPointData point = + ((DoubleBase2ExponentialHistogramAggregator.Handle) handle) + .doAggregateThenMaybeResetDoubles( + 0, 1, Attributes.empty(), Collections.emptyList(), /* reset= */ true); + assertThat(point.getPositiveBuckets()).isInstanceOf(EmptyExponentialHistogramBuckets.class); + assertThat(point.getPositiveBuckets().getScale()).isEqualTo(MAX_SCALE); + assertThat(point.getNegativeBuckets()).isInstanceOf(EmptyExponentialHistogramBuckets.class); + assertThat(point.getNegativeBuckets().getScale()).isEqualTo(MAX_SCALE); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testRecordings(MemoryMode memoryMode) { + initialize(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(0.5, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(1.0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(15.213, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-13.2, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-2.01, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(0.0, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(0, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + List positiveCounts = + Objects.requireNonNull(point).getPositiveBuckets().getBucketCounts(); + List negativeCounts = point.getNegativeBuckets().getBucketCounts(); + int expectedScale = 5; // should be downscaled from 20 to 5 after recordings + + assertThat(point.getScale()).isEqualTo(expectedScale); + assertThat(point.getPositiveBuckets().getScale()).isEqualTo(expectedScale); + assertThat(point.getNegativeBuckets().getScale()).isEqualTo(expectedScale); + assertThat(point.getZeroCount()).isEqualTo(2); + + // Assert positive recordings are at correct index + int posOffset = point.getPositiveBuckets().getOffset(); + assertThat(point.getPositiveBuckets().getTotalCount()).isEqualTo(5); + assertThat(positiveCounts.get(valueToIndex(expectedScale, 0.5) - posOffset)).isEqualTo(1); + assertThat(positiveCounts.get(valueToIndex(expectedScale, 1.0) - posOffset)).isEqualTo(1); + assertThat(positiveCounts.get(valueToIndex(expectedScale, 12.0) - posOffset)).isEqualTo(2); + assertThat(positiveCounts.get(valueToIndex(expectedScale, 15.213) - posOffset)).isEqualTo(1); + + // Assert negative recordings are at correct index + int negOffset = point.getNegativeBuckets().getOffset(); + assertThat(point.getNegativeBuckets().getTotalCount()).isEqualTo(3); + assertThat(negativeCounts.get(valueToIndex(expectedScale, 13.2) - negOffset)).isEqualTo(1); + assertThat(negativeCounts.get(valueToIndex(expectedScale, 2.01) - negOffset)).isEqualTo(1); + assertThat(negativeCounts.get(valueToIndex(expectedScale, 1.0) - negOffset)).isEqualTo(1); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testInvalidRecording(MemoryMode memoryMode) { + initialize(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + // Non-finite recordings should be ignored + aggregatorHandle.recordDouble(Double.POSITIVE_INFINITY, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(Double.NEGATIVE_INFINITY, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(Double.NaN, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(Objects.requireNonNull(point).getSum()).isEqualTo(0); + assertThat(point.getPositiveBuckets().getTotalCount()).isEqualTo(0); + assertThat(point.getNegativeBuckets().getTotalCount()).isEqualTo(0); + assertThat(point.getZeroCount()).isEqualTo(0); + } + + @ParameterizedTest + @MethodSource("provideAggregator") + void testRecordingsAtLimits(DoubleBase2ExponentialHistogramAggregator aggregator) { + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordDouble(Double.MIN_VALUE, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(Double.MAX_VALUE, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + List bucketCounts = Objects.requireNonNull(point).getPositiveBuckets().getBucketCounts(); + + // assert buckets == [1 0 0 0 ... 1] + assertThat(bucketCounts.get(0)).isEqualTo(1); + assertThat(bucketCounts.get(bucketCounts.size() - 1)).isEqualTo(1); + assertThat(bucketCounts.stream().filter(i -> i == 0).count()) + .isEqualTo(bucketCounts.size() - 2); + assertThat(point.getPositiveBuckets().getTotalCount()).isEqualTo(2); + + // With 160 buckets allowed, minimum scale is -4 + assertThat(point.getScale()).isEqualTo(-4); + assertThat(point.getPositiveBuckets().getScale()).isEqualTo(-4); + assertThat(point.getNegativeBuckets().getScale()).isEqualTo(-4); + + // if scale is -4, base is 65,536. + int base = 65_536; + + // Verify the rule holds: + // base ^ (offset+i) <= (values recorded to bucket i) < base ^ (offset+i+1) + + // lowest bucket + // As the bucket lower bound is less than Double.MIN_VALUE, Math.pow() rounds to 0 + assertThat(Math.pow(base, point.getPositiveBuckets().getOffset())).isEqualTo(0); + assertThat(Math.pow(base, point.getPositiveBuckets().getOffset() + 1)) + .isGreaterThan(Double.MIN_VALUE); + + // highest bucket + assertThat(Math.pow(base, point.getPositiveBuckets().getOffset() + bucketCounts.size() - 1)) + .isLessThanOrEqualTo(Double.MAX_VALUE); + // As the bucket upper bound is greater than Double.MAX_VALUE, Math.pow() rounds to infinity + assertThat(Math.pow(base, point.getPositiveBuckets().getOffset() + bucketCounts.size())) + .isEqualTo(Double.POSITIVE_INFINITY); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset_WithExemplars(MemoryMode memoryMode) { + DoubleBase2ExponentialHistogramAggregator agg = + new DoubleBase2ExponentialHistogramAggregator( + reservoirFactory, 160, MAX_SCALE, /* recordMinMax= */ true, memoryMode); + + Attributes attributes = Attributes.builder().put("test", "value").build(); + DoubleExemplarData exemplar = + ImmutableDoubleExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1); + List exemplars = Collections.singletonList(exemplar); + Mockito.when(reservoir.collectAndResetDoubles(Attributes.empty())).thenReturn(exemplars); + + AggregatorHandle aggregatorHandle = agg.createHandle(0); + aggregatorHandle.recordDouble(0, attributes, Context.root()); + + assertThat( + Objects.requireNonNull( + aggregatorHandle.aggregateThenMaybeReset( + 0, 1, Attributes.empty(), /* reset= */ true)) + .getExemplars()) + .isEqualTo(exemplars); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset(MemoryMode memoryMode) { + initialize(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordDouble(5.0, Attributes.empty(), Context.current()); + assertThat( + Objects.requireNonNull( + aggregatorHandle.aggregateThenMaybeReset( + 0, 1, Attributes.empty(), /* reset= */ true)) + .getPositiveBuckets() + .getBucketCounts()) + .isEqualTo(Collections.singletonList(1L)); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testInsert1M(MemoryMode memoryMode) { + initialize(memoryMode); + + AggregatorHandle handle = aggregator.createHandle(0); + + int n = 1024 * 1024 - 1; + double min = 16.0 / n; + double d = min; + for (int i = 0; i < n; i++) { + handle.recordDouble(d, Attributes.empty(), Context.current()); + d += min; + } + + ExponentialHistogramPointData point = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)); + assertThat(point.getScale()).isEqualTo(3); + assertThat(point.getPositiveBuckets().getScale()).isEqualTo(3); + assertThat(point.getNegativeBuckets().getScale()).isEqualTo(3); + assertThat(point.getPositiveBuckets().getBucketCounts().size()).isEqualTo(160); + assertThat(point.getPositiveBuckets().getTotalCount()).isEqualTo(n); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testDownScale(MemoryMode memoryMode) { + initialize(memoryMode); + + DoubleBase2ExponentialHistogramAggregator.Handle handle = + (DoubleBase2ExponentialHistogramAggregator.Handle) aggregator.createHandle(0); + // record a measurement to initialize positive buckets + handle.recordDouble(0.5, Attributes.empty(), Context.current()); + + handle.downScale(20); // down to zero scale + + // test histogram operates properly after being manually scaled down to 0 + handle.recordDouble(1.0, Attributes.empty(), Context.current()); + handle.recordDouble(2.0, Attributes.empty(), Context.current()); + handle.recordDouble(4.0, Attributes.empty(), Context.current()); + handle.recordDouble(16.0, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)); + assertThat(point.getScale()).isEqualTo(0); + assertThat(point.getPositiveBuckets().getScale()).isEqualTo(0); + assertThat(point.getNegativeBuckets().getScale()).isEqualTo(0); + ExponentialHistogramBuckets buckets = point.getPositiveBuckets(); + assertThat(point.getSum()).isEqualTo(23.5); + assertThat(buckets.getOffset()).isEqualTo(-2); + assertThat(buckets.getBucketCounts()).isEqualTo(Arrays.asList(1L, 1L, 1L, 1L, 0L, 1L)); + assertThat(buckets.getTotalCount()).isEqualTo(5); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testToMetricData(MemoryMode memoryMode) { + Attributes attributes = Attributes.builder().put("test", "value").build(); + DoubleExemplarData exemplar = + ImmutableDoubleExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1); + Mockito.when(reservoir.collectAndResetDoubles(Attributes.empty())) + .thenReturn(Collections.singletonList(exemplar)); + + DoubleBase2ExponentialHistogramAggregator cumulativeAggregator = + new DoubleBase2ExponentialHistogramAggregator( + reservoirFactory, 160, MAX_SCALE, /* recordMinMax= */ true, memoryMode); + + AggregatorHandle aggregatorHandle = + cumulativeAggregator.createHandle(0); + aggregatorHandle.recordDouble(0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(123.456, Attributes.empty(), Context.current()); + ExponentialHistogramPointData expPoint = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + + MetricData metricDataCumulative = + cumulativeAggregator.toMetricData( + RESOURCE, + INSTRUMENTATION_SCOPE_INFO, + METRIC_DESCRIPTOR, + Collections.singletonList(expPoint), + AggregationTemporality.CUMULATIVE); + + // Assertions run twice to verify immutability; recordings shouldn't modify the metric data + for (int i = 0; i < 2; i++) { + assertThat(metricDataCumulative) + .hasExponentialHistogramSatisfying(expHistogram -> + expHistogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasSum(123.456) + .hasScale(20) + .hasZeroCount(2) + .hasCount(3) + .hasMin(0) + .hasMax(123.456) + .hasExemplars(exemplar) + .hasPositiveBucketsSatisfying(buckets -> + buckets + .hasCounts(Collections.singletonList(1L)) + .hasOffset(valueToIndex(20, 123.456)) + .hasTotalCount(1)) + .hasNegativeBucketsSatisfying(buckets -> + buckets.hasTotalCount(0).hasCounts(Collections.emptyList())))); + aggregatorHandle.recordDouble(1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(0, Attributes.empty(), Context.current()); + } + + MetricData metricDataDelta = + cumulativeAggregator.toMetricData( + RESOURCE, + INSTRUMENTATION_SCOPE_INFO, + METRIC_DESCRIPTOR, + Collections.singletonList(expPoint), + AggregationTemporality.DELTA); + assertThat(metricDataDelta.getType()).isEqualTo(MetricDataType.EXPONENTIAL_HISTOGRAM); + assertThat(metricDataDelta.getExponentialHistogramData().getAggregationTemporality()) + .isEqualTo(AggregationTemporality.DELTA); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testMultithreadedUpdates(MemoryMode memoryMode) throws InterruptedException { + initialize(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + ImmutableList updates = ImmutableList.of(0D, 0.1D, -0.1D, 1D, -1D, 100D); + int numberOfThreads = updates.size(); + int numberOfUpdates = 10000; + ThreadPoolExecutor executor = + (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThreads); + + executor.invokeAll( + updates.stream() + .map(v -> + Executors.callable(() -> { + for (int j = 0; j < numberOfUpdates; j++) { + aggregatorHandle.recordDouble(v, Attributes.empty(), Context.current()); + if (ThreadLocalRandom.current().nextInt(10) == 0) { + aggregatorHandle.aggregateThenMaybeReset( + 0, 1, Attributes.empty(), /* reset= */ false); + } + } + })) + .collect(Collectors.toList())); + + ExponentialHistogramPointData point = + Objects.requireNonNull( + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false)); + assertThat(point.getZeroCount()).isEqualTo(numberOfUpdates); + assertThat(point.getSum()).isCloseTo(100.0D * 10000, Offset.offset(0.0001)); // float error + assertThat(point.getScale()).isEqualTo(3); + assertThat(point.getPositiveBuckets().getScale()).isEqualTo(3); + assertThat(point.getNegativeBuckets().getScale()).isEqualTo(3); + ExponentialHistogramBuckets positiveBuckets = point.getPositiveBuckets(); + assertThat(positiveBuckets.getTotalCount()).isEqualTo(numberOfUpdates * 3); + assertThat(positiveBuckets.getOffset()).isEqualTo(-27); + ExponentialHistogramBuckets negativeBuckets = point.getNegativeBuckets(); + assertThat(negativeBuckets.getTotalCount()).isEqualTo(numberOfUpdates * 2); + assertThat(negativeBuckets.getOffset()).isEqualTo(-27); + + // Verify positive buckets have correct counts + List posCounts = point.getPositiveBuckets().getBucketCounts(); + assertThat( + posCounts.get( + valueToIndex(point.getScale(), 0.1) - point.getPositiveBuckets().getOffset())) + .isEqualTo(numberOfUpdates); + assertThat( + posCounts.get( + valueToIndex(point.getScale(), 1) - point.getPositiveBuckets().getOffset())) + .isEqualTo(numberOfUpdates); + assertThat( + posCounts.get( + valueToIndex(point.getScale(), 100) - point.getPositiveBuckets().getOffset())) + .isEqualTo(numberOfUpdates); + + // Verify negative buckets have correct counts + List negCounts = point.getNegativeBuckets().getBucketCounts(); + assertThat( + negCounts.get( + valueToIndex(point.getScale(), 0.1) - point.getPositiveBuckets().getOffset())) + .isEqualTo(numberOfUpdates); + assertThat( + negCounts.get( + valueToIndex(point.getScale(), 1) - point.getPositiveBuckets().getOffset())) + .isEqualTo(numberOfUpdates); + } + + @Test + public void verifyMutableDataUsedInReusableDataMemoryMode() { + initialize(MemoryMode.REUSABLE_DATA); + + DoubleBase2ExponentialHistogramAggregator.Handle handle = + (DoubleBase2ExponentialHistogramAggregator.Handle) aggregator.createHandle(0); + + // record a measurement to initialize positive buckets + handle.recordDouble(0.5, Attributes.empty(), Context.current()); + // record a measurement to initialize negative buckets + handle.recordDouble(-13.2, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false)); + + assertThat(point).isInstanceOf(MutableExponentialHistogramPointData.class); + assertThat(point.getPositiveBuckets()).isInstanceOf(MutableExponentialHistogramBuckets.class); + assertThat(point.getNegativeBuckets()).isInstanceOf(MutableExponentialHistogramBuckets.class); + assertThat(point.getPositiveBuckets().getBucketCounts()).isNotEmpty(); + assertThat(point.getNegativeBuckets().getBucketCounts()).isNotEmpty(); + + handle.recordDouble(0.6, Attributes.empty(), Context.current()); + handle.recordDouble(-16.3, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData secondAggregatePoint = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(1, 2, Attributes.empty(), /* reset= */ false)); + + // Mutable point should be reused across collections. + assertThat(secondAggregatePoint).isSameAs(point); + } + + @Test + public void verifyImmutableDataUsedInImmutableDataMemoryMode() { + initialize(MemoryMode.IMMUTABLE_DATA); + + DoubleBase2ExponentialHistogramAggregator.Handle handle = + (DoubleBase2ExponentialHistogramAggregator.Handle) aggregator.createHandle(0); + + // record a measurement to initialize positive buckets + handle.recordDouble(0.5, Attributes.empty(), Context.current()); + // record a measurement to initialize negative buckets + handle.recordDouble(-13.2, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false)); + + assertThat(point).isInstanceOf(ImmutableExponentialHistogramPointData.class); + assertThat(point.getPositiveBuckets()) + .isInstanceOf(DoubleBase2ExponentialHistogramBuckets.class); + assertThat(point.getNegativeBuckets()) + .isInstanceOf(DoubleBase2ExponentialHistogramBuckets.class); + } + + @Test + public void reusablePoint_emptyFirstThenRecordAndCheck() { + initialize(MemoryMode.REUSABLE_DATA); + + DoubleBase2ExponentialHistogramAggregator.Handle handle = + (DoubleBase2ExponentialHistogramAggregator.Handle) aggregator.createHandle(0); + + // Let's create a point without buckets + ExponentialHistogramPointData point = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false)); + + assertThat(point).isInstanceOf(MutableExponentialHistogramPointData.class); + assertThat(point.getPositiveBuckets()).isInstanceOf(EmptyExponentialHistogramBuckets.class); + assertThat(point.getNegativeBuckets()).isInstanceOf(EmptyExponentialHistogramBuckets.class); + + // record a measurement to initialize positive buckets + handle.recordDouble(0.5, Attributes.empty(), Context.current()); + // record a measurement to initialize negative buckets + handle.recordDouble(-13.2, Attributes.empty(), Context.current()); + + point = + Objects.requireNonNull( + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false)); + + assertThat(point).isInstanceOf(MutableExponentialHistogramPointData.class); + assertThat(point.getPositiveBuckets()).isInstanceOf(MutableExponentialHistogramBuckets.class); + assertThat(point.getNegativeBuckets()).isInstanceOf(MutableExponentialHistogramBuckets.class); + assertThat(point.getPositiveBuckets().getBucketCounts()).isNotEmpty(); + assertThat(point.getNegativeBuckets().getBucketCounts()).isNotEmpty(); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testRecordMinMaxDisabled(MemoryMode memoryMode) { + DoubleBase2ExponentialHistogramAggregator aggregator = + new DoubleBase2ExponentialHistogramAggregator( + ExemplarReservoirFactory.noSamples(), 160, 20, /* recordMinMax= */ false, memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(0.5, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(1.0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.0, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(15.213, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-13.2, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-2.01, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData point = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(point).isNotNull(); + assertThat(point.hasMin()).isFalse(); + assertThat(point.hasMax()).isFalse(); + assertThat(point.getSum()).isCloseTo(13.503, Offset.offset(0.0001)); + assertThat(point.getCount()).isEqualTo(6); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramBucketsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramBucketsTest.java new file mode 100644 index 00000000000..6183b8ec68b --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleBase2ExponentialHistogramBucketsTest.java @@ -0,0 +1,179 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.aggregator; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import java.util.Arrays; +import java.util.Collections; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * These are extra test cases for buckets. Much of this class is already tested via more complex + * test cases at {@link DoubleBase2ExponentialHistogramAggregatorTest}. + */ +class DoubleBase2ExponentialHistogramBucketsTest { + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void record_Valid(MemoryMode memoryMode) { + // Can only effectively test recording of one value here due to downscaling required. + // More complex recording/downscaling operations are tested in the aggregator. + DoubleBase2ExponentialHistogramBuckets b = newBuckets(memoryMode); + b.record(1); + b.record(1); + b.record(1); + assertThat(b.getTotalCount()).isEqualTo(3); + assertThat(b.getBucketCounts()).isEqualTo(Collections.singletonList(3L)); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void record_Zero_Throws(MemoryMode memoryMode) { + DoubleBase2ExponentialHistogramBuckets b = newBuckets(memoryMode); + assertThatThrownBy(() -> b.record(0)).isInstanceOf(IllegalStateException.class); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void downscale_Valid(MemoryMode memoryMode) { + DoubleBase2ExponentialHistogramBuckets b = newBuckets(memoryMode); + b.downscale(20); // scale of zero is easy to reason with without a calculator + b.record(1); + b.record(2); + b.record(4); + assertThat(b.getScale()).isEqualTo(0); + assertThat(b.getTotalCount()).isEqualTo(3); + assertThat(b.getBucketCounts()).isEqualTo(Arrays.asList(1L, 1L, 1L)); + assertThat(b.getOffset()).isEqualTo(-1); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void downscale_NegativeIncrement_Throws(MemoryMode memoryMode) { + DoubleBase2ExponentialHistogramBuckets b = newBuckets(memoryMode); + assertThatThrownBy(() -> b.downscale(-1)).isInstanceOf(IllegalStateException.class); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void equalsAndHashCode(MemoryMode memoryMode) { + DoubleBase2ExponentialHistogramBuckets a = newBuckets(memoryMode); + DoubleBase2ExponentialHistogramBuckets b = newBuckets(memoryMode); + + assertThat(a).isNotNull(); + assertThat(b).isEqualTo(a); + assertThat(a).isEqualTo(b); + assertThat(a).hasSameHashCodeAs(b); + + a.record(1); + assertThat(a).isNotEqualTo(b); + assertThat(b).isNotEqualTo(a); + assertThat(a).doesNotHaveSameHashCodeAs(b); + + b.record(1); + assertThat(b).isEqualTo(a); + assertThat(a).isEqualTo(b); + assertThat(a).hasSameHashCodeAs(b); + + // Now we start to play with altering offset, but having same effective counts. + DoubleBase2ExponentialHistogramBuckets empty = newBuckets(memoryMode); + empty.downscale(20); + DoubleBase2ExponentialHistogramBuckets c = newBuckets(memoryMode); + c.downscale(20); + assertThat(c.record(1)).isTrue(); + // Record can fail if scale is not set correctly. + assertThat(c.record(3)).isTrue(); + assertThat(c.getTotalCount()).isEqualTo(2); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toString_Valid(MemoryMode memoryMode) { + // Note this test may break once difference implementations for counts are developed since + // the counts may have different toStrings(). + DoubleBase2ExponentialHistogramBuckets b = newBuckets(memoryMode); + b.record(1); + assertThat(b.toString()) + .isEqualTo("DoubleExponentialHistogramBuckets{scale: 20, offset: -1, counts: {-1=1} }"); + } + + @Test + void testGetBucketCountsWithReusableList() { + // Can only effectively test recording of one value here due to downscaling required. + // More complex recording/downscaling operations are tested in the aggregator. + DoubleBase2ExponentialHistogramBuckets b = newBuckets(MemoryMode.REUSABLE_DATA); + b.record(1); + b.record(1); + b.record(1); + assertThat(b.getBucketCounts()).isEqualTo(Collections.singletonList(3L)); + + DynamicPrimitiveLongList bucketCounts = DynamicPrimitiveLongList.empty(); + b.getBucketCountsIntoReusableList(bucketCounts); + assertThat(bucketCounts).isEqualTo(Collections.singletonList(3L)); + } + + @Test + public void testGetBucketCountsWithReusableListWithEmptyCounts() { + // Can only effectively test recording of one value here due to downscaling required. + // More complex recording/downscaling operations are tested in the aggregator. + DoubleBase2ExponentialHistogramBuckets b = newBuckets(MemoryMode.REUSABLE_DATA); + assertThat(b.getBucketCounts()).isEmpty(); + + DynamicPrimitiveLongList bucketCounts = DynamicPrimitiveLongList.empty(); + b.getBucketCountsIntoReusableList(bucketCounts); + assertThat(bucketCounts).isEmpty(); + } + + @Test + public void testDownScaleReusableCountIsOkWhenUsedForSecondTime() { + DoubleBase2ExponentialHistogramBuckets immutableDataBasedBuckets = + newBuckets(MemoryMode.IMMUTABLE_DATA); + immutableDataBasedBuckets.record(0.5); + immutableDataBasedBuckets.record(1); + immutableDataBasedBuckets.record(10); + immutableDataBasedBuckets.downscale( + 2); // scale of zero is easy to reason with without a calculator + + DoubleBase2ExponentialHistogramBuckets reusableDataBasedBuckets = + newBuckets(MemoryMode.REUSABLE_DATA); + reusableDataBasedBuckets.record(0.5); + reusableDataBasedBuckets.record(1); + reusableDataBasedBuckets.record(10); + reusableDataBasedBuckets.downscale( + 2); // scale of zero is easy to reason with without a calculator + + assertThat(immutableDataBasedBuckets.getScale()).isEqualTo(reusableDataBasedBuckets.getScale()); + assertThat(immutableDataBasedBuckets.getTotalCount()) + .isEqualTo(reusableDataBasedBuckets.getTotalCount()); + assertThat(immutableDataBasedBuckets.getBucketCounts()) + .isEqualTo(reusableDataBasedBuckets.getBucketCounts()); + assertThat(immutableDataBasedBuckets.getOffset()) + .isEqualTo(reusableDataBasedBuckets.getOffset()); + + immutableDataBasedBuckets.downscale( + 3); // scale of zero is easy to reason with without a calculator + reusableDataBasedBuckets.downscale( + 3); // scale of zero is easy to reason with without a calculator + + assertThat(immutableDataBasedBuckets.getScale()).isEqualTo(reusableDataBasedBuckets.getScale()); + assertThat(immutableDataBasedBuckets.getTotalCount()) + .isEqualTo(reusableDataBasedBuckets.getTotalCount()); + assertThat(immutableDataBasedBuckets.getBucketCounts()) + .isEqualTo(reusableDataBasedBuckets.getBucketCounts()); + assertThat(immutableDataBasedBuckets.getOffset()) + .isEqualTo(reusableDataBasedBuckets.getOffset()); + } + + private static DoubleBase2ExponentialHistogramBuckets newBuckets(MemoryMode memoryMode) { + return new DoubleBase2ExponentialHistogramBuckets(20, 160, memoryMode); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java index 8ff3b9e9266..e3676182e3e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExplicitBucketHistogramAggregatorTest.java @@ -7,30 +7,35 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import com.google.common.collect.ImmutableList; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.data.MetricDataType; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.MutableHistogramPointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; import io.opentelemetry.sdk.resources.Resource; +import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.ThreadPoolExecutor; import java.util.stream.Collectors; -import javax.annotation.Nullable; +import java.util.stream.DoubleStream; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @@ -38,39 +43,72 @@ @ExtendWith(MockitoExtension.class) class DoubleExplicitBucketHistogramAggregatorTest { - @Mock ExemplarReservoir reservoir; + @Mock DoubleExemplarReservoir reservoir; + private final ExemplarReservoirFactory reservoirFactory = + new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return reservoir; + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + throw new UnsupportedOperationException(); + } + }; private static final double[] boundaries = new double[] {10.0, 100.0, 1000.0}; + private static final List boundariesList = + DoubleStream.of(boundaries).boxed().collect(Collectors.toList()); private static final Resource RESOURCE = Resource.getDefault(); private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = InstrumentationScopeInfo.empty(); private static final MetricDescriptor METRIC_DESCRIPTOR = MetricDescriptor.create("name", "description", "unit"); - private static final DoubleExplicitBucketHistogramAggregator aggregator = - new DoubleExplicitBucketHistogramAggregator(boundaries, ExemplarReservoir::doubleNoSamples); + private DoubleExplicitBucketHistogramAggregator aggregator; - @Test - void createHandle() { - assertThat(aggregator.createHandle()) + private void init(MemoryMode memoryMode) { + aggregator = + new DoubleExplicitBucketHistogramAggregator( + boundaries, /* recordMinMax= */ true, ExemplarReservoirFactory.noSamples(), memoryMode); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void createHandle(MemoryMode memoryMode) { + init(memoryMode); + assertThat(aggregator.createHandle(0)) .isInstanceOf(DoubleExplicitBucketHistogramAggregator.Handle.class); } - @Test - void testRecordings() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(20); - aggregatorHandle.recordLong(5); - aggregatorHandle.recordLong(150); - aggregatorHandle.recordLong(2000); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())) + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testRecordings(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(20, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(5, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(150, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(2000, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)) .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 2175, /* hasMinMax= */ true, 5d, 2000d, new long[] {1, 1, 1, 1})); + ImmutableHistogramPointData.create( + 0, + 1, + Attributes.empty(), + 2175, + /* hasMin= */ true, + 5d, + /* hasMax= */ true, + 2000d, + boundariesList, + Arrays.asList(1L, 1L, 1L, 1L))); } - @Test - void testExemplarsInAccumulation() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset_WithExemplars(MemoryMode memoryMode) { Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -83,157 +121,94 @@ void testExemplarsInAccumulation() { TraceState.getDefault()), 1); List exemplars = Collections.singletonList(exemplar); - Mockito.when(reservoir.collectAndReset(Attributes.empty())).thenReturn(exemplars); + Mockito.when(reservoir.collectAndResetDoubles(Attributes.empty())).thenReturn(exemplars); DoubleExplicitBucketHistogramAggregator aggregator = - new DoubleExplicitBucketHistogramAggregator(boundaries, () -> reservoir); - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); + new DoubleExplicitBucketHistogramAggregator( + boundaries, /* recordMinMax= */ true, reservoirFactory, memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); aggregatorHandle.recordDouble(0, attributes, Context.root()); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 0, 0, new long[] {1, 0, 0, 0}, exemplars)); - } - - @Test - void toAccumulationAndReset() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordLong(100); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 100, /* hasMinMax= */ true, 100d, 100d, new long[] {0, 1, 0, 0})); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordLong(0); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())) + assertThat( + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)) .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 0d, 0d, new long[] {1, 0, 0, 0})); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); + ImmutableHistogramPointData.create( + 0, + 1, + Attributes.empty(), + 0, + /* hasMin= */ true, + 0.0, + /* hasMax= */ true, + 0.0, + boundariesList, + Arrays.asList(1L, 0L, 0L, 0L), + exemplars)); } - @Test - void accumulateData() { - assertThat(aggregator.accumulateDoubleMeasurement(11.1, Attributes.empty(), Context.current())) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 11.1, /* hasMinMax= */ true, 11.1, 11.1, new long[] {0, 1, 0, 0})); - assertThat(aggregator.accumulateLongMeasurement(10, Attributes.empty(), Context.current())) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 10.0, /* hasMinMax= */ true, 10.0, 10.0, new long[] {1, 0, 0, 0})); - } + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); - @Test - void mergeAccumulation() { - Attributes attributes = Attributes.builder().put("test", "value").build(); - DoubleExemplarData exemplar = - ImmutableDoubleExemplarData.create( - attributes, - 2L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 1); - List exemplars = Collections.singletonList(exemplar); - List previousExemplars = - Collections.singletonList( - ImmutableDoubleExemplarData.create( - attributes, - 1L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 2)); - ExplicitBucketHistogramAccumulation previousAccumulation = - ExplicitBucketHistogramAccumulation.create( - 2, /* hasMinMax= */ true, 1d, 2d, new long[] {1, 1, 0}, previousExemplars); - ExplicitBucketHistogramAccumulation nextAccumulation = - ExplicitBucketHistogramAccumulation.create( - 2, /* hasMinMax= */ true, 2d, 3d, new long[] {0, 0, 2}, exemplars); - // Assure most recent exemplars are kept. - assertThat(aggregator.merge(previousAccumulation, nextAccumulation)) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 4, /* hasMinMax= */ true, 1d, 3d, new long[] {1, 1, 2}, exemplars)); - } - - @Test - void mergeAccumulation_MinAndMax() { - // If min / max is null for both accumulations set min / max to null + aggregatorHandle.recordLong(100, Attributes.empty(), Context.current()); assertThat( - aggregator.merge( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ false, 0, 0, new long[] {}, Collections.emptyList()), - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ false, 0, 0, new long[] {}, Collections.emptyList()))) + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)) .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ false, -1, -1, new long[] {}, Collections.emptyList())); - // If min / max is non-null for only one accumulation set min / max to it - assertThat( - aggregator.merge( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 1d, 2d, new long[] {}, Collections.emptyList()), - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ false, 0, 0, new long[] {}, Collections.emptyList()))) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 1d, 2d, new long[] {}, Collections.emptyList())); - assertThat( - aggregator.merge( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ false, 0, 0, new long[] {}, Collections.emptyList()), - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 1d, 2d, new long[] {}, Collections.emptyList()))) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 1d, 2d, new long[] {}, Collections.emptyList())); - // If both accumulations have min / max compute the min / max + ImmutableHistogramPointData.create( + 0, + 1, + Attributes.empty(), + 100, + /* hasMin= */ true, + 100d, + /* hasMax= */ true, + 100d, + boundariesList, + Arrays.asList(0L, 1L, 0L, 0L))); + + aggregatorHandle.recordLong(0, Attributes.empty(), Context.current()); assertThat( - aggregator.merge( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 1d, 1d, new long[] {}, Collections.emptyList()), - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 2d, 2d, new long[] {}, Collections.emptyList()))) + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)) .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 0, /* hasMinMax= */ true, 1d, 2d, new long[] {}, Collections.emptyList())); + ImmutableHistogramPointData.create( + 0, + 1, + Attributes.empty(), + 0, + /* hasMin= */ true, + 0d, + /* hasMax= */ true, + 0d, + boundariesList, + Arrays.asList(1L, 0L, 0L, 0L))); } - @Test - void toMetricData() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(10); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricData(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(10, Attributes.empty(), Context.current()); MetricData metricData = aggregator.toMetricData( RESOURCE, INSTRUMENTATION_SCOPE_INFO, METRIC_DESCRIPTOR, - Collections.singletonMap( - Attributes.empty(), aggregatorHandle.accumulateThenReset(Attributes.empty())), - AggregationTemporality.DELTA, - 0, - 10, - 100); + Collections.singletonList( + aggregatorHandle.aggregateThenMaybeReset( + 0, 1, Attributes.empty(), /* reset= */ true)), + AggregationTemporality.DELTA); assertThat(metricData).isNotNull(); assertThat(metricData.getType()).isEqualTo(MetricDataType.HISTOGRAM); assertThat(metricData.getHistogramData().getAggregationTemporality()) .isEqualTo(AggregationTemporality.DELTA); } - @Test - void toMetricDataWithExemplars() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricDataWithExemplars(MemoryMode memoryMode) { + init(memoryMode); Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -245,115 +220,92 @@ void toMetricDataWithExemplars() { TraceFlags.getDefault(), TraceState.getDefault()), 1); - ExplicitBucketHistogramAccumulation accumulation = - ExplicitBucketHistogramAccumulation.create( + HistogramPointData histPoint = + ImmutableHistogramPointData.create( + 0, + 1, + Attributes.empty(), 2, - /* hasMinMax= */ true, + /* hasMin= */ true, 2d, + /* hasMax= */ true, 2d, - new long[] {1, 0, 0, 0}, + boundariesList, + Arrays.asList(1L, 0L, 0L, 0L), Collections.singletonList(exemplar)); assertThat( aggregator.toMetricData( RESOURCE, INSTRUMENTATION_SCOPE_INFO, METRIC_DESCRIPTOR, - Collections.singletonMap(Attributes.empty(), accumulation), - AggregationTemporality.CUMULATIVE, - 0, - 10, - 100)) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> - point - .hasSum(2) - .hasMin(2) - .hasMax(2) - .hasBucketCounts(1, 0, 0, 0) - .hasCount(1) - .hasExemplars(exemplar))); + Collections.singletonList(histPoint), + AggregationTemporality.CUMULATIVE)) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point + .hasSum(2) + .hasMin(2) + .hasMax(2) + .hasBucketCounts(1, 0, 0, 0) + .hasCount(1) + .hasExemplars(exemplar))); } - @Test - void testHistogramCounts() { - assertThat( - aggregator - .accumulateDoubleMeasurement(1.1, Attributes.empty(), Context.root()) - .getCounts() - .length) - .isEqualTo(boundaries.length + 1); - assertThat( - aggregator - .accumulateLongMeasurement(1, Attributes.empty(), Context.root()) - .getCounts() - .length) - .isEqualTo(boundaries.length + 1); - - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(1.1); - ExplicitBucketHistogramAccumulation explicitBucketHistogramAccumulation = - aggregatorHandle.accumulateThenReset(Attributes.empty()); - assertThat(explicitBucketHistogramAccumulation).isNotNull(); - assertThat(explicitBucketHistogramAccumulation.getCounts().length) - .isEqualTo(boundaries.length + 1); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testHistogramCounts(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(1.1, Attributes.empty(), Context.current()); + HistogramPointData point = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(point).isNotNull(); + assertThat(point.getCounts().size()).isEqualTo(boundaries.length + 1); } @Test - void testMultithreadedUpdates() throws InterruptedException { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - Histogram summarizer = new Histogram(); - ImmutableList updates = ImmutableList.of(1L, 2L, 3L, 5L, 7L, 11L, 13L, 17L, 19L, 23L); - int numberOfThreads = updates.size(); - int numberOfUpdates = 10000; - ThreadPoolExecutor executor = - (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThreads); - - executor.invokeAll( - updates.stream() - .map( - v -> - Executors.callable( - () -> { - for (int j = 0; j < numberOfUpdates; j++) { - aggregatorHandle.recordLong(v); - if (ThreadLocalRandom.current().nextInt(10) == 0) { - summarizer.process( - aggregatorHandle.accumulateThenReset(Attributes.empty())); - } - } - })) - .collect(Collectors.toList())); + void testReusableDataMemoryMode() { + init(MemoryMode.REUSABLE_DATA); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(10, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(20, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(30, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(40, Attributes.empty(), Context.current()); - // make sure everything gets merged when all the aggregation is done. - summarizer.process(aggregatorHandle.accumulateThenReset(Attributes.empty())); - - assertThat(summarizer.accumulation) - .isEqualTo( - ExplicitBucketHistogramAccumulation.create( - 1010000, /* hasMinMax= */ true, 1d, 23d, new long[] {50000, 50000, 0, 0})); - } + HistogramPointData pointData = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false); + assertThat(pointData).isExactlyInstanceOf(MutableHistogramPointData.class); - private static final class Histogram { - private final Object mutex = new Object(); + aggregatorHandle.recordLong(10, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(20, Attributes.empty(), Context.current()); - @Nullable private ExplicitBucketHistogramAccumulation accumulation; + HistogramPointData anotherPointData = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false); - void process(@Nullable ExplicitBucketHistogramAccumulation other) { - if (other == null) { - return; - } + // The point data instance should be reused + assertThat(anotherPointData).isSameAs(pointData); + } - synchronized (mutex) { - if (accumulation == null) { - accumulation = other; - return; - } - accumulation = aggregator.merge(accumulation, other); - } - } + @ParameterizedTest + @EnumSource(MemoryMode.class) + void testRecordMinMaxDisabled(MemoryMode memoryMode) { + DoubleExplicitBucketHistogramAggregator aggregator = + new DoubleExplicitBucketHistogramAggregator( + boundaries, + /* recordMinMax= */ false, + ExemplarReservoirFactory.noSamples(), + memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(20, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(5, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(150, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(2000, Attributes.empty(), Context.current()); + HistogramPointData point = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(point.getSum()).isEqualTo(2175); + assertThat(point.hasMin()).isFalse(); + assertThat(point.hasMax()).isFalse(); + assertThat(point.getBoundaries()).isEqualTo(boundariesList); + assertThat(point.getCounts()).isEqualTo(Arrays.asList(1L, 1L, 1L, 1L)); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramAggregatorTest.java deleted file mode 100644 index 129c925cc54..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramAggregatorTest.java +++ /dev/null @@ -1,568 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import com.google.common.collect.ImmutableList; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramBuckets; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramData; -import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounterFactory; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadLocalRandom; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import javax.annotation.Nullable; -import org.assertj.core.data.Offset; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class DoubleExponentialHistogramAggregatorTest { - - @Mock ExemplarReservoir reservoir; - - private static final DoubleExponentialHistogramAggregator aggregator = - new DoubleExponentialHistogramAggregator(ExemplarReservoir::doubleNoSamples, 20, 320); - private static final Resource RESOURCE = Resource.getDefault(); - private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.empty(); - private static final MetricDescriptor METRIC_DESCRIPTOR = - MetricDescriptor.create("name", "description", "unit"); - - private static Stream provideAggregator() { - return Stream.of( - aggregator, - new DoubleExponentialHistogramAggregator( - ExemplarReservoir::doubleNoSamples, - ExponentialBucketStrategy.newStrategy( - 20, 320, ExponentialCounterFactory.mapCounter()))); - } - - private static int valueToIndex(int scale, double value) { - double scaleFactor = Math.scalb(1D / Math.log(2), scale); - return (int) Math.floor(Math.log(value) * scaleFactor); - } - - private static ExponentialHistogramAccumulation getTestAccumulation( - List exemplars, double... recordings) { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - for (double r : recordings) { - aggregatorHandle.recordDouble(r); - } - return aggregatorHandle.doAccumulateThenReset(exemplars); - } - - @Test - void createHandle() { - assertThat(aggregator.createHandle()) - .isInstanceOf(DoubleExponentialHistogramAggregator.Handle.class); - } - - @Test - void testRecordings() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(0.5); - aggregatorHandle.recordDouble(1.0); - aggregatorHandle.recordDouble(12.0); - aggregatorHandle.recordDouble(15.213); - aggregatorHandle.recordDouble(12.0); - aggregatorHandle.recordDouble(-13.2); - aggregatorHandle.recordDouble(-2.01); - aggregatorHandle.recordDouble(-1); - aggregatorHandle.recordDouble(0.0); - aggregatorHandle.recordLong(0); - - ExponentialHistogramAccumulation acc = aggregatorHandle.accumulateThenReset(Attributes.empty()); - List positiveCounts = Objects.requireNonNull(acc).getPositiveBuckets().getBucketCounts(); - List negativeCounts = acc.getNegativeBuckets().getBucketCounts(); - int expectedScale = 6; // should be downscaled from 20 to 6 after recordings - - assertThat(acc.getScale()).isEqualTo(expectedScale); - assertThat(acc.getZeroCount()).isEqualTo(2); - - // Assert positive recordings are at correct index - int posOffset = acc.getPositiveBuckets().getOffset(); - assertThat(acc.getPositiveBuckets().getTotalCount()).isEqualTo(5); - assertThat(positiveCounts.get(valueToIndex(expectedScale, 0.5) - posOffset)).isEqualTo(1); - assertThat(positiveCounts.get(valueToIndex(expectedScale, 1.0) - posOffset)).isEqualTo(1); - assertThat(positiveCounts.get(valueToIndex(expectedScale, 12.0) - posOffset)).isEqualTo(2); - assertThat(positiveCounts.get(valueToIndex(expectedScale, 15.213) - posOffset)).isEqualTo(1); - - // Assert negative recordings are at correct index - int negOffset = acc.getNegativeBuckets().getOffset(); - assertThat(acc.getNegativeBuckets().getTotalCount()).isEqualTo(3); - assertThat(negativeCounts.get(valueToIndex(expectedScale, 13.2) - negOffset)).isEqualTo(1); - assertThat(negativeCounts.get(valueToIndex(expectedScale, 2.01) - negOffset)).isEqualTo(1); - assertThat(negativeCounts.get(valueToIndex(expectedScale, 1.0) - negOffset)).isEqualTo(1); - } - - @Test - void testInvalidRecording() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - // Non finite recordings should be ignored - aggregatorHandle.recordDouble(Double.POSITIVE_INFINITY); - aggregatorHandle.recordDouble(Double.NEGATIVE_INFINITY); - aggregatorHandle.recordDouble(Double.NaN); - - ExponentialHistogramAccumulation acc = aggregatorHandle.accumulateThenReset(Attributes.empty()); - assertThat(Objects.requireNonNull(acc).getSum()).isEqualTo(0); - assertThat(acc.getPositiveBuckets().getTotalCount()).isEqualTo(0); - assertThat(acc.getNegativeBuckets().getTotalCount()).isEqualTo(0); - assertThat(acc.getZeroCount()).isEqualTo(0); - } - - @ParameterizedTest - @MethodSource("provideAggregator") - void testRecordingsAtLimits(DoubleExponentialHistogramAggregator aggregator) { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - - aggregatorHandle.recordDouble(Double.MIN_VALUE); - aggregatorHandle.recordDouble(Double.MAX_VALUE); - - ExponentialHistogramAccumulation acc = aggregatorHandle.accumulateThenReset(Attributes.empty()); - List bucketCounts = Objects.requireNonNull(acc).getPositiveBuckets().getBucketCounts(); - - // assert buckets == [1 0 0 0 ... 1] - assertThat(bucketCounts.get(0)).isEqualTo(1); - assertThat(bucketCounts.get(bucketCounts.size() - 1)).isEqualTo(1); - assertThat(bucketCounts.stream().filter(i -> i == 0).count()) - .isEqualTo(bucketCounts.size() - 2); - assertThat(acc.getPositiveBuckets().getTotalCount()).isEqualTo(2); - - // With 320 buckets allowed, minimum scale is -3 - assertThat(acc.getScale()).isEqualTo(-3); - - // if scale is -3, base is 256. - int base = 256; - - // Verify the rule holds: - // base ^ (offset+i) <= (values recorded to bucket i) < base ^ (offset+i+1) - - // lowest bucket - // As the bucket lower bound is less than Double.MIN_VALUE, Math.pow() rounds to 0 - assertThat(Math.pow(base, acc.getPositiveBuckets().getOffset())).isEqualTo(0); - assertThat(Math.pow(base, acc.getPositiveBuckets().getOffset() + 1)) - .isGreaterThan(Double.MIN_VALUE); - - // highest bucket - assertThat(Math.pow(base, acc.getPositiveBuckets().getOffset() + bucketCounts.size() - 1)) - .isLessThanOrEqualTo(Double.MAX_VALUE); - // As the bucket upper bound is greater than Double.MAX_VALUE, Math.pow() rounds to infinity - assertThat(Math.pow(base, acc.getPositiveBuckets().getOffset() + bucketCounts.size())) - .isEqualTo(Double.POSITIVE_INFINITY); - } - - @Test - void testExemplarsInAccumulation() { - DoubleExponentialHistogramAggregator agg = - new DoubleExponentialHistogramAggregator(() -> reservoir, 20, 320); - - Attributes attributes = Attributes.builder().put("test", "value").build(); - DoubleExemplarData exemplar = - ImmutableDoubleExemplarData.create( - attributes, - 2L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 1); - List exemplars = Collections.singletonList(exemplar); - Mockito.when(reservoir.collectAndReset(Attributes.empty())).thenReturn(exemplars); - - AggregatorHandle aggregatorHandle = - agg.createHandle(); - aggregatorHandle.recordDouble(0, attributes, Context.root()); - - assertThat( - Objects.requireNonNull(aggregatorHandle.accumulateThenReset(Attributes.empty())) - .getExemplars()) - .isEqualTo(exemplars); - } - - @Test - void testAccumulationAndReset() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordDouble(5.0); - assertThat( - Objects.requireNonNull(aggregatorHandle.accumulateThenReset(Attributes.empty())) - .getPositiveBuckets() - .getBucketCounts()) - .isEqualTo(Collections.singletonList(1L)); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - } - - @Test - void testAccumulateData() { - ExponentialHistogramAccumulation acc = - aggregator.accumulateDoubleMeasurement(1.2, Attributes.empty(), Context.current()); - ExponentialHistogramAccumulation expected = getTestAccumulation(Collections.emptyList(), 1.2); - assertThat(acc).isEqualTo(expected); - } - - @Test - void testMergeAccumulation() { - Attributes attributes = Attributes.builder().put("test", "value").build(); - DoubleExemplarData exemplar = - ImmutableDoubleExemplarData.create( - attributes, - 2L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 1); - List exemplars = Collections.singletonList(exemplar); - List previousExemplars = - Collections.singletonList( - ImmutableDoubleExemplarData.create( - attributes, - 1L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 2)); - ExponentialHistogramAccumulation previousAccumulation = - getTestAccumulation(previousExemplars, 0, 4.1, 100, 100, 10000, 1000000); - ExponentialHistogramAccumulation nextAccumulation = - getTestAccumulation(exemplars, -1000, -2000000, -8.2, 2.3); - - // Merged accumulations should equal accumulation with equivalent recordings and latest - // exemplars. - assertThat(aggregator.merge(previousAccumulation, nextAccumulation)) - .isEqualTo( - getTestAccumulation( - exemplars, 0, 4.1, 100, 100, 10000, 1000000, -1000, -2000000, -8.2, 2.3)); - } - - @Test - void testMergeAccumulationMinAndMax() { - // If min / max is null for both accumulations set min / max to null - assertThat( - aggregator.merge( - createAccumulation(/* hasMinMax= */ false, 0, 0), - createAccumulation(/* hasMinMax= */ false, 0, 0))) - .isEqualTo(createAccumulation(/* hasMinMax= */ false, -1, -1)); - // If min / max is non-null for only one accumulation set min / max to it - assertThat( - aggregator.merge( - createAccumulation(/* hasMinMax= */ true, 1d, 2d), - createAccumulation(/* hasMinMax= */ false, 0, 0))) - .isEqualTo(createAccumulation(/* hasMinMax= */ true, 1d, 2d)); - assertThat( - aggregator.merge( - createAccumulation(/* hasMinMax= */ false, 0, 0), - createAccumulation(/* hasMinMax= */ true, 1d, 2d))) - .isEqualTo(createAccumulation(/* hasMinMax= */ true, 1d, 2d)); - // If both accumulations have min / max compute the min / max - assertThat( - aggregator.merge( - createAccumulation(/* hasMinMax= */ true, 1d, 1d), - createAccumulation(/* hasMinMax= */ true, 2d, 2d))) - .isEqualTo(createAccumulation(/* hasMinMax= */ true, 1d, 2d)); - } - - private static ExponentialHistogramAccumulation createAccumulation( - boolean hasMinMax, double min, double max) { - DoubleExponentialHistogramBuckets buckets = - new DoubleExponentialHistogramBuckets( - 0, 1, ExponentialCounterFactory.circularBufferCounter()); - return ExponentialHistogramAccumulation.create( - 0, 0, hasMinMax, min, max, buckets, buckets, 0, Collections.emptyList()); - } - - @Test - void testMergeNonOverlap() { - ExponentialHistogramAccumulation previousAccumulation = - getTestAccumulation(Collections.emptyList(), 10, 100, 100, 10000, 100000); - ExponentialHistogramAccumulation nextAccumulation = - getTestAccumulation(Collections.emptyList(), 0.001, 0.01, 0.1, 1); - - assertThat(aggregator.merge(previousAccumulation, nextAccumulation)) - .isEqualTo( - getTestAccumulation( - Collections.emptyList(), 0.001, 0.01, 0.1, 1, 10, 100, 100, 10000, 100000)); - } - - @Test - void testMergeWithEmptyBuckets() { - assertThat( - aggregator.merge( - getTestAccumulation(Collections.emptyList()), - getTestAccumulation(Collections.emptyList(), 1))) - .isEqualTo(getTestAccumulation(Collections.emptyList(), 1)); - - assertThat( - aggregator.merge( - getTestAccumulation(Collections.emptyList(), 1), - getTestAccumulation(Collections.emptyList()))) - .isEqualTo(getTestAccumulation(Collections.emptyList(), 1)); - - assertThat( - aggregator.merge( - getTestAccumulation(Collections.emptyList()), - getTestAccumulation(Collections.emptyList()))) - .isEqualTo(getTestAccumulation(Collections.emptyList())); - } - - @Test - void testMergeOverlap() { - ExponentialHistogramAccumulation previousAccumulation = - getTestAccumulation(Collections.emptyList(), 0, 10, 100, 10000, 100000); - ExponentialHistogramAccumulation nextAccumulation = - getTestAccumulation(Collections.emptyList(), 100000, 10000, 100, 10, 0); - - assertThat(aggregator.merge(previousAccumulation, nextAccumulation)) - .isEqualTo( - getTestAccumulation( - Collections.emptyList(), 0, 0, 10, 10, 100, 100, 10000, 10000, 100000, 100000)); - } - - @Test - void testInsert1M() { - AggregatorHandle handle = - aggregator.createHandle(); - - double min = 1.0 / (1 << 16); - int n = 1024 * 1024 - 1; - double d = min; - for (int i = 0; i < n; i++) { - handle.recordDouble(d); - d += min; - } - - ExponentialHistogramAccumulation acc = handle.accumulateThenReset(Attributes.empty()); - assertThat(Objects.requireNonNull(acc).getScale()).isEqualTo(4); - assertThat(acc.getPositiveBuckets().getBucketCounts().size()).isEqualTo(320); - assertThat(acc.getPositiveBuckets().getTotalCount()).isEqualTo(n); - } - - @Test - void testDownScale() { - DoubleExponentialHistogramAggregator.Handle handle = - (DoubleExponentialHistogramAggregator.Handle) aggregator.createHandle(); - handle.downScale(20); // down to zero scale - - // test histogram operates properly after being manually scaled down to 0 - handle.recordDouble(0.5); - handle.recordDouble(1.0); - handle.recordDouble(2.0); - handle.recordDouble(4.0); - handle.recordDouble(16.0); - - ExponentialHistogramAccumulation acc = handle.accumulateThenReset(Attributes.empty()); - assertThat(Objects.requireNonNull(acc).getScale()).isEqualTo(0); - ExponentialHistogramBuckets buckets = acc.getPositiveBuckets(); - assertThat(acc.getSum()).isEqualTo(23.5); - assertThat(buckets.getOffset()).isEqualTo(-1); - assertThat(buckets.getBucketCounts()).isEqualTo(Arrays.asList(1L, 1L, 1L, 1L, 0L, 1L)); - assertThat(buckets.getTotalCount()).isEqualTo(5); - } - - @Test - void testToMetricData() { - Attributes attributes = Attributes.builder().put("test", "value").build(); - DoubleExemplarData exemplar = - ImmutableDoubleExemplarData.create( - attributes, - 2L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 1); - @SuppressWarnings("unchecked") - Supplier> reservoirSupplier = - Mockito.mock(Supplier.class); - Mockito.when(reservoir.collectAndReset(Attributes.empty())) - .thenReturn(Collections.singletonList(exemplar)); - Mockito.when(reservoirSupplier.get()).thenReturn(reservoir); - - DoubleExponentialHistogramAggregator cumulativeAggregator = - new DoubleExponentialHistogramAggregator(reservoirSupplier, 20, 320); - - AggregatorHandle aggregatorHandle = - cumulativeAggregator.createHandle(); - aggregatorHandle.recordDouble(0); - aggregatorHandle.recordDouble(0); - aggregatorHandle.recordDouble(123.456); - ExponentialHistogramAccumulation acc = aggregatorHandle.accumulateThenReset(Attributes.empty()); - - MetricData metricDataCumulative = - cumulativeAggregator.toMetricData( - RESOURCE, - INSTRUMENTATION_SCOPE_INFO, - METRIC_DESCRIPTOR, - Collections.singletonMap(Attributes.empty(), acc), - AggregationTemporality.CUMULATIVE, - 0, - 10, - 100); - - // Assertions run twice to verify immutability; recordings shouldn't modify the metric data - for (int i = 0; i < 2; i++) { - MetricAssertions.assertThat(metricDataCumulative) - .hasExponentialHistogram() - .isCumulative() - .points() - .satisfiesExactly( - point -> { - MetricAssertions.assertThat(point) - .hasSum(123.456) - .hasScale(20) - .hasZeroCount(2) - .hasCount(3) - .hasMin(0) - .hasMax(123.456) - .hasExemplars(exemplar); - MetricAssertions.assertThat(point.getPositiveBuckets()) - .hasCounts(Collections.singletonList(1L)) - .hasOffset(valueToIndex(20, 123.456)) - .hasTotalCount(1); - MetricAssertions.assertThat(point.getNegativeBuckets()) - .hasTotalCount(0) - .hasCounts(Collections.emptyList()); - }); - aggregatorHandle.recordDouble(1); - aggregatorHandle.recordDouble(-1); - aggregatorHandle.recordDouble(0); - } - - MetricData metricDataDelta = - cumulativeAggregator.toMetricData( - RESOURCE, - INSTRUMENTATION_SCOPE_INFO, - METRIC_DESCRIPTOR, - Collections.singletonMap(Attributes.empty(), acc), - AggregationTemporality.DELTA, - 0, - 10, - 100); - assertThat(ExponentialHistogramData.fromMetricData(metricDataDelta).getAggregationTemporality()) - .isEqualTo(AggregationTemporality.DELTA); - } - - @Test - void testMultithreadedUpdates() throws InterruptedException { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - ExponentialHistogram summarizer = new ExponentialHistogram(); - ImmutableList updates = ImmutableList.of(0D, 0.1D, -0.1D, 1D, -1D, 100D); - int numberOfThreads = updates.size(); - int numberOfUpdates = 10000; - ThreadPoolExecutor executor = - (ThreadPoolExecutor) Executors.newFixedThreadPool(numberOfThreads); - - executor.invokeAll( - updates.stream() - .map( - v -> - Executors.callable( - () -> { - for (int j = 0; j < numberOfUpdates; j++) { - aggregatorHandle.recordDouble(v); - if (ThreadLocalRandom.current().nextInt(10) == 0) { - summarizer.process( - aggregatorHandle.accumulateThenReset(Attributes.empty())); - } - } - })) - .collect(Collectors.toList())); - - // make sure everything gets merged when all the aggregation is done. - summarizer.process(aggregatorHandle.accumulateThenReset(Attributes.empty())); - - ExponentialHistogramAccumulation acc = Objects.requireNonNull(summarizer.accumulation); - assertThat(acc.getZeroCount()).isEqualTo(numberOfUpdates); - assertThat(acc.getSum()).isCloseTo(100.0D * 10000, Offset.offset(0.0001)); // float error - assertThat(acc.getScale()).isEqualTo(5); - MetricAssertions.assertThat(acc.getPositiveBuckets()) - .hasTotalCount(numberOfUpdates * 3) - .hasOffset(-107); - MetricAssertions.assertThat(acc.getNegativeBuckets()) - .hasTotalCount(numberOfUpdates * 2) - .hasOffset(-107); - - // Verify positive buckets have correct counts - List posCounts = acc.getPositiveBuckets().getBucketCounts(); - assertThat( - posCounts.get(valueToIndex(acc.getScale(), 0.1) - acc.getPositiveBuckets().getOffset())) - .isEqualTo(numberOfUpdates); - assertThat( - posCounts.get(valueToIndex(acc.getScale(), 1) - acc.getPositiveBuckets().getOffset())) - .isEqualTo(numberOfUpdates); - assertThat( - posCounts.get(valueToIndex(acc.getScale(), 100) - acc.getPositiveBuckets().getOffset())) - .isEqualTo(numberOfUpdates); - - // Verify negative buckets have correct counts - List negCounts = acc.getNegativeBuckets().getBucketCounts(); - assertThat( - negCounts.get(valueToIndex(acc.getScale(), 0.1) - acc.getPositiveBuckets().getOffset())) - .isEqualTo(numberOfUpdates); - assertThat( - negCounts.get(valueToIndex(acc.getScale(), 1) - acc.getPositiveBuckets().getOffset())) - .isEqualTo(numberOfUpdates); - } - - private static final class ExponentialHistogram { - private final Object mutex = new Object(); - - @Nullable private ExponentialHistogramAccumulation accumulation; - - void process(@Nullable ExponentialHistogramAccumulation other) { - if (other == null) { - return; - } - - synchronized (mutex) { - if (accumulation == null) { - accumulation = other; - return; - } - accumulation = aggregator.merge(accumulation, other); - } - } - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramBucketsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramBucketsTest.java deleted file mode 100644 index 108af2d95f1..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleExponentialHistogramBucketsTest.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.aggregator; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotEquals; - -import io.opentelemetry.sdk.metrics.internal.state.ExponentialCounterFactory; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; -import java.util.Arrays; -import java.util.Collections; -import java.util.stream.Stream; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -/** - * These are extra test cases for buckets. Much of this class is already tested via more complex - * test cases at {@link DoubleExponentialHistogramAggregatorTest}. - */ -class DoubleExponentialHistogramBucketsTest { - - static Stream bucketStrategies() { - return Stream.of( - ExponentialBucketStrategy.newStrategy(20, 320, ExponentialCounterFactory.mapCounter()), - ExponentialBucketStrategy.newStrategy( - 20, 320, ExponentialCounterFactory.circularBufferCounter())); - } - - @ParameterizedTest - @MethodSource("bucketStrategies") - void testRecordSimple(ExponentialBucketStrategy buckets) { - // Can only effectively test recording of one value here due to downscaling required. - // More complex recording/downscaling operations are tested in the aggregator. - DoubleExponentialHistogramBuckets b = buckets.newBuckets(); - b.record(1); - b.record(1); - b.record(1); - MetricAssertions.assertThat(b).hasTotalCount(3).hasCounts(Collections.singletonList(3L)); - } - - @ParameterizedTest - @MethodSource("bucketStrategies") - void testRecordShouldError(ExponentialBucketStrategy buckets) { - DoubleExponentialHistogramBuckets b = buckets.newBuckets(); - assertThatThrownBy(() -> b.record(0)).isInstanceOf(IllegalStateException.class); - } - - @ParameterizedTest - @MethodSource("bucketStrategies") - void testDownscale(ExponentialBucketStrategy buckets) { - DoubleExponentialHistogramBuckets b = buckets.newBuckets(); - b.downscale(20); // scale of zero is easy to reason with without a calculator - b.record(1); - b.record(2); - b.record(4); - assertThat(b.getScale()).isEqualTo(0); - MetricAssertions.assertThat(b) - .hasTotalCount(3) - .hasCounts(Arrays.asList(1L, 1L, 1L)) - .hasOffset(0); - } - - @ParameterizedTest - @MethodSource("bucketStrategies") - void testDownscaleShouldError(ExponentialBucketStrategy buckets) { - DoubleExponentialHistogramBuckets b = buckets.newBuckets(); - assertThatThrownBy(() -> b.downscale(-1)).isInstanceOf(IllegalStateException.class); - } - - @ParameterizedTest - @MethodSource("bucketStrategies") - void testEqualsAndHashCode(ExponentialBucketStrategy buckets) { - DoubleExponentialHistogramBuckets a = buckets.newBuckets(); - DoubleExponentialHistogramBuckets b = buckets.newBuckets(); - - assertThat(a).isNotNull(); - assertEquals(a, b); - assertEquals(b, a); - assertThat(a).hasSameHashCodeAs(b); - - a.record(1); - assertNotEquals(a, b); - assertNotEquals(b, a); - assertThat(a).doesNotHaveSameHashCodeAs(b); - - b.record(1); - assertEquals(a, b); - assertEquals(b, a); - assertThat(a).hasSameHashCodeAs(b); - - // Now we start to play with altering offset, but having same effective counts. - DoubleExponentialHistogramBuckets empty = buckets.newBuckets(); - empty.downscale(20); - DoubleExponentialHistogramBuckets c = buckets.newBuckets(); - c.downscale(20); - assertThat(c.record(1)).isTrue(); - // Record can fail if scale is not set correctly. - assertThat(c.record(3)).isTrue(); - assertThat(c.getTotalCount()).isEqualTo(2); - } - - @ParameterizedTest - @MethodSource("bucketStrategies") - void testToString(ExponentialBucketStrategy buckets) { - // Note this test may break once difference implementations for counts are developed since - // the counts may have different toStrings(). - DoubleExponentialHistogramBuckets b = buckets.newBuckets(); - b.record(1); - assertThat(b.toString()) - .isEqualTo("DoubleExponentialHistogramBuckets{scale: 20, offset: 0, counts: {0=1} }"); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java index 1b5df5b6fd0..0485ca2669a 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleLastValueAggregatorTest.java @@ -7,21 +7,29 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.MutableDoublePointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** Unit tests for {@link AggregatorHandle}. */ class DoubleLastValueAggregatorTest { @@ -30,42 +38,67 @@ class DoubleLastValueAggregatorTest { InstrumentationScopeInfo.empty(); private static final MetricDescriptor METRIC_DESCRIPTOR = MetricDescriptor.create("name", "description", "unit"); - private static final DoubleLastValueAggregator aggregator = - new DoubleLastValueAggregator(ExemplarReservoir::doubleNoSamples); + private DoubleLastValueAggregator aggregator; - @Test - void createHandle() { - assertThat(aggregator.createHandle()).isInstanceOf(DoubleLastValueAggregator.Handle.class); + private void init(MemoryMode memoryMode) { + aggregator = new DoubleLastValueAggregator(ExemplarReservoirFactory.noSamples(), memoryMode); } - @Test - void multipleRecords() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(12.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(12.1); - aggregatorHandle.recordDouble(13.1); - aggregatorHandle.recordDouble(14.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(14.1); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void createHandle(MemoryMode memoryMode) { + init(memoryMode); + assertThat(aggregator.createHandle(0)).isInstanceOf(DoubleLastValueAggregator.Handle.class); } - @Test - void toAccumulationAndReset() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordDouble(13.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(13.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordDouble(12.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(12.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void multipleRecords(MemoryMode memoryMode) { + init(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(12.1); + aggregatorHandle.recordDouble(13.1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(14.1, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(14.1); } - @Test - void mergeAccumulation() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset(MemoryMode memoryMode) { + init(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordDouble(13.1, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(13.1); + + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(12.1); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void diff(MemoryMode memoryMode) { + init(memoryMode); + Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -89,16 +122,20 @@ void mergeAccumulation() { TraceFlags.getDefault(), TraceState.getDefault()), 2)); - DoubleAccumulation result = - aggregator.merge( - DoubleAccumulation.create(1, previousExemplars), - DoubleAccumulation.create(2, exemplars)); + DoublePointData result = + aggregator.diff( + ImmutableDoublePointData.create(0, 1, Attributes.empty(), 1, previousExemplars), + ImmutableDoublePointData.create(0, 1, Attributes.empty(), 2, exemplars)); // Assert that latest measurement is kept. - assertThat(result).isEqualTo(DoubleAccumulation.create(2, exemplars)); + assertThat(result) + .isEqualTo(ImmutableDoublePointData.create(0, 1, Attributes.empty(), 2, exemplars)); } - @Test - void diffAccumulation() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void diffInPlace(MemoryMode memoryMode) { + init(memoryMode); + Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -122,44 +159,117 @@ void diffAccumulation() { TraceFlags.getDefault(), TraceState.getDefault()), 2)); - DoubleAccumulation result = - aggregator.diff( - DoubleAccumulation.create(1, previousExemplars), - DoubleAccumulation.create(2, exemplars)); - // Assert that latest measurement is kept. - assertThat(result).isEqualTo(DoubleAccumulation.create(2, exemplars)); + + MutableDoublePointData previous = new MutableDoublePointData(); + MutableDoublePointData current = new MutableDoublePointData(); + + previous.set(0, 1, Attributes.empty(), 1, previousExemplars); + current.set(0, 1, Attributes.empty(), 2, exemplars); + + aggregator.diffInPlace(previous, current); + + /* Assert that latest measurement is kept and set on {@code previous} */ + assertThat(previous.getStartEpochNanos()).isEqualTo(0); + assertThat(previous.getEpochNanos()).isEqualTo(1); + assertThat(previous.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(previous.getValue()).isEqualTo(2); + assertThat(previous.getExemplars()).isEqualTo(exemplars); } - @Test - @SuppressWarnings("unchecked") - void toMetricData() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(10); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void copyPoint(MemoryMode memoryMode) { + init(memoryMode); + + MutableDoublePointData pointData = (MutableDoublePointData) aggregator.createReusablePoint(); + + Attributes attributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsFrom = + Collections.singletonList( + ImmutableDoubleExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1)); + pointData.set(0, 1, attributes, 2000, exemplarsFrom); + + MutableDoublePointData toPointData = (MutableDoublePointData) aggregator.createReusablePoint(); + + Attributes toAttributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsTo = + Collections.singletonList( + ImmutableDoubleExemplarData.create( + attributes, + 4L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 2)); + toPointData.set(0, 2, toAttributes, 4000, exemplarsTo); + + aggregator.copyPoint(pointData, toPointData); + + assertThat(toPointData.getStartEpochNanos()).isEqualTo(pointData.getStartEpochNanos()); + assertThat(toPointData.getEpochNanos()).isEqualTo(pointData.getEpochNanos()); + assertThat(toPointData.getAttributes()).isEqualTo(pointData.getAttributes()); + assertThat(toPointData.getValue()).isEqualTo(pointData.getValue()); + assertThat(toPointData.getExemplars()).isEqualTo(pointData.getExemplars()); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricData(MemoryMode memoryMode) { + init(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(10, Attributes.empty(), Context.current()); MetricData metricData = aggregator.toMetricData( RESOURCE, INSTRUMENTATION_SCOPE_INFO, METRIC_DESCRIPTOR, - Collections.singletonMap( - Attributes.empty(), aggregatorHandle.accumulateThenReset(Attributes.empty())), - AggregationTemporality.DELTA, - 0, - 10, - 100); + Collections.singletonList( + aggregatorHandle.aggregateThenMaybeReset( + 10, 100, Attributes.empty(), /* reset= */ true)), + AggregationTemporality.DELTA); assertThat(metricData) .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasAttributes(Attributes.empty()) - .hasStartEpochNanos(10) - .hasEpochNanos(100) - .hasValue(10))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point + .hasAttributes(Attributes.empty()) + .hasStartEpochNanos(10) + .hasEpochNanos(100) + .hasValue(10))); + } + + @Test + void testReusableDataOnCollect() { + init(MemoryMode.REUSABLE_DATA); + AggregatorHandle handle = aggregator.createHandle(0); + handle.recordDouble(1, Attributes.empty(), Context.current()); + DoublePointData pointData = + handle.aggregateThenMaybeReset(0, 10, Attributes.empty(), /* reset= */ false); + + handle.recordDouble(1, Attributes.empty(), Context.current()); + DoublePointData pointData2 = + handle.aggregateThenMaybeReset(0, 10, Attributes.empty(), /* reset= */ false); + + assertThat(pointData).isSameAs(pointData2); + + handle.recordDouble(1, Attributes.empty(), Context.current()); + DoublePointData pointDataWithReset = + handle.aggregateThenMaybeReset(0, 10, Attributes.empty(), /* reset= */ true); + + assertThat(pointData).isSameAs(pointDataWithReset); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java index 5f287e310ca..04b92566f9d 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/DoubleSumAggregatorTest.java @@ -7,26 +7,36 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.DoublePointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.MutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; import io.opentelemetry.sdk.resources.Resource; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @@ -35,73 +45,109 @@ @ExtendWith(MockitoExtension.class) class DoubleSumAggregatorTest { - @Mock ExemplarReservoir reservoir; + @Mock DoubleExemplarReservoir reservoir; + private final ExemplarReservoirFactory reservoirFactory = + new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + return reservoir; + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + throw new UnsupportedOperationException(); + } + }; private static final Resource resource = Resource.getDefault(); private static final InstrumentationScopeInfo scope = InstrumentationScopeInfo.empty(); private static final MetricDescriptor metricDescriptor = MetricDescriptor.create("name", "description", "unit"); - private static final DoubleSumAggregator aggregator = - new DoubleSumAggregator( - InstrumentDescriptor.create( - "instrument_name", - "instrument_description", - "instrument_unit", - InstrumentType.COUNTER, - InstrumentValueType.DOUBLE), - ExemplarReservoir::doubleNoSamples); + private DoubleSumAggregator aggregator; - @Test - void createHandle() { - assertThat(aggregator.createHandle()).isInstanceOf(DoubleSumAggregator.Handle.class); + private void init(MemoryMode memoryMode) { + aggregator = + new DoubleSumAggregator( + InstrumentDescriptor.create( + "instrument_name", + "instrument_description", + "instrument_unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty()), + ExemplarReservoirFactory.noSamples(), + memoryMode); } - @Test - void multipleRecords() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(12.1); - aggregatorHandle.recordDouble(12.1); - aggregatorHandle.recordDouble(12.1); - aggregatorHandle.recordDouble(12.1); - aggregatorHandle.recordDouble(12.1); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()) + @ParameterizedTest + @EnumSource(MemoryMode.class) + void createHandle(MemoryMode memoryMode) { + init(memoryMode); + assertThat(aggregator.createHandle(0)).isInstanceOf(DoubleSumAggregator.Handle.class); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void multipleRecords(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12.1, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) .isEqualTo(12.1 * 5); } - @Test - void multipleRecords_WithNegatives() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(12); - aggregatorHandle.recordDouble(12); - aggregatorHandle.recordDouble(-23); - aggregatorHandle.recordDouble(12); - aggregatorHandle.recordDouble(12); - aggregatorHandle.recordDouble(-11); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(14); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void multipleRecords_WithNegatives(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-23, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-11, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(14); } - @Test - void toAccumulationAndReset() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordDouble(13); - aggregatorHandle.recordDouble(12); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(25); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordDouble(12); - aggregatorHandle.recordDouble(-25); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(-13); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordDouble(13, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(12, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(25); + + aggregatorHandle.recordDouble(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordDouble(-25, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(-13); } - @Test - void testExemplarsInAccumulation() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset_WithExemplars(MemoryMode memoryMode) { Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -114,7 +160,7 @@ void testExemplarsInAccumulation() { TraceState.getDefault()), 1); List exemplars = Collections.singletonList(exemplar); - Mockito.when(reservoir.collectAndReset(Attributes.empty())).thenReturn(exemplars); + Mockito.when(reservoir.collectAndResetDoubles(Attributes.empty())).thenReturn(exemplars); DoubleSumAggregator aggregator = new DoubleSumAggregator( InstrumentDescriptor.create( @@ -122,17 +168,20 @@ void testExemplarsInAccumulation() { "instrument_description", "instrument_unit", InstrumentType.COUNTER, - InstrumentValueType.DOUBLE), - () -> reservoir); - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); + InstrumentValueType.DOUBLE, + Advice.empty()), + reservoirFactory, + memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); aggregatorHandle.recordDouble(0, attributes, Context.root()); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())) - .isEqualTo(DoubleAccumulation.create(0, exemplars)); + assertThat( + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)) + .isEqualTo(ImmutableDoublePointData.create(0, 1, Attributes.empty(), 0, exemplars)); } - @Test - void mergeAndDiff() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void mergeAndDiff(MemoryMode memoryMode) { Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -145,85 +194,158 @@ void mergeAndDiff() { TraceState.getDefault()), 1); List exemplars = Collections.singletonList(exemplar); - List previousExemplars = - Collections.singletonList( - ImmutableDoubleExemplarData.create( - attributes, - 1L, - SpanContext.create( - "00000000000000000000000000000001", - "0000000000000002", - TraceFlags.getDefault(), - TraceState.getDefault()), - 2)); for (InstrumentType instrumentType : InstrumentType.values()) { for (AggregationTemporality temporality : AggregationTemporality.values()) { DoubleSumAggregator aggregator = new DoubleSumAggregator( InstrumentDescriptor.create( - "name", "description", "unit", instrumentType, InstrumentValueType.LONG), - ExemplarReservoir::doubleNoSamples); - DoubleAccumulation merged = - aggregator.merge( - DoubleAccumulation.create(1.0d, previousExemplars), - DoubleAccumulation.create(2.0d, exemplars)); - assertThat(merged.getValue()) - .withFailMessage( - "Invalid merge result for instrumentType %s, temporality %s: %s", - instrumentType, temporality, merged) - .isEqualTo(3.0d); - assertThat(merged.getExemplars()).containsExactly(exemplar); + "name", + "description", + "unit", + instrumentType, + InstrumentValueType.LONG, + Advice.empty()), + ExemplarReservoirFactory.noSamples(), + memoryMode); - DoubleAccumulation diffed = + DoublePointData diffed = aggregator.diff( - DoubleAccumulation.create(1d), DoubleAccumulation.create(2d, exemplars)); + ImmutableDoublePointData.create(0, 1, Attributes.empty(), 1d), + ImmutableDoublePointData.create(0, 1, Attributes.empty(), 2d, exemplars)); assertThat(diffed.getValue()) .withFailMessage( "Invalid diff result for instrumentType %s, temporality %s: %s", - instrumentType, temporality, merged) + instrumentType, temporality, diffed) .isEqualTo(1d); assertThat(diffed.getExemplars()).containsExactly(exemplar); } } } - @Test - @SuppressWarnings("unchecked") - void toMetricData() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordDouble(10); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void diffInPlace(MemoryMode memoryMode) { + init(memoryMode); + Attributes attributes = Attributes.builder().put("test", "value").build(); + DoubleExemplarData exemplar = + ImmutableDoubleExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1); + List exemplars = Collections.singletonList(exemplar); + List previousExemplars = + Collections.singletonList( + ImmutableDoubleExemplarData.create( + attributes, + 1L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 2)); + + MutableDoublePointData previous = new MutableDoublePointData(); + MutableDoublePointData current = new MutableDoublePointData(); + + previous.set(0, 1, Attributes.empty(), 1, previousExemplars); + current.set(0, 1, Attributes.empty(), 3, exemplars); + + aggregator.diffInPlace(previous, current); + + /* Assert that latest measurement is kept and set on {@code previous} */ + assertThat(previous.getStartEpochNanos()).isEqualTo(current.getStartEpochNanos()); + assertThat(previous.getEpochNanos()).isEqualTo(current.getEpochNanos()); + assertThat(previous.getAttributes()).isEqualTo(current.getAttributes()); + assertThat(previous.getValue()).isEqualTo(2); + assertThat(previous.getExemplars()).isEqualTo(exemplars); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void copyPoint(MemoryMode memoryMode) { + init(memoryMode); + MutableDoublePointData pointData = (MutableDoublePointData) aggregator.createReusablePoint(); + + Attributes attributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsFrom = + Collections.singletonList( + ImmutableDoubleExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1)); + pointData.set(0, 1, attributes, 2000, exemplarsFrom); + + MutableDoublePointData toPointData = (MutableDoublePointData) aggregator.createReusablePoint(); + + Attributes toAttributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsTo = + Collections.singletonList( + ImmutableDoubleExemplarData.create( + attributes, + 4L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 2)); + toPointData.set(0, 2, toAttributes, 4000, exemplarsTo); + + aggregator.copyPoint(pointData, toPointData); + + assertThat(toPointData.getStartEpochNanos()).isEqualTo(pointData.getStartEpochNanos()); + assertThat(toPointData.getEpochNanos()).isEqualTo(pointData.getEpochNanos()); + assertThat(toPointData.getAttributes()).isEqualTo(pointData.getAttributes()); + assertThat(toPointData.getValue()).isEqualTo(pointData.getValue()); + assertThat(toPointData.getExemplars()).isEqualTo(pointData.getExemplars()); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricData(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(10, Attributes.empty(), Context.current()); MetricData metricData = aggregator.toMetricData( resource, scope, metricDescriptor, - Collections.singletonMap( - Attributes.empty(), aggregatorHandle.accumulateThenReset(Attributes.empty())), - AggregationTemporality.CUMULATIVE, - 0, - 10, - 100); + Collections.singletonList( + aggregatorHandle.aggregateThenMaybeReset( + 0, 100, Attributes.empty(), /* reset= */ true)), + AggregationTemporality.CUMULATIVE); assertThat(metricData) .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(100) - .hasAttributes(Attributes.empty()) - .hasValue(10))); + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(0) + .hasEpochNanos(100) + .hasAttributes(Attributes.empty()) + .hasValue(10))); } - @Test - void toMetricDataWithExemplars() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricDataWithExemplars(MemoryMode memoryMode) { + init(memoryMode); Attributes attributes = Attributes.builder().put("test", "value").build(); DoubleExemplarData exemplar = ImmutableDoubleExemplarData.create( @@ -235,19 +357,33 @@ void toMetricDataWithExemplars() { TraceFlags.getDefault(), TraceState.getDefault()), 1); - DoubleAccumulation accumulation = - DoubleAccumulation.create(1, Collections.singletonList(exemplar)); assertThat( aggregator.toMetricData( resource, scope, metricDescriptor, - Collections.singletonMap(Attributes.empty(), accumulation), - AggregationTemporality.CUMULATIVE, - 0, - 10, - 100)) + Collections.singletonList( + ImmutableDoublePointData.create( + 0, 1, Attributes.empty(), 1, Collections.singletonList(exemplar))), + AggregationTemporality.CUMULATIVE)) .hasDoubleSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(1).hasExemplars(exemplar))); } + + @Test + void sameObjectReturnedOnReusableDataMemoryMode() { + init(MemoryMode.REUSABLE_DATA); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordDouble(1.0, Attributes.empty(), Context.current()); + + DoublePointData firstCollection = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false); + + aggregatorHandle.recordDouble(1.0, Attributes.empty(), Context.current()); + DoublePointData secondCollection = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false); + + // Should be same object since we are in REUSABLE_DATA mode. + assertThat(firstCollection).isSameAs(secondCollection); + } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregatorTest.java index c64c6f0fb4c..dc24e8011be 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongLastValueAggregatorTest.java @@ -7,24 +7,31 @@ import static org.assertj.core.api.Assertions.assertThat; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongExemplarData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.MutableLongPointData; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; import io.opentelemetry.sdk.resources.Resource; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** Unit tests for {@link LongLastValueAggregator}. */ class LongLastValueAggregatorTest { @@ -33,42 +40,65 @@ class LongLastValueAggregatorTest { InstrumentationScopeInfo.empty(); private static final MetricDescriptor METRIC_DESCRIPTOR = MetricDescriptor.create("name", "description", "unit"); - private static final LongLastValueAggregator aggregator = - new LongLastValueAggregator(ExemplarReservoir::longNoSamples); + private LongLastValueAggregator aggregator; - @Test - void createHandle() { - assertThat(aggregator.createHandle()).isInstanceOf(LongLastValueAggregator.Handle.class); + private void init(MemoryMode memoryMode) { + aggregator = new LongLastValueAggregator(ExemplarReservoirFactory.noSamples(), memoryMode); } - @Test - void multipleRecords() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(12); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(12L); - aggregatorHandle.recordLong(13); - aggregatorHandle.recordLong(14); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(14L); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void createHandle(MemoryMode memoryMode) { + init(memoryMode); + assertThat(aggregator.createHandle(0)).isInstanceOf(LongLastValueAggregator.Handle.class); } - @Test - void toAccumulationAndReset() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordLong(13); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(13L); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordLong(12); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(12L); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void multipleRecords(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(12L); + aggregatorHandle.recordLong(13, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(14, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(14L); } - @Test - void mergeAccumulation() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordLong(13, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(13L); + + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(12L); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void diffInPlace(MemoryMode memoryMode) { + init(memoryMode); + Attributes attributes = Attributes.builder().put("test", "value").build(); LongExemplarData exemplar = ImmutableLongExemplarData.create( @@ -92,30 +122,86 @@ void mergeAccumulation() { TraceFlags.getDefault(), TraceState.getDefault()), 2)); - LongAccumulation result = - aggregator.merge( - LongAccumulation.create(1, previousExemplars), LongAccumulation.create(2, exemplars)); - // Assert that latest measurement is kept. - assertThat(result).isEqualTo(LongAccumulation.create(2, exemplars)); + + MutableLongPointData previous = new MutableLongPointData(); + MutableLongPointData current = new MutableLongPointData(); + + previous.set(0, 1, Attributes.empty(), 1, previousExemplars); + current.set(0, 1, Attributes.empty(), 2, exemplars); + + aggregator.diffInPlace(previous, current); + + /* Assert that latest measurement is kept and set on {@code previous} */ + assertThat(previous.getStartEpochNanos()).isEqualTo(0); + assertThat(previous.getEpochNanos()).isEqualTo(1); + assertThat(previous.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(previous.getValue()).isEqualTo(2); + assertThat(previous.getExemplars()).isEqualTo(exemplars); } - @Test - void toMetricData() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(10); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void copyPoint(MemoryMode memoryMode) { + init(memoryMode); + + MutableLongPointData pointData = (MutableLongPointData) aggregator.createReusablePoint(); + + Attributes attributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsFrom = + Collections.singletonList( + ImmutableLongExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1)); + pointData.set(0, 1, attributes, 2000, exemplarsFrom); + + MutableLongPointData toPointData = (MutableLongPointData) aggregator.createReusablePoint(); + + Attributes toAttributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsTo = + Collections.singletonList( + ImmutableLongExemplarData.create( + attributes, + 4L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 2)); + toPointData.set(0, 2, toAttributes, 4000, exemplarsTo); + + aggregator.copyPoint(pointData, toPointData); + + assertThat(toPointData.getStartEpochNanos()).isEqualTo(pointData.getStartEpochNanos()); + assertThat(toPointData.getEpochNanos()).isEqualTo(pointData.getEpochNanos()); + assertThat(toPointData.getAttributes()).isEqualTo(pointData.getAttributes()); + assertThat(toPointData.getValue()).isEqualTo(pointData.getValue()); + assertThat(toPointData.getExemplars()).isEqualTo(pointData.getExemplars()); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricData(MemoryMode memoryMode) { + init(memoryMode); + + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(10, Attributes.empty(), Context.current()); MetricData metricData = aggregator.toMetricData( RESOURCE, INSTRUMENTATION_SCOPE_INFO, METRIC_DESCRIPTOR, - Collections.singletonMap( - Attributes.empty(), aggregatorHandle.accumulateThenReset(Attributes.empty())), - AggregationTemporality.CUMULATIVE, - 2, - 10, - 100); + Collections.singletonList( + aggregatorHandle.aggregateThenMaybeReset( + 2, 100, Attributes.empty(), /* reset= */ true)), + AggregationTemporality.CUMULATIVE); assertThat(metricData) .isEqualTo( ImmutableMetricData.createLongGauge( @@ -128,4 +214,24 @@ void toMetricData() { Collections.singletonList( ImmutableLongPointData.create(2, 100, Attributes.empty(), 10))))); } + + @Test + void testReusablePointOnCollect() { + init(MemoryMode.REUSABLE_DATA); + AggregatorHandle handle = aggregator.createHandle(0); + handle.recordLong(1, Attributes.empty(), Context.current()); + LongPointData pointData = + handle.aggregateThenMaybeReset(0, 10, Attributes.empty(), /* reset= */ false); + + handle.recordLong(1, Attributes.empty(), Context.current()); + LongPointData pointData2 = + handle.aggregateThenMaybeReset(0, 10, Attributes.empty(), /* reset= */ false); + + assertThat(pointData).isSameAs(pointData2); + + LongPointData pointDataWithReset = + handle.aggregateThenMaybeReset(0, 10, Attributes.empty(), /* reset= */ true); + + assertThat(pointData).isSameAs(pointDataWithReset); + } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java index 5598287f8d2..c0fc8ec2e2d 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/aggregator/LongSumAggregatorTest.java @@ -7,26 +7,36 @@ import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongExemplarData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.data.MutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.DoubleExemplarReservoir; +import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarReservoirFactory; +import io.opentelemetry.sdk.metrics.internal.exemplar.LongExemplarReservoir; import io.opentelemetry.sdk.resources.Resource; import java.util.Collections; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; @@ -35,74 +45,108 @@ @ExtendWith(MockitoExtension.class) class LongSumAggregatorTest { - @Mock ExemplarReservoir reservoir; + @Mock LongExemplarReservoir reservoir; + private final ExemplarReservoirFactory reservoirFactory = + new ExemplarReservoirFactory() { + @Override + public DoubleExemplarReservoir createDoubleExemplarReservoir() { + throw new UnsupportedOperationException(); + } + + @Override + public LongExemplarReservoir createLongExemplarReservoir() { + return reservoir; + } + }; private static final Resource resource = Resource.getDefault(); private static final InstrumentationScopeInfo library = InstrumentationScopeInfo.empty(); private static final MetricDescriptor metricDescriptor = MetricDescriptor.create("name", "description", "unit"); - private static final LongSumAggregator aggregator = - new LongSumAggregator( - InstrumentDescriptor.create( - "instrument_name", - "instrument_description", - "instrument_unit", - InstrumentType.COUNTER, - InstrumentValueType.LONG), - ExemplarReservoir::longNoSamples); + private LongSumAggregator aggregator; - @Test - void createHandle() { - assertThat(aggregator.createHandle()).isInstanceOf(LongSumAggregator.Handle.class); + private void init(MemoryMode memoryMode) { + aggregator = + new LongSumAggregator( + InstrumentDescriptor.create( + "instrument_name", + "instrument_description", + "instrument_unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), + ExemplarReservoirFactory.noSamples(), + memoryMode); } - @Test - void multipleRecords() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(12); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()) + @ParameterizedTest + @EnumSource(MemoryMode.class) + void createHandle(MemoryMode memoryMode) { + init(memoryMode); + assertThat(aggregator.createHandle(0)).isInstanceOf(LongSumAggregator.Handle.class); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void multipleRecords(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) .isEqualTo(12 * 5); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); } - @Test - void multipleRecords_WithNegatives() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(-23); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(-11); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(14); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void multipleRecords_WithNegatives(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(-23, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(-11, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(14); } - @Test - void toAccumulationAndReset() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordLong(13); - aggregatorHandle.recordLong(12); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(25); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); - - aggregatorHandle.recordLong(12); - aggregatorHandle.recordLong(-25); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty()).getValue()).isEqualTo(-13); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())).isNull(); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordLong(13, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(25); + + aggregatorHandle.recordLong(12, Attributes.empty(), Context.current()); + aggregatorHandle.recordLong(-25, Attributes.empty(), Context.current()); + assertThat( + aggregatorHandle + .aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true) + .getValue()) + .isEqualTo(-13); } - @Test - void testExemplarsInAccumulation() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void aggregateThenMaybeReset_WithExemplars(MemoryMode memoryMode) { Attributes attributes = Attributes.builder().put("test", "value").build(); LongExemplarData exemplar = ImmutableLongExemplarData.create( @@ -115,7 +159,7 @@ void testExemplarsInAccumulation() { TraceState.getDefault()), 1); List exemplars = Collections.singletonList(exemplar); - Mockito.when(reservoir.collectAndReset(Attributes.empty())).thenReturn(exemplars); + Mockito.when(reservoir.collectAndResetLongs(Attributes.empty())).thenReturn(exemplars); LongSumAggregator aggregator = new LongSumAggregator( InstrumentDescriptor.create( @@ -123,17 +167,20 @@ void testExemplarsInAccumulation() { "instrument_description", "instrument_unit", InstrumentType.COUNTER, - InstrumentValueType.LONG), - () -> reservoir); - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); + InstrumentValueType.LONG, + Advice.empty()), + reservoirFactory, + memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); aggregatorHandle.recordLong(0, attributes, Context.root()); - assertThat(aggregatorHandle.accumulateThenReset(Attributes.empty())) - .isEqualTo(LongAccumulation.create(0, exemplars)); + assertThat( + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true)) + .isEqualTo(ImmutableLongPointData.create(0, 1, Attributes.empty(), 0, exemplars)); } - @Test - void mergeAndDiff() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void mergeAndDiff(MemoryMode memoryMode) { LongExemplarData exemplar = ImmutableLongExemplarData.create( Attributes.empty(), @@ -150,66 +197,153 @@ void mergeAndDiff() { LongSumAggregator aggregator = new LongSumAggregator( InstrumentDescriptor.create( - "name", "description", "unit", instrumentType, InstrumentValueType.LONG), - ExemplarReservoir::longNoSamples); - LongAccumulation merged = - aggregator.merge(LongAccumulation.create(1L), LongAccumulation.create(2L, exemplars)); - assertThat(merged.getValue()) - .withFailMessage( - "Invalid merge result for instrumentType %s, temporality %s: %s", - instrumentType, temporality, merged) - .isEqualTo(3); - assertThat(merged.getExemplars()).containsExactly(exemplar); + "name", + "description", + "unit", + instrumentType, + InstrumentValueType.LONG, + Advice.empty()), + ExemplarReservoirFactory.noSamples(), + memoryMode); - LongAccumulation diffed = - aggregator.diff(LongAccumulation.create(1L), LongAccumulation.create(2L, exemplars)); + LongPointData diffed = + aggregator.diff( + ImmutableLongPointData.create(0, 1, Attributes.empty(), 1L), + ImmutableLongPointData.create(0, 1, Attributes.empty(), 2L, exemplars)); assertThat(diffed.getValue()) .withFailMessage( "Invalid diff result for instrumentType %s, temporality %s: %s", - instrumentType, temporality, merged) + instrumentType, temporality, diffed) .isEqualTo(1); assertThat(diffed.getExemplars()).containsExactly(exemplar); } } } - @Test - @SuppressWarnings("unchecked") - void toMetricData() { - AggregatorHandle aggregatorHandle = - aggregator.createHandle(); - aggregatorHandle.recordLong(10); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void diffInPlace(MemoryMode memoryMode) { + init(memoryMode); + Attributes attributes = Attributes.builder().put("test", "value").build(); + LongExemplarData exemplar = + ImmutableLongExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1); + List exemplars = Collections.singletonList(exemplar); + List previousExemplars = + Collections.singletonList( + ImmutableLongExemplarData.create( + attributes, + 1L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 2)); + + MutableLongPointData previous = new MutableLongPointData(); + MutableLongPointData current = new MutableLongPointData(); + + previous.set(0, 1, Attributes.empty(), 1, previousExemplars); + current.set(0, 1, Attributes.empty(), 3, exemplars); + + aggregator.diffInPlace(previous, current); + + /* Assert that latest measurement is kept and set on {@code previous} */ + assertThat(previous.getStartEpochNanos()).isEqualTo(current.getStartEpochNanos()); + assertThat(previous.getEpochNanos()).isEqualTo(current.getEpochNanos()); + assertThat(previous.getAttributes()).isEqualTo(current.getAttributes()); + assertThat(previous.getValue()).isEqualTo(2); + assertThat(previous.getExemplars()).isEqualTo(current.getExemplars()); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void copyPoint(MemoryMode memoryMode) { + init(memoryMode); + MutableLongPointData pointData = (MutableLongPointData) aggregator.createReusablePoint(); + + Attributes attributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsFrom = + Collections.singletonList( + ImmutableLongExemplarData.create( + attributes, + 2L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 1)); + pointData.set(0, 1, attributes, 2000, exemplarsFrom); + + MutableLongPointData toPointData = (MutableLongPointData) aggregator.createReusablePoint(); + + Attributes toAttributes = Attributes.of(AttributeKey.longKey("test"), 100L); + List exemplarsTo = + Collections.singletonList( + ImmutableLongExemplarData.create( + attributes, + 4L, + SpanContext.create( + "00000000000000000000000000000001", + "0000000000000002", + TraceFlags.getDefault(), + TraceState.getDefault()), + 2)); + toPointData.set(0, 2, toAttributes, 4000, exemplarsTo); + + aggregator.copyPoint(pointData, toPointData); + + assertThat(toPointData.getStartEpochNanos()).isEqualTo(pointData.getStartEpochNanos()); + assertThat(toPointData.getEpochNanos()).isEqualTo(pointData.getEpochNanos()); + assertThat(toPointData.getAttributes()).isEqualTo(pointData.getAttributes()); + assertThat(toPointData.getValue()).isEqualTo(pointData.getValue()); + assertThat(toPointData.getExemplars()).isEqualTo(pointData.getExemplars()); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricData(MemoryMode memoryMode) { + init(memoryMode); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + aggregatorHandle.recordLong(10, Attributes.empty(), Context.current()); MetricData metricData = aggregator.toMetricData( resource, library, metricDescriptor, - Collections.singletonMap( - Attributes.empty(), aggregatorHandle.accumulateThenReset(Attributes.empty())), - AggregationTemporality.CUMULATIVE, - 0, - 10, - 100); + Collections.singletonList( + aggregatorHandle.aggregateThenMaybeReset( + 0, 100, Attributes.empty(), /* reset= */ true)), + AggregationTemporality.CUMULATIVE); assertThat(metricData) .hasName("name") .hasDescription("description") .hasUnit("unit") - .hasLongSumSatisfying( - sum -> - sum.isCumulative() - .isMonotonic() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(100) - .hasAttributes(Attributes.empty()) - .hasValue(10))); + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .isMonotonic() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(0) + .hasEpochNanos(100) + .hasAttributes(Attributes.empty()) + .hasValue(10))); } - @Test - void toMetricDataWithExemplars() { + @ParameterizedTest + @EnumSource(MemoryMode.class) + void toMetricDataWithExemplars(MemoryMode memoryMode) { + init(memoryMode); Attributes attributes = Attributes.builder().put("test", "value").build(); LongExemplarData exemplar = ImmutableLongExemplarData.create( @@ -221,18 +355,34 @@ void toMetricDataWithExemplars() { TraceFlags.getDefault(), TraceState.getDefault()), 1); - LongAccumulation accumulation = LongAccumulation.create(1, Collections.singletonList(exemplar)); + assertThat( aggregator.toMetricData( resource, library, metricDescriptor, - Collections.singletonMap(Attributes.empty(), accumulation), - AggregationTemporality.CUMULATIVE, - 0, - 10, - 100)) + Collections.singletonList( + ImmutableLongPointData.create( + 0, 1, Attributes.empty(), 1, Collections.singletonList(exemplar))), + AggregationTemporality.CUMULATIVE)) .hasLongSumSatisfying( sum -> sum.hasPointsSatisfying(point -> point.hasValue(1).hasExemplars(exemplar))); } + + @Test + void sameObjectReturnedOnReusableDataMemoryMode() { + init(MemoryMode.REUSABLE_DATA); + AggregatorHandle aggregatorHandle = aggregator.createHandle(0); + + aggregatorHandle.recordLong(1L, Attributes.empty(), Context.current()); + LongPointData firstCollection = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false); + + aggregatorHandle.recordLong(1L, Attributes.empty(), Context.current()); + LongPointData secondCollection = + aggregatorHandle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ false); + + // Should be same object since we are in REUSABLE_DATA mode. + assertThat(firstCollection).isSameAs(secondCollection); + } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramBucketsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramBucketsTest.java new file mode 100644 index 00000000000..39c1947cefe --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramBucketsTest.java @@ -0,0 +1,46 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import org.junit.jupiter.api.Test; + +class MutableExponentialHistogramBucketsTest { + + @Test + void testSanity() { + MutableExponentialHistogramBuckets buckets = new MutableExponentialHistogramBuckets(); + assertThat(buckets.getScale()).isEqualTo(0); + assertThat(buckets.getOffset()).isEqualTo(0); + assertThat(buckets.getTotalCount()).isEqualTo(0); + assertThat(buckets.getBucketCounts()).isEmpty(); + assertThat(buckets.getReusableBucketCountsList()).isEmpty(); + + DynamicPrimitiveLongList bucketCounts = DynamicPrimitiveLongList.of(1, 2, 3); + buckets.set(1, 2, 3, bucketCounts); + + assertThat(buckets.getScale()).isEqualTo(1); + assertThat(buckets.getOffset()).isEqualTo(2); + assertThat(buckets.getTotalCount()).isEqualTo(3); + assertThat(buckets.getBucketCounts()).containsExactly(1L, 2L, 3L); + assertThat(buckets.getReusableBucketCountsList()).containsExactly(1L, 2L, 3L); + + assertThat(buckets.toString()) + .isEqualTo( + "MutableExponentialHistogramBuckets{scale=1, offset=2, bucketCounts=[1, 2, 3], totalCount=3}"); + + MutableExponentialHistogramBuckets sameBuckets = new MutableExponentialHistogramBuckets(); + sameBuckets.set(1, 2, 3, DynamicPrimitiveLongList.of(1, 2, 3)); + assertThat(sameBuckets).isEqualTo(buckets); + assertThat(sameBuckets.hashCode()).isEqualTo(buckets.hashCode()); + + sameBuckets.set(1, 2, 3, DynamicPrimitiveLongList.of(1, 20, 3)); + assertThat(sameBuckets).isNotEqualTo(buckets); + assertThat(sameBuckets.hashCode()).isNotEqualTo(buckets.hashCode()); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramPointDataTest.java new file mode 100644 index 00000000000..ca812dc73c6 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableExponentialHistogramPointDataTest.java @@ -0,0 +1,114 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.common.internal.DynamicPrimitiveLongList; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class MutableExponentialHistogramPointDataTest { + + @Test + public void testSanity() { + MutableExponentialHistogramPointData pointData = new MutableExponentialHistogramPointData(); + assertThat(pointData.getSum()).isEqualTo(0); + assertThat(pointData.getCount()).isEqualTo(0); + assertThat(pointData.getPositiveBuckets().getTotalCount()).isEqualTo(0); + assertThat(pointData.getNegativeBuckets().getTotalCount()).isEqualTo(0); + assertThat(pointData.getExemplars()).isEmpty(); + + MutableExponentialHistogramBuckets positiveBuckets = new MutableExponentialHistogramBuckets(); + positiveBuckets.set( + /* scale= */ 1, /* offset= */ 2, /* totalCount= */ 3, DynamicPrimitiveLongList.of(1, 2, 3)); + MutableExponentialHistogramBuckets negativeBuckets = new MutableExponentialHistogramBuckets(); + negativeBuckets.set(10, 20, 30, DynamicPrimitiveLongList.of(50, 60, 70)); + + pointData.set( + /* scale= */ 1, + /* sum= */ 2, + /* zeroCount= */ 10, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + positiveBuckets, + negativeBuckets, + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + Collections.emptyList()); + + assertThat(pointData.getSum()).isEqualTo(2); + assertThat(pointData.getCount()).isEqualTo(10 + 30 + 3); + assertThat(pointData.getAttributes().get(AttributeKey.stringKey("foo"))).isEqualTo("bar"); + assertThat(pointData.getAttributes().size()).isEqualTo(1); + assertThat(pointData.getScale()).isEqualTo(1); + assertThat(pointData.getZeroCount()).isEqualTo(10); + assertThat(pointData.hasMin()).isTrue(); + assertThat(pointData.getMin()).isEqualTo(100); + assertThat(pointData.hasMax()).isTrue(); + assertThat(pointData.getMax()).isEqualTo(1000); + assertThat(pointData.getPositiveBuckets().getTotalCount()).isEqualTo(3); + assertThat(pointData.getNegativeBuckets().getTotalCount()).isEqualTo(30); + assertThat(pointData.getPositiveBuckets().getBucketCounts()).containsExactly(1L, 2L, 3L); + assertThat(pointData.getNegativeBuckets().getBucketCounts()).containsExactly(50L, 60L, 70L); + assertThat(pointData.getStartEpochNanos()).isEqualTo(10); + assertThat(pointData.getEpochNanos()).isEqualTo(20); + assertThat(pointData.getExemplars()).isEmpty(); + + assertThat(pointData.toString()) + .isEqualTo( + "MutableExponentialHistogramPointData{startEpochNanos=10, epochNanos=20, " + + "attributes={foo=\"bar\"}, scale=1, sum=2.0, count=43, zeroCount=10, hasMin=true, " + + "min=100.0, hasMax=true, max=1000.0, " + + "positiveBuckets=MutableExponentialHistogramBuckets{scale=1, offset=2, " + + "bucketCounts=[1, 2, 3], totalCount=3}, " + + "negativeBuckets=MutableExponentialHistogramBuckets{scale=10, offset=20, " + + "bucketCounts=[50, 60, 70], totalCount=30}, exemplars=[]}"); + + MutableExponentialHistogramPointData samePointData = new MutableExponentialHistogramPointData(); + samePointData.set( + /* scale= */ 1, + /* sum= */ 2, + /* zeroCount= */ 10, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + positiveBuckets, + negativeBuckets, + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + Collections.emptyList()); + assertThat(samePointData).isEqualTo(pointData); + assertThat(samePointData.hashCode()).isEqualTo(pointData.hashCode()); + + MutableExponentialHistogramPointData differentPointData = + new MutableExponentialHistogramPointData(); + differentPointData.set( + /* scale= */ 1, + /* sum= */ 2, + /* zeroCount= */ 10000000, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + positiveBuckets, + negativeBuckets, + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + Collections.emptyList()); + + assertThat(differentPointData).isNotEqualTo(pointData); + assertThat(differentPointData.hashCode()).isNotEqualTo(pointData.hashCode()); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java new file mode 100644 index 00000000000..961651b687e --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/data/MutableHistogramPointDataTest.java @@ -0,0 +1,162 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.data; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import java.util.Arrays; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +public class MutableHistogramPointDataTest { + + @Test + void testSanity() { + MutableHistogramPointData pointData = new MutableHistogramPointData(10); + assertThat(pointData.getSum()).isEqualTo(0); + assertThat(pointData.getCount()).isEqualTo(0); + assertThat(pointData.getBoundaries()).isEmpty(); + assertThat(pointData.getCounts().size()).isEqualTo(10); + assertThat(pointData.getExemplars()).isEmpty(); + + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList()); + + assertThat(pointData.getSum()).isEqualTo(2); + assertThat(pointData.getCount()).isEqualTo(10 + 20 + 30 + 40 + 50 + 60 + 70 + 80 + 90 + 100); + assertThat(pointData.getAttributes().get(AttributeKey.stringKey("foo"))).isEqualTo("bar"); + assertThat(pointData.getAttributes().size()).isEqualTo(1); + assertThat(pointData.getBoundaries()) + .containsExactly(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0); + assertThat(pointData.getCounts().toArray()) + .containsExactly(10L, 20L, 30L, 40L, 50L, 60L, 70L, 80L, 90L, 100L); + assertThat(pointData.getStartEpochNanos()).isEqualTo(10); + assertThat(pointData.getEpochNanos()).isEqualTo(20); + + assertThat(pointData.hasMin()).isTrue(); + assertThat(pointData.getMin()).isEqualTo(100); + assertThat(pointData.hasMax()).isTrue(); + assertThat(pointData.getMax()).isEqualTo(1000); + assertThat(pointData.getExemplars()).isEmpty(); + assertThat(pointData.toString()) + .isEqualTo( + "MutableHistogramPointData{startEpochNanos=10, " + + "epochNanos=20, " + + "attributes={foo=\"bar\"}, " + + "sum=2.0, " + + "count=550, " + + "hasMin=true, " + + "min=100.0, " + + "hasMax=true, " + + "max=1000.0, " + + "boundaries=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0], " + + "counts=[10, 20, 30, 40, 50, 60, 70, 80, 90, 100], " + + "exemplars=[]}"); + + MutableHistogramPointData anotherPointData = new MutableHistogramPointData(10); + // Same values + anotherPointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList()); + assertThat(anotherPointData).isEqualTo(pointData); + assertThat(anotherPointData.hashCode()).isEqualTo(pointData.hashCode()); + + // Same values but different sum + anotherPointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 20000, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList()); + assertThat(anotherPointData).isNotEqualTo(pointData); + assertThat(anotherPointData.hashCode()).isNotEqualTo(pointData.hashCode()); + } + + @Test + void testBoundaries() { + MutableHistogramPointData pointData = new MutableHistogramPointData(10); + assertThatThrownBy(() -> + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid boundaries: size should be 9 but was 4"); + + assertThatThrownBy(() -> + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList( + 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, Double.POSITIVE_INFINITY), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}, + Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid boundaries: contains explicit +/-Inf"); + } + + @Test + void testCounts() { + MutableHistogramPointData pointData = new MutableHistogramPointData(10); + assertThatThrownBy(() -> + pointData.set( + /* startEpochNanos= */ 10, + /* epochNanos= */ 20, + Attributes.of(AttributeKey.stringKey("foo"), "bar"), + /* sum= */ 2, + /* hasMin= */ true, + /* min= */ 100, + /* hasMax= */ true, + /* max= */ 1000, + /* boundaries= */ Arrays.asList(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0), + /* counts= */ new long[] {10, 20, 30, 40, 50, 60}, + Collections.emptyList())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("invalid counts: size should be 10 but was 6"); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptorTest.java index dc26e8c196a..eabfac60d1f 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptorTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/descriptor/MetricDescriptorTest.java @@ -12,6 +12,7 @@ import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import java.util.Arrays; import org.junit.jupiter.api.Test; class MetricDescriptorTest { @@ -21,7 +22,12 @@ void metricDescriptor_preservesInstrumentDescriptor() { View view = View.builder().build(); InstrumentDescriptor instrument = InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.DOUBLE); + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty()); MetricDescriptor simple = MetricDescriptor.create(view, SourceInfo.fromCurrentStack(), instrument); assertThat(simple.getName()).isEqualTo("name"); @@ -36,7 +42,12 @@ void metricDescriptor_overridesFromView() { View view = View.builder().setName("new_name").setDescription("new_description").build(); InstrumentDescriptor instrument = InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.HISTOGRAM, InstrumentValueType.DOUBLE); + "name", + "description", + "unit", + InstrumentType.HISTOGRAM, + InstrumentValueType.DOUBLE, + Advice.empty()); MetricDescriptor simple = MetricDescriptor.create(view, SourceInfo.fromCurrentStack(), instrument); assertThat(simple.getName()).isEqualTo("new_name"); @@ -47,115 +58,116 @@ void metricDescriptor_overridesFromView() { } @Test - void metricDescriptor_isCompatible() { + void metricDescriptor_equals() { View view = View.builder().build(); InstrumentDescriptor instrument = InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.DOUBLE); - MetricDescriptor descriptor = + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty()); + MetricDescriptor descriptor1 = MetricDescriptor.create(view, SourceInfo.fromCurrentStack(), instrument); - // Same name, description, source name, source description, source unit, source type, and source - // value type is compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - View.builder().build(), - SourceInfo.fromCurrentStack(), - InstrumentDescriptor.create( - "name", - "description", - "unit", - InstrumentType.COUNTER, - InstrumentValueType.DOUBLE)))) - .isTrue(); - // Different name overridden by view is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - View.builder().setName("bar").build(), - SourceInfo.fromCurrentStack(), - instrument))) - .isFalse(); - // Different description overridden by view is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - View.builder().setDescription("foo").build(), - SourceInfo.fromCurrentStack(), - instrument))) - .isFalse(); - // Different aggregation overridden by view is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - View.builder().setAggregation(Aggregation.lastValue()).build(), - SourceInfo.fromCurrentStack(), - instrument))) - .isFalse(); - // Different instrument source name is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - view, - SourceInfo.fromCurrentStack(), - InstrumentDescriptor.create( - "foo", - "description", - "unit", - InstrumentType.COUNTER, - InstrumentValueType.DOUBLE)))) - .isFalse(); - // Different instrument source description is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - view, - SourceInfo.fromCurrentStack(), - InstrumentDescriptor.create( - "name", - "foo", - "unit", - InstrumentType.COUNTER, - InstrumentValueType.DOUBLE)))) - .isFalse(); - // Different instrument source unit is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - view, - SourceInfo.fromCurrentStack(), - InstrumentDescriptor.create( - "name", - "description", - "foo", - InstrumentType.COUNTER, - InstrumentValueType.DOUBLE)))) - .isFalse(); - // Different instrument source type is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - view, - SourceInfo.fromCurrentStack(), - InstrumentDescriptor.create( - "name", - "description", - "unit", - InstrumentType.HISTOGRAM, - InstrumentValueType.DOUBLE)))) - .isFalse(); - // Different instrument source value type is not compatible - assertThat( - descriptor.isCompatibleWith( - MetricDescriptor.create( - view, - SourceInfo.fromCurrentStack(), - InstrumentDescriptor.create( - "name", - "description", - "unit", - InstrumentType.COUNTER, - InstrumentValueType.LONG)))) - .isFalse(); + // Same name (case-insensitive), description, view, source name (case-insensitive), source unit, + // source description, source type, and source value type is equal. Advice is not part of + // equals. + MetricDescriptor descriptor2 = + MetricDescriptor.create( + View.builder().build(), + SourceInfo.fromCurrentStack(), + InstrumentDescriptor.create( + "Name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.builder().setExplicitBucketBoundaries(Arrays.asList(1.0, 2.0)).build())); + assertThat(descriptor1).isEqualTo(descriptor2).hasSameHashCodeAs(descriptor2); + // Different name overridden by view is not equal + descriptor2 = + MetricDescriptor.create( + View.builder().setName("bar").build(), SourceInfo.fromCurrentStack(), instrument); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different description overridden by view is not equal + descriptor2 = + MetricDescriptor.create( + View.builder().setDescription("foo").build(), + SourceInfo.fromCurrentStack(), + instrument); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different aggregation overridden by view is not equal + descriptor2 = + MetricDescriptor.create( + View.builder().setAggregation(Aggregation.lastValue()).build(), + SourceInfo.fromCurrentStack(), + instrument); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different instrument source name is not equal + descriptor2 = + MetricDescriptor.create( + view, + SourceInfo.fromCurrentStack(), + InstrumentDescriptor.create( + "foo", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty())); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different instrument source description is not equal + descriptor2 = + MetricDescriptor.create( + view, + SourceInfo.fromCurrentStack(), + InstrumentDescriptor.create( + "name", + "foo", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty())); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different instrument source unit is not equal + descriptor2 = + MetricDescriptor.create( + view, + SourceInfo.fromCurrentStack(), + InstrumentDescriptor.create( + "name", + "description", + "foo", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty())); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different instrument source type is not equal + descriptor2 = + MetricDescriptor.create( + view, + SourceInfo.fromCurrentStack(), + InstrumentDescriptor.create( + "name", + "description", + "unit", + InstrumentType.HISTOGRAM, + InstrumentValueType.DOUBLE, + Advice.empty())); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); + // Different instrument source value type is not equal + descriptor2 = + MetricDescriptor.create( + view, + SourceInfo.fromCurrentStack(), + InstrumentDescriptor.create( + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty())); + assertThat(descriptor1).isNotEqualTo(descriptor2).doesNotHaveSameHashCodeAs(descriptor2); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleRandomFixedSizeExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleRandomFixedSizeExemplarReservoirTest.java deleted file mode 100644 index ec72ad9350b..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/DoubleRandomFixedSizeExemplarReservoirTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.RandomSupplier; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; -import io.opentelemetry.sdk.testing.time.TestClock; -import java.time.Duration; -import java.util.Random; -import org.junit.jupiter.api.Test; - -class DoubleRandomFixedSizeExemplarReservoirTest { - private static final String TRACE_ID = "ff000000000000000000000000000041"; - private static final String SPAN_ID = "ff00000000000041"; - - @Test - public void noMeasurement_returnsEmpty() { - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createDouble(clock, 1, RandomSupplier.platformDefault()); - assertThat(reservoir.collectAndReset(Attributes.empty())).isEmpty(); - } - - @Test - public void oneMeasurement_alwaysSamplesFirstMeasurement() { - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createDouble(clock, 1, RandomSupplier.platformDefault()); - reservoir.offerDoubleMeasurement(1.1, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(1.1)); - - // Measurement count is reset, we should sample a new measurement (and only one) - clock.advance(Duration.ofSeconds(1)); - reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(2)); - } - - @Test - public void oneMeasurement_filtersAttributes() { - Attributes all = - Attributes.builder().put("one", 1).put("two", "two").put("three", true).build(); - Attributes partial = Attributes.builder().put("three", true).build(); - Attributes remaining = Attributes.builder().put("one", 1).put("two", "two").build(); - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createDouble(clock, 1, RandomSupplier.platformDefault()); - reservoir.offerDoubleMeasurement(1.1, all, Context.root()); - assertThat(reservoir.collectAndReset(partial)) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasValue(1.1) - .hasFilteredAttributes(remaining)); - } - - @Test - public void oneMeasurement_includesTraceAndSpanIds() { - Attributes all = - Attributes.builder().put("one", 1).put("two", "two").put("three", true).build(); - Context context = - Context.root() - .with( - Span.wrap( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()))); - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createDouble(clock, 1, RandomSupplier.platformDefault()); - reservoir.offerDoubleMeasurement(1, all, context); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasValue(1) - .hasFilteredAttributes(all) - .hasTraceId(TRACE_ID) - .hasSpanId(SPAN_ID)); - } - - @Test - public void multiMeasurements_preservesLatestSamples() { - AttributeKey key = AttributeKey.longKey("K"); - // We cannot mock random in latest jdk, so we create an override. - Random mockRandom = - new Random() { - @Override - public int nextInt(int max) { - switch (max) { - // Force one sample in bucket 1 and two in bucket 0. - case 2: - return 1; - default: - return 0; - } - } - }; - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - ExemplarReservoir.doubleFixedSizeReservoir(clock, 2, () -> mockRandom); - reservoir.offerDoubleMeasurement(1, Attributes.of(key, 1L), Context.root()); - reservoir.offerDoubleMeasurement(2, Attributes.of(key, 2L), Context.root()); - reservoir.offerDoubleMeasurement(3, Attributes.of(key, 3L), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .satisfiesExactlyInAnyOrder( - exemplar -> - MetricAssertions.assertThat(exemplar).hasEpochNanos(clock.now()).hasValue(2), - exemplar -> - MetricAssertions.assertThat(exemplar).hasEpochNanos(clock.now()).hasValue(3)); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterTest.java index 23a90442619..bbe1d1e365a 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/ExemplarFilterTest.java @@ -5,8 +5,10 @@ package io.opentelemetry.sdk.metrics.internal.exemplar; +import static io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal.asExemplarFilterInternal; import static org.assertj.core.api.Assertions.as; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Span; @@ -14,9 +16,9 @@ import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.metrics.ExemplarFilter; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder; -import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; @@ -25,17 +27,17 @@ class ExemplarFilterTest { private static final String SPAN_ID = "ff00000000000041"; @Test - void never_NeverReturnsTrue() { + void alwaysOff_NeverReturnsTrue() { assertThat( - ExemplarFilter.neverSample() + asExemplarFilterInternal(ExemplarFilter.alwaysOff()) .shouldSampleMeasurement(1, Attributes.empty(), Context.root())) .isFalse(); } @Test - void always_AlwaysReturnsTrue() { + void alwaysOn_AlwaysReturnsTrue() { assertThat( - ExemplarFilter.alwaysSample() + asExemplarFilterInternal(ExemplarFilter.alwaysOn()) .shouldSampleMeasurement(1, Attributes.empty(), Context.root())) .isTrue(); } @@ -43,13 +45,13 @@ void always_AlwaysReturnsTrue() { @Test void withSampledTrace_ReturnsFalseOnNoContext() { assertThat( - ExemplarFilter.sampleWithTraces() + asExemplarFilterInternal(ExemplarFilter.traceBased()) .shouldSampleMeasurement(1, Attributes.empty(), Context.root())) .isFalse(); } @Test - void withSampledTrace_sampleWithTrace() { + void traceBased_sampleWithTrace() { Context context = Context.root() .with( @@ -57,13 +59,13 @@ void withSampledTrace_sampleWithTrace() { SpanContext.createFromRemoteParent( TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()))); assertThat( - ExemplarFilter.sampleWithTraces() + asExemplarFilterInternal(ExemplarFilter.traceBased()) .shouldSampleMeasurement(1, Attributes.empty(), context)) .isTrue(); } @Test - void withSampledTrace_notSampleUnsampledTrace() { + void traceBased_notSampleUnsampledTrace() { Context context = Context.root() .with( @@ -71,17 +73,45 @@ void withSampledTrace_notSampleUnsampledTrace() { SpanContext.createFromRemoteParent( TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault()))); assertThat( - ExemplarFilter.sampleWithTraces() + asExemplarFilterInternal(ExemplarFilter.traceBased()) .shouldSampleMeasurement(1, Attributes.empty(), context)) .isFalse(); } @Test void setExemplarFilter() { - SdkMeterProviderBuilder builder = SdkMeterProvider.builder(); - SdkMeterProviderUtil.setExemplarFilter(builder, ExemplarFilter.alwaysSample()); + SdkMeterProviderBuilder builder = + SdkMeterProvider.builder().setExemplarFilter(ExemplarFilter.alwaysOn()); assertThat(builder) - .extracting("exemplarFilter", as(InstanceOfAssertFactories.type(ExemplarFilter.class))) - .isEqualTo(ExemplarFilter.alwaysSample()); + .extracting( + "exemplarFilter", as(InstanceOfAssertFactories.type(ExemplarFilterInternal.class))) + .isEqualTo(ExemplarFilter.alwaysOn()); + } + + @Test + void asExemplarFilterInternal_Valid() { + assertThat(asExemplarFilterInternal(ExemplarFilter.traceBased())) + .isSameAs(ExemplarFilter.traceBased()); + assertThat(asExemplarFilterInternal(ExemplarFilter.alwaysOff())) + .isSameAs(ExemplarFilter.alwaysOff()); + assertThat(asExemplarFilterInternal(ExemplarFilter.alwaysOn())) + .isSameAs(ExemplarFilter.alwaysOn()); + assertThatThrownBy(() -> asExemplarFilterInternal(new ExemplarFilter() {})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void alwaysOff_toString() { + assertThat(ExemplarFilter.alwaysOff().toString()).isEqualTo("AlwaysOffExemplarFilter"); + } + + @Test + void alwaysOn_toString() { + assertThat(ExemplarFilter.alwaysOn().toString()).isEqualTo("AlwaysOnExemplarFilter"); + } + + @Test + void traceBased_toString() { + assertThat(ExemplarFilter.traceBased().toString()).isEqualTo("TraceBasedExemplarFilter"); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoirTest.java index a7b0b0a756b..1abc9e73cd4 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoirTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/FilteredExemplarReservoirTest.java @@ -8,12 +8,13 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import java.util.Collections; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,31 +23,56 @@ @ExtendWith(MockitoExtension.class) class FilteredExemplarReservoirTest { - @Mock ExemplarReservoir reservoir; - @Mock ExemplarFilter filter; + @Mock DoubleExemplarReservoir doubleReservoir; + @Mock LongExemplarReservoir longReservoir; + @Mock ExemplarFilterInternal filter; @Test - void testFilter_preventsSampling() { + void testFilterDouble_preventsSampling() { when(filter.shouldSampleMeasurement(anyDouble(), any(), any())).thenReturn(false); - ExemplarReservoir filtered = - new FilteredExemplarReservoir<>(filter, reservoir); + DoubleExemplarReservoir filtered = new DoubleFilteredExemplarReservoir(filter, doubleReservoir); filtered.offerDoubleMeasurement(1.0, Attributes.empty(), Context.root()); + verify(doubleReservoir, never()).offerDoubleMeasurement(anyDouble(), any(), any()); } @Test - void testFilter_allowsSampling() { + void testFilterLong_preventsSampling() { + when(filter.shouldSampleMeasurement(anyLong(), any(), any())).thenReturn(false); + LongExemplarReservoir filtered = new LongFilteredExemplarReservoir(filter, longReservoir); + filtered.offerLongMeasurement(1L, Attributes.empty(), Context.root()); + verify(longReservoir, never()).offerLongMeasurement(anyLong(), any(), any()); + } + + @Test + void testFilterDouble_allowsSampling() { when(filter.shouldSampleMeasurement(anyDouble(), any(), any())).thenReturn(true); - ExemplarReservoir filtered = - new FilteredExemplarReservoir<>(filter, reservoir); + DoubleExemplarReservoir filtered = new DoubleFilteredExemplarReservoir(filter, doubleReservoir); filtered.offerDoubleMeasurement(1.0, Attributes.empty(), Context.root()); - verify(reservoir).offerDoubleMeasurement(1.0, Attributes.empty(), Context.root()); + verify(doubleReservoir).offerDoubleMeasurement(1.0, Attributes.empty(), Context.root()); + } + + @Test + void testFilterLong_allowsSampling() { + when(filter.shouldSampleMeasurement(anyLong(), any(), any())).thenReturn(true); + LongExemplarReservoir filtered = new LongFilteredExemplarReservoir(filter, longReservoir); + filtered.offerLongMeasurement(1L, Attributes.empty(), Context.root()); + verify(longReservoir).offerLongMeasurement(1L, Attributes.empty(), Context.root()); + } + + @Test + void reservoirDouble_collectsUnderlying() { + when(doubleReservoir.collectAndResetDoubles(Attributes.empty())) + .thenReturn(Collections.emptyList()); + DoubleExemplarReservoir filtered = + new DoubleFilteredExemplarReservoir(filter, doubleReservoir) {}; + assertThat(filtered.collectAndResetDoubles(Attributes.empty())).isEmpty(); } @Test - void reservoir_collectsUnderlying() { - when(reservoir.collectAndReset(Attributes.empty())).thenReturn(Collections.emptyList()); - ExemplarReservoir filtered = - new FilteredExemplarReservoir<>(filter, reservoir); - assertThat(filtered.collectAndReset(Attributes.empty())).isEmpty(); + void reservoirLong_collectsUnderlying() { + when(longReservoir.collectAndResetLongs(Attributes.empty())) + .thenReturn(Collections.emptyList()); + LongExemplarReservoir filtered = new LongFilteredExemplarReservoir(filter, longReservoir) {}; + assertThat(filtered.collectAndResetLongs(Attributes.empty())).isEmpty(); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java index 38702a78553..cfe7a3080dd 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/HistogramExemplarReservoirTest.java @@ -9,9 +9,11 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; import io.opentelemetry.sdk.testing.time.TestClock; import java.time.Duration; import java.util.Arrays; @@ -19,81 +21,126 @@ import org.junit.jupiter.api.Test; class HistogramExemplarReservoirTest { + private static final String TRACE_ID = "ff000000000000000000000000000041"; + private static final String SPAN_ID = "ff00000000000041"; + @Test - public void noMeasurement_returnsEmpty() { + void noMeasurement_returnsEmpty() { TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = + HistogramExemplarReservoir reservoir = new HistogramExemplarReservoir(clock, Collections.emptyList()); - assertThat(reservoir.collectAndReset(Attributes.empty())).isEmpty(); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())).isEmpty(); } @Test - public void oneBucket_samplesEverything() { + void oneBucket_samplesEverything() { TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = + HistogramExemplarReservoir reservoir = new HistogramExemplarReservoir(clock, Collections.emptyList()); reservoir.offerDoubleMeasurement(1.1, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(1.1)); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1.1); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); // Measurement count is reset, we should sample a new measurement (and only one) clock.advance(Duration.ofSeconds(1)); reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(2)); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(2); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); // only latest measurement is kept per-bucket clock.advance(Duration.ofSeconds(1)); reservoir.offerDoubleMeasurement(3, Attributes.empty(), Context.root()); reservoir.offerDoubleMeasurement(4, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(4)); + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(4); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); + } + + @Test + void oneBucket_overwriteWithoutSpan_clearsSpanContext() { + TestClock clock = TestClock.create(); + HistogramExemplarReservoir reservoir = + new HistogramExemplarReservoir(clock, Collections.emptyList()); + Context context = + Context.root() + .with( + Span.wrap( + SpanContext.createFromRemoteParent( + TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()))); + reservoir.offerDoubleMeasurement(1, Attributes.empty(), context); + reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getValue()).isEqualTo(2); + assertThat(exemplar.getSpanContext()).isEqualTo(SpanContext.getInvalid()); + }); } @Test - public void multipleBuckets_samplesIntoCorrectBucket() { + void multipleBuckets_samplesIntoCorrectBucket() { TestClock clock = TestClock.create(); AttributeKey bucketKey = AttributeKey.longKey("bucket"); - ExemplarReservoir reservoir = + HistogramExemplarReservoir reservoir = new HistogramExemplarReservoir(clock, Arrays.asList(0d, 10d, 20d)); reservoir.offerDoubleMeasurement(-1.1, Attributes.of(bucketKey, 0L), Context.root()); reservoir.offerDoubleMeasurement(1, Attributes.of(bucketKey, 1L), Context.root()); reservoir.offerDoubleMeasurement(11, Attributes.of(bucketKey, 2L), Context.root()); reservoir.offerDoubleMeasurement(21, Attributes.of(bucketKey, 3L), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) .hasSize(4) .satisfiesExactlyInAnyOrder( - e -> - MetricAssertions.assertThat(e) - .hasValue(-1.1) - .hasFilteredAttributes(Attributes.of(bucketKey, 0L)), - e -> - MetricAssertions.assertThat(e) - .hasValue(1) - .hasFilteredAttributes(Attributes.of(bucketKey, 1L)), - e -> - MetricAssertions.assertThat(e) - .hasValue(11) - .hasFilteredAttributes(Attributes.of(bucketKey, 2L)), - e -> - MetricAssertions.assertThat(e) - .hasValue(21) - .hasFilteredAttributes(Attributes.of(bucketKey, 3L))); + e -> { + assertThat(e.getValue()).isEqualTo(-1.1); + assertThat(e.getFilteredAttributes()).isEqualTo(Attributes.of(bucketKey, 0L)); + }, + e -> { + assertThat(e.getValue()).isEqualTo(1); + assertThat(e.getFilteredAttributes()).isEqualTo(Attributes.of(bucketKey, 1L)); + }, + e -> { + assertThat(e.getValue()).isEqualTo(11); + assertThat(e.getFilteredAttributes()).isEqualTo(Attributes.of(bucketKey, 2L)); + }, + e -> { + assertThat(e.getValue()).isEqualTo(21); + assertThat(e.getFilteredAttributes()).isEqualTo(Attributes.of(bucketKey, 3L)); + }); + } + + @Test + void longMeasurement_CastsToDouble() { + TestClock clock = TestClock.create(); + HistogramExemplarReservoir reservoir = + new HistogramExemplarReservoir(clock, Collections.emptyList()); + reservoir.offerLongMeasurement(1L, Attributes.empty(), Context.root()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .hasSize(1) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); + // Measurement count is reset, we should sample a new measurement (and only one) + clock.advance(Duration.ofSeconds(1)); + reservoir.offerLongMeasurement(2, Attributes.empty(), Context.root()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .hasSize(1) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(2); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + }); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongRandomFixedSizeExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongRandomFixedSizeExemplarReservoirTest.java deleted file mode 100644 index a59eb42b4f6..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/LongRandomFixedSizeExemplarReservoirTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.exemplar; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanContext; -import io.opentelemetry.api.trace.TraceFlags; -import io.opentelemetry.api.trace.TraceState; -import io.opentelemetry.context.Context; -import io.opentelemetry.sdk.internal.RandomSupplier; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; -import io.opentelemetry.sdk.testing.assertj.MetricAssertions; -import io.opentelemetry.sdk.testing.time.TestClock; -import java.time.Duration; -import java.util.Random; -import org.junit.jupiter.api.Test; - -class LongRandomFixedSizeExemplarReservoirTest { - private static final String TRACE_ID = "ff000000000000000000000000000041"; - private static final String SPAN_ID = "ff00000000000041"; - - @Test - public void noMeasurement_returnsEmpty() { - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createLong(clock, 1, RandomSupplier.platformDefault()); - assertThat(reservoir.collectAndReset(Attributes.empty())).isEmpty(); - } - - @Test - public void oneMeasurement_alwaysSamplesFirstMeasurement() { - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createLong(clock, 1, RandomSupplier.platformDefault()); - reservoir.offerLongMeasurement(1, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(1)); - - // Measurement count is reset, we should sample a new measurement (and only one) - clock.advance(Duration.ofSeconds(1)); - reservoir.offerLongMeasurement(2, Attributes.empty(), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .hasSize(1) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasFilteredAttributes(Attributes.empty()) - .hasValue(2)); - } - - @Test - public void oneMeasurement_filtersAttributes() { - Attributes all = - Attributes.builder().put("one", 1).put("two", "two").put("three", true).build(); - Attributes partial = Attributes.builder().put("three", true).build(); - Attributes remaining = Attributes.builder().put("one", 1).put("two", "two").build(); - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createLong(clock, 1, RandomSupplier.platformDefault()); - reservoir.offerLongMeasurement(1, all, Context.root()); - assertThat(reservoir.collectAndReset(partial)) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasValue(1) - .hasFilteredAttributes(remaining)); - } - - @Test - public void oneMeasurement_includesTraceAndSpanIds() { - Attributes all = - Attributes.builder().put("one", 1).put("two", "two").put("three", true).build(); - Context context = - Context.root() - .with( - Span.wrap( - SpanContext.createFromRemoteParent( - TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()))); - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - RandomFixedSizeExemplarReservoir.createLong(clock, 1, RandomSupplier.platformDefault()); - reservoir.offerLongMeasurement(1, all, context); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .satisfiesExactly( - exemplar -> - MetricAssertions.assertThat(exemplar) - .hasEpochNanos(clock.now()) - .hasValue(1) - .hasFilteredAttributes(all) - .hasTraceId(TRACE_ID) - .hasSpanId(SPAN_ID)); - } - - @Test - public void multiMeasurements_preservesLatestSamples() { - AttributeKey key = AttributeKey.longKey("K"); - // We cannot mock random in latest jdk, so we create an override. - Random mockRandom = - new Random() { - @Override - public int nextInt(int max) { - switch (max) { - // Force one sample in bucket 1 and two in bucket 0. - case 2: - return 1; - default: - return 0; - } - } - }; - TestClock clock = TestClock.create(); - ExemplarReservoir reservoir = - ExemplarReservoir.longFixedSizeReservoir(clock, 2, () -> mockRandom); - reservoir.offerLongMeasurement(1, Attributes.of(key, 1L), Context.root()); - reservoir.offerLongMeasurement(2, Attributes.of(key, 2L), Context.root()); - reservoir.offerLongMeasurement(3, Attributes.of(key, 3L), Context.root()); - assertThat(reservoir.collectAndReset(Attributes.empty())) - .satisfiesExactlyInAnyOrder( - exemplar -> - MetricAssertions.assertThat(exemplar).hasEpochNanos(clock.now()).hasValue(2), - exemplar -> - MetricAssertions.assertThat(exemplar).hasEpochNanos(clock.now()).hasValue(3)); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java new file mode 100644 index 00000000000..6439967c359 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/exemplar/RandomFixedSizeExemplarReservoirTest.java @@ -0,0 +1,138 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.exemplar; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.internal.RandomSupplier; +import io.opentelemetry.sdk.testing.time.TestClock; +import java.time.Duration; +import java.util.Random; +import org.junit.jupiter.api.Test; + +class RandomFixedSizeExemplarReservoirTest { + private static final String TRACE_ID = "ff000000000000000000000000000041"; + private static final String SPAN_ID = "ff00000000000041"; + + @Test + public void noMeasurement_returnsEmpty() { + TestClock clock = TestClock.create(); + RandomFixedSizeExemplarReservoir reservoir = + RandomFixedSizeExemplarReservoir.create(clock, 1, RandomSupplier.platformDefault()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())).isEmpty(); + } + + @Test + public void oneMeasurement_alwaysSamplesFirstMeasurement() { + TestClock clock = TestClock.create(); + RandomFixedSizeExemplarReservoir reservoir = + RandomFixedSizeExemplarReservoir.create(clock, 1, RandomSupplier.platformDefault()); + reservoir.offerDoubleMeasurement(1.1, Attributes.empty(), Context.root()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .hasSize(1) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + assertThat(exemplar.getValue()).isEqualTo(1.1); + }); + + // Measurement count is reset, we should sample a new measurement (and only one) + clock.advance(Duration.ofSeconds(1)); + reservoir.offerDoubleMeasurement(2, Attributes.empty(), Context.root()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .hasSize(1) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getFilteredAttributes()).isEmpty(); + assertThat(exemplar.getValue()).isEqualTo(2); + }); + } + + @Test + public void oneMeasurement_filtersAttributes() { + Attributes all = + Attributes.builder().put("one", 1).put("two", "two").put("three", true).build(); + Attributes partial = Attributes.builder().put("three", true).build(); + Attributes remaining = Attributes.builder().put("one", 1).put("two", "two").build(); + TestClock clock = TestClock.create(); + RandomFixedSizeExemplarReservoir reservoir = + RandomFixedSizeExemplarReservoir.create(clock, 1, RandomSupplier.platformDefault()); + reservoir.offerDoubleMeasurement(1.1, all, Context.root()); + assertThat(reservoir.collectAndResetDoubles(partial)) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1.1); + assertThat(exemplar.getFilteredAttributes()).isEqualTo(remaining); + }); + } + + @Test + public void oneMeasurement_includesTraceAndSpanIds() { + Attributes all = + Attributes.builder().put("one", 1).put("two", "two").put("three", true).build(); + Context context = + Context.root() + .with( + Span.wrap( + SpanContext.createFromRemoteParent( + TRACE_ID, SPAN_ID, TraceFlags.getSampled(), TraceState.getDefault()))); + TestClock clock = TestClock.create(); + RandomFixedSizeExemplarReservoir reservoir = + RandomFixedSizeExemplarReservoir.create(clock, 1, RandomSupplier.platformDefault()); + reservoir.offerDoubleMeasurement(1, all, context); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .satisfiesExactly(exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(1); + assertThat(exemplar.getFilteredAttributes()).isEqualTo(all); + assertThat(exemplar.getSpanContext().getTraceId()).isEqualTo(TRACE_ID); + assertThat(exemplar.getSpanContext().getSpanId()).isEqualTo(SPAN_ID); + }); + } + + @Test + public void multiMeasurements_preservesLatestSamples() { + AttributeKey key = AttributeKey.longKey("K"); + // We cannot mock random in latest jdk, so we create an override. + Random mockRandom = + new Random() { + @Override + public int nextInt(int max) { + switch (max) { + // Force one sample in bucket 1 and two in bucket 0. + case 2: + return 1; + default: + return 0; + } + } + }; + TestClock clock = TestClock.create(); + DoubleExemplarReservoir reservoir = + ExemplarReservoirFactory.fixedSizeReservoir(clock, 2, () -> mockRandom) + .createDoubleExemplarReservoir(); + reservoir.offerDoubleMeasurement(1, Attributes.of(key, 1L), Context.root()); + reservoir.offerDoubleMeasurement(2, Attributes.of(key, 2L), Context.root()); + reservoir.offerDoubleMeasurement(3, Attributes.of(key, 3L), Context.root()); + assertThat(reservoir.collectAndResetDoubles(Attributes.empty())) + .satisfiesExactlyInAnyOrder( + exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(2); + }, + exemplar -> { + assertThat(exemplar.getEpochNanos()).isEqualTo(clock.now()); + assertThat(exemplar.getValue()).isEqualTo(3); + }); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReaderTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReaderTest.java index a063b0f69be..a0a4cf7125b 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReaderTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/export/RegisteredReaderTest.java @@ -8,6 +8,7 @@ import static org.assertj.core.api.Assertions.assertThat; import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -20,10 +21,9 @@ class RegisteredReaderTest { @Test void create_UniqueIdentity() { - RegisteredReader registeredReader1 = RegisteredReader.create(reader); - RegisteredReader registeredReader2 = RegisteredReader.create(reader); + RegisteredReader registeredReader1 = RegisteredReader.create(reader, ViewRegistry.create()); + RegisteredReader registeredReader2 = RegisteredReader.create(reader, ViewRegistry.create()); - assertThat(registeredReader1).isEqualTo(registeredReader1); assertThat(registeredReader1).isNotEqualTo(registeredReader2); assertThat(registeredReader1.hashCode()).isEqualTo(registeredReader1.hashCode()); @@ -32,19 +32,19 @@ void create_UniqueIdentity() { @Test void getReader() { - RegisteredReader registeredReader = RegisteredReader.create(reader); + RegisteredReader registeredReader = RegisteredReader.create(reader, ViewRegistry.create()); assertThat(registeredReader.getReader()).isSameAs(reader); } @Test - void setAndGetLastCollectEpochNanos() { - RegisteredReader registeredReader = RegisteredReader.create(reader); + void getLastCollectEpochNanosOrDefault() { + RegisteredReader registeredReader = RegisteredReader.create(reader, ViewRegistry.create()); - assertThat(registeredReader.getLastCollectEpochNanos()).isEqualTo(0); + assertThat(registeredReader.getLastCollectEpochNanosOrDefault(4)).isEqualTo(4); registeredReader.setLastCollectEpochNanos(1); - assertThat(registeredReader.getLastCollectEpochNanos()).isEqualTo(1); + assertThat(registeredReader.getLastCollectEpochNanosOrDefault(4)).isEqualTo(1); registeredReader.setLastCollectEpochNanos(5); - assertThat(registeredReader.getLastCollectEpochNanos()).isEqualTo(5); + assertThat(registeredReader.getLastCollectEpochNanosOrDefault(5)).isEqualTo(5); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ArrayBasedStackTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ArrayBasedStackTest.java new file mode 100644 index 00000000000..e8cbda1764c --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ArrayBasedStackTest.java @@ -0,0 +1,63 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class ArrayBasedStackTest { + + @Test + void testPushAndPop() { + ArrayBasedStack stack = new ArrayBasedStack<>(); + stack.push(1); + stack.push(2); + assertThat(stack.pop()).isEqualTo(2); + assertThat(stack.pop()).isEqualTo(1); + } + + @Test + void testIsEmpty() { + ArrayBasedStack stack = new ArrayBasedStack<>(); + assertThat(stack.isEmpty()).isTrue(); + stack.push(1); + assertThat(stack.isEmpty()).isFalse(); + } + + @Test + void testSize() { + ArrayBasedStack stack = new ArrayBasedStack<>(); + assertThat(stack.size()).isEqualTo(0); + stack.push(1); + assertThat(stack.size()).isEqualTo(1); + } + + @Test + void testPushBeyondInitialCapacity() { + ArrayBasedStack stack = new ArrayBasedStack<>(); + for (int i = 0; i < ArrayBasedStack.DEFAULT_CAPACITY + 5; i++) { + stack.push(i); + } + assertThat(stack.size()).isEqualTo(ArrayBasedStack.DEFAULT_CAPACITY + 5); + for (int i = ArrayBasedStack.DEFAULT_CAPACITY + 4; i >= 0; i--) { + assertThat(stack.pop()).isEqualTo(i); + } + } + + @Test + void testPopOnEmptyStack() { + ArrayBasedStack stack = new ArrayBasedStack<>(); + assertThat(stack.pop()).isNull(); + } + + @Test + void testPushNullElement() { + ArrayBasedStack stack = new ArrayBasedStack<>(); + assertThatThrownBy(() -> stack.push(null)).isInstanceOf(NullPointerException.class); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java index b09ba1175cc..6133bbdff02 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/AsynchronousMetricStorageTest.java @@ -5,6 +5,8 @@ package io.opentelemetry.sdk.metrics.internal.state; +import static io.opentelemetry.sdk.common.export.MemoryMode.REUSABLE_DATA; +import static io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal.asExemplarFilterInternal; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; import static org.mockito.ArgumentMatchers.any; @@ -14,23 +16,37 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.ExemplarFilter; import io.opentelemetry.sdk.metrics.InstrumentSelector; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.internal.data.MutableLongPointData; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; +import io.opentelemetry.sdk.metrics.internal.view.AttributesFilters; import io.opentelemetry.sdk.metrics.internal.view.RegisteredView; +import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.time.TestClock; -import org.junit.jupiter.api.BeforeEach; +import java.time.Duration; +import java.time.Instant; +import java.util.Collection; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -38,152 +54,529 @@ @ExtendWith(MockitoExtension.class) class AsynchronousMetricStorageTest { + private static final long START_SECOND_NANOS = 1_000_000_000L; + + private static final int CARDINALITY_LIMIT = 25; + @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(AsynchronousMetricStorage.class); - private final TestClock testClock = TestClock.create(); + private final TestClock testClock = TestClock.create(Instant.ofEpochSecond(1)); private final Resource resource = Resource.empty(); private final InstrumentationScopeInfo scope = InstrumentationScopeInfo.empty(); private final InstrumentSelector selector = InstrumentSelector.builder().setName("*").build(); private final RegisteredView registeredView = RegisteredView.create( - selector, View.builder().build(), AttributesProcessor.noop(), SourceInfo.noSourceInfo()); + selector, + View.builder().build(), + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + SourceInfo.noSourceInfo()); @Mock private MetricReader reader; private RegisteredReader registeredReader; - private AsynchronousMetricStorage longCounterStorage; - private AsynchronousMetricStorage doubleCounterStorage; + private AsynchronousMetricStorage longCounterStorage; + private AsynchronousMetricStorage doubleCounterStorage; + + // Not using @BeforeEach since many methods require executing them for each MemoryMode + void setup(MemoryMode memoryMode) { + setup(memoryMode, AggregationTemporality.CUMULATIVE, ExemplarFilter.alwaysOff()); + } + + void setup(MemoryMode memoryMode, AggregationTemporality temporality) { + setup(memoryMode, temporality, ExemplarFilter.alwaysOff()); + } - @BeforeEach - void setup() { - when(reader.getAggregationTemporality(any())).thenReturn(AggregationTemporality.CUMULATIVE); - registeredReader = RegisteredReader.create(reader); + void setup( + MemoryMode memoryMode, AggregationTemporality temporality, ExemplarFilter exemplarFilter) { + when(reader.getAggregationTemporality(any())).thenReturn(temporality); + when(reader.getMemoryMode()).thenReturn(memoryMode); + registeredReader = RegisteredReader.create(reader, ViewRegistry.create()); longCounterStorage = AsynchronousMetricStorage.create( registeredReader, registeredView, + testClock, InstrumentDescriptor.create( "long-counter", "description", "unit", InstrumentType.COUNTER, - InstrumentValueType.LONG)); + InstrumentValueType.LONG, + Advice.empty()), + asExemplarFilterInternal(exemplarFilter), + /* enabled= */ true); doubleCounterStorage = AsynchronousMetricStorage.create( registeredReader, registeredView, + testClock, InstrumentDescriptor.create( "double-counter", "description", "unit", InstrumentType.COUNTER, - InstrumentValueType.DOUBLE)); + InstrumentValueType.DOUBLE, + Advice.empty()), + asExemplarFilterInternal(exemplarFilter), + /* enabled= */ true); } - @Test - void recordLong() { - longCounterStorage.recordLong(1, Attributes.builder().put("key", "a").build()); - longCounterStorage.recordLong(2, Attributes.builder().put("key", "b").build()); - longCounterStorage.recordLong(3, Attributes.builder().put("key", "c").build()); - - assertThat(longCounterStorage.collectAndReset(resource, scope, 0, testClock.nanoTime())) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1).hasAttributes(attributeEntry("key", "a")), - point -> - point.hasValue(2).hasAttributes(attributeEntry("key", "b")), - point -> - point.hasValue(3).hasAttributes(attributeEntry("key", "c"))))); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordLong(MemoryMode memoryMode) { + setup(memoryMode); + + longCounterStorage.record(Attributes.builder().put("key", "a").build(), 1); + longCounterStorage.record(Attributes.builder().put("key", "b").build(), 2); + longCounterStorage.record(Attributes.builder().put("key", "c").build(), 3); + + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(1).hasAttributes(attributeEntry("key", "a")), + point -> point.hasValue(2).hasAttributes(attributeEntry("key", "b")), + point -> point.hasValue(3).hasAttributes(attributeEntry("key", "c"))))); assertThat(logs.size()).isEqualTo(0); } - @Test - void recordDouble() { - doubleCounterStorage.recordDouble(1.1, Attributes.builder().put("key", "a").build()); - doubleCounterStorage.recordDouble(2.2, Attributes.builder().put("key", "b").build()); - doubleCounterStorage.recordDouble(3.3, Attributes.builder().put("key", "c").build()); - - assertThat(doubleCounterStorage.collectAndReset(resource, scope, 0, testClock.nanoTime())) - .satisfies( - metricData -> - assertThat(metricData) - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1.1).hasAttributes(attributeEntry("key", "a")), - point -> - point.hasValue(2.2).hasAttributes(attributeEntry("key", "b")), - point -> - point - .hasValue(3.3) - .hasAttributes(attributeEntry("key", "c"))))); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordDouble(MemoryMode memoryMode) { + setup(memoryMode); + + doubleCounterStorage.record(Attributes.builder().put("key", "a").build(), 1.1); + doubleCounterStorage.record(Attributes.builder().put("key", "b").build(), 2.2); + doubleCounterStorage.record(Attributes.builder().put("key", "c").build(), 3.3); + + assertThat(doubleCounterStorage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(1.1).hasAttributes(attributeEntry("key", "a")), + point -> point.hasValue(2.2).hasAttributes(attributeEntry("key", "b")), + point -> point.hasValue(3.3).hasAttributes(attributeEntry("key", "c"))))); assertThat(logs.size()).isEqualTo(0); } - @Test - void record_ProcessesAttributes() { - AsynchronousMetricStorage storage = + @ParameterizedTest + @EnumSource(MemoryMode.class) + void record_ProcessesAttributes(MemoryMode memoryMode) { + setup(memoryMode); + + AsynchronousMetricStorage storage = AsynchronousMetricStorage.create( registeredReader, RegisteredView.create( selector, - View.builder().build(), - AttributesProcessor.filterByKeyName(key -> key.equals("key1")), + View.builder().setAttributeFilter(key -> key.equals("key1")).build(), + AttributesFilters.byKeyName(key -> key.equals("key1")), + CARDINALITY_LIMIT, SourceInfo.noSourceInfo()), + testClock, InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.LONG)); - - storage.recordLong(1, Attributes.builder().put("key1", "a").put("key2", "b").build()); - - assertThat(storage.collectAndReset(resource, scope, 0, testClock.nanoTime())) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1).hasAttributes(attributeEntry("key1", "a"))))); + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), + asExemplarFilterInternal(ExemplarFilter.alwaysOff()), + /* enabled= */ true); + + storage.record(Attributes.builder().put("key1", "a").put("key2", "b").build(), 1); + + assertThat(storage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(1).hasAttributes(attributeEntry("key1", "a"))))); assertThat(logs.size()).isEqualTo(0); } - @Test - void record_MaxAccumulations() { - for (int i = 0; i <= MetricStorageUtils.MAX_ACCUMULATIONS + 1; i++) { - longCounterStorage.recordLong(1, Attributes.builder().put("key" + i, "val").build()); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void record_MaxCardinality(MemoryMode memoryMode) { + setup(memoryMode); + + for (int i = 0; i <= CARDINALITY_LIMIT + 1; i++) { + longCounterStorage.record(Attributes.builder().put("key" + i, "val").build(), 1); + } + + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT)); + logs.assertContains("Instrument long-counter has exceeded the maximum allowed cardinality"); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void record_DeltaHandlesSpotsAreReleasedAfterCollection(MemoryMode memoryMode) { + setup(memoryMode, AggregationTemporality.DELTA); + + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + longCounterStorage.record(Attributes.builder().put("key" + i, "val").build(), 1); + } + + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT - 1)); + logs.assertDoesNotContain( + "Instrument long-counter has exceeded the maximum allowed cardinality"); + + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + // Different attribute + longCounterStorage.record(Attributes.builder().put("key" + i, "val2").build(), 1); + } + + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData.getLongSumData().getPoints()).hasSize(CARDINALITY_LIMIT - 1)); + logs.assertDoesNotContain( + "Instrument long-counter has exceeded the maximum allowed cardinality"); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void record_DuplicateAttributes(MemoryMode memoryMode) { + setup(memoryMode); + + longCounterStorage.record(Attributes.builder().put("key1", "a").build(), 1); + longCounterStorage.record(Attributes.builder().put("key1", "a").build(), 2); + + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> point.hasValue(3).hasAttributes(attributeEntry("key1", "a"))))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void collect_CumulativeReportsCumulativeObservations(MemoryMode memoryMode) { + setup(memoryMode); + + // Record measurement and collect at time START_SECONDS + 10s + testClock.advance(Duration.ofSeconds(10)); + longCounterStorage.record(Attributes.empty(), 3); + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(3) + .hasAttributes(Attributes.empty()))); + registeredReader.setLastCollectEpochNanos(testClock.now()); + + // Record measurements and collect at time START_SECONDS + 30s + testClock.advance(Duration.ofSeconds(20)); + longCounterStorage.record(Attributes.empty(), 3); + longCounterStorage.record(Attributes.builder().put("key", "value1").build(), 6); + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(3) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(testClock.now() - Duration.ofSeconds(20).toNanos()) + .hasEpochNanos(testClock.now()) + .hasValue(6) + .hasAttributes(Attributes.builder().put("key", "value1").build()))); + registeredReader.setLastCollectEpochNanos(testClock.now()); + + // Record measurement and collect at time START_SECONDS + 35s + testClock.advance(Duration.ofSeconds(5)); + longCounterStorage.record(Attributes.empty(), 4); + longCounterStorage.record(Attributes.builder().put("key", "value2").build(), 5); + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasEpochNanos(testClock.now()) + .hasValue(4) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(testClock.now() - Duration.ofSeconds(5).toNanos()) + .hasEpochNanos(testClock.now()) + .hasValue(5) + .hasAttributes(Attributes.builder().put("key", "value2").build()))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void collect_CumulativeSeriesDisappearsAndReappears(MemoryMode memoryMode) { + setup(memoryMode); + + Attributes attrA = Attributes.empty(); + Attributes attrB = Attributes.builder().put("key", "b").build(); + + // Collection 1: both series reported. start time = instrument creation time + // (START_SECOND_NANOS) + testClock.advance(Duration.ofSeconds(10)); + longCounterStorage.record(attrA, 1); + longCounterStorage.record(attrB, 2); + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasAttributes(attrA) + .hasValue(1), + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasAttributes(attrB) + .hasValue(2))); + registeredReader.setLastCollectEpochNanos(testClock.now()); + + // Collection 2: only attrA reported; attrB disappears and its handle is removed. + testClock.advance(Duration.ofSeconds(10)); + longCounterStorage.record(attrA, 3); + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(START_SECOND_NANOS).hasAttributes(attrA).hasValue(3))); + registeredReader.setLastCollectEpochNanos(testClock.now()); + long collectTime2 = testClock.now(); + + // Collection 3: attrB reappears. Its start time should be the time of the collection + // immediately preceding its reappearance (collectTime2), not the original creation time. + testClock.advance(Duration.ofSeconds(10)); + longCounterStorage.record(attrA, 5); + longCounterStorage.record(attrB, 7); + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(START_SECOND_NANOS) + .hasAttributes(attrA) + .hasValue(5), + point -> + point.hasStartEpochNanos(collectTime2).hasAttributes(attrB).hasValue(7))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void collect_CumulativeRetainsLiveSeriesWhenStaleSeriesAreRemoved(MemoryMode memoryMode) { + setup(memoryMode); + + // Enough series to share buckets, but under the cardinality limit so there's no overflow + // series. + int seriesCount = 20; + + // First collection reports everything. + testClock.advance(Duration.ofSeconds(10)); + for (int i = 0; i < seriesCount; i++) { + longCounterStorage.record(Attributes.builder().put("key", "v" + i).build(), 1); } + longCounterStorage.collect(resource, scope, testClock.now()); + registeredReader.setLastCollectEpochNanos(testClock.now()); + + // Next time only the even series report; the odd ones go stale and get removed while iterating. + // None of the live series should be skipped. + testClock.advance(Duration.ofSeconds(10)); + Set expected = new LinkedHashSet<>(); + for (int i = 0; i < seriesCount; i += 2) { + Attributes attributes = Attributes.builder().put("key", "v" + i).build(); + longCounterStorage.record(attributes, 2); + expected.add(attributes); + } + + MetricData metricData = longCounterStorage.collect(resource, scope, testClock.now()); + Set collected = + metricData.getLongSumData().getPoints().stream() + .map(PointData::getAttributes) + .collect(Collectors.toCollection(LinkedHashSet::new)); + + assertThat(collected).isEqualTo(expected); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void collect_DeltaComputesDiff(MemoryMode memoryMode) { + setup(memoryMode); + + when(reader.getAggregationTemporality(any())).thenReturn(AggregationTemporality.DELTA); + longCounterStorage = + AsynchronousMetricStorage.create( + registeredReader, + registeredView, + testClock, + InstrumentDescriptor.create( + "long-counter", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), + asExemplarFilterInternal(ExemplarFilter.alwaysOff()), + /* enabled= */ true); - assertThat(longCounterStorage.collectAndReset(resource, scope, 0, testClock.nanoTime())) - .satisfies( - metricData -> - assertThat(metricData.getLongSumData().getPoints()) - .hasSize(MetricStorageUtils.MAX_ACCUMULATIONS)); - logs.assertContains("Instrument long-counter has exceeded the maximum allowed accumulations"); + // Record measurement and collect at time 10 + longCounterStorage.record(Attributes.empty(), 3); + assertThat(longCounterStorage.collect(resource, scope, 10)) + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(testClock.now()) + .hasEpochNanos(10) + .hasValue(3) + .hasAttributes(Attributes.empty()))); + registeredReader.setLastCollectEpochNanos(10); + + // Record measurement and collect at time 30 + longCounterStorage.record(Attributes.empty(), 3); + longCounterStorage.record(Attributes.builder().put("key", "value1").build(), 6); + assertThat(longCounterStorage.collect(resource, scope, 30)) + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(10) + .hasEpochNanos(30) + .hasValue(0) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(10) + .hasEpochNanos(30) + .hasValue(6) + .hasAttributes(Attributes.builder().put("key", "value1").build()))); + registeredReader.setLastCollectEpochNanos(30); + + // Record measurement and collect at time 35 + longCounterStorage.record(Attributes.empty(), 4); + longCounterStorage.record(Attributes.builder().put("key", "value2").build(), 5); + assertThat(longCounterStorage.collect(resource, scope, 35)) + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(30) + .hasEpochNanos(35) + .hasValue(1) + .hasAttributes(Attributes.empty()), + point -> + point + .hasStartEpochNanos(30) + .hasEpochNanos(35) + .hasValue(5) + .hasAttributes(Attributes.builder().put("key", "value2").build()))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordLong_AlwaysOnCollectsExemplars(MemoryMode memoryMode) { + setup(memoryMode, AggregationTemporality.CUMULATIVE, ExemplarFilter.alwaysOn()); + + longCounterStorage.record(Attributes.empty(), 3); + + assertThat(longCounterStorage.collect(resource, scope, testClock.now())) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> + point + .hasValue(3) + .hasAttributes(Attributes.empty()) + .hasExemplarsSatisfying(exemplar -> exemplar.hasValue(3)))); } @Test - void record_DuplicateAttributes() { - longCounterStorage.recordLong(1, Attributes.builder().put("key1", "a").build()); - longCounterStorage.recordLong(2, Attributes.builder().put("key1", "a").build()); - - assertThat(longCounterStorage.collectAndReset(resource, scope, 0, testClock.nanoTime())) - .satisfies( - metricData -> - assertThat(metricData) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - point -> - point.hasValue(1).hasAttributes(attributeEntry("key1", "a"))))); - logs.assertContains( - "Instrument long-counter has recorded multiple values for the same attributes"); + void collect_reusableData_reusedObjectsAreReturnedOnSecondCall() { + setup(REUSABLE_DATA); + + longCounterStorage.record(Attributes.builder().put("key", "a").build(), 1); + longCounterStorage.record(Attributes.builder().put("key", "b").build(), 2); + longCounterStorage.record(Attributes.builder().put("key", "c").build(), 3); + + MetricData firstCollectMetricData = + longCounterStorage.collect(resource, scope, testClock.now()); + assertThat(firstCollectMetricData) + .satisfies(metricData -> + assertThat(metricData) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + point -> + point + .hasValue(1) + .hasAttributes(attributeEntry("key", "a")) + .isInstanceOf(MutableLongPointData.class), + point -> + point + .hasValue(2) + .hasAttributes(attributeEntry("key", "b")) + .isInstanceOf(MutableLongPointData.class), + point -> + point + .hasValue(3) + .hasAttributes(attributeEntry("key", "c")) + .isInstanceOf(MutableLongPointData.class)))); + + MetricData secondCollectMetricData = + longCounterStorage.collect(resource, scope, testClock.now()); + + Collection secondCollectPoints = + secondCollectMetricData.getData().getPoints(); + Collection firstCollectionPoints = + firstCollectMetricData.getData().getPoints(); + assertThat(secondCollectPoints).hasSameSizeAs(firstCollectionPoints); + + // Show that second returned objects have been used in first collect response as well + // which proves there is reuse. + for (PointData firstCollectionPoint : firstCollectionPoints) { + assertThat(secondCollectPoints) + .anySatisfy(point -> assertThat(point).isSameAs(firstCollectionPoint)); + } + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void enabledThenDisable_recordAndCollect(MemoryMode memoryMode) { + setup(memoryMode); + + longCounterStorage.setEnabled(false); + + longCounterStorage.record(Attributes.empty(), 10); + + assertThat(longCounterStorage.collect(resource, scope, 0).isEmpty()).isTrue(); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void enabledThenDisableThenEnable_recordAndCollect(MemoryMode memoryMode) { + setup(memoryMode); + + longCounterStorage.setEnabled(false); + longCounterStorage.setEnabled(true); + + longCounterStorage.record(Attributes.empty(), 10); + + assertThat(longCounterStorage.collect(resource, scope, 0).isEmpty()).isFalse(); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistrationTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistrationTest.java index 24e903214df..47f45028e6e 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistrationTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/CallbackRegistrationTest.java @@ -19,14 +19,18 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.export.MetricReader; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; +import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -49,22 +53,24 @@ class CallbackRegistrationTest { "description", "unit", InstrumentType.OBSERVABLE_COUNTER, - InstrumentValueType.LONG); + InstrumentValueType.LONG, + Advice.empty()); private static final InstrumentDescriptor DOUBLE_INSTRUMENT = InstrumentDescriptor.create( "double-counter", "description", "unit", InstrumentType.OBSERVABLE_COUNTER, - InstrumentValueType.LONG); + InstrumentValueType.LONG, + Advice.empty()); @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(CallbackRegistration.class); @Mock private MetricReader reader; - @Mock private AsynchronousMetricStorage storage1; - @Mock private AsynchronousMetricStorage storage2; - @Mock private AsynchronousMetricStorage storage3; + @Mock private AsynchronousMetricStorage storage1; + @Mock private AsynchronousMetricStorage storage2; + @Mock private AsynchronousMetricStorage storage3; private RegisteredReader registeredReader; private SdkObservableMeasurement measurement1; @@ -72,7 +78,8 @@ class CallbackRegistrationTest { @BeforeEach void setup() { - registeredReader = RegisteredReader.create(reader); + when(reader.getMemoryMode()).thenReturn(MemoryMode.IMMUTABLE_DATA); + registeredReader = RegisteredReader.create(reader, ViewRegistry.create()); when(storage1.getRegisteredReader()).thenReturn(registeredReader); when(storage2.getRegisteredReader()).thenReturn(registeredReader); when(storage3.getRegisteredReader()).thenReturn(registeredReader); @@ -85,16 +92,46 @@ void setup() { } @Test - void callbackDescription() { - assertThatThrownBy(() -> CallbackRegistration.callbackDescription(Collections.emptyList())) + void stringRepresentation() { + Runnable callback = () -> {}; + assertThatThrownBy(() -> CallbackRegistration.create(Collections.emptyList(), callback)) .isInstanceOf(IllegalStateException.class) .hasMessage("Callback with no instruments is not allowed"); - assertThat(CallbackRegistration.callbackDescription(Collections.singletonList(LONG_INSTRUMENT))) - .isEqualTo("Instrument long-counter"); assertThat( - CallbackRegistration.callbackDescription( - Arrays.asList(LONG_INSTRUMENT, DOUBLE_INSTRUMENT))) - .isEqualTo("BatchCallback([long-counter,double-counter])"); + CallbackRegistration.create(Collections.singletonList(measurement1), callback) + .toString()) + .isEqualTo( + "CallbackRegistration{" + + "instrumentDescriptors=[" + + "InstrumentDescriptor{" + + "name=double-counter, " + + "description=description, " + + "unit=unit, " + + "type=OBSERVABLE_COUNTER, " + + "valueType=LONG, " + + "advice=Advice{explicitBucketBoundaries=null, attributes=null}" + + "}]}"); + assertThat( + CallbackRegistration.create(Arrays.asList(measurement1, measurement2), callback) + .toString()) + .isEqualTo( + "CallbackRegistration{" + + "instrumentDescriptors=[" + + "InstrumentDescriptor{" + + "name=double-counter, " + + "description=description, " + + "unit=unit, " + + "type=OBSERVABLE_COUNTER, " + + "valueType=LONG, " + + "advice=Advice{explicitBucketBoundaries=null, attributes=null}}, " + + "InstrumentDescriptor{" + + "name=long-counter, " + + "description=description, " + + "unit=unit, " + + "type=OBSERVABLE_COUNTER, " + + "valueType=LONG, " + + "advice=Advice{explicitBucketBoundaries=null, attributes=null}" + + "}]}"); } @Test @@ -110,9 +147,9 @@ void invokeCallback_Double() { callbackRegistration.invokeCallback(registeredReader); assertThat(counter.get()).isEqualTo(1.1); - verify(storage1).recordDouble(1.1, Attributes.builder().put("key", "val").build()); - verify(storage2, never()).recordDouble(anyDouble(), any()); - verify(storage3, never()).recordDouble(anyDouble(), any()); + verify(storage1).record(Attributes.builder().put("key", "val").build(), 1.1); + verify(storage2, never()).record(any(), anyDouble()); + verify(storage3, never()).record(any(), anyDouble()); } @Test @@ -128,9 +165,9 @@ void invokeCallback_Long() { callbackRegistration.invokeCallback(registeredReader); assertThat(counter.get()).isEqualTo(1); - verify(storage1, never()).recordLong(anyLong(), any()); - verify(storage2).recordLong(1, Attributes.builder().put("key", "val").build()); - verify(storage3).recordLong(1, Attributes.builder().put("key", "val").build()); + verify(storage1, never()).record(any(), anyLong()); + verify(storage2).record(Attributes.builder().put("key", "val").build(), 1); + verify(storage3).record(Attributes.builder().put("key", "val").build(), 1); } @Test @@ -151,9 +188,9 @@ void invokeCallback_MultipleMeasurements() { assertThat(doubleCounter.get()).isEqualTo(1.1); assertThat(longCounter.get()).isEqualTo(1); - verify(storage1).recordDouble(1.1, Attributes.builder().put("key", "val").build()); - verify(storage2).recordLong(1, Attributes.builder().put("key", "val").build()); - verify(storage3).recordLong(1, Attributes.builder().put("key", "val").build()); + verify(storage1).record(Attributes.builder().put("key", "val").build(), 1.1); + verify(storage2).record(Attributes.builder().put("key", "val").build(), 1); + verify(storage3).record(Attributes.builder().put("key", "val").build(), 1); } @Test @@ -174,6 +211,59 @@ void invokeCallback_NoStorage() { assertThat(counter.get()).isEqualTo(0); } + @Test + void invokeCallback_RestoresContextClassLoader() { + // Simulate the context class loader at registration time + ClassLoader registrationClassLoader = new ClassLoader() {}; + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + + Thread.currentThread().setContextClassLoader(registrationClassLoader); + AtomicReference observedClassLoader = new AtomicReference<>(); + Runnable callback = + () -> observedClassLoader.set(Thread.currentThread().getContextClassLoader()); + CallbackRegistration callbackRegistration = + CallbackRegistration.create(Collections.singletonList(measurement2), callback); + Thread.currentThread().setContextClassLoader(originalClassLoader); + + // Simulate invocation on a thread with null context class loader (like DaemonThreadFactory) + Thread.currentThread().setContextClassLoader(null); + callbackRegistration.invokeCallback(registeredReader); + + // Callback should have seen the registration-time classloader + assertThat(observedClassLoader.get()).isSameAs(registrationClassLoader); + + // After invocation, the thread's context classloader should be restored to null + assertThat(Thread.currentThread().getContextClassLoader()).isNull(); + + // Clean up + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + + @Test + void invokeCallback_RestoresContextClassLoaderOnException() { + ClassLoader registrationClassLoader = new ClassLoader() {}; + ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); + + Thread.currentThread().setContextClassLoader(registrationClassLoader); + Runnable callback = + () -> { + throw new RuntimeException("Error!"); + }; + CallbackRegistration callbackRegistration = + CallbackRegistration.create(Collections.singletonList(measurement2), callback); + Thread.currentThread().setContextClassLoader(originalClassLoader); + + // Simulate invocation on a thread with null context class loader + Thread.currentThread().setContextClassLoader(null); + callbackRegistration.invokeCallback(registeredReader); + + // Context classloader should still be restored even after exception + assertThat(Thread.currentThread().getContextClassLoader()).isNull(); + + // Clean up + Thread.currentThread().setContextClassLoader(originalClassLoader); + } + @Test void invokeCallback_MultipleMeasurements_ThrowsException() { Runnable callback = @@ -185,11 +275,13 @@ void invokeCallback_MultipleMeasurements_ThrowsException() { callbackRegistration.invokeCallback(registeredReader); - verify(storage1, never()).recordDouble(anyDouble(), any()); - verify(storage2, never()).recordDouble(anyDouble(), any()); - verify(storage3, never()).recordDouble(anyDouble(), any()); - logs.assertContains( - "An exception occurred invoking callback for BatchCallback([double-counter,long-counter])"); + verify(storage1, never()).record(any(), anyLong()); + verify(storage1, never()).record(any(), anyDouble()); + verify(storage2, never()).record(any(), anyLong()); + verify(storage2, never()).record(any(), anyDouble()); + verify(storage3, never()).record(any(), anyLong()); + verify(storage3, never()).record(any(), anyDouble()); + logs.assertContains("An exception occurred invoking callback"); } @Test @@ -203,10 +295,13 @@ void invokeCallback_SingleMeasurement_ThrowsException() { callbackRegistration.invokeCallback(registeredReader); - verify(storage1, never()).recordDouble(anyDouble(), any()); - verify(storage2, never()).recordDouble(anyDouble(), any()); - verify(storage3, never()).recordDouble(anyDouble(), any()); + verify(storage1, never()).record(any(), anyLong()); + verify(storage1, never()).record(any(), anyDouble()); + verify(storage2, never()).record(any(), anyLong()); + verify(storage2, never()).record(any(), anyDouble()); + verify(storage3, never()).record(any(), anyLong()); + verify(storage3, never()).record(any(), anyDouble()); - logs.assertContains("An exception occurred invoking callback for Instrument long-counter"); + logs.assertContains("An exception occurred invoking callback"); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounterTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounterTest.java deleted file mode 100644 index 618b43a392e..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ExponentialCounterTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import static org.assertj.core.api.Assertions.assertThat; - -import java.util.stream.Stream; -import org.junit.jupiter.params.ParameterizedTest; -import org.junit.jupiter.params.provider.MethodSource; - -public class ExponentialCounterTest { - - static Stream counterProviders() { - return Stream.of( - ExponentialCounterFactory.mapCounter(), ExponentialCounterFactory.circularBufferCounter()); - } - - @ParameterizedTest - @MethodSource("counterProviders") - void returnsZeroOutsidePopulatedRange(ExponentialCounterFactory counterFactory) { - ExponentialCounter counter = counterFactory.newCounter(10); - assertThat(counter.get(0)).isEqualTo(0); - assertThat(counter.get(100)).isEqualTo(0); - counter.increment(2, 1); - counter.increment(99, 1); - assertThat(counter.get(0)).isEqualTo(0); - assertThat(counter.get(100)).isEqualTo(0); - } - - @ParameterizedTest - @MethodSource("counterProviders") - void expandLower(ExponentialCounterFactory counterFactory) { - ExponentialCounter counter = counterFactory.newCounter(320); - assertThat(counter.increment(10, 1)).isTrue(); - // Add BEFORE the initial see (array index 0) and make sure we wrap around the datastructure. - assertThat(counter.increment(0, 1)).isTrue(); - assertThat(counter.get(10)).isEqualTo(1); - assertThat(counter.get(0)).isEqualTo(1); - assertThat(counter.getIndexStart()).as("index start").isEqualTo(0); - assertThat(counter.getIndexEnd()).as("index end").isEqualTo(10); - // Add AFTER initial entry and just push back end. - assertThat(counter.increment(20, 1)).isTrue(); - assertThat(counter.get(20)).isEqualTo(1); - assertThat(counter.get(10)).isEqualTo(1); - assertThat(counter.get(0)).isEqualTo(1); - assertThat(counter.getIndexStart()).isEqualTo(0); - assertThat(counter.getIndexEnd()).isEqualTo(20); - } - - @ParameterizedTest - @MethodSource("counterProviders") - void shouldFailAtLimit(ExponentialCounterFactory counterFactory) { - ExponentialCounter counter = counterFactory.newCounter(320); - assertThat(counter.increment(0, 1)).isTrue(); - assertThat(counter.increment(319, 1)).isTrue(); - // Check state - assertThat(counter.getIndexStart()).as("index start").isEqualTo(0); - assertThat(counter.getIndexEnd()).as("index start").isEqualTo(319); - assertThat(counter.get(0)).as("counter[0]").isEqualTo(1); - assertThat(counter.get(319)).as("counter[319]").isEqualTo(1); - // Adding over the maximum # of buckets - assertThat(counter.increment(3000, 1)).isFalse(); - } - - @ParameterizedTest - @MethodSource("counterProviders") - void shouldCopyCounters(ExponentialCounterFactory counterFactory) { - ExponentialCounter counter = counterFactory.newCounter(2); - assertThat(counter.increment(2, 1)).isTrue(); - assertThat(counter.increment(1, 1)).isTrue(); - assertThat(counter.increment(3, 1)).isFalse(); - - ExponentialCounter copy = counterFactory.copy(counter); - assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); - assertThat(copy.get(2)).as("copy[2]").isEqualTo(1); - assertThat(copy.getMaxSize()).isEqualTo(counter.getMaxSize()); - assertThat(copy.getIndexStart()).isEqualTo(counter.getIndexStart()); - assertThat(copy.getIndexEnd()).isEqualTo(counter.getIndexEnd()); - // Mutate copy and make sure original is unchanged. - assertThat(copy.increment(2, 1)).isTrue(); - assertThat(copy.get(2)).as("copy[2]").isEqualTo(2); - assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); - } - - @ParameterizedTest - @MethodSource("counterProviders") - void shouldCopyMapCounters(ExponentialCounterFactory counterFactory) { - ExponentialCounter counter = ExponentialCounterFactory.mapCounter().newCounter(2); - assertThat(counter.increment(2, 1)).isTrue(); - assertThat(counter.increment(1, 1)).isTrue(); - assertThat(counter.increment(3, 1)).isFalse(); - - ExponentialCounter copy = counterFactory.copy(counter); - assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); - assertThat(copy.get(2)).as("copy[2]").isEqualTo(1); - assertThat(copy.getMaxSize()).isEqualTo(counter.getMaxSize()); - assertThat(copy.getIndexStart()).isEqualTo(counter.getIndexStart()); - assertThat(copy.getIndexEnd()).isEqualTo(counter.getIndexEnd()); - // Mutate copy and make sure original is unchanged. - assertThat(copy.increment(2, 1)).isTrue(); - assertThat(copy.get(2)).as("copy[2]").isEqualTo(2); - assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); - } - - @ParameterizedTest - @MethodSource("counterProviders") - void shouldCopyCircularBufferCounters(ExponentialCounterFactory counterFactory) { - ExponentialCounter counter = ExponentialCounterFactory.circularBufferCounter().newCounter(2); - assertThat(counter.increment(2, 1)).isTrue(); - assertThat(counter.increment(1, 1)).isTrue(); - assertThat(counter.increment(3, 1)).isFalse(); - - ExponentialCounter copy = counterFactory.copy(counter); - assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); - assertThat(copy.get(2)).as("copy[2]").isEqualTo(1); - assertThat(copy.getMaxSize()).isEqualTo(counter.getMaxSize()); - assertThat(copy.getIndexStart()).isEqualTo(counter.getIndexStart()); - assertThat(copy.getIndexEnd()).isEqualTo(counter.getIndexEnd()); - // Mutate copy and make sure original is unchanged. - assertThat(copy.increment(2, 1)).isTrue(); - assertThat(copy.get(2)).as("copy[2]").isEqualTo(2); - assertThat(counter.get(2)).as("counter[2]").isEqualTo(1); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistryTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistryTest.java index 2217189eb39..4ca2d8ee8a1 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistryTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageRegistryTest.java @@ -9,27 +9,22 @@ import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; import io.opentelemetry.sdk.resources.Resource; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.RegisterExtension; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; /** Unit tests for {@link MetricStorageRegistry}. */ -@ExtendWith(MockitoExtension.class) @SuppressLogger(MetricStorageRegistry.class) class MetricStorageRegistryTest { private static final MetricDescriptor SYNC_DESCRIPTOR = @@ -46,56 +41,40 @@ class MetricStorageRegistryTest { @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(MetricStorageRegistry.class); - @Mock private MetricReader reader; - private RegisteredReader registeredReader; - - @BeforeEach - void setup() { - registeredReader = RegisteredReader.create(reader); - } - @Test void register_Sync() { - TestMetricStorage storage = new TestMetricStorage(SYNC_DESCRIPTOR, registeredReader); + TestMetricStorage storage = new TestMetricStorage(SYNC_DESCRIPTOR); assertThat(metricStorageRegistry.register(storage)).isSameAs(storage); assertThat(metricStorageRegistry.register(storage)).isSameAs(storage); - assertThat( - metricStorageRegistry.register( - new TestMetricStorage(SYNC_DESCRIPTOR, registeredReader))) + assertThat(metricStorageRegistry.register(new TestMetricStorage(SYNC_DESCRIPTOR))) .isSameAs(storage); } @Test void register_SyncIncompatibleDescriptor() { - TestMetricStorage storage = new TestMetricStorage(SYNC_DESCRIPTOR, registeredReader); + TestMetricStorage storage = new TestMetricStorage(SYNC_DESCRIPTOR); assertThat(metricStorageRegistry.register(storage)).isSameAs(storage); assertThat(logs.getEvents()).isEmpty(); - assertThat( - metricStorageRegistry.register( - new TestMetricStorage(OTHER_SYNC_DESCRIPTOR, registeredReader))) + assertThat(metricStorageRegistry.register(new TestMetricStorage(OTHER_SYNC_DESCRIPTOR))) .isNotSameAs(storage); logs.assertContains("Found duplicate metric definition"); } @Test void register_Async() { - TestMetricStorage storage = new TestMetricStorage(ASYNC_DESCRIPTOR, registeredReader); + TestMetricStorage storage = new TestMetricStorage(ASYNC_DESCRIPTOR); assertThat(metricStorageRegistry.register(storage)).isSameAs(storage); assertThat(metricStorageRegistry.register(storage)).isSameAs(storage); - assertThat( - metricStorageRegistry.register( - new TestMetricStorage(ASYNC_DESCRIPTOR, registeredReader))) + assertThat(metricStorageRegistry.register(new TestMetricStorage(ASYNC_DESCRIPTOR))) .isSameAs(storage); } @Test void register_AsyncIncompatibleDescriptor() { - TestMetricStorage storage = new TestMetricStorage(ASYNC_DESCRIPTOR, registeredReader); + TestMetricStorage storage = new TestMetricStorage(ASYNC_DESCRIPTOR); assertThat(metricStorageRegistry.register(storage)).isSameAs(storage); assertThat(logs.getEvents()).isEmpty(); - assertThat( - metricStorageRegistry.register( - new TestMetricStorage(OTHER_ASYNC_DESCRIPTOR, registeredReader))) + assertThat(metricStorageRegistry.register(new TestMetricStorage(OTHER_ASYNC_DESCRIPTOR))) .isNotSameAs(storage); logs.assertContains("Found duplicate metric definition"); } @@ -106,16 +85,14 @@ private static MetricDescriptor descriptor( View.builder().build(), SourceInfo.fromCurrentStack(), InstrumentDescriptor.create( - name, description, "1", instrumentType, InstrumentValueType.DOUBLE)); + name, description, "1", instrumentType, InstrumentValueType.DOUBLE, Advice.empty())); } private static final class TestMetricStorage implements MetricStorage, WriteableMetricStorage { private final MetricDescriptor descriptor; - private final RegisteredReader registeredReader; - TestMetricStorage(MetricDescriptor descriptor, RegisteredReader registeredReader) { + TestMetricStorage(MetricDescriptor descriptor) { this.descriptor = descriptor; - this.registeredReader = registeredReader; } @Override @@ -124,22 +101,36 @@ public MetricDescriptor getMetricDescriptor() { } @Override - public RegisteredReader getRegisteredReader() { - return registeredReader; + public MetricData collect( + Resource resource, InstrumentationScopeInfo instrumentationScopeInfo, long epochNanos) { + return null; } @Override - public MetricData collectAndReset( - Resource resource, - InstrumentationScopeInfo instrumentationScopeInfo, - long startEpochNanos, - long epochNanos) { - return null; - } + public void recordLong(long value, Attributes attributes, Context context) {} + + @Override + public void recordDouble(double value, Attributes attributes, Context context) {} @Override public BoundStorageHandle bind(Attributes attributes) { - return null; + return new BoundStorageHandle() { + @Override + public void recordLong(long value, Context context) {} + + @Override + public void recordDouble(double value, Context context) {} + }; + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void setEnabled(boolean enabled) { + throw new UnsupportedOperationException("Not implemented"); } } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageUtilsTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageUtilsTest.java deleted file mode 100644 index 08c166039c2..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/MetricStorageUtilsTest.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.AssertionsForClassTypes.entry; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -class MetricStorageUtilsTest { - - private static final Attributes a = Attributes.of(AttributeKey.stringKey("a"), "a"); - private static final Attributes b = Attributes.of(AttributeKey.stringKey("b"), "b"); - private static final Attributes c = Attributes.of(AttributeKey.stringKey("c"), "c"); - private static final Attributes d = Attributes.of(AttributeKey.stringKey("d"), "d"); - private static final Attributes e = Attributes.of(AttributeKey.stringKey("e"), "e"); - private Map result; - private Map toMerge; - - @BeforeEach - public void setup() { - result = new HashMap<>(); - result.put(a, "A"); - result.put(b, "B"); - result.put(d, null); - toMerge = new HashMap<>(); - toMerge.put(b, "B'"); - toMerge.put(c, "C"); - toMerge.put(e, null); - } - - @Test - void mergeInPlace() { - Aggregator agg = buildConcatAggregator(); - MetricStorageUtils.mergeInPlace(result, toMerge, agg); - - assertThat(result).containsOnly(entry(b, "merge(B,B')"), entry(c, "C")); - } - - @Test - void diffInPlace() { - Aggregator agg = buildConcatAggregator(); - MetricStorageUtils.diffInPlace(result, toMerge, agg); - - assertThat(result).containsOnly(entry(b, "diff(B,B')"), entry(c, "C")); - } - - @SuppressWarnings("unchecked") - private static Aggregator buildConcatAggregator() { - Aggregator agg = mock(Aggregator.class); - doAnswer( - invocation -> { - String previousCumulative = invocation.getArgument(0); - String delta = invocation.getArgument(1); - return "merge(" + previousCumulative + "," + delta + ")"; - }) - .when(agg) - .merge(anyString(), anyString()); - doAnswer( - invocation -> { - String previousCumulative = invocation.getArgument(0); - String delta = invocation.getArgument(1); - return "diff(" + previousCumulative + "," + delta + ")"; - }) - .when(agg) - .diff(anyString(), anyString()); - return agg; - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ObjectPoolTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ObjectPoolTest.java new file mode 100644 index 00000000000..ee90d303783 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/ObjectPoolTest.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; + +import java.util.Arrays; +import java.util.List; +import java.util.function.Supplier; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ObjectPoolTest { + private ObjectPool objectPool; + + @BeforeEach + void setUp() { + Supplier supplier = StringBuilder::new; + objectPool = new ObjectPool<>(supplier); + } + + @Test + void testBorrowObjectWhenPoolIsEmpty() { + StringBuilder result = objectPool.borrowObject(); + assertThat(result.toString()).isEmpty(); + } + + @Test + void testReturnAndBorrowMultipleObjects() { + // Borrow three objects + StringBuilder borrowed1 = objectPool.borrowObject(); + StringBuilder borrowed2 = objectPool.borrowObject(); + StringBuilder borrowed3 = objectPool.borrowObject(); + + // Modify and return the borrowed objects + borrowed1.append("pooledObject1"); + objectPool.returnObject(borrowed1); + borrowed2.append("pooledObject2"); + objectPool.returnObject(borrowed2); + borrowed3.append("pooledObject3"); + objectPool.returnObject(borrowed3); + + // Borrow three objects, which should be the same ones we just returned + StringBuilder result1 = objectPool.borrowObject(); + StringBuilder result2 = objectPool.borrowObject(); + StringBuilder result3 = objectPool.borrowObject(); + + // Verify the results using AssertJ assertions and reference comparison + List originalObjects = Arrays.asList(borrowed1, borrowed2, borrowed3); + List borrowedObjects = Arrays.asList(result1, result2, result3); + + assertThat(originalObjects).hasSize(3); + assertThat(borrowedObjects).hasSize(3); + + for (StringBuilder original : originalObjects) { + assertThat(borrowedObjects).anySatisfy(borrowed -> assertThat(borrowed).isSameAs(original)); + } + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java new file mode 100644 index 00000000000..800894a651b --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/PooledHashMapTest.java @@ -0,0 +1,118 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class PooledHashMapTest { + + private PooledHashMap map; + + @BeforeEach + void setup() { + map = new PooledHashMap<>(); + } + + @Test + void putAndGetTest() { + map.put("One", 1); + assertThat(map.get("One")).isEqualTo(1); + } + + @Test + void removeTest() { + map.put("One", 1); + map.remove("One"); + assertThat(map.get("One")).isNull(); + } + + @Test + void sizeTest() { + map.put("One", 1); + map.put("Two", 2); + assertThat(map.size()).isEqualTo(2); + } + + @Test + void isEmptyTest() { + assertThat(map.isEmpty()).isTrue(); + map.put("One", 1); + assertThat(map.isEmpty()).isFalse(); + } + + @Test + void containsKeyTest() { + map.put("One", 1); + assertThat(map.containsKey("One")).isTrue(); + assertThat(map.containsKey("Two")).isFalse(); + } + + @Test + void clearTest() { + map.put("One", 1); + map.put("Two", 2); + map.clear(); + assertThat(map.isEmpty()).isTrue(); + } + + @Test + void forEachTest() { + map.put("One", 1); + map.put("Two", 2); + + Map actualMap = new HashMap<>(); + map.forEach(actualMap::put); + + assertThat(actualMap).containsOnlyKeys("One", "Two").containsValues(1, 2); + } + + @Test + void forEachAllowsRemovalOfCurrentEntry() { + // Keys with the same hashcode always share a bucket (independent of capacity), mirroring + // collection removing a stale series while iterating the others. + PooledHashMap collidingMap = new PooledHashMap<>(); + SameBucketKey first = new SameBucketKey("first"); + SameBucketKey second = new SameBucketKey("second"); + collidingMap.put(first, 1); + collidingMap.put(second, 2); + + Map visited = new HashMap<>(); + collidingMap.forEach((key, value) -> { + visited.put(key, value); + if (visited.size() == 1) { + collidingMap.remove(key); // drop the first one we see + } + }); + + assertThat(visited).containsOnlyKeys(first, second).containsValues(1, 2); + assertThat(collidingMap.size()).isEqualTo(1); + } + + /** Key whose hashcode is constant, so all instances fall in the same bucket. */ + private static final class SameBucketKey { + private final String name; + + SameBucketKey(String name) { + this.name = name; + } + + @Override + public int hashCode() { + return 1; + } + + @Override + public boolean equals(@Nullable Object o) { + return o instanceof SameBucketKey && name.equals(((SameBucketKey) o).name); + } + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurementTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurementTest.java new file mode 100644 index 00000000000..8b859f55479 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SdkObservableMeasurementTest.java @@ -0,0 +1,148 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.state; + +import static io.opentelemetry.sdk.metrics.data.AggregationTemporality.CUMULATIVE; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.InstrumentValueType; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; +import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Arrays; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.slf4j.event.Level; + +@SuppressWarnings("rawtypes") +class SdkObservableMeasurementTest { + + @RegisterExtension + final LogCapturer logs = + LogCapturer.create().captureForLogger(SdkObservableMeasurement.class.getName(), Level.DEBUG); + + private AsynchronousMetricStorage mockAsyncStorage1; + private AsynchronousMetricStorage mockAsyncStorage2; + private RegisteredReader registeredReader1; + private SdkObservableMeasurement sdkObservableMeasurement; + + private void setup(MemoryMode memoryMode) { + InstrumentationScopeInfo instrumentationScopeInfo = + InstrumentationScopeInfo.builder("test-scope").build(); + InstrumentDescriptor instrumentDescriptor = + InstrumentDescriptor.create( + "testCounter", + "an instrument for testing purposes", + "ms", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()); + + InMemoryMetricReader reader1 = + InMemoryMetricReader.builder() + .setAggregationTemporalitySelector(instrumentType -> CUMULATIVE) + .setMemoryMode(memoryMode) + .build(); + registeredReader1 = RegisteredReader.create(reader1, ViewRegistry.create()); + + InMemoryMetricReader reader2 = InMemoryMetricReader.builder().setMemoryMode(memoryMode).build(); + RegisteredReader registeredReader2 = RegisteredReader.create(reader2, ViewRegistry.create()); + + mockAsyncStorage1 = mock(AsynchronousMetricStorage.class); + when(mockAsyncStorage1.getRegisteredReader()).thenReturn(registeredReader1); + mockAsyncStorage2 = mock(AsynchronousMetricStorage.class); + when(mockAsyncStorage2.getRegisteredReader()).thenReturn(registeredReader2); + + sdkObservableMeasurement = + SdkObservableMeasurement.create( + instrumentationScopeInfo, + instrumentDescriptor, + Arrays.asList(mockAsyncStorage1, mockAsyncStorage2)); + } + + void setupAndSetActiveReader(MemoryMode memoryMode) { + setup(memoryMode); + sdkObservableMeasurement.setActiveReader(registeredReader1); + } + + @Test + void recordLong_ImmutableData() { + setupAndSetActiveReader(MemoryMode.IMMUTABLE_DATA); + + try { + sdkObservableMeasurement.record(5); + verify(mockAsyncStorage1).record(Attributes.empty(), 5); + } finally { + sdkObservableMeasurement.unsetActiveReader(); + } + } + + @Test + void recordDouble_ImmutableData() { + setupAndSetActiveReader(MemoryMode.IMMUTABLE_DATA); + + try { + sdkObservableMeasurement.record(4.3); + verify(mockAsyncStorage1).record(Attributes.empty(), 4.3); + } finally { + sdkObservableMeasurement.unsetActiveReader(); + } + } + + @Test + void recordDouble_ReusableData() { + setupAndSetActiveReader(MemoryMode.REUSABLE_DATA); + + try { + sdkObservableMeasurement.record(4.3); + verify(mockAsyncStorage1).record(Attributes.empty(), 4.3); + + sdkObservableMeasurement.record(5.3); + verify(mockAsyncStorage1).record(Attributes.empty(), 5.3); + } finally { + sdkObservableMeasurement.unsetActiveReader(); + } + } + + @Test + void recordLong_ReusableData() { + setupAndSetActiveReader(MemoryMode.REUSABLE_DATA); + + try { + sdkObservableMeasurement.record(2); + verify(mockAsyncStorage1).record(Attributes.empty(), 2); + + sdkObservableMeasurement.record(6); + verify(mockAsyncStorage1).record(Attributes.empty(), 6); + } finally { + sdkObservableMeasurement.unsetActiveReader(); + } + } + + @Test + @SuppressLogger(SdkObservableMeasurement.class) + void recordDouble_NaN() { + setupAndSetActiveReader(MemoryMode.REUSABLE_DATA); + + sdkObservableMeasurement.record(Double.NaN); + verify(mockAsyncStorage1, never()).record(any(), anyDouble()); + logs.assertContains( + "Instrument testCounter has recorded measurement Not-a-Number (NaN) value with attributes {}. Dropping measurement."); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java index a5e48527f9f..6fd7728a754 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/SynchronousMetricStorageTest.java @@ -5,118 +5,849 @@ package io.opentelemetry.sdk.metrics.internal.state; +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; +import static io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal.asExemplarFilterInternal; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.assertj.core.api.BDDAssertions.as; +import static org.assertj.core.api.InstanceOfAssertFactories.collection; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.export.MemoryMode; import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.ExemplarFilter; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; -import io.opentelemetry.sdk.metrics.data.LongExemplarData; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; -import io.opentelemetry.sdk.metrics.export.MetricReader; import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; import io.opentelemetry.sdk.metrics.internal.aggregator.EmptyMetricData; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.metrics.internal.view.AttributesProcessor; +import io.opentelemetry.sdk.metrics.internal.view.AttributesFilters; +import io.opentelemetry.sdk.metrics.internal.view.ViewRegistry; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.assertj.DoubleSumAssert; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; import io.opentelemetry.sdk.testing.time.TestClock; -import org.junit.jupiter.api.BeforeEach; +import java.time.Duration; +import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.jupiter.MockitoExtension; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.slf4j.event.Level; -@ExtendWith(MockitoExtension.class) +@SuppressLogger(DefaultSynchronousMetricStorage.class) public class SynchronousMetricStorageTest { private static final Resource RESOURCE = Resource.empty(); private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("test", "1.0", null); + InstrumentationScopeInfo.builder("test").setVersion("1.0").build(); private static final InstrumentDescriptor DESCRIPTOR = InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.DOUBLE); + "name", + "description", + "unit", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty()); private static final MetricDescriptor METRIC_DESCRIPTOR = MetricDescriptor.create("name", "description", "unit"); + private static final int CARDINALITY_LIMIT = 25; + + @RegisterExtension + LogCapturer logs = + LogCapturer.create().captureForType(DefaultSynchronousMetricStorage.class, Level.DEBUG); + + private RegisteredReader deltaReader; + private RegisteredReader cumulativeReader; private final TestClock testClock = TestClock.create(); - private final Aggregator aggregator = - ((AggregatorFactory) Aggregation.lastValue()) - .createAggregator(DESCRIPTOR, ExemplarFilter.neverSample()); - private final AttributesProcessor attributesProcessor = AttributesProcessor.noop(); + private Aggregator aggregator; + + private void initialize(MemoryMode memoryMode) { + deltaReader = + RegisteredReader.create( + InMemoryMetricReader.builder() + .setAggregationTemporalitySelector(unused -> AggregationTemporality.DELTA) + .setMemoryMode(memoryMode) + .build(), + ViewRegistry.create()); - @Mock private MetricReader reader; - private RegisteredReader registeredReader; + cumulativeReader = + RegisteredReader.create( + InMemoryMetricReader.builder().setMemoryMode(memoryMode).build(), + ViewRegistry.create()); - @BeforeEach - void setup() { - registeredReader = RegisteredReader.create(reader); + aggregator = + spy( + ((AggregatorFactory) Aggregation.sum()) + .createAggregator( + DESCRIPTOR, asExemplarFilterInternal(ExemplarFilter.alwaysOff()), memoryMode)); } - @Test - void attributesProcessor_used() { - AttributesProcessor spyAttributesProcessor = Mockito.spy(this.attributesProcessor); - SynchronousMetricStorage accumulator = - new DefaultSynchronousMetricStorage<>( - registeredReader, METRIC_DESCRIPTOR, aggregator, spyAttributesProcessor); - accumulator.bind(Attributes.empty()); - Mockito.verify(spyAttributesProcessor).process(Attributes.empty(), Context.current()); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordDouble_NaN(MemoryMode memoryMode) { + initialize(memoryMode); + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + cumulativeReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + storage.recordDouble(Double.NaN, Attributes.empty(), Context.current()); + + logs.assertContains( + "Instrument name has recorded measurement Not-a-Number (NaN) value with attributes {}. Dropping measurement."); + verify(aggregator, never()).createHandle(anyLong()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .isEqualTo(EmptyMetricData.getInstance()); } - @Test - void attributesProcessor_applied() { - Attributes labels = Attributes.builder().put("K", "V").build(); - AttributesProcessor attributesProcessor = - AttributesProcessor.append(Attributes.builder().put("modifiedK", "modifiedV").build()); - AttributesProcessor spyLabelsProcessor = Mockito.spy(attributesProcessor); - SynchronousMetricStorage accumulator = - new DefaultSynchronousMetricStorage<>( - registeredReader, METRIC_DESCRIPTOR, aggregator, spyLabelsProcessor); - BoundStorageHandle handle = accumulator.bind(labels); - handle.recordDouble(1, labels, Context.root()); - MetricData md = - accumulator.collectAndReset(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 0, testClock.now()); + @ParameterizedTest + @EnumSource(MemoryMode.class) + void attributeFilter_applied(MemoryMode memoryMode) { + initialize(memoryMode); + + Attributes attributes = Attributes.builder().put("keep", "V").put("drop", "X").build(); + SynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + cumulativeReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.byKeyName("keep"::equals), + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + storage.recordDouble(1, attributes, Context.root()); + MetricData md = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, testClock.now()); assertThat(md) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying(point -> point.hasAttributes(attributeEntry("keep", "V")))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordAndCollect_CumulativeDoesNotReset(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + cumulativeReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record measurement and collect at time 10 + storage.recordDouble(3, Attributes.empty(), Context.current()); + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(10).hasValue(3))); + cumulativeReader.setLastCollectEpochNanos(10); + + // Record measurement and collect at time 30 + storage.recordDouble(3, Attributes.empty(), Context.current()); + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(30).hasValue(6))); + cumulativeReader.setLastCollectEpochNanos(30); + + // Record measurement and collect at time 35 + storage.recordDouble(2, Attributes.empty(), Context.current()); + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35)) + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(35).hasValue(8))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordAndCollect_CumulativeNewSeriesAfterFirstCollection(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + cumulativeReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record for series A and collect at time 10 + storage.recordDouble(3, Attributes.builder().put("series", "A").build(), Context.current()); + long seriesACreationTime = testClock.now(); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(seriesACreationTime) + .hasEpochNanos(10) + .hasValue(3) + .hasAttributes(Attributes.builder().put("series", "A").build()))); + cumulativeReader.setLastCollectEpochNanos(10); + + // Advance clock and record for both series A and a new series B + testClock.advance(Duration.ofSeconds(20)); + storage.recordDouble(5, Attributes.builder().put("series", "A").build(), Context.current()); + storage.recordDouble(7, Attributes.builder().put("series", "B").build(), Context.current()); + long seriesBCreationTime = testClock.now(); + // Series B's start time must be clock.now() at its first measurement, NOT instrument + // creation time or last collection time. + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(seriesACreationTime) + .hasEpochNanos(30) + .hasValue(8) + .hasAttributes(Attributes.builder().put("series", "A").build()), point -> - point.hasAttributes( - attributeEntry("K", "V"), attributeEntry("modifiedK", "modifiedV")))); + point + .hasStartEpochNanos(seriesBCreationTime) + .hasEpochNanos(30) + .hasValue(7) + .hasAttributes(Attributes.builder().put("series", "B").build()))); + } + + @Test + void recordAndCollect_DeltaResets_ImmutableData() { + initialize(IMMUTABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record measurement and collect at time 10 + storage.recordDouble(3, Attributes.empty(), Context.current()); + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(10).hasValue(3))); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(1); + deltaReader.setLastCollectEpochNanos(10); + + // Record measurement and collect at time 30 + storage.recordDouble(3, Attributes.empty(), Context.current()); + // AggregatorHandle should be returned to the pool on reset so shouldn't create additional + // handles + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(1); + deltaReader.setLastCollectEpochNanos(30); + + // Record measurement and collect at time 35 + storage.recordDouble(2, Attributes.empty(), Context.current()); + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35)) + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> point.hasStartEpochNanos(30).hasEpochNanos(35).hasValue(2))); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(1); } @Test - void sameAggregator_ForSameAttributes() { - SynchronousMetricStorage accumulator = - new DefaultSynchronousMetricStorage<>( - registeredReader, METRIC_DESCRIPTOR, aggregator, attributesProcessor); - BoundStorageHandle handle = accumulator.bind(Attributes.builder().put("K", "V").build()); - BoundStorageHandle duplicateHandle = - accumulator.bind(Attributes.builder().put("K", "V").build()); - try { - assertThat(duplicateHandle).isSameAs(handle); - accumulator.collectAndReset(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 0, testClock.now()); - BoundStorageHandle anotherDuplicateAggregatorHandle = - accumulator.bind(Attributes.builder().put("K", "V").build()); - try { - assertThat(anotherDuplicateAggregatorHandle).isSameAs(handle); - } finally { - anotherDuplicateAggregatorHandle.release(); - } - } finally { - duplicateHandle.release(); - handle.release(); + void recordAndCollect_DeltaResets_ReusableData() { + initialize(MemoryMode.REUSABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record measurement and collect at time 10 + storage.recordDouble(3, Attributes.empty(), Context.current()); + verify(aggregator, times(1)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point.hasStartEpochNanos(testClock.now()).hasEpochNanos(10).hasValue(3))); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + + deltaReader.setLastCollectEpochNanos(10); + + // Record measurement and collect at time 30 + storage.recordDouble(3, Attributes.empty(), Context.current()); + + // We're switched to secondary map so a handle will be created + verify(aggregator, times(2)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying( + point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + + deltaReader.setLastCollectEpochNanos(30); + + // Record measurements and collect at time 35 + storage.recordDouble(2, Attributes.empty(), Context.current()); + storage.recordDouble(4, Attributes.of(AttributeKey.stringKey("foo"), "bar"), Context.current()); + + // We don't delete aggregator handles unless max cardinality reached, hence + // aggregator handle is still there, thus no handle was created for empty(), but it will for + // the "foo" + verify(aggregator, times(3)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + + MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 35); + assertThat(metricData).hasDoubleSumSatisfying(DoubleSumAssert::isDelta); + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(2) + .anySatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(30); + assertThat(point.getEpochNanos()).isEqualTo(35); + assertThat(point.getValue()).isEqualTo(2); + assertThat(point.getAttributes()).isEqualTo(Attributes.empty()); + }) + .anySatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(30); + assertThat(point.getEpochNanos()).isEqualTo(35); + assertThat(point.getValue()).isEqualTo(4); + assertThat(point.getAttributes()) + .isEqualTo(Attributes.of(AttributeKey.stringKey("foo"), "bar")); + }))); + + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + + deltaReader.setLastCollectEpochNanos(40); + storage.recordDouble(6, Attributes.of(AttributeKey.stringKey("foo"), "bar"), Context.current()); + + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 45)) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(40); + assertThat(point.getEpochNanos()).isEqualTo(45); + assertThat(point.getValue()).isEqualTo(6); + assertThat(point.getAttributes()) + .isEqualTo(Attributes.of(AttributeKey.stringKey("foo"), "bar")); + }))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void recordAndCollect_CumulativeAtLimit(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + cumulativeReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record measurements for CARDINALITY_LIMIT - 1, since 1 slot is reserved for the overflow + // series + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); } + verify(aggregator, times(CARDINALITY_LIMIT - 1)).createHandle(testClock.now()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT - 1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + assertThat(point.getEpochNanos()).isEqualTo(10); + assertThat(point.getValue()).isEqualTo(3); + }))); + assertThat(logs.getEvents()).isEmpty(); + cumulativeReader.setLastCollectEpochNanos(10); - // If we try to collect once all bound references are gone AND no recordings have occurred, we - // should not see any labels (or metric). - assertThat( - accumulator.collectAndReset(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 0, testClock.now())) - .isEqualTo(EmptyMetricData.getInstance()); + // Record measurement for additional attribute, exceeding limit + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + CARDINALITY_LIMIT).build(), Context.current()); + // Should not create an additional handles for the overflow series + verify(aggregator, times(CARDINALITY_LIMIT)).createHandle(testClock.now()); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + assertThat(point.getEpochNanos()).isEqualTo(20); + assertThat(point.getValue()).isEqualTo(3); + }) + .noneMatch(point -> + ("value" + CARDINALITY_LIMIT + 1) + .equals(point.getAttributes().get(AttributeKey.stringKey("key")))) + .satisfiesOnlyOnce(point -> + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); + logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); + } + + @Test + void recordAndCollect_DeltaAtLimit_ImmutableDataMemoryMode() { + initialize(IMMUTABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record measurements for CARDINALITY_LIMIT - 1, since 1 slot is reserved for the overflow + // series + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + verify(aggregator, times(CARDINALITY_LIMIT - 1)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10)) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT - 1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + assertThat(point.getEpochNanos()).isEqualTo(10); + assertThat(point.getValue()).isEqualTo(3); + }))); + assertThat(storage) + .extracting("aggregatorHandlePool", as(collection(Object.class))) + .hasSize(CARDINALITY_LIMIT - 1); + + assertThat(logs.getEvents()).isEmpty(); + deltaReader.setLastCollectEpochNanos(10); + + // Record measurement for additional attribute, should not exceed limit due to reset + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + CARDINALITY_LIMIT).build(), Context.current()); + // Should use handle returned to pool instead of creating new ones + verify(aggregator, times(CARDINALITY_LIMIT - 1)).createHandle(testClock.now()); + assertThat(storage) + .extracting("aggregatorHandlePool", as(collection(Object.class))) + .hasSize(CARDINALITY_LIMIT - 2); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20)) + .hasDoubleSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasStartEpochNanos(10) + .hasEpochNanos(20) + .hasValue(3) + .hasAttributes( + Attributes.builder().put("key", "value" + CARDINALITY_LIMIT).build()))); + assertThat(storage) + .extracting("aggregatorHandlePool", as(collection(Object.class))) + .hasSize(CARDINALITY_LIMIT - 1); + assertThat(logs.getEvents()).isEmpty(); + deltaReader.setLastCollectEpochNanos(20); + + // Record CARDINALITY_LIMIT measurements, causing one measurement to exceed the cardinality + // limit and fall into the overflow series + for (int i = 0; i < CARDINALITY_LIMIT; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + // Should use handles returned to pool instead of creating new ones + verify(aggregator, times(CARDINALITY_LIMIT)).createHandle(testClock.now()); + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).hasSize(0); + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30)) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(20); + assertThat(point.getEpochNanos()).isEqualTo(30); + assertThat(point.getValue()).isEqualTo(3); + }) + .noneMatch(point -> + ("value" + CARDINALITY_LIMIT + 1) + .equals(point.getAttributes().get(AttributeKey.stringKey("key")))) + .satisfiesOnlyOnce(point -> + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); + + assertThat(storage) + .extracting("aggregatorHandlePool", as(collection(Object.class))) + .hasSize(CARDINALITY_LIMIT); + logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); + } + + @Test + void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode() { + initialize(MemoryMode.REUSABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // Record measurements for CARDINALITY_LIMIT - 1, since 1 slot is reserved for the overflow + // series + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + verify(aggregator, times(CARDINALITY_LIMIT - 1)).createHandle(testClock.now()); + + // First collect + MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10); + + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + Assertions.assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT - 1) + .allSatisfy(point -> { + Assertions.assertThat(point.getStartEpochNanos()).isEqualTo(testClock.now()); + Assertions.assertThat(point.getEpochNanos()).isEqualTo(10); + Assertions.assertThat(point.getValue()).isEqualTo(3); + }))); + + assertThat(logs.getEvents()).isEmpty(); + + deltaReader.setLastCollectEpochNanos(10); + + // Record CARDINALITY_LIMIT measurements, causing one measurement to exceed the cardinality + // limit and fall into the overflow series + for (int i = 0; i < CARDINALITY_LIMIT; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + // After first collection, we expect the secondary map which is empty to be used, + // hence handle creation will still take place + // The +1 is for the overflow handle + verify(aggregator, times((CARDINALITY_LIMIT - 1) * 2 + 1)).createHandle(testClock.now()); + + // Second collect + metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20); + + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(CARDINALITY_LIMIT) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(10); + assertThat(point.getEpochNanos()).isEqualTo(20); + assertThat(point.getValue()).isEqualTo(3); + }) + .noneMatch(point -> + ("value" + CARDINALITY_LIMIT) + .equals(point.getAttributes().get(AttributeKey.stringKey("key")))) + .satisfiesOnlyOnce(point -> + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW)))); + + assertThat(storage).extracting("aggregatorHandlePool", as(collection(Object.class))).isEmpty(); + + logs.assertContains("Instrument name has exceeded the maximum allowed cardinality"); + } + + @Test + void recordAndCollect_DeltaAtLimit_ReusableDataMemoryMode_ExpireUnused() { + initialize(MemoryMode.REUSABLE_DATA); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + // 1st recording: Recording goes to active map + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + // This will switch next recordings to the secondary map (which is empty) + // by making it the active map + storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10); + + // 2nd recording + deltaReader.setLastCollectEpochNanos(10); + for (int i = 0; i < CARDINALITY_LIMIT - 1; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + // This switches maps again, so next recordings will be to the first map + storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 20); + + // 3rd recording: We're recording unseen attributes to a map we know is full, + // since it was filled during 1st recording + deltaReader.setLastCollectEpochNanos(20); + for (int i = CARDINALITY_LIMIT - 1; i < (CARDINALITY_LIMIT - 1) + 15; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + MetricData metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 30); + + assertOnlyOverflowWasRecorded(metricData, 20, 30, 15 * 3); + + // 4th recording: We're recording unseen attributes to a map we know is full, + // since it was filled during *2nd* recording + deltaReader.setLastCollectEpochNanos(30); + for (int i = CARDINALITY_LIMIT - 1; i < (CARDINALITY_LIMIT - 1) + 15; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 40); + + assertOnlyOverflowWasRecorded(metricData, 30, 40, 15 * 3); + + // 5th recording: Map should be empty, since all handlers were removed due to + // no recording being done to them + deltaReader.setLastCollectEpochNanos(40); + for (int i = 0; i < 10; i++) { + storage.recordDouble( + 3, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 50); + + assertNumberOfPoints(metricData, 10); + assertAllPointsWithValue(metricData, 40, 50, 3); + assertOverflowDoesNotExists(metricData); + + // 6th recording: Map should be empty (we switched to secondary map), since all handlers + // were removed due to no recordings being done to them + deltaReader.setLastCollectEpochNanos(50); + for (int i = 0; i < 12; i++) { + storage.recordDouble( + 4, Attributes.builder().put("key", "value" + i).build(), Context.current()); + } + + metricData = storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 60); + + assertNumberOfPoints(metricData, 12); + assertAllPointsWithValue(metricData, 50, 60, 4); + assertOverflowDoesNotExists(metricData); + } + + @SuppressWarnings("SameParameterValue") + private static void assertOnlyOverflowWasRecorded( + MetricData metricData, long startTime, long endTime, double value) { + + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .hasSize(1) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(startTime); + assertThat(point.getEpochNanos()).isEqualTo(endTime); + assertThat(point.getValue()).isEqualTo(value); + assertThat(point.getAttributes()) + .isEqualTo(MetricStorage.CARDINALITY_OVERFLOW); + }))); + } + + private static void assertNumberOfPoints(MetricData metricData, int numberOfPoints) { + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> assertThat(sumData.getPoints()).hasSize(numberOfPoints))); + } + + private static void assertAllPointsWithValue( + MetricData metricData, long startTime, long endTime, double value) { + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .allSatisfy(point -> { + assertThat(point.getStartEpochNanos()).isEqualTo(startTime); + assertThat(point.getEpochNanos()).isEqualTo(endTime); + assertThat(point.getValue()).isEqualTo(value); + }))); + } + + private static void assertOverflowDoesNotExists(MetricData metricData) { + assertThat(metricData) + .hasDoubleSumSatisfying(sum -> + sum.satisfies(sumData -> + assertThat(sumData.getPoints()) + .noneMatch(point -> + point.getAttributes().equals(MetricStorage.CARDINALITY_OVERFLOW)))); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void enabledThenDisable_isEnabled(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + storage.setEnabled(false); + + assertThat(storage.isEnabled()).isFalse(); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void enabledThenDisableThenEnable_isEnabled(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + storage.setEnabled(false); + storage.setEnabled(true); + + assertThat(storage.isEnabled()).isTrue(); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void enabledThenDisable_recordAndCollect(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + storage.setEnabled(false); + + storage.recordDouble(10d, Attributes.empty(), Context.current()); + + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10).isEmpty()).isTrue(); + } + + @ParameterizedTest + @EnumSource(MemoryMode.class) + void enabledThenDisableThenEnable_recordAndCollect(MemoryMode memoryMode) { + initialize(memoryMode); + + DefaultSynchronousMetricStorage storage = + DefaultSynchronousMetricStorage.create( + deltaReader, + METRIC_DESCRIPTOR, + aggregator, + AttributesFilters.ALLOW_ALL, + CARDINALITY_LIMIT, + testClock, + /* enabled= */ true, + /* contextScopedAttributesFilter= */ null); + + storage.setEnabled(false); + storage.setEnabled(true); + + storage.recordDouble(10d, Attributes.empty(), Context.current()); + + assertThat(storage.collect(RESOURCE, INSTRUMENTATION_SCOPE_INFO, 10).isEmpty()).isFalse(); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/TemporalMetricStorageTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/TemporalMetricStorageTest.java deleted file mode 100644 index bb2d7618392..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/state/TemporalMetricStorageTest.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.state; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.metrics.Aggregation; -import io.opentelemetry.sdk.metrics.InstrumentType; -import io.opentelemetry.sdk.metrics.InstrumentValueType; -import io.opentelemetry.sdk.metrics.data.AggregationTemporality; -import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; -import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; -import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; -import io.opentelemetry.sdk.metrics.internal.aggregator.DoubleAccumulation; -import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; -import io.opentelemetry.sdk.metrics.internal.descriptor.MetricDescriptor; -import io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilter; -import io.opentelemetry.sdk.metrics.internal.export.RegisteredReader; -import io.opentelemetry.sdk.resources.Resource; -import java.util.HashMap; -import java.util.Map; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -@ExtendWith(MockitoExtension.class) -class TemporalMetricStorageTest { - private static final InstrumentDescriptor DESCRIPTOR = - InstrumentDescriptor.create( - "name", "description", "unit", InstrumentType.COUNTER, InstrumentValueType.DOUBLE); - private static final InstrumentDescriptor ASYNC_DESCRIPTOR = - InstrumentDescriptor.create( - "name", - "description", - "unit", - InstrumentType.OBSERVABLE_COUNTER, - InstrumentValueType.DOUBLE); - private static final MetricDescriptor METRIC_DESCRIPTOR = - MetricDescriptor.create("name", "description", "unit"); - private static final Aggregator SUM = - ((AggregatorFactory) Aggregation.sum()) - .createAggregator(DESCRIPTOR, ExemplarFilter.neverSample()); - - private static final Aggregator ASYNC_SUM = - ((AggregatorFactory) Aggregation.sum()) - .createAggregator(ASYNC_DESCRIPTOR, ExemplarFilter.neverSample()); - - @Mock private MetricReader reader; - private RegisteredReader registeredReader; - - @BeforeEach - void setup() { - registeredReader = RegisteredReader.create(reader); - registeredReader.setLastCollectEpochNanos(0); - } - - private static Map createMeasurement(double value) { - Map measurement = new HashMap<>(); - measurement.put(Attributes.empty(), DoubleAccumulation.create(value)); - return measurement; - } - - @Test - void synchronousCumulative_joinsWithLastMeasurementForCumulative() { - AggregationTemporality temporality = AggregationTemporality.CUMULATIVE; - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - SUM, /* isSynchronous= */ true, registeredReader, temporality, METRIC_DESCRIPTOR); - // Send in new measurement at time 10 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(10).hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 30 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(30).hasValue(6))); - registeredReader.setLastCollectEpochNanos(30); - - // Send in new measurement at time 35 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(2), 0, 35)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(35).hasValue(8))); - } - - @Test - void synchronousCumulative_dropsStaleAtLimit() { - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - SUM, - /* isSynchronous= */ true, - registeredReader, - AggregationTemporality.CUMULATIVE, - METRIC_DESCRIPTOR); - - // Send in new measurement at time 10, with attr1 - Map measurement1 = new HashMap<>(); - for (int i = 0; i < MetricStorageUtils.MAX_ACCUMULATIONS; i++) { - Attributes attr1 = Attributes.builder().put("key", "value" + i).build(); - measurement1.put(attr1, DoubleAccumulation.create(3)); - } - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement1, 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .satisfies( - sumData -> - assertThat(sumData.getPoints()) - .hasSize(MetricStorageUtils.MAX_ACCUMULATIONS) - .allSatisfy( - point -> { - assertThat(point.getStartEpochNanos()).isEqualTo(0); - assertThat(point.getEpochNanos()).isEqualTo(10); - assertThat(point.getValue()).isEqualTo(3); - }))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 20, with attr2 - // Result should drop accumulation for attr1, only reporting accumulation for attr2 - Map measurement2 = new HashMap<>(); - Attributes attr2 = - Attributes.builder() - .put("key", "value" + (MetricStorageUtils.MAX_ACCUMULATIONS + 1)) - .build(); - measurement2.put(attr2, DoubleAccumulation.create(3)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement2, 0, 20)) - .hasDoubleSumSatisfying( - sum -> sum.isCumulative().hasPointsSatisfying(point -> point.hasAttributes(attr2))); - } - - @Test - void synchronousDelta_dropsStale() { - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - SUM, - /* isSynchronous= */ true, - registeredReader, - AggregationTemporality.DELTA, - METRIC_DESCRIPTOR); - - // Send in new measurement at time 10, with attr1 - Map measurement1 = new HashMap<>(); - Attributes attr1 = Attributes.builder().put("key", "value1").build(); - measurement1.put(attr1, DoubleAccumulation.create(3)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement1, 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(10) - .hasAttributes(attr1) - .hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 20, with attr2 - // Result should drop accumulation for attr1, only reporting accumulation for attr2 - Map measurement2 = new HashMap<>(); - Attributes attr2 = Attributes.builder().put("key", "value2").build(); - measurement2.put(attr2, DoubleAccumulation.create(7)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement2, 0, 20)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(10) - .hasEpochNanos(20) - .hasAttributes(attr2) - .hasValue(7))); - } - - @Test - void synchronousDelta_useLastTimestamp() { - AggregationTemporality temporality = AggregationTemporality.DELTA; - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - SUM, /* isSynchronous= */ true, registeredReader, temporality, METRIC_DESCRIPTOR); - // Send in new measurement at time 10 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(10).hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 30 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(3))); - registeredReader.setLastCollectEpochNanos(30); - - // Send in new measurement at time 35 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(2), 0, 35)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(30).hasEpochNanos(35).hasValue(2))); - } - - @Test - void asynchronousCumulative_doesNotJoin() { - AggregationTemporality temporality = AggregationTemporality.CUMULATIVE; - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - ASYNC_SUM, - /* isSynchronous= */ false, - registeredReader, - temporality, - METRIC_DESCRIPTOR); - // Send in new measurement at time 10 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(10).hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 30 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(30).hasValue(3))); - registeredReader.setLastCollectEpochNanos(30); - - // Send in new measurement at time 35 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(2), 0, 35)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(35).hasValue(2))); - } - - @Test - void asynchronousCumulative_dropsStale() { - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - ASYNC_SUM, - /* isSynchronous= */ false, - registeredReader, - AggregationTemporality.CUMULATIVE, - METRIC_DESCRIPTOR); - - // Send in new measurement at time 10, with attr1 - Map measurement1 = new HashMap<>(); - Attributes attr1 = Attributes.builder().put("key", "value1").build(); - measurement1.put(attr1, DoubleAccumulation.create(3)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement1, 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(10) - .hasAttributes(attr1) - .hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 20, with attr2 - // Result should drop accumulation for attr1, only reporting accumulation for attr2 - Map measurement2 = new HashMap<>(); - Attributes attr2 = Attributes.builder().put("key", "value2").build(); - measurement2.put(attr2, DoubleAccumulation.create(7)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement2, 0, 20)) - .hasDoubleSumSatisfying( - sum -> - sum.isCumulative() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(20) - .hasAttributes(attr2) - .hasValue(7))); - } - - @Test - void asynchronousDelta_dropsStale() { - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - ASYNC_SUM, - /* isSynchronous= */ false, - registeredReader, - AggregationTemporality.DELTA, - METRIC_DESCRIPTOR); - - // Send in new measurement at time 10, with attr1 - Map measurement1 = new HashMap<>(); - Attributes attr1 = Attributes.builder().put("key", "value1").build(); - measurement1.put(attr1, DoubleAccumulation.create(3)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement1, 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(0) - .hasEpochNanos(10) - .hasAttributes(attr1) - .hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 20, with attr2 - // Result should drop accumulation for attr1, only reporting accumulation for attr2 - Map measurement2 = new HashMap<>(); - Attributes attr2 = Attributes.builder().put("key", "value2").build(); - measurement2.put(attr2, DoubleAccumulation.create(7)); - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), measurement2, 0, 20)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(10) - .hasEpochNanos(20) - .hasAttributes(attr2) - .hasValue(7))); - } - - @Test - void asynchronousDelta_diffsLastTimestamp() { - AggregationTemporality temporality = AggregationTemporality.DELTA; - TemporalMetricStorage storage = - new TemporalMetricStorage<>( - ASYNC_SUM, - /* isSynchronous= */ false, - registeredReader, - temporality, - METRIC_DESCRIPTOR); - // Send in new measurement at time 10 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 10)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(0).hasEpochNanos(10).hasValue(3))); - registeredReader.setLastCollectEpochNanos(10); - - // Send in new measurement at time 30 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(3), 0, 30)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(10).hasEpochNanos(30).hasValue(0))); - registeredReader.setLastCollectEpochNanos(30); - - // Send in new measurement at time 35 - assertThat( - storage.buildMetricFor( - Resource.empty(), InstrumentationScopeInfo.empty(), createMeasurement(2), 0, 35)) - .hasDoubleSumSatisfying( - sum -> - sum.isDelta() - .hasPointsSatisfying( - point -> point.hasStartEpochNanos(30).hasEpochNanos(35).hasValue(-1))); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/AttributesProcessorTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/AttributesProcessorTest.java deleted file mode 100644 index 116b552eb87..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/AttributesProcessorTest.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.view; - -import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; - -import io.opentelemetry.api.baggage.Baggage; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.context.Context; -import org.junit.jupiter.api.Test; - -/** Tests for the {@link AttributesProcessor} DSL-ish library. */ -public class AttributesProcessorTest { - @Test - public void filterKeyName_removesKeys() { - AttributesProcessor processor = - AttributesProcessor.filterByKeyName(name -> "test".equals(name)); - - assertThat( - processor.process( - Attributes.builder().put("remove", "me").put("test", "keep").build(), - Context.root())) - .hasSize(1) - .containsEntry("test", "keep"); - } - - @Test - public void append_works() { - AttributesProcessor processor = - AttributesProcessor.append(Attributes.builder().put("append", "me").build()); - assertThat(processor.process(Attributes.empty(), Context.root())) - .hasSize(1) - .containsEntry("append", "me"); - } - - @Test - public void append_doesNotOverrideExistingKeys() { - AttributesProcessor processor = - AttributesProcessor.append(Attributes.builder().put("test", "drop").build()); - assertThat(processor.process(Attributes.builder().put("test", "keep").build(), Context.root())) - .hasSize(1) - .containsEntry("test", "keep"); - } - - @Test - public void appendBaggage_works() { - AttributesProcessor processor = AttributesProcessor.appendBaggageByKeyName(ignored -> true); - Baggage baggage = Baggage.builder().put("baggage", "value").build(); - Context context = Context.root().with(baggage); - - assertThat(processor.process(Attributes.builder().put("test", "keep").build(), context)) - .hasSize(2) - .containsEntry("test", "keep") - .containsEntry("baggage", "value"); - } - - @Test - public void appendBaggage_doesNotOverrideExistingKeys() { - AttributesProcessor processor = AttributesProcessor.appendBaggageByKeyName(ignored -> true); - Baggage baggage = Baggage.builder().put("test", "drop").build(); - Context context = Context.root().with(baggage); - - assertThat(processor.process(Attributes.builder().put("test", "keep").build(), context)) - .hasSize(1) - .containsEntry("test", "keep"); - } - - @Test - public void appendBaggageByKeyName_works() { - AttributesProcessor processor = - AttributesProcessor.appendBaggageByKeyName(name -> "keep".equals(name)); - Baggage baggage = Baggage.builder().put("baggage", "value").put("keep", "baggage").build(); - Context context = Context.root().with(baggage); - - assertThat(processor.process(Attributes.builder().put("test", "keep").build(), context)) - .hasSize(2) - .containsEntry("test", "keep") - .containsEntry("keep", "baggage"); - } - - @Test - public void proccessors_joinByThen() { - // Baggage should be added, then all keys filtered. - AttributesProcessor processor = - AttributesProcessor.appendBaggageByKeyName(ignored -> true) - .then(AttributesProcessor.filterByKeyName(name -> "baggage".equals(name))); - Baggage baggage = Baggage.builder().put("baggage", "value").put("keep", "baggage").build(); - Context context = Context.root().with(baggage); - - assertThat(processor.process(Attributes.builder().put("test", "keep").build(), context)) - .containsEntry("baggage", "value") - .hasSize(1); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/Base2ExponentialHistogramAggregationTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/Base2ExponentialHistogramAggregationTest.java new file mode 100644 index 00000000000..cf8c04ec44e --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/Base2ExponentialHistogramAggregationTest.java @@ -0,0 +1,76 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.view; + +import static io.opentelemetry.sdk.metrics.internal.exemplar.ExemplarFilterInternal.asExemplarFilterInternal; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.Base2ExponentialHistogramOptions; +import io.opentelemetry.sdk.metrics.ExemplarFilter; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.InstrumentValueType; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.aggregator.Aggregator; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorFactory; +import io.opentelemetry.sdk.metrics.internal.aggregator.AggregatorHandle; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; +import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import org.junit.jupiter.api.Test; + +class Base2ExponentialHistogramAggregationTest { + + @Test + void goodConfig() { + assertThat(Base2ExponentialHistogramAggregation.getDefault()).isNotNull(); + assertThat(Base2ExponentialHistogramAggregation.create(10, 20, /* recordMinMax= */ true)) + .isNotNull(); + } + + @Test + void invalidConfig_Throws() { + assertThatThrownBy(() -> Base2ExponentialHistogramOptions.builder().setMaxBuckets(0).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxBuckets must be >= 2"); + assertThatThrownBy(() -> Base2ExponentialHistogramOptions.builder().setMaxScale(21).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxScale must be -10 <= x <= 20"); + assertThatThrownBy(() -> Base2ExponentialHistogramOptions.builder().setMaxScale(-11).build()) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxScale must be -10 <= x <= 20"); + } + + @Test + void minimumBucketsCanAccommodateMaxRange() { + Aggregation aggregation = + Base2ExponentialHistogramAggregation.create(2, 20, /* recordMinMax= */ true); + Aggregator aggregator = + ((AggregatorFactory) aggregation) + .createAggregator( + InstrumentDescriptor.create( + "foo", + "description", + "unit", + InstrumentType.HISTOGRAM, + InstrumentValueType.DOUBLE, + Advice.empty()), + asExemplarFilterInternal(ExemplarFilter.alwaysOff()), + MemoryMode.IMMUTABLE_DATA); + AggregatorHandle handle = aggregator.createHandle(0); + // Record max range + handle.recordDouble(Double.MIN_VALUE, Attributes.empty(), Context.current()); + handle.recordDouble(Double.MAX_VALUE, Attributes.empty(), Context.current()); + + ExponentialHistogramPointData pointData = + handle.aggregateThenMaybeReset(0, 1, Attributes.empty(), /* reset= */ true); + assertThat(pointData.getCount()).isEqualTo(2); + assertThat(pointData.getScale()).isEqualTo(-11); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java index 0569a59f710..b2cbb924321 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExplicitBucketHistogramAggregationTest.java @@ -9,6 +9,7 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.opentelemetry.sdk.metrics.Aggregation; +import io.opentelemetry.sdk.metrics.ExplicitBucketHistogramOptions; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.Test; @@ -23,20 +24,32 @@ void goodConfig() { @Test void badBuckets_throwArgumentException() { - assertThatThrownBy( - () -> - Aggregation.explicitBucketHistogram( - Collections.singletonList(Double.NEGATIVE_INFINITY))) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Collections.singletonList(Double.NEGATIVE_INFINITY)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid bucket boundary: -Inf"); - assertThatThrownBy( - () -> Aggregation.explicitBucketHistogram(Arrays.asList(1.0, Double.POSITIVE_INFINITY))) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, Double.POSITIVE_INFINITY)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid bucket boundary: +Inf"); - assertThatThrownBy(() -> Aggregation.explicitBucketHistogram(Arrays.asList(1.0, Double.NaN))) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(1.0, Double.NaN)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("invalid bucket boundary: NaN"); - assertThatThrownBy(() -> Aggregation.explicitBucketHistogram(Arrays.asList(2.0, 1.0, 3.0))) + assertThatThrownBy(() -> + Aggregation.explicitBucketHistogram( + ExplicitBucketHistogramOptions.builder() + .setBucketBoundaries(Arrays.asList(2.0, 1.0, 3.0)) + .build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Bucket boundaries must be in increasing order: 2.0 >= 1.0"); } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExponentialHistogramAggregationTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExponentialHistogramAggregationTest.java deleted file mode 100644 index ecbe11524c9..00000000000 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ExponentialHistogramAggregationTest.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.metrics.internal.view; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -import org.junit.jupiter.api.Test; - -class ExponentialHistogramAggregationTest { - - @Test - void goodConfig() { - assertThat(ExponentialHistogramAggregation.getDefault()).isNotNull(); - assertThat(ExponentialHistogramAggregation.create(10, 10)).isNotNull(); - } - - @Test - void badBuckets_throwArgumentException() { - assertThatThrownBy(() -> ExponentialHistogramAggregation.create(1, -1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("maxBuckets must be >= 0"); - } -} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java new file mode 100644 index 00000000000..b2c5b7ff946 --- /dev/null +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/FilteredAttributesTest.java @@ -0,0 +1,196 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics.internal.view; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.testing.EqualsTester; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.RepeatedTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** Unit tests for {@link FilteredAttributes}s. */ +@SuppressWarnings("rawtypes") +class FilteredAttributesTest { + + private static final AttributeKey KEY1 = stringKey("key1"); + private static final AttributeKey KEY2 = stringKey("key2"); + private static final AttributeKey KEY3 = stringKey("key3"); + private static final AttributeKey KEY4 = stringKey("key4"); + private static final AttributeKey KEY2_LONG = longKey("key2"); + private static final Set> ALL_KEYS = + ImmutableSet.of(KEY1, KEY2, KEY3, KEY4, KEY2_LONG); + private static final Attributes ALL_ATTRIBUTES = + Attributes.of(KEY1, "value1", KEY2, "value2", KEY2_LONG, 222L, KEY3, "value3"); + private static final Attributes FILTERED_ATTRIBUTES_ONE = + FilteredAttributes.create(ALL_ATTRIBUTES, ImmutableSet.of(KEY1)); + private static final Attributes FILTERED_ATTRIBUTES_TWO = + FilteredAttributes.create(ALL_ATTRIBUTES, ImmutableSet.of(KEY1, KEY2_LONG)); + private static final Attributes FILTERED_ATTRIBUTES_THREE = + FilteredAttributes.create(ALL_ATTRIBUTES, ImmutableSet.of(KEY1, KEY2_LONG, KEY3)); + private static final Attributes FILTERED_ATTRIBUTES_FOUR = + FilteredAttributes.create(ALL_ATTRIBUTES, ImmutableSet.of(KEY1, KEY2_LONG, KEY3, KEY4)); + private static final Attributes FILTERED_ATTRIBUTES_EMPTY_SOURCE = + FilteredAttributes.create(Attributes.empty(), ImmutableSet.of(KEY1)); + private static final Attributes FILTERED_ATTRIBUTES_EMPTY = + FilteredAttributes.create(ALL_ATTRIBUTES, Collections.emptySet()); + + @ParameterizedTest + @MethodSource("mapArgs") + void forEach(Attributes filteredAttributes, Map, Object> expectedMapEntries) { + Map entriesSeen = new HashMap<>(); + filteredAttributes.forEach(entriesSeen::put); + assertThat(entriesSeen).isEqualTo(expectedMapEntries); + } + + @ParameterizedTest + @MethodSource("mapArgs") + void asMap(Attributes filteredAttributes, Map, Object> expectedMapEntries) { + assertThat(filteredAttributes.asMap()).isEqualTo(expectedMapEntries); + } + + @ParameterizedTest + @MethodSource("mapArgs") + void size(Attributes filteredAttributes, Map, Object> expectedMapEntries) { + assertThat(filteredAttributes.size()).isEqualTo(expectedMapEntries.size()); + } + + @ParameterizedTest + @MethodSource("mapArgs") + void isEmpty(Attributes filteredAttributes, Map, Object> expectedMapEntries) { + assertThat(filteredAttributes.isEmpty()).isEqualTo(expectedMapEntries.isEmpty()); + } + + @ParameterizedTest + @MethodSource("mapArgs") + void get(Attributes filteredAttributes, Map, Object> expectedMapEntries) { + for (AttributeKey key : ALL_KEYS) { + Object expectedValue = expectedMapEntries.get(key); + assertThat(filteredAttributes.get(key)).isEqualTo(expectedValue); + } + } + + @ParameterizedTest + @MethodSource("mapArgs") + void toBuilder(Attributes filteredAttributes, Map, Object> expectedMapEntries) { + Attributes attributes = filteredAttributes.toBuilder().build(); + assertThat(attributes.asMap()).isEqualTo(expectedMapEntries); + } + + private static Stream mapArgs() { + return Stream.of( + Arguments.argumentSet( + "one attribute", FILTERED_ATTRIBUTES_ONE, ImmutableMap.of(KEY1, "value1")), + Arguments.argumentSet( + "two attributes", + FILTERED_ATTRIBUTES_TWO, + ImmutableMap.of(KEY1, "value1", KEY2_LONG, 222L)), + Arguments.argumentSet( + "three attributes", + FILTERED_ATTRIBUTES_THREE, + ImmutableMap.of(KEY1, "value1", KEY2_LONG, 222L, KEY3, "value3")), + Arguments.argumentSet( + "four attributes filtered to three", + FILTERED_ATTRIBUTES_FOUR, + ImmutableMap.of(KEY1, "value1", KEY2_LONG, 222L, KEY3, "value3")), + Arguments.argumentSet( + "empty source", FILTERED_ATTRIBUTES_EMPTY_SOURCE, Collections.emptyMap()), + Arguments.argumentSet("empty filtered", FILTERED_ATTRIBUTES_EMPTY, Collections.emptyMap())); + } + + @Test + void stringRepresentation() { + assertThat(FILTERED_ATTRIBUTES_ONE.toString()).isEqualTo("FilteredAttributes{key1=value1}"); + assertThat(FILTERED_ATTRIBUTES_TWO.toString()) + .isEqualTo("FilteredAttributes{key1=value1,key2=222}"); + assertThat(FILTERED_ATTRIBUTES_THREE.toString()) + .isEqualTo("FilteredAttributes{key1=value1,key2=222,key3=value3}"); + assertThat(FILTERED_ATTRIBUTES_FOUR.toString()) + .isEqualTo("FilteredAttributes{key1=value1,key2=222,key3=value3}"); + assertThat(FILTERED_ATTRIBUTES_EMPTY_SOURCE.toString()).isEqualTo("{}"); + assertThat(FILTERED_ATTRIBUTES_EMPTY.toString()).isEqualTo("{}"); + } + + /** + * Test behavior of attributes with more than the 32 limit of FilteredAttributes.filteredIndices. + */ + @RepeatedTest(10) + void largeAttributes() { + Set> allKeys = new HashSet<>(); + AttributesBuilder allAttributesBuilder = Attributes.builder(); + IntStream.range(0, 100) + .forEach(i -> { + AttributeKey key = stringKey("key" + i); + allKeys.add(key); + allAttributesBuilder.put(key, "value" + i); + }); + Attributes allAttributes = allAttributesBuilder.build(); + + Attributes empty = FilteredAttributes.create(allAttributes, Collections.emptySet()); + assertThat(empty.size()).isEqualTo(0); + assertThat(empty.isEmpty()).isTrue(); + + Set> oneKey = allKeys.stream().limit(1).collect(Collectors.toSet()); + Attributes one = FilteredAttributes.create(allAttributes, oneKey); + assertThat(one.size()).isEqualTo(1); + assertThat(one.isEmpty()).isFalse(); + allKeys.stream() + .forEach(key -> { + if (oneKey.contains(key)) { + assertThat(one.get(key)).isNotNull(); + } else { + assertThat(one.get(key)).isNull(); + } + }); + + Set> tenKeys = allKeys.stream().limit(10).collect(Collectors.toSet()); + Attributes ten = FilteredAttributes.create(allAttributes, tenKeys); + assertThat(ten.size()).isEqualTo(10); + assertThat(ten.isEmpty()).isFalse(); + allKeys.stream() + .forEach(key -> { + if (tenKeys.contains(key)) { + assertThat(ten.get(key)).isNotNull(); + } else { + assertThat(ten.get(key)).isNull(); + } + }); + } + + @Test + void equalsAndHashCode() { + new EqualsTester() + .addEqualityGroup( + FILTERED_ATTRIBUTES_ONE, + FilteredAttributes.create(Attributes.of(KEY1, "value1"), Collections.singleton(KEY1)), + FilteredAttributes.create(Attributes.of(KEY1, "value1"), ImmutableSet.of(KEY1, KEY2)), + FilteredAttributes.create( + Attributes.of(KEY1, "value1", KEY2, "value2"), Collections.singleton(KEY1)), + FilteredAttributes.create( + Attributes.of(KEY1, "value1", KEY2_LONG, 222L), Collections.singleton(KEY1))) + .addEqualityGroup(FILTERED_ATTRIBUTES_TWO) + .addEqualityGroup(FILTERED_ATTRIBUTES_THREE, FILTERED_ATTRIBUTES_FOUR) + .addEqualityGroup(FILTERED_ATTRIBUTES_EMPTY, FILTERED_ATTRIBUTES_EMPTY_SOURCE) + .testEquals(); + } +} diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredViewTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredViewTest.java index 1cbd79b4d0d..a18304f2043 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredViewTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/RegisteredViewTest.java @@ -12,6 +12,7 @@ import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.View; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; import org.junit.jupiter.api.Test; class RegisteredViewTest { @@ -32,13 +33,14 @@ void stringRepresentation() { .setDescription("description") .setAggregation(Aggregation.sum()) .build(), - AttributesProcessor.noop(), + AttributesFilters.ALLOW_ALL, + MetricStorage.DEFAULT_MAX_CARDINALITY, SourceInfo.fromCurrentStack()) .toString()) - .isEqualTo( + .startsWith( "RegisteredView{" + "instrumentSelector=InstrumentSelector{instrumentType=COUNTER, instrumentName=name, meterName=meter-name, meterVersion=meter-version, meterSchemaUrl=meter-schema-url}, " - + "view=View{name=name, description=description, aggregation=SumAggregation, attributesProcessor=NoopAttributesProcessor{}}" - + "}"); + + "view=View{name=name, description=description, aggregation=SumAggregation, attributeFilter=") + .endsWith(", cardinalityLimit=2000}}"); } } diff --git a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryTest.java b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryTest.java index a912a298f64..492518edb37 100644 --- a/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryTest.java +++ b/sdk/metrics/src/test/java/io/opentelemetry/sdk/metrics/internal/view/ViewRegistryTest.java @@ -5,10 +5,14 @@ package io.opentelemetry.sdk.metrics.internal.view; -import static io.opentelemetry.sdk.metrics.internal.view.ViewRegistry.toGlobPatternPredicate; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.metrics.internal.view.ViewRegistry.DEFAULT_REGISTERED_VIEW; import static org.assertj.core.api.Assertions.assertThat; import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.Aggregation; @@ -16,8 +20,15 @@ import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.InstrumentValueType; import io.opentelemetry.sdk.metrics.View; +import io.opentelemetry.sdk.metrics.export.CardinalityLimitSelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; import io.opentelemetry.sdk.metrics.internal.debug.SourceInfo; +import io.opentelemetry.sdk.metrics.internal.descriptor.Advice; import io.opentelemetry.sdk.metrics.internal.descriptor.InstrumentDescriptor; +import io.opentelemetry.sdk.metrics.internal.state.MetricStorage; +import java.util.Arrays; +import java.util.Collections; +import org.assertj.core.api.InstanceOfAssertFactories; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; @@ -26,186 +37,336 @@ class ViewRegistryTest { @RegisterExtension LogCapturer logs = LogCapturer.create().captureForType(ViewRegistry.class); private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("name", "version", "schema_url"); + InstrumentationScopeInfo.builder("name") + .setVersion("version") + .setSchemaUrl("schema_url") + .build(); + + private static RegisteredView registeredView(InstrumentSelector instrumentSelector, View view) { + return RegisteredView.create( + instrumentSelector, + view, + AttributesFilters.ALLOW_ALL, + MetricStorage.DEFAULT_MAX_CARDINALITY, + SourceInfo.fromCurrentStack()); + } @Test void findViews_SelectionOnType() { - View view = View.builder().build(); + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder().setType(InstrumentType.COUNTER).build(), + View.builder().setDescription("description").build()); + ViewRegistry viewRegistry = + ViewRegistry.create( + DefaultAggregationSelector.getDefault(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); + + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG, Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(registeredView)); + // this one doesn't match, so it gets the default still. + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "", + "", + "", + InstrumentType.UP_DOWN_COUNTER, + InstrumentValueType.LONG, + Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); + assertThat(logs.getEvents()).hasSize(0); + } + + @Test + void findViews_SelectionOnUnit() { + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder().setUnit("ms").build(), + View.builder().setDescription("description").build()); ViewRegistry viewRegistry = - ViewRegistry.builder() - .addView( - InstrumentSelector.builder().setType(InstrumentType.COUNTER).build(), - view, - AttributesProcessor.noop(), - SourceInfo.fromCurrentStack()) - .build(); + ViewRegistry.create( + DefaultAggregationSelector.getDefault(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); + assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "", "", "ms", InstrumentType.COUNTER, InstrumentValueType.LONG, Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .extracting(RegisteredView::getView) - .isEqualTo(view); - // this one hasn't been configured, so it gets the default still. + .isEqualTo(Collections.singletonList(registeredView)); + // this one doesn't match, so it gets the default still. assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.LONG), + "", + "", + "", + InstrumentType.UP_DOWN_COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat(logs.getEvents()).hasSize(0); } @Test void findViews_SelectionOnName() { - View view = View.builder().build(); - + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder().setName("overridden").build(), + View.builder().setDescription("description").build()); ViewRegistry viewRegistry = - ViewRegistry.builder() - .addView( - InstrumentSelector.builder().setName("overridden").build(), - view, - AttributesProcessor.noop(), - SourceInfo.fromCurrentStack()) - .build(); + ViewRegistry.create( + DefaultAggregationSelector.getDefault(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); + assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "overridden", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "overridden", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .extracting(RegisteredView::getView) - .isSameAs(view); - // this one hasn't been configured, so it gets the default still. + .isEqualTo(Collections.singletonList(registeredView)); + // this one doesn't match, so it gets the default still. assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "default", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "default", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat(logs.getEvents()).hasSize(0); } @Test void findViews_MultipleMatchingViews() { - View view1 = View.builder().setAggregation(Aggregation.sum()).build(); - View view2 = View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build(); + RegisteredView registeredView1 = + registeredView( + InstrumentSelector.builder().setName("overridden").build(), + View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build()); + RegisteredView registeredView2 = + registeredView( + InstrumentSelector.builder().setName("*").build(), + View.builder().setAggregation(Aggregation.sum()).build()); ViewRegistry viewRegistry = - ViewRegistry.builder() - .addView( - InstrumentSelector.builder().setName("overridden").build(), - view2, - AttributesProcessor.noop(), - SourceInfo.fromCurrentStack()) - .addView( - InstrumentSelector.builder().setName("*").build(), - view1, - AttributesProcessor.noop(), - SourceInfo.fromCurrentStack()) - .build(); + ViewRegistry.create( + DefaultAggregationSelector.getDefault(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Arrays.asList(registeredView1, registeredView2)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "overridden", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "overridden", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(2) - .element(0) - .extracting(RegisteredView::getView) - .isEqualTo(view2); + .isEqualTo(Arrays.asList(registeredView1, registeredView2)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "default", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "default", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .extracting(RegisteredView::getView) - .isEqualTo(view1); + .isEqualTo(Collections.singletonList(registeredView2)); assertThat(logs.getEvents()).hasSize(0); } @Test void findViews_SelectionTypeAndName() { - View view = View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build(); - + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder() + .setType(InstrumentType.COUNTER) + .setName("overrides") + .build(), + View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build()); ViewRegistry viewRegistry = - ViewRegistry.builder() - .addView( - InstrumentSelector.builder() - .setType(InstrumentType.COUNTER) - .setName("overrides") - .build(), - view, - AttributesProcessor.noop(), - SourceInfo.fromCurrentStack()) - .build(); + ViewRegistry.create( + DefaultAggregationSelector.getDefault(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "overrides", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "overrides", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .extracting(RegisteredView::getView) - .isEqualTo(view); - // this one hasn't been configured, so it gets the default still.. + .isEqualTo(Collections.singletonList(registeredView)); + // this one doesn't match, so it gets the default still. assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "overrides", "", "", InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.LONG), + "overrides", + "", + "", + InstrumentType.UP_DOWN_COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isEqualTo(ViewRegistry.DEFAULT_REGISTERED_VIEW); - // this one hasn't been configured, so it gets the default still.. + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); + // this one doesn't match, so it gets the default still. assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "default", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "default", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isEqualTo(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat(logs.getEvents()).hasSize(0); } @Test @SuppressLogger(ViewRegistry.class) - void findViews_IncompatibleViewIgnored() { - View view = View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build(); + void findViews_DefaultAggregationSelector() { + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder().setName("overridden").build(), + View.builder().setDescription("description").build()); + // Configure a default aggregation selector that defaults to exponential histogram aggregation + // for histogram and gauge instruments. Note, gauges are incompatible with exponential + // histograms. + DefaultAggregationSelector defaultAggregationSelector = + instrumentType -> + instrumentType == InstrumentType.HISTOGRAM + || instrumentType == InstrumentType.OBSERVABLE_GAUGE + ? Aggregation.base2ExponentialBucketHistogram() + : Aggregation.defaultAggregation(); ViewRegistry viewRegistry = - ViewRegistry.builder() - .addView( - InstrumentSelector.builder().setType(InstrumentType.OBSERVABLE_COUNTER).build(), - view, - AttributesProcessor.noop(), - SourceInfo.fromCurrentStack()) - .build(); + ViewRegistry.create( + defaultAggregationSelector, + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); + // Counter instrument should result in default view assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "test", "", "", InstrumentType.OBSERVABLE_COUNTER, InstrumentValueType.LONG), + "test", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isEqualTo(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); + // Histogram instrument named overridden should match the registered view, for which the + // aggregation is explicit bucket histogram + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "overridden", + "", + "", + InstrumentType.HISTOGRAM, + InstrumentValueType.DOUBLE, + Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(registeredView)); + // Histogram instrument named default should match no views, and should receive a default view + // with the exponential histogram aggregation as dictated by the default aggregation + // selector + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "default", + "", + "", + InstrumentType.HISTOGRAM, + InstrumentValueType.DOUBLE, + Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo( + Collections.singletonList( + registeredView( + InstrumentSelector.builder().setName("*").build(), + View.builder() + .setAggregation(Aggregation.base2ExponentialBucketHistogram()) + .build()))); + // At this point, no warning logs should have been produced. + assertThat(logs.getEvents()).hasSize(0); + // Gauge instrument matches no views, and should receive a default view with the exponential + // histogram aggregation as dictated by the default aggregation selector. However, gauge is + // incompatible with exponential histogram aggregation and the default view should be returned. + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "default", + "", + "", + InstrumentType.OBSERVABLE_GAUGE, + InstrumentValueType.DOUBLE, + Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); + logs.assertContains( + "Instrument default aggregation base2_exponential_bucket_histogram is incompatible with instrument default of type OBSERVABLE_GAUGE"); + } + + @Test + @SuppressLogger(ViewRegistry.class) + void findViews_IncompatibleViewIgnored() { + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder().setType(InstrumentType.OBSERVABLE_COUNTER).build(), + View.builder().setAggregation(Aggregation.explicitBucketHistogram()).build()); + ViewRegistry viewRegistry = + ViewRegistry.create( + DefaultAggregationSelector.getDefault(), + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); + + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "test", + "", + "", + InstrumentType.OBSERVABLE_COUNTER, + InstrumentValueType.LONG, + Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); logs.assertContains( "View aggregation explicit_bucket_histogram is incompatible with instrument test of type OBSERVABLE_COUNTER"); @@ -213,47 +374,52 @@ void findViews_IncompatibleViewIgnored() { @Test void defaults() { - ViewRegistry viewRegistry = ViewRegistry.builder().build(); + ViewRegistry viewRegistry = ViewRegistry.create(); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG), + "", "", "", InstrumentType.COUNTER, InstrumentValueType.LONG, Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.UP_DOWN_COUNTER, InstrumentValueType.LONG), + "", + "", + "", + InstrumentType.UP_DOWN_COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.HISTOGRAM, InstrumentValueType.LONG), + "", "", "", InstrumentType.HISTOGRAM, InstrumentValueType.LONG, Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.OBSERVABLE_COUNTER, InstrumentValueType.LONG), + "", + "", + "", + InstrumentType.OBSERVABLE_COUNTER, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( - "", "", "", InstrumentType.OBSERVABLE_GAUGE, InstrumentValueType.LONG), + "", + "", + "", + InstrumentType.OBSERVABLE_GAUGE, + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat( viewRegistry.findViews( InstrumentDescriptor.create( @@ -261,34 +427,115 @@ void defaults() { "", "", InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, - InstrumentValueType.LONG), + InstrumentValueType.LONG, + Advice.empty()), INSTRUMENTATION_SCOPE_INFO)) - .hasSize(1) - .element(0) - .isSameAs(ViewRegistry.DEFAULT_REGISTERED_VIEW); + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); assertThat(logs.getEvents()).hasSize(0); } @Test - void matchesName() { - assertThat(toGlobPatternPredicate("foo").test("foo")).isTrue(); - assertThat(toGlobPatternPredicate("foo").test("Foo")).isTrue(); - assertThat(toGlobPatternPredicate("foo").test("bar")).isFalse(); - assertThat(toGlobPatternPredicate("fo?").test("foo")).isTrue(); - assertThat(toGlobPatternPredicate("fo??").test("fooo")).isTrue(); - assertThat(toGlobPatternPredicate("fo?").test("fob")).isTrue(); - assertThat(toGlobPatternPredicate("fo?").test("fooo")).isFalse(); - assertThat(toGlobPatternPredicate("*").test("foo")).isTrue(); - assertThat(toGlobPatternPredicate("*").test("bar")).isTrue(); - assertThat(toGlobPatternPredicate("*").test("baz")).isTrue(); - assertThat(toGlobPatternPredicate("*").test("foo.bar.baz")).isTrue(); - assertThat(toGlobPatternPredicate("fo*").test("fo")).isTrue(); - assertThat(toGlobPatternPredicate("fo*").test("foo")).isTrue(); - assertThat(toGlobPatternPredicate("fo*").test("fooo")).isTrue(); - assertThat(toGlobPatternPredicate("fo*").test("foo.bar.baz")).isTrue(); - assertThat(toGlobPatternPredicate("f()[]$^.{}|").test("f()[]$^.{}|")).isTrue(); - assertThat(toGlobPatternPredicate("f()[]$^.{}|?").test("f()[]$^.{}|o")).isTrue(); - assertThat(toGlobPatternPredicate("f()[]$^.{}|*").test("f()[]$^.{}|ooo")).isTrue(); + @SuppressLogger(ViewRegistry.class) + void findViews_ApplyAdvice() { + // use incompatible aggregation for histogram + DefaultAggregationSelector aggregationSelector = + instrumentType -> + instrumentType == InstrumentType.HISTOGRAM + ? Aggregation.lastValue() + : Aggregation.defaultAggregation(); + + RegisteredView registeredView = + registeredView( + InstrumentSelector.builder().setName("test").build(), + View.builder().setDescription("view applied").build()); + ViewRegistry viewRegistry = + ViewRegistry.create( + aggregationSelector, + CardinalityLimitSelector.defaultCardinalityLimitSelector(), + Collections.singletonList(registeredView)); + + // If a view matches the descriptor, use it and ignore the advice + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "test", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.builder() + .setAttributes(Arrays.asList(stringKey("key1"), stringKey("key2"))) + .build()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(registeredView)); + + // If there is no matching view and attributes advice was defined, use it + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "advice", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.builder() + .setAttributes(Arrays.asList(stringKey("key1"), stringKey("key2"))) + .build()), + INSTRUMENTATION_SCOPE_INFO)) + .hasSize(1) + .element(0) + .satisfies(view -> assertAdviceFilter(view, stringKey("key1"), stringKey("key2"))); + + // If there is no matching view and attributes advice was defined, use it - incompatible + // aggregation case + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "histogram_advice", + "", + "", + InstrumentType.HISTOGRAM, + InstrumentValueType.DOUBLE, + Advice.builder() + .setAttributes(Arrays.asList(stringKey("key1"), stringKey("key2"))) + .build()), + INSTRUMENTATION_SCOPE_INFO)) + .hasSize(1) + .element(0) + .satisfies(view -> assertAdviceFilter(view, stringKey("key1"), stringKey("key2"))); + + // if advice is not defined, use the default view + assertThat( + viewRegistry.findViews( + InstrumentDescriptor.create( + "advice", + "", + "", + InstrumentType.COUNTER, + InstrumentValueType.DOUBLE, + Advice.empty()), + INSTRUMENTATION_SCOPE_INFO)) + .isEqualTo(Collections.singletonList(DEFAULT_REGISTERED_VIEW)); + } + + private static void assertAdviceFilter(RegisteredView view, AttributeKey... expectedKeys) { + assertThat(view) + .as("is the same as the default view, except the attributes filter") + .usingRecursiveComparison() + .withStrictTypeChecking() + .ignoringFields("attributesFilter") + .isEqualTo(DEFAULT_REGISTERED_VIEW); + // The advice filter uses FilteredAttributes.create under the hood; verify by applying it to a + // superset of attributes and checking the retained keys. + AttributesBuilder builder = Attributes.builder(); + for (AttributeKey key : expectedKeys) { + builder.put(key.getKey(), "v"); + } + builder.put("extra", "drop"); + Attributes filtered = view.getAttributesFilter().apply(builder.build()); + assertThat(filtered.asMap().keySet()) + .asInstanceOf(InstanceOfAssertFactories.collection(AttributeKey.class)) + .containsExactlyInAnyOrder(expectedKeys); } } diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java new file mode 100644 index 00000000000..ddfff8d611a --- /dev/null +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/AttributesAdviceTest.java @@ -0,0 +1,336 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; +import static java.util.Arrays.asList; +import static org.junit.jupiter.params.provider.Arguments.arguments; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounterBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGaugeBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogramBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounterBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounterBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGaugeBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogramBuilder; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounterBuilder; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.DoubleCounterBuilder; +import io.opentelemetry.api.metrics.DoubleGauge; +import io.opentelemetry.api.metrics.DoubleGaugeBuilder; +import io.opentelemetry.api.metrics.DoubleHistogram; +import io.opentelemetry.api.metrics.DoubleHistogramBuilder; +import io.opentelemetry.api.metrics.DoubleUpDownCounter; +import io.opentelemetry.api.metrics.DoubleUpDownCounterBuilder; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongCounterBuilder; +import io.opentelemetry.api.metrics.LongGauge; +import io.opentelemetry.api.metrics.LongGaugeBuilder; +import io.opentelemetry.api.metrics.LongHistogram; +import io.opentelemetry.api.metrics.LongHistogramBuilder; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.LongUpDownCounterBuilder; +import io.opentelemetry.sdk.testing.assertj.AbstractPointAssert; +import io.opentelemetry.sdk.testing.assertj.DoublePointAssert; +import io.opentelemetry.sdk.testing.assertj.HistogramPointAssert; +import io.opentelemetry.sdk.testing.assertj.LongPointAssert; +import io.opentelemetry.sdk.testing.assertj.MetricAssert; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; +import javax.annotation.Nullable; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; +import org.junit.jupiter.params.support.ParameterDeclarations; + +class AttributesAdviceTest { + + private static final Attributes ATTRIBUTES = + Attributes.builder() + .put(stringKey("key1"), "1") + .put(stringKey("key2"), "2") + .put(stringKey("key3"), "3") + .build(); + + private SdkMeterProvider meterProvider = SdkMeterProvider.builder().build(); + + @AfterEach + void cleanup() { + meterProvider.close(); + } + + @ParameterizedTest + @ArgumentsSource(InstrumentsProvider.class) + void instrumentWithoutAdvice( + InstrumentFactory instrumentFactory, PointsAssert> pointsAssert) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Instrument instrument = instrumentFactory.create(meterProvider, "test", null); + instrument.record(1, ATTRIBUTES); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), point -> point.hasAttributes(ATTRIBUTES))); + } + + @ParameterizedTest + @ArgumentsSource(InstrumentsProvider.class) + void instrumentWithAdvice( + InstrumentFactory instrumentFactory, PointsAssert> pointsAssert) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); + + Instrument instrument = + instrumentFactory.create( + meterProvider, "test", asList(stringKey("key1"), stringKey("key2"))); + instrument.record(1, ATTRIBUTES); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), + point -> + point.hasAttributesSatisfyingExactly( + equalTo(stringKey("key1"), "1"), equalTo(stringKey("key2"), "2")))); + } + + @ParameterizedTest + @ArgumentsSource(InstrumentsProvider.class) + void instrumentWithAdviceAndViews( + InstrumentFactory instrumentFactory, PointsAssert> pointsAssert) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(reader) + .registerView( + InstrumentSelector.builder().setName("test").build(), + View.builder() + .setAttributeFilter(key -> "key2".equals(key) || "key3".equals(key)) + .build()) + .build(); + + Instrument instrument = + instrumentFactory.create( + meterProvider, "test", asList(stringKey("key1"), stringKey("key2"))); + instrument.record(1, ATTRIBUTES); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), + point -> + point.hasAttributesSatisfyingExactly( + equalTo(stringKey("key2"), "2"), equalTo(stringKey("key3"), "3")))); + } + + @ParameterizedTest + @ArgumentsSource(InstrumentsProvider.class) + void instrumentWithAdviceAndDescriptionViews( + InstrumentFactory instrumentFactory, PointsAssert> pointsAssert) { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + // Register a view which sets a description. Since any matching view supersedes any instrument + // advice, the attribute advice is ignored and all attributes are recorded. + meterProvider = + SdkMeterProvider.builder() + .registerMetricReader(reader) + .registerView( + InstrumentSelector.builder().setName("test").build(), + View.builder().setDescription("description").build()) + .build(); + + Instrument instrument = + instrumentFactory.create( + meterProvider, "test", asList(stringKey("key1"), stringKey("key2"))); + instrument.record(1, ATTRIBUTES); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + pointsAssert.hasPointSatisfying( + assertThat(metric), + point -> + point.hasAttributesSatisfyingExactly( + equalTo(stringKey("key1"), "1"), + equalTo(stringKey("key2"), "2"), + equalTo(stringKey("key3"), "3")))); + } + + static final class InstrumentsProvider implements ArgumentsProvider { + + @Override + public Stream provideArguments( + ParameterDeclarations parameters, ExtensionContext context) { + return Stream.of( + // double counter + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + DoubleCounterBuilder doubleCounterBuilder = + meterProvider.get("meter").counterBuilder(name).ofDoubles(); + if (attributesAdvice != null) { + ((ExtendedDoubleCounterBuilder) doubleCounterBuilder) + .setAttributesAdvice(attributesAdvice); + } + DoubleCounter counter = doubleCounterBuilder.build(); + return counter::add; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // long counter + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + LongCounterBuilder doubleCounterBuilder = + meterProvider.get("meter").counterBuilder(name); + if (attributesAdvice != null) { + ((ExtendedLongCounterBuilder) doubleCounterBuilder) + .setAttributesAdvice(attributesAdvice); + } + LongCounter counter = doubleCounterBuilder.build(); + return counter::add; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // double gauge + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + DoubleGaugeBuilder doubleGaugeBuilder = + meterProvider.get("meter").gaugeBuilder(name); + if (attributesAdvice != null) { + ((ExtendedDoubleGaugeBuilder) doubleGaugeBuilder) + .setAttributesAdvice(attributesAdvice); + } + DoubleGauge gauge = doubleGaugeBuilder.build(); + return gauge::set; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasDoubleGaugeSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // long gauge + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + LongGaugeBuilder longGaugeBuilder = + meterProvider.get("meter").gaugeBuilder(name).ofLongs(); + if (attributesAdvice != null) { + ((ExtendedLongGaugeBuilder) longGaugeBuilder) + .setAttributesAdvice(attributesAdvice); + } + LongGauge gauge = longGaugeBuilder.build(); + return gauge::set; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasLongGaugeSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // double histogram + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + DoubleHistogramBuilder doubleHistogramBuilder = + meterProvider.get("meter").histogramBuilder(name); + if (attributesAdvice != null) { + ((ExtendedDoubleHistogramBuilder) doubleHistogramBuilder) + .setAttributesAdvice(attributesAdvice); + } + DoubleHistogram histogram = doubleHistogramBuilder.build(); + return histogram::record; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasHistogramSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // long histogram + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + LongHistogramBuilder doubleHistogramBuilder = + meterProvider.get("meter").histogramBuilder(name).ofLongs(); + if (attributesAdvice != null) { + ((ExtendedLongHistogramBuilder) doubleHistogramBuilder) + .setAttributesAdvice(attributesAdvice); + } + LongHistogram histogram = doubleHistogramBuilder.build(); + return histogram::record; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasHistogramSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // double up down counter + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + DoubleUpDownCounterBuilder doubleUpDownCounterBuilder = + meterProvider.get("meter").upDownCounterBuilder(name).ofDoubles(); + if (attributesAdvice != null) { + ((ExtendedDoubleUpDownCounterBuilder) doubleUpDownCounterBuilder) + .setAttributesAdvice(attributesAdvice); + } + DoubleUpDownCounter upDownCounter = doubleUpDownCounterBuilder.build(); + return upDownCounter::add; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasDoubleSumSatisfying( + sum -> sum.hasPointsSatisfying(assertions))), + // long up down counter + arguments( + (InstrumentFactory) + (meterProvider, name, attributesAdvice) -> { + LongUpDownCounterBuilder doubleUpDownCounterBuilder = + meterProvider.get("meter").upDownCounterBuilder(name); + if (attributesAdvice != null) { + ((ExtendedLongUpDownCounterBuilder) doubleUpDownCounterBuilder) + .setAttributesAdvice(attributesAdvice); + } + LongUpDownCounter upDownCounter = doubleUpDownCounterBuilder.build(); + return upDownCounter::add; + }, + (PointsAssert) + (metricAssert, assertions) -> + metricAssert.hasLongSumSatisfying( + sum -> sum.hasPointsSatisfying(assertions)))); + } + } + + @FunctionalInterface + interface InstrumentFactory { + + Instrument create( + SdkMeterProvider meterProvider, + String name, + @Nullable List> attributesAdvice); + } + + @FunctionalInterface + interface Instrument { + + void record(long value, Attributes attributes); + } + + @FunctionalInterface + interface PointsAssert

      > { + + void hasPointSatisfying(MetricAssert metricAssert, Consumer

      assertion); + } +} diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java new file mode 100644 index 00000000000..3d77fd6e99b --- /dev/null +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/BoundInstrumentExemplarTest.java @@ -0,0 +1,65 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.BoundLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class BoundInstrumentExemplarTest { + + /** + * When two bindings collapse to the same delta series, each must record exemplars with its own + * attributes rather than a later binding's. + */ + @Test + void delta_collapsingBindings_keepPerBindExemplarAttributes() { + InMemoryMetricReader deltaReader = InMemoryMetricReader.createDelta(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .setExemplarFilter(ExemplarFilter.alwaysOn()) + // Drops "drop", collapsing the two attribute sets below to the single series {keep=k}. + .registerView( + InstrumentSelector.builder().setName("test-counter").build(), + View.builder().setAttributeFilter(Collections.singleton("keep")).build()) + .registerMetricReader(deltaReader) + .build(); + Meter meter = meterProvider.get(BoundInstrumentExemplarTest.class.getName()); + + ExtendedLongCounter counter = + (ExtendedLongCounter) meter.counterBuilder("test-counter").build(); + + Attributes first = Attributes.builder().put("keep", "k").put("drop", "first").build(); + Attributes second = Attributes.builder().put("keep", "k").put("drop", "second").build(); + + BoundLongCounter boundFirst = counter.bind(first); + BoundLongCounter boundSecond = counter.bind(second); + assertThat(boundFirst).isNotSameAs(boundSecond); + + boundFirst.add(1); + + assertThat(deltaReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasLongSumSatisfying(sum -> + sum.isDelta() + .hasPointsSatisfying(point -> + point + .hasValue(1) + .hasAttributes(Attributes.builder().put("keep", "k").build()) + .hasExemplarsSatisfying(exemplar -> + exemplar + .hasValue(1) + .hasFilteredAttributes( + Attributes.builder().put("drop", "first").build()))))); + } +} diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/ContextScopedAttributesMetricTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/ContextScopedAttributesMetricTest.java new file mode 100644 index 00000000000..8438e65b634 --- /dev/null +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/ContextScopedAttributesMetricTest.java @@ -0,0 +1,385 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.common.ContextAttributes; +import io.opentelemetry.api.incubator.metrics.BoundDoubleCounter; +import io.opentelemetry.api.incubator.metrics.BoundLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.metrics.DoubleCounter; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +class ContextScopedAttributesMetricTest { + + private InMemoryMetricReader reader; + private SdkMeterProviderBuilder builder; + + @BeforeEach + void setUp() { + reader = InMemoryMetricReader.create(); + builder = SdkMeterProvider.builder().registerMetricReader(reader); + } + + @Test + void disabledByDefault() { + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + LongCounter counter = meter.counterBuilder("counter").build(); + + Context ctx = ContextAttributes.set(Context.current(), Attributes.of(stringKey("k1"), "v1")); + try (Scope ignored = ctx.makeCurrent()) { + counter.add(1); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("counter") + .hasLongSumPointsSatisfying( + point -> point.hasValue(1).hasAttributes(Attributes.empty()))); + } + + @Test + void enabled_mergesWithExplicitPrecedenceAndAppliesViewFilter() { + builder.registerView( + InstrumentSelector.builder().setName("filtered_counter").build(), + View.builder().setAttributeFilter(Collections.singleton("allowed_ctx_key")).build()); + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + LongCounter counter = meter.counterBuilder("counter").build(); + LongCounter filteredCounter = meter.counterBuilder("filtered_counter").build(); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of( + stringKey("k1"), + "from-context", + stringKey("k2"), + "from-context", + stringKey("allowed_ctx_key"), + "allowed")); + try (Scope ignored = ctx.makeCurrent()) { + counter.add(5, Attributes.of(stringKey("k2"), "explicit", stringKey("k3"), "v3")); + filteredCounter.add(3, Attributes.of(stringKey("unallowed_explicit"), "dropped")); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metric -> + assertThat(metric) + .hasName("counter") + .hasLongSumPointsSatisfying(point -> + point + .hasValue(5) + .hasAttributes( + attributeEntry("k1", "from-context"), + attributeEntry("k2", "explicit"), + attributeEntry("k3", "v3"), + attributeEntry("allowed_ctx_key", "allowed"))), + metric -> + assertThat(metric) + .hasName("filtered_counter") + .hasLongSumPointsSatisfying(point -> + point + .hasValue(3) + .hasAttributes(attributeEntry("allowed_ctx_key", "allowed")))); + } + + @ParameterizedTest + @EnumSource(AggregationTemporality.class) + void boundLongCounter(AggregationTemporality temporality) { + InMemoryMetricReader localReader = + temporality == AggregationTemporality.DELTA + ? InMemoryMetricReader.createDelta() + : InMemoryMetricReader.create(); + SdkMeterProviderBuilder localBuilder = + SdkMeterProvider.builder().registerMetricReader(localReader); + SdkMeterProviderUtil.setContextScopedAttributesFilter(localBuilder, (scope, key) -> true); + SdkMeterProvider provider = localBuilder.build(); + Meter meter = provider.get("test"); + ExtendedLongCounter counter = + (ExtendedLongCounter) meter.counterBuilder("bound_counter").build(); + BoundLongCounter bound = + counter.bind( + Attributes.of(stringKey("k_bound"), "bound", stringKey("k_clash"), "bound-win")); + + bound.add(3); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("k_ctx"), "ctx", stringKey("k_clash"), "ctx-lose")); + try (Scope ignored = ctx.makeCurrent()) { + bound.add(7); + } + + assertThat(localReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("bound_counter") + .hasLongSumPointsSatisfying(point -> + point + .hasValue(10) + .hasAttributes( + attributeEntry("k_bound", "bound"), + attributeEntry("k_clash", "bound-win")))); + } + + @ParameterizedTest + @EnumSource(AggregationTemporality.class) + void boundDoubleCounter(AggregationTemporality temporality) { + InMemoryMetricReader localReader = + temporality == AggregationTemporality.DELTA + ? InMemoryMetricReader.createDelta() + : InMemoryMetricReader.create(); + SdkMeterProviderBuilder localBuilder = + SdkMeterProvider.builder().registerMetricReader(localReader); + SdkMeterProviderUtil.setContextScopedAttributesFilter(localBuilder, (scope, key) -> true); + SdkMeterProvider provider = localBuilder.build(); + Meter meter = provider.get("test"); + ExtendedDoubleCounter counter = + (ExtendedDoubleCounter) meter.counterBuilder("bound_double").ofDoubles().build(); + BoundDoubleCounter bound = + counter.bind( + Attributes.of(stringKey("k_bound"), "bound", stringKey("k_clash"), "bound-win")); + + bound.add(1.5); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("k_ctx"), "ctx", stringKey("k_clash"), "ctx-lose")); + try (Scope ignored = ctx.makeCurrent()) { + bound.add(2.5); + } + + assertThat(localReader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("bound_double") + .hasDoubleSumPointsSatisfying(point -> + point + .hasValue(4.0) + .hasAttributes( + attributeEntry("k_bound", "bound"), + attributeEntry("k_clash", "bound-win")))); + } + + @Test + void doubleCounter_explicitContext() { + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + DoubleCounter counter = meter.counterBuilder("double_counter").ofDoubles().build(); + + Context explicitCtx = + ContextAttributes.set( + Context.root(), + Attributes.of(stringKey("k_ctx"), "ctx", stringKey("k_clash"), "ctx-lose")); + + counter.add( + 2.5, + Attributes.of(stringKey("k_explicit"), "val", stringKey("k_clash"), "explicit-win"), + explicitCtx); + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("double_counter") + .hasDoubleSumPointsSatisfying(point -> + point + .hasValue(2.5) + .hasAttributes( + attributeEntry("k_explicit", "val"), + attributeEntry("k_clash", "explicit-win"), + attributeEntry("k_ctx", "ctx")))); + } + + @Test + void boundCounter_droppedInstrument() { + builder.registerView( + InstrumentSelector.builder().setName("dropped_*").build(), + View.builder().setAggregation(Aggregation.drop()).build()); + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + + ExtendedLongCounter longCounter = + (ExtendedLongCounter) meter.counterBuilder("dropped_long").build(); + BoundLongCounter boundLong = longCounter.bind(Attributes.empty()); + boundLong.add(10); + + ExtendedDoubleCounter doubleCounter = + (ExtendedDoubleCounter) meter.counterBuilder("dropped_double").ofDoubles().build(); + BoundDoubleCounter boundDouble = doubleCounter.bind(Attributes.empty()); + boundDouble.add(10.5); + + assertThat(reader.collectAllMetrics()).isEmpty(); + } + + @Test + void unboundCounter_emptyAttributesUsesContextAttributesDirectly() { + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + LongCounter counter = meter.counterBuilder("counter_empty_attrs").build(); + + Context ctx = + ContextAttributes.set(Context.current(), Attributes.of(stringKey("k_ctx"), "ctx")); + try (Scope ignored = ctx.makeCurrent()) { + counter.add(1, Attributes.empty()); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("counter_empty_attrs") + .hasLongSumPointsSatisfying( + point -> point.hasValue(1).hasAttributes(attributeEntry("k_ctx", "ctx")))); + } + + @Test + void doubleCounter_nanDropped() { + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + DoubleCounter counter = meter.counterBuilder("double_nan").ofDoubles().build(); + + Context ctx = + ContextAttributes.set(Context.current(), Attributes.of(stringKey("k_ctx"), "ctx")); + try (Scope ignored = ctx.makeCurrent()) { + counter.add(Double.NaN, Attributes.empty()); + } + + ExtendedDoubleCounter extendedCounter = (ExtendedDoubleCounter) counter; + BoundDoubleCounter bound = extendedCounter.bind(Attributes.empty()); + try (Scope ignored = ctx.makeCurrent()) { + bound.add(Double.NaN); + } + + assertThat(reader.collectAllMetrics()).isEmpty(); + } + + @Test + void boundAndUnbound_isolationInSameContext() { + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + + LongCounter unboundCounter = meter.counterBuilder("unbound_requests").build(); + ExtendedLongCounter extendedCounter = + (ExtendedLongCounter) meter.counterBuilder("bound_infra").build(); + BoundLongCounter boundCounter = + extendedCounter.bind(Attributes.of(stringKey("pool"), "shared-infra")); + + Context ctx = + ContextAttributes.set(Context.current(), Attributes.of(stringKey("tenant.id"), "acme")); + + try (Scope ignored = ctx.makeCurrent()) { + unboundCounter.add(1, Attributes.of(stringKey("route"), "/api")); + boundCounter.add(1); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metric -> + assertThat(metric) + .hasName("unbound_requests") + .hasLongSumPointsSatisfying(point -> + point + .hasValue(1) + .hasAttributes( + attributeEntry("route", "/api"), + attributeEntry("tenant.id", "acme"))), + metric -> + assertThat(metric) + .hasName("bound_infra") + .hasLongSumPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("pool", "shared-infra")))); + } + + @Test + void sameNameDifferentType_explicitWins() { + SdkMeterProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkMeterProvider provider = builder.build(); + Meter meter = provider.get("test"); + + LongCounter counter = meter.counterBuilder("collision_counter").build(); + Context ctx = + ContextAttributes.set(Context.current(), Attributes.of(stringKey("code"), "context_ok")); + + try (Scope ignored = ctx.makeCurrent()) { + counter.add(1, Attributes.of(longKey("code"), 200L)); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactly(metric -> + assertThat(metric) + .hasName("collision_counter") + .hasLongSumPointsSatisfying( + point -> point.hasValue(1).hasAttributes(attributeEntry("code", 200L)))); + } + + @Test + void filterPredicate_filtersByScopeAndKey() { + SdkMeterProviderUtil.setContextScopedAttributesFilter( + builder, + (scope, key) -> + scope.getName().equals("allowed-meter") && key.getKey().startsWith("allowed.")); + SdkMeterProvider provider = builder.build(); + + Meter allowedMeter = provider.get("allowed-meter"); + Meter otherMeter = provider.get("other-meter"); + + LongCounter allowedCounter = allowedMeter.counterBuilder("m1").build(); + LongCounter otherCounter = otherMeter.counterBuilder("m2").build(); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of( + stringKey("allowed.k"), "v1", + stringKey("denied.k"), "v2")); + + try (Scope ignored = ctx.makeCurrent()) { + allowedCounter.add(1); + otherCounter.add(1); + } + + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metric -> + assertThat(metric) + .hasName("m1") + .hasLongSumPointsSatisfying(point -> + point.hasValue(1).hasAttributes(attributeEntry("allowed.k", "v1"))), + metric -> + assertThat(metric) + .hasName("m2") + .hasLongSumPointsSatisfying( + point -> point.hasValue(1).hasAttributes(Attributes.empty()))); + } +} diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java new file mode 100644 index 00000000000..bd77a48e337 --- /dev/null +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/MeterConfigTest.java @@ -0,0 +1,301 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameMatchesGlob; +import static io.opentelemetry.sdk.metrics.internal.MeterConfig.defaultConfig; +import static io.opentelemetry.sdk.metrics.internal.MeterConfig.disabled; +import static io.opentelemetry.sdk.metrics.internal.MeterConfig.enabled; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static java.util.stream.Collectors.groupingBy; + +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.internal.MeterConfig; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class MeterConfigTest { + + @Test + void disableScopes() { + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + // Disable meterB. Since meters are enabled by default, meterA and meterC are enabled. + .addMeterConfiguratorCondition(nameEquals("meterB"), disabled()) + .registerMetricReader(reader) + // Register drop aggregation for all instruments of meterD. Instruments are disabled if + // their relevant MeterConfig is disabled, or if there are no resolved views which + // consume the measurements. + .registerView( + InstrumentSelector.builder().setMeterName("meterD").build(), + View.builder().setAggregation(Aggregation.drop()).build()) + .build(); + + Meter meterA = meterProvider.get("meterA"); + Meter meterB = meterProvider.get("meterB"); + Meter meterC = meterProvider.get("meterC"); + Meter meterD = meterProvider.get("meterD"); + AtomicLong meterAInvocations = new AtomicLong(); + AtomicLong meterBInvocations = new AtomicLong(); + AtomicLong meterCInvocations = new AtomicLong(); + AtomicLong meterDInvocations = new AtomicLong(); + + // Record measurements to each instrument type + recordToMeterInstruments(meterA, meterAInvocations); + recordToMeterInstruments(meterB, meterBInvocations); + recordToMeterInstruments(meterC, meterCInvocations); + recordToMeterInstruments(meterD, meterDInvocations); + + // Only metrics from meterA and meterC should be seen + assertThat(reader.collectAllMetrics()) + .satisfies(metrics -> { + Map> metricsByScope = + metrics.stream().collect(groupingBy(MetricData::getInstrumentationScopeInfo)); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterA"))).hasSize(14); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterB"))).isNull(); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterC"))).hasSize(14); + assertThat(metricsByScope.get(InstrumentationScopeInfo.create("meterD"))).isNull(); + }); + // Only async callbacks from meterA and meterC should be invoked + assertThat(meterAInvocations.get()).isPositive(); + assertThat(meterBInvocations.get()).isZero(); + assertThat(meterCInvocations.get()).isPositive(); + assertThat(meterDInvocations.get()).isZero(); + // Instruments from meterA and meterC are enabled, meterC is not enabled + assertMeterInstrumentsEnabled(meterA, /* expectedEnabled= */ true); + assertMeterInstrumentsEnabled(meterB, /* expectedEnabled= */ false); + assertMeterInstrumentsEnabled(meterC, /* expectedEnabled= */ true); + assertMeterInstrumentsEnabled(meterD, /* expectedEnabled= */ false); + } + + private static void recordToMeterInstruments(Meter meter, AtomicLong asyncInvocationsCount) { + meter.counterBuilder("longCounter").build().add(1); + meter.counterBuilder("doubleCounter").ofDoubles().build().add(1); + meter + .counterBuilder("asyncLongCounter") + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); + meter + .counterBuilder("asyncDoubleCounter") + .ofDoubles() + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); + meter.upDownCounterBuilder("longUpDownCounter").build().add(1); + meter.upDownCounterBuilder("doubleUpDownCounter").ofDoubles().build().add(1); + meter + .upDownCounterBuilder("asyncLongUpDownCounter") + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); + meter + .upDownCounterBuilder("asyncDoubleUpDownCounter") + .ofDoubles() + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); + meter.histogramBuilder("doubleHistogram").build().record(1.0); + meter.histogramBuilder("longHistogram").ofLongs().build().record(1); + meter.gaugeBuilder("doubleGauge").build().set(1); + meter.gaugeBuilder("longGauge").ofLongs().build().set(1); + meter + .gaugeBuilder("asyncDoubleGauge") + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1.0); + }); + meter + .gaugeBuilder("asyncLongGauge") + .ofLongs() + .buildWithCallback(observable -> { + asyncInvocationsCount.incrementAndGet(); + observable.record(1); + }); + } + + private static void assertMeterInstrumentsEnabled(Meter meter, boolean expectedEnabled) { + assertThat( + ((ExtendedDoubleCounter) meter.counterBuilder("doubleCounter").ofDoubles().build()) + .isEnabled()) + .isEqualTo(expectedEnabled); + assertThat(((ExtendedLongCounter) meter.counterBuilder("longCounter").build()).isEnabled()) + .isEqualTo(expectedEnabled); + assertThat( + ((ExtendedDoubleUpDownCounter) + meter.upDownCounterBuilder("doubleUpDownCounter").ofDoubles().build()) + .isEnabled()) + .isEqualTo(expectedEnabled); + assertThat( + ((ExtendedLongUpDownCounter) meter.upDownCounterBuilder("longUpDownCounter").build()) + .isEnabled()) + .isEqualTo(expectedEnabled); + assertThat( + ((ExtendedDoubleHistogram) meter.histogramBuilder("doubleHistogram").build()) + .isEnabled()) + .isEqualTo(expectedEnabled); + assertThat( + ((ExtendedLongHistogram) meter.histogramBuilder("longHistogram").ofLongs().build()) + .isEnabled()) + .isEqualTo(expectedEnabled); + assertThat(((ExtendedDoubleGauge) meter.gaugeBuilder("doubleGauge").build()).isEnabled()) + .isEqualTo(expectedEnabled); + assertThat(((ExtendedLongGauge) meter.gaugeBuilder("longGauge").ofLongs().build()).isEnabled()) + .isEqualTo(expectedEnabled); + } + + @ParameterizedTest + @MethodSource("meterConfiguratorArgs") + void meterConfigurator( + ScopeConfigurator meterConfigurator, + InstrumentationScopeInfo scope, + MeterConfig expectedMeterConfig) { + MeterConfig meterConfig = meterConfigurator.apply(scope); + meterConfig = meterConfig == null ? defaultConfig() : meterConfig; + assertThat(meterConfig).isEqualTo(expectedMeterConfig); + } + + private static final InstrumentationScopeInfo scopeCat = InstrumentationScopeInfo.create("cat"); + private static final InstrumentationScopeInfo scopeDog = InstrumentationScopeInfo.create("dog"); + private static final InstrumentationScopeInfo scopeDuck = InstrumentationScopeInfo.create("duck"); + + private static Stream meterConfiguratorArgs() { + ScopeConfigurator defaultConfigurator = MeterConfig.configuratorBuilder().build(); + ScopeConfigurator disableCat = + MeterConfig.configuratorBuilder() + .addCondition(nameEquals("cat"), MeterConfig.disabled()) + // Second matching rule for cat should be ignored + .addCondition(nameEquals("cat"), enabled()) + .build(); + ScopeConfigurator disableStartsWithD = + MeterConfig.configuratorBuilder() + .addCondition(nameMatchesGlob("d*"), MeterConfig.disabled()) + .build(); + ScopeConfigurator enableCat = + MeterConfig.configuratorBuilder() + .setDefault(MeterConfig.disabled()) + .addCondition(nameEquals("cat"), enabled()) + // Second matching rule for cat should be ignored + .addCondition(nameEquals("cat"), MeterConfig.disabled()) + .build(); + ScopeConfigurator enableStartsWithD = + MeterConfig.configuratorBuilder() + .setDefault(MeterConfig.disabled()) + .addCondition(nameMatchesGlob("d*"), MeterConfig.enabled()) + .build(); + + return Stream.of( + Arguments.argumentSet("default cat", defaultConfigurator, scopeCat, defaultConfig()), + Arguments.argumentSet("default dog", defaultConfigurator, scopeDog, defaultConfig()), + Arguments.argumentSet("default duck", defaultConfigurator, scopeDuck, defaultConfig()), + Arguments.argumentSet( + "disable cat - cat disabled", disableCat, scopeCat, MeterConfig.disabled()), + Arguments.argumentSet("disable cat - dog enabled", disableCat, scopeDog, enabled()), + Arguments.argumentSet("disable cat - duck enabled", disableCat, scopeDuck, enabled()), + Arguments.argumentSet("disable d* - cat enabled", disableStartsWithD, scopeCat, enabled()), + Arguments.argumentSet( + "disable d* - dog disabled", disableStartsWithD, scopeDog, MeterConfig.disabled()), + Arguments.argumentSet( + "disable d* - duck disabled", disableStartsWithD, scopeDuck, MeterConfig.disabled()), + Arguments.argumentSet("enable cat - cat enabled", enableCat, scopeCat, enabled()), + Arguments.argumentSet( + "enable cat - dog disabled", enableCat, scopeDog, MeterConfig.disabled()), + Arguments.argumentSet( + "enable cat - duck disabled", enableCat, scopeDuck, MeterConfig.disabled()), + Arguments.argumentSet( + "enable d* - cat disabled", enableStartsWithD, scopeCat, MeterConfig.disabled()), + Arguments.argumentSet("enable d* - dog enabled", enableStartsWithD, scopeDog, enabled()), + Arguments.argumentSet("enable d* - duck enabled", enableStartsWithD, scopeDuck, enabled())); + } + + @Test + void setScopeConfigurator() { + // 1. Initially, configure all meters to be enabled except meterB + InMemoryMetricReader reader = InMemoryMetricReader.create(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder() + .addMeterConfiguratorCondition(nameEquals("meterB"), disabled()) + .registerMetricReader(reader) + .build(); + + SdkMeter meterA = (SdkMeter) meterProvider.get("meterA"); + SdkMeter meterB = (SdkMeter) meterProvider.get("meterB"); + SdkMeter meterC = (SdkMeter) meterProvider.get("meterC"); + + // verify isMeterEnabled() + assertThat(meterA.isMeterEnabled()).isTrue(); + assertThat(meterB.isMeterEnabled()).isFalse(); + assertThat(meterC.isMeterEnabled()).isTrue(); + + // verify metrics are emitted as expected + meterA.counterBuilder("meterA").build().add(1); + meterB.counterBuilder("meterB").build().add(2); + meterC.counterBuilder("meterC").build().add(3); + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metricData -> assertThat(metricData).hasName("meterA"), + metricData -> assertThat(metricData).hasName("meterC")); + + // 2. Update config to disable all meters + meterProvider.setMeterConfigurator( + ScopeConfigurator.builder().setDefault(disabled()).build()); + + // verify isEnabled() + assertThat(meterA.isMeterEnabled()).isFalse(); + assertThat(meterB.isMeterEnabled()).isFalse(); + assertThat(meterC.isMeterEnabled()).isFalse(); + + // verify metrics are emitted as expected + meterA.counterBuilder("meterA").build().add(1); + meterB.counterBuilder("meterB").build().add(2); + meterC.counterBuilder("meterC").build().add(3); + assertThat(reader.collectAllMetrics()).isEmpty(); + + // 3. Update config to restore original + meterProvider.setMeterConfigurator( + ScopeConfigurator.builder() + .addCondition(nameEquals("meterB"), disabled()) + .build()); + + // verify isEnabled() + assertThat(meterA.isMeterEnabled()).isTrue(); + assertThat(meterB.isMeterEnabled()).isFalse(); + assertThat(meterC.isMeterEnabled()).isTrue(); + + // verify metrics are emitted as expected + meterA.counterBuilder("meterA").build().add(1); + meterB.counterBuilder("meterB").build().add(2); + meterC.counterBuilder("meterC").build().add(3); + assertThat(reader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + metricData -> assertThat(metricData).hasName("meterA"), + metricData -> assertThat(metricData).hasName("meterC")); + } +} diff --git a/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java new file mode 100644 index 00000000000..c1babd7f59d --- /dev/null +++ b/sdk/metrics/src/testIncubating/java/io/opentelemetry/sdk/metrics/SynchronousInstrumentStressTest.java @@ -0,0 +1,921 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.metrics; + +import static io.opentelemetry.api.common.Attributes.empty; +import static io.opentelemetry.sdk.metrics.InstrumentType.COUNTER; +import static io.opentelemetry.sdk.metrics.InstrumentType.GAUGE; +import static io.opentelemetry.sdk.metrics.InstrumentType.HISTOGRAM; +import static io.opentelemetry.sdk.metrics.InstrumentType.UP_DOWN_COUNTER; +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static java.util.stream.Collectors.toList; +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.common.util.concurrent.Uninterruptibles; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedDoubleUpDownCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongCounter; +import io.opentelemetry.api.incubator.metrics.ExtendedLongGauge; +import io.opentelemetry.api.incubator.metrics.ExtendedLongHistogram; +import io.opentelemetry.api.incubator.metrics.ExtendedLongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.internal.testing.CleanupExtension; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.data.HistogramPointData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.PointData; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; +import io.opentelemetry.sdk.metrics.internal.aggregator.ExplicitBucketHistogramUtils; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.LongStream; +import java.util.stream.Stream; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.extension.RegisterExtension; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +/** + * {@link #stressTest(AggregationTemporality, InstrumentType, Aggregation, MemoryMode, + * InstrumentValueType, boolean)} performs a stress test to confirm simultaneous record and + * collections do not have concurrency issues like lost writes, partial writes, duplicate writes, + * etc. All combinations of the following dimensions are tested: aggregation temporality, instrument + * type (synchronous), memory mode, instrument value type, and whether recording goes through bound + * instruments ({@code Extended*#bind(Attributes)}) or unbound instruments. + * + *

      Lives in {@code testIncubating} because the bound dimension exercises {@code + * opentelemetry-api-incubator}, which the base {@code test} source set is not allowed to depend on. + */ +class SynchronousInstrumentStressTest { + + private static final String INSTRUMENT_NAME = "instrument"; + private static final List BUCKET_BOUNDARIES = + ExplicitBucketHistogramUtils.DEFAULT_HISTOGRAM_BUCKET_BOUNDARIES; + private static final double[] BUCKET_BOUNDARIES_ARR = + BUCKET_BOUNDARIES.stream().mapToDouble(Double::doubleValue).toArray(); + + private static final AttributeKey KEY = AttributeKey.stringKey("key"); + private static final Attributes ATTR_1 = Attributes.of(KEY, "value1"); + private static final Attributes ATTR_2 = Attributes.of(KEY, "value2"); + private static final Attributes ATTR_3 = Attributes.of(KEY, "value3"); + private static final Attributes ATTR_4 = Attributes.of(KEY, "value4"); + + @RegisterExtension CleanupExtension cleanup = new CleanupExtension(); + + // Can change to a higher value when making changes to internals to improve confidence of + // correctness. + private static final int STRESS_TEST_REPETITIONS = 10; + + @ParameterizedTest + @MethodSource("stressTestArgs") + void stressTest( + AggregationTemporality aggregationTemporality, + InstrumentType instrumentType, + Aggregation aggregation, + MemoryMode memoryMode, + InstrumentValueType instrumentValueType, + boolean bound) { + for (int repetition = 0; repetition < STRESS_TEST_REPETITIONS; repetition++) { + stressTestOnce( + aggregationTemporality, + instrumentType, + aggregation, + memoryMode, + instrumentValueType, + bound); + } + } + + @SuppressWarnings({"ThreadPriorityCheck", "ReferenceEquality"}) + private void stressTestOnce( + AggregationTemporality aggregationTemporality, + InstrumentType instrumentType, + Aggregation aggregation, + MemoryMode memoryMode, + InstrumentValueType instrumentValueType, + boolean bound) { + // Define list of measurements to record. Shuffled 0..1999. + int measurementCount = 2000; + List measurements = new ArrayList<>(); + for (int i = 0; i < measurementCount; i++) { + measurements.add((long) i); + } + Collections.shuffle(measurements); + + List collectedMetrics = + runStressLoop( + aggregationTemporality, + instrumentType, + aggregation, + memoryMode, + instrumentValueType, + bound, + measurements); + int threadCount = 4; + + // Assert collected data is consistent with recorded measurements by independently computing the + // expected aggregated value and comparing to the actual results. + // NOTE: this does not validate the absence of partial writes for cumulative instruments which + // track multiple fields. For example, explicit histogram tracks sum and bucket counts. These + // should be atomically updated such that we never collect the sum without corresponding bucket + // counts update, or vice versa. This test asserts that the cumulative state at the end is + // consistent, and interim collects unknowingly see partial writes. + AtomicLong lastValue = new AtomicLong(0); + AtomicLong sum = new AtomicLong(0); + AtomicLong min = new AtomicLong(Long.MAX_VALUE); + AtomicLong max = new AtomicLong(-1); + List bucketCounts = new ArrayList<>(); + for (int i = 0; i < BUCKET_BOUNDARIES.size() + 1; i++) { + bucketCounts.add(0L); + } + AtomicLong totalCount = new AtomicLong(0); + AtomicLong zeroCount = new AtomicLong(0); + LongStream.range(0, threadCount) + .flatMap(i -> measurements.stream().mapToLong(l -> l)) + .forEach(measurement -> { + lastValue.set(measurement); + sum.addAndGet(measurement); + min.updateAndGet(v -> Math.min(v, measurement)); + max.updateAndGet(v -> Math.max(v, measurement)); + totalCount.incrementAndGet(); + int bucketIndex = + ExplicitBucketHistogramUtils.findBucketIndex( + BUCKET_BOUNDARIES_ARR, (double) measurement); + bucketCounts.set(bucketIndex, bucketCounts.get(bucketIndex) + 1); + if (measurement == 0) { + zeroCount.incrementAndGet(); + } + }); + + boolean isCumulative = aggregationTemporality == AggregationTemporality.CUMULATIVE; + List points = + Stream.of(ATTR_1, ATTR_2, ATTR_3, ATTR_4) + .map(attr -> getReducedPointData(collectedMetrics, isCumulative, attr)) + .collect(toList()); + if (aggregation == Aggregation.sum()) { + if (instrumentValueType == InstrumentValueType.DOUBLE) { + assertThat(points) + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + DoublePointData.class, + p -> assertThat(p.getValue()).isEqualTo((double) sum.get()))); + + } else { + assertThat(points) + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + LongPointData.class, p -> assertThat(p.getValue()).isEqualTo(sum.get()))); + } + } else if (aggregation == Aggregation.lastValue()) { + if (instrumentValueType == InstrumentValueType.DOUBLE) { + assertThat(points) + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + DoublePointData.class, + p -> assertThat(p.getValue()).isEqualTo((double) lastValue.get()))); + } else { + assertThat(points) + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + LongPointData.class, + p -> assertThat(p.getValue()).isEqualTo(lastValue.get()))); + } + } else if (aggregation == Aggregation.explicitBucketHistogram()) { + assertThat(points) + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + HistogramPointData.class, + p -> { + assertThat(p.getSum()).isEqualTo((double) sum.get()); + assertThat(p.getMin()).isEqualTo((double) min.get()); + assertThat(p.getMax()).isEqualTo((double) max.get()); + assertThat(p.getCount()) + .isEqualTo(bucketCounts.stream().reduce(0L, Long::sum)); + assertThat(p.getCounts()).isEqualTo(bucketCounts); + })); + } else if (aggregation == Aggregation.base2ExponentialBucketHistogram()) { + assertThat(points) + .allSatisfy(point -> + assertThat(point) + .isInstanceOfSatisfying( + ExponentialHistogramPointData.class, + p -> { + assertThat(p.getSum()).isEqualTo((double) sum.get()); + assertThat(p.getMin()).isEqualTo((double) min.get()); + assertThat(p.getMax()).isEqualTo((double) max.get()); + assertThat(p.getZeroCount()).isEqualTo(zeroCount.get()); + assertThat( + p.getPositiveBuckets().getBucketCounts().stream() + .reduce(0L, Long::sum)) + .isEqualTo(totalCount.get() - zeroCount.get()); + })); + } else { + throw new IllegalArgumentException(); + } + } + + /** + * Complements {@link #stressTest} by asserting that no interim collected snapshot ever + * shows a partial write β€” e.g., a histogram with {@code sum} disagreeing with the sum of its + * bucket counts, indicating the collector observed a recorder mid-write. + * + *

      Every recorder records a uniform value of 1, so the assertions are checkable per snapshot + * without knowing which specific observations completed at snapshot time: for any histogram + * point, {@code sum == count * 1}, and the sum of bucket counts equals {@code count}. + * + *

      Assertions run after the stress phase completes, so the collector loop is never slowed down. + * Scoped to histogram aggregations β€” the invariant is trivial for scalar aggregations + * (sum/last-value), which don't span multiple mutable fields per record. + */ + @ParameterizedTest + @MethodSource("stressTestArgs") + @Timeout(value = 10, unit = TimeUnit.SECONDS, threadMode = Timeout.ThreadMode.SEPARATE_THREAD) + void partialWriteStressTest( + AggregationTemporality aggregationTemporality, + InstrumentType instrumentType, + Aggregation aggregation, + MemoryMode memoryMode, + InstrumentValueType instrumentValueType, + boolean bound) { + for (int repetition = 0; repetition < STRESS_TEST_REPETITIONS; repetition++) { + partialWriteStressTestOnce( + aggregationTemporality, + instrumentType, + aggregation, + memoryMode, + instrumentValueType, + bound); + } + } + + @SuppressWarnings("ReferenceEquality") + private void partialWriteStressTestOnce( + AggregationTemporality aggregationTemporality, + InstrumentType instrumentType, + Aggregation aggregation, + MemoryMode memoryMode, + InstrumentValueType instrumentValueType, + boolean bound) { + // Uniform value of 1 so that at any interim snapshot: sum == count. + int measurementCount = 2000; + List measurements = new ArrayList<>(measurementCount); + for (int i = 0; i < measurementCount; i++) { + measurements.add(1L); + } + + List collectedMetrics = + runStressLoop( + aggregationTemporality, + instrumentType, + aggregation, + memoryMode, + instrumentValueType, + bound, + measurements); + + // Assert every collected point is internally consistent (no partial writes visible). Scalar + // aggregators can't produce partial writes structurally, but we still exercise them for + // general concurrent-path regression coverage with light per-type invariants. + if (aggregation == Aggregation.explicitBucketHistogram()) { + collectedMetrics.stream() + .flatMap(m -> m.getHistogramData().getPoints().stream()) + .forEach(p -> { + long bucketSum = p.getCounts().stream().reduce(0L, Long::sum); + assertThat(p.getCount()).as("count == sum of bucket counts").isEqualTo(bucketSum); + assertThat(p.getSum()) + .as("sum == count (uniform value=1)") + .isEqualTo((double) p.getCount()); + if (p.getCount() > 0) { + assertThat(p.hasMin()).isTrue(); + assertThat(p.getMin()).as("min == 1 (uniform value)").isEqualTo(1.0); + assertThat(p.hasMax()).isTrue(); + assertThat(p.getMax()).as("max == 1 (uniform value)").isEqualTo(1.0); + } + }); + } else if (aggregation == Aggregation.base2ExponentialBucketHistogram()) { + collectedMetrics.stream() + .flatMap(m -> m.getExponentialHistogramData().getPoints().stream()) + .forEach(p -> { + long positiveBucketSum = + p.getPositiveBuckets().getBucketCounts().stream().reduce(0L, Long::sum); + long negativeBucketSum = + p.getNegativeBuckets().getBucketCounts().stream().reduce(0L, Long::sum); + assertThat(p.getCount()) + .as("count == pos + neg + zero bucket counts") + .isEqualTo(positiveBucketSum + negativeBucketSum + p.getZeroCount()); + assertThat(p.getSum()) + .as("sum == count (uniform value=1)") + .isEqualTo((double) p.getCount()); + if (p.getCount() > 0) { + assertThat(p.hasMin()).isTrue(); + assertThat(p.getMin()).as("min == 1 (uniform value)").isEqualTo(1.0); + assertThat(p.hasMax()).isTrue(); + assertThat(p.getMax()).as("max == 1 (uniform value)").isEqualTo(1.0); + } + }); + } else if (aggregation == Aggregation.sum()) { + // Uniform value=1 adds only. Sum should be a non-negative whole number. + if (instrumentValueType == InstrumentValueType.DOUBLE) { + collectedMetrics.stream() + .flatMap(m -> m.getDoubleSumData().getPoints().stream()) + .forEach(p -> { + assertThat(p.getValue()).as("sum non-negative").isGreaterThanOrEqualTo(0.0); + assertThat(p.getValue()).as("sum is integral").isEqualTo(Math.floor(p.getValue())); + }); + } else { + collectedMetrics.stream() + .flatMap(m -> m.getLongSumData().getPoints().stream()) + .forEach( + p -> assertThat(p.getValue()).as("sum non-negative").isGreaterThanOrEqualTo(0L)); + } + } else if (aggregation == Aggregation.lastValue()) { + // Every observation is 1; any non-empty snapshot's value must be 1. + if (instrumentValueType == InstrumentValueType.DOUBLE) { + collectedMetrics.stream() + .flatMap(m -> m.getDoubleGaugeData().getPoints().stream()) + .forEach(p -> assertThat(p.getValue()).as("last-value == 1").isEqualTo(1.0)); + } else { + collectedMetrics.stream() + .flatMap(m -> m.getLongGaugeData().getPoints().stream()) + .forEach(p -> assertThat(p.getValue()).as("last-value == 1").isEqualTo(1L)); + } + } else { + throw new IllegalArgumentException("Unexpected aggregation: " + aggregation); + } + } + + /** + * Runs a record/collect stress loop and returns the collected metric snapshots. Each of the 4 + * recording threads iterates {@code measurements}, and for each measurement records it against + * every attribute (or, when {@code bound}, every pre-bound instrument). The collector thread + * continuously calls {@code collectAllMetrics} until recorders complete, then does one final + * collect. Copies are taken of each collected {@link MetricData} because {@code REUSABLE_DATA} + * mode reuses instances across collects. + */ + @SuppressWarnings("ThreadPriorityCheck") + private List runStressLoop( + AggregationTemporality aggregationTemporality, + InstrumentType instrumentType, + Aggregation aggregation, + MemoryMode memoryMode, + InstrumentValueType instrumentValueType, + boolean bound, + List measurements) { + DefaultAggregationSelector aggregationSelector = + DefaultAggregationSelector.getDefault().with(instrumentType, aggregation); + InMemoryMetricReader reader = + InMemoryMetricReader.builder() + .setDefaultAggregationSelector(aggregationSelector) + .setAggregationTemporalitySelector(unused -> aggregationTemporality) + .setMemoryMode(memoryMode) + .build(); + SdkMeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(reader).build(); + cleanup.addCloseable(meterProvider); + Meter meter = meterProvider.get("test"); + List attributes = Arrays.asList(ATTR_1, ATTR_2, ATTR_3, ATTR_4); + Collections.shuffle(attributes); + // When unbound, record through `instrument`, looking up the series by attributes on each call. + // When bound, bind one instrument per series up front and record straight to those (no + // per-record attribute lookup) β€” the record loop below forks accordingly. + Instrument instrument = getInstrument(meter, instrumentType, instrumentValueType); + List boundInstruments = new ArrayList<>(); + if (bound) { + for (Attributes attr : attributes) { + boundInstruments.add(getBoundInstrument(meter, instrumentType, instrumentValueType, attr)); + } + } + + int threadCount = 4; + List recordThreads = new ArrayList<>(); + CountDownLatch latch = new CountDownLatch(threadCount); + CountDownLatch startSignal = new CountDownLatch(1); + for (int i = 0; i < threadCount; i++) { + recordThreads.add( + new Thread(() -> { + Uninterruptibles.awaitUninterruptibly(startSignal); + if (bound) { + for (Long measurement : measurements) { + for (BoundInstrument boundInstrument : boundInstruments) { + boundInstrument.record(measurement); + } + Thread.yield(); + } + } else { + for (Long measurement : measurements) { + for (Attributes attr : attributes) { + instrument.record(measurement, attr); + } + Thread.yield(); + } + } + latch.countDown(); + })); + } + + List collectedMetrics = new ArrayList<>(); + Thread collectThread = + new Thread(() -> { + Uninterruptibles.awaitUninterruptibly(startSignal); + while (latch.getCount() != 0) { + Thread.yield(); + collectedMetrics.addAll( + reader.collectAllMetrics().stream() + .map(SynchronousInstrumentStressTest::copy) + .collect(toList())); + } + collectedMetrics.addAll( + reader.collectAllMetrics().stream() + .map(SynchronousInstrumentStressTest::copy) + .collect(toList())); + }); + + // Start all the threads, then release the start signal so they begin simultaneously + collectThread.start(); + recordThreads.forEach(Thread::start); + startSignal.countDown(); + + // Wait for the collect thread to end, which collects until the record threads are done + Uninterruptibles.joinUninterruptibly(collectThread); + return collectedMetrics; + } + + private static Stream stressTestArgs() { + List argumentsList = new ArrayList<>(); + for (AggregationTemporality aggregationTemporality : AggregationTemporality.values()) { + for (InstrumentTypeAndAggregation instrumentTypeAndAggregation : + InstrumentTypeAndAggregation.values()) { + for (MemoryMode memoryMode : MemoryMode.values()) { + for (InstrumentValueType instrumentValueType : InstrumentValueType.values()) { + for (boolean bound : new boolean[] {false, true}) { + argumentsList.add( + Arguments.argumentSet( + aggregationTemporality + + " " + + instrumentTypeAndAggregation.instrumentType + + " " + + memoryMode + + " " + + instrumentValueType + + (bound ? " bound" : " unbound"), + aggregationTemporality, + instrumentTypeAndAggregation.instrumentType, + instrumentTypeAndAggregation.aggregation, + memoryMode, + instrumentValueType, + bound)); + } + } + } + } + } + return argumentsList.stream(); + } + + private static Instrument getInstrument( + Meter meter, InstrumentType instrumentType, InstrumentValueType instrumentValueType) { + switch (instrumentType) { + case COUNTER: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.counterBuilder(INSTRUMENT_NAME).ofDoubles().build()::add + : meter.counterBuilder(INSTRUMENT_NAME).build()::add; + case UP_DOWN_COUNTER: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.upDownCounterBuilder(INSTRUMENT_NAME).ofDoubles().build()::add + : meter.upDownCounterBuilder(INSTRUMENT_NAME).build()::add; + case HISTOGRAM: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter + .histogramBuilder(INSTRUMENT_NAME) + .setExplicitBucketBoundariesAdvice(BUCKET_BOUNDARIES) + .build() + ::record + : meter + .histogramBuilder(INSTRUMENT_NAME) + .setExplicitBucketBoundariesAdvice(BUCKET_BOUNDARIES) + .ofLongs() + .build() + ::record; + case GAUGE: + return instrumentValueType == InstrumentValueType.DOUBLE + ? meter.gaugeBuilder(INSTRUMENT_NAME).build()::set + : meter.gaugeBuilder(INSTRUMENT_NAME).ofLongs().build()::set; + case OBSERVABLE_COUNTER: + case OBSERVABLE_UP_DOWN_COUNTER: + case OBSERVABLE_GAUGE: + } + throw new IllegalArgumentException(); + } + + /** + * Builds the instrument for the given type / value type and binds it to {@code attributes}, + * returning a {@link BoundInstrument} that records straight to that series. Mirrors {@link + * #getInstrument} but for the bound API. + */ + private static BoundInstrument getBoundInstrument( + Meter meter, + InstrumentType instrumentType, + InstrumentValueType instrumentValueType, + Attributes attributes) { + boolean isDouble = instrumentValueType == InstrumentValueType.DOUBLE; + switch (instrumentType) { + case COUNTER: + return isDouble + ? ((ExtendedDoubleCounter) meter.counterBuilder(INSTRUMENT_NAME).ofDoubles().build()) + .bind(attributes) + ::add + : ((ExtendedLongCounter) meter.counterBuilder(INSTRUMENT_NAME).build()).bind(attributes) + ::add; + case UP_DOWN_COUNTER: + return isDouble + ? ((ExtendedDoubleUpDownCounter) + meter.upDownCounterBuilder(INSTRUMENT_NAME).ofDoubles().build()) + .bind(attributes) + ::add + : ((ExtendedLongUpDownCounter) meter.upDownCounterBuilder(INSTRUMENT_NAME).build()) + .bind(attributes) + ::add; + case HISTOGRAM: + return isDouble + ? ((ExtendedDoubleHistogram) + meter + .histogramBuilder(INSTRUMENT_NAME) + .setExplicitBucketBoundariesAdvice(BUCKET_BOUNDARIES) + .build()) + .bind(attributes) + ::record + : ((ExtendedLongHistogram) + meter + .histogramBuilder(INSTRUMENT_NAME) + .setExplicitBucketBoundariesAdvice(BUCKET_BOUNDARIES) + .ofLongs() + .build()) + .bind(attributes) + ::record; + case GAUGE: + return isDouble + ? ((ExtendedDoubleGauge) meter.gaugeBuilder(INSTRUMENT_NAME).build()).bind(attributes) + ::set + : ((ExtendedLongGauge) meter.gaugeBuilder(INSTRUMENT_NAME).ofLongs().build()) + .bind(attributes) + ::set; + case OBSERVABLE_COUNTER: + case OBSERVABLE_UP_DOWN_COUNTER: + case OBSERVABLE_GAUGE: + } + throw new IllegalArgumentException(); + } + + private interface Instrument { + void record(long value, Attributes attributes); + } + + @FunctionalInterface + private interface BoundInstrument { + void record(long value); + } + + private static MetricData copy(MetricData m) { + switch (m.getType()) { + case LONG_GAUGE: + return ImmutableMetricData.createLongGauge( + m.getResource(), + m.getInstrumentationScopeInfo(), + m.getName(), + m.getDescription(), + m.getUnit(), + ImmutableGaugeData.create( + m.getLongGaugeData().getPoints().stream() + .map(p -> + ImmutableLongPointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) + .collect(toList()))); + case DOUBLE_GAUGE: + return ImmutableMetricData.createDoubleGauge( + m.getResource(), + m.getInstrumentationScopeInfo(), + m.getName(), + m.getDescription(), + m.getUnit(), + ImmutableGaugeData.create( + m.getDoubleGaugeData().getPoints().stream() + .map(p -> + ImmutableDoublePointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) + .collect(toList()))); + case LONG_SUM: + return ImmutableMetricData.createLongSum( + m.getResource(), + m.getInstrumentationScopeInfo(), + m.getName(), + m.getDescription(), + m.getUnit(), + ImmutableSumData.create( + m.getLongSumData().isMonotonic(), + m.getLongSumData().getAggregationTemporality(), + m.getLongSumData().getPoints().stream() + .map(p -> + ImmutableLongPointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) + .collect(toList()))); + case DOUBLE_SUM: + return ImmutableMetricData.createDoubleSum( + m.getResource(), + m.getInstrumentationScopeInfo(), + m.getName(), + m.getDescription(), + m.getUnit(), + ImmutableSumData.create( + m.getDoubleSumData().isMonotonic(), + m.getDoubleSumData().getAggregationTemporality(), + m.getDoubleSumData().getPoints().stream() + .map(p -> + ImmutableDoublePointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getValue(), + p.getExemplars())) + .collect(toList()))); + case HISTOGRAM: + return ImmutableMetricData.createDoubleHistogram( + m.getResource(), + m.getInstrumentationScopeInfo(), + m.getName(), + m.getDescription(), + m.getUnit(), + ImmutableHistogramData.create( + m.getHistogramData().getAggregationTemporality(), + m.getHistogramData().getPoints().stream() + .map(p -> + ImmutableHistogramPointData.create( + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getSum(), + p.hasMin(), + p.getMin(), + p.hasMax(), + p.getMax(), + p.getBoundaries(), + new ArrayList<>(p.getCounts()), + p.getExemplars())) + .collect(toList()))); + case EXPONENTIAL_HISTOGRAM: + return ImmutableMetricData.createExponentialHistogram( + m.getResource(), + m.getInstrumentationScopeInfo(), + m.getName(), + m.getDescription(), + m.getUnit(), + ImmutableExponentialHistogramData.create( + m.getExponentialHistogramData().getAggregationTemporality(), + m.getExponentialHistogramData().getPoints().stream() + .map(p -> + ImmutableExponentialHistogramPointData.create( + p.getScale(), + p.getSum(), + p.getZeroCount(), + p.hasMin(), + p.getMin(), + p.hasMax(), + p.getMax(), + ExponentialHistogramBuckets.create( + p.getPositiveBuckets().getScale(), + p.getPositiveBuckets().getOffset(), + new ArrayList<>(p.getPositiveBuckets().getBucketCounts())), + ExponentialHistogramBuckets.create( + p.getNegativeBuckets().getScale(), + p.getNegativeBuckets().getOffset(), + new ArrayList<>(p.getNegativeBuckets().getBucketCounts())), + p.getStartEpochNanos(), + p.getEpochNanos(), + p.getAttributes(), + p.getExemplars())) + .collect(toList()))); + case SUMMARY: + } + throw new IllegalArgumentException(); + } + + /** + * Reduce a list of metric data assumed to be uniform and for a single instrument to a single + * point data. If cumulative, return the last point data. If delta, merge the data points. + */ + private static PointData getReducedPointData( + List metrics, boolean isCumulative, Attributes attributes) { + metrics.forEach(metricData -> assertThat(metricData.getName()).isEqualTo(INSTRUMENT_NAME)); + MetricData first = metrics.get(0); + switch (first.getType()) { + case LONG_GAUGE: + List lgaugePoints = + metrics.stream() + .flatMap(m -> m.getLongGaugeData().getPoints().stream()) + .filter(p -> attributes.equals(p.getAttributes())) + .collect(toList()); + return lgaugePoints.get(lgaugePoints.size() - 1); + case DOUBLE_GAUGE: + List dgaugePoints = + metrics.stream() + .flatMap(m -> m.getDoubleGaugeData().getPoints().stream()) + .filter(p -> attributes.equals(p.getAttributes())) + .collect(toList()); + return dgaugePoints.get(dgaugePoints.size() - 1); + case LONG_SUM: + List lsumPoints = + metrics.stream() + .flatMap(m -> m.getLongSumData().getPoints().stream()) + .filter(p -> attributes.equals(p.getAttributes())) + .collect(toList()); + return isCumulative + ? lsumPoints.get(lsumPoints.size() - 1) + : lsumPoints.stream() + .reduce( + ImmutableLongPointData.create(0, 0, empty(), 0), + (p1, p2) -> + ImmutableLongPointData.create( + 0, 0, empty(), p1.getValue() + p2.getValue(), emptyList())); + case DOUBLE_SUM: + List dsumPoints = + metrics.stream() + .flatMap(m -> m.getDoubleSumData().getPoints().stream()) + .filter(p -> attributes.equals(p.getAttributes())) + .collect(toList()); + return isCumulative + ? dsumPoints.get(dsumPoints.size() - 1) + : dsumPoints.stream() + .reduce( + ImmutableDoublePointData.create(0, 0, empty(), 0), + (p1, p2) -> + ImmutableDoublePointData.create( + 0, 0, empty(), p1.getValue() + p2.getValue(), emptyList())); + case HISTOGRAM: + List histPoints = + metrics.stream() + .flatMap(m -> m.getHistogramData().getPoints().stream()) + .filter(p -> attributes.equals(p.getAttributes())) + .collect(toList()); + return isCumulative + ? histPoints.get(histPoints.size() - 1) + : histPoints.stream() + .reduce( + ImmutableHistogramPointData.create( + 0, + 0, + empty(), + 0, + /* hasMin= */ true, + 0, + /* hasMax= */ true, + 0, + emptyList(), + singletonList(0L)), + (p1, p2) -> + ImmutableHistogramPointData.create( + 0, + 0, + empty(), + p1.getSum() + p2.getSum(), + p1.hasMin() || p2.hasMin(), + Math.min(p1.getMin(), p2.getMin()), + p2.hasMax() || p1.hasMax(), + Math.max(p1.getMax(), p2.getMax()), + p2.getBoundaries(), + mergeBuckets(p1.getCounts(), p2.getCounts()))); + case EXPONENTIAL_HISTOGRAM: + List expoHistPoints = + metrics.stream() + .flatMap(m -> m.getExponentialHistogramData().getPoints().stream()) + .filter(p -> attributes.equals(p.getAttributes())) + .collect(toList()); + return isCumulative + ? expoHistPoints.get(expoHistPoints.size() - 1) + : expoHistPoints.stream() + .reduce( + // NOTE: we're only testing the correctness of sum, count, min, and max, so we + // skip the complexity of correctly merge which involves re-bucketing when the + // scale changes. The result is bucket counts with meaningless values, but + // correct aggregate counts. + ImmutableExponentialHistogramPointData.create( + 0, + 0, + 0, + /* hasMin= */ true, + 0, + /* hasMax= */ true, + 0, + ExponentialHistogramBuckets.create(0, 0, emptyList()), + ExponentialHistogramBuckets.create(0, 0, emptyList()), + 0, + 0, + empty(), + emptyList()), + (p1, p2) -> + ImmutableExponentialHistogramPointData.create( + Math.min(p1.getScale(), p2.getScale()), + p1.getSum() + p2.getSum(), + p1.getZeroCount() + p2.getZeroCount(), + p1.hasMin() || p2.hasMin(), + Math.min(p1.getMin(), p2.getMin()), + p1.hasMax() || p2.hasMax(), + Math.max(p1.getMax(), p2.getMax()), + ExponentialHistogramBuckets.create( + 0, + 0, + mergeBuckets( + p1.getPositiveBuckets().getBucketCounts(), + p2.getPositiveBuckets().getBucketCounts())), + ExponentialHistogramBuckets.create( + 0, + 0, + mergeBuckets( + p1.getNegativeBuckets().getBucketCounts(), + p2.getNegativeBuckets().getBucketCounts())), + 0, + 0, + empty(), + emptyList())); + case SUMMARY: + } + throw new IllegalArgumentException(); + } + + private static List mergeBuckets(List l1, List l2) { + int size = Math.max(l1.size(), l2.size()); + List merged = new ArrayList<>(size); + for (int i = 0; i < size; i++) { + long mergedCount = 0; + if (i < l1.size()) { + mergedCount += l1.get(i); + } + if (i < l2.size()) { + mergedCount += l2.get(i); + } + merged.add(mergedCount); + } + return merged; + } + + @SuppressWarnings("ImmutableEnumChecker") + private enum InstrumentTypeAndAggregation { + COUNTER_SUM(COUNTER, Aggregation.sum()), + UP_DOWN_COUNTER_SUM(UP_DOWN_COUNTER, Aggregation.sum()), + GAUGE_LAST_VALUE(GAUGE, Aggregation.lastValue()), + HISTOGRAM_EXPLICIT(HISTOGRAM, Aggregation.explicitBucketHistogram()), + HISTOGRAM_BASE2_EXPONENTIAL(HISTOGRAM, Aggregation.base2ExponentialBucketHistogram()); + + InstrumentTypeAndAggregation(InstrumentType instrumentType, Aggregation aggregation) { + this.instrumentType = instrumentType; + this.aggregation = aggregation; + } + + private final InstrumentType instrumentType; + private final Aggregation aggregation; + } +} diff --git a/sdk/processcontext/build.gradle.kts b/sdk/processcontext/build.gradle.kts new file mode 100644 index 00000000000..de4a83975b3 --- /dev/null +++ b/sdk/processcontext/build.gradle.kts @@ -0,0 +1,104 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") +} + +description = "OpenTelemetry - ProcessContext SDK" +otelJava.moduleName.set("io.opentelemetry.sdk.processcontext") +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.sdk.autoconfigure.declarativeconfig")) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider", + "io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider", +)) + +dependencies { + api(project(":sdk:all")) + api(project(":exporters:common")) // MessageWriter + + annotationProcessor("com.google.auto.value:auto-value") + + implementation(project(":exporters:otlp:common")) + implementation(project(":api:incubator")) // ExtendedOpenTelemetry (parent of ExtendedOpenTelemetrySdk) + + compileOnly(project(":sdk-extensions:declarative-config")) + compileOnly(project(":sdk-extensions:autoconfigure-spi")) + + testImplementation(project(":sdk:testing")) + testImplementation(project(":sdk-extensions:autoconfigure")) + testImplementation("io.opentelemetry.proto:opentelemetry-proto") + testImplementation("com.google.protobuf:protobuf-java-util") +} + +java { + sourceSets { + create("java25") { + java { + srcDir("src/main/java25") + } + compileClasspath += sourceSets.main.get().output + sourceSets.main.get().compileClasspath + } + } + toolchain { + languageVersion.set(JavaLanguageVersion.of(25)) + } +} + +tasks.named("compileJava") { + options.release.set(8) +} + +tasks.named("compileJava25Java") { + options.release.set(25) +} + +val testJavaVersion = project.findProperty("testJavaVersion") as String? + +testing { + suites { + register("java25Test") { + sources { + java { + setSrcDirs(listOf("src/test/java25")) + } + } + dependencies { + implementation(project()) + implementation(project(":sdk:testing")) + implementation(project(":sdk-extensions:autoconfigure")) + implementation(project(":sdk-extensions:declarative-config")) + implementation(sourceSets["java25"].output) + } + targets { + all { + testTask { + enabled = (testJavaVersion != null && Integer.valueOf(testJavaVersion) >= 25) + // Enables the Panama publisher so autoconfigure end-to-end tests can observe the + // OTEL_CTX mapping. Must be set at JVM start because the factory singleton reads it + // once at class load. + systemProperty("otel.experimental.process.context.enabled", "true") + } + } + } + } + } +} + +tasks.named("compileJava25TestJava") { + options.release.set(25) +} + +// Default `test` runs OS/JDK-agnostic tests. The java25Test suite covers everything that +// requires Linux + JDK 25 (Panama FFM, /proc//maps). + +tasks.check { + dependsOn(testing.suites) +} + +tasks.named("jar") { + manifest { + attributes["Multi-Release"] = "true" + } + from(sourceSets.named("java25").get().output) { + into("META-INF/versions/25") + } +} diff --git a/sdk-extensions/jfr-events/gradle.properties b/sdk/processcontext/gradle.properties similarity index 100% rename from sdk-extensions/jfr-events/gradle.properties rename to sdk/processcontext/gradle.properties diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/NoopProcessContextPublisher.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/NoopProcessContextPublisher.java new file mode 100644 index 00000000000..dcf400d4e2e --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/NoopProcessContextPublisher.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import java.util.Objects; + +final class NoopProcessContextPublisher implements ProcessContextPublisher { + + @Override + public void publish(ProcessContextData processContextData, Clock clock) { + Objects.requireNonNull(processContextData, "processContextData"); + Objects.requireNonNull(clock, "clock"); + } + + @Override + public void close() {} +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextMarshaler.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextMarshaler.java new file mode 100644 index 00000000000..1486921186a --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextMarshaler.java @@ -0,0 +1,49 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import io.opentelemetry.exporter.internal.marshal.MarshalerUtil; +import io.opentelemetry.exporter.internal.marshal.MarshalerWithSize; +import io.opentelemetry.exporter.internal.marshal.Serializer; +import io.opentelemetry.exporter.internal.otlp.KeyValueMarshaler; +import io.opentelemetry.exporter.internal.otlp.ResourceMarshaler; +import io.opentelemetry.proto.processcontext.v1development.internal.ProcessContext; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import java.io.IOException; + +final class ProcessContextMarshaler extends MarshalerWithSize { + + private final ResourceMarshaler resourceMarshaler; + private final KeyValueMarshaler[] attributeMarshalers; + + static ProcessContextMarshaler create(ProcessContextData processContextData) { + KeyValueMarshaler[] attributeMarshalers = + KeyValueMarshaler.createForAttributes(processContextData.getAttributes()); + return new ProcessContextMarshaler( + ResourceMarshaler.create(processContextData.getResource()), attributeMarshalers); + } + + private ProcessContextMarshaler( + ResourceMarshaler resourceMarshaler, KeyValueMarshaler[] attributeMarshalers) { + super(calculateSize(resourceMarshaler, attributeMarshalers)); + this.resourceMarshaler = resourceMarshaler; + this.attributeMarshalers = attributeMarshalers; + } + + @Override + protected void writeTo(Serializer output) throws IOException { + output.serializeMessage(ProcessContext.RESOURCE, resourceMarshaler); + output.serializeRepeatedMessage(ProcessContext.ATTRIBUTES, attributeMarshalers); + } + + private static int calculateSize( + ResourceMarshaler resourceMarshaler, KeyValueMarshaler[] attributeMarshalers) { + int size = 0; + size += MarshalerUtil.sizeMessage(ProcessContext.RESOURCE, resourceMarshaler); + size += MarshalerUtil.sizeRepeatedMessage(ProcessContext.ATTRIBUTES, attributeMarshalers); + return size; + } +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisher.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisher.java new file mode 100644 index 00000000000..be43c281b5c --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisher.java @@ -0,0 +1,45 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import java.io.IOException; + +/** + * Exposes process context information to external readers using the shared memory mechanism + * specified in OTEP-4719. + * + *

      Access the singleton via {@link #getInstance()}. The implementation returned is selected at + * class load time based on the running JVM and the {@code + * otel.experimental.process.context.enabled} property; it may be a no-op. + * + *

      Note that publication is a process-wide singleton per OTEP-4719. If multiple {@link + * io.opentelemetry.sdk.OpenTelemetrySdk} instances exist in the same JVM, each subsequent {@link + * #publish} call overwrites the previous publication (last-writer-wins). + * + * @see OTEP + * 4719 + */ +public interface ProcessContextPublisher extends AutoCloseable { + + /** Returns the process-wide {@link ProcessContextPublisher} instance. */ + static ProcessContextPublisher getInstance() { + return ProcessContextPublisherFactory.getInstance().create(); + } + + /** + * Called to publish a {@code ProcessContextData}s. + * + * @param processContextData the process Resource descriptor and optional additional metadata. + * @param clock the time source for the publication. + */ + void publish(ProcessContextData processContextData, Clock clock) throws IOException; + + @Override + void close() throws IOException; +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisherFactory.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisherFactory.java new file mode 100644 index 00000000000..4cc06ded4a0 --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisherFactory.java @@ -0,0 +1,88 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import io.opentelemetry.common.impl.ConfigUtil; +import java.lang.reflect.Method; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Factory for obtaining the process-wide {@link ProcessContextPublisher}. + * + *

      The supplied publisher will, depending on the Java version and OpenTelemetry configuration, be + * either a no-op or an implementation using Linux libc via Panama FFM. + */ +final class ProcessContextPublisherFactory { + + private static final Logger logger = + Logger.getLogger(ProcessContextPublisherFactory.class.getName()); + + private static final ProcessContextPublisherFactory INSTANCE = + new ProcessContextPublisherFactory(); + + private final ProcessContextPublisher processContextPublisher; + + private ProcessContextPublisherFactory() { + processContextPublisher = selectPublisher(); + } + + static ProcessContextPublisherFactory getInstance() { + return INSTANCE; + } + + ProcessContextPublisher create() { + return processContextPublisher; + } + + private static ProcessContextPublisher selectPublisher() { + // Off by default until stable. + // Spec in progress: OTEL_EXPERIMENTAL_PROCESS_CONTEXT_ENABLED + // https://github.com/open-telemetry/opentelemetry-specification/pull/5341 + boolean enabled = + "true" + .equalsIgnoreCase( + ConfigUtil.getString("otel.experimental.process.context.enabled", "false")); + + if (!enabled) { + return new NoopProcessContextPublisher(); + } + + // Panama publisher uses Linux-specific syscalls and requires JDK 25+. + boolean available = + "Linux".equalsIgnoreCase(System.getProperty("os.name")) + && isJava25Plus(System.getProperty("java.specification.version")); + + if (!available) { + logger.log( + Level.WARNING, + "Process context publication requested, but no suitable implementation available for this environment"); + return new NoopProcessContextPublisher(); + } + + try { + Method create = + Class.forName("io.opentelemetry.sdk.processcontext.PanamaProcessContextPublisher") + .getDeclaredMethod("create"); + create.setAccessible(true); + return (ProcessContextPublisher) create.invoke(null); + } catch (ReflectiveOperationException | LinkageError e) { + logger.log(Level.WARNING, "Failed to init ProcessContextPublisher", e); + return new NoopProcessContextPublisher(); + } + } + + // java.specification.version is a bare integer from Java 9 onwards ("9", "11", "25", ...) and + // "1.N" on older releases, which are never >= 25. Pre-Java 9 strings fail parseInt and we treat + // anything unparseable as unsupported. + private static boolean isJava25Plus(String version) { + try { + return Integer.parseInt(version) >= 25; + } catch (NumberFormatException e) { + return false; + } + } +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/data/ProcessContextData.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/data/ProcessContextData.java new file mode 100644 index 00000000000..8729b3671cc --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/data/ProcessContextData.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext.data; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.concurrent.Immutable; + +/** + * Describes a ProcessContext. + * + * @see + * OTEP-4719 Process Context : Payload + */ +@Immutable +public interface ProcessContextData { + + /** Returns the resource of this process. */ + Resource getResource(); + + /** Additional attributes that are not part of the Resource. */ + Attributes getAttributes(); +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/ProcessContextAutoConfigureListener.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/ProcessContextAutoConfigureListener.java new file mode 100644 index 00000000000..6773dbe9229 --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/ProcessContextAutoConfigureListener.java @@ -0,0 +1,72 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext.internal; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.internal.ExtendedOpenTelemetrySdk; +import io.opentelemetry.sdk.processcontext.ProcessContextPublisher; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import java.io.IOException; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * SPI integration that publishes process context after {@link OpenTelemetrySdk} autoconfiguration. + * + *

      Registered as an {@link AutoConfigurationCustomizerProvider} so autoconfigure discovers it via + * {@link java.util.ServiceLoader}; {@link AutoConfigureListener} is piggybacked on the same load + * (see {@code SpiHelper#maybeAddListener}). + * + *

      If more than one {@link OpenTelemetrySdk} is autoconfigured in the same JVM, each invocation + * of {@link #afterAutoConfigure} will publish on the shared process-wide {@link + * ProcessContextPublisher} singleton. The last caller's resource wins (OTEP-4719 mandates a single + * process context per process). + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +// TODO(jack-berg): should we have other mechanisms to detect / prevent publishing multiple process +// contexts? +public final class ProcessContextAutoConfigureListener + implements AutoConfigurationCustomizerProvider, AutoConfigureListener { + + private static final Logger logger = + Logger.getLogger(ProcessContextAutoConfigureListener.class.getName()); + + @Override + public void customize(AutoConfigurationCustomizer autoConfiguration) { + // No customization needed; implemented only so autoconfigure discovers us via SPI and the + // AutoConfigureListener piggyback can fire. + } + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) { + Objects.requireNonNull(sdk, "sdk"); + + if (!(sdk instanceof ExtendedOpenTelemetrySdk)) { + throw new IllegalStateException( + "Expected ExtendedOpenTelemetrySdk, got " + sdk.getClass().getName()); + } + SdkResourceProvider sdkResourceProvider = + ((ExtendedOpenTelemetrySdk) sdk).getSdkResourceProvider(); + + ProcessContextData processContextData = + SdkProcessContextData.create(sdkResourceProvider.getResource(), Attributes.empty()); + + try { + ProcessContextPublisher.getInstance().publish(processContextData, Clock.getDefault()); + } catch (IOException e) { + logger.log(Level.WARNING, "Failed to publish process context", e); + } + } +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/ProcessContextDeclarativeConfigListener.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/ProcessContextDeclarativeConfigListener.java new file mode 100644 index 00000000000..2d5f39dacab --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/ProcessContextDeclarativeConfigListener.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext.internal; + +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizer; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider; +import io.opentelemetry.sdk.autoconfigure.spi.internal.AutoConfigureListener; + +/** + * Publishes process context after declarative configuration. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public final class ProcessContextDeclarativeConfigListener + implements DeclarativeConfigurationCustomizerProvider, AutoConfigureListener { + + private final ProcessContextAutoConfigureListener listener = + new ProcessContextAutoConfigureListener(); + + @Override + public void customize(DeclarativeConfigurationCustomizer customizer) {} + + @Override + public void afterAutoConfigure(OpenTelemetrySdk sdk) { + listener.afterAutoConfigure(sdk); + } +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/SdkProcessContextData.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/SdkProcessContextData.java new file mode 100644 index 00000000000..a66011b6693 --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/internal/SdkProcessContextData.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Objects; +import javax.annotation.concurrent.Immutable; + +/** + * AutoValue implementation of {@link ProcessContextData}. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +public abstract class SdkProcessContextData implements ProcessContextData { + + /** Returns a new {@link ProcessContextData}. */ + public static ProcessContextData create(Resource resource, Attributes attributes) { + Objects.requireNonNull(resource, "resource"); + Objects.requireNonNull(attributes, "attributes"); + return new AutoValue_SdkProcessContextData(resource, attributes); + } + + SdkProcessContextData() {} +} diff --git a/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/package-info.java b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/package-info.java new file mode 100644 index 00000000000..33670bdd3b9 --- /dev/null +++ b/sdk/processcontext/src/main/java/io/opentelemetry/sdk/processcontext/package-info.java @@ -0,0 +1,14 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * The SDK implementation of Process Context. + * + * @see io.opentelemetry.sdk.processcontext.ProcessContextPublisher + */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.processcontext; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/processcontext/src/main/java25/io/opentelemetry/sdk/processcontext/PanamaProcessContextPublisher.java b/sdk/processcontext/src/main/java25/io/opentelemetry/sdk/processcontext/PanamaProcessContextPublisher.java new file mode 100644 index 00000000000..3e7c76bc1bd --- /dev/null +++ b/sdk/processcontext/src/main/java25/io/opentelemetry/sdk/processcontext/PanamaProcessContextPublisher.java @@ -0,0 +1,362 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import io.opentelemetry.api.internal.GuardedBy; +import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.export.MessageWriter; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.lang.foreign.Arena; +import java.lang.foreign.FunctionDescriptor; +import java.lang.foreign.Linker; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.StructLayout; +import java.lang.foreign.SymbolLookup; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandle; +import java.lang.invoke.VarHandle; +import javax.annotation.Nullable; + +@SuppressWarnings({"restricted", "ThrowSpecificExceptions"}) +final class PanamaProcessContextPublisher implements ProcessContextPublisher { + + private static final String OTEL_NAME = "OTEL_CTX"; + + // System constants + private static final int PROT_READ = 0x1; + private static final int PROT_WRITE = 0x2; + private static final int MAP_PRIVATE = 0x2; + private static final int MAP_ANONYMOUS = 0x20; + // Linux: MADV_DONTFORK is 10 (0x10 is MADV_DONTDUMP, which is unrelated). + private static final int MADV_DONTFORK = 10; + private static final int PR_SET_VMA = 0x53564d41; + private static final int PR_SET_VMA_ANON_NAME = 0; + private static final int MFD_CLOEXEC = 0x1; + private static final int MFD_ALLOW_SEALING = 0x2; + private static final int MFD_NOEXEC_SEAL = 0x8; + private static final int EINVAL = 22; + + private static final long MAPPING_SIZE = ProcessContextHeader.byteSize(); + + private static final Linker LINKER = Linker.nativeLinker(); + private static final SymbolLookup LIBC = LINKER.defaultLookup(); + + private static final Linker.Option ERRNO_LINKER_OPTION; + private static final StructLayout ERRNO_STATE_LAYOUT; + private static final VarHandle ERRNO_HANDLE; + + private static final MethodHandle MMAP; + private static final MethodHandle MUNMAP; + private static final MethodHandle MADVISE; + private static final MethodHandle PRCTL; + private static final MethodHandle MEMFD_CREATE; + private static final MethodHandle FTRUNCATE; + private static final MethodHandle CLOSE; + + static { + try { + + // note that whilst all these libc functions support errno, + // we care about it only on memfd_create + ERRNO_LINKER_OPTION = Linker.Option.captureCallState("errno"); + ERRNO_STATE_LAYOUT = Linker.Option.captureStateLayout(); + ERRNO_HANDLE = ERRNO_STATE_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("errno")); + + MMAP = + LINKER.downcallHandle( + LIBC.find("mmap").orElseThrow(), + // void *mmap(void addr[.length], size_t length, int prot, int flags, int fd, off_t + // offset); + FunctionDescriptor.of( + ValueLayout.ADDRESS, + ValueLayout.ADDRESS, + ValueLayout.JAVA_LONG, + ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT, + ValueLayout.JAVA_LONG)); + MUNMAP = + LINKER.downcallHandle( + LIBC.find("munmap").orElseThrow(), + // int munmap(void addr[.length], size_t length) + FunctionDescriptor.of( + ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_LONG)); + MADVISE = + LINKER.downcallHandle( + LIBC.find("madvise").orElseThrow(), + // int madvise(void addr[.size], size_t size, int advice) + FunctionDescriptor.of( + ValueLayout.JAVA_INT, + ValueLayout.ADDRESS, + ValueLayout.JAVA_LONG, + ValueLayout.JAVA_INT)); + PRCTL = + LINKER.downcallHandle( + LIBC.find("prctl").orElseThrow(), + // int prctl(int op, ...) + FunctionDescriptor.of( + ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT, + ValueLayout.JAVA_INT, + ValueLayout.ADDRESS, + ValueLayout.JAVA_LONG, + ValueLayout.ADDRESS)); + MEMFD_CREATE = + LINKER.downcallHandle( + LIBC.find("memfd_create").orElseThrow(), + // int memfd_create(const char *name, unsigned int flags) + FunctionDescriptor.of( + ValueLayout.JAVA_INT, ValueLayout.ADDRESS, ValueLayout.JAVA_INT), + ERRNO_LINKER_OPTION); + FTRUNCATE = + LINKER.downcallHandle( + LIBC.find("ftruncate").orElseThrow(), + // int ftruncate(int fd, off_t length) + FunctionDescriptor.of( + ValueLayout.JAVA_INT, ValueLayout.JAVA_INT, ValueLayout.JAVA_LONG)); + CLOSE = + LINKER.downcallHandle( + LIBC.find("close").orElseThrow(), + // int close(int fd) + FunctionDescriptor.of(ValueLayout.JAVA_INT, ValueLayout.JAVA_INT)); + } catch (Throwable e) { + throw new RuntimeException("Failed to initialize native method handles", e); + } + } + + private final Object lock = new Object(); + + @GuardedBy("lock") + @Nullable + private MemorySegment mapping = null; + + @GuardedBy("lock") + @Nullable + private ProcessContextHeader header = null; + + @GuardedBy("lock") + @Nullable + private Arena payloadArena = null; + + @GuardedBy("lock") + private long lastTimestampNs = 0L; + + /** Package-private factory used reflectively by {@link ProcessContextPublisherFactory}. */ + static PanamaProcessContextPublisher create() { + return new PanamaProcessContextPublisher(); + } + + private PanamaProcessContextPublisher() {} + + @Override + public void publish(ProcessContextData processContextData, Clock clock) throws IOException { + synchronized (lock) { + if (header == null) { + publishFirstTime(processContextData, clock); + } else { + publishUpdate(processContextData, clock); + } + } + } + + @SuppressWarnings("MustBeClosedChecker") // externally visible memory must exceed method lifetime + private void publishFirstTime(ProcessContextData processContextData, Clock clock) + throws IOException { + MemorySegment newMapping = null; + Arena newPayloadArena = null; + try { + newMapping = initializeMapping(); // spec: publication steps 1-5 + ProcessContextHeader newHeader = new ProcessContextHeader(newMapping); + // spec publication step 6 (equiv updating step 1). Encode payload + newPayloadArena = Arena.ofShared(); + MemorySegment payload = encode(newPayloadArena, processContextData); + long now = clock.nanoTime(); + newHeader.publish(payload, now); // spec: publication steps 7-9 + nameMapping(newMapping); // spec: publication step 10. + + // commit state only after all steps succeed + this.mapping = newMapping; + this.header = newHeader; + this.payloadArena = newPayloadArena; + this.lastTimestampNs = now; + } catch (Throwable t) { + // roll back partial resources so a retry can start clean + if (newPayloadArena != null) { + try { + newPayloadArena.close(); + } catch (Throwable suppressed) { + t.addSuppressed(suppressed); + } + } + if (newMapping != null) { + try { + MUNMAP.invoke(newMapping, MAPPING_SIZE); + } catch (Throwable suppressed) { + t.addSuppressed(suppressed); + } + } + throw new IOException(t); + } + } + + @SuppressWarnings("MustBeClosedChecker") // externally visible memory must exceed method lifetime + private void publishUpdate(ProcessContextData processContextData, Clock clock) + throws IOException { + long now = clock.nanoTime(); + if (now <= lastTimestampNs) { + // No time has elapsed since the previous publication; no meaningful update to report, and + // publishing with an unchanged timestamp would prevent readers from detecting the update + // via the seqlock protocol. + return; + } + Arena prevPayloadArena = payloadArena; + try { + // spec updating step 1. Encode payload + Arena newPayloadArena = Arena.ofShared(); + MemorySegment payload = encode(newPayloadArena, processContextData); + header.update(payload, now); // spec: updating steps 2-6 + payloadArena = newPayloadArena; + lastTimestampNs = now; + prevPayloadArena.close(); // free old payload memory + nameMapping(mapping); // spec: updating step 7. + } catch (Throwable t) { + throw new IOException(t); + } + } + + @Override + public void close() throws IOException { + synchronized (lock) { + if (header == null) { + return; + } + try { + // Signal in-flight readers to abort before freeing memory. + // Per OTEP-4719 reading protocol step 3, a zero timestamp indicates the mapping is + // being mutated and the reader must retry. + header.invalidate(); + MUNMAP.invoke(mapping, MAPPING_SIZE); + payloadArena.close(); + } catch (Throwable t) { + throw new IOException(t); + } finally { + // allow reopening even if teardown partially failed + header = null; + mapping = null; + payloadArena = null; + } + } + } + + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/profiles/4719-process-ctx.md#publication-protocol + private static MemorySegment initializeMapping() throws Throwable { + + MemorySegment mapping; + + // spec: publication step 2a. Allocate new memfd and size it: Create a new memfd using + // memfd_create("OTEL_CTX", MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_NOEXEC_SEAL) + int fd = -1; + try (Arena arena = Arena.ofConfined()) { + MemorySegment nameSegment = arena.allocateFrom(OTEL_NAME); + MemorySegment errnoSegment = arena.allocate(ERRNO_STATE_LAYOUT); + + fd = + (Integer) + MEMFD_CREATE.invoke( + errnoSegment, nameSegment, MFD_CLOEXEC | MFD_ALLOW_SEALING | MFD_NOEXEC_SEAL); + + if (fd < 0 && ((int) ERRNO_HANDLE.get(errnoSegment, 0) == EINVAL)) { + // spec: publication step 2a. MFD_NOEXEC_SEAL is only on 6.3+, fallback for older kernels: + fd = + (Integer) + MEMFD_CREATE.invoke(errnoSegment, nameSegment, MFD_CLOEXEC | MFD_ALLOW_SEALING); + } + } + + if (fd >= 0) { + // spec: publication step 2b. size it with ftruncate. + if ((Integer) FTRUNCATE.invoke(fd, MAPPING_SIZE) == -1) { + CLOSE.invoke(fd); + throw new IOException("Failed to truncate memfd"); + } + + // spec: publication step 3. Allocate a new mmap from the memfd then close the memfd: Setup an + // mmap using mmap(..., PROT_READ | PROT_WRITE, MAP_PRIVATE, memfd, 0). This makes the memfd + // show up in /proc//maps; afterwards the file descriptor can be closed + mapping = + ((MemorySegment) + MMAP.invoke( + MemorySegment.NULL, // addr + MAPPING_SIZE, // length + PROT_READ | PROT_WRITE, // prot + MAP_PRIVATE, // flags + fd, // fd + 0L // offset + )) + .reinterpret(MAPPING_SIZE); + CLOSE.invoke(fd); + } else { + // spec: publication step 4. If memfd is not available (step 2): If system security + // restrictions disallow memfd, fall back to creating a new anonymous mapping using mmap(..., + // PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0) and use that instead + // Note that's we've just assumed the cause of the memfd failure, we're not sure it's a + // security issue. + mapping = + ((MemorySegment) + MMAP.invoke( + MemorySegment.NULL, // addr + MAPPING_SIZE, // length + PROT_READ | PROT_WRITE, // prot + MAP_PRIVATE | MAP_ANONYMOUS, // flags + -1, // fd + 0L // offset + )) + .reinterpret(MAPPING_SIZE); + } + + if (mapping.address() == -1L) { + throw new IOException("Failed to allocate mapping"); + } + + // spec: publication step 5. Prevent fork inheritance: Apply madvise(..., MADV_DONTFORK) to + // prevent child processes from inheriting stale data + int madviseResult = (Integer) MADVISE.invoke(mapping, MAPPING_SIZE, MADV_DONTFORK); + if (madviseResult == -1) { + MUNMAP.invoke(mapping, MAPPING_SIZE); + throw new IOException("Failed to setup MADV_DONTFORK"); + } + return mapping; + } + + private static void nameMapping(MemorySegment target) throws Throwable { + // spec: publication step 10. and updating protocol step 7: Name mapping + // Use prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ...,"OTEL_CTX") to name the mapping. + // This step should be done unconditionally, although naming + // mappings is not always supported by the kernel. + try (Arena arena = Arena.ofConfined()) { + MemorySegment nameSegment = arena.allocateFrom(OTEL_NAME); + PRCTL.invoke(PR_SET_VMA, PR_SET_VMA_ANON_NAME, target, MAPPING_SIZE, nameSegment); + } + } + + private static MemorySegment encode(Arena arena, ProcessContextData processContextData) + throws IOException { + // depressingly clunky, as OutputStream doesn't play nice with MemorySegment. + ProcessContextMarshaler processContextMarshaler = + ProcessContextMarshaler.create(processContextData); + MessageWriter messageWriter = processContextMarshaler.toBinaryMessageWriter(); + ByteArrayOutputStream outputStream = + new ByteArrayOutputStream(messageWriter.getContentLength()); + messageWriter.writeMessage(outputStream); + outputStream.close(); + MemorySegment memorySegment = arena.allocate(messageWriter.getContentLength()); + memorySegment.copyFrom(MemorySegment.ofArray(outputStream.toByteArray())); + return memorySegment; + } +} diff --git a/sdk/processcontext/src/main/java25/io/opentelemetry/sdk/processcontext/ProcessContextHeader.java b/sdk/processcontext/src/main/java25/io/opentelemetry/sdk/processcontext/ProcessContextHeader.java new file mode 100644 index 00000000000..8e1cb615ec3 --- /dev/null +++ b/sdk/processcontext/src/main/java25/io/opentelemetry/sdk/processcontext/ProcessContextHeader.java @@ -0,0 +1,165 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import java.lang.foreign.GroupLayout; +import java.lang.foreign.MemoryLayout; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.nio.charset.StandardCharsets; + +/** + * Provides a typesafe overlay on a region of memory, with layout conforming to the process context + * header specification provided in OTEP-4719. + * + *

      This class is not threadsafe and must be externally synchronized. + * + * @see OTEP + * 4719 + */ +final class ProcessContextHeader { + + private static final byte[] OTEL_CTX_SIGNATURE = "OTEL_CTX".getBytes(StandardCharsets.UTF_8); + private static final int VERSION = 2; + + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/profiles/4719-process-ctx.md#header-structure + private static final GroupLayout HEADER_LAYOUT = + MemoryLayout.structLayout( + MemoryLayout.sequenceLayout(8, ValueLayout.JAVA_BYTE).withName("signature"), + ValueLayout.JAVA_INT.withName("version"), + ValueLayout.JAVA_INT.withName("payload_size"), + ValueLayout.JAVA_LONG.withName("monotonic_published_at_ns"), + ValueLayout.ADDRESS.withName("payload")); + + private static final VarHandle VERSION_HANDLE = + MethodHandles.insertCoordinates( + HEADER_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("version")), 1, 0L); + private static final VarHandle PAYLOAD_SIZE_HANDLE = + MethodHandles.insertCoordinates( + HEADER_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("payload_size")), 1, 0L); + private static final VarHandle TIMESTAMP_HANDLE = + MethodHandles.insertCoordinates( + HEADER_LAYOUT.varHandle( + MemoryLayout.PathElement.groupElement("monotonic_published_at_ns")), + 1, + 0L); + private static final VarHandle PAYLOAD_ADDRESS_HANDLE = + MethodHandles.insertCoordinates( + HEADER_LAYOUT.varHandle(MemoryLayout.PathElement.groupElement("payload")), 1, 0L); + + static long byteSize() { + return HEADER_LAYOUT.byteSize(); + } + + private final MemorySegment memorySegment; + + /** + * Wraps the given region of memory. + * + * @param memorySegment the underlying memory. + */ + ProcessContextHeader(MemorySegment memorySegment) { + this.memorySegment = memorySegment; + } + + // for test integration + MemorySegment getMemorySegment() { + return memorySegment; + } + + /** + * Runs the header-specific steps of the publication protocol. + * + * @param payload the memory holding the serialized payload information. + * @param now the timestamp to publish. + * @see OTEP + * 4719 publication protocol + */ + void publish(MemorySegment payload, long now) { + + // spec: publication step 7. Write header fields: Populate signature, version, payload_size, + // payload but not yet + // monotonic_published_at_ns + MemorySegment.copy( + OTEL_CTX_SIGNATURE, 0, memorySegment.asSlice(0, 8), ValueLayout.JAVA_BYTE, 0, 8); + VERSION_HANDLE.set(memorySegment, VERSION); + publishPayload(payload); + + // spec: publication step 8. Memory barrier: Use language/compiler-specific techniques to ensure + // all previous + // writes complete before proceeding (atomic_thread_fence(memory_order_seq_cst) or equivalent) + VarHandle.fullFence(); + + // spec: publication step 9. Write timestamp: Write monotonic_published_at_ns last. This field + // is used to detect + // that the context is ready for use by the reader. + publishTimestamp(now); + } + + /** + * Runs the header-specific steps of the updating protocol. + * + * @param payload the memory holding the serialized payload information. + * @param now the timestamp to publish. + * @see OTEP + * 4719 updating protocol + */ + void update(MemorySegment payload, long now) { + + // spec: updating step 2. Signal update start: Write 0 to the monotonic_published_at_ns field. + // This signals to + // readers that an update is in progress (readers verify this field is non-zero). + TIMESTAMP_HANDLE.set(memorySegment, 0L); + + // spec: updating step 3. Memory barrier: Ensure the write to monotonic_published_at_ns is + // visible before + // proceeding (atomic_thread_fence(memory_order_seq_cst) or equivalent). + VarHandle.fullFence(); + + // spec: updating step 4. Update payload fields: Update the payload pointer and payload_size + // fields to point + // to the new payload. + publishPayload(payload); + + // spec: updating step 5. Memory barrier: Ensure the payload fields are updated before + // finalizing the + // timestamp (atomic_thread_fence(memory_order_seq_cst) or equivalent). + VarHandle.fullFence(); + + // spec: updating step 6. Signal update complete: Write the new timestamp to + // monotonic_published_at_ns; this + // is an aligned 64-bit write and thus expected to be atomic. + publishTimestamp(now); + } + + /** + * Signal to in-flight readers that the context is no longer valid. Writes 0 to + * monotonic_published_at_ns; per the reader protocol this is treated as "update in progress" and + * triggers a reader retry, giving us a safe window to tear down the mapping. + * + * @see OTEP + * 4719 reading protocol + */ + void invalidate() { + TIMESTAMP_HANDLE.set(memorySegment, 0L); + VarHandle.fullFence(); + } + + private void publishPayload(MemorySegment payload) { + PAYLOAD_SIZE_HANDLE.set(memorySegment, (int) payload.byteSize()); + PAYLOAD_ADDRESS_HANDLE.set(memorySegment, payload); + } + + private void publishTimestamp(long now) { + TIMESTAMP_HANDLE.set(memorySegment, now); + } +} diff --git a/sdk/processcontext/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider b/sdk/processcontext/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider new file mode 100644 index 00000000000..1deabd77b72 --- /dev/null +++ b/sdk/processcontext/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfigurationCustomizerProvider @@ -0,0 +1 @@ +io.opentelemetry.sdk.processcontext.internal.ProcessContextDeclarativeConfigListener diff --git a/sdk/processcontext/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider b/sdk/processcontext/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider new file mode 100644 index 00000000000..59c1b1a1dbd --- /dev/null +++ b/sdk/processcontext/src/main/resources/META-INF/services/io.opentelemetry.sdk.autoconfigure.spi.AutoConfigurationCustomizerProvider @@ -0,0 +1 @@ +io.opentelemetry.sdk.processcontext.internal.ProcessContextAutoConfigureListener diff --git a/sdk/processcontext/src/test/java/io/opentelemetry/sdk/processcontext/ProcessContextMarshalerTest.java b/sdk/processcontext/src/test/java/io/opentelemetry/sdk/processcontext/ProcessContextMarshalerTest.java new file mode 100644 index 00000000000..9dfb5dc6b60 --- /dev/null +++ b/sdk/processcontext/src/test/java/io/opentelemetry/sdk/processcontext/ProcessContextMarshalerTest.java @@ -0,0 +1,92 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.google.protobuf.InvalidProtocolBufferException; +import com.google.protobuf.Message; +import com.google.protobuf.util.JsonFormat; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.exporter.internal.marshal.Marshaler; +import io.opentelemetry.proto.processcontext.v1development.ProcessContext; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import io.opentelemetry.sdk.processcontext.internal.SdkProcessContextData; +import io.opentelemetry.sdk.resources.Resource; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.nio.charset.StandardCharsets; +import org.junit.jupiter.api.Test; + +class ProcessContextMarshalerTest { + + @Test + void compareProcessContextMarshaling() { + ProcessContextData input = + SdkProcessContextData.create(Resource.create(Attributes.empty()), Attributes.empty()); + ProcessContext builderResult = + ProcessContext.newBuilder() + .setResource(io.opentelemetry.proto.resource.v1.Resource.newBuilder().build()) + .build(); + + ProcessContext roundTripResult = + parse(ProcessContext.getDefaultInstance(), ProcessContextMarshaler.create(input)); + assertThat(roundTripResult).isEqualTo(builderResult); + } + + @SuppressWarnings("unchecked") // use of Builder API + private static T parse(T prototype, Marshaler marshaler) { + byte[] serialized = toByteArray(marshaler); + T result; + try { + result = (T) prototype.newBuilderForType().mergeFrom(serialized).build(); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + // Our marshaler should produce the exact same length of serialized output (for example, field + // default values are not outputted), so we check that here. The output itself may have slightly + // different ordering, mostly due to the way we don't output oneof values in field order all the + // tieme. If the lengths are equal and the resulting protos are equal, the marshaling is + // guaranteed to be valid. + assertThat(result.getSerializedSize()).isEqualTo(serialized.length); + + // We don't compare JSON strings due to some differences (particularly serializing enums as + // numbers instead of names). This may improve in the future but what matters is what we produce + // can be parsed. + String json = toJson(marshaler); + Message.Builder builder = prototype.newBuilderForType(); + try { + JsonFormat.parser().merge(json, builder); + } catch (InvalidProtocolBufferException e) { + throw new UncheckedIOException(e); + } + + assertThat(builder.build()).isEqualTo(result); + + return result; + } + + private static byte[] toByteArray(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeBinaryTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return bos.toByteArray(); + } + + private static String toJson(Marshaler marshaler) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + try { + marshaler.writeJsonTo(bos); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + return new String(bos.toByteArray(), StandardCharsets.UTF_8); + } +} diff --git a/sdk/processcontext/src/test/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisherFactoryTest.java b/sdk/processcontext/src/test/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisherFactoryTest.java new file mode 100644 index 00000000000..2e2cdb8beb4 --- /dev/null +++ b/sdk/processcontext/src/test/java/io/opentelemetry/sdk/processcontext/ProcessContextPublisherFactoryTest.java @@ -0,0 +1,21 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; + +class ProcessContextPublisherFactoryTest { + + @Test + void noopByDefault() { + ProcessContextPublisher publisher = ProcessContextPublisher.getInstance(); + + assertThat(publisher).isNotNull(); + assertThat(publisher).isInstanceOf(NoopProcessContextPublisher.class); + } +} diff --git a/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextAutoConfigureListenerTest.java b/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextAutoConfigureListenerTest.java new file mode 100644 index 00000000000..e9b8053b20c --- /dev/null +++ b/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextAutoConfigureListenerTest.java @@ -0,0 +1,82 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.OpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.DeclarativeConfiguration; +import io.opentelemetry.sdk.autoconfigure.declarativeconfig.model.OpenTelemetryConfigurationModel; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; + +@EnabledOnOs(OS.LINUX) +class ProcessContextAutoConfigureListenerTest { + + @AfterEach + void cleanupPublishedMapping() throws IOException { + // The publisher singleton is reused across tests; close it so the OTEL_CTX VMA doesn't leak + // into unrelated tests in the same JVM. + ProcessContextPublisher.getInstance().close(); + } + + @Test + void autoConfigurePublishesContext() throws IOException { + // Depends on otel.experimental.process.context.enabled=true being set at JVM start (see + // build.gradle.kts java25Test suite) so the factory selects the Panama publisher. + assertThat(ProcessContextPublisher.getInstance()) + .isNotInstanceOf(NoopProcessContextPublisher.class); + + assertThat(containsMappingWith("OTEL_CTX")).isFalse(); + + Map props = new HashMap<>(); + props.put("otel.traces.exporter", "none"); + props.put("otel.metrics.exporter", "none"); + props.put("otel.logs.exporter", "none"); + OpenTelemetrySdk sdk = + AutoConfiguredOpenTelemetrySdk.builder() + .addPropertiesSupplier(() -> props) + .build() + .getOpenTelemetrySdk(); + + assertThat(sdk).isNotNull(); + assertThat(containsMappingWith("OTEL_CTX")).isTrue(); + } + + @Test + void declarativeConfigPublishesContext() throws IOException { + assertThat(containsMappingWith("OTEL_CTX")).isFalse(); + + try (OpenTelemetrySdk sdk = + DeclarativeConfiguration.create(new OpenTelemetryConfigurationModel().setFileFormat("1.2")) + .getSdk()) { + assertThat(sdk).isNotNull(); + assertThat(containsMappingWith("OTEL_CTX")).isTrue(); + } + } + + private static boolean containsMappingWith(String value) throws IOException { + String pid = ManagementFactory.getRuntimeMXBean().getName(); + pid = pid.substring(0, pid.indexOf('@')); + List lines = Files.readAllLines(Path.of("/proc/" + pid + "/maps")); + for (String line : lines) { + if (line.contains(value)) { + return true; + } + } + return false; + } +} diff --git a/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextHeaderTest.java b/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextHeaderTest.java new file mode 100644 index 00000000000..7f979a4787c --- /dev/null +++ b/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextHeaderTest.java @@ -0,0 +1,89 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.testing.time.TestClock; +import java.lang.foreign.Arena; +import java.lang.foreign.MemorySegment; +import java.lang.foreign.ValueLayout; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import org.junit.jupiter.api.Test; + +class ProcessContextHeaderTest { + + @Test + void emptyHeader() { + try (Arena arena = Arena.ofConfined()) { + ProcessContextHeader processContextHeader = + new ProcessContextHeader(arena.allocate(ProcessContextHeader.byteSize())); + byte[] content = processContextHeader.getMemorySegment().toArray(ValueLayout.JAVA_BYTE); + assertThat(content).isEqualTo(new byte[32]); + } + } + + @Test + void headerPublicationAndUpdate() { + try (Arena arena = Arena.ofConfined()) { + ProcessContextHeader processContextHeader = + new ProcessContextHeader(arena.allocate(ProcessContextHeader.byteSize())); + + TestClock clock = TestClock.create(); + + MemorySegment payloadA = arena.allocate(20); + processContextHeader.publish(payloadA, clock.now()); // initial publication + validateContent(processContextHeader.getMemorySegment(), payloadA, clock.now()); + + clock.advance(Duration.ofSeconds(1)); + + MemorySegment payloadB = arena.allocate(30); + processContextHeader.update(payloadB, clock.now()); // subsequent update + validateContent(processContextHeader.getMemorySegment(), payloadB, clock.now()); + } + } + + @Test + void invalidateZeroesTimestamp() { + try (Arena arena = Arena.ofConfined()) { + ProcessContextHeader processContextHeader = + new ProcessContextHeader(arena.allocate(ProcessContextHeader.byteSize())); + MemorySegment payload = arena.allocate(20); + TestClock clock = TestClock.create(); + + processContextHeader.publish(payload, clock.now()); + long publishedTimestamp = + processContextHeader.getMemorySegment().get(ValueLayout.JAVA_LONG, 16); + assertThat(publishedTimestamp).isNotZero(); + + processContextHeader.invalidate(); + long invalidatedTimestamp = + processContextHeader.getMemorySegment().get(ValueLayout.JAVA_LONG, 16); + assertThat(invalidatedTimestamp).isZero(); + } + } + + private static void validateContent(MemorySegment published, MemorySegment payload, long now) { + byte[] actualSignature = published.asSlice(0, 8).toArray(ValueLayout.JAVA_BYTE); + assertThat(actualSignature).isEqualTo("OTEL_CTX".getBytes(StandardCharsets.UTF_8)); + + assertThat(ValueLayout.JAVA_INT.order()).isEqualTo(ByteOrder.nativeOrder()); + + int actualVersion = published.get(ValueLayout.JAVA_INT, 8); + assertThat(actualVersion).isEqualTo(2); + + int actualPayloadSize = published.get(ValueLayout.JAVA_INT, 12); + assertThat(actualPayloadSize).isEqualTo(payload.byteSize()); + + long actualTimestamp = published.get(ValueLayout.JAVA_LONG, 16); + assertThat(actualTimestamp).isEqualTo(now); + + long actualAddress = published.get(ValueLayout.ADDRESS, 24).address(); + assertThat(actualAddress).isEqualTo(payload.address()); + } +} diff --git a/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextPublisherTest.java b/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextPublisherTest.java new file mode 100644 index 00000000000..408ed639665 --- /dev/null +++ b/sdk/processcontext/src/test/java25/io/opentelemetry/sdk/processcontext/ProcessContextPublisherTest.java @@ -0,0 +1,76 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.processcontext; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.processcontext.data.ProcessContextData; +import io.opentelemetry.sdk.processcontext.internal.SdkProcessContextData; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.time.TestClock; +import java.io.IOException; +import java.lang.management.ManagementFactory; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; + +@EnabledOnOs(OS.LINUX) +class ProcessContextPublisherTest { + + @Test + void lifecycle() throws IOException { + + assertThat(containsMappingWith("OTEL_CTX")).isFalse(); + + ProcessContextData initial = + SdkProcessContextData.create( + Resource.create(Attributes.of(AttributeKey.stringKey("foo1"), "bar1")), + Attributes.of(AttributeKey.stringKey("foo2"), "bar2")); + ProcessContextData updated = + SdkProcessContextData.create( + Resource.create(Attributes.of(AttributeKey.stringKey("foo1"), "bar1-updated")), + Attributes.of(AttributeKey.stringKey("foo2"), "bar2-updated")); + + ProcessContextPublisher processContextPublisher = PanamaProcessContextPublisher.create(); + TestClock clock = TestClock.create(); + + // first publish: exercises publishFirstTime + processContextPublisher.publish(initial, clock); + assertThat(containsMappingWith("OTEL_CTX")).isTrue(); + + // no-op: clock hasn't advanced, publishUpdate should short-circuit without throwing + processContextPublisher.publish(updated, clock); + assertThat(containsMappingWith("OTEL_CTX")).isTrue(); + + // real update: exercises publishUpdate + clock.advance(Duration.ofSeconds(1)); + processContextPublisher.publish(updated, clock); + assertThat(containsMappingWith("OTEL_CTX")).isTrue(); + + processContextPublisher.close(); + assertThat(containsMappingWith("OTEL_CTX")).isFalse(); + } + + private static boolean containsMappingWith(String value) throws IOException { + + String pid = ManagementFactory.getRuntimeMXBean().getName(); + pid = pid.substring(0, pid.indexOf('@')); // expect format e.g. pidnumber@thing" + + List lines = Files.readAllLines(Path.of("/proc/" + pid + "/maps")); + for (String line : lines) { + if (line.contains(value)) { + return true; + } + } + return false; + } +} diff --git a/sdk/profiles/build.gradle.kts b/sdk/profiles/build.gradle.kts new file mode 100644 index 00000000000..10a704f44f5 --- /dev/null +++ b/sdk/profiles/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { + id("otel.java-conventions") + id("otel.publish-conventions") + + id("otel.animalsniffer-conventions") +} + +description = "OpenTelemetry - Profiles SDK" +otelJava.moduleName.set("sdk.profiles") +otelJava.requireSuppressWarningsExplanation.set(false) + +dependencies { + api(project(":sdk:common")) + + annotationProcessor("com.google.auto.value:auto-value") +} diff --git a/sdk-extensions/metric-incubator/gradle.properties b/sdk/profiles/gradle.properties similarity index 100% rename from sdk-extensions/metric-incubator/gradle.properties rename to sdk/profiles/gradle.properties diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/DictionaryTable.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/DictionaryTable.java new file mode 100644 index 00000000000..3b103f1d3b6 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/DictionaryTable.java @@ -0,0 +1,60 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * This data structure is effectively an indexed Set. + * + *

      It stores each offered element without duplication (like a Set, not a List), but supports + * reference to elements by their position (like a List index). + * + *

      This class is not threadsafe and must be externally synchronized. + * + *

      For a given Object o, after i = putIfAbsent(o), then getTable().get(i).equals(o); + * + * @param the type of elements maintained by this table. The type should implement equals and + * hashCode in a manner consistent with Set/Map key expectations. + */ +public class DictionaryTable { + + // Whilst it's possible to compute either from the other, we keep two views on the data, + // prioritising access efficiency over memory footprint. + private final List table = new ArrayList<>(); + private final Map map = new HashMap<>(); + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + *

      Note that whilst the update semantics of this method are consistent with Map.putIfAbsent, + * the return value is always the index, i.e. reflects the post-update state, not the prior state, + * and therefore does not allow for determining if the method had an effect or not. + * + * @param value an element to store. + * @return the index of the added or existing element. + */ + public Integer putIfAbsent(T value) { + Integer index = map.computeIfAbsent(value, k -> map.size()); + if (map.size() != table.size()) { + table.add(value); + } + return index; + } + + /** + * Provides a view of the Table in List form. + * + * @return an immutable List containing the table entries in index position. + */ + public List getTable() { + return Collections.unmodifiableList(table); + } +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/ProfileExporter.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/ProfileExporter.java new file mode 100644 index 00000000000..efeefab3712 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/ProfileExporter.java @@ -0,0 +1,50 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.profiles.data.ProfileData; +import java.io.Closeable; +import java.util.Collection; +import java.util.concurrent.TimeUnit; + +/** + * An interface that allows different profiling services to export recorded data in their own + * format. + */ +public interface ProfileExporter extends Closeable { + + /** + * Called to export sampled {@code ProfileData}s. Note that export operations can be performed + * simultaneously depending on the type of processor being used. + * + * @param profiles the collection of sampled profiles to be exported. + * @return the result of the export, which is often an asynchronous operation. + */ + CompletableResultCode export(Collection profiles); + + /** + * Exports the collection of sampled {@code ProfileData}s that have not yet been exported. Note + * that export operations can be performed simultaneously depending on the type of span processor + * being used. + * + * @return the result of the flush, which is often an asynchronous operation. + */ + CompletableResultCode flush(); + + /** + * Asynchronously terminate operation of the exporter. + * + * @return a {@link CompletableResultCode} which is completed when shutdown completes. + */ + CompletableResultCode shutdown(); + + /** Closes this {@link ProfileExporter}, releasing any resources. */ + @Override + default void close() { + shutdown().join(10, TimeUnit.SECONDS); + } +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/ProfilesDictionaryCompositor.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/ProfilesDictionaryCompositor.java new file mode 100644 index 00000000000..179e2d93606 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/ProfilesDictionaryCompositor.java @@ -0,0 +1,153 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.sdk.profiles.data.FunctionData; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import io.opentelemetry.sdk.profiles.data.LinkData; +import io.opentelemetry.sdk.profiles.data.LocationData; +import io.opentelemetry.sdk.profiles.data.MappingData; +import io.opentelemetry.sdk.profiles.data.ProfilesDictionaryData; +import io.opentelemetry.sdk.profiles.data.StackData; +import java.util.Collections; + +/** + * This class allows for the assembly of the reference tables which form a ProfilesDictionaryData. + * + *

      It's effectively a builder, though without the fluent API. Instead, mutation methods return + * the index of the offered element, this information being required to construct any element that + * references into the tables. + * + *

      Note this class does not enforce referential integrity, i.e. will accept an element which + * references a non-existing element. + * + *

      This class is not threadsafe and must be externally synchronized. + */ +public class ProfilesDictionaryCompositor { + + // This implementation relies on the *Data interface impls having equals/hashCode that works. + // The provided AutoValue_* ones do, but it's potentially fragile if used externally. + + private final DictionaryTable mappingTable = new DictionaryTable<>(); + private final DictionaryTable locationTable = new DictionaryTable<>(); + private final DictionaryTable functionTable = new DictionaryTable<>(); + private final DictionaryTable linkTable = new DictionaryTable<>(); + private final DictionaryTable stringTable = new DictionaryTable<>(); + private final DictionaryTable attributeTable = new DictionaryTable<>(); + private final DictionaryTable stackTable = new DictionaryTable<>(); + + public ProfilesDictionaryCompositor() { + + // The [0] element of each table should be a 'null' element, such that a 0 value pointer can be + // used to indicate null / not set, in preference to requiring an 'optional' modifier on the + // pointer declarations. The value of this placeholder element is one with all default field + // values, such that it encodes to the minimal number of bytes. + // These values are inlined here, as there is no other point of use. + // They could be public static constants on this class or the corresponding Immutable*Data + // classes if other use cases require them. + + mappingTable.putIfAbsent(MappingData.create(0, 0, 0, 0, Collections.emptyList())); + locationTable.putIfAbsent( + LocationData.create(0, 0, Collections.emptyList(), Collections.emptyList())); + functionTable.putIfAbsent(FunctionData.create(0, 0, 0, 0)); + linkTable.putIfAbsent(LinkData.create(TraceId.getInvalid(), SpanId.getInvalid())); + stringTable.putIfAbsent(""); + attributeTable.putIfAbsent(KeyValueAndUnitData.create(0, Value.of(""), 0)); + stackTable.putIfAbsent(StackData.create(Collections.emptyList())); + } + + /** + * Provides the contents of the dictionary tables as a ProfileDictionaryData. + * + *

      The return value is a view, not a copy. No further elements should be inserted after this is + * called as it would compromise the intended immutability of the result. + * + * @return a ProfileDictionaryData with the contents of the tables. + */ + public ProfilesDictionaryData getProfileDictionaryData() { + return ProfilesDictionaryData.create( + mappingTable.getTable(), + locationTable.getTable(), + functionTable.getTable(), + linkTable.getTable(), + stringTable.getTable(), + attributeTable.getTable(), + stackTable.getTable()); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param mappingData an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(MappingData mappingData) { + return mappingTable.putIfAbsent(mappingData); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param locationData an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(LocationData locationData) { + return locationTable.putIfAbsent(locationData); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param functionData an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(FunctionData functionData) { + return functionTable.putIfAbsent(functionData); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param linkData an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(LinkData linkData) { + return linkTable.putIfAbsent(linkData); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param string an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(String string) { + return stringTable.putIfAbsent(string); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param keyValueAndUnitData an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(KeyValueAndUnitData keyValueAndUnitData) { + return attributeTable.putIfAbsent(keyValueAndUnitData); + } + + /** + * Stores the provided element if an equivalent is not already present, and returns its index. + * + * @param stackData an element to store. + * @return the index of the added or existing element. + */ + public int putIfAbsent(StackData stackData) { + return stackTable.putIfAbsent(stackData); + } +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionBuilder.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionBuilder.java new file mode 100644 index 00000000000..c389a407ff8 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionBuilder.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import io.opentelemetry.sdk.profiles.data.SampleData; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import javax.annotation.Nullable; + +/** + * Assembles a collection of state observations into a collection of SampleData objects i.e. proto + * Sample messages. + * + *

      Observations (samples or traces from a profiler) having the same key can be merged to save + * space without loss of fidelity. On the wire, a single Sample, modelled in the API as a SampleData + * object, comprises shared fields (the key) and per-occurrence fields (the value and timestamp). + * This class maps the raw observations to the aggregations. + * + *

      This class is not threadsafe and must be externally synchronized. + */ +public class SampleCompositionBuilder { + + private final Map map = new HashMap<>(); + + /** + * Constructs a new collection of SampleData instances based on the builder's value. + * + * @return a new {@code List} + */ + public List build() { + List result = new ArrayList<>(map.size()); + for (Map.Entry entry : map.entrySet()) { + SampleCompositionKey key = entry.getKey(); + SampleCompositionValue value = entry.getValue(); + SampleData sampleData = + SampleData.create( + key.getStackIndex(), + key.getAttributeIndices(), + key.getLinkIndex(), + value.getValues(), + value.getTimestamps()); + result.add(sampleData); + } + + return result; + } + + /** + * Adds a new observation to the collection. + * + * @param key the shared ('primary key') fields of the observation. + * @param value the observed data point. + * @param timestamp the time of the observation. + */ + public void add(SampleCompositionKey key, @Nullable Long value, @Nullable Long timestamp) { + SampleCompositionValue v = map.computeIfAbsent(key, key1 -> new SampleCompositionValue()); + v.add(value, timestamp); + } +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionKey.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionKey.java new file mode 100644 index 00000000000..3a5eeddb582 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionKey.java @@ -0,0 +1,64 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import javax.annotation.concurrent.Immutable; + +/** + * A SampleCompositionKey represents the identity portion of an aggregation of observed data. + * Observations (samples) having the same key can be merged to save space without loss of fidelity. + */ +@Immutable +public class SampleCompositionKey { + + // on the wire, a Sample's identity (i.e. 'primary key') is the tuple of + // {stack_index, set_of(attribute_indices), link_index} + // we sort attribute_indices and apply list equality over the result, + // though other techniques for set equality exist. + private final int stackIndex; + private final List attributeIndices; + private final int linkIndex; + + public SampleCompositionKey(int stackIndex, List attributeIndices, int linkIndex) { + this.stackIndex = stackIndex; + List tmp = new ArrayList<>(attributeIndices); + Collections.sort(tmp); + this.attributeIndices = Collections.unmodifiableList(tmp); + this.linkIndex = linkIndex; + } + + public int getStackIndex() { + return stackIndex; + } + + public List getAttributeIndices() { + return attributeIndices; + } + + public int getLinkIndex() { + return linkIndex; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof SampleCompositionKey)) { + return false; + } + SampleCompositionKey that = (SampleCompositionKey) o; + return stackIndex == that.stackIndex + && linkIndex == that.linkIndex + && Objects.equals(attributeIndices, that.attributeIndices); + } + + @Override + public int hashCode() { + return Objects.hash(stackIndex, attributeIndices, linkIndex); + } +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionValue.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionValue.java new file mode 100644 index 00000000000..6b97b2d2003 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/SampleCompositionValue.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; + +/** + * A SampleCompositionValue represents the per-observation parts of an aggregation of observed data. + * Observations (samples) having the same key can be merged by appending their distinct fields to + * the composed value. + * + *

      This class is not threadsafe and must be externally synchronized. + */ +public class SampleCompositionValue { + + private final List values = new ArrayList<>(); + private final List timestamps = new ArrayList<>(); + + public List getValues() { + return Collections.unmodifiableList(values); + } + + public List getTimestamps() { + return Collections.unmodifiableList(timestamps); + } + + /** + * Add a new observation to the collection. + * + *

      Note that, whilst not enforced by the API, it is required that all observations in a + * collection share the same 'shape'. That is, they have either a value without timestamp, a + * timestamp without value, or both timestamp and value. Thus, each array (values, timestamps) in + * the collection is either zero length, or the same length as the other. + * + * @param value the observed data point. + * @param timestamp the time of the observation. + */ + public void add(@Nullable Long value, @Nullable Long timestamp) { + if (value != null) { + values.add(value); + } + if (timestamp != null) { + timestamps.add(timestamp); + } + } +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/FunctionData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/FunctionData.java new file mode 100644 index 00000000000..04c346e8648 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/FunctionData.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import javax.annotation.concurrent.Immutable; + +/** + * Describes a function. + * + * @see "profiles.proto::Function" + */ +@Immutable +public interface FunctionData { + + /** + * Returns a new FunctionData describing the given function characteristics. + * + * @return a new FunctionData describing the given function characteristics. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static FunctionData create( + int nameStringIndex, int systemNameStringIndex, int filenameStringIndex, long startLine) { + return new AutoValue_ImmutableFunctionData( + nameStringIndex, systemNameStringIndex, filenameStringIndex, startLine); + } + + /** Name of the function, in human-readable form if available. Index into string table. */ + int getNameStringIndex(); + + /** + * Name of the function, as identified by the system. For instance, it can be a C++ mangled name. + * Index into string table. + */ + int getSystemNameStringIndex(); + + /** Source file containing the function. Index into string table. */ + int getFilenameStringIndex(); + + /** Line number in source file. */ + long getStartLine(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableFunctionData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableFunctionData.java new file mode 100644 index 00000000000..09185a188fd --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableFunctionData.java @@ -0,0 +1,22 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link FunctionData}, which describes a code function. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableFunctionData implements FunctionData { + + ImmutableFunctionData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableKeyValueAndUnitData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableKeyValueAndUnitData.java new file mode 100644 index 00000000000..e51f6e19645 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableKeyValueAndUnitData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link KeyValueAndUnitData}, which describes a Key Value pair with + * optional unit for the value. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableKeyValueAndUnitData implements KeyValueAndUnitData { + + ImmutableKeyValueAndUnitData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLineData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLineData.java new file mode 100644 index 00000000000..cc2edf2590d --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLineData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link LineData}, which details a specific line in a source code, + * linked to a function. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableLineData implements LineData { + + ImmutableLineData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLinkData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLinkData.java new file mode 100644 index 00000000000..8016d37cb31 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLinkData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link LinkData}, which represents a connection from a profile + * Sample to a trace Span. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableLinkData implements LinkData { + + ImmutableLinkData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLocationData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLocationData.java new file mode 100644 index 00000000000..2b8c66f356c --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableLocationData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link LocationData}, which describes function and line table debug + * information. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableLocationData implements LocationData { + + ImmutableLocationData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableMappingData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableMappingData.java new file mode 100644 index 00000000000..a52bcbb0bc2 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableMappingData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link MappingData}, which describes the mapping of a binary in + * memory. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableMappingData implements MappingData { + + ImmutableMappingData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableProfileData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableProfileData.java new file mode 100644 index 00000000000..383afe17d4a --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableProfileData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link ProfileData}, which represents a complete profile, including + * sample types, samples, mappings to binaries, locations, and additional metadata. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableProfileData implements ProfileData { + + ImmutableProfileData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableProfilesDictionaryData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableProfilesDictionaryData.java new file mode 100644 index 00000000000..da3ccc15166 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableProfilesDictionaryData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link ProfilesDictionaryData}, which represents profiles data + * shared across the entire message being sent. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableProfilesDictionaryData implements ProfilesDictionaryData { + + ImmutableProfilesDictionaryData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableSampleData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableSampleData.java new file mode 100644 index 00000000000..972a3624bac --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableSampleData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link SampleData}, which records values encountered in some program + * context. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableSampleData implements SampleData { + + ImmutableSampleData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableStackData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableStackData.java new file mode 100644 index 00000000000..266c99302ef --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableStackData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link StackData}, which records a list of locations, starting from + * the leaf frame. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableStackData implements StackData { + + ImmutableStackData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableValueTypeData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableValueTypeData.java new file mode 100644 index 00000000000..f4d9547f10e --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ImmutableValueTypeData.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import com.google.auto.value.AutoValue; +import javax.annotation.concurrent.Immutable; + +/** + * Auto value implementation of {@link ValueTypeData}, which describes the type and units of a + * value. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +@Immutable +@AutoValue +abstract class ImmutableValueTypeData implements ValueTypeData { + + ImmutableValueTypeData() {} +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/KeyValueAndUnitData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/KeyValueAndUnitData.java new file mode 100644 index 00000000000..1174c812daa --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/KeyValueAndUnitData.java @@ -0,0 +1,32 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import io.opentelemetry.api.common.Value; + +/** + * Describes a KeyValue pair with optional unit description for the value. Similar to + * io.opentelemetry.api.common.KeyValue, but dictionary-centric. + * + * @see "common.proto::KeyValue" + * @see "profiles.proto::KeyValueAndUnit" + */ +public interface KeyValueAndUnitData { + + /** Returns a {@link KeyValueAndUnitData} for the given parameters. */ + @SuppressWarnings("AutoValueSubclassLeaked") + static KeyValueAndUnitData create(int keyStringIndex, Value value, int unitStringIndex) { + return new AutoValue_ImmutableKeyValueAndUnitData(keyStringIndex, value, unitStringIndex); + } + + /** Index into string table. */ + int getKeyStringIndex(); + + Value getValue(); + + /** Index into string table. 0 indicates implicit (via semconv) or undefined. */ + int getUnitStringIndex(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LineData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LineData.java new file mode 100644 index 00000000000..89198eead34 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LineData.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import javax.annotation.concurrent.Immutable; + +/** + * Details a specific line in a source code, linked to a function. + * + * @see "profiles.proto::Line" + */ +@Immutable +public interface LineData { + + /** + * Returns a new LineData describing the given details a specific line in a source code. + * + * @return a new LineData describing the given details a specific line in a source code. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static LineData create(int functionIndex, long line, long column) { + return new AutoValue_ImmutableLineData(functionIndex, line, column); + } + + /** The index of the corresponding Function for this line. Index into function table. */ + int getFunctionIndex(); + + /** Line number in source code. */ + long getLine(); + + /** Column number in source code. */ + long getColumn(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LinkData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LinkData.java new file mode 100644 index 00000000000..4daf3d0fbf0 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LinkData.java @@ -0,0 +1,36 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import javax.annotation.concurrent.Immutable; + +/** + * A connection from a profile Sample to a trace Span. + * + * @see "profiles.proto::Link" + */ +@Immutable +public interface LinkData { + + /** + * Returns a new LinkData representing an association to the given trace span. + * + * @return a new LinkData representing an association to the given trace span. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static LinkData create(String traceId, String spanId) { + return new AutoValue_ImmutableLinkData(traceId, spanId); + } + + /** + * Returns a unique identifier of a trace that this linked span is part of as 32 character + * lowercase hex String. + */ + String getTraceId(); + + /** Returns a unique identifier for the linked span, as 16 character lowercase hex String. */ + String getSpanId(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LocationData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LocationData.java new file mode 100644 index 00000000000..83e8eb156dd --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/LocationData.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * Describes function and line table debug information. + * + * @see "profiles.proto::Location" + */ +@Immutable +public interface LocationData { + + /** + * Returns a new LocationData describing the given function and line table information. + * + * @return a new LocationData describing the given function and line table information. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static LocationData create( + int mappingIndex, long address, List lines, List attributeIndices) { + return new AutoValue_ImmutableLocationData(mappingIndex, address, lines, attributeIndices); + } + + /** + * The index of the corresponding profile.Mapping for this location. It can be 0 if the mapping is + * unknown or not applicable for this profile type. + */ + int getMappingIndex(); + + /** The instruction address for this location, if available. */ + long getAddress(); + + /** + * Multiple line indicates this location has inlined functions, where the last entry represents + * the caller into which the preceding entries were inlined. + */ + List getLines(); + + /** References to attributes in Profile.attribute_table. */ + List getAttributeIndices(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/MappingData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/MappingData.java new file mode 100644 index 00000000000..363d50fbd90 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/MappingData.java @@ -0,0 +1,52 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * Describes the mapping of a binary in memory. + * + * @see "profiles.proto::Mapping" + */ +@Immutable +public interface MappingData { + + /** + * Returns a new MappingData describing the given mapping of a binary in memory. + * + * @return a new MappingData describing the given mapping of a binary in memory. + */ + @SuppressWarnings({"TooManyParameters", "AutoValueSubclassLeaked"}) + static MappingData create( + long memoryStart, + long memoryLimit, + long fileOffset, + int filenameStringIndex, + List attributeIndices) { + return new AutoValue_ImmutableMappingData( + memoryStart, memoryLimit, fileOffset, filenameStringIndex, attributeIndices); + } + + /** Address at which the binary (or DLL) is loaded into memory. */ + long getMemoryStart(); + + /** The limit of the address range occupied by this mapping. */ + long getMemoryLimit(); + + /** Offset in the binary that corresponds to the first mapped address. */ + long getFileOffset(); + + /** + * The object this entry is loaded from. This can be a filename on disk for the main binary and + * shared libraries, or virtual abstraction like "[vdso]". Index into the string table. + */ + int getFilenameStringIndex(); + + /** References to attributes in Profile.attribute_table. */ + List getAttributeIndices(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ProfileData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ProfileData.java new file mode 100644 index 00000000000..113f0fe0ee3 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ProfileData.java @@ -0,0 +1,136 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import io.opentelemetry.api.impl.Base16EncodingUtils; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.resources.Resource; +import java.nio.ByteBuffer; +import java.util.List; +import javax.annotation.Nullable; +import javax.annotation.concurrent.Immutable; + +/** + * Represents a complete profile, including sample types, samples, mappings to binaries, locations, + * and additional metadata. + * + * @see "profiles.proto::Profile" + */ +@Immutable +public interface ProfileData { + + /** + * Returns a new ProfileData representing the given data. + * + * @return a new ProfileData representing the given data. + */ + @SuppressWarnings({"TooManyParameters", "AutoValueSubclassLeaked"}) + static ProfileData create( + Resource resource, + InstrumentationScopeInfo instrumentationScopeInfo, + ProfilesDictionaryData profilesDictionaryData, + ValueTypeData sampleType, + List samples, + long timeNanos, + long durationNanos, + ValueTypeData periodType, + long period, + String profileId, + int totalAttributeCount, + String originalPayloadFormat, + ByteBuffer originalPayload, + List attributeIndices) { + return new AutoValue_ImmutableProfileData( + resource, + instrumentationScopeInfo, + profilesDictionaryData, + sampleType, + samples, + timeNanos, + durationNanos, + periodType, + period, + profileId, + totalAttributeCount, + originalPayloadFormat, + originalPayload, + attributeIndices); + } + + /** Returns the resource of this profile. */ + Resource getResource(); + + /** Returns the instrumentation scope that generated this profile. */ + InstrumentationScopeInfo getInstrumentationScopeInfo(); + + /** Returns the dictionary data of this profile. */ + ProfilesDictionaryData getProfileDictionaryData(); + + /** A description of the type associated with each Sample.value. */ + ValueTypeData getSampleType(); + + /** The set of samples recorded in this profile. */ + List getSamples(); + + /** Time of collection (UTC) represented as nanoseconds past the epoch. */ + long getTimeNanos(); + + /** Duration of the profile, if a duration makes sense. */ + long getDurationNanos(); + + /** + * The kind of events between sampled occurrences. e.g [ "cpu","cycles" ] or [ "heap","bytes" ] + */ + ValueTypeData getPeriodType(); + + /** The number of events between sampled occurrences. */ + long getPeriod(); + + /** + * Returns a globally unique identifier for a profile, as 32 character lowercase hex String. An ID + * with all zeroes is considered invalid. This field is required. + */ + String getProfileId(); + + /** + * Returns a globally unique identifier for a profile, as a 16 bytes array. An ID with all zeroes + * is considered invalid. This field is required. + */ + default byte[] getProfileIdBytes() { + return Base16EncodingUtils.bytesFromBase16(getProfileId(), 32); + } + + /** + * Returns the total number of attributes that were recorded on this profile. + * + *

      This number may be larger than the number of attributes that are attached to this profile, + * if the total number recorded was greater than the configured maximum value. + */ + int getTotalAttributeCount(); + + /** + * Returns the format of the original payload. Common values are defined in semantic conventions. + * [required if original_payload is present] + */ + @Nullable + String getOriginalPayloadFormat(); + + /** + * Returns the original payload, in a profiler-native format e.g. JFR. Optional. Default behavior + * should be to not include the original payload. If the original payload is in pprof format, it + * should not be included in this field. + */ + ByteBuffer getOriginalPayload(); + + /** + * Returns indexes of profile-wide attributes, referencing to Profile.attribute_table. Attribute + * keys MUST be unique (it is not allowed to have more than one attribute with the same key). + * + * @see + * "https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/common/README.md#attribute" + */ + List getAttributeIndices(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ProfilesDictionaryData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ProfilesDictionaryData.java new file mode 100644 index 00000000000..ec9f9567389 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ProfilesDictionaryData.java @@ -0,0 +1,69 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * Represents profiles data shared across the entire message being sent. + * + * @see "profiles.proto::ProfilesDictionary" + */ +@Immutable +public interface ProfilesDictionaryData { + + /** + * Returns a new ProfilesDictionaryData representing the given data. + * + * @return a new ProfilesDictionaryData representing the given data. + */ + @SuppressWarnings({"TooManyParameters", "AutoValueSubclassLeaked"}) + static ProfilesDictionaryData create( + List mappingTable, + List locationTable, + List functionTable, + List linkTable, + List stringTable, + List attributeTable, + List stackTable) { + return new AutoValue_ImmutableProfilesDictionaryData( + mappingTable, + locationTable, + functionTable, + linkTable, + stringTable, + attributeTable, + stackTable); + } + + /** + * Mapping from address ranges to the image/binary/library mapped into that address range. + * mapping_table[0] must always be the zero value (an empty Mapping), since Location.mapping_index + * 0 means unknown or not applicable. + */ + List getMappingTable(); + + /** Locations referenced by samples via Stack.location_indices. */ + List getLocationTable(); + + /** Functions referenced by locations. */ + List getFunctionTable(); + + /** Lookup table for links. */ + List getLinkTable(); + + /** + * A common table for strings referenced by various messages. string_table[0] must always be "". + */ + List getStringTable(); + + /** Lookup table for attributes. */ + List getAttributeTable(); + + /** Lookup table for stacks. */ + List getStackTable(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/SampleData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/SampleData.java new file mode 100644 index 00000000000..303fd989f0d --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/SampleData.java @@ -0,0 +1,62 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * Each Sample records values encountered in some program context. The program context is typically + * a stack trace, perhaps augmented with auxiliary information like the thread-id, some indicator of + * a higher level request being handled etc. + * + *

      A Sample's identity (i.e. 'primary key') is the tuple of {stack_index, + * set_of(attribute_indices), link_index} + * + *

      The values and timestamps are per-observation data sharing the same context key, i.e. forming + * a series. + * + * @see "profiles.proto::Sample" + */ +@Immutable +public interface SampleData { + + /** + * Returns a new SampleData representing the given program context. + * + * @return a new SampleData representing the given program context. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static SampleData create( + int stackIndex, + List attributeIndices, + int linkIndex, + List values, + List timestamps) { + return new AutoValue_ImmutableSampleData( + stackIndex, attributeIndices, linkIndex, values, timestamps); + } + + /** Reference to stack in Profile.stack_table. */ + int getStackIndex(); + + /** References to attributes in Profile.attribute_table. */ + List getAttributeIndices(); + + /** Reference to link in Profile.link_table. 0 if none. */ + int getLinkIndex(); + + /** + * The type and unit of each value is defined by the corresponding entry in Profile.sample_type. + */ + List getValues(); + + /** + * Timestamps associated with Sample represented as nanoseconds past the epoch. These timestamps + * are expected to fall within the Profile's time range. + */ + List getTimestamps(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/StackData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/StackData.java new file mode 100644 index 00000000000..465084c710d --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/StackData.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import java.util.List; +import javax.annotation.concurrent.Immutable; + +/** + * A Stack represents a list of locations. The first location is the leaf frame. + * + * @see "profiles.proto::Stack" + */ +@Immutable +public interface StackData { + + /** + * Returns a new StackData representing the given list of frames. + * + * @return a new StackData representing the given list of frames. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static StackData create(List locationIndices) { + return new AutoValue_ImmutableStackData(locationIndices); + } + + List getLocationIndices(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ValueTypeData.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ValueTypeData.java new file mode 100644 index 00000000000..61ead44b0e8 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/data/ValueTypeData.java @@ -0,0 +1,33 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles.data; + +import javax.annotation.concurrent.Immutable; + +/** + * ValueType describes the type and units of a value. + * + * @see "profiles.proto::ValueType" + */ +@Immutable +public interface ValueTypeData { + + /** + * Returns a new ValueTypeData describing the given type and unit characteristics. + * + * @return a new ValueTypeData describing the given type and unit characteristics. + */ + @SuppressWarnings("AutoValueSubclassLeaked") + static ValueTypeData create(int typeStringIndex, int unitStringIndex) { + return new AutoValue_ImmutableValueTypeData(typeStringIndex, unitStringIndex); + } + + /** Index into string table. */ + int getTypeStringIndex(); + + /** Index into string table. */ + int getUnitStringIndex(); +} diff --git a/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/package-info.java b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/package-info.java new file mode 100644 index 00000000000..6e53e2e7c37 --- /dev/null +++ b/sdk/profiles/src/main/java/io/opentelemetry/sdk/profiles/package-info.java @@ -0,0 +1,10 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +/** The sdk to support profiles signal. */ +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.profiles; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/DictionaryTableTest.java b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/DictionaryTableTest.java new file mode 100644 index 00000000000..95337956862 --- /dev/null +++ b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/DictionaryTableTest.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class DictionaryTableTest { + + DictionaryTable table; + + @BeforeEach + void setUp() { + table = new DictionaryTable<>(); + } + + @Test + void isInitiallyEmpty() { + assertThat(table.getTable()).isEmpty(); + } + + @Test + void isDeduplicating() { + assertThat(table.putIfAbsent("foo")).isEqualTo(0); + assertThat(table.putIfAbsent("foo")).isEqualTo(0); + assertThat(table.getTable()).size().isEqualTo(1); + } + + @Test + void isSequencing() { + assertThat(table.putIfAbsent("foo")).isEqualTo(0); + assertThat(table.putIfAbsent("bar")).isEqualTo(1); + assertThat(table.getTable()).size().isEqualTo(2); + assertThat(table.getTable().get(0)).isEqualTo("foo"); + assertThat(table.getTable().get(1)).isEqualTo("bar"); + } +} diff --git a/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/KeyValueAndUnitDataTest.java b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/KeyValueAndUnitDataTest.java new file mode 100644 index 00000000000..5d888c6d257 --- /dev/null +++ b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/KeyValueAndUnitDataTest.java @@ -0,0 +1,23 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import org.junit.jupiter.api.Test; + +// Lives outside the data package on purpose: create() must be usable from other packages. +class KeyValueAndUnitDataTest { + + @Test + void createResultIsUsableOutsideDataPackage() { + assertThat(KeyValueAndUnitData.create(1, Value.of("v"), 2).getKeyStringIndex()).isEqualTo(1); + assertThat(KeyValueAndUnitData.create(1, Value.of("v"), 2).getValue()).isEqualTo(Value.of("v")); + assertThat(KeyValueAndUnitData.create(1, Value.of("v"), 2).getUnitStringIndex()).isEqualTo(2); + } +} diff --git a/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/ProfilesDictionaryCompositorTest.java b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/ProfilesDictionaryCompositorTest.java new file mode 100644 index 00000000000..3c92469f58e --- /dev/null +++ b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/ProfilesDictionaryCompositorTest.java @@ -0,0 +1,148 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.Value; +import io.opentelemetry.sdk.profiles.data.FunctionData; +import io.opentelemetry.sdk.profiles.data.KeyValueAndUnitData; +import io.opentelemetry.sdk.profiles.data.LinkData; +import io.opentelemetry.sdk.profiles.data.LocationData; +import io.opentelemetry.sdk.profiles.data.MappingData; +import io.opentelemetry.sdk.profiles.data.ProfilesDictionaryData; +import io.opentelemetry.sdk.profiles.data.StackData; +import java.util.Arrays; +import java.util.Collections; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class ProfilesDictionaryCompositorTest { + + ProfilesDictionaryCompositor compositor; + + @BeforeEach + void setUp() { + compositor = new ProfilesDictionaryCompositor(); + } + + @Test + void hasInitialZeroElements() { + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getMappingTable()).size().isEqualTo(1); + assertThat(data.getLocationTable()).size().isEqualTo(1); + assertThat(data.getFunctionTable()).size().isEqualTo(1); + assertThat(data.getLinkTable()).size().isEqualTo(1); + assertThat(data.getStringTable()).size().isEqualTo(1); + assertThat(data.getAttributeTable()).size().isEqualTo(1); + assertThat(data.getStackTable()).size().isEqualTo(1); + } + + @Test + void handlesMappings() { + MappingData a = MappingData.create(1, 2, 3, 4, Collections.emptyList()); + MappingData b = MappingData.create(2, 3, 4, 5, Collections.emptyList()); + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getMappingTable()).size().isEqualTo(3); + assertThat(data.getMappingTable().get(1)).isEqualTo(a); + assertThat(data.getMappingTable().get(2)).isEqualTo(b); + } + + @Test + void handlesLocations() { + LocationData a = LocationData.create(1, 2, Collections.emptyList(), Collections.emptyList()); + LocationData b = LocationData.create(3, 4, Collections.emptyList(), Collections.emptyList()); + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getLocationTable()).size().isEqualTo(3); + assertThat(data.getLocationTable().get(1)).isEqualTo(a); + assertThat(data.getLocationTable().get(2)).isEqualTo(b); + } + + @Test + void handlesFunctions() { + FunctionData a = FunctionData.create(1, 2, 3, 4); + FunctionData b = FunctionData.create(5, 6, 7, 8); + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getFunctionTable()).size().isEqualTo(3); + assertThat(data.getFunctionTable().get(1)).isEqualTo(a); + assertThat(data.getFunctionTable().get(2)).isEqualTo(b); + } + + @Test + void handlesLinks() { + LinkData a = LinkData.create("a1", "a2"); + LinkData b = LinkData.create("b1", "b2"); + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getLinkTable()).size().isEqualTo(3); + assertThat(data.getLinkTable().get(1)).isEqualTo(a); + assertThat(data.getLinkTable().get(2)).isEqualTo(b); + } + + @Test + void handlesStrings() { + String a = "foo"; + String b = "bar"; + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getStringTable()).size().isEqualTo(3); + assertThat(data.getStringTable().get(1)).isEqualTo(a); + assertThat(data.getStringTable().get(2)).isEqualTo(b); + } + + @Test + void handlesAttributes() { + KeyValueAndUnitData a = KeyValueAndUnitData.create(1, Value.of("a"), 2); + KeyValueAndUnitData b = KeyValueAndUnitData.create(3, Value.of("b"), 4); + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getAttributeTable()).size().isEqualTo(3); + assertThat(data.getAttributeTable().get(1)).isEqualTo(a); + assertThat(data.getAttributeTable().get(2)).isEqualTo(b); + } + + @Test + void handlesStacks() { + StackData a = StackData.create(Arrays.asList(1, 2)); + StackData b = StackData.create(Arrays.asList(3, 4)); + + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(a)).isEqualTo(1); + assertThat(compositor.putIfAbsent(b)).isEqualTo(2); + + ProfilesDictionaryData data = compositor.getProfileDictionaryData(); + assertThat(data.getStackTable()).size().isEqualTo(3); + assertThat(data.getStackTable().get(1)).isEqualTo(a); + assertThat(data.getStackTable().get(2)).isEqualTo(b); + } +} diff --git a/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/SampleCompositionTest.java b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/SampleCompositionTest.java new file mode 100644 index 00000000000..48fabfe3bf7 --- /dev/null +++ b/sdk/profiles/src/test/java/io/opentelemetry/sdk/profiles/SampleCompositionTest.java @@ -0,0 +1,91 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.profiles; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.profiles.data.SampleData; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +class SampleCompositionTest { + + SampleCompositionBuilder sampleCompositionBuilder; + + @BeforeEach + void setUp() { + sampleCompositionBuilder = new SampleCompositionBuilder(); + } + + @Test + public void empty() { + assertThat(sampleCompositionBuilder.build()).isEmpty(); + } + + @Test + public void keyEquality() { + SampleCompositionKey a; + SampleCompositionKey b; + + a = new SampleCompositionKey(1, listOf(2, 3), 4); + b = new SampleCompositionKey(1, listOf(2, 3), 4); + assertThat(a).isEqualTo(b); + assertThat(a.hashCode()).isEqualTo(b.hashCode()); + + b = new SampleCompositionKey(1, listOf(3, 2), 4); + assertThat(a).isEqualTo(b); + assertThat(a.hashCode()).isEqualTo(b.hashCode()); + + b = new SampleCompositionKey(2, listOf(2, 3), 4); + assertThat(a).isNotEqualTo(b); + } + + @Test + public void valueElidesNulls() { + SampleCompositionValue v = new SampleCompositionValue(); + v.add(1L, 1L); + v.add(null, 2L); + v.add(2L, null); + assertThat(v.getValues().size()).isEqualTo(2); + assertThat(v.getTimestamps().size()).isEqualTo(2); + } + + @Test + public void isAggregatingSameKey() { + SampleCompositionKey sampleCompositionKey = + new SampleCompositionKey(0, Collections.emptyList(), 0); + sampleCompositionBuilder.add(sampleCompositionKey, 1L, 1L); + sampleCompositionBuilder.add(sampleCompositionKey, 2L, 2L); + + List sampleDataList = sampleCompositionBuilder.build(); + assertThat(sampleDataList).size().isEqualTo(1); + assertThat(sampleDataList.get(0).getTimestamps().size()).isEqualTo(2); + assertThat(sampleDataList.get(0).getValues().size()).isEqualTo(2); + } + + @Test + public void isNotAggregatingDifferentKey() { + SampleCompositionKey keyA = new SampleCompositionKey(1, Collections.emptyList(), 0); + sampleCompositionBuilder.add(keyA, 1L, 1L); + SampleCompositionKey keyB = new SampleCompositionKey(2, Collections.emptyList(), 0); + sampleCompositionBuilder.add(keyB, 2L, 2L); + + List sampleDataList = sampleCompositionBuilder.build(); + assertThat(sampleDataList).size().isEqualTo(2); + assertThat(sampleDataList.get(0).getTimestamps().size()).isEqualTo(1); + assertThat(sampleDataList.get(1).getTimestamps().size()).isEqualTo(1); + } + + private static List listOf(T a, T b) { + ArrayList list = new ArrayList<>(); + list.add(a); + list.add(b); + return Collections.unmodifiableList(list); + } +} diff --git a/sdk/testing/README.md b/sdk/testing/README.md deleted file mode 100644 index f57880691e8..00000000000 --- a/sdk/testing/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry SDK Testing - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-testing.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-testing diff --git a/sdk/testing/build.gradle.kts b/sdk/testing/build.gradle.kts index a61888b9cbb..33ee59ef7e2 100644 --- a/sdk/testing/build.gradle.kts +++ b/sdk/testing/build.gradle.kts @@ -5,10 +5,15 @@ plugins { description = "OpenTelemetry SDK Testing utilities" otelJava.moduleName.set("io.opentelemetry.sdk.testing") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiServiceLoaderProvides.set(listOf( + "io.opentelemetry.context.ContextStorageProvider", +)) dependencies { api(project(":api:all")) api(project(":sdk:all")) + compileOnly(project(":api:incubator")) compileOnly("org.assertj:assertj-core") compileOnly("junit:junit") @@ -16,8 +21,18 @@ dependencies { annotationProcessor("com.google.auto.value:auto-value") - implementation(project(":semconv")) + testImplementation(project(":api:incubator")) testImplementation("junit:junit") testImplementation("org.junit.vintage:junit-vintage-engine") } + +testing { + suites { + register("testIncubating") { + dependencies { + implementation(project(":api:incubator")) + } + } + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointAssert.java index 013a971fd3c..41da09a10e5 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AbstractPointAssert.java @@ -14,11 +14,16 @@ import java.util.Arrays; import java.util.Map; import java.util.Set; +import java.util.function.Consumer; import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Assertions; -/** Assertions for an exported {@link PointData}. */ +/** + * Assertions for an exported {@link PointData}. + * + * @since 1.14.0 + */ public abstract class AbstractPointAssert< PointAssertT extends AbstractPointAssert, PointT extends PointData> extends AbstractAssert { @@ -89,8 +94,8 @@ public final PointAssertT hasAttributes(Map.Entry, ?>. } /** - * Asserts the point has attributes matching all {@code assertions} and no more. Assertions can be - * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * Asserts the point has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, * OpenTelemetryAssertions.LongAssertConsumer)}. */ public final PointAssertT hasAttributesSatisfying(AttributeAssertion... assertions) { @@ -98,12 +103,47 @@ public final PointAssertT hasAttributesSatisfying(AttributeAssertion... assertio } /** - * Asserts the point has attributes matching all {@code assertions} and no more. Assertions can be - * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * Asserts the point has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, * OpenTelemetryAssertions.LongAssertConsumer)}. */ public final PointAssertT hasAttributesSatisfying(Iterable assertions) { AssertUtil.assertAttributes(actual.getAttributes(), assertions); return myself; } + + /** + * Asserts the point has attributes satisfying the given condition. + * + * @since 1.33.0 + */ + public final PointAssertT hasAttributesSatisfying(Consumer attributes) { + isNotNull(); + assertThat(actual.getAttributes()).as("attributes").satisfies(attributes); + return myself; + } + + /** + * Asserts the point has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public final PointAssertT hasAttributesSatisfyingExactly(AttributeAssertion... assertions) { + return hasAttributesSatisfyingExactly(Arrays.asList(assertions)); + } + + /** + * Asserts the point has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public final PointAssertT hasAttributesSatisfyingExactly( + Iterable assertions) { + AssertUtil.assertAttributesExactly(actual.getAttributes(), assertions); + return myself; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AssertUtil.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AssertUtil.java index b605cdabcb5..5ff3d40f14b 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AssertUtil.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AssertUtil.java @@ -34,6 +34,32 @@ static > Consumer[] toConsumers( } static void assertAttributes(Attributes actual, Iterable assertions) { + assertAttributes(actual, assertions, "attribute keys"); + } + + static void assertAttributes( + Attributes actual, Iterable assertions, String name) { + Set> actualKeys = actual.asMap().keySet(); + Set> checkedKeys = new HashSet<>(); + for (AttributeAssertion attributeAssertion : assertions) { + AttributeKey key = attributeAssertion.getKey(); + Object value = actual.get(key); + if (value != null) { + checkedKeys.add(key); + } + AbstractAssert assertion = AttributeAssertion.attributeValueAssertion(key, value); + attributeAssertion.getAssertion().accept(assertion); + } + + assertThat(actualKeys).as(name).containsAll(checkedKeys); + } + + static void assertAttributesExactly(Attributes actual, Iterable assertions) { + assertAttributesExactly(actual, assertions, "attribute keys"); + } + + static void assertAttributesExactly( + Attributes actual, Iterable assertions, String name) { Set> actualKeys = actual.asMap().keySet(); Set> checkedKeys = new HashSet<>(); for (AttributeAssertion attributeAssertion : assertions) { @@ -46,7 +72,7 @@ static void assertAttributes(Attributes actual, Iterable ass attributeAssertion.getAssertion().accept(assertion); } - assertThat(actualKeys).as("attribute keys").containsExactlyInAnyOrderElementsOf(checkedKeys); + assertThat(actualKeys).as(name).containsExactlyInAnyOrderElementsOf(checkedKeys); } /** diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertion.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertion.java index e72e81a16ed..bcd55090f25 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertion.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertion.java @@ -9,6 +9,7 @@ import com.google.auto.value.AutoValue; import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Value; import java.util.List; import java.util.function.Consumer; import javax.annotation.Nullable; @@ -37,6 +38,13 @@ static AttributeAssertion create( // suppressing here. @SuppressWarnings("NullAway") static AbstractAssert attributeValueAssertion(AttributeKey key, @Nullable Object value) { + AbstractAssert, ?> abstractAssert = makeAssertion(key, value); + String description = "%s attribute '%s'"; + return abstractAssert.as(description, key.getType(), key.getKey()); + } + + private static AbstractAssert, ?> makeAssertion( + AttributeKey key, @Nullable Object value) { switch (key.getType()) { case STRING: return assertThat((String) value); @@ -51,6 +59,8 @@ static AttributeAssertion create( case LONG_ARRAY: case DOUBLE_ARRAY: return assertThat((List) value); + case VALUE: + return assertThat((Value) value); } throw new IllegalArgumentException("Unknown type for key " + key); } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributesAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributesAssert.java index 00a4f194180..2abe315f017 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributesAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/AttributesAssert.java @@ -9,6 +9,7 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import java.util.Arrays; import java.util.Collections; import java.util.List; @@ -19,6 +20,7 @@ import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; import org.assertj.core.error.ShouldContainKeys; +import org.assertj.core.error.ShouldNotContainKeys; /** Assertions for {@link Attributes}. */ public final class AttributesAssert extends AbstractAssert { @@ -89,6 +91,15 @@ public AttributesAssert containsEntry(String key, Double... value) { return containsEntry(AttributeKey.doubleArrayKey(key), Arrays.asList(value)); } + /** + * Asserts the attributes have the given key and {@link Value} value. + * + * @since 1.59.0 + */ + public AttributesAssert containsEntry(String key, Value value) { + return containsEntry(AttributeKey.valueKey(key), value); + } + /** Asserts the attributes have the given key and string array value. */ public AttributesAssert containsEntryWithStringValuesOf(String key, Iterable value) { isNotNull(); @@ -183,6 +194,37 @@ public AttributesAssert containsKey(String key) { return this; } + /** + * Asserts the attributes do not contain the given key. + * + * @since 1.18.0 + */ + public AttributesAssert doesNotContainKey(AttributeKey key) { + if (actual.get(key) != null) { + failWithMessage( + ShouldNotContainKeys.shouldNotContainKeys(actual, Collections.singleton(key)) + .create(info.description(), info.representation())); + } + return this; + } + + /** + * Asserts the attributes do not contain the given key. + * + * @since 1.18.0 + */ + public AttributesAssert doesNotContainKey(String key) { + boolean containsKey = + actual.asMap().keySet().stream() + .anyMatch(attributeKey -> attributeKey.getKey().equals(key)); + if (containsKey) { + failWithMessage( + ShouldNotContainKeys.shouldNotContainKeys(actual, Collections.singleton(key)) + .create(info.description(), info.representation())); + } + return this; + } + /** Asserts the attributes have no entries. */ public AttributesAssert isEmpty() { return isEqualTo(Attributes.empty()); diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleExemplarAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleExemplarAssert.java index 579299a2855..b40fc005c63 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleExemplarAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleExemplarAssert.java @@ -17,7 +17,11 @@ import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; -/** Assertions for an exported {@link DoubleExemplarData}. */ +/** + * Assertions for an exported {@link DoubleExemplarData}. + * + * @since 1.14.0 + */ public final class DoubleExemplarAssert extends AbstractAssert { DoubleExemplarAssert(@Nullable DoubleExemplarData actual) { @@ -93,19 +97,48 @@ public final DoubleExemplarAssert hasFilteredAttributes( return hasFilteredAttributes(attributes); } - /** Asserts the exemplar has filtered attributes matching all {@code assertions} and no more. */ + /** + * Asserts the exemplar has filtered attributes matching all {@code assertions}. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ public DoubleExemplarAssert hasFilteredAttributesSatisfying(AttributeAssertion... assertions) { return hasFilteredAttributesSatisfying(Arrays.asList(assertions)); } + /** + * Asserts the exemplar has filtered attributes matching all {@code assertions}. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public DoubleExemplarAssert hasFilteredAttributesSatisfying( + Iterable assertions) { + AssertUtil.assertAttributes(actual.getFilteredAttributes(), assertions); + return myself; + } + /** * Asserts the exemplar has filtered attributes matching all {@code assertions} and no more. * Assertions can be created using methods like {@link * OpenTelemetryAssertions#satisfies(AttributeKey, OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 */ - public DoubleExemplarAssert hasFilteredAttributesSatisfying( + public DoubleExemplarAssert hasFilteredAttributesSatisfyingExactly( + AttributeAssertion... assertions) { + return hasFilteredAttributesSatisfyingExactly(Arrays.asList(assertions)); + } + + /** + * Asserts the exemplar has filtered attributes matching all {@code assertions} and no more. + * Assertions can be created using methods like {@link + * OpenTelemetryAssertions#satisfies(AttributeKey, OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public DoubleExemplarAssert hasFilteredAttributesSatisfyingExactly( Iterable assertions) { - AssertUtil.assertAttributes(actual.getFilteredAttributes(), assertions); + AssertUtil.assertAttributesExactly(actual.getFilteredAttributes(), assertions); return myself; } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleGaugeAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleGaugeAssert.java index b8190e38dfd..99c81429861 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleGaugeAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleGaugeAssert.java @@ -14,7 +14,11 @@ import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; -/** Assertions for an exported double {@link GaugeData}. */ +/** + * Assertions for an exported double {@link GaugeData}. + * + * @since 1.14.0 + */ public final class DoubleGaugeAssert extends AbstractAssert> { @@ -41,4 +45,35 @@ public DoubleGaugeAssert hasPointsSatisfying( .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, DoublePointAssert::new)); return this; } + + /** + * Asserts that for each given assertion, at least one point in the gauge satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final DoubleGaugeAssert containsPointsSatisfying( + Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the gauge satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + public DoubleGaugeAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new DoublePointAssert(point))); + } + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoublePointAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoublePointAssert.java index 6cf6e6015b3..9513b23f1f1 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoublePointAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoublePointAssert.java @@ -12,9 +12,14 @@ import java.util.Arrays; import java.util.function.Consumer; import javax.annotation.Nullable; +import org.assertj.core.api.AbstractDoubleAssert; import org.assertj.core.api.Assertions; -/** Test assertions for {@link DoublePointData}. */ +/** + * Test assertions for {@link DoublePointData}. + * + * @since 1.14.0 + */ public final class DoublePointAssert extends AbstractPointAssert { @@ -29,6 +34,17 @@ public DoublePointAssert hasValue(double expected) { return this; } + /** + * Asserts the point's value satisfies the given assertion. + * + * @since 1.62.0 + */ + public DoublePointAssert hasValueSatisfying(Consumer> valueAssertion) { + isNotNull(); + valueAssertion.accept(Assertions.assertThat(actual.getValue()).as("value")); + return this; + } + /** Asserts the point has the specified exemplars, in any order. */ public DoublePointAssert hasExemplars(DoubleExemplarData... exemplars) { isNotNull(); diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleSumAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleSumAssert.java index 455f49521a1..06aa6a23092 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleSumAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/DoubleSumAssert.java @@ -14,7 +14,11 @@ import java.util.function.Consumer; import org.assertj.core.api.AbstractAssert; -/** Test assertions for double {@link SumData}. */ +/** + * Test assertions for double {@link SumData}. + * + * @since 1.14.0 + */ public final class DoubleSumAssert extends AbstractAssert> { DoubleSumAssert(SumData actual) { @@ -84,4 +88,34 @@ public DoubleSumAssert hasPointsSatisfying( .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, DoublePointAssert::new)); return this; } + + /** + * Asserts that for each given assertion, at least one point in the sum satisfies it. Extra points + * that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final DoubleSumAssert containsPointsSatisfying(Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the sum satisfies it. Extra points + * that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + public DoubleSumAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new DoublePointAssert(point))); + } + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/EventDataAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/EventDataAssert.java index 9dd24e8c59a..f0f280dd9a3 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/EventDataAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/EventDataAssert.java @@ -7,9 +7,11 @@ import static org.assertj.core.api.Assertions.assertThat; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.trace.data.EventData; import java.time.Instant; +import java.util.Arrays; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import javax.annotation.Nullable; @@ -82,4 +84,50 @@ public EventDataAssert hasAttributesSatisfying(Consumer attributes) assertThat(actual.getAttributes()).as("attributes").satisfies(attributes); return this; } + + /** + * Asserts the event has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public EventDataAssert hasAttributesSatisfying(AttributeAssertion... assertions) { + return hasAttributesSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts the event has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public EventDataAssert hasAttributesSatisfying(Iterable assertions) { + AssertUtil.assertAttributes(actual.getAttributes(), assertions); + return this; + } + + /** + * Asserts the event has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public EventDataAssert hasAttributesSatisfyingExactly(AttributeAssertion... assertions) { + return hasAttributesSatisfyingExactly(Arrays.asList(assertions)); + } + + /** + * Asserts the event has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public EventDataAssert hasAttributesSatisfyingExactly(Iterable assertions) { + AssertUtil.assertAttributesExactly(actual.getAttributes(), assertions); + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramAssert.java new file mode 100644 index 00000000000..eeff8c0485e --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramAssert.java @@ -0,0 +1,107 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.metrics.data.AggregationTemporality; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; +import java.util.Arrays; +import java.util.function.Consumer; +import org.assertj.core.api.AbstractAssert; + +/** + * Test assertions for {@link ExponentialHistogramData}. + * + * @since 1.23.0 + */ +public final class ExponentialHistogramAssert + extends AbstractAssert { + + ExponentialHistogramAssert(ExponentialHistogramData actual) { + super(actual, ExponentialHistogramAssert.class); + } + + /** Ensures that {@code aggregation_temporality} field is {@code CUMULATIVE}. */ + public ExponentialHistogramAssert isCumulative() { + isNotNull(); + if (actual.getAggregationTemporality() != AggregationTemporality.CUMULATIVE) { + failWithActualExpectedAndMessage( + actual, + "aggregationTemporality: CUMULATIVE", + "Expected Histogram to have cumulative aggregation but found <%s>", + actual.getAggregationTemporality()); + } + return this; + } + + /** Ensures that {@code aggregation_temporality} field is {@code DELTA}. */ + public ExponentialHistogramAssert isDelta() { + isNotNull(); + if (actual.getAggregationTemporality() != AggregationTemporality.DELTA) { + failWithActualExpectedAndMessage( + actual, + "aggregationTemporality: DELTA", + "Expected Histogram to have delta aggregation but found <%s>", + actual.getAggregationTemporality()); + } + return this; + } + + /** + * Asserts the exponential histogram has points matching all of the given assertions and no more, + * in any order. + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final ExponentialHistogramAssert hasPointsSatisfying( + Consumer... assertions) { + return hasPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts the exponential histogram has points matching all of the given assertions and no more, + * in any order. + */ + public ExponentialHistogramAssert hasPointsSatisfying( + Iterable> assertions) { + assertThat(actual.getPoints()) + .satisfiesExactlyInAnyOrder( + AssertUtil.toConsumers(assertions, ExponentialHistogramPointAssert::new)); + return this; + } + + /** + * Asserts that for each given assertion, at least one point in the exponential histogram + * satisfies it. Extra points that match none of the assertions are allowed, and a single point + * may satisfy multiple assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final ExponentialHistogramAssert containsPointsSatisfying( + Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the exponential histogram + * satisfies it. Extra points that match none of the assertions are allowed, and a single point + * may satisfy multiple assertions. + * + * @since 1.62.0 + */ + public ExponentialHistogramAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new ExponentialHistogramPointAssert(point))); + } + return this; + } +} diff --git a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramBucketsAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramBucketsAssert.java similarity index 82% rename from sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramBucketsAssert.java rename to sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramBucketsAssert.java index 28b0e345499..78f7fd14d01 100644 --- a/sdk/metrics-testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramBucketsAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramBucketsAssert.java @@ -5,16 +5,20 @@ package io.opentelemetry.sdk.testing.assertj; -import io.opentelemetry.sdk.metrics.internal.data.exponentialhistogram.ExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramBuckets; import java.util.List; import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Assertions; -/** Test assertions for {@link ExponentialHistogramBuckets}. */ -public class ExponentialHistogramBucketsAssert +/** + * Test assertions for {@link ExponentialHistogramBuckets}. + * + * @since 1.23.0 + */ +public final class ExponentialHistogramBucketsAssert extends AbstractAssert { - protected ExponentialHistogramBucketsAssert(ExponentialHistogramBuckets actual) { + ExponentialHistogramBucketsAssert(ExponentialHistogramBuckets actual) { super(actual, ExponentialHistogramBucketsAssert.class); } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramPointAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramPointAssert.java new file mode 100644 index 00000000000..bae8084a7fe --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ExponentialHistogramPointAssert.java @@ -0,0 +1,110 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; +import java.util.Arrays; +import java.util.function.Consumer; +import org.assertj.core.api.Assertions; + +/** + * Test assertions for {@link ExponentialHistogramPointData}. + * + * @since 1.23.0 + */ +public final class ExponentialHistogramPointAssert + extends AbstractPointAssert { + ExponentialHistogramPointAssert(ExponentialHistogramPointData actual) { + super(actual, ExponentialHistogramPointAssert.class); + } + + /** Ensures the {@code sum} field matches the expected value. */ + public ExponentialHistogramPointAssert hasSum(double expected) { + isNotNull(); + Assertions.assertThat(actual.getSum()).as("sum").isEqualTo(expected); + return this; + } + + /** Ensures the {@code min} field matches the expected value. */ + public ExponentialHistogramPointAssert hasMin(double expected) { + isNotNull(); + Assertions.assertThat(actual.getMin()).as("min").isEqualTo(expected); + return this; + } + + /** Ensures the {@code min} field matches the expected value. */ + public ExponentialHistogramPointAssert hasMax(double expected) { + isNotNull(); + Assertions.assertThat(actual.getMax()).as("max").isEqualTo(expected); + return this; + } + + /** Ensures the {@code count} field matches the expected value. */ + public ExponentialHistogramPointAssert hasCount(long expected) { + isNotNull(); + Assertions.assertThat(actual.getCount()).as("count").isEqualTo(expected); + return this; + } + + /** Ensures the {@code scale} field matches the expected value. */ + public ExponentialHistogramPointAssert hasScale(int expected) { + isNotNull(); + Assertions.assertThat(actual.getScale()).as("scale").isEqualTo(expected); + return this; + } + + /** Ensures the {@code zeroCount} field matches the expected value. */ + public ExponentialHistogramPointAssert hasZeroCount(long expected) { + isNotNull(); + Assertions.assertThat(actual.getZeroCount()).as("zeroCount").isEqualTo(expected); + return this; + } + + /** Ensures the {@code positiveBuckets} field satisfies the provided assertion. */ + public ExponentialHistogramPointAssert hasPositiveBucketsSatisfying( + Consumer assertion) { + isNotNull(); + assertion.accept(new ExponentialHistogramBucketsAssert(actual.getPositiveBuckets())); + return this; + } + + /** Ensures the {@code negativeBuckets} field satisfies the provided assertion. */ + public ExponentialHistogramPointAssert hasNegativeBucketsSatisfying( + Consumer assertion) { + isNotNull(); + assertion.accept(new ExponentialHistogramBucketsAssert(actual.getNegativeBuckets())); + return this; + } + + /** Asserts the point has the specified exemplars, in any order. */ + public ExponentialHistogramPointAssert hasExemplars(DoubleExemplarData... exemplars) { + isNotNull(); + Assertions.assertThat(actual.getExemplars()) + .as("exemplars") + .containsExactlyInAnyOrder(exemplars); + return myself; + } + + /** Asserts the point has exemplars matching all of the assertions, in any order. */ + @SafeVarargs + @SuppressWarnings("varargs") + public final ExponentialHistogramPointAssert hasExemplarsSatisfying( + Consumer... assertions) { + return hasExemplarsSatisfying(Arrays.asList(assertions)); + } + + /** Asserts the point has exemplars matching all of the assertions, in any order. */ + public ExponentialHistogramPointAssert hasExemplarsSatisfying( + Iterable> assertions) { + isNotNull(); + assertThat(actual.getExemplars()) + .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, DoubleExemplarAssert::new)); + return myself; + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramAssert.java index 1204db03b5d..ac73640bcdc 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramAssert.java @@ -13,7 +13,11 @@ import java.util.function.Consumer; import org.assertj.core.api.AbstractAssert; -/** Test assertions for {@link HistogramData}. */ +/** + * Test assertions for {@link HistogramData}. + * + * @since 1.14.0 + */ public final class HistogramAssert extends AbstractAssert { HistogramAssert(HistogramData actual) { @@ -28,7 +32,6 @@ public HistogramAssert isCumulative() { actual, "aggregationTemporality: CUMULATIVE", "Expected Histogram to have cumulative aggregation but found <%s>", - AggregationTemporality.CUMULATIVE, actual.getAggregationTemporality()); } return this; @@ -41,8 +44,7 @@ public HistogramAssert isDelta() { failWithActualExpectedAndMessage( actual, "aggregationTemporality: DELTA", - "Expected Histgram to have cumulative aggregation but found <%s>", - AggregationTemporality.DELTA, + "Expected Histogram to have delta aggregation but found <%s>", actual.getAggregationTemporality()); } return this; @@ -68,4 +70,35 @@ public HistogramAssert hasPointsSatisfying( .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, HistogramPointAssert::new)); return this; } + + /** + * Asserts that for each given assertion, at least one point in the histogram satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final HistogramAssert containsPointsSatisfying( + Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the histogram satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + public HistogramAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new HistogramPointAssert(point))); + } + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramPointAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramPointAssert.java index 7219b6c1dbb..3ce2fe38d2c 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramPointAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/HistogramPointAssert.java @@ -6,14 +6,20 @@ package io.opentelemetry.sdk.testing.assertj; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.HistogramPointData; import java.util.Arrays; import java.util.function.Consumer; import org.assertj.core.api.Assertions; +import org.assertj.core.data.Offset; -/** Test assertions for {@link HistogramPointData}. */ +/** + * Test assertions for {@link HistogramPointData}. + * + * @since 1.14.0 + */ public final class HistogramPointAssert extends AbstractPointAssert { @@ -64,9 +70,20 @@ public HistogramPointAssert hasCount(long expected) { * @param boundaries The set of bucket boundaries in the same order as the expected collection. */ public HistogramPointAssert hasBucketBoundaries(double... boundaries) { + return hasBucketBoundaries(boundaries, within(0.000_001)); + } + + /** + * Asserts the {@code boundaries} field matches the expected value. The boundaries are may vary + * with a specified precision. + * + * @param boundaries The set of bucket boundaries in the same order as the expected collection. + * @param precision The precision under which boundaries may vary. + */ + public HistogramPointAssert hasBucketBoundaries(double[] boundaries, Offset precision) { isNotNull(); - Double[] bigBoundaries = Arrays.stream(boundaries).boxed().toArray(Double[]::new); - Assertions.assertThat(actual.getBoundaries()).as("boundaries").containsExactly(bigBoundaries); + double[] actualBoundaries = actual.getBoundaries().stream().mapToDouble(d -> d).toArray(); + Assertions.assertThat(actualBoundaries).as("boundaries").containsExactly(boundaries, precision); return this; } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogRecordDataAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogRecordDataAssert.java new file mode 100644 index 00000000000..95be6dc07f4 --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LogRecordDataAssert.java @@ -0,0 +1,478 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static io.opentelemetry.api.common.ValueType.KEY_VALUE_LIST; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static java.util.stream.Collectors.toList; +import static org.junit.Assert.assertNotNull; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.common.ValueType; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.resources.Resource; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.assertj.core.api.AbstractAssert; + +/** + * Test assertions for {@link LogRecordData}. + * + * @since 1.27.0 + */ +public final class LogRecordDataAssert extends AbstractAssert { + + private static final AttributeKey EXCEPTION_TYPE = + AttributeKey.stringKey("exception.type"); + private static final AttributeKey EXCEPTION_MESSAGE = + AttributeKey.stringKey("exception.message"); + private static final AttributeKey EXCEPTION_STACKTRACE = + AttributeKey.stringKey("exception.stacktrace"); + + LogRecordDataAssert(@Nullable LogRecordData actual) { + super(actual, LogRecordDataAssert.class); + } + + /** Asserts the {@link Resource} associated with a log matches the expected value. */ + public LogRecordDataAssert hasResource(Resource resource) { + isNotNull(); + if (!actual.getResource().equals(resource)) { + failWithActualExpectedAndMessage( + actual, + "resource: " + resource, + "Expected log to have resource <%s> but found <%s>", + resource, + actual.getResource()); + } + return this; + } + + /** + * Asserts the log has a resource satisfying the given condition. + * + * @since 1.29.0 + */ + public LogRecordDataAssert hasResourceSatisfying(Consumer resource) { + isNotNull(); + resource.accept( + new ResourceAssert(actual.getResource(), String.format("log [%s]", actual.getBodyValue()))); + return this; + } + + /** + * Asserts the {@link InstrumentationScopeInfo} associated with a log matches the expected value. + */ + public LogRecordDataAssert hasInstrumentationScope( + InstrumentationScopeInfo instrumentationScopeInfo) { + isNotNull(); + if (!actual.getInstrumentationScopeInfo().equals(instrumentationScopeInfo)) { + failWithActualExpectedAndMessage( + actual, + "instrumentation scope: " + instrumentationScopeInfo, + "Expected log to have scope <%s> but found <%s>", + instrumentationScopeInfo, + actual.getInstrumentationScopeInfo()); + } + return this; + } + + /** + * Asserts the log has the given epoch {@code eventName}. + * + * @since 1.50.0 + */ + public LogRecordDataAssert hasEventName(String eventName) { + isNotNull(); + if (!eventName.equals(actual.getEventName())) { + failWithActualExpectedAndMessage( + actual.getEventName(), + eventName, + "Expected log to have eventName <%s> but was <%s>", + eventName, + actual.getEventName()); + } + return this; + } + + /** Asserts the log has the given epoch {@code timestamp}. */ + public LogRecordDataAssert hasTimestamp(long timestampEpochNanos) { + isNotNull(); + if (actual.getTimestampEpochNanos() != timestampEpochNanos) { + failWithActualExpectedAndMessage( + actual.getTimestampEpochNanos(), + timestampEpochNanos, + "Expected log to have timestamp <%s> nanos but was <%s>", + timestampEpochNanos, + actual.getTimestampEpochNanos()); + } + return this; + } + + /** Asserts the log has the given epoch {@code observedTimestamp}. */ + public LogRecordDataAssert hasObservedTimestamp(long observedEpochNanos) { + isNotNull(); + if (actual.getObservedTimestampEpochNanos() != observedEpochNanos) { + failWithActualExpectedAndMessage( + actual.getObservedTimestampEpochNanos(), + observedEpochNanos, + "Expected log to have observed timestamp <%s> nanos but was <%s>", + observedEpochNanos, + actual.getObservedTimestampEpochNanos()); + } + return this; + } + + /** Asserts the log has the given span context. */ + public LogRecordDataAssert hasSpanContext(SpanContext spanContext) { + isNotNull(); + if (!actual.getSpanContext().equals(spanContext)) { + failWithActualExpectedAndMessage( + actual.getSpanContext(), + spanContext, + "Expected log to have span context <%s> but was <%s>", + spanContext, + actual.getSpanContext()); + } + return this; + } + + /** Asserts the log has the given severity. */ + public LogRecordDataAssert hasSeverity(Severity severity) { + isNotNull(); + if (actual.getSeverity() != severity) { + failWithActualExpectedAndMessage( + actual.getSeverity(), + severity, + "Expected log to have severity <%s> but was <%s>", + severity, + actual.getSeverity()); + } + return this; + } + + /** Asserts the log has the given severity text. */ + public LogRecordDataAssert hasSeverityText(String severityText) { + isNotNull(); + if (!severityText.equals(actual.getSeverityText())) { + failWithActualExpectedAndMessage( + actual.getSeverityText(), + severityText, + "Expected log to have severity text <%s> but was <%s>", + severityText, + actual.getSeverityText()); + } + return this; + } + + /** Asserts the log has the given body. */ + public LogRecordDataAssert hasBody(String body) { + isNotNull(); + return hasBody(Value.of(body)); + } + + /** + * Asserts the log has the given body. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBody(@Nullable Value body) { + isNotNull(); + if (!Objects.equals(actual.getBodyValue(), body)) { + failWithActualExpectedAndMessage( + actual.getBodyValue(), + body, + "Expected log to have body <%s> but was <%s>", + body, + actual.getBodyValue()); + } + return this; + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and String {@code value}. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, String value) { + return hasBodyField(key, Value.of(value)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and long {@code value}. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, long value) { + return hasBodyField(key, Value.of(value)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and double {@code value}. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, double value) { + return hasBodyField(key, Value.of(value)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and boolean {@code value}. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, boolean value) { + return hasBodyField(key, Value.of(value)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and list of String {@code value}s. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, String... value) { + List> values = new ArrayList<>(value.length); + for (String val : value) { + values.add(Value.of(val)); + } + return hasBodyField(key, Value.of(values)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and list of long {@code value}s. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, long... value) { + List> values = new ArrayList<>(value.length); + for (long val : value) { + values.add(Value.of(val)); + } + return hasBodyField(key, Value.of(values)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and list of double {@code value}s. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, double... value) { + List> values = new ArrayList<>(value.length); + for (double val : value) { + values.add(Value.of(val)); + } + return hasBodyField(key, Value.of(values)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and list of boolean {@code value}s. + * + * @since 1.42.0 + */ + public LogRecordDataAssert hasBodyField(String key, boolean... value) { + List> values = new ArrayList<>(value.length); + for (boolean val : value) { + values.add(Value.of(val)); + } + return hasBodyField(key, Value.of(values)); + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given {@code key} and {@code value}. + * + * @since 1.42.0 + */ + @SuppressWarnings({"unchecked"}) + public LogRecordDataAssert hasBodyField(String key, Value value) { + isNotNull(); + Value bodyValue = actual.getBodyValue(); + assertNotNull( + "Body was not expected to be null.", bodyValue); // Can't use assertj or nullaway complains + assertThat(bodyValue.getType()).isEqualTo(KEY_VALUE_LIST); + Value> body = (Value>) bodyValue; + List payload = body.getValue(); + KeyValue expected = KeyValue.of(key, value); + assertThat(payload).contains(expected); + return this; + } + + /** + * Asserts the log has a body of type {@link ValueType#KEY_VALUE_LIST}, containing a field with + * the given attribute {@code key} and {@code value}. + * + * @since 1.42.0 + */ + @SuppressWarnings({"unchecked"}) + public LogRecordDataAssert hasBodyField(AttributeKey key, T value) { + switch (key.getType()) { + case STRING: + return hasBodyField(key.getKey(), (String) value); + case BOOLEAN: + return hasBodyField(key.getKey(), (boolean) value); + case LONG: + return hasBodyField(key.getKey(), (long) value); + case DOUBLE: + return hasBodyField(key.getKey(), (double) value); + case STRING_ARRAY: + return hasBodyField( + key.getKey(), + Value.of(((List) value).stream().map(Value::of).collect(toList()))); + case BOOLEAN_ARRAY: + return hasBodyField( + key.getKey(), + Value.of(((List) value).stream().map(Value::of).collect(toList()))); + case LONG_ARRAY: + return hasBodyField( + key.getKey(), Value.of(((List) value).stream().map(Value::of).collect(toList()))); + case DOUBLE_ARRAY: + return hasBodyField( + key.getKey(), + Value.of(((List) value).stream().map(Value::of).collect(toList()))); + case VALUE: + return hasBodyField(key.getKey(), (Value) value); + } + return this; + } + + /** + * Asserts the log has exception attributes for the given {@link Throwable}. The stack trace is + * not matched against. + * + * @since 1.60.0 + */ + @SuppressWarnings("NullAway") + public LogRecordDataAssert hasException(Throwable exception) { + isNotNull(); + + assertThat(actual.getAttributes()) + .as("exception.type") + .containsEntry(EXCEPTION_TYPE, exception.getClass().getCanonicalName()); + if (exception.getMessage() != null) { + assertThat(actual.getAttributes()) + .as("exception.message") + .containsEntry(EXCEPTION_MESSAGE, exception.getMessage()); + } + + // Exceptions used in assertions always have a different stack trace, just confirm it was + // recorded. + String stackTrace = actual.getAttributes().get(EXCEPTION_STACKTRACE); + assertThat(stackTrace).as("exception.stacktrace").isNotNull(); + + return this; + } + + /** Asserts the log has the given attributes. */ + public LogRecordDataAssert hasAttributes(Attributes attributes) { + isNotNull(); + if (!attributesAreEqual(attributes)) { + failWithActualExpectedAndMessage( + actual.getAttributes(), + attributes, + "Expected log to have attributes <%s> but was <%s>", + attributes, + actual.getAttributes()); + } + return this; + } + + /** Asserts the log has the given attributes. */ + @SuppressWarnings({"rawtypes", "unchecked"}) + @SafeVarargs + public final LogRecordDataAssert hasAttributes( + Map.Entry, ?>... entries) { + AttributesBuilder attributesBuilder = Attributes.builder(); + for (Map.Entry, ?> attr : entries) { + attributesBuilder.put((AttributeKey) attr.getKey(), attr.getValue()); + } + Attributes attributes = attributesBuilder.build(); + return hasAttributes(attributes); + } + + /** Asserts the log has attributes satisfying the given condition. */ + public LogRecordDataAssert hasAttributesSatisfying(Consumer attributes) { + isNotNull(); + assertThat(actual.getAttributes()).as("attributes").satisfies(attributes); + return this; + } + + /** + * Asserts the log has attributes matching all {@code assertions}. Assertions can be created using + * methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public LogRecordDataAssert hasAttributesSatisfying(AttributeAssertion... assertions) { + return hasAttributesSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts the log has attributes matching all {@code assertions}. Assertions can be created using + * methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public LogRecordDataAssert hasAttributesSatisfying(Iterable assertions) { + AssertUtil.assertAttributes(actual.getAttributes(), assertions); + return myself; + } + + /** + * Asserts the log has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public LogRecordDataAssert hasAttributesSatisfyingExactly(AttributeAssertion... assertions) { + return hasAttributesSatisfyingExactly(Arrays.asList(assertions)); + } + + /** + * Asserts the log has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public LogRecordDataAssert hasAttributesSatisfyingExactly( + Iterable assertions) { + AssertUtil.assertAttributesExactly(actual.getAttributes(), assertions); + return myself; + } + + private boolean attributesAreEqual(Attributes attributes) { + // compare as maps, since implementations do not have equals that work correctly across + // implementations. + return actual.getAttributes().asMap().equals(attributes.asMap()); + } + + /** Asserts the log has the given total attributes. */ + public LogRecordDataAssert hasTotalAttributeCount(int totalAttributeCount) { + isNotNull(); + if (actual.getTotalAttributeCount() != totalAttributeCount) { + failWithActualExpectedAndMessage( + actual.getTotalAttributeCount(), + totalAttributeCount, + "Expected log to have recorded <%s> total attributes but did not", + totalAttributeCount); + } + return this; + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongExemplarAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongExemplarAssert.java index 9d90a41e544..b8c304b451f 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongExemplarAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongExemplarAssert.java @@ -17,7 +17,11 @@ import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; -/** Assertions for an exported {@link LongExemplarData}. */ +/** + * Assertions for an exported {@link LongExemplarData}. + * + * @since 1.14.0 + */ public final class LongExemplarAssert extends AbstractAssert { LongExemplarAssert(@Nullable LongExemplarData actual) { super(actual, LongExemplarAssert.class); @@ -92,19 +96,48 @@ public final LongExemplarAssert hasFilteredAttributes( return hasFilteredAttributes(attributes); } - /** Asserts the exemplar has filtered attributes matching all {@code assertions} and no more. */ + /** + * Asserts the exemplar has filtered attributes matching all {@code assertions}. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ public LongExemplarAssert hasFilteredAttributesSatisfying(AttributeAssertion... assertions) { return hasFilteredAttributesSatisfying(Arrays.asList(assertions)); } + /** + * Asserts the exemplar has filtered attributes matching all {@code assertions}. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public LongExemplarAssert hasFilteredAttributesSatisfying( + Iterable assertions) { + AssertUtil.assertAttributes(actual.getFilteredAttributes(), assertions); + return myself; + } + /** * Asserts the exemplar has filtered attributes matching all {@code assertions} and no more. * Assertions can be created using methods like {@link * OpenTelemetryAssertions#satisfies(AttributeKey, OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 */ - public LongExemplarAssert hasFilteredAttributesSatisfying( + public LongExemplarAssert hasFilteredAttributesSatisfyingExactly( + AttributeAssertion... assertions) { + return hasFilteredAttributesSatisfyingExactly(Arrays.asList(assertions)); + } + + /** + * Asserts the exemplar has filtered attributes matching all {@code assertions} and no more. + * Assertions can be created using methods like {@link + * OpenTelemetryAssertions#satisfies(AttributeKey, OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public LongExemplarAssert hasFilteredAttributesSatisfyingExactly( Iterable assertions) { - AssertUtil.assertAttributes(actual.getFilteredAttributes(), assertions); + AssertUtil.assertAttributesExactly(actual.getFilteredAttributes(), assertions); return myself; } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongGaugeAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongGaugeAssert.java index 3b4f51c3c6f..dbaea3becf6 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongGaugeAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongGaugeAssert.java @@ -14,7 +14,11 @@ import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; -/** Assertions for an exported long {@link GaugeData}. */ +/** + * Assertions for an exported long {@link GaugeData}. + * + * @since 1.14.0 + */ public final class LongGaugeAssert extends AbstractAssert> { @@ -40,4 +44,34 @@ public LongGaugeAssert hasPointsSatisfying( .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, LongPointAssert::new)); return this; } + + /** + * Asserts that for each given assertion, at least one point in the gauge satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final LongGaugeAssert containsPointsSatisfying(Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the gauge satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + public LongGaugeAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new LongPointAssert(point))); + } + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongPointAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongPointAssert.java index e4ce951d1f5..7d4b988e90e 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongPointAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongPointAssert.java @@ -12,8 +12,13 @@ import java.util.Arrays; import java.util.function.Consumer; import javax.annotation.Nullable; +import org.assertj.core.api.AbstractLongAssert; -/** Assertions for an exported {@link LongPointData}. */ +/** + * Assertions for an exported {@link LongPointData}. + * + * @since 1.14.0 + */ public final class LongPointAssert extends AbstractPointAssert { LongPointAssert(@Nullable LongPointData actual) { @@ -27,6 +32,17 @@ public LongPointAssert hasValue(long expected) { return this; } + /** + * Asserts the point's value satisfies the given assertion. + * + * @since 1.62.0 + */ + public LongPointAssert hasValueSatisfying(Consumer> valueAssertion) { + isNotNull(); + valueAssertion.accept(assertThat(actual.getValue()).as("value")); + return this; + } + /** Asserts the point has the specified exemplars, in any order. */ public LongPointAssert hasExemplars(LongExemplarData... exemplars) { isNotNull(); diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongSumAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongSumAssert.java index 91e19869102..bfa2deaf750 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongSumAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/LongSumAssert.java @@ -14,7 +14,11 @@ import java.util.function.Consumer; import org.assertj.core.api.AbstractAssert; -/** Test assertions for long {@link SumData}. */ +/** + * Test assertions for long {@link SumData}. + * + * @since 1.14.0 + */ public final class LongSumAssert extends AbstractAssert> { LongSumAssert(SumData actual) { super(actual, LongSumAssert.class); @@ -69,18 +73,48 @@ public LongSumAssert isDelta() { return myself; } - /** Asserts the sum has points matching all of the given assertions and no more, in any order. */ + /** Asserts the sum has points matching all the given assertions and no more, in any order. */ @SafeVarargs @SuppressWarnings("varargs") public final LongSumAssert hasPointsSatisfying(Consumer... assertions) { return hasPointsSatisfying(Arrays.asList(assertions)); } - /** Asserts the sum has points matching all of the given assertions and no more, in any order. */ + /** Asserts the sum has points matching all the given assertions and no more, in any order. */ public LongSumAssert hasPointsSatisfying( Iterable> assertions) { assertThat(actual.getPoints()) .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, LongPointAssert::new)); return this; } + + /** + * Asserts that for each given assertion, at least one point in the sum satisfies it. Extra points + * that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final LongSumAssert containsPointsSatisfying(Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the sum satisfies it. Extra points + * that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + public LongSumAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new LongPointAssert(point))); + } + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssert.java index f65feb8f347..bcc2af929c1 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/MetricAssert.java @@ -13,7 +13,11 @@ import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; -/** Assertions for an exported {@link MetricData}. */ +/** + * Assertions for an exported {@link MetricData}. + * + * @since 1.14.0 + */ public final class MetricAssert extends AbstractAssert { MetricAssert(@Nullable MetricData actual) { super(actual, MetricAssert.class); @@ -33,6 +37,18 @@ public MetricAssert hasResource(Resource resource) { return this; } + /** + * Asserts the metric has a resource satisfying the given condition. + * + * @since 1.23.0 + */ + public MetricAssert hasResourceSatisfying(Consumer resource) { + isNotNull(); + resource.accept( + new ResourceAssert(actual.getResource(), String.format("metric [%s]", actual.getName()))); + return this; + } + /** Asserts the metric has the given the {@link InstrumentationScopeInfo}. */ public MetricAssert hasInstrumentationScope(InstrumentationScopeInfo instrumentationScopeInfo) { isNotNull(); @@ -40,7 +56,7 @@ public MetricAssert hasInstrumentationScope(InstrumentationScopeInfo instrumenta failWithActualExpectedAndMessage( actual, "instrumentation scope: " + instrumentationScopeInfo, - "Expected MetricData to have resource <%s> but found <%s>", + "Expected MetricData to have instrumentation scope <%s> but found <%s>", instrumentationScopeInfo, actual.getInstrumentationScopeInfo()); } @@ -106,6 +122,30 @@ public MetricAssert hasDoubleGaugeSatisfying(Consumer asserti return this; } + /** + * Asserts this {@link MetricData} is a double gauge with points matching all of the given + * assertions and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasDoubleGaugePointsSatisfying( + Consumer... assertions) { + return hasDoubleGaugeSatisfying(gauge -> gauge.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is a double gauge with points matching all of the given + * assertions and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasDoubleGaugePointsSatisfying( + Iterable> assertions) { + return hasDoubleGaugeSatisfying(gauge -> gauge.hasPointsSatisfying(assertions)); + } + /** * Asserts this {@link MetricData} is a {@code LongGauge} that satisfies the provided assertion. */ @@ -123,6 +163,29 @@ public MetricAssert hasLongGaugeSatisfying(Consumer assertion) return this; } + /** + * Asserts this {@link MetricData} is a long gauge with points matching all of the given + * assertions and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasLongGaugePointsSatisfying(Consumer... assertions) { + return hasLongGaugeSatisfying(gauge -> gauge.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is a long gauge with points matching all of the given + * assertions and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasLongGaugePointsSatisfying( + Iterable> assertions) { + return hasLongGaugeSatisfying(gauge -> gauge.hasPointsSatisfying(assertions)); + } + /** Asserts this {@link MetricData} is a double sum that satisfies the provided assertion. */ public MetricAssert hasDoubleSumSatisfying(Consumer assertion) { isNotNull(); @@ -138,6 +201,30 @@ public MetricAssert hasDoubleSumSatisfying(Consumer assertion) return this; } + /** + * Asserts this {@link MetricData} is a double sum with points matching all of the given + * assertions and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasDoubleSumPointsSatisfying( + Consumer... assertions) { + return hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is a double sum with points matching all of the given + * assertions and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasDoubleSumPointsSatisfying( + Iterable> assertions) { + return hasDoubleSumSatisfying(sum -> sum.hasPointsSatisfying(assertions)); + } + /** Asserts this {@link MetricData} is a long sum that satisfies the provided assertion. */ public MetricAssert hasLongSumSatisfying(Consumer assertion) { isNotNull(); @@ -153,6 +240,29 @@ public MetricAssert hasLongSumSatisfying(Consumer assertion) { return this; } + /** + * Asserts this {@link MetricData} is a long sum with points matching all of the given assertions + * and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasLongSumPointsSatisfying(Consumer... assertions) { + return hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is a long sum with points matching all of the given assertions + * and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasLongSumPointsSatisfying( + Iterable> assertions) { + return hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(assertions)); + } + /** Asserts this {@link MetricData} is a histogram that satisfies the provided assertion. */ public MetricAssert hasHistogramSatisfying(Consumer assertion) { isNotNull(); @@ -168,6 +278,77 @@ public MetricAssert hasHistogramSatisfying(Consumer assertion) return this; } + /** + * Asserts this {@link MetricData} is a histogram with points matching all of the given assertions + * and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasHistogramPointsSatisfying( + Consumer... assertions) { + return hasHistogramSatisfying(histogram -> histogram.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is a histogram with points matching all of the given assertions + * and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasHistogramPointsSatisfying( + Iterable> assertions) { + return hasHistogramSatisfying(histogram -> histogram.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is an exponential histogram that satisfies the provided + * assertion. + * + * @since 1.23.0 + */ + public MetricAssert hasExponentialHistogramSatisfying( + Consumer assertion) { + isNotNull(); + if (actual.getType() != MetricDataType.EXPONENTIAL_HISTOGRAM) { + failWithActualExpectedAndMessage( + actual, + "type: EXPONENTIAL_HISTOGRAM", + "Expected MetricData to have type <%s> but found <%s>", + MetricDataType.EXPONENTIAL_HISTOGRAM, + actual.getType()); + } + assertion.accept(new ExponentialHistogramAssert(actual.getExponentialHistogramData())); + return this; + } + + /** + * Asserts this {@link MetricData} is an exponential histogram with points matching all of the + * given assertions and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasExponentialHistogramPointsSatisfying( + Consumer... assertions) { + return hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is an exponential histogram with points matching all of the + * given assertions and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasExponentialHistogramPointsSatisfying( + Iterable> assertions) { + return hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(assertions)); + } + /** Asserts this {@link MetricData} is a summary that satisfies the provided assertion. */ public MetricAssert hasSummarySatisfying(Consumer assertion) { isNotNull(); @@ -182,4 +363,27 @@ public MetricAssert hasSummarySatisfying(Consumer assertion) { assertion.accept(new SummaryAssert(actual.getSummaryData())); return this; } + + /** + * Asserts this {@link MetricData} is a summary with points matching all of the given assertions + * and no more, in any order. + * + * @since 1.68.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final MetricAssert hasSummaryPointsSatisfying(Consumer... assertions) { + return hasSummarySatisfying(summary -> summary.hasPointsSatisfying(assertions)); + } + + /** + * Asserts this {@link MetricData} is a summary with points matching all of the given assertions + * and no more, in any order. + * + * @since 1.68.0 + */ + public MetricAssert hasSummaryPointsSatisfying( + Iterable> assertions) { + return hasSummarySatisfying(summary -> summary.hasPointsSatisfying(assertions)); + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/OpenTelemetryAssertions.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/OpenTelemetryAssertions.java index f4df5dd24a8..c6693829ffa 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/OpenTelemetryAssertions.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/OpenTelemetryAssertions.java @@ -7,6 +7,8 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.sdk.logs.data.LogRecordData; import io.opentelemetry.sdk.metrics.data.MetricData; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.SpanData; @@ -23,6 +25,7 @@ import org.assertj.core.api.AbstractStringAssert; import org.assertj.core.api.Assertions; import org.assertj.core.api.ListAssert; +import org.assertj.core.api.ObjectAssert; /** * Entry point for assertion methods for OpenTelemetry types. To use type-specific assertions, @@ -41,7 +44,11 @@ public static SpanDataAssert assertThat(@Nullable SpanData spanData) { return new SpanDataAssert(spanData); } - /** Returns an assertion for {@link MetricData}. */ + /** + * Returns an assertion for {@link MetricData}. + * + * @since 1.14.0 + */ public static MetricAssert assertThat(@Nullable MetricData metricData) { return new MetricAssert(metricData); } @@ -51,6 +58,15 @@ public static EventDataAssert assertThat(@Nullable EventData eventData) { return new EventDataAssert(eventData); } + /** + * Returns an assertion for {@link LogRecordData}. + * + * @since 1.27.0 + */ + public static LogRecordDataAssert assertThat(@Nullable LogRecordData log) { + return new LogRecordDataAssert(log); + } + /** * Returns an attribute entry with a String value for use with {@link * AttributesAssert#containsOnly(java.util.Map.Entry[])}. @@ -124,6 +140,17 @@ public static Map.Entry>, List> attributeEntry Arrays.stream(value).boxed().collect(Collectors.toList())); } + /** + * Returns an attribute entry with a Value for use with {@link + * AttributesAssert#containsOnly(java.util.Map.Entry[])}. + * + * @since 1.59.0 + */ + public static Map.Entry>, Value> attributeEntry( + String key, Value value) { + return new AbstractMap.SimpleImmutableEntry<>(AttributeKey.valueKey(key), value); + } + /** * Returns an {@link AttributeAssertion} that asserts the given {@code key} is present with a * value satisfying {@code assertion}. @@ -198,11 +225,22 @@ public static AttributeAssertion satisfies( return AttributeAssertion.create(key, assertion); } + /** + * Returns an {@link AttributeAssertion} that asserts the given {@code key} is present with a + * value satisfying {@code assertion}. + * + * @since 1.59.0 + */ + public static AttributeAssertion satisfies( + AttributeKey> key, ValueAssertConsumer assertion) { + return AttributeAssertion.create(key, assertion); + } + /** * Returns an {@link AttributeAssertion} that asserts the given {@code key} is present with the * given {@code value}. */ - public static AttributeAssertion equalTo(AttributeKey key, T value) { + public static AttributeAssertion equalTo(AttributeKey key, @Nullable T value) { return AttributeAssertion.create(key, val -> val.isEqualTo(value)); } @@ -217,22 +255,33 @@ public static AttributeAssertion equalTo(AttributeKey key, int value) { // Unique interfaces to prevent generic functional interface clash. These are not interesting at // all but are required to be able to use the same method name in methods like satisfies above. + /** Assertions on a string attribute value. */ public interface StringAssertConsumer extends Consumer> {} + /** Assertions on a boolean attribute value. */ public interface BooleanAssertConsumer extends Consumer> {} + /** Assertions on a long attribute value. */ public interface LongAssertConsumer extends Consumer> {} + /** Assertions on a double attribute value. */ public interface DoubleAssertConsumer extends Consumer> {} + /** Assertions on a string array attribute value. */ public interface StringListAssertConsumer extends Consumer> {} + /** Assertions on a boolean array attribute value. */ public interface BooleanListAssertConsumer extends Consumer> {} + /** Assertions on a long array attribute value. */ public interface LongListAssertConsumer extends Consumer> {} + /** Assertions on a double array attribute value. */ public interface DoubleListAssertConsumer extends Consumer> {} + /** Assertions on a structured attribute value. */ + public interface ValueAssertConsumer extends Consumer>> {} + private static List toList(boolean... values) { Boolean[] boxed = new Boolean[values.length]; for (int i = 0; i < values.length; i++) { diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ResourceAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ResourceAssert.java new file mode 100644 index 00000000000..fccfd472d04 --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ResourceAssert.java @@ -0,0 +1,142 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.sdk.resources.Resource; +import java.util.Arrays; +import java.util.Map; +import java.util.Set; +import java.util.function.Consumer; +import javax.annotation.Nullable; +import org.assertj.core.api.AbstractAssert; + +/** + * Assertions for {@link Resource}. + * + * @since 1.23.0 + */ +public final class ResourceAssert extends AbstractAssert { + + private final String label; + + ResourceAssert(Resource resource, String label) { + super(resource, ResourceAssert.class); + this.label = label; + } + + /** Asserts the resource has a schemaUrl satisfying the given condition. */ + // Workaround "passing @Nullable parameter 'schemaUrl' where @NonNull is required", Nullaway + // seems to think assertThat is supposed to be passed NonNull even though we know that can't be + // true for assertions. + @SuppressWarnings("NullAway") + public ResourceAssert hasSchemaUrl(@Nullable String schemaUrl) { + isNotNull(); + assertThat(actual.getSchemaUrl()).as("resource schema URL of %s", label).isEqualTo(schemaUrl); + return this; + } + + /** Asserts the resource has the given attribute. */ + public ResourceAssert hasAttribute(AttributeKey key, T value) { + return hasAttribute(OpenTelemetryAssertions.equalTo(key, value)); + } + + /** Asserts the resource has an attribute matching the {@code attributeAssertion}. */ + public ResourceAssert hasAttribute(AttributeAssertion attributeAssertion) { + isNotNull(); + + Set> actualKeys = actual.getAttributes().asMap().keySet(); + AttributeKey key = attributeAssertion.getKey(); + + assertThat(actualKeys).as("resource attribute keys of %s", label).contains(key); + + Object value = actual.getAttributes().get(key); + AbstractAssert assertion = AttributeAssertion.attributeValueAssertion(key, value); + attributeAssertion.getAssertion().accept(assertion); + + return this; + } + + /** Asserts the resource has the given attributes. */ + public ResourceAssert hasAttributes(Attributes attributes) { + isNotNull(); + if (!AssertUtil.attributesAreEqual(actual.getAttributes(), attributes)) { + failWithActualExpectedAndMessage( + actual.getAttributes(), + attributes, + "Expected resource of <%s> to have attributes <%s> but was <%s>", + label, + attributes, + actual.getAttributes()); + } + return this; + } + + /** Asserts the resource has the given attributes. */ + @SuppressWarnings({"rawtypes", "unchecked"}) + @SafeVarargs + public final ResourceAssert hasAttributes(Map.Entry, ?>... entries) { + AttributesBuilder attributesBuilder = Attributes.builder(); + for (Map.Entry, ?> attr : entries) { + attributesBuilder.put((AttributeKey) attr.getKey(), attr.getValue()); + } + Attributes attributes = attributesBuilder.build(); + return hasAttributes(attributes); + } + + /** Asserts the resource has attributes satisfying the given condition. */ + public ResourceAssert hasAttributesSatisfying(Consumer attributes) { + isNotNull(); + OpenTelemetryAssertions.assertThat(actual.getAttributes()) + .as("resource attributes of %s", label) + .satisfies(attributes); + return this; + } + + /** + * Asserts the event has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public ResourceAssert hasAttributesSatisfying(AttributeAssertion... assertions) { + return hasAttributesSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts the event has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public ResourceAssert hasAttributesSatisfying(Iterable assertions) { + AssertUtil.assertAttributes( + actual.getAttributes(), assertions, String.format("resource of %s attribute keys", label)); + return this; + } + + /** + * Asserts the resource has attributes matching all {@code assertions} and no more. Assertions can + * be created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public ResourceAssert hasAttributesSatisfyingExactly(AttributeAssertion... assertions) { + return hasAttributesSatisfyingExactly(Arrays.asList(assertions)); + } + + /** + * Asserts the resource has attributes matching all {@code assertions} and no more. Assertions can + * be created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ + public ResourceAssert hasAttributesSatisfyingExactly(Iterable assertions) { + AssertUtil.assertAttributesExactly( + actual.getAttributes(), assertions, String.format("resource of %s attribute keys", label)); + return this; + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SpanDataAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SpanDataAssert.java index fdd42af1ae7..387229fd091 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SpanDataAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SpanDataAssert.java @@ -13,16 +13,15 @@ import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import java.time.Instant; import java.util.Arrays; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -34,6 +33,14 @@ /** Assertions for an exported {@link SpanData}. */ public final class SpanDataAssert extends AbstractAssert { + private static final AttributeKey EXCEPTION_TYPE = + AttributeKey.stringKey("exception.type"); + private static final AttributeKey EXCEPTION_MESSAGE = + AttributeKey.stringKey("exception.message"); + private static final AttributeKey EXCEPTION_STACKTRACE = + AttributeKey.stringKey("exception.stacktrace"); + private static final String EXCEPTION_EVENT_NAME = "exception"; + SpanDataAssert(@Nullable SpanData actual) { super(actual, SpanDataAssert.class); } @@ -160,6 +167,18 @@ public SpanDataAssert hasResource(Resource resource) { return this; } + /** + * Asserts the span has a resource satisfying the given condition. + * + * @since 1.23.0 + */ + public SpanDataAssert hasResourceSatisfying(Consumer resource) { + isNotNull(); + resource.accept( + new ResourceAssert(actual.getResource(), String.format("span [%s]", actual.getName()))); + return this; + } + /** * Asserts the span has the given {@link io.opentelemetry.sdk.common.InstrumentationLibraryInfo}. * @@ -167,7 +186,7 @@ public SpanDataAssert hasResource(Resource resource) { */ @Deprecated public SpanDataAssert hasInstrumentationLibraryInfo( - io.opentelemetry.sdk.common.InstrumentationLibraryInfo instrumentationLibraryInfo) { + InstrumentationLibraryInfo instrumentationLibraryInfo) { isNotNull(); if (!actual.getInstrumentationLibraryInfo().equals(instrumentationLibraryInfo)) { failWithActualExpectedAndMessage( @@ -307,7 +326,37 @@ public SpanDataAssert hasAttributesSatisfying(Consumer attributes) { return this; } - /** Asserts the span has attributes matching all {@code assertions} and no more. */ + /** + * Asserts the event has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public SpanDataAssert hasAttributesSatisfying(AttributeAssertion... assertions) { + return hasAttributesSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts the event has attributes matching all {@code assertions}. Assertions can be created + * using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + * + * @since 1.21.0 + */ + public SpanDataAssert hasAttributesSatisfying(Iterable assertions) { + AssertUtil.assertAttributes( + actual.getAttributes(), + assertions, + String.format("span [%s] attribute keys", actual.getName())); + return this; + } + + /** + * Asserts the span has attributes matching all {@code assertions} and no more. Assertions can be + * created using methods like {@link OpenTelemetryAssertions#satisfies(AttributeKey, + * OpenTelemetryAssertions.LongAssertConsumer)}. + */ public SpanDataAssert hasAttributesSatisfyingExactly(AttributeAssertion... assertions) { return hasAttributesSatisfyingExactly(Arrays.asList(assertions)); } @@ -318,40 +367,37 @@ public SpanDataAssert hasAttributesSatisfyingExactly(AttributeAssertion... asser * OpenTelemetryAssertions.LongAssertConsumer)}. */ public SpanDataAssert hasAttributesSatisfyingExactly(Iterable assertions) { - Set> actualKeys = actual.getAttributes().asMap().keySet(); - Set> checkedKeys = new HashSet<>(); - for (AttributeAssertion attributeAssertion : assertions) { - AttributeKey key = attributeAssertion.getKey(); - Object value = actual.getAttributes().get(key); - if (value != null) { - checkedKeys.add(key); - } - AbstractAssert assertion = AttributeAssertion.attributeValueAssertion(key, value); - attributeAssertion.getAssertion().accept(assertion); - } - - assertThat(actualKeys) - .as("span [%s] attribute keys", actual.getName()) - .containsExactlyInAnyOrderElementsOf(checkedKeys); - + AssertUtil.assertAttributesExactly( + actual.getAttributes(), + assertions, + String.format("span [%s] attribute keys", actual.getName())); return this; } /** * Asserts the span has an exception event for the given {@link Throwable}. The stack trace is not - * matched against. + * matched against. If {@code exception} is {@code null}, asserts the span has no exception event. */ // Workaround "passing @Nullable parameter 'stackTrace' where @NonNull is required", Nullaway // seems to think assertThat is supposed to be passed NonNull even though we know that can't be // true for assertions. @SuppressWarnings("NullAway") - public SpanDataAssert hasException(Throwable exception) { + public SpanDataAssert hasException(@Nullable Throwable exception) { EventData exceptionEvent = actual.getEvents().stream() - .filter(event -> event.getName().equals(SemanticAttributes.EXCEPTION_EVENT_NAME)) + .filter(event -> event.getName().equals(EXCEPTION_EVENT_NAME)) .findFirst() .orElse(null); + if (exception == null) { + if (exceptionEvent != null) { + failWithMessage( + "Expected span [%s] to have no exception event but had <%s>", + actual.getName(), exceptionEvent); + } + return this; + } + if (exceptionEvent == null) { failWithMessage( "Expected span [%s] to have an exception event but only had events <%s>", @@ -362,16 +408,16 @@ public SpanDataAssert hasException(Throwable exception) { assertThat(exceptionEvent.getAttributes()) .as("exception.type") - .containsEntry(SemanticAttributes.EXCEPTION_TYPE, exception.getClass().getCanonicalName()); + .containsEntry(EXCEPTION_TYPE, exception.getClass().getCanonicalName()); if (exception.getMessage() != null) { assertThat(exceptionEvent.getAttributes()) .as("exception.message") - .containsEntry(SemanticAttributes.EXCEPTION_MESSAGE, exception.getMessage()); + .containsEntry(EXCEPTION_MESSAGE, exception.getMessage()); } // Exceptions used in assertions always have a different stack trace, just confirm it was // recorded. - String stackTrace = exceptionEvent.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE); + String stackTrace = exceptionEvent.getAttributes().get(EXCEPTION_STACKTRACE); assertThat(stackTrace).as("exception.stacktrace").isNotNull(); return this; @@ -440,7 +486,11 @@ public SpanDataAssert hasLinksSatisfying(Consumer> cond return this; } - /** Asserts the span has the given {@link StatusData}. */ + /** + * Asserts the span has the given {@link StatusData}. + * + * @since 1.16.0 + */ public SpanDataAssert hasStatus(StatusData status) { isNotNull(); if (!actual.getStatus().equals(status)) { @@ -455,6 +505,14 @@ public SpanDataAssert hasStatus(StatusData status) { return this; } + /** Asserts the span has a status satisfying the given condition. */ + public SpanDataAssert hasStatusSatisfying(Consumer condition) { + isNotNull(); + StatusDataAssert statusDataAssert = new StatusDataAssert(actual.getStatus()); + condition.accept(statusDataAssert); + return this; + } + /** Asserts the span ends at the given epoch timestamp, in nanos. */ public SpanDataAssert endsAt(long endEpochNanos) { isNotNull(); diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/StatusDataAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/StatusDataAssert.java new file mode 100644 index 00000000000..933b6be9125 --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/StatusDataAssert.java @@ -0,0 +1,57 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.sdk.trace.data.SpanData; +import io.opentelemetry.sdk.trace.data.StatusData; +import javax.annotation.Nullable; +import org.assertj.core.api.AbstractAssert; + +/** + * Assertions for the {@link StatusData} of an exported {@link SpanData}. + * + * @since 1.16.0 + */ +public final class StatusDataAssert extends AbstractAssert { + + StatusDataAssert(@Nullable StatusData statusData) { + super(statusData, StatusDataAssert.class); + } + + /** Asserts that the status is {@link io.opentelemetry.api.trace.StatusCode#OK}. */ + public StatusDataAssert isOk() { + return hasCode(StatusCode.OK); + } + + /** Asserts that the status is {@link io.opentelemetry.api.trace.StatusCode#ERROR}. */ + public StatusDataAssert isError() { + return hasCode(StatusCode.ERROR); + } + + /** Asserts that the status has the given {@link io.opentelemetry.api.trace.StatusCode}. */ + public StatusDataAssert hasCode(StatusCode expected) { + isNotNull(); + assertThat(actual.getStatusCode()).isEqualTo(expected); + return this; + } + + /** Asserts that the status has the given description. */ + public StatusDataAssert hasDescription(String expected) { + isNotNull(); + assertThat(actual.getDescription()).isEqualTo(expected); + return this; + } + + /** Asserts that the status has a description matching the given regular expression. */ + public StatusDataAssert hasDescriptionMatching(String regex) { + isNotNull(); + assertThat(actual.getDescription()).matches(regex); + return this; + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryAssert.java index 3b1956890a6..600e280e560 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryAssert.java @@ -15,7 +15,11 @@ import org.assertj.core.api.AbstractIterableAssert; import org.assertj.core.api.Assertions; -/** Test assertions for {@link SummaryData}. */ +/** + * Test assertions for {@link SummaryData}. + * + * @since 1.14.0 + */ public final class SummaryAssert extends AbstractAssert { SummaryAssert(SummaryData actual) { @@ -48,4 +52,34 @@ public SummaryAssert hasPointsSatisfying( .satisfiesExactlyInAnyOrder(AssertUtil.toConsumers(assertions, SummaryPointAssert::new)); return this; } + + /** + * Asserts that for each given assertion, at least one point in the summary satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + @SafeVarargs + @SuppressWarnings("varargs") + public final SummaryAssert containsPointsSatisfying(Consumer... assertions) { + return containsPointsSatisfying(Arrays.asList(assertions)); + } + + /** + * Asserts that for each given assertion, at least one point in the summary satisfies it. Extra + * points that match none of the assertions are allowed, and a single point may satisfy multiple + * assertions. + * + * @since 1.62.0 + */ + public SummaryAssert containsPointsSatisfying( + Iterable> assertions) { + isNotNull(); + for (Consumer assertion : assertions) { + assertThat(actual.getPoints()) + .anySatisfy(point -> assertion.accept(new SummaryPointAssert(point))); + } + return this; + } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryPointAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryPointAssert.java index 813ef698bf6..c948d17af13 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryPointAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/SummaryPointAssert.java @@ -12,7 +12,11 @@ import java.util.function.Consumer; import org.assertj.core.api.Assertions; -/** Test assertions for (deprecated) {@link SummaryPointData}. */ +/** + * Test assertions for {@link SummaryPointData}. + * + * @since 1.14.0 + */ public final class SummaryPointAssert extends AbstractPointAssert { diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TraceAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TraceAssert.java index 5f3da9db7f4..ee19607e2cd 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TraceAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TraceAssert.java @@ -59,9 +59,10 @@ public TraceAssert hasSpansSatisfyingExactly( List> assertionsList = StreamSupport.stream(assertions.spliterator(), false).collect(Collectors.toList()); hasSize(assertionsList.size()); + // Avoid zipSatisfy - https://github.com/assertj/assertj-core/issues/2300 for (int i = 0; i < assertionsList.size(); i++) { - assertionsList.get(i).accept(new SpanDataAssert(actual.get(i))); + assertionsList.get(i).accept(new SpanDataAssert(actual.get(i)).describedAs("Span " + i)); } return this; } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java index 78da139991a..e8d38b15c09 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/TracesAssert.java @@ -7,12 +7,17 @@ import static java.util.stream.Collectors.toList; +import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.sdk.trace.data.SpanData; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.function.Consumer; +import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.assertj.core.api.AbstractIterableAssert; @@ -21,6 +26,41 @@ public final class TracesAssert extends AbstractIterableAssert< TracesAssert, List>, List, TraceAssert> { + /** Compare spans by start time, placing parents before their children as a tiebreaker. */ + static final Comparator SPAN_DATA_COMPARATOR = + Comparator.comparingLong(SpanData::getStartEpochNanos) + .thenComparing((span1, span2) -> { + SpanContext parent1 = span1.getParentSpanContext(); + if (parent1.isValid() && parent1.getSpanId().equals(span2.getSpanId())) { + return 1; + } + SpanContext parent2 = span2.getParentSpanContext(); + if (parent2.isValid() && parent2.getSpanId().equals(span1.getSpanId())) { + return -1; + } + return 0; + }); + + /** + * Returns an assertion for a list of traces. The provided spans will be grouped into traces by + * their trace ID. + * + * @since 1.23.0 + */ + public static TracesAssert assertThat(List spanData) { + Map> traces = + spanData.stream() + .collect( + Collectors.groupingBy( + SpanData::getTraceId, + LinkedHashMap::new, + Collectors.toCollection(ArrayList::new))); + for (List trace : traces.values()) { + trace.sort(SPAN_DATA_COMPARATOR); + } + return assertThat(traces.values()); + } + /** * Returns an assertion for a list of traces. The traces must already be grouped into {@code * List} where each list has spans with the same trace ID. @@ -64,7 +104,7 @@ public TracesAssert hasTracesSatisfyingExactly( hasSize(assertionsList.size()); // Avoid zipSatisfy - https://github.com/assertj/assertj-core/issues/2300 for (int i = 0; i < assertionsList.size(); i++) { - assertionsList.get(i).accept(new TraceAssert(actual.get(i))); + assertionsList.get(i).accept(new TraceAssert(actual.get(i)).describedAs("Trace " + i)); } return this; } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ValueAtQuantileAssert.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ValueAtQuantileAssert.java index 1000353a500..162fec94bd6 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ValueAtQuantileAssert.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/assertj/ValueAtQuantileAssert.java @@ -9,7 +9,11 @@ import org.assertj.core.api.AbstractAssert; import org.assertj.core.api.Assertions; -/** Test assertions for (deprecated) {@link ValueAtQuantile}. */ +/** + * Test assertions for {@link ValueAtQuantile}. + * + * @since 1.14.0 + */ public final class ValueAtQuantileAssert extends AbstractAssert { diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/context/SettableContextStorageProvider.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/context/SettableContextStorageProvider.java index 1a34c3eade4..22b4fc6ec87 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/context/SettableContextStorageProvider.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/context/SettableContextStorageProvider.java @@ -34,6 +34,7 @@ public static ContextStorage getContextStorage() { private enum SettableContextStorage implements ContextStorage { INSTANCE; + @SuppressWarnings("NonFinalStaticField") private static volatile ContextStorage delegate = createStorage(); @Override diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryLogRecordExporter.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryLogRecordExporter.java new file mode 100644 index 00000000000..acb4a47c35b --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryLogRecordExporter.java @@ -0,0 +1,87 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.exporter; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.LogRecordExporter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; + +/** + * A {@link LogRecordExporter} implementation that can be used to test OpenTelemetry integration. + * + * @since 1.27.0 + */ +public final class InMemoryLogRecordExporter implements LogRecordExporter { + private final Queue finishedLogItems = new ConcurrentLinkedQueue<>(); + private boolean isStopped = false; + + private InMemoryLogRecordExporter() {} + + /** + * Returns a new instance of the {@link InMemoryLogRecordExporter}. + * + * @return a new instance of the {@link InMemoryLogRecordExporter}. + */ + public static InMemoryLogRecordExporter create() { + return new InMemoryLogRecordExporter(); + } + + /** + * Returns a {@code List} of the finished {@code Log}s, represented by {@code LogRecord}. + * + * @return a {@code List} of the finished {@code Log}s. + */ + public List getFinishedLogRecordItems() { + return Collections.unmodifiableList(new ArrayList<>(finishedLogItems)); + } + + /** + * Clears the internal {@code List} of finished {@code Log}s. + * + *

      Does not reset the state of this exporter if already shutdown. + */ + public void reset() { + finishedLogItems.clear(); + } + + /** + * Exports the collection of {@code Log}s into the inmemory queue. + * + *

      If this is called after {@code shutdown}, this will return {@code ResultCode.FAILURE}. + */ + @Override + public CompletableResultCode export(Collection logs) { + if (isStopped) { + return CompletableResultCode.ofFailure(); + } + finishedLogItems.addAll(logs); + return CompletableResultCode.ofSuccess(); + } + + @Override + public CompletableResultCode flush() { + return CompletableResultCode.ofSuccess(); + } + + /** + * Clears the internal {@code List} of finished {@code Log}s. + * + *

      Any subsequent call to export() function on this exporter, will return {@code + * CompletableResultCode.ofFailure()} + */ + @Override + public CompletableResultCode shutdown() { + isStopped = true; + finishedLogItems.clear(); + return CompletableResultCode.ofSuccess(); + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporter.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporter.java index 78432ca1e52..38b2c1e2fa6 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporter.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporter.java @@ -9,6 +9,7 @@ import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; import io.opentelemetry.sdk.metrics.export.MetricExporter; import java.util.ArrayList; import java.util.Collection; @@ -20,60 +21,60 @@ /** * A {@link MetricExporter} implementation that can be used to test OpenTelemetry integration. * - *

      Can be created using {@code InMemoryMetricExporter.create()} + *

      Can be created using {@link #create()} or configured using {@link #builder()}. * *

      Example usage: * - *

      
      - * public class InMemoryMetricExporterExample {
      + * 
      {@code
      + * // class MyClassTest {
      + * //   private final InMemoryMetricExporter exporter = InMemoryMetricExporter.create();
      + * //   private final SdkMeterProvider meterProvider =
      + * //       SdkMeterProvider.builder()
      + * //           .registerMetricReader(PeriodicMetricReader.builder(exporter).build())
      + * //           .build();
      + * //
      + * //   @Test
      + * //   public void getFinishedMetricItems() {
      + * //     LongCounter counter = meterProvider.get("test-scope").counterBuilder("counter").build();
      + * //     counter.add(1);
      + * //     meterProvider.forceFlush().join(10, TimeUnit.SECONDS);
      + * //
      + * //     assertThat(exporter.getFinishedMetricItems()).hasSize(1);
      + * //   }
      + * // }
      + * }
      * - * // creating InMemoryMetricExporter - * private final InMemoryMetricExporter exporter = InMemoryMetricExporter.create(); - * private final MeterSdkProvider meterSdkProvider = OpenTelemetrySdk.getMeterProvider(); - * private final Meter meter = meterSdkProvider.get("InMemoryMetricExporterExample"); - * private IntervalMetricReader intervalMetricReader; - * - * void setup() { - * intervalMetricReader = - * IntervalMetricReader.builder() - * .setMetricExporter(exporter) - * .setMetricProducers(Collections.singletonList(meterSdkProvider.getMetricProducer())) - * .setExportIntervalMillis(1000) - * .build(); - * } - * - * LongCounter generateLongCounterMeter(String name) { - * return meter.longCounterBuilder(name).setDescription("Sample LongCounter").build(); - * } - * - * public static void main(String[] args) throws InterruptedException { - * InMemoryMetricExporterExample example = new InMemoryMetricExporterExample(); - * example.setup(); - * example.generateLongCounterMeter("counter-1"); - * } - * } - *
      + * @since 1.14.0 */ public final class InMemoryMetricExporter implements MetricExporter { private final Queue finishedMetricItems = new ConcurrentLinkedQueue<>(); - private final AggregationTemporality aggregationTemporality; + private final AggregationTemporalitySelector aggregationTemporalitySelector; private boolean isStopped = false; - private InMemoryMetricExporter(AggregationTemporality aggregationTemporality) { - this.aggregationTemporality = aggregationTemporality; + InMemoryMetricExporter(AggregationTemporalitySelector aggregationTemporalitySelector) { + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + } + + /** + * Creates an {@link InMemoryMetricExporterBuilder} with defaults. + * + * @return a builder with always-cumulative {@link AggregationTemporalitySelector} + */ + public static InMemoryMetricExporterBuilder builder() { + return new InMemoryMetricExporterBuilder(); } /** - * Returns a new {@link InMemoryMetricExporter} with a aggregation temporality of {@link - * AggregationTemporality#CUMULATIVE}. + * Returns a new {@link InMemoryMetricExporter} with cumulative aggregation temporality for all + * instrument types. */ public static InMemoryMetricExporter create() { - return create(AggregationTemporality.CUMULATIVE); + return builder().build(); } /** Returns a new {@link InMemoryMetricExporter} with the given {@code aggregationTemporality}. */ public static InMemoryMetricExporter create(AggregationTemporality aggregationTemporality) { - return new InMemoryMetricExporter(aggregationTemporality); + return builder().setAggregationTemporalitySelector(unused -> aggregationTemporality).build(); } /** @@ -96,7 +97,7 @@ public void reset() { @Override public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return aggregationTemporality; + return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); } /** diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterBuilder.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterBuilder.java new file mode 100644 index 00000000000..324168e4e9a --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterBuilder.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.exporter; + +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import java.util.Objects; + +/** Builder for {@link InMemoryMetricExporter}. */ +public final class InMemoryMetricExporterBuilder { + private AggregationTemporalitySelector aggregationTemporalitySelector = + AggregationTemporalitySelector.alwaysCumulative(); + + InMemoryMetricExporterBuilder() {} + + /** + * Sets the {@link AggregationTemporalitySelector} used by {@link + * InMemoryMetricExporter#getAggregationTemporality(InstrumentType)}. + * + *

      If unset, defaults to {@link AggregationTemporalitySelector#alwaysCumulative()}. + * + * @param aggregationTemporalitySelector the {@link AggregationTemporalitySelector} to set + * @return this {@link InMemoryMetricExporterBuilder} + */ + public InMemoryMetricExporterBuilder setAggregationTemporalitySelector( + AggregationTemporalitySelector aggregationTemporalitySelector) { + Objects.requireNonNull(aggregationTemporalitySelector, "aggregationTemporalitySelector"); + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + return this; + } + + /** Constructs an {@link InMemoryMetricExporter} based on the builder's values. */ + public InMemoryMetricExporter build() { + return new InMemoryMetricExporter(aggregationTemporalitySelector); + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReader.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReader.java index eb6a65f3e23..45845a85791 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReader.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReader.java @@ -5,13 +5,18 @@ package io.opentelemetry.sdk.testing.exporter; +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; + import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.Aggregation; import io.opentelemetry.sdk.metrics.InstrumentType; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; import io.opentelemetry.sdk.metrics.export.CollectionRegistration; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; import io.opentelemetry.sdk.metrics.export.MetricReader; -import io.opentelemetry.sdk.metrics.internal.export.MetricProducer; import java.util.Collection; import java.util.Collections; import java.util.concurrent.atomic.AtomicBoolean; @@ -28,7 +33,7 @@ * private final InMemoryMetricReader reader = InMemoryMetricReader.create(); * private final SdkMeterProvider sdkMeterProvider = SdkMeterProvider.builder().registerMetricReader(reader).build(); * private final Meter meter = sdkMeterProvider.get("example"); - * private final LongCounter metricCallCount = meter.counterBuilder("num_collects"); + * private final LongCounter metricCallCount = meter.counterBuilder("num_collects").build(); * * public void printMetrics() { * metricCallCount.add(1); @@ -41,24 +46,63 @@ * } * } * + * + * @since 1.14.0 */ public class InMemoryMetricReader implements MetricReader { - private final AggregationTemporality aggregationTemporality; + private final AggregationTemporalitySelector aggregationTemporalitySelector; + private final DefaultAggregationSelector defaultAggregationSelector; private final AtomicBoolean isShutdown = new AtomicBoolean(false); - private volatile MetricProducer metricProducer = MetricProducer.noop(); + private volatile CollectionRegistration collectionRegistration = CollectionRegistration.noop(); + private final MemoryMode memoryMode; + + /** + * Creates an {@link InMemoryMetricReaderBuilder} with defaults. + * + * @return a builder with always-cumulative {@link AggregationTemporalitySelector}, default {@link + * DefaultAggregationSelector} and {@link MemoryMode#IMMUTABLE_DATA} {@link MemoryMode} + * @since 1.31.0 + */ + public static InMemoryMetricReaderBuilder builder() { + return new InMemoryMetricReaderBuilder(); + } /** Returns a new {@link InMemoryMetricReader}. */ public static InMemoryMetricReader create() { - return new InMemoryMetricReader(AggregationTemporality.CUMULATIVE); + return new InMemoryMetricReader( + AggregationTemporalitySelector.alwaysCumulative(), DefaultAggregationSelector.getDefault()); + } + + /** + * Returns a new {@link InMemoryMetricReader}. + * + * @since 1.26.0 + */ + public static InMemoryMetricReader create( + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector) { + return new InMemoryMetricReader(aggregationTemporalitySelector, defaultAggregationSelector); } /** Creates a new {@link InMemoryMetricReader} that prefers DELTA aggregation. */ public static InMemoryMetricReader createDelta() { - return new InMemoryMetricReader(AggregationTemporality.DELTA); + return new InMemoryMetricReader( + unused -> AggregationTemporality.DELTA, DefaultAggregationSelector.getDefault()); + } + + private InMemoryMetricReader( + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector) { + this(aggregationTemporalitySelector, defaultAggregationSelector, IMMUTABLE_DATA); } - private InMemoryMetricReader(AggregationTemporality aggregationTemporality) { - this.aggregationTemporality = aggregationTemporality; + InMemoryMetricReader( + AggregationTemporalitySelector aggregationTemporalitySelector, + DefaultAggregationSelector defaultAggregationSelector, + MemoryMode memoryMode) { + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + this.defaultAggregationSelector = defaultAggregationSelector; + this.memoryMode = memoryMode; } /** Returns all metrics accumulated since the last call. */ @@ -66,17 +110,22 @@ public Collection collectAllMetrics() { if (isShutdown.get()) { return Collections.emptyList(); } - return metricProducer.collectAllMetrics(); + return collectionRegistration.collectAllMetrics(); } @Override - public void register(CollectionRegistration registration) { - this.metricProducer = MetricProducer.asMetricProducer(registration); + public void register(CollectionRegistration collectionRegistration) { + this.collectionRegistration = collectionRegistration; } @Override public AggregationTemporality getAggregationTemporality(InstrumentType instrumentType) { - return aggregationTemporality; + return aggregationTemporalitySelector.getAggregationTemporality(instrumentType); + } + + @Override + public Aggregation getDefaultAggregation(InstrumentType instrumentType) { + return defaultAggregationSelector.getDefaultAggregation(instrumentType); } @Override @@ -91,8 +140,13 @@ public CompletableResultCode shutdown() { return CompletableResultCode.ofSuccess(); } + @Override + public MemoryMode getMemoryMode() { + return memoryMode; + } + @Override public String toString() { - return "InMemoryMetricReader{aggregationTemporality=" + aggregationTemporality + "}"; + return "InMemoryMetricReader{}"; } } diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderBuilder.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderBuilder.java new file mode 100644 index 00000000000..9ee5f1ee7ee --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderBuilder.java @@ -0,0 +1,78 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.exporter; + +import static io.opentelemetry.sdk.common.export.MemoryMode.IMMUTABLE_DATA; + +import io.opentelemetry.sdk.common.export.MemoryMode; +import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.DefaultAggregationSelector; + +/** + * Builder for {@link InMemoryMetricReader}. + * + * @since 1.31.0 + */ +public final class InMemoryMetricReaderBuilder { + private AggregationTemporalitySelector aggregationTemporalitySelector = + AggregationTemporalitySelector.alwaysCumulative(); + private DefaultAggregationSelector defaultAggregationSelector = + DefaultAggregationSelector.getDefault(); + private MemoryMode memoryMode = IMMUTABLE_DATA; + + /** + * Creates an {@link InMemoryMetricReaderBuilder} with defaults. + * + *

      Creates a builder with always-cumulative {@link AggregationTemporalitySelector}, default + * {@link DefaultAggregationSelector} and {@link MemoryMode#IMMUTABLE_DATA} {@link MemoryMode} + */ + InMemoryMetricReaderBuilder() {} + + /** + * Sets the {@link AggregationTemporalitySelector} used by {@link + * InMemoryMetricReader#getAggregationTemporality(InstrumentType)}. + * + * @param aggregationTemporalitySelector the {@link AggregationTemporalitySelector} to set + * @return this {@link InMemoryMetricReaderBuilder} + */ + public InMemoryMetricReaderBuilder setAggregationTemporalitySelector( + AggregationTemporalitySelector aggregationTemporalitySelector) { + this.aggregationTemporalitySelector = aggregationTemporalitySelector; + return this; + } + + /** + * Sets the {@link DefaultAggregationSelector} used by {@link + * InMemoryMetricReader#getDefaultAggregation(InstrumentType)}. + * + * @param defaultAggregationSelector the {@link DefaultAggregationSelector} to set + * @return this {@link InMemoryMetricReaderBuilder} + */ + @SuppressWarnings("unused") + public InMemoryMetricReaderBuilder setDefaultAggregationSelector( + DefaultAggregationSelector defaultAggregationSelector) { + this.defaultAggregationSelector = defaultAggregationSelector; + return this; + } + + /** + * Sets the {@link MemoryMode}. + * + * @param memoryMode the {@link MemoryMode} to set + * @return this {@link InMemoryMetricReaderBuilder} + */ + public InMemoryMetricReaderBuilder setMemoryMode(MemoryMode memoryMode) { + this.memoryMode = memoryMode; + return this; + } + + /** Constructs a {@link InMemoryMetricReader} based on the builder's values. */ + public InMemoryMetricReader build() { + return new InMemoryMetricReader( + aggregationTemporalitySelector, defaultAggregationSelector, memoryMode); + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemorySpanExporter.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemorySpanExporter.java index 7c1a4f0eb68..0c2768d8b7f 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemorySpanExporter.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/exporter/InMemorySpanExporter.java @@ -22,19 +22,18 @@ * *

      {@code
        * // class MyClassTest {
      - * //   private final Tracer tracer = new TracerSdk();
        * //   private final InMemorySpanExporter testExporter = InMemorySpanExporter.create();
      - * //
      - * //   @Before
      - * //   public void setup() {
      - * //     tracer.addSpanProcessor(SimpleSampledSpansProcessor.builder(testExporter).build());
      - * //   }
      + * //   private final SdkTracerProvider tracerProvider = SdkTracerProvider
      + * //     .builder()
      + * //     .addSpanProcessor(SimpleSpanProcessor.create(testExporter))
      + * //     .build();
        * //
        * //   @Test
        * //   public void getFinishedSpanData() {
      + * //     Tracer tracer = tracerProvider.tracerBuilder("test-scope").build();
        * //     tracer.spanBuilder("span").startSpan().end();
        * //
      - * //     List spanItems = exporter.getFinishedSpanItems();
      + * //     List spanItems = testExporter.getFinishedSpanItems();
        * //     assertThat(spanItems).isNotNull();
        * //     assertThat(spanItems.size()).isEqualTo(1);
        * //     assertThat(spanItems.get(0).getName()).isEqualTo("span");
      diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRule.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRule.java
      index a8f46977d1d..0fb0a7fd181 100644
      --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRule.java
      +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRule.java
      @@ -7,13 +7,19 @@
       
       import io.opentelemetry.api.GlobalOpenTelemetry;
       import io.opentelemetry.api.OpenTelemetry;
      +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator;
       import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
       import io.opentelemetry.context.propagation.ContextPropagators;
      +import io.opentelemetry.context.propagation.TextMapPropagator;
       import io.opentelemetry.sdk.OpenTelemetrySdk;
      +import io.opentelemetry.sdk.logs.SdkLoggerProvider;
      +import io.opentelemetry.sdk.logs.data.LogRecordData;
      +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor;
       import io.opentelemetry.sdk.metrics.SdkMeterProvider;
       import io.opentelemetry.sdk.metrics.data.AggregationTemporality;
       import io.opentelemetry.sdk.metrics.data.MetricData;
       import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil;
      +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter;
       import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
       import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter;
       import io.opentelemetry.sdk.trace.SdkTracerProvider;
      @@ -29,7 +35,7 @@
        *
        * 
      {@code
        * // public class CoolTest {
      - * //   @Rule public OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create();
      + * //   @Rule public OpenTelemetryRule otelTesting = OpenTelemetryRule.create();
        * //
        * //   private Tracer tracer;
        * //   private Meter meter;
      @@ -71,27 +77,42 @@ public static OpenTelemetryRule create() {
           SdkMeterProvider meterProvider =
               SdkMeterProvider.builder().registerMetricReader(metricReader).build();
       
      +    InMemoryLogRecordExporter logRecordExporter = InMemoryLogRecordExporter.create();
      +
      +    SdkLoggerProvider loggerProvider =
      +        SdkLoggerProvider.builder()
      +            .addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter))
      +            .build();
      +
           OpenTelemetrySdk openTelemetry =
               OpenTelemetrySdk.builder()
      -            .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
      +            .setPropagators(
      +                ContextPropagators.create(
      +                    TextMapPropagator.composite(
      +                        W3CTraceContextPropagator.getInstance(),
      +                        W3CBaggagePropagator.getInstance())))
                   .setTracerProvider(tracerProvider)
                   .setMeterProvider(meterProvider)
      +            .setLoggerProvider(loggerProvider)
                   .build();
       
      -    return new OpenTelemetryRule(openTelemetry, spanExporter, metricReader);
      +    return new OpenTelemetryRule(openTelemetry, spanExporter, metricReader, logRecordExporter);
         }
       
         private final OpenTelemetrySdk openTelemetry;
         private final InMemorySpanExporter spanExporter;
         private final InMemoryMetricReader metricReader;
      +  private final InMemoryLogRecordExporter logRecordExporter;
       
         private OpenTelemetryRule(
             OpenTelemetrySdk openTelemetry,
             InMemorySpanExporter spanExporter,
      -      InMemoryMetricReader metricReader) {
      +      InMemoryMetricReader metricReader,
      +      InMemoryLogRecordExporter logRecordExporter) {
           this.openTelemetry = openTelemetry;
           this.spanExporter = spanExporter;
           this.metricReader = metricReader;
      +    this.logRecordExporter = logRecordExporter;
         }
       
         /** Returns the {@link OpenTelemetrySdk} created by this extension. */
      @@ -104,11 +125,24 @@ public List getSpans() {
           return spanExporter.getFinishedSpanItems();
         }
       
      -  /** Returns the current {@link MetricData} in {@link AggregationTemporality#CUMULATIVE} format. */
      +  /**
      +   * Returns the current {@link MetricData} in {@link AggregationTemporality#CUMULATIVE} format.
      +   *
      +   * @since 1.15.0
      +   */
         public List getMetrics() {
           return new ArrayList<>(metricReader.collectAllMetrics());
         }
       
      +  /**
      +   * Returns all the exported {@link LogRecordData} so far.
      +   *
      +   * @since 1.32.0
      +   */
      +  public List getLogRecords() {
      +    return new ArrayList<>(logRecordExporter.getFinishedLogRecordItems());
      +  }
      +
         /**
          * Clears the collected exported {@link SpanData}. Consider making your test smaller instead of
          * manually clearing state using this method.
      @@ -117,17 +151,32 @@ public void clearSpans() {
           spanExporter.reset();
         }
       
      -  /** Clears all registered metric instruments, such that {@link #getMetrics()} is empty. */
      +  /**
      +   * Clears all registered metric instruments, such that {@link #getMetrics()} is empty.
      +   *
      +   * @since 1.15.0
      +   */
         public void clearMetrics() {
           SdkMeterProviderUtil.resetForTest(openTelemetry.getSdkMeterProvider());
         }
       
      +  /**
      +   * Clears the collected exported {@link LogRecordData}. Consider making your test smaller instead
      +   * of manually clearing state using this method.
      +   *
      +   * @since 1.32.0
      +   */
      +  public void clearLogRecords() {
      +    logRecordExporter.reset();
      +  }
      +
         @Override
         protected void before() {
           GlobalOpenTelemetry.resetForTest();
           GlobalOpenTelemetry.set(openTelemetry);
           clearSpans();
           clearMetrics();
      +    clearLogRecords();
         }
       
         @Override
      diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtension.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtension.java
      index 5ef05161930..3e9d84a815c 100644
      --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtension.java
      +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtension.java
      @@ -9,25 +9,27 @@
       
       import io.opentelemetry.api.GlobalOpenTelemetry;
       import io.opentelemetry.api.OpenTelemetry;
      +import io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator;
       import io.opentelemetry.api.trace.propagation.W3CTraceContextPropagator;
       import io.opentelemetry.context.propagation.ContextPropagators;
      +import io.opentelemetry.context.propagation.TextMapPropagator;
       import io.opentelemetry.sdk.OpenTelemetrySdk;
      +import io.opentelemetry.sdk.logs.SdkLoggerProvider;
      +import io.opentelemetry.sdk.logs.data.LogRecordData;
      +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor;
       import io.opentelemetry.sdk.metrics.SdkMeterProvider;
       import io.opentelemetry.sdk.metrics.data.AggregationTemporality;
       import io.opentelemetry.sdk.metrics.data.MetricData;
       import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil;
       import io.opentelemetry.sdk.testing.assertj.TracesAssert;
      +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter;
       import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
       import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter;
       import io.opentelemetry.sdk.trace.SdkTracerProvider;
       import io.opentelemetry.sdk.trace.data.SpanData;
       import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
       import java.util.ArrayList;
      -import java.util.Comparator;
      -import java.util.LinkedHashMap;
       import java.util.List;
      -import java.util.Map;
      -import java.util.stream.Collectors;
       import org.junit.jupiter.api.extension.AfterAllCallback;
       import org.junit.jupiter.api.extension.BeforeAllCallback;
       import org.junit.jupiter.api.extension.BeforeEachCallback;
      @@ -77,27 +79,42 @@ public static OpenTelemetryExtension create() {
           SdkMeterProvider meterProvider =
               SdkMeterProvider.builder().registerMetricReader(metricReader).build();
       
      +    InMemoryLogRecordExporter logRecordExporter = InMemoryLogRecordExporter.create();
      +
      +    SdkLoggerProvider loggerProvider =
      +        SdkLoggerProvider.builder()
      +            .addLogRecordProcessor(SimpleLogRecordProcessor.create(logRecordExporter))
      +            .build();
      +
           OpenTelemetrySdk openTelemetry =
               OpenTelemetrySdk.builder()
      -            .setPropagators(ContextPropagators.create(W3CTraceContextPropagator.getInstance()))
      +            .setPropagators(
      +                ContextPropagators.create(
      +                    TextMapPropagator.composite(
      +                        W3CTraceContextPropagator.getInstance(),
      +                        W3CBaggagePropagator.getInstance())))
                   .setTracerProvider(tracerProvider)
                   .setMeterProvider(meterProvider)
      +            .setLoggerProvider(loggerProvider)
                   .build();
       
      -    return new OpenTelemetryExtension(openTelemetry, spanExporter, metricReader);
      +    return new OpenTelemetryExtension(openTelemetry, spanExporter, metricReader, logRecordExporter);
         }
       
         private final OpenTelemetrySdk openTelemetry;
         private final InMemorySpanExporter spanExporter;
         private final InMemoryMetricReader metricReader;
      +  private final InMemoryLogRecordExporter logRecordExporter;
       
         private OpenTelemetryExtension(
             OpenTelemetrySdk openTelemetry,
             InMemorySpanExporter spanExporter,
      -      InMemoryMetricReader metricReader) {
      +      InMemoryMetricReader metricReader,
      +      InMemoryLogRecordExporter logRecordExporter) {
           this.openTelemetry = openTelemetry;
           this.spanExporter = spanExporter;
           this.metricReader = metricReader;
      +    this.logRecordExporter = logRecordExporter;
         }
       
         /** Returns the {@link OpenTelemetrySdk} created by this extension. */
      @@ -110,25 +127,30 @@ public List getSpans() {
           return spanExporter.getFinishedSpanItems();
         }
       
      -  /** Returns the current {@link MetricData} in {@link AggregationTemporality#CUMULATIVE} format. */
      +  /**
      +   * Returns the current {@link MetricData} in {@link AggregationTemporality#CUMULATIVE} format.
      +   *
      +   * @since 1.15.0
      +   */
         public List getMetrics() {
           return new ArrayList<>(metricReader.collectAllMetrics());
         }
       
      +  /**
      +   * Returns all the exported {@link LogRecordData} so far.
      +   *
      +   * @since 1.32.0
      +   */
      +  public List getLogRecords() {
      +    return new ArrayList<>(logRecordExporter.getFinishedLogRecordItems());
      +  }
      +
         /**
          * Returns a {@link TracesAssert} for asserting on the currently exported traces. This method
          * requires AssertJ to be on the classpath.
          */
         public TracesAssert assertTraces() {
      -    Map> traces =
      -        getSpans().stream()
      -            .collect(
      -                Collectors.groupingBy(
      -                    SpanData::getTraceId, LinkedHashMap::new, Collectors.toList()));
      -    for (List trace : traces.values()) {
      -      trace.sort(Comparator.comparing(SpanData::getStartEpochNanos));
      -    }
      -    return assertThat(traces.values());
      +    return assertThat(spanExporter.getFinishedSpanItems());
         }
       
         /**
      @@ -139,15 +161,30 @@ public void clearSpans() {
           spanExporter.reset();
         }
       
      -  /** Clears all registered metric instruments, such that {@link #getMetrics()} is empty. */
      +  /**
      +   * Clears all registered metric instruments, such that {@link #getMetrics()} is empty.
      +   *
      +   * @since 1.15.0
      +   */
         public void clearMetrics() {
           SdkMeterProviderUtil.resetForTest(openTelemetry.getSdkMeterProvider());
         }
       
      +  /**
      +   * Clears the collected exported {@link LogRecordData}. Consider making your test smaller instead
      +   * of manually clearing state using this method.
      +   *
      +   * @since 1.32.0
      +   */
      +  public void clearLogRecords() {
      +    logRecordExporter.reset();
      +  }
      +
         @Override
         public void beforeEach(ExtensionContext context) {
           clearSpans();
           clearMetrics();
      +    clearLogRecords();
         }
       
         @Override
      @@ -159,5 +196,8 @@ public void beforeAll(ExtensionContext context) {
         @Override
         public void afterAll(ExtensionContext context) {
           GlobalOpenTelemetry.resetForTest();
      +    if (context.getParent().isPresent() && !context.getParent().get().getTestClass().isPresent()) {
      +      openTelemetry.close();
      +    }
         }
       }
      diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/logs/TestLogRecordData.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/logs/TestLogRecordData.java
      new file mode 100644
      index 00000000000..7d9c6d8beb4
      --- /dev/null
      +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/logs/TestLogRecordData.java
      @@ -0,0 +1,187 @@
      +/*
      + * Copyright The OpenTelemetry Authors
      + * SPDX-License-Identifier: Apache-2.0
      + */
      +
      +package io.opentelemetry.sdk.testing.logs;
      +
      +import com.google.auto.value.AutoValue;
      +import io.opentelemetry.api.common.Attributes;
      +import io.opentelemetry.api.common.Value;
      +import io.opentelemetry.api.logs.Severity;
      +import io.opentelemetry.api.trace.SpanContext;
      +import io.opentelemetry.sdk.common.InstrumentationScopeInfo;
      +import io.opentelemetry.sdk.logs.data.Body;
      +import io.opentelemetry.sdk.logs.data.LogRecordData;
      +import io.opentelemetry.sdk.resources.Resource;
      +import java.time.Instant;
      +import java.util.concurrent.TimeUnit;
      +import javax.annotation.Nullable;
      +import javax.annotation.concurrent.Immutable;
      +
      +/**
      + * Immutable representation of {@link LogRecordData}.
      + *
      + * @since 1.27.0
      + */
      +@Immutable
      +@AutoValue
      +@AutoValue.CopyAnnotations
      +// Carry suppression for Body to AutoValue implementation via @AutoValue.CopyAnnotations
      +@SuppressWarnings("deprecation")
      +public abstract class TestLogRecordData implements LogRecordData {
      +
      +  /** Creates a new Builder for creating an {@link LogRecordData} instance. */
      +  public static Builder builder() {
      +    return new AutoValue_TestLogRecordData.Builder()
      +        .setResource(Resource.empty())
      +        .setInstrumentationScopeInfo(InstrumentationScopeInfo.empty())
      +        .setTimestamp(0, TimeUnit.NANOSECONDS)
      +        .setObservedTimestamp(0, TimeUnit.NANOSECONDS)
      +        .setSpanContext(SpanContext.getInvalid())
      +        .setSeverity(Severity.UNDEFINED_SEVERITY_NUMBER)
      +        .setAttributes(Attributes.empty())
      +        .setTotalAttributeCount(0);
      +  }
      +
      +  @Deprecated
      +  public Body getBody() {
      +    Value valueBody = getBodyValue();
      +    return valueBody == null ? Body.empty() : Body.string(valueBody.asString());
      +  }
      +
      +  /**
      +   * {@inheritDoc}
      +   *
      +   * @since 1.42.0
      +   */
      +  @Override
      +  @Nullable
      +  public abstract Value getBodyValue();
      +
      +  @Override
      +  @Nullable
      +  public abstract String getEventName();
      +
      +  TestLogRecordData() {}
      +
      +  /** A {@code Builder} class for {@link TestLogRecordData}. */
      +  @AutoValue.Builder
      +  public abstract static class Builder {
      +
      +    abstract TestLogRecordData autoBuild();
      +
      +    /** Create a new {@link LogRecordData} instance from the data in this. */
      +    public TestLogRecordData build() {
      +      return autoBuild();
      +    }
      +
      +    /** Set the {@link Resource}. */
      +    public abstract Builder setResource(Resource resource);
      +
      +    /** Sets the {@link InstrumentationScopeInfo}. */
      +    public abstract Builder setInstrumentationScopeInfo(
      +        InstrumentationScopeInfo instrumentationScopeInfo);
      +
      +    /**
      +     * Set the epoch {@code timestamp}, using the instant.
      +     *
      +     * 

      The {@code timestamp} is the time at which the log record occurred. + */ + public Builder setTimestamp(Instant instant) { + return setTimestampEpochNanos( + TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano()); + } + + /** + * Set the epoch {@code timestamp}, using the timestamp and unit. + * + *

      The {@code timestamp} is the time at which the log record occurred. + */ + public Builder setTimestamp(long timestamp, TimeUnit unit) { + return setTimestampEpochNanos(unit.toNanos(timestamp)); + } + + /** + * Set the epoch {@code timestamp}. + * + *

      The {@code timestamp} is the time at which the log record occurred. + */ + abstract Builder setTimestampEpochNanos(long epochNanos); + + /** + * Set the {@code observedTimestamp}, using the instant. + * + *

      The {@code observedTimestamp} is the time at which the log record was observed. + */ + public Builder setObservedTimestamp(Instant instant) { + return setObservedTimestampEpochNanos( + TimeUnit.SECONDS.toNanos(instant.getEpochSecond()) + instant.getNano()); + } + + /** + * Set the epoch {@code observedTimestamp}, using the timestamp and unit. + * + *

      The {@code observedTimestamp} is the time at which the log record was observed. + */ + public Builder setObservedTimestamp(long timestamp, TimeUnit unit) { + return setObservedTimestampEpochNanos(unit.toNanos(timestamp)); + } + + /** + * Set the epoch {@code observedTimestamp}. + * + *

      The {@code observedTimestamp} is the time at which the log record was observed. + */ + abstract Builder setObservedTimestampEpochNanos(long epochNanos); + + /** Set the span context. */ + public abstract Builder setSpanContext(SpanContext spanContext); + + /** Set the severity. */ + public abstract Builder setSeverity(Severity severity); + + /** Set the severity text. */ + public abstract Builder setSeverityText(String severityText); + + /** Set the body string. */ + public Builder setBody(String body) { + return setBodyValue(Value.of(body)); + } + + /** + * Set the body. + * + * @deprecated Use {@link #setBodyValue(Value)}. + */ + @Deprecated + public Builder setBody(Body body) { + if (body.getType() == Body.Type.STRING) { + setBodyValue(Value.of(body.asString())); + } else if (body.getType() == Body.Type.EMPTY) { + setBodyValue(null); + } + return this; + } + + /** + * Set the body. + * + * @since 1.42.0 + */ + public abstract Builder setBodyValue(@Nullable Value body); + + /** Set the attributes. */ + public abstract Builder setAttributes(Attributes attributes); + + /** Set the total attribute count. */ + public abstract Builder setTotalAttributeCount(int totalAttributeCount); + + /** + * Set the event name. + * + * @since 1.50.0 + */ + public abstract Builder setEventName(String eventName); + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/logs/package-info.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/logs/package-info.java new file mode 100644 index 00000000000..7b6b01d11d3 --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/logs/package-info.java @@ -0,0 +1,9 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +@ParametersAreNonnullByDefault +package io.opentelemetry.sdk.testing.logs; + +import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/metrics/TestMetricData.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/metrics/TestMetricData.java new file mode 100644 index 00000000000..238b0288e83 --- /dev/null +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/metrics/TestMetricData.java @@ -0,0 +1,93 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.metrics; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.metrics.data.Data; +import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramData; +import io.opentelemetry.sdk.metrics.data.GaugeData; +import io.opentelemetry.sdk.metrics.data.HistogramData; +import io.opentelemetry.sdk.metrics.data.LongPointData; +import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.MetricDataType; +import io.opentelemetry.sdk.metrics.data.SumData; +import io.opentelemetry.sdk.metrics.data.SummaryData; +import io.opentelemetry.sdk.resources.Resource; +import javax.annotation.concurrent.Immutable; + +/** + * Immutable representation of all data collected by the {@link + * io.opentelemetry.sdk.metrics.data.MetricData} class. + * + * @since 1.50.0 + */ +@Immutable +@AutoValue +public abstract class TestMetricData implements MetricData { + public static Builder builder() { + return new AutoValue_TestMetricData.Builder() + .setResource(Resource.empty()) + .setInstrumentationScopeInfo(InstrumentationScopeInfo.empty()); + } + + /** A builder for {@link TestMetricData}. */ + @AutoValue.Builder + public abstract static class Builder { + abstract TestMetricData autoBuild(); + + public TestMetricData build() { + return autoBuild(); + } + + public abstract Builder setResource(Resource resource); + + public abstract Builder setName(String name); + + public abstract Builder setDescription(String description); + + public abstract Builder setUnit(String unit); + + // Make setType package-private to restrict direct access + abstract Builder setType(MetricDataType type); + + // Keep the generic setData method for internal use + abstract Builder setData(Data data); + + // Add specific setData overloads for each metric data type + public Builder setExponentialHistogramData(ExponentialHistogramData data) { + return setType(MetricDataType.EXPONENTIAL_HISTOGRAM).setData(data); + } + + public Builder setHistogramData(HistogramData data) { + return setType(MetricDataType.HISTOGRAM).setData(data); + } + + public Builder setLongSumData(SumData data) { + return setType(MetricDataType.LONG_SUM).setData(data); + } + + public Builder setDoubleSumData(SumData data) { + return setType(MetricDataType.DOUBLE_SUM).setData(data); + } + + public Builder setDoubleGaugeData(GaugeData data) { + return setType(MetricDataType.DOUBLE_GAUGE).setData(data); + } + + public Builder setLongGaugeData(GaugeData data) { + return setType(MetricDataType.LONG_GAUGE).setData(data); + } + + public Builder setSummaryData(SummaryData data) { + return setType(MetricDataType.SUMMARY).setData(data); + } + + public abstract Builder setInstrumentationScopeInfo( + InstrumentationScopeInfo instrumentationScopeInfo); + } +} diff --git a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/trace/TestSpanData.java b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/trace/TestSpanData.java index 1f1b577fd05..1743c46a3f5 100644 --- a/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/trace/TestSpanData.java +++ b/sdk/testing/src/main/java/io/opentelemetry/sdk/testing/trace/TestSpanData.java @@ -9,8 +9,9 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.InstrumentationScopeUtil; +import io.opentelemetry.sdk.common.internal.InstrumentationScopeUtil; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.LinkData; @@ -59,10 +60,13 @@ public final boolean hasEnded() { @Override @Deprecated - public io.opentelemetry.sdk.common.InstrumentationLibraryInfo getInstrumentationLibraryInfo() { + public InstrumentationLibraryInfo getInstrumentationLibraryInfo() { return InstrumentationScopeUtil.toInstrumentationLibraryInfo(getInstrumentationScopeInfo()); } + @Override + public abstract InstrumentationScopeInfo getInstrumentationScopeInfo(); + /** A {@code Builder} class for {@link TestSpanData}. */ @AutoValue.Builder public abstract static class Builder { @@ -119,7 +123,7 @@ public TestSpanData build() { */ @Deprecated public Builder setInstrumentationLibraryInfo( - io.opentelemetry.sdk.common.InstrumentationLibraryInfo instrumentationLibraryInfo) { + InstrumentationLibraryInfo instrumentationLibraryInfo) { return setInstrumentationScopeInfo( InstrumentationScopeUtil.toInstrumentationScopeInfo(instrumentationLibraryInfo)); } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AssertUtilTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AssertUtilTest.java new file mode 100644 index 00000000000..3a29fff3c13 --- /dev/null +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AssertUtilTest.java @@ -0,0 +1,97 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +class AssertUtilTest { + private static final AttributeKey WARM = AttributeKey.booleanKey("warm"); + private static final AttributeKey TEMPERATURE = AttributeKey.longKey("temperature"); + private static final AttributeKey LENGTH = AttributeKey.doubleKey("length"); + private static final AttributeKey> COLORS = AttributeKey.stringArrayKey("colors"); + private static final AttributeKey> BYTES = AttributeKey.valueKey("bytes"); + + private static final Attributes ATTRIBUTES = + Attributes.builder() + .put(WARM, true) + .put(TEMPERATURE, 30) + .put(LENGTH, 1.2) + .put(COLORS, Arrays.asList("red", "blue")) + .put(BYTES, Value.of(new byte[] {1, 2, 3})) + .build(); + + @Test + void assertAttributesShouldThrowIfNoAttributeMatch() { + List assertions = Arrays.asList(equalTo(WARM, false)); + + assertThatThrownBy(() -> AssertUtil.assertAttributes(ATTRIBUTES, assertions)) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertAttributesShouldNotThrowIfSomeAttributesMatch() { + List assertions = Arrays.asList(equalTo(WARM, true)); + + AssertUtil.assertAttributes(ATTRIBUTES, assertions); + } + + @Test + void assertAttributesShouldNotThrowIfAllAttributesMatch() { + List assertions = + Arrays.asList( + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(LENGTH, 1.2), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3}))); + + AssertUtil.assertAttributes(ATTRIBUTES, assertions); + } + + @Test + void assertAttributesShouldNotThrowIfEqualToNullAndAttributeNotSet() { + List assertions = Arrays.asList(equalTo(WARM, null)); + + AssertUtil.assertAttributes(Attributes.empty(), assertions); + } + + @Test + void assertAttributesExactlyShouldThrowIfNoAttributeMatch() { + List assertions = Arrays.asList(equalTo(WARM, false)); + + assertThatThrownBy(() -> AssertUtil.assertAttributesExactly(ATTRIBUTES, assertions)) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertAttributesExactlyShouldThrowIfSomeAttributesMatch() { + List assertions = Arrays.asList(equalTo(WARM, true)); + + assertThatThrownBy(() -> AssertUtil.assertAttributesExactly(ATTRIBUTES, assertions)) + .isInstanceOf(AssertionError.class); + } + + @Test + void assertAttributesExactlyShouldNotThrowIfAllAttributesMatch() { + List assertions = + Arrays.asList( + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(LENGTH, 1.2), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3}))); + + AssertUtil.assertAttributesExactly(ATTRIBUTES, assertions); + } +} diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java new file mode 100644 index 00000000000..e64fb2382bf --- /dev/null +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/AttributeAssertionTest.java @@ -0,0 +1,30 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import org.assertj.core.api.AbstractAssert; +import org.junit.jupiter.api.Test; + +class AttributeAssertionTest { + + @Test + void nullAttr_errorMessageContainsAttrName() { + AttributeKey key = AttributeKey.stringKey("flib"); + + assertThatThrownBy(() -> + AttributeAssertion.create(key, AbstractAssert::isNotNull) + .getAssertion() + .accept(AttributeAssertion.attributeValueAssertion(key, null))) + .isInstanceOf(AssertionError.class) + .hasMessage( + "[STRING attribute 'flib'] " + + System.lineSeparator() + + "Expecting actual not to be null"); + } +} diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java new file mode 100644 index 00000000000..2df7107f865 --- /dev/null +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/LogAssertionsTest.java @@ -0,0 +1,352 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.satisfies; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.KeyValue; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.api.logs.Severity; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; + +public class LogAssertionsTest { + private static final Resource RESOURCE = + Resource.create(Attributes.builder().put("dog", "bark").put("dog is cute", true).build()); + private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = + InstrumentationScopeInfo.create("instrumentation_library"); + private static final String TRACE_ID = "00000000000000010000000000000002"; + private static final String SPAN_ID = "0000000000000003"; + + private static final AttributeKey DOG = stringKey("dog"); + private static final Attributes ATTRIBUTES = + Attributes.builder() + .put("bear", "mya") + .put("warm", true) + .put("temperature", 30) + .put("length", 1.2) + .put("colors", "red", "blue") + .put("conditions", false, true) + .put("scores", 0L, 1L) + .put("coins", 0.01, 0.05, 0.1) + .put("bytes", Value.of(new byte[] {1, 2, 3})) + .build(); + + private static final LogRecordData LOG_DATA = + TestLogRecordData.builder() + .setResource(RESOURCE) + .setInstrumentationScopeInfo(INSTRUMENTATION_SCOPE_INFO) + .setEventName("event name") + .setTimestamp(100, TimeUnit.NANOSECONDS) + .setObservedTimestamp(200, TimeUnit.NANOSECONDS) + .setSpanContext( + SpanContext.create( + TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) + .setSeverity(Severity.INFO) + .setSeverityText("info") + .setBody("message") + .setAttributes(ATTRIBUTES) + .setTotalAttributeCount(999) + .build(); + + @Test + void passing() { + assertThat(LOG_DATA) + .hasResource(RESOURCE) + .hasResourceSatisfying(resource -> + resource + .hasSchemaUrl(null) + .hasAttribute(DOG, "bark") + .hasAttributes( + Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) + .hasAttributes(attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(2) + .containsEntry(stringKey("dog"), "bark") + .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) + .hasEntrySatisfying( + AttributeKey.booleanKey("dog is cute"), + value -> assertThat(value).isTrue()))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.startsWith("bar")), + satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) + .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) + .hasEventName("event name") + .hasTimestamp(100) + .hasObservedTimestamp(200) + .hasSpanContext( + SpanContext.create(TRACE_ID, SPAN_ID, TraceFlags.getDefault(), TraceState.getDefault())) + .hasSeverity(Severity.INFO) + .hasSeverityText("info") + .hasBody("message") + .hasAttributes(ATTRIBUTES) + .hasAttributes( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes) + .hasSize(9) + .containsEntry(stringKey("bear"), "mya") + .hasEntrySatisfying(stringKey("bear"), value -> assertThat(value).hasSize(3)) + .containsEntry("bear", "mya") + .containsEntry("warm", true) + .containsEntry("temperature", 30) + .containsEntry(longKey("temperature"), 30L) + .containsEntry(longKey("temperature"), 30) + .containsEntry("length", 1.2) + .containsEntry("colors", "red", "blue") + .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) + .containsEntry("conditions", false, true) + .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) + .containsEntry("scores", 0L, 1L) + .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsKey(stringKey("bear")) + .containsKey("bear") + .containsOnly( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3})))) + .hasAttributesSatisfying( + equalTo(stringKey("bear"), "mya"), + equalTo(AttributeKey.booleanArrayKey("conditions"), Arrays.asList(false, true))) + .hasAttributesSatisfyingExactly( + equalTo(stringKey("bear"), "mya"), + equalTo(AttributeKey.booleanKey("warm"), true), + equalTo(longKey("temperature"), 30L), + equalTo(AttributeKey.doubleKey("length"), 1.2), + equalTo(AttributeKey.stringArrayKey("colors"), Arrays.asList("red", "blue")), + equalTo(AttributeKey.booleanArrayKey("conditions"), Arrays.asList(false, true)), + equalTo(AttributeKey.longArrayKey("scores"), Arrays.asList(0L, 1L)), + equalTo(AttributeKey.doubleArrayKey("coins"), Arrays.asList(0.01, 0.05, 0.1)), + equalTo(AttributeKey.valueKey("bytes"), Value.of(new byte[] {1, 2, 3}))) + .hasTotalAttributeCount(999); + } + + @Test + void failure() { + assertThatThrownBy(() -> assertThat(LOG_DATA).hasResource(Resource.empty())); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying( + resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying( + resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying( + attributes -> assertThat(attributes).hasSize(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy( + () -> assertThat(LOG_DATA).hasInstrumentationScope(InstrumentationScopeInfo.empty())); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasEventName("foo")); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasTimestamp(200)); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasObservedTimestamp(100)); + SpanContext otherSpanContext = + SpanContext.create( + TRACE_ID, "0000000000000004", TraceFlags.getDefault(), TraceState.getDefault()); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasSpanContext(otherSpanContext)) + .hasMessage( + "Expected log to have span context <" + + otherSpanContext + + "> but was <" + + LOG_DATA.getSpanContext() + + ">"); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasSeverity(Severity.DEBUG)); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasSeverityText("warning")); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasBody("bar")); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasAttributes(Attributes.empty())) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasAttributes(attributeEntry("food", "burger"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes).containsEntry("cat", "bark"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes).containsKey(stringKey("cat")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes).containsKey("cat"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying( + attributes -> OpenTelemetryAssertions.assertThat(attributes).isEmpty())) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying( + attributes -> OpenTelemetryAssertions.assertThat(attributes).hasSize(33))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfying(attributes -> + OpenTelemetryAssertions.assertThat(attributes) + .hasEntrySatisfying( + stringKey("bear"), value -> assertThat(value).hasSize(2)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy( + () -> assertThat(LOG_DATA).hasAttributesSatisfying(equalTo(stringKey("bear"), "moo"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LOG_DATA) + .hasAttributesSatisfyingExactly( + equalTo(stringKey("bear"), "mya"), + equalTo(AttributeKey.booleanKey("warm"), true), + equalTo(longKey("temperature"), 30L), + equalTo(AttributeKey.doubleKey("length"), 1.2))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> assertThat(LOG_DATA).hasTotalAttributeCount(11)) + .isInstanceOf(AssertionError.class); + } + + @Test + void logBodyAssertions() { + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + Logger logger = loggerProvider.get("test.test"); + logger + .logRecordBuilder() + .setBody( + Value.of( + KeyValue.of("foostr", Value.of("bar")), + KeyValue.of("foobool", Value.of(true)), + KeyValue.of("foolong", Value.of(12L)), + KeyValue.of("foodbl", Value.of(12.0)), + KeyValue.of( + "foostra", Value.of(Value.of("bar"), Value.of("baz"), Value.of("buzz"))), + KeyValue.of( + "foolonga", + Value.of(Value.of(9), Value.of(0), Value.of(2), Value.of(1), Value.of(0))), + KeyValue.of( + "foodbla", + Value.of( + Value.of(9.1), Value.of(0.2), Value.of(2.3), Value.of(1.4), Value.of(0.5))), + KeyValue.of( + "fooboola", + Value.of(Value.of(true), Value.of(true), Value.of(true), Value.of(false))), + KeyValue.of("fooany", Value.of("grim")), + KeyValue.of("foobytes", Value.of(new byte[] {1, 2, 3})))) + .emit(); + List logs = exporter.getFinishedLogRecordItems(); + assertThat(logs).hasSize(1); + assertThat(logs.get(0)) + .hasBodyField("foostr", "bar") + .hasBodyField("foobool", true) + .hasBodyField("foolong", 12L) + .hasBodyField("foodbl", 12.0) + .hasBodyField("foostra", "bar", "baz", "buzz") + .hasBodyField("foolonga", 9, 0, 2, 1, 0) + .hasBodyField("foodbla", 9.1, 0.2, 2.3, 1.4, 0.5) + .hasBodyField("fooboola", true, true, true, false) + .hasBodyField("fooany", Value.of("grim")) + .hasBodyField("foobytes", Value.of(new byte[] {1, 2, 3})); + } + + @Test + void logBodyAssertions_withAttributeKeys() { + InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + SdkLoggerProvider loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + Logger logger = loggerProvider.get("test.test"); + + logger + .logRecordBuilder() + .setBody( + Value.of( + KeyValue.of("strField", Value.of("value1")), + KeyValue.of("boolField", Value.of(false)), + KeyValue.of("longField", Value.of(42L)), + KeyValue.of("doubleField", Value.of(3.14)), + KeyValue.of("strArrayField", Value.of(Value.of("a"), Value.of("b"))), + KeyValue.of("boolArrayField", Value.of(Value.of(true), Value.of(false))), + KeyValue.of("longArrayField", Value.of(Value.of(1L), Value.of(2L))), + KeyValue.of("doubleArrayField", Value.of(Value.of(1.1), Value.of(2.2))), + KeyValue.of("bytes", Value.of(new byte[] {1, 2, 3})))) + .emit(); + + List logs = exporter.getFinishedLogRecordItems(); + assertThat(logs).hasSize(1); + + assertThat(logs.get(0)) + .hasBodyField(AttributeKey.stringKey("strField"), "value1") + .hasBodyField(AttributeKey.booleanKey("boolField"), false) + .hasBodyField(AttributeKey.longKey("longField"), 42L) + .hasBodyField(AttributeKey.doubleKey("doubleField"), 3.14) + .hasBodyField(AttributeKey.stringArrayKey("strArrayField"), Arrays.asList("a", "b")) + .hasBodyField(AttributeKey.booleanArrayKey("boolArrayField"), Arrays.asList(true, false)) + .hasBodyField(AttributeKey.longArrayKey("longArrayField"), Arrays.asList(1L, 2L)) + .hasBodyField(AttributeKey.doubleArrayKey("doubleArrayField"), Arrays.asList(1.1, 2.2)) + .hasBodyField(AttributeKey.valueKey("bytes"), Value.of(new byte[] {1, 2, 3})); + } +} diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java index 2fc0602b986..846d5340f27 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/MetricAssertionsTest.java @@ -5,15 +5,19 @@ package io.opentelemetry.sdk.testing.assertj; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.satisfies; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.offset; +import static org.assertj.core.api.Assertions.within; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; @@ -21,13 +25,18 @@ import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.DoubleExemplarData; import io.opentelemetry.sdk.metrics.data.DoublePointData; +import io.opentelemetry.sdk.metrics.data.ExponentialHistogramPointData; import io.opentelemetry.sdk.metrics.data.HistogramPointData; import io.opentelemetry.sdk.metrics.data.LongExemplarData; import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.data.MetricDataType; import io.opentelemetry.sdk.metrics.data.SummaryPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoubleExemplarData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableDoublePointData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramBuckets; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramData; +import io.opentelemetry.sdk.metrics.internal.data.ImmutableExponentialHistogramPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableGaugeData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableHistogramPointData; @@ -42,7 +51,12 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; +import java.util.function.Consumer; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; // We always assert the contents of lists out of order to verify that assertions behave that way. class MetricAssertionsTest { @@ -51,12 +65,13 @@ class MetricAssertionsTest { private static final String SPAN_ID2 = "0000000000000004"; private static final Resource RESOURCE = - Resource.create(Attributes.builder().put("dog", "bark").build()); + Resource.create(Attributes.builder().put("dog", "bark").put("dog is cute", true).build()); private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("opentelemetry", "1.0", null); + InstrumentationScopeInfo.builder("opentelemetry").setVersion("1.0").build(); - private static final AttributeKey BEAR = AttributeKey.stringKey("bear"); - private static final AttributeKey CAT = AttributeKey.stringKey("cat"); + private static final AttributeKey DOG = stringKey("dog"); + private static final AttributeKey BEAR = stringKey("bear"); + private static final AttributeKey CAT = stringKey("cat"); private static final AttributeKey WARM = AttributeKey.booleanKey("warm"); private static final AttributeKey TEMPERATURE = AttributeKey.longKey("temperature"); private static final AttributeKey LENGTH = AttributeKey.doubleKey("length"); @@ -65,6 +80,7 @@ class MetricAssertionsTest { AttributeKey.booleanArrayKey("conditions"); private static final AttributeKey> SCORES = AttributeKey.longArrayKey("scores"); private static final AttributeKey> COINS = AttributeKey.doubleArrayKey("coins"); + private static final AttributeKey> BYTES = valueKey("bytes"); private static final Attributes ATTRIBUTES = Attributes.builder() @@ -76,6 +92,7 @@ class MetricAssertionsTest { .put(CONDITIONS, Arrays.asList(false, true)) .put(SCORES, Arrays.asList(0L, 1L)) .put(COINS, Arrays.asList(0.01, 0.05, 0.1)) + .put(BYTES, Value.of(new byte[] {1, 2, 3})) .build(); private static final DoubleExemplarData DOUBLE_EXEMPLAR1 = @@ -202,7 +219,9 @@ class MetricAssertionsTest { 2, Attributes.empty(), 15, + /* hasMin= */ true, 4.0, + /* hasMax= */ true, 7.0, Collections.singletonList(10.0), Arrays.asList(1L, 2L)); @@ -217,7 +236,7 @@ class MetricAssertionsTest { ImmutableHistogramData.create( AggregationTemporality.CUMULATIVE, // Points - Arrays.asList(HISTOGRAM_POINT_DATA))); + Collections.singletonList(HISTOGRAM_POINT_DATA))); private static final MetricData HISTOGRAM_METRIC_DELTA = ImmutableMetricData.createDoubleHistogram( @@ -229,7 +248,47 @@ class MetricAssertionsTest { ImmutableHistogramData.create( AggregationTemporality.DELTA, // Points - Arrays.asList(HISTOGRAM_POINT_DATA))); + Collections.singletonList(HISTOGRAM_POINT_DATA))); + + private static final ExponentialHistogramPointData EXPONENTIAL_HISTOGRAM_POINT_DATA = + ImmutableExponentialHistogramPointData.create( + 1, + 10.0, + 1, + /* hasMin= */ true, + 2.0, + /* hasMax= */ true, + 4.0, + ImmutableExponentialHistogramBuckets.create(1, 10, Arrays.asList(1L, 2L)), + ImmutableExponentialHistogramBuckets.create(1, 0, Collections.emptyList()), + 1, + 2, + Attributes.empty(), + Arrays.asList(DOUBLE_EXEMPLAR1, DOUBLE_EXEMPLAR2)); + + private static final MetricData EXPONENTIAL_HISTOGRAM_METRIC = + ImmutableMetricData.createExponentialHistogram( + RESOURCE, + INSTRUMENTATION_SCOPE_INFO, + /* name= */ "exponential_histogram", + /* description= */ "description", + /* unit= */ "unit", + ImmutableExponentialHistogramData.create( + AggregationTemporality.CUMULATIVE, + // Points + Collections.singletonList(EXPONENTIAL_HISTOGRAM_POINT_DATA))); + + private static final MetricData EXPONENTIAL_HISTOGRAM_DELTA_METRIC = + ImmutableMetricData.createExponentialHistogram( + RESOURCE, + INSTRUMENTATION_SCOPE_INFO, + /* name= */ "exponential_histogram_delta", + /* description= */ "description", + /* unit= */ "unit", + ImmutableExponentialHistogramData.create( + AggregationTemporality.DELTA, + // Points + Collections.singletonList(EXPONENTIAL_HISTOGRAM_POINT_DATA))); private static final SummaryPointData SUMMARY_POINT_DATA = ImmutableSummaryPointData.create( @@ -249,144 +308,469 @@ class MetricAssertionsTest { /* unit= */ "1", ImmutableSummaryData.create( // Points - Arrays.asList(SUMMARY_POINT_DATA))); + Collections.singletonList(SUMMARY_POINT_DATA))); + + @Test + void doubleGaugePointsSatisfying() { + assertThat(DOUBLE_GAUGE_METRIC) + .hasName("gauge") + .hasDoubleGaugePointsSatisfying( + point -> point.hasValue(3.0).hasStartEpochNanos(3), + point -> point.hasValue(3.0).hasStartEpochNanos(1)) + .hasDoubleGaugePointsSatisfying( + Arrays.asList( + point -> point.hasValue(3.0).hasStartEpochNanos(3), + point -> point.hasValue(3.0).hasStartEpochNanos(1))) + .hasUnit("1"); + } + + @Test + void longGaugePointsSatisfying() { + assertThat(LONG_GAUGE_METRIC) + .hasName("gauge") + .hasLongGaugePointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1)) + .hasLongGaugePointsSatisfying( + Arrays.asList(point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1))) + .hasUnit("1"); + } + + @Test + void doubleSumPointsSatisfying() { + assertThat(DOUBLE_SUM_METRIC) + .hasName("sum") + .hasDoubleSumPointsSatisfying( + point -> point.hasValue(3.0).hasStartEpochNanos(3), + point -> point.hasValue(3.0).hasStartEpochNanos(1)) + .hasDoubleSumPointsSatisfying( + Arrays.asList( + point -> point.hasValue(3.0).hasStartEpochNanos(3), + point -> point.hasValue(3.0).hasStartEpochNanos(1))) + .hasDoubleSumSatisfying(sum -> sum.isMonotonic().isCumulative()); + } + + @Test + void longSumPointsSatisfying() { + assertThat(LONG_SUM_METRIC) + .hasName("sum") + .hasLongSumPointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1)) + .hasLongSumPointsSatisfying( + Arrays.asList(point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1))) + .hasLongSumSatisfying(sum -> sum.isMonotonic().isCumulative()); + } + + @Test + void histogramPointsSatisfying() { + MetricAssert assertion = assertThat(HISTOGRAM_METRIC).hasName("histogram"); + assertThat( + assertion + .hasHistogramPointsSatisfying(point -> point.hasCount(3).hasSum(15)) + .hasHistogramSatisfying(HistogramAssert::isCumulative)) + .isSameAs(assertion); + assertThat( + assertion + .hasHistogramPointsSatisfying( + Collections.singletonList(point -> point.hasCount(3).hasSum(15))) + .hasUnit("1")) + .isSameAs(assertion); + } + + @Test + void exponentialHistogramPointsSatisfying() { + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasName("exponential_histogram") + .hasExponentialHistogramPointsSatisfying(point -> point.hasCount(4).hasSum(10).hasScale(1)) + .hasExponentialHistogramPointsSatisfying( + Collections.singletonList(point -> point.hasCount(4).hasSum(10).hasScale(1))) + .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isCumulative); + } + + @Test + void summaryPointsSatisfying() { + assertThat(SUMMARY_METRIC) + .hasName("summary") + .hasSummaryPointsSatisfying(point -> point.hasCount(1).hasSum(2)) + .hasSummaryPointsSatisfying(Collections.singletonList(point -> point.hasCount(1).hasSum(2))) + .hasUnit("1"); + } + + @ParameterizedTest + @MethodSource("pointShortcuts") + void pointShortcutsFailure(MetricData metric, Consumer assertion) { + assertThatThrownBy(() -> assertion.accept(assertThat((MetricData) null))) + .isInstanceOf(AssertionError.class) + .hasMessageContaining("not to be null"); + + MetricData wrongType = + metric.getType() == MetricDataType.HISTOGRAM ? SUMMARY_METRIC : HISTOGRAM_METRIC; + assertThatThrownBy(() -> assertion.accept(assertThat(wrongType))) + .isInstanceOf(AssertionError.class) + .hasMessage( + "Expected MetricData to have type <%s> but found <%s>", + metric.getType(), wrongType.getType()); + + assertThatThrownBy(() -> assertion.accept(assertThat(metric))) + .isInstanceOf(AssertionError.class); + } + + static Stream pointShortcuts() { + return Stream.of( + Arguments.argumentSet( + "double gauge varargs", + DOUBLE_GAUGE_METRIC, + (Consumer) MetricAssert::hasDoubleGaugePointsSatisfying), + Arguments.argumentSet( + "double gauge iterable", + DOUBLE_GAUGE_METRIC, + (Consumer) + metric -> metric.hasDoubleGaugePointsSatisfying(Collections.emptyList())), + Arguments.argumentSet( + "long gauge varargs", + LONG_GAUGE_METRIC, + (Consumer) MetricAssert::hasLongGaugePointsSatisfying), + Arguments.argumentSet( + "long gauge iterable", + LONG_GAUGE_METRIC, + (Consumer) + metric -> metric.hasLongGaugePointsSatisfying(Collections.emptyList())), + Arguments.argumentSet( + "double sum varargs", + DOUBLE_SUM_METRIC, + (Consumer) MetricAssert::hasDoubleSumPointsSatisfying), + Arguments.argumentSet( + "double sum iterable", + DOUBLE_SUM_METRIC, + (Consumer) + metric -> metric.hasDoubleSumPointsSatisfying(Collections.emptyList())), + Arguments.argumentSet( + "long sum varargs", + LONG_SUM_METRIC, + (Consumer) MetricAssert::hasLongSumPointsSatisfying), + Arguments.argumentSet( + "long sum iterable", + LONG_SUM_METRIC, + (Consumer) + metric -> metric.hasLongSumPointsSatisfying(Collections.emptyList())), + Arguments.argumentSet( + "histogram varargs", + HISTOGRAM_METRIC, + (Consumer) MetricAssert::hasHistogramPointsSatisfying), + Arguments.argumentSet( + "histogram iterable", + HISTOGRAM_METRIC, + (Consumer) + metric -> metric.hasHistogramPointsSatisfying(Collections.emptyList())), + Arguments.argumentSet( + "exponential histogram varargs", + EXPONENTIAL_HISTOGRAM_METRIC, + (Consumer) MetricAssert::hasExponentialHistogramPointsSatisfying), + Arguments.argumentSet( + "exponential histogram iterable", + EXPONENTIAL_HISTOGRAM_METRIC, + (Consumer) + metric -> metric.hasExponentialHistogramPointsSatisfying(Collections.emptyList())), + Arguments.argumentSet( + "summary varargs", + SUMMARY_METRIC, + (Consumer) MetricAssert::hasSummaryPointsSatisfying), + Arguments.argumentSet( + "summary iterable", + SUMMARY_METRIC, + (Consumer) + metric -> metric.hasSummaryPointsSatisfying(Collections.emptyList()))); + } + + @Test + void pointShortcutsRejectMismatchedPoints() { + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC).hasHistogramPointsSatisfying(point -> point.hasCount(42))) + .isInstanceOf(AssertionError.class); + } + + @Test + void pointShortcutsRequireExactMatching() { + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC).hasLongGaugePointsSatisfying(point -> point.hasValue(1))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugePointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), + point -> point.hasValue(1), + point -> point.hasValue(1))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugePointsSatisfying( + point -> point.hasValue(1), point -> point.hasValue(1))) + .isInstanceOf(AssertionError.class); + } + + @Test + @SuppressWarnings("NullAway") + void pointShortcutsNullAssertions() { + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramPointsSatisfying((Consumer[]) null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramPointsSatisfying((Iterable>) null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramPointsSatisfying((Consumer) null)) + .isInstanceOf(NullPointerException.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasHistogramPointsSatisfying((Consumer[]) null)) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat((MetricData) null) + .hasHistogramPointsSatisfying((Consumer[]) null)) + .isInstanceOf(AssertionError.class); + } @Test + @SuppressWarnings("Convert2MethodRef") void doubleGauge() { assertThat(DOUBLE_GAUGE_METRIC) .hasResource(RESOURCE) + .hasResourceSatisfying(resource -> + resource + .hasSchemaUrl(null) + .hasAttribute(DOG, "bark") + .hasAttributes( + Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) + .hasAttributes(attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(2) + .containsEntry(stringKey("dog"), "bark") + .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) + .hasEntrySatisfying( + AttributeKey.booleanKey("dog is cute"), + value -> assertThat(value).isTrue()))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.startsWith("bar")), + satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) .hasInstrumentationScope(INSTRUMENTATION_SCOPE_INFO) .hasName("gauge") .hasDescription("a gauge") .hasUnit("1") - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasStartEpochNanos(3) - .hasEpochNanos(4) - .hasAttributes(Attributes.empty()) - .hasValue(3.0) - .hasExemplars(DOUBLE_EXEMPLAR2, DOUBLE_EXEMPLAR1) - .hasExemplarsSatisfying( - exemplar -> - exemplar - .hasEpochNanos(2) - .hasTraceId(TRACE_ID) - .hasSpanId(SPAN_ID2) - .hasValue(2.0) - .hasFilteredAttributes(Attributes.empty()), - exemplar -> - exemplar - .hasEpochNanos(0) - .hasTraceId(TRACE_ID) - .hasSpanId(SPAN_ID1) - .hasValue(1.0) - .hasFilteredAttribute(BEAR, "mya") - .hasFilteredAttribute(equalTo(BEAR, "mya")) - .hasFilteredAttributes(ATTRIBUTES) - .hasFilteredAttributes( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1)) - .hasFilteredAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30), - equalTo(LENGTH, 1.2), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1))) - .hasFilteredAttributesSatisfying( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(WARM, val -> val.isTrue()), - satisfies( - TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies( - COLORS, val -> val.containsExactly("red", "blue")), - satisfies( - CONDITIONS, - val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies( - COINS, val -> val.containsExactly(0.01, 0.05, 0.1))) - // Demonstrates common usage of many exact matches and one - // needing a loose one. - .hasFilteredAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30L), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), - satisfies( - LENGTH, val -> val.isCloseTo(1, offset(0.3))))), - point -> - point - .hasStartEpochNanos(1) - .hasEpochNanos(2) - .hasValue(3.0) - .hasAttribute(BEAR, "mya") - .hasAttribute(equalTo(BEAR, "mya")) - .hasAttributes(ATTRIBUTES) - .hasAttributes( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1)) - .hasAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30), - equalTo(LENGTH, 1.2), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1))) - .hasAttributesSatisfying( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1))) - // Demonstrates common usage of many exact matches and one needing a - // loose one. - .hasAttributesSatisfying( - equalTo(BEAR, "mya"), - equalTo(WARM, true), - equalTo(TEMPERATURE, 30L), - equalTo(COLORS, Arrays.asList("red", "blue")), - equalTo(CONDITIONS, Arrays.asList(false, true)), - equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))))); + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasStartEpochNanos(3) + .hasEpochNanos(4) + .hasAttributes(Attributes.empty()) + .hasValue(3.0) + .hasValueSatisfying(val -> val.isEqualTo(3.0)) + .hasExemplars(DOUBLE_EXEMPLAR2, DOUBLE_EXEMPLAR1) + .hasExemplarsSatisfying( + exemplar -> + exemplar + .hasEpochNanos(2) + .hasTraceId(TRACE_ID) + .hasSpanId(SPAN_ID2) + .hasValue(2.0) + .hasFilteredAttributes(Attributes.empty()), + exemplar -> + exemplar + .hasEpochNanos(0) + .hasTraceId(TRACE_ID) + .hasSpanId(SPAN_ID1) + .hasValue(1.0) + .hasFilteredAttribute(BEAR, "mya") + .hasFilteredAttribute(equalTo(BEAR, "mya")) + .hasFilteredAttributes(ATTRIBUTES) + .hasFilteredAttributes( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) + .hasFilteredAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30), + equalTo(LENGTH, 1.2)) + .hasFilteredAttributesSatisfying( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(WARM, val -> val.isTrue()), + satisfies( + TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies( + COLORS, val -> val.containsExactly("red", "blue")), + satisfies( + CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies( + COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) + // Demonstrates common usage of many exact matches and one + // needing a loose one. + .hasFilteredAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(COLORS, Arrays.asList("red", "blue")), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) + .hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))))), + point -> + point + .hasStartEpochNanos(1) + .hasEpochNanos(2) + .hasValue(3.0) + .hasAttribute(BEAR, "mya") + .hasAttribute(equalTo(BEAR, "mya")) + .hasAttributes(ATTRIBUTES) + .hasAttributes( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) + .hasAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30), + equalTo(LENGTH, 1.2), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3}))) + .hasAttributesSatisfying( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) + // Demonstrates common usage of many exact matches and one needing a + // loose one. + .hasAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(9) + .containsEntry(stringKey("bear"), "mya") + .containsEntry("warm", true) + .containsEntry("temperature", 30L) + .containsEntry("colors", "red", "blue") + .containsEntry("conditions", false, true) + .containsEntry("scores", 0L, 1L) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsEntry("length", 1.2)))); } @Test + @SuppressWarnings("Convert2MethodRef") void doubleGaugeFailure() { assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasResource(Resource.empty())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasInstrumentationScope(InstrumentationScopeInfo.empty())) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying( + resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying( + resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying( + attributes -> assertThat(attributes).hasSize(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes).containsEntry(stringKey("dog"), "meow")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes) + .containsEntry(AttributeKey.booleanKey("dog is cute"), false)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("meow"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying( + resource -> resource.hasAttributesSatisfyingExactly(equalTo(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.isEqualTo("bark"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasInstrumentationScope(InstrumentationScopeInfo.empty())) + .isInstanceOf(AssertionError.class) + .hasMessage( + "Expected MetricData to have instrumentation scope <" + + InstrumentationScopeInfo.empty() + + "> but found <" + + DOUBLE_GAUGE_METRIC.getInstrumentationScopeInfo() + + ">"); assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasName("whoami")) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasDescription("whatami")) @@ -395,187 +779,109 @@ void doubleGaugeFailure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(DOUBLE_GAUGE_METRIC).hasLongGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - // Not enough points - gauge -> gauge.hasPointsSatisfying(point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasStartEpochNanos(100), point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasEpochNanos(100), point -> {}))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying(point -> point.hasValue(100), point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + // Not enough points + gauge -> gauge.hasPointsSatisfying(point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - // Not enough exemplars - point -> point.hasExemplarsSatisfying(exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasStartEpochNanos(100), point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - // Not enough exemplars - point -> point.hasExemplars(DOUBLE_EXEMPLAR1), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> point.hasEpochNanos(100), point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasEpochNanos(100), exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + gauge -> gauge.hasPointsSatisfying(point -> point.hasValue(100), point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasTraceId("trace"), exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + // Not enough exemplars + point -> point.hasExemplarsSatisfying(exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasSpanId("span"), exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + // Not enough exemplars + point -> point.hasExemplars(DOUBLE_EXEMPLAR1), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(100.0), exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasEpochNanos(100), exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasFilteredAttribute(CAT, "garfield"), - exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasTraceId("trace"), exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - exemplar.hasFilteredAttributes( - Attributes.of(CAT, "garfield")), - exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasSpanId("span"), exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> - // Extra CAT - exemplar.hasFilteredAttributesSatisfying( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(CAT, val -> val.startsWith("nya")), - satisfies(WARM, val -> val.isTrue()), - satisfies( - TEMPERATURE, - val -> val.isGreaterThanOrEqualTo(30)), - satisfies( - LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies( - COLORS, - val -> val.containsExactly("red", "blue")), - satisfies( - CONDITIONS, - val -> val.containsExactly(false, true)), - satisfies( - SCORES, val -> val.containsExactly(0L, 1L)), - satisfies( - COINS, - val -> val.containsExactly(0.01, 0.05, 0.1))), - exemplar -> {}), - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(100.0), exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - point -> point.hasAttribute(CAT, "garfield")))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasFilteredAttribute(CAT, "garfield"), + exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - point -> point.hasAttributes(Attributes.of(CAT, "garfield"))))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> + exemplar.hasFilteredAttributes(Attributes.of(CAT, "garfield")), + exemplar -> {}), + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_GAUGE_METRIC) - .hasDoubleGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasAttributes(Attributes.empty()), - // Extra CAT - point -> - point.hasAttributesSatisfying( + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> + // Extra CAT + exemplar.hasFilteredAttributesSatisfying( satisfies(BEAR, val -> val.startsWith("mya")), satisfies(CAT, val -> val.startsWith("nya")), satisfies(WARM, val -> val.isTrue()), @@ -588,7 +894,92 @@ void doubleGaugeFailure() { CONDITIONS, val -> val.containsExactly(false, true)), satisfies(SCORES, val -> val.containsExactly(0L, 1L)), satisfies( - COINS, val -> val.containsExactly(0.01, 0.05, 0.1)))))) + COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))), + exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> + // Extra CAT + exemplar.hasFilteredAttributesSatisfyingExactly( + satisfies(WARM, val -> val.isTrue()), + satisfies( + TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies( + COLORS, val -> val.containsExactly("red", "blue")), + satisfies( + CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies( + COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))), + exemplar -> {}), + point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + point -> point.hasAttribute(CAT, "garfield")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + point -> point.hasAttributes(Attributes.of(CAT, "garfield"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + // Extra CAT + point -> + point.hasAttributesSatisfying( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(CAT, val -> val.startsWith("nya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasAttributes(Attributes.empty()), + point -> + point.hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(9) + .containsEntry( + stringKey("bear"), "WRONG BEAR NAME") // Failed here + .containsEntry("warm", true) + .containsEntry("temperature", 30L) + .containsEntry("colors", "red", "blue") + .containsEntry("conditions", false, true) + .containsEntry("scores", 0L, 1L) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsEntry("length", 1.2))))) .isInstanceOf(AssertionError.class); } @@ -599,62 +990,115 @@ void doubleGaugeFailure() { @Test void longGauge() { assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point - .hasValue(Long.MAX_VALUE) - .hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(2), exemplar -> exemplar.hasValue(1)), - point -> point.hasValue(1))); + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasValue(Long.MAX_VALUE) + .hasValueSatisfying(val -> val.isEqualTo(Long.MAX_VALUE)) + .hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(2), + exemplar -> + exemplar + .hasValue(1) + .hasFilteredAttributesSatisfying( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) + .hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + equalTo(TEMPERATURE, 30L), + equalTo(COLORS, Arrays.asList("red", "blue")), + equalTo(CONDITIONS, Arrays.asList(false, true)), + equalTo(SCORES, Arrays.asList(0L, 1L)), + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))))), + point -> point.hasValue(1))); } @Test void longGaugeFailure() { assertThatThrownBy(() -> assertThat(LONG_GAUGE_METRIC).hasDoubleGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - // Not enough points - point -> {}))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + // Not enough points + point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasValue(2), point -> point.hasValue(1)))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasValue(2), point -> point.hasValue(1)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> point.hasExemplars(LONG_EXEMPLAR2), - point -> point.hasValue(1)))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasValueSatisfying(val -> val.isNegative()), + point -> point.hasValueSatisfying(val -> val.isNegative())))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_GAUGE_METRIC) - .hasLongGaugeSatisfying( - gauge -> - gauge.hasPointsSatisfying( - point -> - point.hasExemplarsSatisfying( - exemplar -> exemplar.hasValue(100), exemplar -> {}), - point -> point.hasValue(1)))) + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> point.hasExemplars(LONG_EXEMPLAR2), point -> point.hasValue(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point.hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(100), exemplar -> {}), + point -> point.hasValue(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasExemplarsSatisfying(exemplar -> + exemplar.hasFilteredAttributesSatisfying( + equalTo(CAT, "mya"), equalTo(WARM, true)))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying(point -> + point.hasExemplarsSatisfying(exemplar -> + exemplar.hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"), + equalTo(WARM, true), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))))))) + .isInstanceOf(AssertionError.class); + // hasFilteredAttributesSatisfyingExactly must reject extra filtered attributes. The exemplar + // has nine filtered attributes but only one is asserted, so the exact assertion must fail. + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.hasPointsSatisfying( + point -> + point + .hasValue(Long.MAX_VALUE) + .hasExemplarsSatisfying( + exemplar -> exemplar.hasValue(2), + exemplar -> + exemplar + .hasValue(1) + .hasFilteredAttributesSatisfyingExactly( + equalTo(BEAR, "mya"))), + point -> point.hasValue(1)))) .isInstanceOf(AssertionError.class); } @Test - void duobleSum() { + void doubleSum() { assertThat(DOUBLE_SUM_METRIC) .hasDoubleSumSatisfying( sum -> sum.isMonotonic().isCumulative().hasPointsSatisfying(point -> {}, point -> {})); @@ -664,17 +1108,16 @@ void duobleSum() { } @Test + @SuppressWarnings("Convert2MethodRef") void doubleSumFailure() { assertThatThrownBy(() -> assertThat(DOUBLE_SUM_METRIC).hasLongSumSatisfying(sum -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_SUM_METRIC) - .hasDoubleSumSatisfying( - sum -> - sum.hasPointsSatisfying( - // Not enough points - point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_SUM_METRIC) + .hasDoubleSumSatisfying(sum -> + sum.hasPointsSatisfying( + // Not enough points + point -> {}))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(DOUBLE_SUM_METRIC).hasDoubleSumSatisfying(sum -> sum.isNotMonotonic())) @@ -682,15 +1125,13 @@ void doubleSumFailure() { assertThatThrownBy( () -> assertThat(DOUBLE_SUM_METRIC).hasDoubleSumSatisfying(sum -> sum.isDelta())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) - .hasDoubleSumSatisfying(sum -> sum.isMonotonic())) + assertThatThrownBy(() -> + assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) + .hasDoubleSumSatisfying(sum -> sum.isMonotonic())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) - .hasDoubleSumSatisfying(sum -> sum.isCumulative())) + assertThatThrownBy(() -> + assertThat(DOUBLE_SUM_METRIC_DELTA_NONMONOTONIC) + .hasDoubleSumSatisfying(sum -> sum.isCumulative())) .isInstanceOf(AssertionError.class); } @@ -705,51 +1146,47 @@ void longSum() { } @Test + @SuppressWarnings("Convert2MethodRef") void longSumFailure() { assertThatThrownBy(() -> assertThat(LONG_SUM_METRIC).hasDoubleSumSatisfying(sum -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_SUM_METRIC) - .hasLongSumSatisfying( - sum -> - sum.hasPointsSatisfying( - // Not enough points - point -> {}))) + assertThatThrownBy(() -> + assertThat(LONG_SUM_METRIC) + .hasLongSumSatisfying(sum -> + sum.hasPointsSatisfying( + // Not enough points + point -> {}))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(LONG_SUM_METRIC).hasLongSumSatisfying(sum -> sum.isNotMonotonic())) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(LONG_SUM_METRIC).hasLongSumSatisfying(sum -> sum.isDelta())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) - .hasLongSumSatisfying(sum -> sum.isMonotonic())) + assertThatThrownBy(() -> + assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) + .hasLongSumSatisfying(sum -> sum.isMonotonic())) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) - .hasLongSumSatisfying(sum -> sum.isCumulative())) + assertThatThrownBy(() -> + assertThat(LONG_SUM_METRIC_DELTA_NONMONOTONIC) + .hasLongSumSatisfying(sum -> sum.isCumulative())) .isInstanceOf(AssertionError.class); } @Test void histogram() { assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram - .isCumulative() - .hasPointsSatisfying( - point -> - point - .hasSum(15.0) - .hasSumGreaterThan(10.1) - .hasMax(7.0) - .hasMin(4.0) - .hasCount(3) - .hasBucketBoundaries(10.0))); + .hasHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasSum(15.0) + .hasSumGreaterThan(10.1) + .hasMax(7.0) + .hasMin(4.0) + .hasCount(3) + .hasBucketBoundaries(10.0) + .hasBucketBoundaries(new double[] {10.1}, within(0.1)))); assertThat(HISTOGRAM_METRIC_DELTA).hasHistogramSatisfying(histogram -> histogram.isDelta()); } @@ -757,122 +1194,245 @@ void histogram() { void histogram_failure() { assertThatThrownBy(() -> assertThat(HISTOGRAM_METRIC).hasDoubleGaugeSatisfying(gauge -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying(histogram -> histogram.isDelta())) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC).hasHistogramSatisfying(histogram -> histogram.isDelta())) + .isInstanceOf(AssertionError.class) + .hasMessage("Expected Histogram to have delta aggregation but found "); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC_DELTA) + .hasHistogramSatisfying(histogram -> histogram.isCumulative())) + .isInstanceOf(AssertionError.class) + .hasMessage("Expected Histogram to have cumulative aggregation but found "); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC_DELTA) - .hasHistogramSatisfying(histogram -> histogram.isCumulative())) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> point.hasSumGreaterThan(16.0)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying(point -> point.hasSumGreaterThan(16.0)))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> point.hasBucketBoundaries(11.0)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying( + point -> point.hasBucketBoundaries(new double[] {11.0}, within(0.1))))) .isInstanceOf(AssertionError.class); + } + + @Test + void exponentialHistogram() { + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying(histogram -> + histogram + .isCumulative() + .hasPointsSatisfying(point -> + point + .hasScale(1) + .hasSum(10.0) + .hasZeroCount(1) + .hasCount(4) + .hasMin(2.0) + .hasMax(4.0) + .hasPositiveBucketsSatisfying(buckets -> + buckets.hasOffset(10).hasCounts(Arrays.asList(1L, 2L)).hasTotalCount(3)) + .hasNegativeBucketsSatisfying(buckets -> + buckets + .hasOffset(0) + .hasCounts(Collections.emptyList()) + .hasTotalCount(0)) + .hasStartEpochNanos(1) + .hasEpochNanos(2) + .hasAttributes(Attributes.empty()) + .hasExemplars(DOUBLE_EXEMPLAR1, DOUBLE_EXEMPLAR2) + .hasExemplarsSatisfying(exemplar -> {}, exemplar -> {}))); + assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC) + .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isDelta); + } + + @Test + void exponentialHistogram_failure() { assertThatThrownBy( - () -> - assertThat(HISTOGRAM_METRIC) - .hasHistogramSatisfying( - histogram -> - histogram.hasPointsSatisfying( - point -> point.hasBucketBoundaries(11.0)))) + () -> assertThat(EXPONENTIAL_HISTOGRAM_METRIC).hasDoubleGaugeSatisfying(gauge -> {})) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isDelta)) + .isInstanceOf(AssertionError.class) + .hasMessage("Expected Histogram to have delta aggregation but found "); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_DELTA_METRIC) + .hasExponentialHistogramSatisfying(ExponentialHistogramAssert::isCumulative)) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> {}, point -> {}))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasSum(14.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMax(8.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasMin(5.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.hasPointsSatisfying(point -> point.hasCount(4)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying(histogram -> + histogram.hasPointsSatisfying(point -> + point.hasPositiveBucketsSatisfying( + buckets -> buckets.hasCounts(Collections.singletonList(1L)))))) .isInstanceOf(AssertionError.class); } @Test void summary() { assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> - point - .hasSum(2.0) - .hasCount(1) - .hasValuesSatisfying(value -> value.hasQuantile(0.0).hasValue(1.0)))); + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying(point -> + point + .hasSum(2.0) + .hasCount(1) + .hasValuesSatisfying(value -> value.hasQuantile(0.0).hasValue(1.0)))); } @Test void summary_failure() { assertThatThrownBy(() -> assertThat(SUMMARY_METRIC).hasHistogramSatisfying(histogram -> {})) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> point.hasSum(1.0)))) + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> {}, point -> {}))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> summary.hasPointsSatisfying(point -> point.hasCount(2)))) + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> point.hasSum(1.0)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> point.hasValuesSatisfying(value -> {}, value -> {})))) + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.hasPointsSatisfying(point -> point.hasCount(2)))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> - point.hasValuesSatisfying(value -> value.hasQuantile(1.0))))) + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying( + point -> point.hasValuesSatisfying(value -> {}, value -> {})))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SUMMARY_METRIC) - .hasSummarySatisfying( - summary -> - summary.hasPointsSatisfying( - point -> point.hasValuesSatisfying(value -> value.hasValue(3.0))))) + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying( + point -> point.hasValuesSatisfying(value -> value.hasQuantile(1.0))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying(summary -> + summary.hasPointsSatisfying( + point -> point.hasValuesSatisfying(value -> value.hasValue(3.0))))) + .isInstanceOf(AssertionError.class); + } + + @Test + void containsPointsSatisfying() { + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + gauge -> gauge.containsPointsSatisfying(point -> point.hasValue(3.0))); + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.containsPointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(1))); + assertThat(DOUBLE_SUM_METRIC) + .hasDoubleSumSatisfying(sum -> sum.containsPointsSatisfying(point -> point.hasValue(3.0))); + assertThat(LONG_SUM_METRIC) + .hasLongSumSatisfying( + sum -> sum.containsPointsSatisfying(point -> point.hasValue(Long.MAX_VALUE))); + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(15))); + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(10.0))); + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.containsPointsSatisfying(point -> point.hasSum(2.0))); + } + + @Test + void containsPointsSatisfyingFailure() { + // single assertion that matches no point + assertThatThrownBy(() -> + assertThat(DOUBLE_GAUGE_METRIC) + .hasDoubleGaugeSatisfying( + gauge -> gauge.containsPointsSatisfying(point -> point.hasValue(42.0)))) + .isInstanceOf(AssertionError.class); + // one of multiple assertions unmatched + assertThatThrownBy(() -> + assertThat(LONG_GAUGE_METRIC) + .hasLongGaugeSatisfying(gauge -> + gauge.containsPointsSatisfying( + point -> point.hasValue(Long.MAX_VALUE), point -> point.hasValue(42)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(HISTOGRAM_METRIC) + .hasHistogramSatisfying( + histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(42)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(EXPONENTIAL_HISTOGRAM_METRIC) + .hasExponentialHistogramSatisfying( + histogram -> histogram.containsPointsSatisfying(point -> point.hasSum(42.0)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SUMMARY_METRIC) + .hasSummarySatisfying( + summary -> summary.containsPointsSatisfying(point -> point.hasSum(42.0)))) .isInstanceOf(AssertionError.class); } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java index 820d0d58964..a93a6e27f98 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TraceAssertionsTest.java @@ -5,6 +5,8 @@ package io.opentelemetry.sdk.testing.assertj; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; @@ -15,8 +17,10 @@ import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; @@ -26,7 +30,7 @@ import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; +import java.nio.ByteBuffer; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -43,12 +47,13 @@ class TraceAssertionsTest { private static final String SPAN_ID2 = "0000000000000004"; private static final TraceState TRACE_STATE = TraceState.builder().put("cat", "meow").build(); private static final Resource RESOURCE = - Resource.create(Attributes.builder().put("dog", "bark").build()); + Resource.create(Attributes.builder().put("dog", "bark").put("dog is cute", true).build()); private static final InstrumentationScopeInfo INSTRUMENTATION_SCOPE_INFO = - InstrumentationScopeInfo.create("opentelemetry", "1.0", null); + InstrumentationScopeInfo.builder("opentelemetry").setVersion("1.0").build(); - private static final AttributeKey BEAR = AttributeKey.stringKey("bear"); - private static final AttributeKey CAT = AttributeKey.stringKey("cat"); + private static final AttributeKey DOG = stringKey("dog"); + private static final AttributeKey BEAR = stringKey("bear"); + private static final AttributeKey CAT = stringKey("cat"); private static final AttributeKey WARM = AttributeKey.booleanKey("warm"); private static final AttributeKey TEMPERATURE = AttributeKey.longKey("temperature"); private static final AttributeKey LENGTH = AttributeKey.doubleKey("length"); @@ -57,7 +62,8 @@ class TraceAssertionsTest { AttributeKey.booleanArrayKey("conditions"); private static final AttributeKey> SCORES = AttributeKey.longArrayKey("scores"); private static final AttributeKey> COINS = AttributeKey.doubleArrayKey("coins"); - private static final AttributeKey UNSET = AttributeKey.stringKey("unset"); + private static final AttributeKey> BYTES = valueKey("bytes"); + private static final AttributeKey UNSET = stringKey("unset"); private static final Attributes ATTRIBUTES = Attributes.builder() @@ -69,6 +75,7 @@ class TraceAssertionsTest { .put(CONDITIONS, Arrays.asList(false, true)) .put(SCORES, Arrays.asList(0L, 1L)) .put(COINS, Arrays.asList(0.01, 0.05, 0.1)) + .put(BYTES, Value.of(new byte[] {1, 2, 3})) .build(); private static final List EVENTS = Arrays.asList( @@ -76,11 +83,11 @@ class TraceAssertionsTest { EventData.create(20, "event2", Attributes.builder().put("cookie monster", "yum").build()), EventData.create( 30, - SemanticAttributes.EXCEPTION_EVENT_NAME, + "exception", Attributes.builder() - .put(SemanticAttributes.EXCEPTION_TYPE, "java.lang.IllegalArgumentException") - .put(SemanticAttributes.EXCEPTION_MESSAGE, "bad argument") - .put(SemanticAttributes.EXCEPTION_STACKTRACE, "some obfuscated stack") + .put(stringKey("exception.type"), "java.lang.IllegalArgumentException") + .put(stringKey("exception.message"), "bad argument") + .put(stringKey("exception.stacktrace"), "some obfuscated stack") .build())); private static final List LINKS = Arrays.asList( @@ -131,6 +138,7 @@ class TraceAssertionsTest { } @Test + @SuppressWarnings("Convert2MethodRef") void passing() { assertThat(SPAN1) .hasTraceId(TRACE_ID) @@ -139,6 +147,30 @@ void passing() { .hasTraceState(TRACE_STATE) .hasParentSpanId(SPAN_ID2) .hasResource(RESOURCE) + .hasResourceSatisfying(resource -> + resource + .hasSchemaUrl(null) + .hasAttribute(DOG, "bark") + .hasAttributes( + Attributes.of(DOG, "bark", AttributeKey.booleanKey("dog is cute"), true)) + .hasAttributes(attributeEntry("dog", "bark"), attributeEntry("dog is cute", true)) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(2) + .containsEntry(stringKey("dog"), "bark") + .hasEntrySatisfying(DOG, value -> assertThat(value).hasSize(4)) + .hasEntrySatisfying( + AttributeKey.booleanKey("dog is cute"), + value -> assertThat(value).isTrue()))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("bark")))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + equalTo(DOG, "bark"), equalTo(AttributeKey.booleanKey("dog is cute"), true))) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.startsWith("bar")), + satisfies(AttributeKey.booleanKey("dog is cute"), val -> val.isTrue()))) .hasInstrumentationScopeInfo(INSTRUMENTATION_SCOPE_INFO) .hasName("span") .hasKind(SpanKind.CLIENT) @@ -156,7 +188,10 @@ void passing() { attributeEntry("colors", "red", "blue"), attributeEntry("conditions", false, true), attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1)) + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3}))) + .hasAttributesSatisfying( + equalTo(BEAR, "mya"), equalTo(WARM, true), equalTo(TEMPERATURE, 30)) .hasAttributesSatisfyingExactly( equalTo(BEAR, "mya"), equalTo(WARM, true), @@ -165,7 +200,8 @@ void passing() { equalTo(COLORS, Arrays.asList("red", "blue")), equalTo(CONDITIONS, Arrays.asList(false, true)), equalTo(SCORES, Arrays.asList(0L, 1L)), - equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1))) + equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3}))) .hasAttributesSatisfyingExactly( satisfies(BEAR, val -> val.startsWith("mya")), satisfies(WARM, val -> val.isTrue()), @@ -174,7 +210,8 @@ void passing() { satisfies(COLORS, val -> val.containsExactly("red", "blue")), satisfies(CONDITIONS, val -> val.containsExactly(false, true)), satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1))) + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3})))) // Demonstrates common usage of many exact matches and one needing a loose one. .hasAttributesSatisfyingExactly( equalTo(BEAR, "mya"), @@ -184,63 +221,74 @@ void passing() { equalTo(CONDITIONS, Arrays.asList(false, true)), equalTo(SCORES, Arrays.asList(0L, 1L)), equalTo(COINS, Arrays.asList(0.01, 0.05, 0.1)), + equalTo(BYTES, Value.of(new byte[] {1, 2, 3})), satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3)))) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasSize(8) - .containsEntry(AttributeKey.stringKey("bear"), "mya") - .hasEntrySatisfying( - AttributeKey.stringKey("bear"), value -> assertThat(value).hasSize(3)) - .containsEntry("bear", "mya") - .containsEntry("warm", true) - .containsEntry("temperature", 30) - .containsEntry(AttributeKey.longKey("temperature"), 30L) - .containsEntry(AttributeKey.longKey("temperature"), 30) - .containsEntry("length", 1.2) - .containsEntry("colors", "red", "blue") - .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) - .containsEntry("conditions", false, true) - .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) - .containsEntry("scores", 0L, 1L) - .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) - .containsEntry("coins", 0.01, 0.05, 0.1) - .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) - .containsKey(AttributeKey.stringKey("bear")) - .containsKey("bear") - .containsOnly( - attributeEntry("bear", "mya"), - attributeEntry("warm", true), - attributeEntry("temperature", 30), - attributeEntry("length", 1.2), - attributeEntry("colors", "red", "blue"), - attributeEntry("conditions", false, true), - attributeEntry("scores", 0L, 1L), - attributeEntry("coins", 0.01, 0.05, 0.1))) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasSize(9) + .containsEntry(stringKey("bear"), "mya") + .hasEntrySatisfying(stringKey("bear"), value -> assertThat(value).hasSize(3)) + .containsEntry("bear", "mya") + .containsEntry("warm", true) + .containsEntry("temperature", 30) + .containsEntry(AttributeKey.longKey("temperature"), 30L) + .containsEntry(AttributeKey.longKey("temperature"), 30) + .containsEntry("length", 1.2) + .containsEntry("colors", "red", "blue") + .containsEntryWithStringValuesOf("colors", Arrays.asList("red", "blue")) + .containsEntry("conditions", false, true) + .containsEntryWithBooleanValuesOf("conditions", Arrays.asList(false, true)) + .containsEntry("scores", 0L, 1L) + .containsEntryWithLongValuesOf("scores", Arrays.asList(0L, 1L)) + .containsEntry("coins", 0.01, 0.05, 0.1) + .containsEntryWithDoubleValuesOf("coins", Arrays.asList(0.01, 0.05, 0.1)) + .containsEntry("bytes", Value.of(new byte[] {1, 2, 3})) + .containsKey(stringKey("bear")) + .containsKey("bear") + .doesNotContainKey(stringKey("cat")) + .doesNotContainKey("cat") + .containsOnly( + attributeEntry("bear", "mya"), + attributeEntry("warm", true), + attributeEntry("temperature", 30), + attributeEntry("length", 1.2), + attributeEntry("colors", "red", "blue"), + attributeEntry("conditions", false, true), + attributeEntry("scores", 0L, 1L), + attributeEntry("coins", 0.01, 0.05, 0.1), + attributeEntry("bytes", Value.of(new byte[] {1, 2, 3})))) .hasEvents(EVENTS) .hasEvents(EVENTS.toArray(new EventData[0])) - .hasEventsSatisfying( - events -> { - assertThat(events).hasSize(EVENTS.size()); - assertThat(events.get(0)) - .hasName("event") - .hasTimestamp(10) - .hasTimestamp(10, TimeUnit.NANOSECONDS) - .hasTimestamp(Instant.ofEpochSecond(0, 10)) - .hasAttributes(Attributes.empty()) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).isEqualTo(Attributes.empty())) - .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty()); - }) + .hasEventsSatisfying(events -> { + assertThat(events).hasSize(EVENTS.size()); + assertThat(events.get(0)) + .hasName("event") + .hasTimestamp(10) + .hasTimestamp(10, TimeUnit.NANOSECONDS) + .hasTimestamp(Instant.ofEpochSecond(0, 10)) + .hasAttributes(Attributes.empty()) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).isEqualTo(Attributes.empty())) + .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty()); + assertThat(events.get(2)) + .hasAttributesSatisfying( + equalTo(stringKey("exception.type"), "java.lang.IllegalArgumentException")) + .hasAttributesSatisfyingExactly( + equalTo(stringKey("exception.type"), "java.lang.IllegalArgumentException"), + equalTo(stringKey("exception.message"), "bad argument"), + equalTo(stringKey("exception.stacktrace"), "some obfuscated stack")); + }) .hasEventsSatisfyingExactly( event -> event.hasName("event"), event -> event.hasName("event2"), - event -> event.hasName(SemanticAttributes.EXCEPTION_EVENT_NAME)) + event -> event.hasName("exception")) .hasException(new IllegalArgumentException("bad argument")) .hasLinks(LINKS) .hasLinks(LINKS.toArray(new LinkData[0])) .hasLinksSatisfying(links -> assertThat(links).hasSize(LINKS.size())) .hasStatus(StatusData.ok()) + .hasStatusSatisfying(status -> + status.isOk().hasCode(StatusCode.OK).hasDescription("").hasDescriptionMatching("^$")) .endsAt(200) .endsAt(200, TimeUnit.NANOSECONDS) .endsAt(Instant.ofEpochSecond(0, 200)) @@ -249,10 +297,14 @@ void passing() { .hasTotalRecordedLinks(400) .hasTotalAttributeCount(500); - assertThat(RESOURCE.getAttributes()).containsOnly(entry(AttributeKey.stringKey("dog"), "bark")); + assertThat(RESOURCE.getAttributes()) + .containsOnly(entry(DOG, "bark"), entry(AttributeKey.booleanKey("dog is cute"), true)); + + assertThat(buildTestSpan(SPAN_ID1, "span")).hasException(null); } @Test + @SuppressWarnings("Convert2MethodRef") void failure() { assertThatThrownBy(() -> assertThat(SPAN1).hasTraceId("foo")) .isInstanceOf(AssertionError.class); @@ -265,6 +317,58 @@ void failure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasResource(Resource.empty())) .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> resource.hasSchemaUrl("http://example.com"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1).hasResourceSatisfying(resource -> resource.hasAttribute(DOG, "meow"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying( + resource -> resource.hasAttributes(Attributes.of(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying( + resource -> resource.hasAttributes(attributeEntry("dog is cute", true)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying( + attributes -> assertThat(attributes).hasSize(1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes).containsEntry(stringKey("dog"), "meow")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(attributes -> + assertThat(attributes) + .containsEntry(AttributeKey.booleanKey("dog is cute"), false)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfying(satisfies(DOG, val -> val.isEqualTo("meow"))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying( + resource -> resource.hasAttributesSatisfyingExactly(equalTo(DOG, "bark")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasResourceSatisfying(resource -> + resource.hasAttributesSatisfyingExactly( + satisfies(DOG, val -> val.isEqualTo("bark"))))) + .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasInstrumentationScopeInfo(InstrumentationScopeInfo.empty())) .isInstanceOf(AssertionError.class); @@ -276,140 +380,139 @@ void failure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).startsAt(Instant.EPOCH)) .isInstanceOf(AssertionError.class); - assertThatThrownBy(() -> assertThat(SPAN1).hasAttribute(AttributeKey.stringKey("foo"), "bar")) + assertThatThrownBy(() -> assertThat(SPAN1).hasAttribute(stringKey("foo"), "bar")) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasAttributes(Attributes.empty())) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasAttributes(attributeEntry("food", "burger"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfyingExactly( - // Failed - satisfies(BEAR, val -> val.doesNotContain("mya")), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - // Missing BEAR - .hasAttributesSatisfyingExactly( - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - // Extra CAT - .hasAttributesSatisfyingExactly( - satisfies(BEAR, val -> val.startsWith("mya")), - satisfies(CAT, val -> val.startsWith("nya")), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).containsEntry("cat", "bark"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes).containsKey(AttributeKey.stringKey("cat")))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> assertThat(attributes).containsKey("cat"))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty())) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying(attributes -> assertThat(attributes).hasSize(33))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes) - .hasEntrySatisfying( - AttributeKey.stringKey("bear"), - value -> assertThat(value).hasSize(2)))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfyingExactly( + // Failed + satisfies(BEAR, val -> val.doesNotContain("mya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + // Missing BEAR + .hasAttributesSatisfyingExactly( + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + // Extra CAT + .hasAttributesSatisfyingExactly( + satisfies(BEAR, val -> val.startsWith("mya")), + satisfies(CAT, val -> val.startsWith("nya")), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies(BYTES, val -> val.isEqualTo(Value.of(new byte[] {1, 2, 3}))))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).containsEntry("cat", "bark"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).containsKey(stringKey("cat")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> assertThat(attributes).containsKey("cat"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).doesNotContainKey(stringKey("bear")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).doesNotContainKey("bear"))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> assertThat(attributes).isEmpty())) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> assertThat(attributes).hasSize(33))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfying(attributes -> + assertThat(attributes) + .hasEntrySatisfying( + stringKey("bear"), value -> assertThat(value).hasSize(2)))) .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasEvents()).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasEvents(Collections.emptyList())) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasEventsSatisfying(events -> assertThat(events).isEmpty())); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying(events -> assertThat(events.get(0)).hasName("notevent"))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> assertThat(events.get(0)).hasName("notevent"))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasEventsSatisfyingExactly(event -> event.hasName("notevent"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying(events -> assertThat(events.get(0)).hasTimestamp(1))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> assertThat(events.get(0)).hasTimestamp(1, TimeUnit.NANOSECONDS))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(0)).hasTimestamp(Instant.ofEpochSecond(0, 1)))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(0)).hasAttributes(RESOURCE.getAttributes()))) - .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasEventsSatisfying( - events -> - assertThat(events.get(0)) - .hasAttributesSatisfying( - attributes -> - assertThat(attributes).containsEntry("dogs", "meow")))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> assertThat(events.get(0)).hasTimestamp(1))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying( + events -> assertThat(events.get(0)).hasTimestamp(1, TimeUnit.NANOSECONDS))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying( + events -> assertThat(events.get(0)).hasTimestamp(Instant.ofEpochSecond(0, 1)))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying( + events -> assertThat(events.get(0)).hasAttributes(RESOURCE.getAttributes()))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> + assertThat(events.get(0)) + .hasAttributesSatisfying( + attributes -> assertThat(attributes).containsEntry("dogs", "meow")))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasEventsSatisfying(events -> + assertThat(events.get(2)) + .hasAttributesSatisfyingExactly( + equalTo( + stringKey("exception.type"), "java.lang.IllegalArgumentException"), + equalTo(stringKey("exception.message"), "bad argument")))) .isInstanceOf(AssertionError.class); assertThatThrownBy( () -> assertThat(SPAN1).hasException(new IllegalStateException("bad argument"))) @@ -417,6 +520,8 @@ void failure() { assertThatThrownBy( () -> assertThat(SPAN1).hasException(new IllegalArgumentException("good argument"))) .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> assertThat(SPAN1).hasException(null)) + .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasLinks()).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasLinks(Collections.emptyList())) .isInstanceOf(AssertionError.class); @@ -425,6 +530,14 @@ void failure() { .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).hasStatus(StatusData.error())) .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> assertThat(SPAN1).hasStatusSatisfying(StatusDataAssert::isError)) + .isInstanceOf(AssertionError.class); + assertThatThrownBy( + () -> assertThat(SPAN1).hasStatusSatisfying(status -> status.hasCode(StatusCode.ERROR))) + .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + assertThat(SPAN1).hasStatusSatisfying(status -> status.hasDescriptionMatching("test"))) + .isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).endsAt(10)).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN1).endsAt(10, TimeUnit.NANOSECONDS)) .isInstanceOf(AssertionError.class); @@ -441,21 +554,17 @@ void failure() { assertThatThrownBy(() -> assertThat(SPAN2).isSampled()).isInstanceOf(AssertionError.class); assertThatThrownBy(() -> assertThat(SPAN2).hasEnded()).isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(RESOURCE.getAttributes()) - .containsOnly( - entry(AttributeKey.stringKey("dog"), "bark"), - entry(AttributeKey.stringKey("cat"), "meow"))) + assertThatThrownBy(() -> + assertThat(RESOURCE.getAttributes()) + .containsOnly(entry(stringKey("dog"), "bark"), entry(stringKey("cat"), "meow"))) .isInstanceOf(AssertionError.class); - assertThatThrownBy( - () -> - assertThat(RESOURCE.getAttributes()) - .containsOnly(entry(AttributeKey.stringKey("cat"), "meow"))) + assertThatThrownBy(() -> + assertThat(RESOURCE.getAttributes()).containsOnly(entry(stringKey("cat"), "meow"))) .isInstanceOf(AssertionError.class); } @Test + @SuppressWarnings("Convert2MethodRef") void optionalAttributes() { assertThat(SPAN1) .hasAttributesSatisfyingExactly( @@ -477,26 +586,34 @@ void optionalAttributes() { satisfies(COLORS, val -> val.containsExactly("red", "blue")), satisfies(CONDITIONS, val -> val.containsExactly(false, true)), satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1))); + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> + val.extracting(v -> ((ByteBuffer) v.getValue()).get(0)).isEqualTo((byte) 1))); - assertThatThrownBy( - () -> - assertThat(SPAN1) - .hasAttributesSatisfyingExactly( - // Yes null - satisfies( - UNSET, - val -> - val.satisfiesAnyOf( - v -> assertThat(v).isNull(), - v -> assertThat(v).isEqualTo("objection"))), - satisfies(WARM, val -> val.isTrue()), - satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), - satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), - satisfies(COLORS, val -> val.containsExactly("red", "blue")), - satisfies(CONDITIONS, val -> val.containsExactly(false, true)), - satisfies(SCORES, val -> val.containsExactly(0L, 1L)), - satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)))) + assertThatThrownBy(() -> + assertThat(SPAN1) + .hasAttributesSatisfyingExactly( + // Yes null + satisfies( + UNSET, + val -> + val.satisfiesAnyOf( + v -> assertThat(v).isNull(), + v -> assertThat(v).isEqualTo("objection"))), + satisfies(WARM, val -> val.isTrue()), + satisfies(TEMPERATURE, val -> val.isGreaterThanOrEqualTo(30)), + satisfies(LENGTH, val -> val.isCloseTo(1, offset(0.3))), + satisfies(COLORS, val -> val.containsExactly("red", "blue")), + satisfies(CONDITIONS, val -> val.containsExactly(false, true)), + satisfies(SCORES, val -> val.containsExactly(0L, 1L)), + satisfies(COINS, val -> val.containsExactly(0.01, 0.05, 0.1)), + satisfies( + BYTES, + val -> + val.extracting(v -> ((ByteBuffer) v.getValue()).get(0)) + .isEqualTo((byte) 1)))) .isInstanceOf(AssertionError.class); } @@ -521,41 +638,43 @@ void hasSpansSatisfyingExactly() { // test asserting spans in exact oder TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactly( - span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactly( + span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); + // wrong number of spans + assertThatThrownBy(() -> + TracesAssert.assertThat(traces) + .hasTracesSatisfyingExactly( + trace -> trace.hasSpansSatisfyingExactly(span -> span.hasSpanId(SPAN_ID1)))) + .isInstanceOf(AssertionError.class) + .hasMessageStartingWith( + "[Trace 0] " + System.lineSeparator() + "Expected size: 1 but was: 2"); + // test asserting spans in wrong oder - assertThatThrownBy( - () -> - TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactly( - span -> span.hasSpanId(SPAN_ID2), - span -> span.hasSpanId(SPAN_ID1)))) - .isInstanceOf(AssertionError.class); + assertThatThrownBy(() -> + TracesAssert.assertThat(traces) + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactly( + span -> span.hasSpanId(SPAN_ID2), span -> span.hasSpanId(SPAN_ID1)))) + .isInstanceOf(AssertionError.class) + .hasMessage( + "[Span 0] Expected span [span1] to have span ID <0000000000000004> but was <0000000000000003>"); // test asserting spans in any order TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactlyInAnyOrder( - span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactlyInAnyOrder( + span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID2))); TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactlyInAnyOrder( - span -> span.hasSpanId(SPAN_ID2), span -> span.hasSpanId(SPAN_ID1))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactlyInAnyOrder( + span -> span.hasSpanId(SPAN_ID2), span -> span.hasSpanId(SPAN_ID1))); // test not asserting all spans - assertThatThrownBy( - () -> - TracesAssert.assertThat(traces) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactlyInAnyOrder( - span -> span.hasSpanId(SPAN_ID1), - span -> span.hasSpanId(SPAN_ID1)))) + assertThatThrownBy(() -> + TracesAssert.assertThat(traces) + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactlyInAnyOrder( + span -> span.hasSpanId(SPAN_ID1), span -> span.hasSpanId(SPAN_ID1)))) .isInstanceOf(AssertionError.class); } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TracesAssertTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TracesAssertTest.java new file mode 100644 index 00000000000..acc977ebaef --- /dev/null +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/assertj/TracesAssertTest.java @@ -0,0 +1,75 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.assertj; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.sdk.testing.trace.TestSpanData; +import io.opentelemetry.sdk.trace.data.StatusData; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.jupiter.api.Test; + +class TracesAssertTest { + @Test + void spanDataComparator() { + TestSpanData before = createBasicSpanBuilder().setStartEpochNanos(9).build(); + + String traceId = TraceId.fromLongs(1, 2); + TestSpanData parent = + createBasicSpanBuilder() + .setName("parent") + .setSpanContext( + SpanContext.create( + traceId, SpanId.fromLong(1), TraceFlags.getDefault(), TraceState.getDefault())) + .setStartEpochNanos(10) + .build(); + TestSpanData child = + createBasicSpanBuilder() + .setName("child") + .setSpanContext( + SpanContext.create( + traceId, SpanId.fromLong(2), TraceFlags.getDefault(), TraceState.getDefault())) + .setStartEpochNanos(10) + .setParentSpanContext(parent.getSpanContext()) + .build(); + + TestSpanData sameTime1 = + createBasicSpanBuilder().setName("sameTime1").setStartEpochNanos(11).build(); + TestSpanData sameTime2 = + createBasicSpanBuilder().setName("sameTime2").setStartEpochNanos(11).build(); + + assertSort(Arrays.asList(child, parent, before), before, parent, child); + assertSort(Arrays.asList(parent, child, before), before, parent, child); + + assertSort(Arrays.asList(sameTime1, sameTime2, before), before, sameTime1, sameTime2); + assertSort(Arrays.asList(sameTime2, sameTime1, before), before, sameTime2, sameTime1); + } + + private static void assertSort(List spanData, TestSpanData... expected) { + ArrayList list = new ArrayList<>(spanData); + list.sort(TracesAssert.SPAN_DATA_COMPARATOR); + assertThat(list).containsExactly(expected); + } + + private static TestSpanData.Builder createBasicSpanBuilder() { + return TestSpanData.builder() + .setHasEnded(true) + .setName("spanName") + .setEndEpochNanos(100) + .setKind(SpanKind.SERVER) + .setStatus(StatusData.ok()) + .setTotalRecordedEvents(0) + .setTotalRecordedLinks(0); + } +} diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryLogRecordExporterTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryLogRecordExporterTest.java new file mode 100644 index 00000000000..1c1147d3de4 --- /dev/null +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryLogRecordExporterTest.java @@ -0,0 +1,98 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.exporter; + +import static io.opentelemetry.api.logs.Severity.DEBUG; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.logs.Logger; +import io.opentelemetry.sdk.logs.SdkLoggerProvider; +import io.opentelemetry.sdk.logs.data.LogRecordData; +import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor; +import io.opentelemetry.sdk.testing.logs.TestLogRecordData; +import java.util.Collections; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Unit tests for {@link InMemoryLogRecordExporter}. */ +class InMemoryLogRecordExporterTest { + private final InMemoryLogRecordExporter exporter = InMemoryLogRecordExporter.create(); + + private SdkLoggerProvider loggerProvider; + private Logger logger; + + @BeforeEach + void setup() { + loggerProvider = + SdkLoggerProvider.builder() + .addLogRecordProcessor(SimpleLogRecordProcessor.create(exporter)) + .build(); + logger = loggerProvider.loggerBuilder("logger").build(); + } + + @AfterEach + void tearDown() { + loggerProvider.shutdown(); + } + + @Test + void getFinishedLogItems() { + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 1").emit(); + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 2").emit(); + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 3").emit(); + + List logItems = exporter.getFinishedLogRecordItems(); + assertThat(logItems).isNotNull(); + assertThat(logItems.size()).isEqualTo(3); + assertThat(logItems.get(0)).hasBody("message 1"); + assertThat(logItems.get(1)).hasBody("message 2"); + assertThat(logItems.get(2)).hasBody("message 3"); + } + + @Test + void reset() { + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 1").emit(); + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 2").emit(); + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 3").emit(); + List logItems = exporter.getFinishedLogRecordItems(); + assertThat(logItems).isNotNull(); + assertThat(logItems.size()).isEqualTo(3); + // Reset then expect no items in memory. + exporter.reset(); + assertThat(exporter.getFinishedLogRecordItems()).isEmpty(); + } + + @Test + void shutdown() { + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 1").emit(); + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 2").emit(); + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 3").emit(); + List logItems = exporter.getFinishedLogRecordItems(); + assertThat(logItems).isNotNull(); + assertThat(logItems.size()).isEqualTo(3); + // Shutdown then expect no items in memory. + exporter.shutdown(); + assertThat(exporter.getFinishedLogRecordItems()).isEmpty(); + // Cannot add new elements after the shutdown. + logger.logRecordBuilder().setSeverity(DEBUG).setBody("message 1").emit(); + assertThat(exporter.getFinishedLogRecordItems()).isEmpty(); + } + + @Test + void export_ReturnCode() { + LogRecordData logRecordData = + TestLogRecordData.builder().setBody("message 1").setSeverity(DEBUG).build(); + assertThat(exporter.export(Collections.singletonList(logRecordData)).isSuccess()).isTrue(); + exporter.shutdown(); + // After shutdown no more export. + assertThat(exporter.export(Collections.singletonList(logRecordData)).isSuccess()).isFalse(); + exporter.reset(); + // Reset does not do anything if already shutdown. + assertThat(exporter.export(Collections.singletonList(logRecordData)).isSuccess()).isFalse(); + } +} diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java index deb30859fb1..45a03c281b3 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricExporterTest.java @@ -5,22 +5,33 @@ package io.opentelemetry.sdk.testing.exporter; -import static org.assertj.core.api.Assertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.metrics.InstrumentType; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.metrics.data.AggregationTemporality; import io.opentelemetry.sdk.metrics.data.MetricData; +import io.opentelemetry.sdk.metrics.export.AggregationTemporalitySelector; +import io.opentelemetry.sdk.metrics.export.PeriodicMetricReader; import io.opentelemetry.sdk.metrics.internal.data.ImmutableLongPointData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableMetricData; import io.opentelemetry.sdk.metrics.internal.data.ImmutableSumData; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.testing.time.TestClock; +import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** Unit tests for {@link InMemoryMetricExporter}. */ class InMemoryMetricExporterTest { @@ -44,14 +55,111 @@ private static MetricData generateFakeMetric() { startNs, endNs, Attributes.builder().put("k", "v").build(), 5)))); } - @Test - void getAggregationTemporality() { - assertThat(InMemoryMetricExporter.create().getAggregationTemporality(InstrumentType.COUNTER)) + @ParameterizedTest + @EnumSource(InstrumentType.class) + void getAggregationTemporality(InstrumentType instrumentType) { + assertThat(InMemoryMetricExporter.create().getAggregationTemporality(instrumentType)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(InMemoryMetricExporter.builder().build().getAggregationTemporality(instrumentType)) .isEqualTo(AggregationTemporality.CUMULATIVE); assertThat( InMemoryMetricExporter.create(AggregationTemporality.DELTA) - .getAggregationTemporality(InstrumentType.COUNTER)) + .getAggregationTemporality(instrumentType)) .isEqualTo(AggregationTemporality.DELTA); + assertThat( + InMemoryMetricExporter.create(AggregationTemporality.CUMULATIVE) + .getAggregationTemporality(instrumentType)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + } + + @ParameterizedTest + @EnumSource(InstrumentType.class) + void getAggregationTemporality_deltaPreferred(InstrumentType instrumentType) { + assertThat( + InMemoryMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build() + .getAggregationTemporality(instrumentType)) + .isEqualTo( + instrumentType == InstrumentType.UP_DOWN_COUNTER + || instrumentType == InstrumentType.OBSERVABLE_UP_DOWN_COUNTER + ? AggregationTemporality.CUMULATIVE + : AggregationTemporality.DELTA); + } + + @Test + void setAggregationTemporalitySelector_null() { + assertThatThrownBy( + () -> InMemoryMetricExporter.builder().setAggregationTemporalitySelector(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("aggregationTemporalitySelector"); + } + + @Test + void builder_reusable() { + InMemoryMetricExporterBuilder builder = InMemoryMetricExporter.builder(); + InMemoryMetricExporter cumulativeExporter = builder.build(); + InMemoryMetricExporter deltaExporter = + builder + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build(); + + assertThat(cumulativeExporter.getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.CUMULATIVE); + assertThat(deltaExporter.getAggregationTemporality(InstrumentType.COUNTER)) + .isEqualTo(AggregationTemporality.DELTA); + } + + @Test + void export_deltaPreferred() { + InMemoryMetricExporter deltaExporter = + InMemoryMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build(); + TestClock clock = TestClock.create(); + PeriodicMetricReader reader = + PeriodicMetricReader.builder(deltaExporter).setInterval(Duration.ofDays(1)).build(); + try (SdkMeterProvider meterProvider = + SdkMeterProvider.builder().setClock(clock).registerMetricReader(reader).build()) { + Meter meter = meterProvider.get("test"); + LongCounter counter = meter.counterBuilder("counter").build(); + LongUpDownCounter upDownCounter = meter.upDownCounterBuilder("upDownCounter").build(); + + for (int value : new int[] {1, 2}) { + counter.add(value); + upDownCounter.add(value == 1 ? 1 : -1); + clock.advance(Duration.ofSeconds(1)); + + assertThat(reader.forceFlush().join(10, TimeUnit.SECONDS).isSuccess()).isTrue(); + assertThat(deltaExporter.getFinishedMetricItems()) + .filteredOn(metric -> metric.getInstrumentationScopeInfo().getName().equals("test")) + .satisfiesExactlyInAnyOrder( + metric -> + assertThat(metric) + .hasName("counter") + .hasLongSumSatisfying(sum -> + sum.isDelta().hasPointsSatisfying(point -> point.hasValue(value))), + metric -> + assertThat(metric) + .hasName("upDownCounter") + .hasLongSumSatisfying(sum -> + sum.isCumulative() + .hasPointsSatisfying(point -> point.hasValue(value == 1 ? 1 : 0)))); + deltaExporter.reset(); + } + } + } + + @Test + void export_preservesMetricData() { + InMemoryMetricExporter deltaExporter = + InMemoryMetricExporter.builder() + .setAggregationTemporalitySelector(AggregationTemporalitySelector.deltaPreferred()) + .build(); + MetricData metric = generateFakeMetric(); + + assertThat(deltaExporter.export(Collections.singletonList(metric)).isSuccess()).isTrue(); + assertThat(deltaExporter.getFinishedMetricItems()).singleElement().isSameAs(metric); } @Test diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderTest.java index 9df4a48c783..8dadfd14bbd 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/exporter/InMemoryMetricReaderTest.java @@ -92,7 +92,6 @@ void shutdown_Cumulative() { @Test void stringRepresentation() { - assertThat(deltaReader.toString()) - .isEqualTo("InMemoryMetricReader{aggregationTemporality=DELTA}"); + assertThat(deltaReader.toString()).isEqualTo("InMemoryMetricReader{}"); } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java index a9450c471fb..244b5fb4b0c 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit4/OpenTelemetryRuleTest.java @@ -7,10 +7,20 @@ import static org.assertj.core.api.Assertions.assertThat; +import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Logger; import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.context.propagation.TextMapSetter; import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; @@ -21,11 +31,13 @@ public class OpenTelemetryRuleTest { private Tracer tracer; private Meter meter; + private Logger logger; @Before public void setup() { tracer = otelTesting.getOpenTelemetry().getTracer("test"); meter = otelTesting.getOpenTelemetry().getMeter("test"); + logger = otelTesting.getOpenTelemetry().getLogsBridge().get("test"); } @Test @@ -61,12 +73,10 @@ public void getMetrics() { counter.add(1); OpenTelemetryAssertions.assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - OpenTelemetryAssertions.assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactlyInAnyOrder(metricData -> + OpenTelemetryAssertions.assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } // We have two tests to verify metrics get cleared up between tests. @@ -76,11 +86,67 @@ public void getMetricsAgain() { counter.add(1); OpenTelemetryAssertions.assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - OpenTelemetryAssertions.assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + .satisfiesExactlyInAnyOrder(metricData -> + OpenTelemetryAssertions.assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + } + + @Test + public void getLogRecords() { + logger.logRecordBuilder().setBody("body").emit(); + + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + // Logs cleared between tests, not when retrieving + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + } + + // We have two tests to verify logs get cleared up between tests. + @Test + public void getLogRecordsAgain() { + logger.logRecordBuilder().setBody("body").emit(); + + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + // Logs cleared between tests, not when retrieving + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + } + + @Test + public void baggageAndTracePropagation() { + OpenTelemetryRule rule = OpenTelemetryRule.create(); + Span span = rule.getOpenTelemetry().getTracer("test").spanBuilder("test").startSpan(); + try (Scope baggageScope = Baggage.builder().put("key", "value").build().makeCurrent(); + Scope spanScope = span.makeCurrent()) { + Map carrier = new HashMap<>(); + rule.getOpenTelemetry() + .getPropagators() + .getTextMapPropagator() + .inject(Context.current(), carrier, new MapTextMapSetter()); + assertThat(carrier).containsEntry("baggage", "key=value"); + assertThat(carrier).containsKey("traceparent"); + } finally { + span.end(); + } + } + + public static class MapTextMapSetter implements TextMapSetter> { + @Override + public void set(@Nullable Map carrier, String key, String value) { + if (carrier != null) { + carrier.put(key, value); + } + } } } diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionNestedTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionNestedTest.java new file mode 100644 index 00000000000..302b3e5974e --- /dev/null +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionNestedTest.java @@ -0,0 +1,47 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.testing.junit5; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.trace.Tracer; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class OpenTelemetryExtensionNestedTest { + @RegisterExtension + static final OpenTelemetryExtension otelTesting = OpenTelemetryExtension.create(); + + private final Tracer tracer = otelTesting.getOpenTelemetry().getTracer("test"); + + @Nested + class FirstNestedClass { + + @Test + void recordSpan() { + String testSpanName = "span-from-first-nested"; + tracer.spanBuilder(testSpanName).startSpan().end(); + + assertThat(otelTesting.getSpans()) + .singleElement() + .satisfies(span -> assertThat(span.getName()).isEqualTo(testSpanName)); + } + } + + @Nested + class SecondNestedClass { + @Test + void recordSpan() { + String testSpanName = "span-from-second-nested"; + tracer.spanBuilder(testSpanName).startSpan().end(); + + assertThat(otelTesting.getSpans()) + .singleElement() + .satisfies(span -> assertThat(span.getName()).isEqualTo(testSpanName)); + } + } +} diff --git a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java index 4c579c3bfe8..e6bc5251532 100644 --- a/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java +++ b/sdk/testing/src/test/java/io/opentelemetry/sdk/testing/junit5/OpenTelemetryExtensionTest.java @@ -5,20 +5,34 @@ package io.opentelemetry.sdk.testing.junit5; -import static org.assertj.core.api.Assertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; +import io.opentelemetry.api.GlobalOpenTelemetry; +import io.opentelemetry.api.OpenTelemetry; +import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.common.Value; +import io.opentelemetry.api.logs.Logger; import io.opentelemetry.api.metrics.LongCounter; import io.opentelemetry.api.metrics.Meter; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; import io.opentelemetry.context.Scope; -import io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions; +import io.opentelemetry.context.propagation.TextMapSetter; import io.opentelemetry.sdk.trace.data.SpanData; import java.util.Arrays; +import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import javax.annotation.Nullable; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.RegisterExtension; class OpenTelemetryExtensionTest { @@ -28,6 +42,7 @@ class OpenTelemetryExtensionTest { private final Tracer tracer = otelTesting.getOpenTelemetry().getTracer("test"); private final Meter meter = otelTesting.getOpenTelemetry().getMeter("test"); + private final Logger logger = otelTesting.getOpenTelemetry().getLogsBridge().get("test"); @Test public void getSpans() { @@ -58,9 +73,9 @@ public void getSpansAgain() { @Test public void assertTraces() { - Span span = tracer.spanBuilder("testa1").startSpan(); + Span span = tracer.spanBuilder("testa1").setStartTimestamp(1000, TimeUnit.SECONDS).startSpan(); try (Scope ignored = span.makeCurrent()) { - tracer.spanBuilder("testa2").startSpan().end(); + tracer.spanBuilder("testa2").setStartTimestamp(1000, TimeUnit.SECONDS).startSpan().end(); } finally { span.end(); } @@ -124,11 +139,8 @@ public void assertTraces() { s -> s.hasName("testb2"), s -> s.hasName("testexception"))))); - assertThatThrownBy( - () -> - otelTesting - .assertTraces() - .hasTracesSatisfyingExactly(trace -> trace.hasTraceId("foo"))) + assertThatThrownBy(() -> + otelTesting.assertTraces().hasTracesSatisfyingExactly(trace -> trace.hasTraceId("foo"))) .isInstanceOf(AssertionError.class); otelTesting @@ -138,10 +150,8 @@ public void assertTraces() { otelTesting .assertTraces() .filteredOn(trace -> trace.size() == 2) - .hasTracesSatisfyingExactly( - trace -> - trace.hasSpansSatisfyingExactly( - s -> s.hasName("testa1"), s -> s.hasName("testa2"))); + .hasTracesSatisfyingExactly(trace -> + trace.hasSpansSatisfyingExactly(s -> s.hasName("testa1"), s -> s.hasName("testa2"))); } @Test @@ -149,13 +159,11 @@ void getMetrics() { LongCounter counter = meter.counterBuilder("counter").build(); counter.add(1); - OpenTelemetryAssertions.assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - OpenTelemetryAssertions.assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + assertThat(otelTesting.getMetrics()) + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); } // We have two tests to verify metrics get cleared up between tests. @@ -164,12 +172,123 @@ void getMetricsAgain() { LongCounter counter = meter.counterBuilder("counter").build(); counter.add(1); - OpenTelemetryAssertions.assertThat(otelTesting.getMetrics()) - .satisfiesExactlyInAnyOrder( - metricData -> - OpenTelemetryAssertions.assertThat(metricData) - .hasName("counter") - .hasLongSumSatisfying( - sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + assertThat(otelTesting.getMetrics()) + .satisfiesExactlyInAnyOrder(metricData -> + assertThat(metricData) + .hasName("counter") + .hasLongSumSatisfying(sum -> sum.hasPointsSatisfying(point -> point.hasValue(1)))); + } + + @Test + public void getLogRecords() { + logger.logRecordBuilder().setBody("body").emit(); + + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + // Logs cleared between tests, not when retrieving + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + } + + // We have two tests to verify spans get cleared up between tests. + @Test + public void getLogRecordsAgain() { + logger.logRecordBuilder().setBody("body").emit(); + + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + // Logs cleared between tests, not when retrieving + assertThat(otelTesting.getLogRecords()) + .singleElement() + .satisfies( + logRecordData -> assertThat(logRecordData.getBodyValue()).isEqualTo(Value.of("body"))); + } + + @Test + void afterAll() { + // Use a different instance of OpenTelemetryExtension to avoid interfering with other tests + OpenTelemetryExtension extension = OpenTelemetryExtension.create(); + + ExtensionContext parentContext = spy(ExtensionContext.class); + when(parentContext.getTestClass()).thenReturn(Optional.empty()); + + ExtensionContext context = spy(ExtensionContext.class); + when(context.getParent()).thenReturn(Optional.of(parentContext)); + + extension.beforeAll(context); + + Meter meter = extension.getOpenTelemetry().getMeter("meter"); + Tracer tracer = extension.getOpenTelemetry().getTracer("tracer"); + + meter.counterBuilder("counter").build().add(10); + tracer.spanBuilder("span").startSpan().end(); + assertThat(extension.getMetrics()).isNotEmpty(); + assertThat(extension.getSpans()).isNotEmpty(); + + extension.afterAll(context); + assertThat(GlobalOpenTelemetry.get()).extracting("delegate").isSameAs(OpenTelemetry.noop()); + + meter.counterBuilder("counter").build().add(10); + tracer.spanBuilder("span").startSpan().end(); + assertThat(extension.getMetrics()).isEmpty(); + assertThat(extension.getSpans()).isEmpty(); + } + + @Test + void afterAllNestedOnly() { + // Demonstrate specifically that Nested tests do not reset extension sdk + OpenTelemetryExtension extension = OpenTelemetryExtension.create(); + + ExtensionContext context = spy(ExtensionContext.class); + when(context.getParent()).thenReturn(Optional.empty()); + + extension.beforeAll(context); + + Meter meter = extension.getOpenTelemetry().getMeter("meter"); + Tracer tracer = extension.getOpenTelemetry().getTracer("tracer"); + + extension.afterAll(context); + + assertThat(GlobalOpenTelemetry.get()).extracting("delegate").isSameAs(OpenTelemetry.noop()); + + // GlobalTelemetry was reset, but extension's sdk was not closed + meter.counterBuilder("counter").build().add(10); + tracer.spanBuilder("span").startSpan().end(); + assertThat(extension.getMetrics()).isNotEmpty(); + assertThat(extension.getSpans()).isNotEmpty(); + } + + @Test + void baggageAndTracePropagation() { + OpenTelemetryExtension extension = OpenTelemetryExtension.create(); + Span span = extension.getOpenTelemetry().getTracer("test").spanBuilder("test").startSpan(); + try (Scope baggageScope = Baggage.builder().put("key", "value").build().makeCurrent(); + Scope spanScope = span.makeCurrent()) { + Map carrier = new HashMap<>(); + extension + .getOpenTelemetry() + .getPropagators() + .getTextMapPropagator() + .inject(Context.current(), carrier, new MapTextMapSetter()); + assertThat(carrier).containsEntry("baggage", "key=value"); + assertThat(carrier).containsKey("traceparent"); + } finally { + span.end(); + } + } + + public static class MapTextMapSetter implements TextMapSetter> { + @Override + public void set(@Nullable Map carrier, String key, String value) { + if (carrier != null) { + carrier.put(key, value); + } + } } } diff --git a/sdk/trace-shaded-deps/build.gradle.kts b/sdk/trace-shaded-deps/build.gradle.kts index 14f73ca4b79..40fc36592cd 100644 --- a/sdk/trace-shaded-deps/build.gradle.kts +++ b/sdk/trace-shaded-deps/build.gradle.kts @@ -1,13 +1,15 @@ plugins { id("otel.java-conventions") - id("com.github.johnrengelman.shadow") + id("com.gradleup.shadow") } // This project is not published, it is bundled into :sdk:trace description = "Internal use only - shaded dependencies of OpenTelemetry SDK for Tracing" otelJava.moduleName.set("io.opentelemetry.sdk.trace.internal") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) dependencies { implementation("org.jctools:jctools-core") @@ -17,12 +19,18 @@ tasks { shadowJar { minimize() - relocate("org.jctools", "io.opentelemetry.internal.shaded.jctools") + exclude("META-INF/maven/**") + relocate("org.jctools", "io.opentelemetry.sdk.trace.internal.shaded.jctools") } - val extractShadowJar by registering(Copy::class) { + register("extractShadowJar") { dependsOn(shadowJar) from(zipTree(shadowJar.get().archiveFile)) into("build/extracted/shadow") } } + +tasks.withType().configureEach { + // JcToolsSecurityManagerTest interferes with JcToolsTest + setForkEvery(1) +} diff --git a/sdk/trace-shaded-deps/src/main/java/io/opentelemetry/sdk/trace/internal/JcTools.java b/sdk/trace-shaded-deps/src/main/java/io/opentelemetry/sdk/trace/internal/JcTools.java index 026f4c6d82e..cef70f486bf 100644 --- a/sdk/trace-shaded-deps/src/main/java/io/opentelemetry/sdk/trace/internal/JcTools.java +++ b/sdk/trace-shaded-deps/src/main/java/io/opentelemetry/sdk/trace/internal/JcTools.java @@ -6,9 +6,9 @@ package io.opentelemetry.sdk.trace.internal; import java.util.Queue; -import java.util.concurrent.ArrayBlockingQueue; +import java.util.function.Consumer; import org.jctools.queues.MessagePassingQueue; -import org.jctools.queues.MpscArrayQueue; +import org.jctools.queues.atomic.MpscAtomicArrayQueue; /** * Internal accessor of JCTools package for fast queues. @@ -22,12 +22,7 @@ public final class JcTools { * Returns a new {@link Queue} appropriate for use with multiple producers and a single consumer. */ public static Queue newFixedSizeQueue(int capacity) { - try { - return new MpscArrayQueue<>(capacity); - } catch (java.lang.NoClassDefFoundError e) { - // Happens when modules such as jdk.unsupported are disabled in a custom JRE distribution - return new ArrayBlockingQueue<>(capacity); - } + return new MpscAtomicArrayQueue<>(capacity); } /** @@ -35,11 +30,18 @@ public static Queue newFixedSizeQueue(int capacity) { * to use the shaded classes. */ public static long capacity(Queue queue) { - if (queue instanceof MessagePassingQueue) { - return ((MessagePassingQueue) queue).capacity(); - } else { - return (long) ((ArrayBlockingQueue) queue).remainingCapacity() + queue.size(); - } + return ((MessagePassingQueue) queue).capacity(); + } + + /** + * Remove up to limit elements from the {@link Queue} and hand to consume. + * + * @throws IllegalArgumentException consumer is {@code null} + * @throws IllegalArgumentException if limit is negative + */ + @SuppressWarnings("unchecked") + public static int drain(Queue queue, int limit, Consumer consumer) { + return ((MessagePassingQueue) queue).drain(consumer::accept, limit); } private JcTools() {} diff --git a/sdk/trace-shaded-deps/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-sdk-trace/reflect-config.json b/sdk/trace-shaded-deps/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-sdk-trace/reflect-config.json new file mode 100644 index 00000000000..59812d53bbe --- /dev/null +++ b/sdk/trace-shaded-deps/src/main/resources/META-INF/native-image/io.opentelemetry/opentelemetry-sdk-trace/reflect-config.json @@ -0,0 +1,35 @@ +[ + { + "condition": { + "typeReachable": "io.opentelemetry.sdk.trace.internal.shaded.jctools.queues.MpscArrayQueueConsumerIndexField" + }, + "name": "io.opentelemetry.sdk.trace.internal.shaded.jctools.queues.MpscArrayQueueConsumerIndexField", + "fields": [ + { + "name": "consumerIndex" + } + ] + }, + { + "condition": { + "typeReachable": "io.opentelemetry.sdk.trace.internal.shaded.jctools.queues.MpscArrayQueueProducerIndexField" + }, + "name": "io.opentelemetry.sdk.trace.internal.shaded.jctools.queues.MpscArrayQueueProducerIndexField", + "fields": [ + { + "name": "producerIndex" + } + ] + }, + { + "condition": { + "typeReachable": "io.opentelemetry.sdk.trace.internal.shaded.jctools.queues.MpscArrayQueueProducerLimitField" + }, + "name": "io.opentelemetry.sdk.trace.internal.shaded.jctools.queues.MpscArrayQueueProducerLimitField", + "fields": [ + { + "name": "producerLimit" + } + ] + } +] diff --git a/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/JcToolsSecurityManagerTest.java b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/JcToolsSecurityManagerTest.java new file mode 100644 index 00000000000..56a5c4143c6 --- /dev/null +++ b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/JcToolsSecurityManagerTest.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.util.Queue; +import org.jctools.queues.atomic.MpscAtomicArrayQueue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; + +public class JcToolsSecurityManagerTest { + + @Test + // System.setSecurityManager throws UnsupportedOperationException in Java 18+ + @EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_17}) + @SuppressLogger(JcTools.class) + void newFixedSizeQueue_SunMiscProhibited() { + assertThat(System.getSecurityManager()).isNull(); + SunMiscProhibitedSecurityManager testingSecurityManager = + new SunMiscProhibitedSecurityManager(); + try { + System.setSecurityManager(testingSecurityManager); + Queue queue = + AccessController.doPrivileged( + (PrivilegedAction>) () -> JcTools.newFixedSizeQueue(10)); + assertThat(queue).isInstanceOf(MpscAtomicArrayQueue.class); + } finally { + System.setSecurityManager(null); + } + } +} diff --git a/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/JcToolsTest.java b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/JcToolsTest.java new file mode 100644 index 00000000000..1fad53021da --- /dev/null +++ b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/JcToolsTest.java @@ -0,0 +1,74 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.ArrayList; +import java.util.Queue; +import org.jctools.queues.MessagePassingQueue; +import org.junit.jupiter.api.Test; + +class JcToolsTest { + + ArrayList batch = new ArrayList<>(10); + + @Test + void drain_MessagePassingQueue() { + // Arrange + batch.add("Test3"); + Queue queue = JcTools.newFixedSizeQueue(10); + queue.add("Test1"); + queue.add("Test2"); + + // Act + JcTools.drain(queue, 5, batch::add); + + // Assert + assertThat(batch).hasSize(3); + assertThat(queue).hasSize(0); + } + + @Test + void drain_MaxBatch() { + // Arrange + Queue queue = JcTools.newFixedSizeQueue(10); + queue.add("Test1"); + queue.add("Test2"); + + // Act + JcTools.drain(queue, 1, batch::add); + + // Assert + assertThat(batch).hasSize(1); + assertThat(queue).hasSize(1); + } + + @Test + void newFixedSize_MpscQueue() { + // Arrange + int capacity = 10; + + // Act + Queue objects = JcTools.newFixedSizeQueue(capacity); + + // Assert + assertThat(objects).isInstanceOf(MessagePassingQueue.class); + } + + @Test + void capacity_MpscQueue() { + // Arrange + int capacity = 10; + Queue queue = JcTools.newFixedSizeQueue(capacity); + + // Act + long queueSize = JcTools.capacity(queue); + + // Assert + assertThat(queueSize).isGreaterThan(capacity); + } +} diff --git a/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/SunMiscProhibitedSecurityManager.java b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/SunMiscProhibitedSecurityManager.java new file mode 100644 index 00000000000..a158cc02ec9 --- /dev/null +++ b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/SunMiscProhibitedSecurityManager.java @@ -0,0 +1,111 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import java.io.FileDescriptor; +import java.net.InetAddress; +import java.security.AccessControlException; +import java.security.Permission; + +/** + * A security manager which disallows access to classes in sun.misc. Running the tests with a + * standard security manager is too invasive. + */ +public class SunMiscProhibitedSecurityManager extends SecurityManager { + + public SunMiscProhibitedSecurityManager() {} + + @Override + protected Class[] getClassContext() { + return super.getClassContext(); + } + + @Override + public void checkPermission(Permission perm) { + if (perm.getName().equals("accessClassInPackage.sun.misc")) { + throw new AccessControlException("access denied " + perm, perm); + } + } + + @Override + public void checkPermission(Permission perm, Object context) {} + + @Override + public void checkCreateClassLoader() {} + + @Override + public void checkAccess(Thread t) {} + + @Override + public void checkAccess(ThreadGroup g) {} + + @Override + public void checkExit(int status) {} + + @Override + public void checkExec(String cmd) {} + + @Override + public void checkLink(String lib) {} + + @Override + public void checkRead(FileDescriptor fd) {} + + @Override + public void checkRead(String file) {} + + @Override + public void checkRead(String file, Object context) {} + + @Override + public void checkWrite(FileDescriptor fd) {} + + @Override + public void checkWrite(String file) {} + + @Override + public void checkDelete(String file) {} + + @Override + public void checkConnect(String host, int port) {} + + @Override + public void checkConnect(String host, int port, Object context) {} + + @Override + public void checkListen(int port) {} + + @Override + public void checkAccept(String host, int port) {} + + @Override + public void checkMulticast(InetAddress maddr) {} + + @Override + public void checkPropertiesAccess() {} + + @Override + public void checkPropertyAccess(String key) {} + + @Override + public void checkPrintJobAccess() {} + + @Override + public void checkPackageAccess(String pkg) { + if (pkg.equals("sun.misc")) { + super.checkPackageAccess(pkg); + } + } + + @Override + public void checkPackageDefinition(String pkg) {} + + @Override + public void checkSetFactory() {} + + @Override + public void checkSecurityAccess(String target) {} +} diff --git a/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/SunMiscProhibitedSecurityManagerTest.java b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/SunMiscProhibitedSecurityManagerTest.java new file mode 100644 index 00000000000..205f2385fc1 --- /dev/null +++ b/sdk/trace-shaded-deps/src/test/java/io/opentelemetry/sdk/trace/internal/SunMiscProhibitedSecurityManagerTest.java @@ -0,0 +1,45 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import static org.assertj.core.api.Assertions.assertThatNoException; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.security.AccessControlException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnJre; +import org.junit.jupiter.api.condition.JRE; + +// Security manager removed in Java 24 +@EnabledOnJre({JRE.JAVA_8, JRE.JAVA_11, JRE.JAVA_17, JRE.JAVA_21}) +class SunMiscProhibitedSecurityManagerTest { + + @Test + public void checkPackageAccess_ProhibitsSunMisc() { + SunMiscProhibitedSecurityManager sm = new SunMiscProhibitedSecurityManager(); + assertThatThrownBy(() -> sm.checkPackageAccess("sun.misc")) + .isInstanceOf(AccessControlException.class) + .hasMessage( + "access denied (\"java.lang.RuntimePermission\" \"accessClassInPackage.sun.misc\")"); + } + + @Test + public void checkPackageAccess_ProhibitsSunMiscRuntimePermission() { + SunMiscProhibitedSecurityManager sm = new SunMiscProhibitedSecurityManager(); + + assertThatThrownBy( + () -> sm.checkPermission(new RuntimePermission("accessClassInPackage.sun.misc"))) + .isInstanceOf(AccessControlException.class) + .hasMessage( + "access denied (\"java.lang.RuntimePermission\" \"accessClassInPackage.sun.misc\")"); + } + + @Test + public void checkPackageAccess_AllowsOtherPackage() { + SunMiscProhibitedSecurityManager sm = new SunMiscProhibitedSecurityManager(); + assertThatNoException().isThrownBy(() -> sm.checkPackageAccess("io.opentelemetry.sdk")); + } +} diff --git a/sdk/trace/README.md b/sdk/trace/README.md deleted file mode 100644 index 7798d150306..00000000000 --- a/sdk/trace/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# OpenTelemetry Trace SDK - -[![Javadocs][javadoc-image]][javadoc-url] - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-sdk-trace.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-sdk-trace diff --git a/sdk/trace/build.gradle.kts b/sdk/trace/build.gradle.kts index 88afa8a2e29..c63d20fb74d 100644 --- a/sdk/trace/build.gradle.kts +++ b/sdk/trace/build.gradle.kts @@ -1,5 +1,3 @@ -import ru.vyarus.gradle.plugin.animalsniffer.AnimalSniffer - plugins { id("otel.java-conventions") id("otel.publish-conventions") @@ -10,6 +8,8 @@ plugins { description = "OpenTelemetry SDK For Tracing" otelJava.moduleName.set("io.opentelemetry.sdk.trace") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiOptionalPackages.set(listOf("io.opentelemetry.api.incubator")) sourceSets { main { @@ -22,10 +22,9 @@ dependencies { api(project(":api:all")) api(project(":sdk:common")) + compileOnly(project(":api:incubator")) compileOnly(project(":sdk:trace-shaded-deps")) - implementation(project(":semconv")) - annotationProcessor("com.google.auto.value:auto-value") testAnnotationProcessor("com.google.auto.value:auto-value") @@ -41,9 +40,8 @@ dependencies { // dependencies. isTransitive = false } - jmh(project(":exporters:jaeger-thrift")) - jmh(project(":exporters:otlp:trace")) { - // The opentelemetry-exporter-otlp-trace depends on this project itself. So don"t pull in + jmh(project(":exporters:otlp:all")) { + // The opentelemetry-exporter-otlp depends on this project itself. So don't pull in // the transitive dependencies. isTransitive = false } @@ -51,6 +49,13 @@ dependencies { jmh(project(":exporters:otlp:common")) { isTransitive = false } + jmh(project(":exporters:common")) { + isTransitive = false + } + jmh(project(":exporters:sender:okhttp")) + jmh(project(":sdk-extensions:autoconfigure-spi")) { + isTransitive = false + } jmh("io.opentelemetry.proto:opentelemetry-proto") jmh("com.google.guava:guava") @@ -59,10 +64,19 @@ dependencies { jmh("org.testcontainers:testcontainers") // testContainer for OTLP collector } +testing { + suites { + register("testIncubating") { + dependencies { + implementation(project(":sdk:testing")) + implementation(project(":api:incubator")) + } + } + } +} + tasks { - withType().configureEach { - // We catch NoClassDefFoundError to fallback to non-jctools queues. - exclude("**/internal/shaded/jctools/**") - exclude("**/internal/JcTools*") + check { + dependsOn(testing.suites) } } diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExceptionBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExceptionBenchmark.java deleted file mode 100644 index 438deb7b69d..00000000000 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExceptionBenchmark.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace; - -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.SpanBuilder; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.BenchmarkMode; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.Mode; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Threads; -import org.openjdk.jmh.annotations.Warmup; - -@State(Scope.Benchmark) -public class ExceptionBenchmark { - private static SpanBuilder spanBuilder; - - @Setup(Level.Trial) - public final void setup() { - SdkTracerProvider tracerProvider = - SdkTracerProvider.builder().setSampler(Sampler.alwaysOn()).build(); - - Tracer tracer = tracerProvider.get("benchmarkTracer"); - spanBuilder = tracer.spanBuilder("benchmarkSpanBuilder"); - } - - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @BenchmarkMode(Mode.AverageTime) - public Span createSpan() { - Span span = spanBuilder.startSpan(); - span.end(); - return span; - } - - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @BenchmarkMode(Mode.AverageTime) - public Span createSpanAndRecordException() { - Span span = spanBuilder.startSpan(); - span.recordException(new RuntimeException()); - span.end(); - return span; - } - - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.NANOSECONDS) - @BenchmarkMode(Mode.AverageTime) - public RuntimeException createException() { - return new RuntimeException(); - } -} diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExporterBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExporterBenchmark.java index c1837a2f872..a355dcc9c56 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExporterBenchmark.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/ExporterBenchmark.java @@ -7,7 +7,6 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.exporter.jaeger.thrift.JaegerThriftSpanExporter; import io.opentelemetry.exporter.otlp.trace.OtlpGrpcSpanExporter; import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; @@ -37,9 +36,9 @@ private ExporterBenchmark() {} @State(Scope.Benchmark) public abstract static class AbstractProcessorBenchmark { private static final DockerImageName OTLP_COLLECTOR_IMAGE = - DockerImageName.parse("otel/opentelemetry-collector-dev:latest"); + DockerImageName.parse( + "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea"); protected static final int OTLP_PORT = 5678; - protected static final int JAEGER_PORT = 14268; private static final int HEALTH_CHECK_PORT = 13133; protected SdkSpanBuilder sdkSpanBuilder; @@ -50,7 +49,7 @@ public void setup() { // Configuring the collector test-container GenericContainer collector = new GenericContainer<>(OTLP_COLLECTOR_IMAGE) - .withExposedPorts(OTLP_PORT, HEALTH_CHECK_PORT, JAEGER_PORT) + .withExposedPorts(OTLP_PORT, HEALTH_CHECK_PORT) .waitingFor(Wait.forHttp("/").forPort(HEALTH_CHECK_PORT)) .withCopyFileToContainer( MountableFile.forClasspathResource("/otel.yaml"), "/etc/otel.yaml") @@ -93,15 +92,4 @@ protected OtlpGrpcSpanExporter createExporter(GenericContainer collector) { .build(); } } - - public static class JaegerBenchmark extends AbstractProcessorBenchmark { - @Override - protected JaegerThriftSpanExporter createExporter(GenericContainer collector) { - String host = collector.getHost(); - int port = collector.getMappedPort(JAEGER_PORT); - return JaegerThriftSpanExporter.builder() - .setEndpoint("http://" + host + ":" + port + "/api/traces") - .build(); - } - } } diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/PrintThrowableBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/PrintThrowableBenchmark.java deleted file mode 100644 index 153581fe733..00000000000 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/PrintThrowableBenchmark.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace; - -import com.google.common.io.CharStreams; -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.nio.charset.StandardCharsets; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Threads; -import org.openjdk.jmh.annotations.Warmup; - -@Threads(value = 1) -@Fork(3) -@Warmup(iterations = 10, time = 1) -@Measurement(iterations = 20, time = 1) -@OutputTimeUnit(TimeUnit.MILLISECONDS) -public class PrintThrowableBenchmark { - - private static final int THROWABLE_SIZE = 50; - - private static final Throwable THROWABLE; - - static { - Throwable throwable = null; - try { - throwAfter(THROWABLE_SIZE); - } catch (Throwable t) { - throwable = t; - } - if (throwable == null) { - throw new AssertionError(); - } - THROWABLE = throwable; - } - - private static void throwAfter(int count) { - if (count == THROWABLE_SIZE) { - throw new AssertionError("threw"); - } else { - throwAfter(count + 1); - } - } - - /** Measures performance of {@link StringBuilder} + Guava {@link CharStreams}. */ - @Benchmark - public String normalPrintWriter() { - StringBuilder sb = new StringBuilder(); - PrintWriter writer = new PrintWriter(CharStreams.asWriter(sb)); - THROWABLE.printStackTrace(writer); - return sb.toString(); - } - - /** Measures performance of JDK {@link StringWriter}. */ - @Benchmark - public String stringWriter() { - StringWriter sw = new StringWriter(); - PrintWriter writer = new PrintWriter(sw); - THROWABLE.printStackTrace(writer); - return sw.toString(); - } - - /** Measures performance of a {@link PrintStream}. */ - @Benchmark - public String printStream() throws Exception { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - PrintStream stream = new PrintStream(bos); - THROWABLE.printStackTrace(stream); - return bos.toString(StandardCharsets.UTF_8.name()); - } -} diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanBenchmark.java deleted file mode 100644 index c8063e1bb07..00000000000 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanBenchmark.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.trace.Span; -import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.resources.Resource; -import io.opentelemetry.sdk.trace.samplers.Sampler; -import java.util.concurrent.TimeUnit; -import org.openjdk.jmh.annotations.Benchmark; -import org.openjdk.jmh.annotations.Fork; -import org.openjdk.jmh.annotations.Level; -import org.openjdk.jmh.annotations.Measurement; -import org.openjdk.jmh.annotations.OutputTimeUnit; -import org.openjdk.jmh.annotations.Scope; -import org.openjdk.jmh.annotations.Setup; -import org.openjdk.jmh.annotations.State; -import org.openjdk.jmh.annotations.Threads; -import org.openjdk.jmh.annotations.Warmup; - -@State(Scope.Benchmark) -public class SpanBenchmark { - private static SdkSpanBuilder sdkSpanBuilder; - private final Resource serviceResource = - Resource.create( - Attributes.builder() - .put("service.name", "benchmark1") - .put("service.version", "123.456.89") - .put("service.instance.id", "123ab456-a123-12ab-12ab-12340a1abc12") - .build()); - - @Setup(Level.Trial) - public final void setup() { - SdkTracerProvider tracerProvider = - SdkTracerProvider.builder() - .setResource(serviceResource) - .setSampler(Sampler.alwaysOn()) - .build(); - - Tracer tracerSdk = tracerProvider.get("benchmarkTracer"); - sdkSpanBuilder = - (SdkSpanBuilder) - tracerSdk.spanBuilder("benchmarkSpanBuilder").setAttribute("longAttribute", 33L); - } - - @Benchmark - @Threads(value = 1) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void simpleSpanStartAddEventEnd_01Thread() { - doSpanWork(); - } - - @Benchmark - @Threads(value = 5) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void simpleSpanStartAddEventEnd_05Threads() { - doSpanWork(); - } - - @Benchmark - @Threads(value = 2) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void simpleSpanStartAddEventEnd_02Threads() { - doSpanWork(); - } - - @Benchmark - @Threads(value = 10) - @Fork(1) - @Warmup(iterations = 5, time = 1) - @Measurement(iterations = 10, time = 1) - @OutputTimeUnit(TimeUnit.MILLISECONDS) - public void simpleSpanStartAddEventEnd_10Threads() { - doSpanWork(); - } - - private static void doSpanWork() { - Span span = sdkSpanBuilder.startSpan(); - span.addEvent("testEvent"); - span.end(); - } -} diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanPipelineBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanPipelineBenchmark.java index 03684d1a348..e0b2e7a4b1b 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanPipelineBenchmark.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/SpanPipelineBenchmark.java @@ -38,7 +38,8 @@ private SpanPipelineBenchmark() {} @State(Scope.Benchmark) public abstract static class AbstractProcessorBenchmark { private static final DockerImageName OTLP_COLLECTOR_IMAGE = - DockerImageName.parse("otel/opentelemetry-collector-dev:latest"); + DockerImageName.parse( + "otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea"); private static final int EXPOSED_PORT = 5678; private static final int HEALTH_CHECK_PORT = 13133; private Tracer tracer; diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorCpuBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorCpuBenchmark.java index 7756a752b82..b5f86793f72 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorCpuBenchmark.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorCpuBenchmark.java @@ -28,6 +28,7 @@ import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.BenchmarkParams; /* * Run this along with a profiler to measure the CPU usage of BatchSpanProcessor's exporter thread. @@ -47,7 +48,8 @@ public static class BenchmarkState { private long droppedSpans; @Setup(Level.Iteration) - public final void setup() { + public final void setup(BenchmarkParams params) { + numThreads = params.getThreads(); metricReader = InMemoryMetricReader.create(); MeterProvider meterProvider = SdkMeterProvider.builder().registerMetricReader(metricReader).build(); @@ -110,7 +112,6 @@ private static void doWork(BenchmarkState benchmarkState) { @OutputTimeUnit(TimeUnit.SECONDS) public void export_01Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 1; doWork(benchmarkState); } @@ -123,7 +124,6 @@ public void export_01Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_02Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 2; doWork(benchmarkState); } @@ -136,7 +136,6 @@ public void export_02Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_05Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 5; doWork(benchmarkState); } @@ -149,7 +148,6 @@ public void export_05Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_10Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 10; doWork(benchmarkState); } @@ -162,7 +160,6 @@ public void export_10Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_20Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 20; doWork(benchmarkState); } } diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorDroppedSpansBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorDroppedSpansBenchmark.java index b5a438db88e..de580ccf4e6 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorDroppedSpansBenchmark.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorDroppedSpansBenchmark.java @@ -24,6 +24,7 @@ import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.BenchmarkParams; public class BatchSpanProcessorDroppedSpansBenchmark { @@ -36,9 +37,12 @@ public static class BenchmarkState { private long exportedSpans; private long droppedSpans; private int numThreads; + private int numIterations; @Setup(Level.Iteration) - public final void setup() { + public final void setup(BenchmarkParams params) { + numThreads = params.getThreads(); + numIterations = params.getMeasurement().getCount(); metricReader = InMemoryMetricReader.create(); MeterProvider meterProvider = SdkMeterProvider.builder().registerMetricReader(metricReader).build(); @@ -52,7 +56,7 @@ public final void setup() { public final void recordMetrics() { BatchSpanProcessorMetrics metrics = new BatchSpanProcessorMetrics(metricReader.collectAllMetrics(), numThreads); - dropRatio = metrics.dropRatio(); + dropRatio = metrics.dropRatio(numIterations); exportedSpans = metrics.exportedSpans(); droppedSpans = metrics.droppedSpans(); } @@ -64,7 +68,7 @@ public final void tearDown() { } @State(Scope.Thread) - @AuxCounters(AuxCounters.Type.OPERATIONS) + @AuxCounters(AuxCounters.Type.EVENTS) public static class ThreadState { BenchmarkState benchmarkState; @@ -95,7 +99,6 @@ public long droppedSpans() { @BenchmarkMode(Mode.Throughput) public void export( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 5; benchmarkState.processor.onEnd( (ReadableSpan) benchmarkState.tracer.spanBuilder("span").startSpan()); } diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorFlushBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorFlushBenchmark.java index 68517bc773d..e5b876abd9e 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorFlushBenchmark.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorFlushBenchmark.java @@ -8,14 +8,9 @@ import com.google.common.collect.ImmutableList; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; -import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.ReadableSpan; import io.opentelemetry.sdk.trace.SdkTracerProvider; -import io.opentelemetry.sdk.trace.data.SpanData; -import java.util.Collection; import java.util.List; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Fork; @@ -33,36 +28,6 @@ @State(Scope.Benchmark) public class BatchSpanProcessorFlushBenchmark { - private static class DelayingSpanExporter implements SpanExporter { - - private final ScheduledExecutorService executor; - - private final int delayMs; - - private DelayingSpanExporter(int delayMs) { - executor = Executors.newScheduledThreadPool(5); - this.delayMs = delayMs; - } - - @SuppressWarnings("FutureReturnValueIgnored") - @Override - public CompletableResultCode export(Collection spans) { - CompletableResultCode result = new CompletableResultCode(); - executor.schedule((Runnable) result::succeed, delayMs, TimeUnit.MILLISECONDS); - return result; - } - - @Override - public CompletableResultCode flush() { - return CompletableResultCode.ofSuccess(); - } - - @Override - public CompletableResultCode shutdown() { - return CompletableResultCode.ofSuccess(); - } - } - @Param({"0", "1", "5"}) private int delayMs; diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java index 9a74d60070e..cb0db4dc941 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMetrics.java @@ -5,12 +5,13 @@ package io.opentelemetry.sdk.trace.export; -import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.booleanKey; import io.opentelemetry.sdk.metrics.data.LongPointData; import io.opentelemetry.sdk.metrics.data.MetricData; import java.util.Collection; import java.util.OptionalLong; +import org.openjdk.jmh.annotations.AuxCounters; public class BatchSpanProcessorMetrics { private final Collection allMetrics; @@ -21,13 +22,26 @@ public BatchSpanProcessorMetrics(Collection allMetrics, int numThrea this.numThreads = numThreads; } - public double dropRatio() { + /** + * Returns the share of dropped spans as a value in {@code [0, 1]}. + * + *

      Only meaningful for benchmarks whose {@link AuxCounters} use {@link + * AuxCounters.Type#EVENTS}: JMH emits a {@code ScalarResult} with {@code AggregationPolicy.SUM}, + * which sums the aux counters across the {@code numThreads} thread-local {@code @State} instances + * and the {@code numIterations} measurement iterations. The raw {@code dropped / (exported + + * dropped)} is therefore inflated by {@code numThreads * numIterations}, and both factors are + * divided back out here so the value reported by JMH equals the per-iteration drop ratio. + * + *

      For {@link AuxCounters.Type#OPERATIONS} JMH emits a {@code ThroughputResult} (rate per unit + * time) aggregated as a mean across iterations, so this method does not apply β€” the drop rate is + * read directly from {@link #droppedSpans()} and the ratio, if needed, is computed from the two + * rates. + */ + public double dropRatio(int numIterations) { long exported = getMetric(false); long dropped = getMetric(true); long total = exported + dropped; - // Due to peculiarities of JMH reporting we have to divide this by the number of the - // concurrent threads running the actual benchmark. - return total == 0 ? 0 : (double) dropped / total / numThreads; + return total == 0 ? 0.0 : (double) dropped / total / numThreads / numIterations; } public long exportedSpans() { @@ -39,14 +53,16 @@ public long droppedSpans() { } private long getMetric(boolean dropped) { - String labelValue = String.valueOf(dropped); OptionalLong value = allMetrics.stream() .filter(metricData -> metricData.getName().equals("processedSpans")) .filter(metricData -> !metricData.isEmpty()) .map(metricData -> metricData.getLongSumData().getPoints()) .flatMap(Collection::stream) - .filter(point -> labelValue.equals(point.getAttributes().get(stringKey("dropped")))) + .filter(point -> { + Boolean attrDropped = point.getAttributes().get(booleanKey("dropped")); + return attrDropped != null && attrDropped == dropped; + }) .mapToLong(LongPointData::getValue) .findFirst(); return value.isPresent() ? value.getAsLong() : 0; diff --git a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMultiThreadBenchmark.java b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMultiThreadBenchmark.java index d8eabb090c3..c92c52f55fa 100644 --- a/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMultiThreadBenchmark.java +++ b/sdk/trace/src/jmh/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorMultiThreadBenchmark.java @@ -27,6 +27,7 @@ import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.annotations.Threads; import org.openjdk.jmh.annotations.Warmup; +import org.openjdk.jmh.infra.BenchmarkParams; @State(Scope.Benchmark) public class BatchSpanProcessorMultiThreadBenchmark { @@ -37,15 +38,19 @@ public static class BenchmarkState { private BatchSpanProcessor processor; private Tracer tracer; private int numThreads = 1; + private int numIterations = 1; @Param({"0"}) private int delayMs; + private double dropRatio; private long exportedSpans; private long droppedSpans; @Setup(Level.Iteration) - public final void setup() { + public final void setup(BenchmarkParams params) { + numThreads = params.getThreads(); + numIterations = params.getMeasurement().getCount(); collector = InMemoryMetricReader.create(); MeterProvider meterProvider = SdkMeterProvider.builder().registerMetricReader(collector).build(); @@ -59,6 +64,7 @@ public final void setup() { public final void recordMetrics() { BatchSpanProcessorMetrics metrics = new BatchSpanProcessorMetrics(collector.collectAllMetrics(), numThreads); + dropRatio = metrics.dropRatio(numIterations); exportedSpans = metrics.exportedSpans(); droppedSpans = metrics.droppedSpans(); processor.shutdown().join(10, TimeUnit.SECONDS); @@ -66,7 +72,7 @@ public final void recordMetrics() { } @State(Scope.Thread) - @AuxCounters(AuxCounters.Type.OPERATIONS) + @AuxCounters(AuxCounters.Type.EVENTS) public static class ThreadState { BenchmarkState benchmarkState; @@ -75,6 +81,10 @@ public final void recordMetrics(BenchmarkState benchmarkState) { this.benchmarkState = benchmarkState; } + public double dropRatio() { + return benchmarkState.dropRatio; + } + public long exportedSpans() { return benchmarkState.exportedSpans; } @@ -93,7 +103,6 @@ public long droppedSpans() { @OutputTimeUnit(TimeUnit.SECONDS) public void export_01Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 1; benchmarkState.processor.onEnd( (ReadableSpan) benchmarkState.tracer.spanBuilder("span").startSpan()); } @@ -107,7 +116,6 @@ public void export_01Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_02Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 2; benchmarkState.processor.onEnd( (ReadableSpan) benchmarkState.tracer.spanBuilder("span").startSpan()); } @@ -121,7 +129,6 @@ public void export_02Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_05Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 5; benchmarkState.processor.onEnd( (ReadableSpan) benchmarkState.tracer.spanBuilder("span").startSpan()); } @@ -135,7 +142,6 @@ public void export_05Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_10Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 10; benchmarkState.processor.onEnd( (ReadableSpan) benchmarkState.tracer.spanBuilder("span").startSpan()); } @@ -149,7 +155,6 @@ public void export_10Thread( @OutputTimeUnit(TimeUnit.SECONDS) public void export_20Thread( BenchmarkState benchmarkState, @SuppressWarnings("unused") ThreadState threadState) { - benchmarkState.numThreads = 20; benchmarkState.processor.onEnd( (ReadableSpan) benchmarkState.tracer.spanBuilder("span").startSpan()); } diff --git a/sdk/trace/src/jmh/resources/otel.yaml b/sdk/trace/src/jmh/resources/otel.yaml index 316ff8da1ef..b2fe534507f 100644 --- a/sdk/trace/src/jmh/resources/otel.yaml +++ b/sdk/trace/src/jmh/resources/otel.yaml @@ -3,9 +3,6 @@ receivers: protocols: grpc: endpoint: 0.0.0.0:5678 - jaeger: - protocols: - thrift_http: processors: batch: @@ -14,12 +11,12 @@ extensions: health_check: exporters: - logging: + debug: service: extensions: [health_check] pipelines: traces: - receivers: [otlp, jaeger] + receivers: [otlp] processors: [batch] - exporters: [logging] + exporters: [debug] diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AttributesMap.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AttributesMap.java deleted file mode 100644 index 53c52a8575d..00000000000 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AttributesMap.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace; - -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.internal.AttributeUtil; -import java.util.Collections; -import java.util.HashMap; -import java.util.Map; -import java.util.function.BiConsumer; -import javax.annotation.Nullable; - -/** - * A map with a fixed capacity that drops attributes when the map gets full, and which truncates - * string and array string attribute values to the {@link #lengthLimit}. - */ -final class AttributesMap extends HashMap, Object> implements Attributes { - - private static final long serialVersionUID = -5072696312123632376L; - - private final long capacity; - private final int lengthLimit; - private int totalAddedValues = 0; - - AttributesMap(long capacity, int lengthLimit) { - this.capacity = capacity; - this.lengthLimit = lengthLimit; - } - - void put(AttributeKey key, T value) { - totalAddedValues++; - if (size() >= capacity && !containsKey(key)) { - return; - } - super.put(key, AttributeUtil.applyAttributeLengthLimit(value, lengthLimit)); - } - - int getTotalAddedValues() { - return totalAddedValues; - } - - @SuppressWarnings("unchecked") - @Override - @Nullable - public T get(AttributeKey key) { - return (T) super.get(key); - } - - @Override - public Map, Object> asMap() { - // Because Attributes is marked Immutable, IDEs may recognize this as redundant usage. However, - // this class is private and is actually mutable, so we need to wrap with unmodifiableMap - // anyways. We implement the immutable Attributes for this class to support the - // Attributes.builder().putAll usage - it is tricky but an implementation detail of this private - // class. - return Collections.unmodifiableMap(this); - } - - @Override - public AttributesBuilder toBuilder() { - return Attributes.builder().putAll(this); - } - - @Override - public void forEach(BiConsumer, ? super Object> action) { - // https://github.com/open-telemetry/opentelemetry-java/issues/4161 - // Help out android desugaring by having an explicit call to HashMap.forEach, when forEach is - // just called through Attributes.forEach desugaring is unable to correctly handle it. - super.forEach(action); - } - - @Override - public String toString() { - return "AttributesMap{" - + "data=" - + super.toString() - + ", capacity=" - + capacity - + ", totalAddedValues=" - + totalAddedValues - + '}'; - } - - Attributes immutableCopy() { - return Attributes.builder().putAll(this).build(); - } -} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ExtendedSdkSpanBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ExtendedSdkSpanBuilder.java new file mode 100644 index 00000000000..8ddf5a4a957 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ExtendedSdkSpanBuilder.java @@ -0,0 +1,160 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.propagation.ExtendedContextPropagators; +import io.opentelemetry.api.incubator.trace.ExtendedSpanBuilder; +import io.opentelemetry.api.incubator.trace.SpanCallable; +import io.opentelemetry.api.incubator.trace.SpanRunnable; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.api.trace.StatusCode; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.context.propagation.ContextPropagators; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.function.BiConsumer; +import javax.annotation.Nullable; + +/** {@link ExtendedSdkSpanBuilder} is SDK implementation of {@link ExtendedSpanBuilder}. */ +final class ExtendedSdkSpanBuilder extends SdkSpanBuilder implements ExtendedSpanBuilder { + + ExtendedSdkSpanBuilder( + String spanName, + InstrumentationScopeInfo instrumentationScopeInfo, + TracerSharedState tracerSharedState, + SpanLimits spanLimits) { + super(spanName, instrumentationScopeInfo, tracerSharedState, spanLimits); + } + + @Override + public ExtendedSpanBuilder setParent(Context context) { + super.setParent(context); + return this; + } + + @Override + public ExtendedSpanBuilder setNoParent() { + super.setNoParent(); + return this; + } + + @Override + public ExtendedSpanBuilder setSpanKind(SpanKind spanKind) { + super.setSpanKind(spanKind); + return this; + } + + @Override + public ExtendedSpanBuilder addLink(SpanContext spanContext) { + super.addLink(spanContext); + return this; + } + + @Override + public ExtendedSpanBuilder addLink(SpanContext spanContext, Attributes attributes) { + super.addLink(spanContext, attributes); + return this; + } + + @Override + public ExtendedSpanBuilder setAttribute(String key, @Nullable String value) { + super.setAttribute(key, value); + return this; + } + + @Override + public ExtendedSpanBuilder setAttribute(String key, long value) { + super.setAttribute(key, value); + return this; + } + + @Override + public ExtendedSpanBuilder setAttribute(String key, double value) { + super.setAttribute(key, value); + return this; + } + + @Override + public ExtendedSpanBuilder setAttribute(String key, boolean value) { + super.setAttribute(key, value); + return this; + } + + @Override + public ExtendedSpanBuilder setAttribute(AttributeKey key, @Nullable T value) { + super.setAttribute(key, value); + return this; + } + + @Override + public ExtendedSpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit) { + super.setStartTimestamp(startTimestamp, unit); + return this; + } + + @Override + public ExtendedSpanBuilder setParentFrom( + ContextPropagators propagators, Map carrier) { + super.setParent( + ExtendedContextPropagators.extractTextMapPropagationContext(carrier, propagators)); + return this; + } + + @Override + public T startAndCall(SpanCallable spanCallable) throws E { + return startAndCall(spanCallable, ExtendedSdkSpanBuilder::setSpanError); + } + + @Override + public T startAndCall( + SpanCallable spanCallable, BiConsumer handleException) throws E { + Span span = startSpan(); + + //noinspection unused + try (Scope unused = span.makeCurrent()) { + return spanCallable.callInSpan(); + } catch (Throwable e) { + handleException.accept(span, e); + throw e; + } finally { + span.end(); + } + } + + @Override + public void startAndRun(SpanRunnable runnable) throws E { + startAndRun(runnable, ExtendedSdkSpanBuilder::setSpanError); + } + + @SuppressWarnings("NullAway") + @Override + public void startAndRun( + SpanRunnable runnable, BiConsumer handleException) throws E { + startAndCall( + () -> { + runnable.runInSpan(); + return null; + }, + handleException); + } + + /** + * Marks a span as error. This is the default exception handler. + * + * @param span the span + * @param exception the exception that caused the error + */ + private static void setSpanError(Span span, Throwable exception) { + span.setStatus(StatusCode.ERROR); + span.recordException(exception); + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ExtendedSdkTracer.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ExtendedSdkTracer.java new file mode 100644 index 00000000000..b74829ceeba --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ExtendedSdkTracer.java @@ -0,0 +1,27 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import io.opentelemetry.api.incubator.trace.ExtendedSpanBuilder; +import io.opentelemetry.api.incubator.trace.ExtendedTracer; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.trace.internal.TracerConfig; + +/** {@link ExtendedSdkTracer} is SDK implementation of {@link ExtendedTracer}. */ +final class ExtendedSdkTracer extends SdkTracer implements ExtendedTracer { + + ExtendedSdkTracer( + TracerSharedState sharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + TracerConfig tracerConfig) { + super(sharedState, instrumentationScopeInfo, tracerConfig); + } + + @Override + public ExtendedSpanBuilder spanBuilder(String spanName) { + return (ExtendedSpanBuilder) super.spanBuilder(spanName); + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IdGenerator.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IdGenerator.java index e0ecd8efac5..9113412ccda 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IdGenerator.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IdGenerator.java @@ -38,4 +38,17 @@ static IdGenerator random() { * @return a new valid {@code TraceId}. */ String generateTraceId(); + + /** + * Declares whether TraceIds generated by this IdGenerator have their lower 56 bits uniformly + * distributed over the [0..2^56-1]interval, making them compatible with W3C Trace Context Level 2 + * recommendation @see Random TraceId flag. + * + * @return true if the generated TraceIds are random + * @since 1.60.0 + */ + default boolean generatesRandomTraceIds() { + return false; + } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IncubatingUtil.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IncubatingUtil.java new file mode 100644 index 00000000000..d8304f652af --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/IncubatingUtil.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.common.ContextAttributes; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.trace.internal.TracerConfig; + +/** + * Utilities for interacting with {@code io.opentelemetry:opentelemetry-api-incubator}, which is not + * guaranteed to be present on the classpath. For all methods, callers MUST first separately + * reflectively confirm that the incubator is available on the classpath. + */ +final class IncubatingUtil { + + private IncubatingUtil() {} + + static SdkTracer createExtendedTracer( + TracerSharedState sharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + TracerConfig tracerConfig) { + return new ExtendedSdkTracer(sharedState, instrumentationScopeInfo, tracerConfig); + } + + static SdkSpanBuilder createExtendedSpanBuilder( + String spanName, + InstrumentationScopeInfo instrumentationScopeInfo, + TracerSharedState tracerSharedState, + SpanLimits spanLimits) { + return new ExtendedSdkSpanBuilder( + spanName, instrumentationScopeInfo, tracerSharedState, spanLimits); + } + + static Attributes getContextAttributes(Context context) { + return ContextAttributes.get(context); + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/MultiSpanProcessor.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/MultiSpanProcessor.java index 705351e83f5..65b37096568 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/MultiSpanProcessor.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/MultiSpanProcessor.java @@ -7,6 +7,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.internal.ExtendedSpanProcessor; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -16,8 +17,9 @@ * Implementation of the {@code SpanProcessor} that simply forwards all received events to a list of * {@code SpanProcessor}s. */ -final class MultiSpanProcessor implements SpanProcessor { +final class MultiSpanProcessor implements ExtendedSpanProcessor { private final List spanProcessorsStart; + private final List spanProcessorsEnding; private final List spanProcessorsEnd; private final List spanProcessorsAll; private final AtomicBoolean isShutdown = new AtomicBoolean(false); @@ -35,9 +37,9 @@ static SpanProcessor create(List spanProcessorList) { } @Override - public void onStart(Context parentContext, ReadWriteSpan readableSpan) { + public void onStart(Context parentContext, ReadWriteSpan readWriteSpan) { for (SpanProcessor spanProcessor : spanProcessorsStart) { - spanProcessor.onStart(parentContext, readableSpan); + spanProcessor.onStart(parentContext, readWriteSpan); } } @@ -58,6 +60,18 @@ public boolean isEndRequired() { return !spanProcessorsEnd.isEmpty(); } + @Override + public void onEnding(ReadWriteSpan span) { + for (ExtendedSpanProcessor spanProcessor : spanProcessorsEnding) { + spanProcessor.onEnding(span); + } + } + + @Override + public boolean isOnEndingRequired() { + return !spanProcessorsEnding.isEmpty(); + } + @Override public CompletableResultCode shutdown() { if (isShutdown.getAndSet(true)) { @@ -83,10 +97,17 @@ private MultiSpanProcessor(List spanProcessors) { this.spanProcessorsAll = spanProcessors; this.spanProcessorsStart = new ArrayList<>(spanProcessorsAll.size()); this.spanProcessorsEnd = new ArrayList<>(spanProcessorsAll.size()); + this.spanProcessorsEnding = new ArrayList<>(spanProcessorsAll.size()); for (SpanProcessor spanProcessor : spanProcessorsAll) { if (spanProcessor.isStartRequired()) { spanProcessorsStart.add(spanProcessor); } + if (spanProcessor instanceof ExtendedSpanProcessor) { + ExtendedSpanProcessor extendedSpanProcessor = (ExtendedSpanProcessor) spanProcessor; + if (extendedSpanProcessor.isOnEndingRequired()) { + spanProcessorsEnding.add(extendedSpanProcessor); + } + } if (spanProcessor.isEndRequired()) { spanProcessorsEnd.add(spanProcessor); } @@ -98,6 +119,8 @@ public String toString() { return "MultiSpanProcessor{" + "spanProcessorsStart=" + spanProcessorsStart + + ", spanProcessorsEnding=" + + spanProcessorsEnding + ", spanProcessorsEnd=" + spanProcessorsEnd + ", spanProcessorsAll=" diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/RandomIdGenerator.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/RandomIdGenerator.java index a9a1cc5de88..5456afcbb39 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/RandomIdGenerator.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/RandomIdGenerator.java @@ -7,7 +7,7 @@ import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.TraceId; -import io.opentelemetry.sdk.internal.RandomSupplier; +import io.opentelemetry.sdk.common.internal.RandomSupplier; import java.util.Random; import java.util.function.Supplier; @@ -38,6 +38,11 @@ public String generateTraceId() { return TraceId.fromLongs(idHi, idLo); } + @Override + public boolean generatesRandomTraceIds() { + return true; + } + @Override public String toString() { return "RandomIdGenerator{}"; diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ReadableSpan.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ReadableSpan.java index 9645ab1cab2..bb31fc8017b 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ReadableSpan.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/ReadableSpan.java @@ -6,10 +6,13 @@ package io.opentelemetry.sdk.trace; import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.InstrumentationScopeUtil; import io.opentelemetry.sdk.trace.data.SpanData; import javax.annotation.Nullable; @@ -61,14 +64,16 @@ public interface ReadableSpan { * @deprecated Use {@link #getInstrumentationScopeInfo()}. */ @Deprecated - io.opentelemetry.sdk.common.InstrumentationLibraryInfo getInstrumentationLibraryInfo(); + InstrumentationLibraryInfo getInstrumentationLibraryInfo(); /** * Returns the instrumentation scope specified when creating the tracer which produced this span. * * @return an instance of {@link InstrumentationScopeInfo} describing the instrumentation scope */ - InstrumentationScopeInfo getInstrumentationScopeInfo(); + default InstrumentationScopeInfo getInstrumentationScopeInfo() { + return InstrumentationScopeUtil.toInstrumentationScopeInfo(getInstrumentationLibraryInfo()); + } /** * Returns whether this Span has already been ended. @@ -108,4 +113,21 @@ public interface ReadableSpan { */ @Nullable T getAttribute(AttributeKey key); + + /** + * Returns the Span attributes. + * + *

      Attributes can be changed during the lifetime of the Span by using {@link + * Span#setAttribute}} so this value cannot be cached. + * + *

      Note: the implementation of this method performs locking and returns an immutable copy to + * ensure thread-safe behavior. If you only need a single attribute it is better to call {@link + * #getAttribute(AttributeKey)}. + * + * @return the Span attributes, or {@link Attributes#empty()} if the span has no attributes. + * @since 1.38.0 + */ + default Attributes getAttributes() { + return Attributes.empty(); + } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpan.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpan.java index 8c4b77b495b..ef3d2254c0b 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpan.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpan.java @@ -14,15 +14,19 @@ import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.AttributeUtil; -import io.opentelemetry.sdk.internal.InstrumentationScopeUtil; +import io.opentelemetry.sdk.common.internal.AttributeUtil; +import io.opentelemetry.sdk.common.internal.AttributesMap; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.InstrumentationScopeUtil; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.data.EventData; +import io.opentelemetry.sdk.trace.data.ExceptionEventData; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.sdk.trace.internal.data.ExceptionEventData; +import io.opentelemetry.sdk.trace.internal.ExtendedSpanProcessor; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -46,11 +50,8 @@ final class SdkSpan implements ReadWriteSpan { private final SpanContext parentSpanContext; // Handler called when the span starts and ends. private final SpanProcessor spanProcessor; - // The displayed name of the span. - // List of recorded links to parent and child spans. - private final List links; - // Number of links recorded. - private final int totalRecordedLinks; + // Resolves exception.* when an recordException is called + private final ExceptionAttributeResolver exceptionAttributeResolver; // The kind of the span. private final SpanKind kind; // The clock used to get the time. @@ -61,30 +62,65 @@ final class SdkSpan implements ReadWriteSpan { private final InstrumentationScopeInfo instrumentationScopeInfo; // The start time of the span. private final long startEpochNanos; + // Callback to run when span ends to record metrics. + private final Runnable recordEndMetrics; + // Lock used to internally guard the mutable state of this instance private final Object lock = new Object(); @GuardedBy("lock") private String name; + // Set of recorded attributes. DO NOT CALL any other method that changes the ordering of events. @GuardedBy("lock") @Nullable private AttributesMap attributes; + // List of recorded events. @GuardedBy("lock") - private final List events; + @Nullable + private List events; + // Number of events recorded. @GuardedBy("lock") private int totalRecordedEvents = 0; + + // The displayed name of the span. + // List of recorded links to parent and child spans. + @GuardedBy("lock") + @Nullable + List links; + + // Number of links recorded. + @GuardedBy("lock") + private int totalRecordedLinks; + // The status of the span. @GuardedBy("lock") private StatusData status = StatusData.unset(); + // The end time of the span. @GuardedBy("lock") private long endEpochNanos; - // True if the span is ended. + + private enum EndState { + NOT_ENDED, + ENDING, + ENDED + } + + @GuardedBy("lock") + private EndState hasEnded; + + /** + * The thread on which {@link #end()} is called and which will be invoking the {@link + * SpanProcessor}s. This field is used to ensure that only this thread may modify the span while + * it is in state {@link EndState#ENDING} to prevent concurrent updates outside of {@link + * ExtendedSpanProcessor#onEnding(ReadWriteSpan)}. + */ @GuardedBy("lock") - private boolean hasEnded; + @Nullable + private Thread spanEndingThread; private SdkSpan( SpanContext context, @@ -94,12 +130,14 @@ private SdkSpan( SpanContext parentSpanContext, SpanLimits spanLimits, SpanProcessor spanProcessor, + ExceptionAttributeResolver exceptionAttributeResolver, AnchoredClock clock, Resource resource, @Nullable AttributesMap attributes, - List links, + @Nullable List links, int totalRecordedLinks, - long startEpochNanos) { + long startEpochNanos, + Runnable recordEndMetrics) { this.context = context; this.instrumentationScopeInfo = instrumentationScopeInfo; this.parentSpanContext = parentSpanContext; @@ -108,13 +146,14 @@ private SdkSpan( this.name = name; this.kind = kind; this.spanProcessor = spanProcessor; + this.exceptionAttributeResolver = exceptionAttributeResolver; this.resource = resource; - this.hasEnded = false; + this.hasEnded = EndState.NOT_ENDED; this.clock = clock; this.startEpochNanos = startEpochNanos; this.attributes = attributes; - this.events = new ArrayList<>(); this.spanLimits = spanLimits; + this.recordEndMetrics = recordEndMetrics; } /** @@ -130,6 +169,7 @@ private SdkSpan( * @param resource the resource associated with this span. * @param attributes the attributes set during span creation. * @param links the links set during span creation, may be truncated. The list MUST be immutable. + * @param recordEndMetrics a {@link Runnable} to run when the span is ended to record metrics. * @return a new and started span. */ static SdkSpan startSpan( @@ -141,12 +181,14 @@ static SdkSpan startSpan( Context parentContext, SpanLimits spanLimits, SpanProcessor spanProcessor, + ExceptionAttributeResolver exceptionAttributeResolver, Clock tracerClock, Resource resource, @Nullable AttributesMap attributes, - List links, + @Nullable List links, int totalRecordedLinks, - long userStartEpochNanos) { + long userStartEpochNanos, + Runnable recordEndMetrics) { boolean createdAnchoredClock; AnchoredClock clock; if (parentSpan instanceof SdkSpan) { @@ -179,15 +221,19 @@ static SdkSpan startSpan( parentSpan.getSpanContext(), spanLimits, spanProcessor, + exceptionAttributeResolver, clock, resource, attributes, links, totalRecordedLinks, - startEpochNanos); + startEpochNanos, + recordEndMetrics); // Call onStart here instead of calling in the constructor to make sure the span is completely // initialized. - spanProcessor.onStart(parentContext, span); + if (spanProcessor.isStartRequired()) { + spanProcessor.onStart(parentContext, span); + } return span; } @@ -197,15 +243,16 @@ public SpanData toSpanData() { synchronized (lock) { return SpanWrapper.create( this, - links, + getImmutableLinks(), getImmutableTimedEvents(), getImmutableAttributes(), (attributes == null) ? 0 : attributes.getTotalAddedValues(), totalRecordedEvents, + totalRecordedLinks, status, name, endEpochNanos, - hasEnded); + hasEnded == EndState.ENDED); } } @@ -217,10 +264,17 @@ public T getAttribute(AttributeKey key) { } } + @Override + public Attributes getAttributes() { + synchronized (lock) { + return attributes == null ? Attributes.empty() : attributes.immutableCopy(); + } + } + @Override public boolean hasEnded() { synchronized (lock) { - return hasEnded; + return hasEnded == EndState.ENDED; } } @@ -248,7 +302,7 @@ public String getName() { @Override @Deprecated - public io.opentelemetry.sdk.common.InstrumentationLibraryInfo getInstrumentationLibraryInfo() { + public InstrumentationLibraryInfo getInstrumentationLibraryInfo() { return InstrumentationScopeUtil.toInstrumentationLibraryInfo(getInstrumentationScopeInfo()); } @@ -266,7 +320,7 @@ public InstrumentationScopeInfo getInstrumentationScopeInfo() { @Override public long getLatencyNanos() { synchronized (lock) { - return (hasEnded ? endEpochNanos : clock.now()) - startEpochNanos; + return (hasEnded == EndState.NOT_ENDED ? clock.now() : endEpochNanos) - startEpochNanos; } } @@ -276,18 +330,18 @@ AnchoredClock getClock() { } @Override - public ReadWriteSpan setAttribute(AttributeKey key, T value) { + public ReadWriteSpan setAttribute(AttributeKey key, @Nullable T value) { if (key == null || key.getKey().isEmpty() || value == null) { return this; } synchronized (lock) { - if (hasEnded) { + if (!isModifiableByCurrentThread()) { logger.log(Level.FINE, "Calling setAttribute() on an ended Span."); return this; } if (attributes == null) { attributes = - new AttributesMap( + AttributesMap.create( spanLimits.getMaxNumberOfAttributes(), spanLimits.getMaxAttributeValueLength()); } @@ -296,6 +350,13 @@ public ReadWriteSpan setAttribute(AttributeKey key, T value) { return this; } + @GuardedBy("lock") + @SuppressWarnings("ReferenceEquality") + private boolean isModifiableByCurrentThread() { + return hasEnded == EndState.NOT_ENDED + || (hasEnded == EndState.ENDING && Thread.currentThread() == spanEndingThread); + } + @Override public ReadWriteSpan addEvent(String name) { if (name == null) { @@ -358,10 +419,13 @@ public ReadWriteSpan addEvent(String name, Attributes attributes, long timestamp private void addTimedEvent(EventData timedEvent) { synchronized (lock) { - if (hasEnded) { + if (!isModifiableByCurrentThread()) { logger.log(Level.FINE, "Calling addEvent() on an ended Span."); return; } + if (events == null) { + events = new ArrayList<>(); + } if (events.size() < spanLimits.getMaxNumberOfEvents()) { events.add(timedEvent); } @@ -375,10 +439,29 @@ public ReadWriteSpan setStatus(StatusCode statusCode, @Nullable String descripti return this; } synchronized (lock) { - if (hasEnded) { + if (!isModifiableByCurrentThread()) { logger.log(Level.FINE, "Calling setStatus() on an ended Span."); return this; } + + // If current status is OK, ignore further attempts to change it + if (this.status.getStatusCode() == StatusCode.OK) { + logger.log(Level.FINE, "Calling setStatus() on a Span that is already set to OK."); + return this; + } + + // Ignore attempts to set status to UNSET + if (statusCode == StatusCode.UNSET) { + logger.log(Level.FINE, "Ignoring call to setStatus() with status UNSET."); + return this; + } + + // Ignore description when status is not ERROR + if (description != null && statusCode != StatusCode.ERROR) { + logger.log(Level.FINE, "Ignoring setStatus() description since status is not ERROR."); + description = null; + } + this.status = StatusData.create(statusCode, description); } return this; @@ -399,8 +482,19 @@ public ReadWriteSpan recordException(Throwable exception, Attributes additionalA additionalAttributes = Attributes.empty(); } + int maxAttributeLength = spanLimits.getMaxAttributeValueLength(); + AttributesMap attributes = + AttributesMap.create( + spanLimits.getMaxNumberOfAttributes(), spanLimits.getMaxAttributeValueLength()); + + exceptionAttributeResolver.setExceptionAttributes( + attributes::putIfCapacity, exception, maxAttributeLength); + + additionalAttributes.forEach(attributes::put); + addTimedEvent( - ExceptionEventData.create(spanLimits, clock.now(), exception, additionalAttributes)); + ExceptionEventData.create( + clock.now(), exception, attributes, attributes.getTotalAddedValues())); return this; } @@ -410,7 +504,7 @@ public ReadWriteSpan updateName(String name) { return this; } synchronized (lock) { - if (hasEnded) { + if (!isModifiableByCurrentThread()) { logger.log(Level.FINE, "Calling updateName() on an ended Span."); return this; } @@ -419,6 +513,41 @@ public ReadWriteSpan updateName(String name) { return this; } + @Override + public Span addLink(SpanContext spanContext, Attributes attributes) { + if (spanContext == null) { + return this; + } + if (attributes == null) { + attributes = Attributes.empty(); + } + if (!spanContext.isValid() && attributes.isEmpty() && spanContext.getTraceState().isEmpty()) { + return this; + } + LinkData link = + LinkData.create( + spanContext, + AttributeUtil.applyAttributesLimit( + attributes, + spanLimits.getMaxNumberOfAttributesPerLink(), + spanLimits.getMaxAttributeValueLength()), + attributes.size()); + synchronized (lock) { + if (!isModifiableByCurrentThread()) { + logger.log(Level.FINE, "Calling addLink() on an ended Span."); + return this; + } + if (links == null) { + links = new ArrayList<>(); + } + if (links.size() < spanLimits.getMaxNumberOfLinks()) { + links.add(link); + } + totalRecordedLinks++; + } + return this; + } + @Override public void end() { endInternal(clock.now()); @@ -434,20 +563,34 @@ public void end(long timestamp, TimeUnit unit) { private void endInternal(long endEpochNanos) { synchronized (lock) { - if (hasEnded) { - logger.log(Level.FINE, "Calling end() on an ended Span."); + if (hasEnded != EndState.NOT_ENDED) { + logger.log(Level.FINE, "Calling end() on an ended or ending Span."); return; } this.endEpochNanos = endEpochNanos; - hasEnded = true; + spanEndingThread = Thread.currentThread(); + hasEnded = EndState.ENDING; + } + recordEndMetrics.run(); + if (spanProcessor instanceof ExtendedSpanProcessor) { + ExtendedSpanProcessor extendedSpanProcessor = (ExtendedSpanProcessor) spanProcessor; + if (extendedSpanProcessor.isOnEndingRequired()) { + extendedSpanProcessor.onEnding(this); + } + } + synchronized (lock) { + hasEnded = EndState.ENDED; + spanEndingThread = null; + } + if (spanProcessor.isEndRequired()) { + spanProcessor.onEnd(this); } - spanProcessor.onEnd(this); } @Override public boolean isRecording() { synchronized (lock) { - return !hasEnded; + return hasEnded != EndState.ENDED; } } @@ -464,19 +607,15 @@ long getStartEpochNanos() { return startEpochNanos; } - int getTotalRecordedLinks() { - return totalRecordedLinks; - } - @GuardedBy("lock") private List getImmutableTimedEvents() { - if (events.isEmpty()) { + if (events == null) { return Collections.emptyList(); } // if the span has ended, then the events are unmodifiable // so we can return them directly and save copying all the data. - if (hasEnded) { + if (hasEnded == EndState.ENDED) { return Collections.unmodifiableList(events); } @@ -490,13 +629,21 @@ private Attributes getImmutableAttributes() { } // if the span has ended, then the attributes are unmodifiable, // so we can return them directly and save copying all the data. - if (hasEnded) { + if (hasEnded == EndState.ENDED) { return attributes; } // otherwise, make a copy of the data into an immutable container. return attributes.immutableCopy(); } + @GuardedBy("lock") + private List getImmutableLinks() { + if (links == null || links.isEmpty()) { + return Collections.emptyList(); + } + return Collections.unmodifiableList(links); + } + @Override public String toString() { String name; @@ -504,12 +651,14 @@ public String toString() { String status; long totalRecordedEvents; long endEpochNanos; + long totalRecordedLinks; synchronized (lock) { name = this.name; attributes = String.valueOf(this.attributes); status = String.valueOf(this.status); totalRecordedEvents = this.totalRecordedEvents; endEpochNanos = this.endEpochNanos; + totalRecordedLinks = this.totalRecordedLinks; } return "SdkSpan{traceId=" + context.getTraceId() diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpanBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpanBuilder.java index e91413288f3..c910706ed43 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpanBuilder.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkSpanBuilder.java @@ -16,12 +16,16 @@ import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.AttributeUtil; +import io.opentelemetry.sdk.common.internal.AttributeUtil; +import io.opentelemetry.sdk.common.internal.AttributesMap; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.samplers.SamplingDecision; import io.opentelemetry.sdk.trace.samplers.SamplingResult; @@ -29,10 +33,25 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.function.BiPredicate; import javax.annotation.Nullable; /** {@link SdkSpanBuilder} is SDK implementation of {@link SpanBuilder}. */ -final class SdkSpanBuilder implements SpanBuilder { +class SdkSpanBuilder implements SpanBuilder { + + private static final Span RANDOM_TRACE_ID_PRIMORDIAL_SPAN = + Span.wrap( + SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.builder().setRandomTraceId(true).build(), + TraceState.getDefault())); + + // Pre-built for the common case where parentContext is root (no extra context to preserve). + private static final Context ROOT_CONTEXT_WITH_RANDOM_TRACE_ID_BIT = + Context.root().with(RANDOM_TRACE_ID_PRIMORDIAL_SPAN); + private static final Context NO_PARENT = + Context.root().with(ContextKey.named("opentelemetry-no-parent"), Boolean.TRUE); private final String spanName; private final InstrumentationScopeInfo instrumentationScopeInfo; @@ -68,7 +87,7 @@ public SpanBuilder setParent(Context context) { @Override public SpanBuilder setNoParent() { - this.parent = Context.root(); + this.parent = NO_PARENT; return this; } @@ -83,7 +102,7 @@ public SpanBuilder setSpanKind(SpanKind spanKind) { @Override public SpanBuilder addLink(SpanContext spanContext) { - if (spanContext == null || !spanContext.isValid()) { + if (spanContext == null || (!spanContext.isValid() && spanContext.getTraceState().isEmpty())) { return this; } addLink(LinkData.create(spanContext)); @@ -92,12 +111,15 @@ public SpanBuilder addLink(SpanContext spanContext) { @Override public SpanBuilder addLink(SpanContext spanContext, Attributes attributes) { - if (spanContext == null || !spanContext.isValid()) { + if (spanContext == null) { return this; } if (attributes == null) { attributes = Attributes.empty(); } + if (!spanContext.isValid() && attributes.isEmpty() && spanContext.getTraceState().isEmpty()) { + return this; + } int totalAttributeCount = attributes.size(); addLink( LinkData.create( @@ -125,7 +147,7 @@ private void addLink(LinkData link) { } @Override - public SpanBuilder setAttribute(String key, String value) { + public SpanBuilder setAttribute(String key, @Nullable String value) { return setAttribute(stringKey(key), value); } @@ -145,7 +167,7 @@ public SpanBuilder setAttribute(String key, boolean value) { } @Override - public SpanBuilder setAttribute(AttributeKey key, T value) { + public SpanBuilder setAttribute(AttributeKey key, @Nullable T value) { if (key == null || key.getKey().isEmpty() || value == null) { return this; } @@ -163,32 +185,73 @@ public SpanBuilder setStartTimestamp(long startTimestamp, TimeUnit unit) { } @Override - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({"rawtypes", "ReferenceEquality"}) public Span startSpan() { - Context parentContext = parent == null ? Context.current() : parent; + boolean isNoParent = parent == NO_PARENT; + Context parentContext = + isNoParent ? Context.root() : (parent == null ? Context.current() : parent); Span parentSpan = Span.fromContext(parentContext); SpanContext parentSpanContext = parentSpan.getSpanContext(); String traceId; + boolean isTraceIdRandom; IdGenerator idGenerator = tracerSharedState.getIdGenerator(); String spanId = idGenerator.generateSpanId(); + + Context parentContextForSampler = parentContext; if (!parentSpanContext.isValid()) { // New root span. traceId = idGenerator.generateTraceId(); + if (idGenerator.generatesRandomTraceIds()) { + isTraceIdRandom = true; + // Replace parentContext for sampling with one with RANDOM_TRACE_ID bit set. + // Use the pre-built singleton when parentContext is root to avoid an allocation; + // otherwise graft onto parentContext to preserve any extra context values. + parentContextForSampler = + parentContext == Context.root() + ? ROOT_CONTEXT_WITH_RANDOM_TRACE_ID_BIT + : parentContext.with(RANDOM_TRACE_ID_PRIMORDIAL_SPAN); + } else { + isTraceIdRandom = false; + } } else { // New child span. traceId = parentSpanContext.getTraceId(); + isTraceIdRandom = parentSpanContext.getTraceFlags().isTraceIdRandom(); } + List currentLinks = links; List immutableLinks = - links == null ? Collections.emptyList() : Collections.unmodifiableList(links); + currentLinks == null ? Collections.emptyList() : Collections.unmodifiableList(currentLinks); // Avoid any possibility to modify the links list by adding links to the Builder after the // startSpan is called. If that happens all the links will be added in a new list. links = null; + BiPredicate> filter = + tracerSharedState.getContextScopedAttributesFilter(); + if (filter != null && SdkTracer.INCUBATOR_AVAILABLE) { + Context contextForAttributes = isNoParent ? Context.current() : parentContext; + Attributes contextAttributes = IncubatingUtil.getContextAttributes(contextForAttributes); + if (!contextAttributes.isEmpty()) { + AttributesMap spanAttributes = attributes(); + contextAttributes.forEach((key, value) -> { + if (!filter.test(instrumentationScopeInfo, key)) { + return; + } + if (!spanAttributes.containsKey(key.getKey())) { + spanAttributes.put((AttributeKey) key, value); + } + }); + } + } Attributes immutableAttributes = attributes == null ? Attributes.empty() : attributes; SamplingResult samplingResult = tracerSharedState .getSampler() .shouldSample( - parentContext, traceId, spanName, spanKind, immutableAttributes, immutableLinks); + parentContextForSampler, + traceId, + spanName, + spanKind, + immutableAttributes, + immutableLinks); SamplingDecision samplingDecision = samplingResult.getDecision(); TraceState samplingResultTraceState = @@ -197,11 +260,17 @@ public Span startSpan() { ImmutableSpanContext.create( traceId, spanId, - isSampled(samplingDecision) ? TraceFlags.getSampled() : TraceFlags.getDefault(), + TraceFlags.builder() + .setSampled(isSampled(samplingDecision)) + .setRandomTraceId(isTraceIdRandom) + .build(), samplingResultTraceState, /* remote= */ false, tracerSharedState.isIdGeneratorSafeToSkipIdValidation()); + Runnable recordEndSpanMetrics = + tracerSharedState.getTracerInstrumentation().startSpan(parentSpanContext, samplingDecision); + if (!isRecording(samplingDecision)) { return Span.wrap(spanContext); } @@ -224,19 +293,21 @@ public Span startSpan() { parentContext, spanLimits, tracerSharedState.getActiveSpanProcessor(), + tracerSharedState.getExceptionAttributesResolver(), tracerSharedState.getClock(), tracerSharedState.getResource(), recordedAttributes, - immutableLinks, + currentLinks, totalNumberOfLinksAdded, - startEpochNanos); + startEpochNanos, + recordEndSpanMetrics); } private AttributesMap attributes() { AttributesMap attributes = this.attributes; if (attributes == null) { this.attributes = - new AttributesMap( + AttributesMap.create( spanLimits.getMaxNumberOfAttributes(), spanLimits.getMaxAttributeValueLength()); attributes = this.attributes; } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracer.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracer.java index 81282097cd1..e68a5332720 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracer.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracer.java @@ -9,34 +9,81 @@ import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.trace.internal.TracerConfig; /** {@link SdkTracer} is SDK implementation of {@link Tracer}. */ -final class SdkTracer implements Tracer { +class SdkTracer implements Tracer { static final String FALLBACK_SPAN_NAME = ""; + private static final Tracer NOOP_TRACER = TracerProvider.noop().get("noop"); + static final boolean INCUBATOR_AVAILABLE; + + static { + boolean incubatorAvailable = false; + try { + Class.forName("io.opentelemetry.api.incubator.trace.ExtendedDefaultTracerProvider"); + incubatorAvailable = true; + } catch (ClassNotFoundException e) { + // Not available + } + INCUBATOR_AVAILABLE = incubatorAvailable; + } private final TracerSharedState sharedState; private final InstrumentationScopeInfo instrumentationScopeInfo; - SdkTracer(TracerSharedState sharedState, InstrumentationScopeInfo instrumentationScopeInfo) { + protected volatile boolean tracerEnabled; + + SdkTracer( + TracerSharedState sharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + TracerConfig tracerConfig) { this.sharedState = sharedState; this.instrumentationScopeInfo = instrumentationScopeInfo; + this.tracerEnabled = tracerConfig.isEnabled(); + } + + static SdkTracer create( + TracerSharedState sharedState, + InstrumentationScopeInfo instrumentationScopeInfo, + TracerConfig tracerConfig) { + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedTracer(sharedState, instrumentationScopeInfo, tracerConfig) + : new SdkTracer(sharedState, instrumentationScopeInfo, tracerConfig); } + @Override + public boolean isEnabled() { + return tracerEnabled; + } + + /** + * Note that {@link ExtendedSdkTracer#spanBuilder(String)} calls this and depends on it returning + * {@link ExtendedSdkTracer} in all cases when the incubator is present. + */ @Override public SpanBuilder spanBuilder(String spanName) { + if (!tracerEnabled) { + return NOOP_TRACER.spanBuilder(spanName); + } if (spanName == null || spanName.trim().isEmpty()) { spanName = FALLBACK_SPAN_NAME; } if (sharedState.hasBeenShutdown()) { - Tracer tracer = TracerProvider.noop().get(instrumentationScopeInfo.getName()); - return tracer.spanBuilder(spanName); + return NOOP_TRACER.spanBuilder(spanName); } - return new SdkSpanBuilder( - spanName, instrumentationScopeInfo, sharedState, sharedState.getSpanLimits()); + return INCUBATOR_AVAILABLE + ? IncubatingUtil.createExtendedSpanBuilder( + spanName, instrumentationScopeInfo, sharedState, sharedState.getSpanLimits()) + : new SdkSpanBuilder( + spanName, instrumentationScopeInfo, sharedState, sharedState.getSpanLimits()); } // Visible for testing InstrumentationScopeInfo getInstrumentationScopeInfo() { return instrumentationScopeInfo; } + + void updateTracerConfig(TracerConfig tracerConfig) { + this.tracerEnabled = tracerConfig.isEnabled(); + } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerBuilder.java index fb6ccdea627..39489f751fc 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerBuilder.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerBuilder.java @@ -5,9 +5,10 @@ package io.opentelemetry.sdk.trace; +import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerBuilder; -import io.opentelemetry.sdk.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.internal.ComponentRegistry; import javax.annotation.Nullable; class SdkTracerBuilder implements TracerBuilder { @@ -36,6 +37,7 @@ public TracerBuilder setInstrumentationVersion(String instrumentationScopeVersio @Override public Tracer build() { - return registry.get(instrumentationScopeName, instrumentationScopeVersion, schemaUrl); + return registry.get( + instrumentationScopeName, instrumentationScopeVersion, schemaUrl, Attributes.empty()); } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerInstrumentation.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerInstrumentation.java new file mode 100644 index 00000000000..c686d0ae67a --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerInstrumentation.java @@ -0,0 +1,208 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_SPAN_PARENT_ORIGIN; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_SPAN_SAMPLING_RESULT; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.LongUpDownCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * SDK metrics exported for started and ended spans as defined in the semantic + * conventions. + */ +final class SdkTracerInstrumentation { + + private static final Attributes noParentDrop = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, "none", OTEL_SPAN_SAMPLING_RESULT, SamplingDecision.DROP.name()); + private static final Attributes noParentRecordOnly = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.RECORD_ONLY.name()); + private static final Attributes noParentRecordAndSample = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.RECORD_AND_SAMPLE.name()); + + private static final Attributes remoteParentDrop = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.DROP.name()); + private static final Attributes remoteParentRecordOnly = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.RECORD_ONLY.name()); + private static final Attributes remoteParentRecordAndSample = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.RECORD_AND_SAMPLE.name()); + + private static final Attributes localParentDrop = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.DROP.name()); + private static final Attributes localParentRecordOnly = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.RECORD_ONLY.name()); + private static final Attributes localParentRecordAndSample = + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + SamplingDecision.RECORD_AND_SAMPLE.name()); + + private static final Attributes recordOnly = + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, SamplingDecision.RECORD_ONLY.name()); + private static final Attributes recordAndSample = + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, SamplingDecision.RECORD_AND_SAMPLE.name()); + + private final Object lock = new Object(); + + private final Supplier meterProvider; + + @Nullable private Meter meter; + @Nullable private volatile LongCounter startedSpans; + @Nullable private volatile LongUpDownCounter liveSpans; + + SdkTracerInstrumentation(Supplier meterProvider) { + this.meterProvider = meterProvider; + } + + /** + * Records metrics for when a span starts and returns a {@link Runnable} to execute when ending + * the span. + */ + Runnable startSpan(SpanContext parentSpanContext, SamplingDecision samplingDecision) { + if (!parentSpanContext.isValid()) { + switch (samplingDecision) { + case DROP: + startedSpans().add(1, noParentDrop); + return SdkTracerInstrumentation::noop; + case RECORD_ONLY: + startedSpans().add(1, noParentRecordOnly); + liveSpans().add(1, recordOnly); + return this::decrementRecordOnly; + case RECORD_AND_SAMPLE: + startedSpans().add(1, noParentRecordAndSample); + liveSpans().add(1, recordAndSample); + return this::decrementRecordAndSample; + } + throw new IllegalArgumentException("Unrecognized sampling decision: " + samplingDecision); + } else if (parentSpanContext.isRemote()) { + switch (samplingDecision) { + case DROP: + startedSpans().add(1, remoteParentDrop); + return SdkTracerInstrumentation::noop; + case RECORD_ONLY: + startedSpans().add(1, remoteParentRecordOnly); + liveSpans().add(1, recordOnly); + return this::decrementRecordOnly; + case RECORD_AND_SAMPLE: + startedSpans().add(1, remoteParentRecordAndSample); + liveSpans().add(1, recordAndSample); + return this::decrementRecordAndSample; + } + throw new IllegalArgumentException("Unrecognized sampling decision: " + samplingDecision); + } + // local parent + switch (samplingDecision) { + case DROP: + startedSpans().add(1, localParentDrop); + return SdkTracerInstrumentation::noop; + case RECORD_ONLY: + startedSpans().add(1, localParentRecordOnly); + liveSpans().add(1, recordOnly); + return this::decrementRecordOnly; + case RECORD_AND_SAMPLE: + startedSpans().add(1, localParentRecordAndSample); + liveSpans().add(1, recordAndSample); + return this::decrementRecordAndSample; + } + throw new IllegalArgumentException("Unrecognized sampling decision: " + samplingDecision); + } + + private static void noop() {} + + private void decrementRecordOnly() { + liveSpans().add(-1, recordOnly); + } + + private void decrementRecordAndSample() { + liveSpans().add(-1, recordAndSample); + } + + private LongCounter startedSpans() { + LongCounter startedSpans = this.startedSpans; + if (startedSpans == null) { + synchronized (lock) { + startedSpans = this.startedSpans; + if (startedSpans == null) { + startedSpans = + meter() + .counterBuilder(SemConvConstants.OTEL_SDK_SPAN_STARTED_NAME) + .setUnit(SemConvConstants.OTEL_SDK_SPAN_STARTED_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_SPAN_STARTED_DESCRIPTION) + .build(); + this.startedSpans = startedSpans; + } + } + } + return startedSpans; + } + + private LongUpDownCounter liveSpans() { + LongUpDownCounter liveSpans = this.liveSpans; + if (liveSpans == null) { + synchronized (lock) { + liveSpans = this.liveSpans; + if (liveSpans == null) { + liveSpans = + meter() + .upDownCounterBuilder(SemConvConstants.OTEL_SDK_SPAN_LIVE_NAME) + .setUnit(SemConvConstants.OTEL_SDK_SPAN_LIVE_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_SPAN_LIVE_DESCRIPTION) + .build(); + this.liveSpans = liveSpans; + } + } + } + return liveSpans; + } + + private Meter meter() { + if (meter == null) { + // Safe to call from multiple threads. + meter = meterProvider.get().get("io.opentelemetry.sdk.trace"); + } + return meter; + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java index 44d33f09347..744da6da708 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProvider.java @@ -5,17 +5,26 @@ package io.opentelemetry.sdk.trace; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.api.trace.TracerBuilder; import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ComponentRegistry; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.internal.TracerConfig; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.io.Closeable; import java.util.List; import java.util.concurrent.TimeUnit; +import java.util.function.BiPredicate; import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -26,7 +35,11 @@ public final class SdkTracerProvider implements TracerProvider, Closeable { private static final Logger logger = Logger.getLogger(SdkTracerProvider.class.getName()); static final String DEFAULT_TRACER_NAME = ""; private final TracerSharedState sharedState; + private final SdkResourceProvider resourceProvider; private final ComponentRegistry tracerSdkComponentRegistry; + // deliberately not volatile because of performance concerns + // - which means its eventually consistent + private ScopeConfigurator tracerConfigurator; /** * Returns a new {@link SdkTracerProviderBuilder} for {@link SdkTracerProvider}. @@ -37,19 +50,41 @@ public static SdkTracerProviderBuilder builder() { return new SdkTracerProviderBuilder(); } + @SuppressWarnings("NonApiType") SdkTracerProvider( Clock clock, IdGenerator idsGenerator, - Resource resource, + SdkResourceProvider resourceProvider, Supplier spanLimitsSupplier, Sampler sampler, - List spanProcessors) { + List spanProcessors, + ScopeConfigurator tracerConfigurator, + ExceptionAttributeResolver exceptionAttributeResolver, + Supplier meterProvider, + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.resourceProvider = resourceProvider; this.sharedState = new TracerSharedState( - clock, idsGenerator, resource, spanLimitsSupplier, sampler, spanProcessors); + clock, + idsGenerator, + resourceProvider, + spanLimitsSupplier, + sampler, + spanProcessors, + exceptionAttributeResolver, + new SdkTracerInstrumentation(meterProvider), + contextScopedAttributesFilter); this.tracerSdkComponentRegistry = - new ComponentRegistry<>( - instrumentationScopeInfo -> new SdkTracer(sharedState, instrumentationScopeInfo)); + new ComponentRegistry<>(instrumentationScopeInfo -> + SdkTracer.create( + sharedState, instrumentationScopeInfo, getTracerConfig(instrumentationScopeInfo))); + this.tracerConfigurator = tracerConfigurator; + } + + private TracerConfig getTracerConfig(InstrumentationScopeInfo instrumentationScopeInfo) { + TracerConfig tracerConfig = tracerConfigurator.apply(instrumentationScopeInfo); + return tracerConfig == null ? TracerConfig.defaultConfig() : tracerConfig; } @Override @@ -71,9 +106,22 @@ public TracerBuilder tracerBuilder(@Nullable String instrumentationScopeName) { logger.fine("Tracer requested without instrumentation scope name."); instrumentationScopeName = DEFAULT_TRACER_NAME; } + if (sharedState.hasNoSpanProcessor()) { + return TracerProvider.noop().tracerBuilder(instrumentationScopeName); + } return new SdkTracerBuilder(tracerSdkComponentRegistry, instrumentationScopeName); } + /** + * Returns the {@link SdkResourceProvider} used to resolve the {@link Resource} attached to spans. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#getSdkResourceProvider(SdkTracerProvider)}. + */ + SdkResourceProvider getSdkResourceProvider() { + return resourceProvider; + } + /** Returns the {@link SpanLimits} that are currently applied to created spans. */ public SpanLimits getSpanLimits() { return sharedState.getSpanLimits(); @@ -84,6 +132,23 @@ public Sampler getSampler() { return sharedState.getSampler(); } + /** + * Updates the tracer configurator, which computes {@link TracerConfig} for each {@link + * InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#setTracerConfigurator(SdkTracerProvider, ScopeConfigurator)}. + * + * @see TracerConfig#configuratorBuilder() + */ + void setTracerConfigurator(ScopeConfigurator tracerConfigurator) { + this.tracerConfigurator = tracerConfigurator; + this.tracerSdkComponentRegistry + .getComponents() + .forEach(sdkTracer -> + sdkTracer.updateTracerConfig(getTracerConfig(sdkTracer.getInstrumentationScopeInfo()))); + } + /** * Attempts to stop all the activity for {@link Tracer}s created by this provider. Calls {@link * SpanProcessor#shutdown()} for all registered {@link SpanProcessor}s. @@ -101,7 +166,7 @@ public Sampler getSampler() { */ public CompletableResultCode shutdown() { if (sharedState.hasBeenShutdown()) { - logger.log(Level.WARNING, "Calling shutdown() multiple times."); + logger.log(Level.INFO, "Calling shutdown() multiple times."); return CompletableResultCode.ofSuccess(); } return sharedState.shutdown(); @@ -149,6 +214,8 @@ public String toString() { + sharedState.getSampler() + ", spanProcessor=" + sharedState.getActiveSpanProcessor() + + ", tracerConfigurator=" + + tracerConfigurator + '}'; } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilder.java index 7801a3fa728..44faa7ca08f 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilder.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilder.java @@ -7,12 +7,26 @@ import static java.util.Objects.requireNonNull; +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.Span; import io.opentelemetry.sdk.common.Clock; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.internal.TracerConfig; import io.opentelemetry.sdk.trace.samplers.Sampler; import java.util.ArrayList; import java.util.List; +import java.util.Objects; +import java.util.function.BiPredicate; +import java.util.function.Predicate; import java.util.function.Supplier; +import javax.annotation.Nullable; /** Builder of {@link SdkTracerProvider}. */ public final class SdkTracerProviderBuilder { @@ -23,12 +37,22 @@ public final class SdkTracerProviderBuilder { private Clock clock = Clock.getDefault(); private IdGenerator idsGenerator = IdGenerator.random(); private Resource resource = Resource.getDefault(); + private boolean resourceExplicitlySet = false; + @Nullable private SdkResourceProvider resourceProvider; private Supplier spanLimitsSupplier = SpanLimits::getDefault; private Sampler sampler = DEFAULT_SAMPLER; + private ScopeConfiguratorBuilder tracerConfiguratorBuilder = + TracerConfig.configuratorBuilder(); + private ExceptionAttributeResolver exceptionAttributeResolver = + ExceptionAttributeResolver.getDefault(); + private Supplier meterProvider = MeterProvider::noop; + + @Nullable + private BiPredicate> contextScopedAttributesFilter; /** - * Assign a {@link Clock}. {@link Clock} will be used each time a {@link - * io.opentelemetry.api.trace.Span} is started, ended or any event is recorded. + * Assign a {@link Clock}. {@link Clock} will be used each time a {@link Span} is started, ended + * or any event is recorded. * *

      The {@code clock} must be thread-safe and return immediately (no remote calls, as contention * free as possible). @@ -43,8 +67,8 @@ public SdkTracerProviderBuilder setClock(Clock clock) { } /** - * Assign an {@link IdGenerator}. {@link IdGenerator} will be used each time a {@link - * io.opentelemetry.api.trace.Span} is started. + * Assign an {@link IdGenerator}. {@link IdGenerator} will be used each time a {@link Span} is + * started. * *

      The {@code idGenerator} must be thread-safe and return immediately (no remote calls, as * contention free as possible). @@ -63,10 +87,56 @@ public SdkTracerProviderBuilder setIdGenerator(IdGenerator idGenerator) { * * @param resource A Resource implementation. * @return this + * @throws IllegalStateException if {@link #setSdkResourceProvider(SdkResourceProvider)} was + * already called */ public SdkTracerProviderBuilder setResource(Resource resource) { requireNonNull(resource, "resource"); + if (resourceProvider != null) { + throw new IllegalStateException( + "Cannot call setResource after setSdkResourceProvider has been called."); + } this.resource = resource; + this.resourceExplicitlySet = true; + return this; + } + + /** + * Merge a {@link Resource} with the current. + * + * @param resource {@link Resource} to merge with current. + * @throws IllegalStateException if {@link #setSdkResourceProvider(SdkResourceProvider)} was + * already called + * @since 1.29.0 + */ + public SdkTracerProviderBuilder addResource(Resource resource) { + Objects.requireNonNull(resource, "resource"); + if (resourceProvider != null) { + throw new IllegalStateException( + "Cannot call addResource after setSdkResourceProvider has been called."); + } + this.resource = this.resource.merge(resource); + this.resourceExplicitlySet = true; + return this; + } + + /** + * Sets the {@link SdkResourceProvider} used to resolve the {@link Resource} attached to all + * spans. + * + *

      Mutually exclusive with {@link #setResource(Resource)} and {@link #addResource(Resource)}. + * The conflicting setter throws {@link IllegalStateException} if both are configured. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#setSdkResourceProvider(SdkTracerProviderBuilder, SdkResourceProvider)}. + */ + SdkTracerProviderBuilder setSdkResourceProvider(SdkResourceProvider resourceProvider) { + requireNonNull(resourceProvider, "resourceProvider"); + if (resourceExplicitlySet) { + throw new IllegalStateException( + "Cannot call setSdkResourceProvider after setResource or addResource has been called."); + } + this.resourceProvider = resourceProvider; return this; } @@ -76,8 +146,7 @@ public SdkTracerProviderBuilder setResource(Resource resource) { *

      This method is equivalent to calling {@link #setSpanLimits(Supplier)} like this {@code * #setSpanLimits(() -> spanLimits)}. * - * @param spanLimits the limits that will be used for every {@link - * io.opentelemetry.api.trace.Span}. + * @param spanLimits the limits that will be used for every {@link Span}. * @return this */ public SdkTracerProviderBuilder setSpanLimits(SpanLimits spanLimits) { @@ -88,13 +157,13 @@ public SdkTracerProviderBuilder setSpanLimits(SpanLimits spanLimits) { /** * Assign a {@link Supplier} of {@link SpanLimits}. {@link SpanLimits} will be retrieved each time - * a {@link io.opentelemetry.api.trace.Span} is started. + * a {@link Span} is started. * *

      The {@code spanLimitsSupplier} must be thread-safe and return immediately (no remote calls, * as contention free as possible). * * @param spanLimitsSupplier the supplier that will be used to retrieve the {@link SpanLimits} for - * every {@link io.opentelemetry.api.trace.Span}. + * every {@link Span}. * @return this */ public SdkTracerProviderBuilder setSpanLimits(Supplier spanLimitsSupplier) { @@ -105,7 +174,7 @@ public SdkTracerProviderBuilder setSpanLimits(Supplier spanLimitsSup /** * Assign a {@link Sampler} to use for sampling traces. {@link Sampler} will be called each time a - * {@link io.opentelemetry.api.trace.Span} is started. + * {@link Span} is started. * *

      The {@code sampler} must be thread-safe and return immediately (no remote calls, as * contention free as possible). @@ -121,7 +190,7 @@ public SdkTracerProviderBuilder setSampler(Sampler sampler) { /** * Add a SpanProcessor to the span pipeline that will be built. {@link SpanProcessor} will be - * called each time a {@link io.opentelemetry.api.trace.Span} is started or ended. + * called each time a {@link Span} is started or ended. * *

      The {@code spanProcessor} must be thread-safe and return immediately (no remote calls, as * contention free as possible). @@ -130,18 +199,129 @@ public SdkTracerProviderBuilder setSampler(Sampler sampler) { * @return this */ public SdkTracerProviderBuilder addSpanProcessor(SpanProcessor spanProcessor) { + requireNonNull(spanProcessor, "spanProcessor"); spanProcessors.add(spanProcessor); return this; } + /** + * Add a SpanProcessor to the beginning of the span pipeline that will be built. {@link + * SpanProcessor} will be called each time a {@link Span} is started or ended. + * + *

      The {@code spanProcessor} must be thread-safe and return immediately (no remote calls, as + * contention free as possible). + * + * @param spanProcessor the processor to be added to the beginning of the span pipeline. + * @return this + * @since 1.50.0 + */ + public SdkTracerProviderBuilder addSpanProcessorFirst(SpanProcessor spanProcessor) { + requireNonNull(spanProcessor, "spanProcessor"); + spanProcessors.add(0, spanProcessor); + return this; + } + + /** + * Set the tracer configurator, which computes {@link TracerConfig} for each {@link + * InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#setTracerConfigurator(SdkTracerProviderBuilder, ScopeConfigurator)}. + * + *

      Overrides any matchers added via {@link #addTracerConfiguratorCondition(Predicate, + * TracerConfig)}. + * + * @see TracerConfig#configuratorBuilder() + */ + SdkTracerProviderBuilder setTracerConfigurator( + ScopeConfigurator tracerConfigurator) { + this.tracerConfiguratorBuilder = tracerConfigurator.toBuilder(); + return this; + } + + /** + * Adds a condition to the tracer configurator, which computes {@link TracerConfig} for each + * {@link InstrumentationScopeInfo}. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#addTracerConfiguratorCondition(SdkTracerProviderBuilder, Predicate, + * TracerConfig)}. + * + *

      Applies after any previously added conditions. + * + *

      If {@link #setTracerConfigurator(ScopeConfigurator)} was previously called, this condition + * will only be applied if the {@link ScopeConfigurator#apply(Object)} returns null for the + * matched {@link InstrumentationScopeInfo}(s). + * + * @see ScopeConfiguratorBuilder#nameEquals(String) + * @see ScopeConfiguratorBuilder#nameMatchesGlob(String) + */ + SdkTracerProviderBuilder addTracerConfiguratorCondition( + Predicate scopeMatcher, TracerConfig tracerConfig) { + this.tracerConfiguratorBuilder.addCondition(scopeMatcher, tracerConfig); + return this; + } + + /** + * Sets the exception attribute resolver, which resolves {@code exception.*} attributes when + * {@link Span#recordException(Throwable)} is called. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#setExceptionAttributeResolver(SdkTracerProviderBuilder, + * ExceptionAttributeResolver)}. + */ + SdkTracerProviderBuilder setExceptionAttributeResolver( + ExceptionAttributeResolver exceptionAttributeResolver) { + requireNonNull(exceptionAttributeResolver, "exceptionAttributeResolver"); + this.exceptionAttributeResolver = exceptionAttributeResolver; + return this; + } + + /** + * Sets the {@link MeterProvider} to use to generate SDK Span + * Metrics. + * + * @since 1.58.0 + */ + public SdkTracerProviderBuilder setMeterProvider(Supplier meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = meterProvider; + return this; + } + + /** + * Sets the filter predicate to determine which context-scoped attributes are inherited by spans. + * + *

      This method is experimental so not public. You may reflectively call it using {@link + * SdkTracerProviderUtil#setContextScopedAttributesFilter(SdkTracerProviderBuilder, BiPredicate)}. + */ + SdkTracerProviderBuilder setContextScopedAttributesFilter( + @Nullable + BiPredicate> contextScopedAttributesFilter) { + this.contextScopedAttributesFilter = contextScopedAttributesFilter; + return this; + } + /** * Create a new {@link SdkTracerProvider} instance with the configuration. * * @return The instance. */ public SdkTracerProvider build() { + SdkResourceProvider effectiveSdkResourceProvider = + resourceProvider != null ? resourceProvider : SdkResourceProvider.create(resource); return new SdkTracerProvider( - clock, idsGenerator, resource, spanLimitsSupplier, sampler, spanProcessors); + clock, + idsGenerator, + effectiveSdkResourceProvider, + spanLimitsSupplier, + sampler, + spanProcessors, + tracerConfiguratorBuilder.build(), + exceptionAttributeResolver, + meterProvider, + contextScopedAttributesFilter); } SdkTracerProviderBuilder() {} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanLimitsBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanLimitsBuilder.java index 14b5f06f1a6..30f8f69a562 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanLimitsBuilder.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanLimitsBuilder.java @@ -29,12 +29,13 @@ public final class SpanLimitsBuilder { /** * Sets the max number of attributes per {@link Span}. * - * @param maxNumberOfAttributes the max number of attributes per {@link Span}. Must be positive. + * @param maxNumberOfAttributes the max number of attributes per {@link Span}. Must not be + * negative. * @return this. - * @throws IllegalArgumentException if {@code maxNumberOfAttributes} is not positive. + * @throws IllegalArgumentException if {@code maxNumberOfAttributes} is negative. */ public SpanLimitsBuilder setMaxNumberOfAttributes(int maxNumberOfAttributes) { - Utils.checkArgument(maxNumberOfAttributes > 0, "maxNumberOfAttributes must be greater than 0"); + Utils.checkArgument(maxNumberOfAttributes >= 0, "maxNumberOfAttributes must be non-negative"); this.maxNumAttributes = maxNumberOfAttributes; return this; } @@ -42,12 +43,12 @@ public SpanLimitsBuilder setMaxNumberOfAttributes(int maxNumberOfAttributes) { /** * Sets the max number of events per {@link Span}. * - * @param maxNumberOfEvents the max number of events per {@link Span}. Must be positive. + * @param maxNumberOfEvents the max number of events per {@link Span}. Must not be negative. * @return this. - * @throws IllegalArgumentException if {@code maxNumberOfEvents} is not positive. + * @throws IllegalArgumentException if {@code maxNumberOfEvents} is negative. */ public SpanLimitsBuilder setMaxNumberOfEvents(int maxNumberOfEvents) { - Utils.checkArgument(maxNumberOfEvents > 0, "maxNumberOfEvents must be greater than 0"); + Utils.checkArgument(maxNumberOfEvents >= 0, "maxNumberOfEvents must be non-negative"); this.maxNumEvents = maxNumberOfEvents; return this; } @@ -55,12 +56,12 @@ public SpanLimitsBuilder setMaxNumberOfEvents(int maxNumberOfEvents) { /** * Sets the max number of links per {@link Span}. * - * @param maxNumberOfLinks the max number of links per {@link Span}. Must be positive. + * @param maxNumberOfLinks the max number of links per {@link Span}. Must not be negative. * @return this. - * @throws IllegalArgumentException if {@code maxNumberOfLinks} is not positive. + * @throws IllegalArgumentException if {@code maxNumberOfLinks} is negative. */ public SpanLimitsBuilder setMaxNumberOfLinks(int maxNumberOfLinks) { - Utils.checkArgument(maxNumberOfLinks > 0, "maxNumberOfLinks must be greater than 0"); + Utils.checkArgument(maxNumberOfLinks >= 0, "maxNumberOfLinks must be non-negative"); this.maxNumLinks = maxNumberOfLinks; return this; } @@ -68,13 +69,14 @@ public SpanLimitsBuilder setMaxNumberOfLinks(int maxNumberOfLinks) { /** * Sets the max number of attributes per event. * - * @param maxNumberOfAttributesPerEvent the max number of attributes per event. Must be positive. + * @param maxNumberOfAttributesPerEvent the max number of attributes per event. Must not be + * negative. * @return this. - * @throws IllegalArgumentException if {@code maxNumberOfAttributesPerEvent} is not positive. + * @throws IllegalArgumentException if {@code maxNumberOfAttributesPerEvent} is negative. */ public SpanLimitsBuilder setMaxNumberOfAttributesPerEvent(int maxNumberOfAttributesPerEvent) { Utils.checkArgument( - maxNumberOfAttributesPerEvent > 0, "maxNumberOfAttributesPerEvent must be greater than 0"); + maxNumberOfAttributesPerEvent >= 0, "maxNumberOfAttributesPerEvent must be non-negative"); this.maxNumAttributesPerEvent = maxNumberOfAttributesPerEvent; return this; } @@ -82,13 +84,14 @@ public SpanLimitsBuilder setMaxNumberOfAttributesPerEvent(int maxNumberOfAttribu /** * Sets the max number of attributes per link. * - * @param maxNumberOfAttributesPerLink the max number of attributes per link. Must be positive. + * @param maxNumberOfAttributesPerLink the max number of attributes per link. Must not be + * negative. * @return this. - * @throws IllegalArgumentException if {@code maxNumberOfAttributesPerLink} is not positive. + * @throws IllegalArgumentException if {@code maxNumberOfAttributesPerLink} is negative. */ public SpanLimitsBuilder setMaxNumberOfAttributesPerLink(int maxNumberOfAttributesPerLink) { Utils.checkArgument( - maxNumberOfAttributesPerLink > 0, "maxNumberOfAttributesPerLink must be greater than 0"); + maxNumberOfAttributesPerLink >= 0, "maxNumberOfAttributesPerLink must be non-negative"); this.maxNumAttributesPerLink = maxNumberOfAttributesPerLink; return this; } @@ -104,7 +107,7 @@ public SpanLimitsBuilder setMaxNumberOfAttributesPerLink(int maxNumberOfAttribut */ public SpanLimitsBuilder setMaxAttributeValueLength(int maxAttributeValueLength) { Utils.checkArgument( - maxAttributeValueLength > -1, "maxAttributeValueLength must be non-negative"); + maxAttributeValueLength >= 0, "maxAttributeValueLength must be non-negative"); this.maxAttributeValueLength = maxAttributeValueLength; return this; } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanWrapper.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanWrapper.java index 962601b1d58..651e07d1127 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanWrapper.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/SpanWrapper.java @@ -9,8 +9,9 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.InstrumentationScopeUtil; +import io.opentelemetry.sdk.common.internal.InstrumentationScopeUtil; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.data.EventData; import io.opentelemetry.sdk.trace.data.LinkData; @@ -43,6 +44,8 @@ abstract class SpanWrapper implements SpanData { abstract int totalRecordedEvents(); + abstract int totalRecordedLinks(); + abstract StatusData status(); abstract String name(); @@ -62,6 +65,7 @@ static SpanWrapper create( Attributes attributes, int totalAttributeCount, int totalRecordedEvents, + int totalRecordedLinks, StatusData status, String name, long endEpochNanos, @@ -73,6 +77,7 @@ static SpanWrapper create( attributes, totalAttributeCount, totalRecordedEvents, + totalRecordedLinks, status, name, endEpochNanos, @@ -96,7 +101,7 @@ public Resource getResource() { @Override @Deprecated - public io.opentelemetry.sdk.common.InstrumentationLibraryInfo getInstrumentationLibraryInfo() { + public InstrumentationLibraryInfo getInstrumentationLibraryInfo() { return InstrumentationScopeUtil.toInstrumentationLibraryInfo( delegate().getInstrumentationScopeInfo()); } @@ -158,7 +163,7 @@ public int getTotalRecordedEvents() { @Override public int getTotalRecordedLinks() { - return delegate().getTotalRecordedLinks(); + return totalRecordedLinks(); } @Override diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/TracerSharedState.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/TracerSharedState.java index 99cd1ea26c0..21abf410ef2 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/TracerSharedState.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/TracerSharedState.java @@ -5,43 +5,69 @@ package io.opentelemetry.sdk.trace; +import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; import io.opentelemetry.sdk.trace.samplers.Sampler; +import java.util.Arrays; import java.util.List; +import java.util.function.BiPredicate; import java.util.function.Supplier; import javax.annotation.Nullable; // Represents the shared state/config between all Tracers created by the same TracerProvider. final class TracerSharedState { + private final Object lock = new Object(); private final Clock clock; private final IdGenerator idGenerator; // tracks whether it is safe to skip id validation on ids from the above generator private final boolean idGeneratorSafeToSkipIdValidation; - private final Resource resource; + private final SdkResourceProvider resourceProvider; private final Supplier spanLimitsSupplier; private final Sampler sampler; private final SpanProcessor activeSpanProcessor; + private final ExceptionAttributeResolver exceptionAttributeResolver; + private final SdkTracerInstrumentation tracerInstrumentation; + + @Nullable + private final BiPredicate> + contextScopedAttributesFilter; + + private final boolean noSpanProcessor; @Nullable private volatile CompletableResultCode shutdownResult = null; TracerSharedState( Clock clock, IdGenerator idGenerator, - Resource resource, + SdkResourceProvider resourceProvider, Supplier spanLimitsSupplier, Sampler sampler, - List spanProcessors) { + List spanProcessors, + ExceptionAttributeResolver exceptionAttributeResolver, + SdkTracerInstrumentation tracerInstrumentation, + @Nullable + BiPredicate> contextScopedAttributesFilter) { this.clock = clock; this.idGenerator = idGenerator; this.idGeneratorSafeToSkipIdValidation = idGenerator instanceof RandomIdGenerator; - this.resource = resource; + this.resourceProvider = resourceProvider; this.spanLimitsSupplier = spanLimitsSupplier; this.sampler = sampler; - activeSpanProcessor = SpanProcessor.composite(spanProcessors); + this.activeSpanProcessor = SpanProcessor.composite(spanProcessors); + this.exceptionAttributeResolver = exceptionAttributeResolver; + this.tracerInstrumentation = tracerInstrumentation; + this.contextScopedAttributesFilter = contextScopedAttributesFilter; + // Note: This relies on SpanProcessor.composite(..) returning NoopSpanProcessor unwrapped + // when given an empty list. If SpanProcessor.composite(..) behavior changes, this instanceof + // check must change too + this.noSpanProcessor = activeSpanProcessor instanceof NoopSpanProcessor; } Clock getClock() { @@ -57,7 +83,7 @@ boolean isIdGeneratorSafeToSkipIdValidation() { } Resource getResource() { - return resource; + return resourceProvider.getResource(); } /** Returns the current {@link SpanLimits}. */ @@ -88,19 +114,41 @@ boolean hasBeenShutdown() { return shutdownResult != null; } + boolean hasNoSpanProcessor() { + return noSpanProcessor; + } + + /** Return the {@link ExceptionAttributeResolver}. */ + ExceptionAttributeResolver getExceptionAttributesResolver() { + return exceptionAttributeResolver; + } + + SdkTracerInstrumentation getTracerInstrumentation() { + return tracerInstrumentation; + } + + @Nullable + BiPredicate> getContextScopedAttributesFilter() { + return contextScopedAttributesFilter; + } + /** - * Stops tracing, including shutting down processors and set to {@code true} {@link + * Stops tracing, including shutting down processors and sampler and set to {@code true} {@link * #hasBeenShutdown()}. * - * @return a {@link CompletableResultCode} that will be completed when the span processor is shut - * down. + * @return a {@link CompletableResultCode} that will be completed when the span processor and + * sampler are shut down. */ CompletableResultCode shutdown() { synchronized (lock) { if (shutdownResult != null) { return shutdownResult; } - shutdownResult = activeSpanProcessor.shutdown(); + + shutdownResult = + CompletableResultCode.ofAll( + Arrays.asList(activeSpanProcessor.shutdown(), sampler.shutdown())); + return shutdownResult; } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/DelegatingSpanData.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/DelegatingSpanData.java index 859fd912675..d443f85285a 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/DelegatingSpanData.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/DelegatingSpanData.java @@ -10,6 +10,7 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; import io.opentelemetry.sdk.resources.Resource; import java.util.List; @@ -29,7 +30,7 @@ * // SpanDataWithClientType(SpanData delegate) { * // super(delegate); * // String clientType = ClientConfig.parseUserAgent( - * // delegate.getAttributes().get(SemanticAttributes.HTTP_USER_AGENT).getStringValue()); + * // delegate.getAttributes().get(SemanticAttributes.USER_AGENT_ORIGINAL).getStringValue()); * // Attributes.Builder newAttributes = Attributes.builder(delegate.getAttributes()); * // newAttributes.setAttribute("client_type", clientType); * // attributes = newAttributes.build(); @@ -67,7 +68,7 @@ public Resource getResource() { @Override @Deprecated - public io.opentelemetry.sdk.common.InstrumentationLibraryInfo getInstrumentationLibraryInfo() { + public InstrumentationLibraryInfo getInstrumentationLibraryInfo() { return delegate.getInstrumentationLibraryInfo(); } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/ExceptionEventData.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/ExceptionEventData.java new file mode 100644 index 00000000000..c5170e2485a --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/ExceptionEventData.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.data; + +import io.opentelemetry.api.common.Attributes; +import javax.annotation.concurrent.Immutable; + +/** + * Data representation of an event for a recorded exception. + * + * @since 1.44.0 + */ +@Immutable +public interface ExceptionEventData extends EventData { + + /** + * Returns a new immutable {@link ExceptionEventData}. + * + * @param epochNanos epoch timestamp in nanos of the {@link ExceptionEventData}. + * @param exception the {@link Throwable exception} of the {@code Event}. + * @param attributes the additional attributes of the {@link ExceptionEventData}. + * @param totalAttributeCount the total number of attributes for this {@code} Event. + * @return a new immutable {@link ExceptionEventData} + */ + static ExceptionEventData create( + long epochNanos, Throwable exception, Attributes attributes, int totalAttributeCount) { + return ImmutableExceptionEventData.create( + epochNanos, exception, attributes, totalAttributeCount); + } + + /** + * Return the {@link Throwable exception} of the {@link ExceptionEventData}. + * + * @return the {@link Throwable exception} of the {@link ExceptionEventData} + */ + Throwable getException(); +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/ImmutableExceptionEventData.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/ImmutableExceptionEventData.java new file mode 100644 index 00000000000..fd2e4bac752 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/ImmutableExceptionEventData.java @@ -0,0 +1,40 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.data; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.common.Attributes; +import javax.annotation.concurrent.Immutable; + +/** An effectively immutable implementation of {@link ExceptionEventData}. */ +@AutoValue +@Immutable +abstract class ImmutableExceptionEventData implements ExceptionEventData { + + private static final String EXCEPTION_EVENT_NAME = "exception"; + + @Override + public final String getName() { + return EXCEPTION_EVENT_NAME; + } + + /** + * Returns a new immutable {@code Event}. + * + * @param epochNanos epoch timestamp in nanos of the {@code Event}. + * @param exception the {@link Throwable exception} of the {@code Event}. + * @param attributes the additional {@link Attributes} of the {@code Event}. + * @param totalAttributeCount the total number of attributes for this {@code} Event. + * @return a new immutable {@code Event} + */ + static ExceptionEventData create( + long epochNanos, Throwable exception, Attributes attributes, int totalAttributeCount) { + return new AutoValue_ImmutableExceptionEventData( + attributes, epochNanos, totalAttributeCount, exception); + } + + ImmutableExceptionEventData() {} +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/SpanData.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/SpanData.java index ae1de5255cb..f3dda48d31f 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/SpanData.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/data/SpanData.java @@ -8,7 +8,9 @@ import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanKind; +import io.opentelemetry.sdk.common.InstrumentationLibraryInfo; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.InstrumentationScopeUtil; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.trace.SpanLimits; import java.util.List; @@ -157,7 +159,7 @@ default String getParentSpanId() { * @deprecated Use {@link #getInstrumentationScopeInfo()}. */ @Deprecated - io.opentelemetry.sdk.common.InstrumentationLibraryInfo getInstrumentationLibraryInfo(); + InstrumentationLibraryInfo getInstrumentationLibraryInfo(); /** * Returns the instrumentation scope specified when creating the tracer which produced this {@code @@ -165,7 +167,9 @@ default String getParentSpanId() { * * @return an instance of {@link InstrumentationScopeInfo} */ - InstrumentationScopeInfo getInstrumentationScopeInfo(); + default InstrumentationScopeInfo getInstrumentationScopeInfo() { + return InstrumentationScopeUtil.toInstrumentationScopeInfo(getInstrumentationLibraryInfo()); + } /** * Returns the resource of this {@code Span}. diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java index ad805b4c1b1..422c9a576c1 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessor.java @@ -5,15 +5,15 @@ package io.opentelemetry.sdk.trace.export; -import io.opentelemetry.api.common.AttributeKey; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.metrics.LongCounter; -import io.opentelemetry.api.metrics.Meter; +import static java.util.Objects.requireNonNull; + import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.CompletableResultCode; -import io.opentelemetry.sdk.internal.DaemonThreadFactory; -import io.opentelemetry.sdk.internal.ThrowableUtil; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.DaemonThreadFactory; +import io.opentelemetry.sdk.common.internal.ThrowableUtil; import io.opentelemetry.sdk.trace.ReadWriteSpan; import io.opentelemetry.sdk.trace.ReadableSpan; import io.opentelemetry.sdk.trace.SpanProcessor; @@ -21,6 +21,7 @@ import io.opentelemetry.sdk.trace.internal.JcTools; import java.util.ArrayList; import java.util.Collections; +import java.util.List; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; @@ -28,6 +29,7 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -42,16 +44,33 @@ */ public final class BatchSpanProcessor implements SpanProcessor { + private static final ComponentId COMPONENT_ID = + ComponentId.generateLazy("batching_span_processor"); + + private static final Logger logger = Logger.getLogger(BatchSpanProcessor.class.getName()); + private static final String WORKER_THREAD_NAME = BatchSpanProcessor.class.getSimpleName() + "_WorkerThread"; - private static final AttributeKey SPAN_PROCESSOR_TYPE_LABEL = - AttributeKey.stringKey("spanProcessorType"); - private static final AttributeKey SPAN_PROCESSOR_DROPPED_LABEL = - AttributeKey.booleanKey("dropped"); - private static final String SPAN_PROCESSOR_TYPE_VALUE = BatchSpanProcessor.class.getSimpleName(); + private final boolean exportUnsampledSpans; private final Worker worker; - private final AtomicBoolean isShutdown = new AtomicBoolean(false); + + /** + * Returns a new {@link BatchSpanProcessor} with default configuration which batches spans + * exported by the SDK then pushes them to the {@code spanExporter}. + * + *

      This is a convenience method equivalent to {@code + * BatchSpanProcessor.builder(spanExporter).build()}. Use {@link #builder(SpanExporter)} if you + * need to customize the configuration. + * + * @param spanExporter the {@link SpanExporter} to which the Spans are pushed. + * @return a new {@link BatchSpanProcessor}. + * @since 1.64.0 + */ + public static BatchSpanProcessor create(SpanExporter spanExporter) { + requireNonNull(spanExporter, "spanExporter"); + return builder(spanExporter).build(); + } /** * Returns a new Builder for {@link BatchSpanProcessor}. @@ -66,19 +85,24 @@ public static BatchSpanProcessorBuilder builder(SpanExporter spanExporter) { BatchSpanProcessor( SpanExporter spanExporter, - MeterProvider meterProvider, + boolean exportUnsampledSpans, + Supplier meterProvider, + InternalTelemetryVersion telemetryVersion, long scheduleDelayNanos, int maxQueueSize, int maxExportBatchSize, long exporterTimeoutNanos) { + this.exportUnsampledSpans = exportUnsampledSpans; this.worker = new Worker( spanExporter, meterProvider, + telemetryVersion, scheduleDelayNanos, maxExportBatchSize, exporterTimeoutNanos, - JcTools.newFixedSizeQueue(maxQueueSize)); + JcTools.newFixedSizeQueue(maxQueueSize), + maxQueueSize); Thread workerThread = new DaemonThreadFactory(WORKER_THREAD_NAME).newThread(worker); workerThread.start(); } @@ -93,10 +117,9 @@ public boolean isStartRequired() { @Override public void onEnd(ReadableSpan span) { - if (span == null || !span.getSpanContext().isSampled()) { - return; + if (span != null && (exportUnsampledSpans || span.getSpanContext().isSampled())) { + worker.addSpan(span); } - worker.addSpan(span); } @Override @@ -106,9 +129,6 @@ public boolean isEndRequired() { @Override public CompletableResultCode shutdown() { - if (isShutdown.getAndSet(true)) { - return CompletableResultCode.ofSuccess(); - } return worker.shutdown(); } @@ -117,8 +137,17 @@ public CompletableResultCode forceFlush() { return worker.forceFlush(); } + /** + * Return the processor's configured {@link SpanExporter}. + * + * @since 1.37.0 + */ + public SpanExporter getSpanExporter() { + return worker.spanExporter; + } + // Visible for testing - ArrayList getBatch() { + List getBatch() { return worker.batch; } @@ -132,6 +161,8 @@ public String toString() { return "BatchSpanProcessor{" + "spanExporter=" + worker.spanExporter + + ", exportUnsampledSpans=" + + exportUnsampledSpans + ", scheduleDelayNanos=" + worker.scheduleDelayNanos + ", maxExportBatchSize=" @@ -145,11 +176,7 @@ public String toString() { // the data. private static final class Worker implements Runnable { - private static final Logger logger = Logger.getLogger(Worker.class.getName()); - - private final LongCounter processedSpansCounter; - private final Attributes droppedAttrs; - private final Attributes exportedAttrs; + private final SpanProcessorInstrumentation spanProcessorInstrumentation; private final SpanExporter spanExporter; private final long scheduleDelayNanos; @@ -159,6 +186,7 @@ private static final class Worker implements Runnable { private long nextExportTime; private final Queue queue; + private final AtomicInteger queueSize = new AtomicInteger(); // When waiting on the spans queue, exporter thread sets this atomic to the number of more // spans it needs before doing an export. Writer threads would then wait for the queue to reach // spansNeeded size before notifying the exporter thread about new entries. @@ -168,62 +196,46 @@ private static final class Worker implements Runnable { private final AtomicInteger spansNeeded = new AtomicInteger(Integer.MAX_VALUE); private final BlockingQueue signal; private final AtomicReference flushRequested = new AtomicReference<>(); + private final AtomicBoolean isShutdown = new AtomicBoolean(false); private volatile boolean continueWork = true; private final ArrayList batch; + private final long maxQueueSize; + private final AtomicInteger droppedSpanCount = new AtomicInteger(0); private Worker( SpanExporter spanExporter, - MeterProvider meterProvider, + Supplier meterProvider, + InternalTelemetryVersion telemetryVersion, long scheduleDelayNanos, int maxExportBatchSize, long exporterTimeoutNanos, - Queue queue) { + Queue queue, + long maxQueueSize) { this.spanExporter = spanExporter; this.scheduleDelayNanos = scheduleDelayNanos; this.maxExportBatchSize = maxExportBatchSize; this.exporterTimeoutNanos = exporterTimeoutNanos; this.queue = queue; this.signal = new ArrayBlockingQueue<>(1); - Meter meter = meterProvider.meterBuilder("io.opentelemetry.sdk.trace").build(); - meter - .gaugeBuilder("queueSize") - .ofLongs() - .setDescription("The number of spans queued") - .setUnit("1") - .buildWithCallback( - result -> - result.record( - queue.size(), - Attributes.of(SPAN_PROCESSOR_TYPE_LABEL, SPAN_PROCESSOR_TYPE_VALUE))); - processedSpansCounter = - meter - .counterBuilder("processedSpans") - .setUnit("1") - .setDescription( - "The number of spans processed by the BatchSpanProcessor. " - + "[dropped=true if they were dropped due to high throughput]") - .build(); - droppedAttrs = - Attributes.of( - SPAN_PROCESSOR_TYPE_LABEL, - SPAN_PROCESSOR_TYPE_VALUE, - SPAN_PROCESSOR_DROPPED_LABEL, - true); - exportedAttrs = - Attributes.of( - SPAN_PROCESSOR_TYPE_LABEL, - SPAN_PROCESSOR_TYPE_VALUE, - SPAN_PROCESSOR_DROPPED_LABEL, - false); + + spanProcessorInstrumentation = + SpanProcessorInstrumentation.get(telemetryVersion, COMPONENT_ID, meterProvider); + this.maxQueueSize = maxQueueSize; this.batch = new ArrayList<>(this.maxExportBatchSize); } private void addSpan(ReadableSpan span) { + if (isShutdown.get()) { + spanProcessorInstrumentation.dropSpansAlreadyShutdown(1); + return; + } + spanProcessorInstrumentation.buildQueueMetricsOnce(maxQueueSize, queue::size); if (!queue.offer(span)) { - processedSpansCounter.add(1, droppedAttrs); + spanProcessorInstrumentation.dropSpansQueueFull(1); + droppedSpanCount.incrementAndGet(); } else { - if (queue.size() >= spansNeeded.get()) { + if (queueSize.incrementAndGet() >= spansNeeded.get()) { signal.offer(true); } } @@ -237,9 +249,8 @@ public void run() { if (flushRequested.get() != null) { flush(); } - while (!queue.isEmpty() && batch.size() < maxExportBatchSize) { - batch.add(queue.poll().toSpanData()); - } + drain(maxExportBatchSize - batch.size()); + if (batch.size() >= maxExportBatchSize || System.nanoTime() >= nextExportTime) { exportCurrentBatch(); updateNextExportTime(); @@ -260,13 +271,17 @@ public void run() { } } + private int drain(int limit) { + int drained = JcTools.drain(queue, limit, span -> batch.add(span.toSpanData())); + queueSize.addAndGet(-drained); + return drained; + } + private void flush() { - int spansToFlush = queue.size(); + int spansToFlush = queueSize.get(); while (spansToFlush > 0) { - ReadableSpan span = queue.poll(); - assert span != null; - batch.add(span.toSpanData()); - spansToFlush--; + int drained = drain(maxExportBatchSize - batch.size()); + spansToFlush -= drained; if (batch.size() >= maxExportBatchSize) { exportCurrentBatch(); } @@ -284,22 +299,23 @@ private void updateNextExportTime() { } private CompletableResultCode shutdown() { + if (isShutdown.getAndSet(true)) { + return CompletableResultCode.ofSuccess(); + } CompletableResultCode result = new CompletableResultCode(); CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - continueWork = false; - CompletableResultCode shutdownResult = spanExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); + flushResult.whenComplete(() -> { + continueWork = false; + CompletableResultCode shutdownResult = spanExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); return result; } @@ -322,12 +338,25 @@ private void exportCurrentBatch() { return; } + int dropped = droppedSpanCount.getAndSet(0); + if (dropped > 0) { + logger.log( + Level.WARNING, + "BatchSpanProcessor dropped " + + dropped + + " span(s) since the last export because the queue is full" + + " (maxQueueSize=" + + maxQueueSize + + ")"); + } + try { + // We always increment for every export invocation, so we increment before the export call + // to make sure thrown errors don't affect it. + spanProcessorInstrumentation.finishSpans(batch.size()); CompletableResultCode result = spanExporter.export(Collections.unmodifiableList(batch)); result.join(exporterTimeoutNanos, TimeUnit.NANOSECONDS); - if (result.isSuccess()) { - processedSpansCounter.add(batch.size(), exportedAttrs); - } else { + if (!result.isSuccess()) { logger.log(Level.FINE, "Exporter failed"); } } catch (Throwable t) { diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorBuilder.java index d801c2296bc..67336addd08 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorBuilder.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorBuilder.java @@ -9,11 +9,16 @@ import static java.util.Objects.requireNonNull; import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; import java.time.Duration; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.logging.Level; +import java.util.logging.Logger; /** Builder class for {@link BatchSpanProcessor}. */ public final class BatchSpanProcessorBuilder { + private static final Logger logger = Logger.getLogger(BatchSpanProcessorBuilder.class.getName()); // Visible for testing static final long DEFAULT_SCHEDULE_DELAY_MILLIS = 5000; @@ -25,16 +30,29 @@ public final class BatchSpanProcessorBuilder { static final int DEFAULT_EXPORT_TIMEOUT_MILLIS = 30_000; private final SpanExporter spanExporter; + private boolean exportUnsampledSpans = false; private long scheduleDelayNanos = TimeUnit.MILLISECONDS.toNanos(DEFAULT_SCHEDULE_DELAY_MILLIS); private int maxQueueSize = DEFAULT_MAX_QUEUE_SIZE; private int maxExportBatchSize = DEFAULT_MAX_EXPORT_BATCH_SIZE; private long exporterTimeoutNanos = TimeUnit.MILLISECONDS.toNanos(DEFAULT_EXPORT_TIMEOUT_MILLIS); - private MeterProvider meterProvider = MeterProvider.noop(); + private Supplier meterProvider = MeterProvider::noop; + private InternalTelemetryVersion telemetryVersion = InternalTelemetryVersion.LEGACY; BatchSpanProcessorBuilder(SpanExporter spanExporter) { this.spanExporter = requireNonNull(spanExporter, "spanExporter"); } + /** + * Sets whether unsampled spans should be exported. If unset, defaults to exporting only sampled + * spans. + * + * @since 1.34.0 + */ + public BatchSpanProcessorBuilder setExportUnsampledSpans(boolean exportUnsampledSpans) { + this.exportUnsampledSpans = exportUnsampledSpans; + return this; + } + /** * Sets the delay interval between two consecutive exports. If unset, defaults to {@value * DEFAULT_SCHEDULE_DELAY_MILLIS}ms. @@ -67,7 +85,7 @@ long getScheduleDelayNanos() { public BatchSpanProcessorBuilder setExporterTimeout(long timeout, TimeUnit unit) { requireNonNull(unit, "unit"); checkArgument(timeout >= 0, "timeout must be non-negative"); - exporterTimeoutNanos = unit.toNanos(timeout); + exporterTimeoutNanos = timeout == 0 ? Long.MAX_VALUE : unit.toNanos(timeout); return this; } @@ -94,9 +112,11 @@ long getExporterTimeoutNanos() { * @param maxQueueSize the maximum number of Spans that are kept in the queue before start * dropping. * @return this. + * @throws IllegalArgumentException if {@code maxQueueSize} is not positive. * @see BatchSpanProcessorBuilder#DEFAULT_MAX_QUEUE_SIZE */ public BatchSpanProcessorBuilder setMaxQueueSize(int maxQueueSize) { + checkArgument(maxQueueSize > 0, "maxQueueSize must be positive."); this.maxQueueSize = maxQueueSize; return this; } @@ -127,11 +147,35 @@ public BatchSpanProcessorBuilder setMaxExportBatchSize(int maxExportBatchSize) { * metrics will not be collected. */ public BatchSpanProcessorBuilder setMeterProvider(MeterProvider meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = () -> meterProvider; + return this; + } + + /** + * Sets the {@link MeterProvider} to use to collect metrics related to batch export. If not set, + * metrics will not be collected. + * + * @since 1.58.0 + */ + public BatchSpanProcessorBuilder setMeterProvider(Supplier meterProvider) { requireNonNull(meterProvider, "meterProvider"); this.meterProvider = meterProvider; return this; } + /** + * Sets the {@link InternalTelemetryVersion} defining which metrics this processor records. + * + * @since 1.58.0 + */ + public BatchSpanProcessorBuilder setInternalTelemetryVersion( + InternalTelemetryVersion telemetryVersion) { + requireNonNull(telemetryVersion, "telemetryVersion"); + this.telemetryVersion = telemetryVersion; + return this; + } + // Visible for testing int getMaxExportBatchSize() { return maxExportBatchSize; @@ -144,9 +188,18 @@ int getMaxExportBatchSize() { * @return a new {@link BatchSpanProcessor}. */ public BatchSpanProcessor build() { + if (maxExportBatchSize > maxQueueSize) { + logger.log( + Level.WARNING, + "maxExportBatchSize should not exceed maxQueueSize. Setting maxExportBatchSize to {0} instead of {1}", + new Object[] {maxQueueSize, maxExportBatchSize}); + maxExportBatchSize = maxQueueSize; + } return new BatchSpanProcessor( spanExporter, + exportUnsampledSpans, meterProvider, + telemetryVersion, scheduleDelayNanos, maxQueueSize, maxExportBatchSize, diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java new file mode 100644 index 00000000000..368d66f7413 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LegacySpanProcessorInstrumentation.java @@ -0,0 +1,113 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.export; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** Span processor metrics defined before they were standardized in semconv. */ +final class LegacySpanProcessorInstrumentation implements SpanProcessorInstrumentation { + private static final AttributeKey SPAN_PROCESSOR_TYPE_LABEL = + AttributeKey.stringKey("processorType"); + private static final AttributeKey SPAN_PROCESSOR_DROPPED_LABEL = + AttributeKey.booleanKey("dropped"); + // Legacy metrics are only created for batch span processor. + private static final String SPAN_PROCESSOR_TYPE_VALUE = BatchSpanProcessor.class.getSimpleName(); + + private final Object lock = new Object(); + private final AtomicBoolean builtQueueMetrics = new AtomicBoolean(false); + + private final Supplier meterProvider; + private final Attributes standardAttrs; + private final Attributes droppedAttrs; + + @Nullable private Meter meter; + @Nullable private volatile LongCounter processedSpans; + + LegacySpanProcessorInstrumentation(Supplier meterProvider) { + this.meterProvider = meterProvider; + + standardAttrs = + Attributes.of( + SPAN_PROCESSOR_TYPE_LABEL, + SPAN_PROCESSOR_TYPE_VALUE, + SPAN_PROCESSOR_DROPPED_LABEL, + false); + droppedAttrs = + Attributes.of( + SPAN_PROCESSOR_TYPE_LABEL, + SPAN_PROCESSOR_TYPE_VALUE, + SPAN_PROCESSOR_DROPPED_LABEL, + true); + } + + @Override + public void dropSpansQueueFull(int count) { + processedSpans().add(count, droppedAttrs); + } + + @Override + public void dropSpansAlreadyShutdown(int count) { + // Legacy did not record this metric. + } + + @Override + public void finishSpans(int count) { + processedSpans().add(count, standardAttrs); + } + + @Override + public void buildQueueMetricsOnce(long unusedCapacity, LongCallable getSize) { + if (!builtQueueMetrics.compareAndSet(false, true)) { + return; + } + meter() + .gaugeBuilder("queueSize") + .ofLongs() + .setDescription("The number of items queued") + .setUnit("1") + .buildWithCallback(result -> + result.record( + getSize.get(), + Attributes.of(SPAN_PROCESSOR_TYPE_LABEL, SPAN_PROCESSOR_TYPE_VALUE))); + // No capacity metric when legacy. + } + + private LongCounter processedSpans() { + LongCounter processedSpans = this.processedSpans; + if (processedSpans == null) { + synchronized (lock) { + processedSpans = this.processedSpans; + if (processedSpans == null) { + processedSpans = + meter() + .counterBuilder("processedSpans") + .setUnit("1") + .setDescription( + "The number of spans processed by the BatchSpanProcessor. " + + "[dropped=true if they were dropped due to high throughput]") + .build(); + this.processedSpans = processedSpans; + } + } + } + return processedSpans; + } + + private Meter meter() { + if (meter == null) { + // Safe to call from multiple threads. + meter = meterProvider.get().get("io.opentelemetry.sdk.trace"); + } + return meter; + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LongCallable.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LongCallable.java new file mode 100644 index 00000000000..2f7e03d40b4 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/LongCallable.java @@ -0,0 +1,13 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.export; + +/** A Callable returning a primitive long value. */ +@FunctionalInterface +interface LongCallable { + /** Returns the value. */ + long get(); +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/MultiSpanExporter.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/MultiSpanExporter.java index 22afba92935..c8fdb30497a 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/MultiSpanExporter.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/MultiSpanExporter.java @@ -6,6 +6,7 @@ package io.opentelemetry.sdk.trace.export; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.internal.ThrowableUtil; import io.opentelemetry.sdk.trace.SpanProcessor; import io.opentelemetry.sdk.trace.data.SpanData; import java.util.ArrayList; @@ -43,9 +44,10 @@ public CompletableResultCode export(Collection spans) { CompletableResultCode exportResult; try { exportResult = spanExporter.export(spans); - } catch (RuntimeException e) { + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); // If an exception was thrown by the exporter - logger.log(Level.WARNING, "Exception thrown by the export.", e); + logger.log(Level.WARNING, "Exception thrown by the export.", t); results.add(CompletableResultCode.ofFailure()); continue; } @@ -66,9 +68,10 @@ public CompletableResultCode flush() { CompletableResultCode flushResult; try { flushResult = spanExporter.flush(); - } catch (RuntimeException e) { + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); // If an exception was thrown by the exporter - logger.log(Level.WARNING, "Exception thrown by the flush.", e); + logger.log(Level.WARNING, "Exception thrown by the flush.", t); results.add(CompletableResultCode.ofFailure()); continue; } @@ -84,9 +87,10 @@ public CompletableResultCode shutdown() { CompletableResultCode shutdownResult; try { shutdownResult = spanExporter.shutdown(); - } catch (RuntimeException e) { + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); // If an exception was thrown by the exporter - logger.log(Level.WARNING, "Exception thrown by the shutdown.", e); + logger.log(Level.WARNING, "Exception thrown by the shutdown.", t); results.add(CompletableResultCode.ofFailure()); continue; } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SemConvSpanProcessorInstrumentation.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SemConvSpanProcessorInstrumentation.java new file mode 100644 index 00000000000..b147631fddd --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SemConvSpanProcessorInstrumentation.java @@ -0,0 +1,122 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.export; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.LongCounter; +import io.opentelemetry.api.metrics.Meter; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.SemConvConstants; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; +import javax.annotation.Nullable; + +/** + * SDK metrics exported for span processors as defined in the semantic + * conventions. + */ +final class SemConvSpanProcessorInstrumentation implements SpanProcessorInstrumentation { + + private final Object lock = new Object(); + private final AtomicBoolean builtQueueMetrics = new AtomicBoolean(false); + + private final Supplier meterProvider; + private final Attributes standardAttrs; + private final Attributes queueFullAttrs; + private final Attributes shutdownAttrs; + + @Nullable private Meter meter; + @Nullable private volatile LongCounter processedSpans; + + SemConvSpanProcessorInstrumentation( + ComponentId componentId, Supplier meterProvider) { + this.meterProvider = meterProvider; + + standardAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName()); + queueFullAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName(), + SemConvConstants.ERROR_TYPE, + "queue_full"); + shutdownAttrs = + Attributes.of( + SemConvConstants.OTEL_COMPONENT_TYPE, + componentId.getTypeName(), + SemConvConstants.OTEL_COMPONENT_NAME, + componentId.getComponentName(), + SemConvConstants.ERROR_TYPE, + "already_shutdown"); + } + + @Override + public void dropSpansQueueFull(int count) { + processedSpans().add(count, queueFullAttrs); + } + + @Override + public void dropSpansAlreadyShutdown(int count) { + processedSpans().add(count, shutdownAttrs); + } + + @Override + public void finishSpans(int count) { + processedSpans().add(count, standardAttrs); + } + + @Override + public void buildQueueMetricsOnce(long capacity, LongCallable getSize) { + if (!builtQueueMetrics.compareAndSet(false, true)) { + return; + } + meter() + .upDownCounterBuilder(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_NAME) + .setUnit(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_CAPACITY_DESCRIPTION) + .buildWithCallback(m -> m.record(capacity, standardAttrs)); + meter() + .upDownCounterBuilder(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_NAME) + .setUnit(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_QUEUE_SIZE_DESCRIPTION) + .buildWithCallback(m -> m.record(getSize.get(), standardAttrs)); + } + + private LongCounter processedSpans() { + LongCounter processedSpans = this.processedSpans; + if (processedSpans == null) { + synchronized (lock) { + processedSpans = this.processedSpans; + if (processedSpans == null) { + processedSpans = + meter() + .counterBuilder(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_NAME) + .setUnit(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_UNIT) + .setDescription(SemConvConstants.OTEL_SDK_PROCESSOR_SPAN_PROCESSED_DESCRIPTION) + .build(); + this.processedSpans = processedSpans; + } + } + } + return processedSpans; + } + + private Meter meter() { + if (meter == null) { + // Safe to call from multiple threads. + meter = meterProvider.get().get("io.opentelemetry.sdk.trace"); + } + return meter; + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java index ba05a5f0e94..80a14438d11 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessor.java @@ -7,8 +7,12 @@ import static java.util.Objects.requireNonNull; +import io.opentelemetry.api.metrics.MeterProvider; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import io.opentelemetry.sdk.common.internal.ThrowableUtil; import io.opentelemetry.sdk.trace.ReadWriteSpan; import io.opentelemetry.sdk.trace.ReadableSpan; import io.opentelemetry.sdk.trace.SpanProcessor; @@ -18,6 +22,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -33,13 +38,18 @@ */ public final class SimpleSpanProcessor implements SpanProcessor { + private static final ComponentId COMPONENT_ID = ComponentId.generateLazy("simple_span_processor"); + private static final Logger logger = Logger.getLogger(SimpleSpanProcessor.class.getName()); private final SpanExporter spanExporter; - private final boolean sampled; + private final boolean exportUnsampledSpans; private final Set pendingExports = Collections.newSetFromMap(new ConcurrentHashMap<>()); private final AtomicBoolean isShutdown = new AtomicBoolean(false); + private final SpanProcessorInstrumentation spanProcessorInstrumentation; + + private final Object exporterLock = new Object(); /** * Returns a new {@link SimpleSpanProcessor} which exports spans to the {@link SpanExporter} @@ -53,12 +63,28 @@ public final class SimpleSpanProcessor implements SpanProcessor { */ public static SpanProcessor create(SpanExporter exporter) { requireNonNull(exporter, "exporter"); - return new SimpleSpanProcessor(exporter, /* sampled= */ true); + return builder(exporter).build(); + } + + /** + * Returns a new Builder for {@link SimpleSpanProcessor}. + * + * @since 1.34.0 + */ + public static SimpleSpanProcessorBuilder builder(SpanExporter exporter) { + requireNonNull(exporter, "exporter"); + return new SimpleSpanProcessorBuilder(exporter); } - SimpleSpanProcessor(SpanExporter spanExporter, boolean sampled) { + SimpleSpanProcessor( + SpanExporter spanExporter, + boolean exportUnsampledSpans, + Supplier meterProvider) { this.spanExporter = requireNonNull(spanExporter, "spanExporter"); - this.sampled = sampled; + this.exportUnsampledSpans = exportUnsampledSpans; + spanProcessorInstrumentation = + SpanProcessorInstrumentation.get( + InternalTelemetryVersion.LATEST, COMPONENT_ID, meterProvider); } @Override @@ -73,22 +99,34 @@ public boolean isStartRequired() { @Override public void onEnd(ReadableSpan span) { - if (sampled && !span.getSpanContext().isSampled()) { - return; - } - try { - List spans = Collections.singletonList(span.toSpanData()); - CompletableResultCode result = spanExporter.export(spans); - pendingExports.add(result); - result.whenComplete( - () -> { - pendingExports.remove(result); - if (!result.isSuccess()) { - logger.log(Level.FINE, "Exporter failed"); - } - }); - } catch (RuntimeException e) { - logger.log(Level.WARNING, "Exporter threw an Exception", e); + if (span != null && (exportUnsampledSpans || span.getSpanContext().isSampled())) { + if (isShutdown.get()) { + spanProcessorInstrumentation.dropSpansAlreadyShutdown(1); + return; + } + + try { + List spans = Collections.singletonList(span.toSpanData()); + CompletableResultCode result; + + synchronized (exporterLock) { + // We always increment for every export invocation, so we increment before the export + // call to make sure thrown errors don't affect it. + spanProcessorInstrumentation.finishSpans(1); + result = spanExporter.export(spans); + } + + pendingExports.add(result); + result.whenComplete(() -> { + pendingExports.remove(result); + if (!result.isSuccess()) { + logger.log(Level.FINE, "Exporter failed"); + } + }); + } catch (Throwable t) { + ThrowableUtil.propagateIfFatal(t); + logger.log(Level.WARNING, "Exporter threw an Exception", t); + } } } @@ -105,18 +143,16 @@ public CompletableResultCode shutdown() { CompletableResultCode result = new CompletableResultCode(); CompletableResultCode flushResult = forceFlush(); - flushResult.whenComplete( - () -> { - CompletableResultCode shutdownResult = spanExporter.shutdown(); - shutdownResult.whenComplete( - () -> { - if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { - result.fail(); - } else { - result.succeed(); - } - }); - }); + flushResult.whenComplete(() -> { + CompletableResultCode shutdownResult = spanExporter.shutdown(); + shutdownResult.whenComplete(() -> { + if (!flushResult.isSuccess() || !shutdownResult.isSuccess()) { + result.fail(); + } else { + result.succeed(); + } + }); + }); return result; } @@ -126,8 +162,22 @@ public CompletableResultCode forceFlush() { return CompletableResultCode.ofAll(pendingExports); } + /** + * Return the processor's configured {@link SpanExporter}. + * + * @since 1.37.0 + */ + public SpanExporter getSpanExporter() { + return spanExporter; + } + @Override public String toString() { - return "SimpleSpanProcessor{" + "spanExporter=" + spanExporter + '}'; + return "SimpleSpanProcessor{" + + "spanExporter=" + + spanExporter + + ", exportUnsampledSpans=" + + exportUnsampledSpans + + '}'; } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorBuilder.java new file mode 100644 index 00000000000..9bf5e0c4677 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorBuilder.java @@ -0,0 +1,59 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.export; + +import static java.util.Objects.requireNonNull; + +import io.opentelemetry.api.metrics.MeterProvider; +import java.util.function.Supplier; + +/** + * Builder class for {@link SimpleSpanProcessor}. + * + * @since 1.34.0 + */ +public final class SimpleSpanProcessorBuilder { + private final SpanExporter spanExporter; + private Supplier meterProvider = MeterProvider::noop; + private boolean exportUnsampledSpans = false; + + SimpleSpanProcessorBuilder(SpanExporter spanExporter) { + this.spanExporter = requireNonNull(spanExporter, "spanExporter"); + } + + /** + * Sets whether unsampled spans should be exported. If unset, defaults to exporting only sampled + * spans. + */ + public SimpleSpanProcessorBuilder setExportUnsampledSpans(boolean exportUnsampledSpans) { + this.exportUnsampledSpans = exportUnsampledSpans; + return this; + } + + /** + * Sets the {@link MeterProvider} to use to generate SDK Span + * Metrics. + * + * @since 1.58.0 + */ + public SimpleSpanProcessorBuilder setMeterProvider(Supplier meterProvider) { + requireNonNull(meterProvider, "meterProvider"); + this.meterProvider = meterProvider; + return this; + } + + // TODO: add `setInternalTelemetryVersion when we support more than one version + + /** + * Returns a new {@link SimpleSpanProcessor} with the configuration of this builder. + * + * @return a new {@link SimpleSpanProcessor}. + */ + public SimpleSpanProcessor build() { + return new SimpleSpanProcessor(spanExporter, exportUnsampledSpans, meterProvider); + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanExporter.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanExporter.java index 86fb4aa0fb8..1a1818bf6f2 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanExporter.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanExporter.java @@ -55,6 +55,15 @@ static SpanExporter composite(Iterable exporters) { return MultiSpanExporter.create(exportersList); } + /** + * Returns a {@link SpanExporter} that does nothing. All exported Spans are ignored. + * + * @since 1.63.0 + */ + static SpanExporter noop() { + return NoopSpanExporter.getInstance(); + } + /** * Called to export sampled {@code Span}s. Note that export operations can be performed * simultaneously depending on the type of span processor being used. However, the {@link diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanProcessorInstrumentation.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanProcessorInstrumentation.java new file mode 100644 index 00000000000..b2ed1ae9245 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/export/SpanProcessorInstrumentation.java @@ -0,0 +1,39 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.export; + +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.common.internal.ComponentId; +import java.util.function.Supplier; + +/** Metrics exported by span processors. */ +interface SpanProcessorInstrumentation { + + static SpanProcessorInstrumentation get( + InternalTelemetryVersion telemetryVersion, + ComponentId componentId, + Supplier meterProvider) { + switch (telemetryVersion) { + case LEGACY: + return new LegacySpanProcessorInstrumentation(meterProvider); + default: + return new SemConvSpanProcessorInstrumentation(componentId, meterProvider); + } + } + + /** Records metrics for spans dropped because a queue is full. */ + void dropSpansQueueFull(int count); + + /** Record metrics for spans dropped since processor is shutdown. */ + void dropSpansAlreadyShutdown(int count); + + /** Record metrics for spans processed successfully. */ + void finishSpans(int count); + + /** Registers metrics for processor queue capacity and size. */ + void buildQueueMetricsOnce(long capacity, LongCallable getSize); +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessor.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessor.java new file mode 100644 index 00000000000..5c608bf8275 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessor.java @@ -0,0 +1,41 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SpanProcessor; + +/** + * Extended {@link SpanProcessor} with experimental APIs. + * + *

      This class is internal and is hence not for public use. Its APIs are unstable and can change + * at any time. + */ +public interface ExtendedSpanProcessor extends SpanProcessor { + + /** + * Called when a {@link io.opentelemetry.api.trace.Span} is ended, but before {@link + * SpanProcessor#onEnd(ReadableSpan)} is invoked with an immutable variant of this span. This + * means that the span will still be mutable. Note that the span will only be modifiable + * synchronously from this callback, concurrent modifications from other threads will be + * prevented. Only called if {@link Span#isRecording()} returns true. + * + *

      This method is called synchronously on the execution thread, should not throw or block the + * execution thread. + * + * @param span the {@code Span} that is just about to be ended. + */ + void onEnding(ReadWriteSpan span); + + /** + * Returns {@code true} if this {@link SpanProcessor} requires onEnding events. + * + * @return {@code true} if this {@link SpanProcessor} requires onEnding events. + */ + boolean isOnEndingRequired(); +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/SdkTracerProviderUtil.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/SdkTracerProviderUtil.java new file mode 100644 index 00000000000..03f5a3dc0b1 --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/SdkTracerProviderUtil.java @@ -0,0 +1,141 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.function.BiPredicate; +import java.util.function.Predicate; +import javax.annotation.Nullable; + +/** + * A collection of methods that allow use of experimental features prior to availability in public + * APIs. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + */ +public final class SdkTracerProviderUtil { + + private SdkTracerProviderUtil() {} + + /** Reflectively set the {@link ScopeConfigurator} to the {@link SdkTracerProvider}. */ + public static void setTracerConfigurator( + SdkTracerProvider sdkTracerProvider, ScopeConfigurator scopeConfigurator) { + try { + Method method = + SdkTracerProvider.class.getDeclaredMethod( + "setTracerConfigurator", ScopeConfigurator.class); + method.setAccessible(true); + method.invoke(sdkTracerProvider, scopeConfigurator); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setTracerConfigurator on SdkTracerProvider", e); + } + } + + /** Reflectively set the {@link ScopeConfigurator} to the {@link SdkTracerProviderBuilder}. */ + public static void setTracerConfigurator( + SdkTracerProviderBuilder sdkTracerProviderBuilder, + ScopeConfigurator tracerConfigurator) { + try { + Method method = + SdkTracerProviderBuilder.class.getDeclaredMethod( + "setTracerConfigurator", ScopeConfigurator.class); + method.setAccessible(true); + method.invoke(sdkTracerProviderBuilder, tracerConfigurator); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setTracerConfigurator on SdkTracerProviderBuilder", e); + } + } + + /** Reflectively add a tracer configurator condition to the {@link SdkTracerProviderBuilder}. */ + public static void addTracerConfiguratorCondition( + SdkTracerProviderBuilder sdkTracerProviderBuilder, + Predicate scopeMatcher, + TracerConfig tracerConfig) { + try { + Method method = + SdkTracerProviderBuilder.class.getDeclaredMethod( + "addTracerConfiguratorCondition", Predicate.class, TracerConfig.class); + method.setAccessible(true); + method.invoke(sdkTracerProviderBuilder, scopeMatcher, tracerConfig); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling addTracerConfiguratorCondition on SdkTracerProviderBuilder", e); + } + } + + /** Reflectively set the {@link SdkResourceProvider} on the {@link SdkTracerProviderBuilder}. */ + public static void setSdkResourceProvider( + SdkTracerProviderBuilder sdkTracerProviderBuilder, SdkResourceProvider resourceProvider) { + try { + Method method = + SdkTracerProviderBuilder.class.getDeclaredMethod( + "setSdkResourceProvider", SdkResourceProvider.class); + method.setAccessible(true); + method.invoke(sdkTracerProviderBuilder, resourceProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setSdkResourceProvider on SdkTracerProviderBuilder", e); + } + } + + /** Reflectively get the {@link SdkResourceProvider} from the {@link SdkTracerProvider}. */ + public static SdkResourceProvider getSdkResourceProvider(SdkTracerProvider sdkTracerProvider) { + try { + Method method = SdkTracerProvider.class.getDeclaredMethod("getSdkResourceProvider"); + method.setAccessible(true); + return (SdkResourceProvider) method.invoke(sdkTracerProvider); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling getSdkResourceProvider on SdkTracerProvider", e); + } + } + + /** Reflectively set exception attribute resolver to the {@link SdkTracerProviderBuilder}. */ + public static void setExceptionAttributeResolver( + SdkTracerProviderBuilder sdkTracerProviderBuilder, + ExceptionAttributeResolver exceptionAttributeResolver) { + try { + Method method = + SdkTracerProviderBuilder.class.getDeclaredMethod( + "setExceptionAttributeResolver", ExceptionAttributeResolver.class); + method.setAccessible(true); + method.invoke(sdkTracerProviderBuilder, exceptionAttributeResolver); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setExceptionAttributeResolver on SdkTracerProviderBuilder", e); + } + } + + /** + * Reflectively set the context-scoped attributes filter on the {@link SdkTracerProviderBuilder}. + */ + public static void setContextScopedAttributesFilter( + SdkTracerProviderBuilder sdkTracerProviderBuilder, + @Nullable BiPredicate> filter) { + try { + Method method = + SdkTracerProviderBuilder.class.getDeclaredMethod( + "setContextScopedAttributesFilter", BiPredicate.class); + method.setAccessible(true); + method.invoke(sdkTracerProviderBuilder, filter); + } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { + throw new IllegalStateException( + "Error calling setContextScopedAttributesFilter on SdkTracerProviderBuilder", e); + } + } +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/TracerConfig.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/TracerConfig.java new file mode 100644 index 00000000000..4d88a034f5d --- /dev/null +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/TracerConfig.java @@ -0,0 +1,67 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import com.google.auto.value.AutoValue; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder; +import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder; +import java.util.function.Predicate; +import javax.annotation.concurrent.Immutable; + +/** + * A collection of configuration options which define the behavior of a {@link Tracer}. + * + *

      This class is internal and experimental. Its APIs are unstable and can change at any time. Its + * APIs (or a version of them) may be promoted to the public stable API in the future, but no + * guarantees are made. + * + * @see SdkTracerProviderUtil#setTracerConfigurator(SdkTracerProviderBuilder, ScopeConfigurator) + * @see SdkTracerProviderUtil#addTracerConfiguratorCondition(SdkTracerProviderBuilder, Predicate, + * TracerConfig) + */ +@AutoValue +@Immutable +public abstract class TracerConfig { + + private static final TracerConfig DEFAULT_CONFIG = + new AutoValue_TracerConfig(/* enabled= */ true); + private static final TracerConfig DISABLED_CONFIG = + new AutoValue_TracerConfig(/* enabled= */ false); + + /** Returns a disabled {@link TracerConfig}. */ + public static TracerConfig disabled() { + return DISABLED_CONFIG; + } + + /** Returns an enabled {@link TracerConfig}. */ + public static TracerConfig enabled() { + return DEFAULT_CONFIG; + } + + /** + * Returns the default {@link TracerConfig}, which is used when no configurator is set or when the + * tracer configurator returns {@code null} for a {@link InstrumentationScopeInfo}. + */ + public static TracerConfig defaultConfig() { + return DEFAULT_CONFIG; + } + + /** + * Create a {@link ScopeConfiguratorBuilder} for configuring {@link + * SdkTracerProviderUtil#setTracerConfigurator(SdkTracerProviderBuilder, ScopeConfigurator)}. + */ + public static ScopeConfiguratorBuilder configuratorBuilder() { + return ScopeConfigurator.builder(); + } + + TracerConfig() {} + + /** Returns {@code true} if this tracer is enabled. Defaults to {@code true}. */ + public abstract boolean isEnabled(); +} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/ExceptionEventData.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/ExceptionEventData.java deleted file mode 100644 index 7e41c5a6b66..00000000000 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/ExceptionEventData.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace.internal.data; - -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.sdk.trace.SpanLimits; -import io.opentelemetry.sdk.trace.data.EventData; - -/** - * Data representation of an event for a recorded exception. - * - *

      This class is internal and is hence not for public use. Its APIs are unstable and can change - * at any time. - */ -public interface ExceptionEventData extends EventData { - - /** - * Returns a new immutable {@link ExceptionEventData}. - * - * @param spanLimits limits applied to {@link ExceptionEventData}. - * @param epochNanos epoch timestamp in nanos of the {@link ExceptionEventData}. - * @param exception the {@link Throwable exception} of the {@code Event}. - * @param additionalAttributes the additional attributes of the {@link ExceptionEventData}. - * @return a new immutable {@link ExceptionEventData} - */ - static ExceptionEventData create( - SpanLimits spanLimits, - long epochNanos, - Throwable exception, - Attributes additionalAttributes) { - return ImmutableExceptionEventData.create( - spanLimits, epochNanos, exception, additionalAttributes); - } - - /** - * Return the {@link Throwable exception} of the {@link ExceptionEventData}. - * - * @return the {@link Throwable exception} of the {@link ExceptionEventData} - */ - Throwable getException(); - - /** - * Return the additional {@link Attributes attributes} of the {@link ExceptionEventData}. - * - * @return the additional {@link Attributes attributes} of the {@link ExceptionEventData} - */ - Attributes getAdditionalAttributes(); -} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/ImmutableExceptionEventData.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/ImmutableExceptionEventData.java deleted file mode 100644 index b36b757a486..00000000000 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/ImmutableExceptionEventData.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace.internal.data; - -import com.google.auto.value.AutoValue; -import com.google.auto.value.extension.memoized.Memoized; -import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.common.AttributesBuilder; -import io.opentelemetry.sdk.internal.AttributeUtil; -import io.opentelemetry.sdk.trace.SpanLimits; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; -import java.io.PrintWriter; -import java.io.StringWriter; -import javax.annotation.concurrent.Immutable; - -/** An effectively immutable implementation of {@link ExceptionEventData}. */ -@AutoValue -@Immutable -abstract class ImmutableExceptionEventData implements ExceptionEventData { - - /** - * Returns a new immutable {@code Event}. - * - * @param spanLimits limits applied to {@code Event}. - * @param epochNanos epoch timestamp in nanos of the {@code Event}. - * @param exception the {@link Throwable exception} of the {@code Event}. - * @param additionalAttributes the additional {@link Attributes} of the {@code Event}. - * @return a new immutable {@code Event} - */ - static ExceptionEventData create( - SpanLimits spanLimits, - long epochNanos, - Throwable exception, - Attributes additionalAttributes) { - - return new AutoValue_ImmutableExceptionEventData( - epochNanos, exception, additionalAttributes, spanLimits); - } - - ImmutableExceptionEventData() {} - - protected abstract SpanLimits getSpanLimits(); - - @Override - public final String getName() { - return SemanticAttributes.EXCEPTION_EVENT_NAME; - } - - @Override - @Memoized - public Attributes getAttributes() { - Throwable exception = getException(); - Attributes additionalAttributes = getAdditionalAttributes(); - AttributesBuilder attributesBuilder = Attributes.builder(); - - attributesBuilder.put( - SemanticAttributes.EXCEPTION_TYPE, exception.getClass().getCanonicalName()); - String message = exception.getMessage(); - if (message != null) { - attributesBuilder.put(SemanticAttributes.EXCEPTION_MESSAGE, message); - } - - StringWriter stringWriter = new StringWriter(); - try (PrintWriter printWriter = new PrintWriter(stringWriter)) { - exception.printStackTrace(printWriter); - } - attributesBuilder.put(SemanticAttributes.EXCEPTION_STACKTRACE, stringWriter.toString()); - attributesBuilder.putAll(additionalAttributes); - - SpanLimits spanLimits = getSpanLimits(); - return AttributeUtil.applyAttributesLimit( - attributesBuilder.build(), - spanLimits.getMaxNumberOfAttributesPerEvent(), - spanLimits.getMaxAttributeValueLength()); - } - - @Override - public final int getTotalAttributeCount() { - return getAttributes().size(); - } -} diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/package-info.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/package-info.java deleted file mode 100644 index bab18f74550..00000000000 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/internal/data/package-info.java +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * Interfaces and implementations that are internal to OpenTelemetry. - * - *

      All the content under this package and its subpackages are considered not part of the public - * API, and must not be used by users of the OpenTelemetry library. - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.sdk.trace.internal.data; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilder.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilder.java index 24cb7ea4860..4944ff5e0a9 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilder.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilder.java @@ -5,11 +5,14 @@ package io.opentelemetry.sdk.trace.samplers; +import java.util.logging.Logger; import javax.annotation.Nullable; /** A builder for creating ParentBased sampler instances. */ public final class ParentBasedSamplerBuilder { + private static final Logger logger = Logger.getLogger(ParentBasedSamplerBuilder.class.getName()); + private final Sampler root; @Nullable private Sampler remoteParentSampled; @Nullable private Sampler remoteParentNotSampled; @@ -17,6 +20,8 @@ public final class ParentBasedSamplerBuilder { @Nullable private Sampler localParentNotSampled; ParentBasedSamplerBuilder(Sampler root) { + // This is the only valid traceIdSampler location according to Spec + // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/sdk.md#compatibility-warnings-for-traceidratiobased-sampler this.root = root; } @@ -27,6 +32,7 @@ public final class ParentBasedSamplerBuilder { * @return this Builder */ public ParentBasedSamplerBuilder setRemoteParentSampled(Sampler remoteParentSampled) { + maybeLogTraceIdSamplerWarning(remoteParentSampled, "remoteParentSampled"); this.remoteParentSampled = remoteParentSampled; return this; } @@ -38,6 +44,7 @@ public ParentBasedSamplerBuilder setRemoteParentSampled(Sampler remoteParentSamp * @return this Builder */ public ParentBasedSamplerBuilder setRemoteParentNotSampled(Sampler remoteParentNotSampled) { + maybeLogTraceIdSamplerWarning(remoteParentNotSampled, "remoteParentNotSampled"); this.remoteParentNotSampled = remoteParentNotSampled; return this; } @@ -49,6 +56,7 @@ public ParentBasedSamplerBuilder setRemoteParentNotSampled(Sampler remoteParentN * @return this Builder */ public ParentBasedSamplerBuilder setLocalParentSampled(Sampler localParentSampled) { + maybeLogTraceIdSamplerWarning(localParentSampled, "localParentSampled"); this.localParentSampled = localParentSampled; return this; } @@ -60,10 +68,22 @@ public ParentBasedSamplerBuilder setLocalParentSampled(Sampler localParentSample * @return this Builder */ public ParentBasedSamplerBuilder setLocalParentNotSampled(Sampler localParentNotSampled) { + maybeLogTraceIdSamplerWarning(localParentNotSampled, "localParentNotSampled"); this.localParentNotSampled = localParentNotSampled; return this; } + private static void maybeLogTraceIdSamplerWarning(Sampler sampler, String field) { + if (sampler instanceof TraceIdRatioBasedSampler) { + logger.warning( + "TraceIdRatioBasedSampler is being used as a child sampler (" + + field + + "). " + + "This configuration is discouraged per the OpenTelemetry specification " + + "and may lead to unexpected sampling behavior."); + } + } + /** * Builds the {@link ParentBasedSampler}. * diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/Sampler.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/Sampler.java index 73edba3b6f1..3f67b495b22 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/Sampler.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/Sampler.java @@ -11,13 +11,16 @@ import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.data.LinkData; +import java.io.Closeable; import java.util.List; +import java.util.concurrent.TimeUnit; import javax.annotation.concurrent.ThreadSafe; /** A Sampler is used to make decisions on {@link Span} sampling. */ @ThreadSafe -public interface Sampler { +public interface Sampler extends Closeable { /** * Returns a {@link Sampler} that always makes a "yes" {@link SamplingResult} for {@link Span} @@ -119,4 +122,21 @@ SamplingResult shouldSample( * @return the description of this {@code Sampler}. */ String getDescription(); + + /** + * Shuts down the sampler, releasing any resources held by it. + * + *

      This method is called when the {@code SdkTracerProvider} is shut down. + * + * @return a {@link CompletableResultCode} which is completed when shutdown is finished. + * @since 1.65.0 + */ + default CompletableResultCode shutdown() { + return CompletableResultCode.ofSuccess(); + } + + @Override + default void close() { + shutdown().join(10, TimeUnit.SECONDS); + } } diff --git a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSampler.java b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSampler.java index b84dd374f39..19f38c5f5eb 100644 --- a/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSampler.java +++ b/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSampler.java @@ -6,11 +6,14 @@ package io.opentelemetry.sdk.trace.samplers; import io.opentelemetry.api.common.Attributes; -import io.opentelemetry.api.internal.OtelEncodingUtils; +import io.opentelemetry.api.impl.Base16EncodingUtils; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.trace.data.LinkData; +import java.text.DecimalFormat; +import java.text.DecimalFormatSymbols; import java.util.List; +import java.util.Locale; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; @@ -52,7 +55,7 @@ static TraceIdRatioBasedSampler create(double ratio) { TraceIdRatioBasedSampler(double ratio, long idUpperBound) { this.idUpperBound = idUpperBound; - description = String.format("TraceIdRatioBased{%.6f}", ratio); + description = "TraceIdRatioBased{" + decimalFormat(ratio) + "}"; } @Override @@ -106,6 +109,14 @@ long getIdUpperBound() { } private static long getTraceIdRandomPart(String traceId) { - return OtelEncodingUtils.longFromBase16String(traceId, 16); + return Base16EncodingUtils.longFromBase16String(traceId, 16); + } + + private static String decimalFormat(double value) { + DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance(Locale.ROOT); + decimalFormatSymbols.setDecimalSeparator('.'); + + DecimalFormat decimalFormat = new DecimalFormat("0.000000", decimalFormatSymbols); + return decimalFormat.format(value); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/AttributesMapTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/AttributesMapTest.java deleted file mode 100644 index 7cc4e3f2697..00000000000 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/AttributesMapTest.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.sdk.trace; - -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.entry; - -import org.junit.jupiter.api.Test; - -class AttributesMapTest { - - @Test - void asMap() { - AttributesMap attributesMap = new AttributesMap(2, Integer.MAX_VALUE); - attributesMap.put(longKey("one"), 1L); - attributesMap.put(longKey("two"), 2L); - - assertThat(attributesMap.asMap()) - .containsOnly(entry(longKey("one"), 1L), entry(longKey("two"), 2L)); - } -} diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/MultiSpanProcessorTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/MultiSpanProcessorTest.java index c51fe61c954..34ac6e1c03d 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/MultiSpanProcessorTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/MultiSpanProcessorTest.java @@ -14,6 +14,7 @@ import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.internal.ExtendedSpanProcessor; import java.util.Arrays; import java.util.Collections; import org.junit.jupiter.api.BeforeEach; @@ -27,18 +28,20 @@ @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) class MultiSpanProcessorTest { - @Mock private SpanProcessor spanProcessor1; - @Mock private SpanProcessor spanProcessor2; + @Mock private ExtendedSpanProcessor spanProcessor1; + @Mock private ExtendedSpanProcessor spanProcessor2; @Mock private ReadableSpan readableSpan; @Mock private ReadWriteSpan readWriteSpan; @BeforeEach void setUp() { when(spanProcessor1.isStartRequired()).thenReturn(true); + when(spanProcessor1.isOnEndingRequired()).thenReturn(true); when(spanProcessor1.isEndRequired()).thenReturn(true); when(spanProcessor1.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); when(spanProcessor1.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); when(spanProcessor2.isStartRequired()).thenReturn(true); + when(spanProcessor2.isOnEndingRequired()).thenReturn(true); when(spanProcessor2.isEndRequired()).thenReturn(true); when(spanProcessor2.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); when(spanProcessor2.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); @@ -61,12 +64,17 @@ void oneSpanProcessor() { @Test void twoSpanProcessor() { - SpanProcessor multiSpanProcessor = - SpanProcessor.composite(Arrays.asList(spanProcessor1, spanProcessor2)); + ExtendedSpanProcessor multiSpanProcessor = + (ExtendedSpanProcessor) + SpanProcessor.composite(Arrays.asList(spanProcessor1, spanProcessor2)); multiSpanProcessor.onStart(Context.root(), readWriteSpan); verify(spanProcessor1).onStart(same(Context.root()), same(readWriteSpan)); verify(spanProcessor2).onStart(same(Context.root()), same(readWriteSpan)); + multiSpanProcessor.onEnding(readWriteSpan); + verify(spanProcessor1).onEnding(same(readWriteSpan)); + verify(spanProcessor2).onEnding(same(readWriteSpan)); + multiSpanProcessor.onEnd(readableSpan); verify(spanProcessor1).onEnd(same(readableSpan)); verify(spanProcessor2).onEnd(same(readableSpan)); @@ -83,9 +91,11 @@ void twoSpanProcessor() { @Test void twoSpanProcessor_DifferentRequirements() { when(spanProcessor1.isEndRequired()).thenReturn(false); + when(spanProcessor2.isOnEndingRequired()).thenReturn(false); when(spanProcessor2.isStartRequired()).thenReturn(false); - SpanProcessor multiSpanProcessor = - SpanProcessor.composite(Arrays.asList(spanProcessor1, spanProcessor2)); + ExtendedSpanProcessor multiSpanProcessor = + (ExtendedSpanProcessor) + SpanProcessor.composite(Arrays.asList(spanProcessor1, spanProcessor2)); assertThat(multiSpanProcessor.isStartRequired()).isTrue(); assertThat(multiSpanProcessor.isEndRequired()).isTrue(); @@ -94,6 +104,10 @@ void twoSpanProcessor_DifferentRequirements() { verify(spanProcessor1).onStart(same(Context.root()), same(readWriteSpan)); verify(spanProcessor2, times(0)).onStart(any(Context.class), any(ReadWriteSpan.class)); + multiSpanProcessor.onEnding(readWriteSpan); + verify(spanProcessor1).onEnding(same(readWriteSpan)); + verify(spanProcessor2, times(0)).onEnding(any(ReadWriteSpan.class)); + multiSpanProcessor.onEnd(readableSpan); verify(spanProcessor1, times(0)).onEnd(any(ReadableSpan.class)); verify(spanProcessor2).onEnd(same(readableSpan)); @@ -117,6 +131,7 @@ void stringRepresentation() { .hasToString( "MultiSpanProcessor{" + "spanProcessorsStart=[spanProcessor1, spanProcessor1], " + + "spanProcessorsEnding=[spanProcessor1, spanProcessor1], " + "spanProcessorsEnd=[spanProcessor1, spanProcessor1], " + "spanProcessorsAll=[spanProcessor1, spanProcessor1]}"); } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanBuilderTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanBuilderTest.java index 56aa58cfe34..283c80d69a4 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanBuilderTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanBuilderTest.java @@ -13,13 +13,16 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; import static java.util.stream.Collectors.joining; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanBuilder; import io.opentelemetry.api.trace.SpanContext; @@ -27,10 +30,14 @@ import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.context.Context; +import io.opentelemetry.context.ContextKey; import io.opentelemetry.context.Scope; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.samplers.Sampler; @@ -41,10 +48,15 @@ import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; @@ -87,7 +99,10 @@ void addLink() { SdkSpan span = (SdkSpan) spanBuilder.startSpan(); try { - assertThat(span.toSpanData().getLinks()).hasSize(2); + assertThat(span.toSpanData().getLinks()) + .containsExactly( + LinkData.create(sampledSpanContext), LinkData.create(sampledSpanContext)); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(2); } finally { span.end(); } @@ -108,11 +123,128 @@ void addLink_invalid() { } } + @ParameterizedTest + @MethodSource("invalidLinkArguments") + void addLink_invalidWithMetadata( + boolean hasTraceState, @Nullable Attributes attributes, boolean recorded) { + SpanContext context = + SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.builder().setSampled(true).setRandomTraceId(true).build(), + hasTraceState + ? TraceState.builder().put("vendor", "value").build() + : TraceState.getDefault()); + + SdkSpan span = (SdkSpan) sdkTracer.spanBuilder(SPAN_NAME).addLink(context).startSpan(); + span.end(); + assertThat(span.toSpanData().getLinks()) + .containsExactlyElementsOf( + hasTraceState ? singletonList(LinkData.create(context)) : emptyList()); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(hasTraceState ? 1 : 0); + + span = (SdkSpan) sdkTracer.spanBuilder(SPAN_NAME).addLink(context, attributes).startSpan(); + span.end(); + assertThat(span.toSpanData().getLinks()) + .containsExactlyElementsOf( + recorded + ? singletonList( + LinkData.create(context, attributes == null ? Attributes.empty() : attributes)) + : emptyList()); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(recorded ? 1 : 0); + } + + private static Stream invalidLinkArguments() { + Attributes attributes = Attributes.of(stringKey("message.id"), "123"); + return Stream.of( + Arguments.argumentSet("attributes", false, attributes, true), + Arguments.argumentSet("trace state", true, Attributes.empty(), true), + Arguments.argumentSet("attributes and trace state", true, attributes, true), + Arguments.argumentSet("flags only", false, Attributes.empty(), false), + Arguments.argumentSet("null attributes", false, null, false), + Arguments.argumentSet("trace state and null attributes", true, null, true)); + } + + @ParameterizedTest + @MethodSource("linkLimits") + void addLink_invalidWithMetadataLimitsAndSampling(int maxLinks, int maxAttributes) { + Sampler sampler = Mockito.spy(Sampler.alwaysOn()); + Mockito.when(mockedSpanProcessor.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + try (SdkTracerProvider provider = + SdkTracerProvider.builder() + .setSampler(sampler) + .addSpanProcessor(mockedSpanProcessor) + .setSpanLimits( + SpanLimits.builder() + .setMaxNumberOfLinks(maxLinks) + .setMaxNumberOfAttributesPerLink(maxAttributes) + .setMaxAttributeValueLength(3) + .build()) + .build()) { + SpanContext invalid = SpanContext.getInvalid(); + SpanContext withTraceState = + SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.getDefault(), + TraceState.builder().put("vendor", "value").build()); + Attributes attributes = Attributes.of(stringKey("key0"), "value", stringKey("key1"), "other"); + SdkSpan span = + (SdkSpan) + provider + .get("test") + .spanBuilder(SPAN_NAME) + .addLink(null, attributes) + .addLink(invalid) + .addLink(invalid, attributes) + .addLink(sampledSpanContext) + .addLink(withTraceState) + .addLink(withTraceState, attributes) + .startSpan(); + span.end(); + SpanData spanData = span.toSpanData(); + assertThat(spanData.getLinks()) + .containsExactlyElementsOf( + maxLinks == 0 + ? emptyList() + : Arrays.asList( + LinkData.create( + invalid, + maxAttributes == 0 + ? Attributes.empty() + : Attributes.of(stringKey("key0"), "val"), + 2), + LinkData.create(sampledSpanContext), + LinkData.create(withTraceState))); + assertThat(spanData.getTotalRecordedLinks()).isEqualTo(4); + Mockito.verify(sampler) + .shouldSample( + ArgumentMatchers.any(), + ArgumentMatchers.anyString(), + ArgumentMatchers.eq(SPAN_NAME), + ArgumentMatchers.eq(SpanKind.INTERNAL), + ArgumentMatchers.eq(Attributes.empty()), + ArgumentMatchers.eq(spanData.getLinks())); + } + } + + private static Stream linkLimits() { + return Stream.of( + Arguments.argumentSet("zero links and attributes", 0, 0), + Arguments.argumentSet("zero links", 0, 1), + Arguments.argumentSet("zero attributes", 3, 0), + Arguments.argumentSet("limited links and attributes", 3, 1)); + } + @Test void truncateLink() { int maxNumberOfLinks = 8; SpanLimits spanLimits = SpanLimits.builder().setMaxNumberOfLinks(maxNumberOfLinks).build(); - TracerProvider tracerProvider = SdkTracerProvider.builder().setSpanLimits(spanLimits).build(); + TracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(mockedSpanProcessor) + .setSpanLimits(spanLimits) + .build(); // Verify methods do not crash. SpanBuilder spanBuilder = tracerProvider.get("test").spanBuilder(SPAN_NAME); for (int i = 0; i < 2 * maxNumberOfLinks; i++) { @@ -135,7 +267,11 @@ void truncateLink() { @Test void truncateLinkAttributes() { SpanLimits spanLimits = SpanLimits.builder().setMaxNumberOfAttributesPerLink(1).build(); - TracerProvider tracerProvider = SdkTracerProvider.builder().setSpanLimits(spanLimits).build(); + TracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(mockedSpanProcessor) + .setSpanLimits(spanLimits) + .build(); // Verify methods do not crash. SpanBuilder spanBuilder = tracerProvider.get("test").spanBuilder(SPAN_NAME); Attributes attributes = @@ -160,6 +296,7 @@ void linkAttributeLength() { TracerProvider tracerProvider = SdkTracerProvider.builder() .setSpanLimits(SpanLimits.builder().setMaxAttributeValueLength(maxLength).build()) + .addSpanProcessor(mockedSpanProcessor) .build(); SpanBuilder spanBuilder = tracerProvider.get("test").spanBuilder(SPAN_NAME); String strVal = IntStream.range(0, maxLength).mapToObj(i -> "a").collect(joining()); @@ -233,8 +370,11 @@ void addLinkSpanContextAttributes_nullContext() { @Test void addLinkSpanContextAttributes_nullAttributes() { - assertThatCode(() -> sdkTracer.spanBuilder(SPAN_NAME).addLink(sampledSpanContext, null)) - .doesNotThrowAnyException(); + SdkSpan span = + (SdkSpan) sdkTracer.spanBuilder(SPAN_NAME).addLink(sampledSpanContext, null).startSpan(); + span.end(); + assertThat(span.toSpanData().getLinks()).containsExactly(LinkData.create(sampledSpanContext)); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(1); } @Test @@ -246,19 +386,21 @@ void setAttribute() { .setAttribute("long", 12345L) .setAttribute("double", .12345) .setAttribute("boolean", true) - .setAttribute(stringKey("stringAttribute"), "attrvalue"); + .setAttribute(stringKey("stringAttribute"), "attrvalue") + .setAttribute(longKey("longAttribute"), 123); SdkSpan span = (SdkSpan) spanBuilder.startSpan(); try { SpanData spanData = span.toSpanData(); Attributes attrs = spanData.getAttributes(); - assertThat(attrs.size()).isEqualTo(5); + assertThat(attrs.size()).isEqualTo(6); assertThat(attrs.get(stringKey("string"))).isEqualTo("value"); assertThat(attrs.get(longKey("long"))).isEqualTo(12345L); assertThat(attrs.get(doubleKey("double"))).isEqualTo(0.12345); assertThat(attrs.get(booleanKey("boolean"))).isEqualTo(true); assertThat(attrs.get(stringKey("stringAttribute"))).isEqualTo("attrvalue"); - assertThat(spanData.getTotalAttributeCount()).isEqualTo(5); + assertThat(attrs.get(longKey("longAttribute"))).isEqualTo(123); + assertThat(spanData.getTotalAttributeCount()).isEqualTo(6); } finally { span.end(); } @@ -365,8 +507,10 @@ void setAttribute_nullAttributeValue() { spanBuilder.setAttribute(booleanArrayKey("boolArrayAttribute"), Arrays.asList(true, null)); spanBuilder.setAttribute(longArrayKey("longArrayAttribute"), Arrays.asList(12345L, null)); spanBuilder.setAttribute(doubleArrayKey("doubleArrayAttribute"), Arrays.asList(1.2345, null)); + spanBuilder.setAttribute(valueKey("emptyValue"), Value.empty()); + spanBuilder.setAttribute(valueKey("nullValue"), null); SdkSpan span = (SdkSpan) spanBuilder.startSpan(); - assertThat(span.toSpanData().getAttributes().size()).isEqualTo(9); + assertThat(span.toSpanData().getAttributes().size()).isEqualTo(10); } @Test @@ -381,10 +525,11 @@ void setAttribute_nullAttributeValue_afterEnd() { spanBuilder.setAttribute(booleanArrayKey("boolArrayAttribute"), Arrays.asList(true, null)); spanBuilder.setAttribute(longArrayKey("longArrayAttribute"), Arrays.asList(12345L, null)); spanBuilder.setAttribute(doubleArrayKey("doubleArrayAttribute"), Arrays.asList(1.2345, null)); + spanBuilder.setAttribute(valueKey("emptyValue"), Value.empty()); SdkSpan span = (SdkSpan) spanBuilder.startSpan(); - assertThat(span.toSpanData().getAttributes().size()).isEqualTo(9); + assertThat(span.toSpanData().getAttributes().size()).isEqualTo(10); span.end(); - span.setAttribute("emptyString", null); + span.setAttribute("emptyString", (String) null); span.setAttribute(stringKey("emptyStringAttributeValue"), null); span.setAttribute(longKey("longAttribute"), null); span.setAttribute(booleanKey("boolAttribute"), null); @@ -393,14 +538,19 @@ void setAttribute_nullAttributeValue_afterEnd() { span.setAttribute(booleanArrayKey("boolArrayAttribute"), null); span.setAttribute(longArrayKey("longArrayAttribute"), null); span.setAttribute(doubleArrayKey("doubleArrayAttribute"), null); - assertThat(span.toSpanData().getAttributes().size()).isEqualTo(9); + span.setAttribute(valueKey("emptyValue"), null); + assertThat(span.toSpanData().getAttributes().size()).isEqualTo(10); } @Test void droppingAttributes() { int maxNumberOfAttrs = 8; SpanLimits spanLimits = SpanLimits.builder().setMaxNumberOfAttributes(maxNumberOfAttrs).build(); - TracerProvider tracerProvider = SdkTracerProvider.builder().setSpanLimits(spanLimits).build(); + TracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(mockedSpanProcessor) + .setSpanLimits(spanLimits) + .build(); // Verify methods do not crash. SpanBuilder spanBuilder = tracerProvider.get("test").spanBuilder(SPAN_NAME); for (int i = 0; i < 2 * maxNumberOfAttrs; i++) { @@ -441,7 +591,11 @@ public String getDescription() { return "test"; } }; - TracerProvider tracerProvider = SdkTracerProvider.builder().setSampler(sampler).build(); + TracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(mockedSpanProcessor) + .setSampler(sampler) + .build(); // Verify methods do not crash. SpanBuilder spanBuilder = tracerProvider.get("test").spanBuilder(SPAN_NAME); SdkSpan span = (SdkSpan) spanBuilder.startSpan(); @@ -509,7 +663,7 @@ void setAllAttributes_mergesAttributes() { assertThat(attrs.get(doubleKey("double"))).isEqualTo(0.12345); assertThat(attrs.get(booleanKey("boolean"))).isEqualTo(true); assertThat(attrs.get(stringKey("stringAttribute"))).isEqualTo("attrvalue"); - assertThat(spanData.getTotalAttributeCount()).isEqualTo(8); + assertThat(spanData.getTotalAttributeCount()).isEqualTo(6); } finally { span.end(); } @@ -683,6 +837,7 @@ public String getDescription() { return "test sampler"; } }) + .addSpanProcessor(mockedSpanProcessor) .build() .get("test") .spanBuilder(SPAN_NAME) @@ -900,6 +1055,124 @@ void parent_invalidContext() { } } + @Test + void propagateRandomTraceIdFlag() { + Span parent = sdkTracer.spanBuilder(SPAN_NAME).startSpan(); + assertThat(parent.getSpanContext().getTraceFlags().isTraceIdRandom()).isTrue(); + try (Scope ignored = parent.makeCurrent()) { + Span span = (SdkSpan) sdkTracer.spanBuilder(SPAN_NAME).startSpan(); + assertThat(span.getSpanContext().getTraceId()) + .isEqualTo(parent.getSpanContext().getTraceId()); + assertThat(span.getSpanContext().getTraceFlags().isTraceIdRandom()).isTrue(); + try (Scope spanScope = span.makeCurrent()) { + // Nested span + Span nestedSpan = sdkTracer.spanBuilder(SPAN_NAME).startSpan(); + // check that still the same trace + assertThat(nestedSpan.getSpanContext().getTraceId()) + .isEqualTo(parent.getSpanContext().getTraceId()); + // check if RandomTraceIdFlag is still there + assertThat(nestedSpan.getSpanContext().getTraceFlags().isTraceIdRandom()).isTrue(); + try (Scope nestedScope = span.makeCurrent()) { + Context nestedContext = Context.current(); + Span currentSpan = Span.fromContext(nestedContext); + assertThat(currentSpan.getSpanContext().getTraceFlags().isTraceIdRandom()).isTrue(); + } finally { + nestedSpan.end(); + } + } finally { + span.end(); + } + } finally { + parent.end(); + } + } + + @Test + void samplerReceivesPropagatorContextWithRandomTraceId() { + Sampler mockSampler = Mockito.mock(Sampler.class); + Mockito.when( + mockSampler.shouldSample( + ArgumentMatchers.any(), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.any(), + ArgumentMatchers.any(), + ArgumentMatchers.anyList())) + .thenReturn(SamplingResult.recordAndSample()); + + SdkTracerProvider provider = + SdkTracerProvider.builder() + .addSpanProcessor(mockedSpanProcessor) + .setSampler(mockSampler) + .build(); + ContextKey propagatorKey = ContextKey.named("propagator-test-key"); + Context parentWithPropagatorData = Context.root().with(propagatorKey, "test-value"); + + Span span = + provider.get("test").spanBuilder(SPAN_NAME).setParent(parentWithPropagatorData).startSpan(); + span.end(); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(Context.class); + Mockito.verify(mockSampler) + .shouldSample( + contextCaptor.capture(), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.any(), + ArgumentMatchers.any(), + ArgumentMatchers.anyList()); + + Context samplerContext = contextCaptor.getValue(); + assertThat(samplerContext.get(propagatorKey)).isEqualTo("test-value"); + assertThat(Span.fromContext(samplerContext).getSpanContext().getTraceFlags().isTraceIdRandom()) + .isTrue(); + } + + @Test + void samplerReceivesRootContextWithRandomTraceIdWhenNoExtraContext() { + Sampler mockSampler = Mockito.mock(Sampler.class); + Mockito.when( + mockSampler.shouldSample( + ArgumentMatchers.any(), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.any(), + ArgumentMatchers.any(), + ArgumentMatchers.anyList())) + .thenReturn(SamplingResult.recordAndSample()); + + SdkTracerProvider provider = + SdkTracerProvider.builder() + .addSpanProcessor(mockedSpanProcessor) + .setSampler(mockSampler) + .build(); + + // setNoParent() explicitly sets parentContext to Context.root(), exercising the singleton path. + // Start two spans and assert the sampler received the exact same Context instance both times, + // proving the pre-built singleton is reused rather than a new object allocated each call. + provider.get("test").spanBuilder(SPAN_NAME).setNoParent().startSpan().end(); + provider.get("test").spanBuilder(SPAN_NAME).setNoParent().startSpan().end(); + + ArgumentCaptor contextCaptor = ArgumentCaptor.forClass(Context.class); + Mockito.verify(mockSampler, Mockito.times(2)) + .shouldSample( + contextCaptor.capture(), + ArgumentMatchers.anyString(), + ArgumentMatchers.anyString(), + ArgumentMatchers.any(), + ArgumentMatchers.any(), + ArgumentMatchers.anyList()); + + List samplerContexts = contextCaptor.getAllValues(); + assertThat(samplerContexts.get(0)).isSameAs(samplerContexts.get(1)); + assertThat( + Span.fromContext(samplerContexts.get(0)) + .getSpanContext() + .getTraceFlags() + .isTraceIdRandom()) + .isTrue(); + } + @Test void startTimestamp_numeric() { SdkSpan span = @@ -981,7 +1254,7 @@ void spanDataToString() { "SpanData\\{spanContext=ImmutableSpanContext\\{" + "traceId=[0-9a-f]{32}, " + "spanId=[0-9a-f]{16}, " - + "traceFlags=01, " + + "traceFlags=03, " + "traceState=ArrayBasedTraceState\\{entries=\\[]}, remote=false, valid=true}, " + "parentSpanContext=ImmutableSpanContext\\{" + "traceId=00000000000000000000000000000000, " @@ -989,11 +1262,12 @@ void spanDataToString() { + "traceFlags=00, " + "traceState=ArrayBasedTraceState\\{entries=\\[]}, remote=false, valid=false}, " + "resource=Resource\\{schemaUrl=null, " + + "entities=\\[\\], " + "attributes=\\{service.name=\"unknown_service:java\", " + "telemetry.sdk.language=\"java\", telemetry.sdk.name=\"opentelemetry\", " - + "telemetry.sdk.version=\"\\d+.\\d+.\\d+(-rc.\\d+)?(-SNAPSHOT)?\"}}, " + + "telemetry.sdk.version=\"\\d+.\\d+.\\d+(-rc.\\d+)?(-SNAPSHOT)?\"\\}\\}, " + "instrumentationScopeInfo=InstrumentationScopeInfo\\{" - + "name=SpanBuilderSdkTest, version=null, schemaUrl=null}, " + + "name=SpanBuilderSdkTest, version=null, schemaUrl=null, attributes=\\{}}, " + "name=span_name, " + "kind=INTERNAL, " + "startEpochNanos=[0-9]+, " @@ -1009,6 +1283,7 @@ void spanDataToString() { } @Test + @SuppressLogger(loggerName = "io.opentelemetry.usage") void doNotCrash() { assertThatCode( () -> { @@ -1050,4 +1325,25 @@ void doNotCrash() { }) .doesNotThrowAnyException(); } + + @Test + void setAttribute_sameKeyDifferentType_lastValueWins() { + // Regression test for https://github.com/open-telemetry/opentelemetry-java/issues/7897 + // Setting the same string key with different types must overwrite, not accumulate. + SdkSpan span = + (SdkSpan) + sdkTracer + .spanBuilder("test") + .setAttribute("key", "string_value") + .setAttribute("key", false) + .startSpan(); + try { + Attributes attributes = span.toSpanData().getAttributes(); + assertThat(attributes.size()).isEqualTo(1); + assertThat(attributes.get(booleanKey("key"))).isEqualTo(false); + assertThat(attributes.get(stringKey("key"))).isNull(); + } finally { + span.end(); + } + } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java index 67a17d8d7a8..d42cc3f88a7 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkSpanTest.java @@ -13,35 +13,50 @@ import static io.opentelemetry.api.common.AttributeKey.longKey; import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.api.common.AttributeKey.valueKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.equalTo; +import static java.util.Collections.singletonList; import static java.util.stream.Collectors.joining; -import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import io.opentelemetry.api.common.AttributeKey; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.common.AttributesBuilder; +import io.opentelemetry.api.common.Value; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.SpanContext; import io.opentelemetry.api.trace.SpanId; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.api.trace.StatusCode; import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; -import io.opentelemetry.sdk.internal.InstrumentationScopeUtil; +import io.opentelemetry.sdk.common.internal.AttributesMap; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.InstrumentationScopeUtil; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.sdk.testing.time.TestClock; import io.opentelemetry.sdk.trace.data.EventData; +import io.opentelemetry.sdk.trace.data.ExceptionEventData; import io.opentelemetry.sdk.trace.data.LinkData; import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.data.StatusData; -import io.opentelemetry.sdk.trace.internal.data.ExceptionEventData; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; +import io.opentelemetry.sdk.trace.internal.ExtendedSpanProcessor; import java.io.PrintWriter; import java.io.StringWriter; import java.time.Duration; import java.time.Instant; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; @@ -52,17 +67,27 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Consumer; import java.util.stream.IntStream; +import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; @SuppressWarnings({"rawtypes", "unchecked"}) @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) class SdkSpanTest { private static final String SPAN_NAME = "MySpanName"; private static final String SPAN_NEW_NAME = "NewName"; @@ -81,7 +106,7 @@ class SdkSpanTest { private final Map attributes = new HashMap<>(); private Attributes expectedAttributes; private final LinkData link = LinkData.create(spanContext); - @Mock private SpanProcessor spanProcessor; + @Mock private ExtendedSpanProcessor spanProcessor; private TestClock testClock; @@ -97,6 +122,9 @@ void setUp() { } expectedAttributes = builder.build(); testClock = TestClock.create(Instant.ofEpochSecond(0, START_EPOCH_NANOS)); + when(spanProcessor.isStartRequired()).thenReturn(true); + when(spanProcessor.isOnEndingRequired()).thenReturn(true); + when(spanProcessor.isEndRequired()).thenReturn(true); } @Test @@ -111,12 +139,25 @@ void nothingChangedAfterEnd() { spanData, Attributes.empty(), Collections.emptyList(), - Collections.singletonList(link), + singletonList(link), SPAN_NAME, START_EPOCH_NANOS, START_EPOCH_NANOS, StatusData.unset(), - /*hasEnded=*/ true); + /* hasEnded= */ true); + } + + /** + * {@code SdkSpan.spanEndingThread} prevents concurrent modification of spans while in the ending + * phase such that only {@link ExtendedSpanProcessor#onEnding(ReadWriteSpan)} implementations can + * modify. Here, we verify the thread ref is released so the thread can be garbage collected. This + * is particularly important where processors hold refs to {@link ReadWriteSpan}. + */ + @Test + void end_ReleasesSpanEndingThreadRef() { + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + span.end(); + assertThat(span).extracting("spanEndingThread").isNull(); } @Test @@ -129,6 +170,91 @@ void endSpanTwice_DoNotCrash() { assertThat(span.hasEnded()).isTrue(); } + @Test + void onEnding_spanStillMutable() { + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + + AttributeKey dummyAttrib = AttributeKey.stringKey("processor_foo"); + + AtomicBoolean endedStateInProcessor = new AtomicBoolean(); + doAnswer( + invocation -> { + ReadWriteSpan sp = invocation.getArgument(0, ReadWriteSpan.class); + assertThat(sp.hasEnded()).isFalse(); + sp.end(); // should have no effect, nested end should be detected + endedStateInProcessor.set(sp.hasEnded()); + sp.setAttribute(dummyAttrib, "bar"); + return null; + }) + .when(spanProcessor) + .onEnding(any()); + + span.end(); + verify(spanProcessor).onEnding(same(span)); + assertThat(span.hasEnded()).isTrue(); + assertThat(endedStateInProcessor.get()).isFalse(); + assertThat(span.getAttribute(dummyAttrib)).isEqualTo("bar"); + } + + @Test + void onEnding_concurrentModificationsPrevented() { + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + + AttributeKey syncAttrib = AttributeKey.stringKey("sync_foo"); + AttributeKey concurrentAttrib = AttributeKey.stringKey("concurrent_foo"); + + doAnswer( + invocation -> { + ReadWriteSpan sp = invocation.getArgument(0, ReadWriteSpan.class); + + Thread concurrent = + new Thread(() -> { + sp.setAttribute(concurrentAttrib, "concurrent_bar"); + }); + concurrent.start(); + concurrent.join(); + + sp.setAttribute(syncAttrib, "sync_bar"); + + return null; + }) + .when(spanProcessor) + .onEnding(any()); + + span.end(); + verify(spanProcessor).onEnding(same(span)); + assertThat(span.getAttribute(concurrentAttrib)).isNull(); + assertThat(span.getAttribute(syncAttrib)).isEqualTo("sync_bar"); + } + + @Test + void onEnding_latencyPinned() { + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + + AtomicLong spanLatencyInProcessor = new AtomicLong(); + doAnswer( + invocation -> { + ReadWriteSpan sp = invocation.getArgument(0, ReadWriteSpan.class); + + testClock.advance(Duration.ofSeconds(100)); + spanLatencyInProcessor.set(sp.getLatencyNanos()); + return null; + }) + .when(spanProcessor) + .onEnding(any()); + + testClock.advance(Duration.ofSeconds(1)); + long expectedDuration = testClock.now() - START_EPOCH_NANOS; + + assertThat(span.getLatencyNanos()).isEqualTo(expectedDuration); + + span.end(); + verify(spanProcessor).onEnding(same(span)); + assertThat(span.hasEnded()).isTrue(); + assertThat(span.getLatencyNanos()).isEqualTo(expectedDuration); + assertThat(spanLatencyInProcessor.get()).isEqualTo(expectedDuration); + } + @Test void toSpanData_ActiveSpan() { SdkSpan span = createTestSpan(SpanKind.INTERNAL); @@ -141,13 +267,13 @@ void toSpanData_ActiveSpan() { verifySpanData( spanData, expectedAttributes, - Collections.singletonList(event), - Collections.singletonList(link), + singletonList(event), + singletonList(link), SPAN_NEW_NAME, START_EPOCH_NANOS, 0, StatusData.unset(), - /*hasEnded=*/ false); + /* hasEnded= */ false); assertThat(span.hasEnded()).isFalse(); assertThat(span.isRecording()).isTrue(); } finally { @@ -172,13 +298,13 @@ void toSpanData_EndedSpan() { verifySpanData( spanData, expectedAttributes, - Collections.singletonList(event), - Collections.singletonList(link), + singletonList(event), + singletonList(link), SPAN_NEW_NAME, START_EPOCH_NANOS, testClock.now(), StatusData.create(StatusCode.ERROR, "CANCELLED"), - /*hasEnded=*/ true); + /* hasEnded= */ true); } @Test @@ -330,7 +456,34 @@ void getAttribute() { } @Test - @SuppressWarnings("deprecation") // Testing deprecated code + void getAttributes() { + SdkSpan span = createTestSpanWithAttributes(attributes); + try { + assertThat(span.getAttributes()) + .isEqualTo( + Attributes.builder() + .put("MyBooleanAttributeKey", false) + .put("MyStringAttributeKey", "MyStringAttributeValue") + .put("MyLongAttributeKey", 123L) + .build()); + } finally { + span.end(); + } + } + + @Test + void getAttributes_Empty() { + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + try { + assertThat(span.getAttributes()).isEqualTo(Attributes.empty()); + } finally { + span.end(); + } + } + + @Test + @SuppressWarnings("deprecation") + // Testing deprecated code void getInstrumentationLibraryInfo() { SdkSpan span = createTestSpan(SpanKind.CLIENT); try { @@ -395,7 +548,7 @@ void setAttribute() { SdkSpan span = createTestRootSpan(); try { span.setAttribute("StringKey", "StringVal"); - span.setAttribute("NullStringKey", null); + span.setAttribute("NullStringKey", (String) null); span.setAttribute("EmptyStringKey", ""); span.setAttribute(stringKey("NullStringAttributeValue"), null); span.setAttribute(stringKey("EmptyStringAttributeValue"), ""); @@ -404,6 +557,7 @@ void setAttribute() { span.setAttribute(longKey("LongKey3"), 6L); span.setAttribute("DoubleKey", 10.0); span.setAttribute("BooleanKey", false); + span.setAttribute("BytesValueKey", Value.of(new byte[] {1, 2, 3})); span.setAttribute( stringArrayKey("ArrayStringKey"), Arrays.asList("StringVal", null, "", "StringVal2")); span.setAttribute(longArrayKey("ArrayLongKey"), Arrays.asList(1L, 2L, 3L, 4L, 5L)); @@ -415,19 +569,18 @@ void setAttribute() { span.setAttribute(longArrayKey("NullArrayLongKey"), null); span.setAttribute(doubleArrayKey("NullArrayDoubleKey"), null); span.setAttribute(booleanArrayKey("NullArrayBooleanKey"), null); + span.setAttribute(valueKey("NullValueKey"), null); // These should be maintained - span.setAttribute(longArrayKey("ArrayWithNullLongKey"), Arrays.asList(new Long[] {null})); - span.setAttribute( - stringArrayKey("ArrayWithNullStringKey"), Arrays.asList(new String[] {null})); - span.setAttribute( - doubleArrayKey("ArrayWithNullDoubleKey"), Arrays.asList(new Double[] {null})); - span.setAttribute( - booleanArrayKey("ArrayWithNullBooleanKey"), Arrays.asList(new Boolean[] {null})); + span.setAttribute(longArrayKey("ArrayWithNullLongKey"), singletonList(null)); + span.setAttribute(stringArrayKey("ArrayWithNullStringKey"), singletonList(null)); + span.setAttribute(doubleArrayKey("ArrayWithNullDoubleKey"), singletonList(null)); + span.setAttribute(booleanArrayKey("ArrayWithNullBooleanKey"), singletonList(null)); + span.setAttribute(valueKey("ValueKey"), Value.of(new byte[] {0})); } finally { span.end(); } SpanData spanData = span.toSpanData(); - assertThat(spanData.getAttributes().size()).isEqualTo(16); + assertThat(spanData.getAttributes().size()).isEqualTo(18); assertThat(spanData.getAttributes().get(stringKey("StringKey"))).isNotNull(); assertThat(spanData.getAttributes().get(stringKey("EmptyStringKey"))).isNotNull(); assertThat(spanData.getAttributes().get(stringKey("EmptyStringAttributeValue"))).isNotNull(); @@ -436,6 +589,8 @@ void setAttribute() { assertThat(spanData.getAttributes().get(longKey("LongKey3"))).isEqualTo(6L); assertThat(spanData.getAttributes().get(doubleKey("DoubleKey"))).isNotNull(); assertThat(spanData.getAttributes().get(booleanKey("BooleanKey"))).isNotNull(); + assertThat(spanData.getAttributes().get(valueKey("BytesValueKey"))) + .isEqualTo(Value.of(new byte[] {1, 2, 3})); assertThat(spanData.getAttributes().get(stringArrayKey("ArrayStringKey"))).isNotNull(); assertThat(spanData.getAttributes().get(longArrayKey("ArrayLongKey"))).isNotNull(); assertThat(spanData.getAttributes().get(doubleArrayKey("ArrayDoubleKey"))).isNotNull(); @@ -445,6 +600,7 @@ void setAttribute() { assertThat(spanData.getAttributes().get(doubleArrayKey("ArrayWithNullDoubleKey"))).isNotNull(); assertThat(spanData.getAttributes().get(booleanArrayKey("ArrayWithNullBooleanKey"))) .isNotNull(); + assertThat(spanData.getAttributes().get(valueKey("ValueKey"))).isNotNull(); assertThat(spanData.getAttributes().get(stringArrayKey("ArrayStringKey")).size()).isEqualTo(4); assertThat(spanData.getAttributes().get(longArrayKey("ArrayLongKey")).size()).isEqualTo(5); assertThat(spanData.getAttributes().get(doubleArrayKey("ArrayDoubleKey")).size()).isEqualTo(5); @@ -477,6 +633,7 @@ void setAttribute_nullKeys() { span.setAttribute(null, Collections.emptyList()); span.setAttribute(null, Collections.emptyList()); span.setAttribute(null, Collections.emptyList()); + span.setAttribute((AttributeKey>) null, Value.empty()); assertThat(span.toSpanData().getAttributes().size()).isZero(); } @@ -504,7 +661,7 @@ void setAttribute_emptyArrayAttributeValue() { @Test void setAttribute_nullStringValue() { SdkSpan span = createTestRootSpan(); - span.setAttribute("nullString", null); + span.setAttribute("nullString", (String) null); span.setAttribute("emptyString", ""); span.setAttribute(stringKey("nullStringAttributeValue"), null); span.setAttribute(stringKey("emptyStringAttributeValue"), ""); @@ -525,7 +682,9 @@ void setAttribute_nullAttributeValue() { span.setAttribute(booleanArrayKey("boolArrayAttribute"), Arrays.asList(true, null)); span.setAttribute(longArrayKey("longArrayAttribute"), Arrays.asList(12345L, null)); span.setAttribute(doubleArrayKey("doubleArrayAttribute"), Arrays.asList(1.2345, null)); - assertThat(span.toSpanData().getAttributes().size()).isEqualTo(9); + span.setAttribute(valueKey("emptyValue"), Value.empty()); + span.setAttribute(valueKey("nullValue"), null); + assertThat(span.toSpanData().getAttributes().size()).isEqualTo(10); } @Test @@ -555,10 +714,10 @@ void setAllAttributes() { .put(doubleArrayKey("NullArrayDoubleKey"), (Double[]) null) .put(booleanArrayKey("NullArrayBooleanKey"), (Boolean[]) null) // These should be maintained - .put(longArrayKey("ArrayWithNullLongKey"), Arrays.asList(new Long[] {null})) - .put(stringArrayKey("ArrayWithNullStringKey"), Arrays.asList(new String[] {null})) - .put(doubleArrayKey("ArrayWithNullDoubleKey"), Arrays.asList(new Double[] {null})) - .put(booleanArrayKey("ArrayWithNullBooleanKey"), Arrays.asList(new Boolean[] {null})) + .put(longArrayKey("ArrayWithNullLongKey"), singletonList(null)) + .put(stringArrayKey("ArrayWithNullStringKey"), singletonList(null)) + .put(doubleArrayKey("ArrayWithNullDoubleKey"), singletonList(null)) + .put(booleanArrayKey("ArrayWithNullBooleanKey"), singletonList(null)) .build(); try { @@ -658,50 +817,43 @@ void addEvent() { List events = span.toSpanData().getEvents(); assertThat(events).hasSize(6); assertThat(events.get(0)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event1"); - assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); - assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event1"); + assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); + }); assertThat(events.get(1)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event2"); - assertThat(event.getAttributes()) - .isEqualTo(Attributes.of(stringKey("e1key"), "e1Value")); - assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event2"); + assertThat(event.getAttributes()).isEqualTo(Attributes.of(stringKey("e1key"), "e1Value")); + assertThat(event.getEpochNanos()).isEqualTo(START_EPOCH_NANOS); + }); assertThat(events.get(2)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event3"); - assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(10)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event3"); + assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(10)); + }); assertThat(events.get(3)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event4"); - assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(20)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event4"); + assertThat(event.getAttributes()).isEqualTo(Attributes.empty()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.SECONDS.toNanos(20)); + }); assertThat(events.get(4)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event5"); - assertThat(event.getAttributes()) - .isEqualTo(Attributes.builder().put("foo", "bar").build()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(30)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event5"); + assertThat(event.getAttributes()) + .isEqualTo(Attributes.builder().put("foo", "bar").build()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(30)); + }); assertThat(events.get(5)) - .satisfies( - event -> { - assertThat(event.getName()).isEqualTo("event6"); - assertThat(event.getAttributes()) - .isEqualTo(Attributes.builder().put("foo", "bar").build()); - assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(1000)); - }); + .satisfies(event -> { + assertThat(event.getName()).isEqualTo("event6"); + assertThat(event.getAttributes()) + .isEqualTo(Attributes.builder().put("foo", "bar").build()); + assertThat(event.getEpochNanos()).isEqualTo(TimeUnit.MILLISECONDS.toNanos(1000)); + }); } @Test @@ -744,11 +896,12 @@ void attributeLength() { assertThat(events).hasSize(1); EventData event = events.get(0); assertThat(event.getName()).isEqualTo("exception"); - assertThat(event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE)) + assertThat(event.getAttributes().get(stringKey("exception.type"))) .isEqualTo("java.lang.IllegalStateException".substring(0, maxLength)); - assertThat(event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE)).isEqualTo(strVal); - assertThat(event.getAttributes().get(SemanticAttributes.EXCEPTION_STACKTRACE).length()) + assertThat(event.getAttributes().get(stringKey("exception.message"))).isEqualTo(strVal); + assertThat(event.getAttributes().get(stringKey("exception.stacktrace")).length()) .isLessThanOrEqualTo(maxLength); + assertThat(event.getAttributes().size()).isEqualTo(3); } finally { span.end(); } @@ -792,6 +945,243 @@ void eventAttributeLength() { } } + @Test + void addLink() { + int maxLinks = 3; + int maxNumberOfAttributes = 4; + int maxAttributeLength = 5; + SdkSpan span = + createTestSpan( + SpanKind.INTERNAL, + SpanLimits.builder() + .setMaxNumberOfLinks(maxLinks) + .setMaxNumberOfAttributesPerLink(maxNumberOfAttributes) + .setMaxAttributeValueLength(maxAttributeLength) + .build(), + parentSpanId, + null, + null, + ExceptionAttributeResolver.getDefault()); + try { + Span span1 = createTestSpan(SpanKind.INTERNAL); + Span span2 = createTestSpan(SpanKind.INTERNAL); + Span span3 = createTestSpan(SpanKind.INTERNAL); + Span span4 = createTestSpan(SpanKind.INTERNAL); + + span.addLink(span1.getSpanContext()); + + Attributes span2LinkAttributes = + Attributes.builder() + .put("key1", true) + .put("key2", true) + .put("key3", true) + .put( + "key4", + IntStream.range(0, maxAttributeLength + 1).mapToObj(i -> "a").collect(joining())) + .build(); + span.addLink(span2.getSpanContext(), span2LinkAttributes); + + Attributes span3LinkAttributes = + Attributes.builder() + .put("key1", true) + .put("key2", true) + .put("key3", true) + .put("key4", true) + .put("key5", true) + .build(); + span.addLink(span3.getSpanContext(), span3LinkAttributes); + + span.addLink(span4.getSpanContext()); + + SpanData spanData = span.toSpanData(); + // 1 link added during span construction via createTestSpan, 4 links added after span start + assertThat(spanData.getTotalRecordedLinks()).isEqualTo(4); + assertThat(spanData.getLinks()) + .satisfiesExactly( + link -> { + assertThat(link.getSpanContext()).isEqualTo(span1.getSpanContext()); + assertThat(link.getAttributes()).isEqualTo(Attributes.empty()); + }, + link -> { + assertThat(link.getSpanContext()).isEqualTo(span2.getSpanContext()); + assertThat(link.getAttributes()) + .isEqualTo( + Attributes.builder() + .put("key1", true) + .put("key2", true) + .put("key3", true) + // Should be truncated to max attribute length + .put( + "key4", + IntStream.range(0, maxAttributeLength) + .mapToObj(i -> "a") + .collect(joining())) + .build()); + }, + link -> { + assertThat(link.getSpanContext()).isEqualTo(span2.getSpanContext()); + // The 5th attribute key should be omitted due to attribute limits. Can't predict + // which of the 5 is dropped. + assertThat(link.getAttributes().size()).isEqualTo(4); + assertThat(link.getTotalAttributeCount()).isEqualTo(5); + }); + } finally { + span.end(); + } + } + + @Test + void addLink_InvalidArgs() { + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + assertThatCode(() -> span.addLink(null)).doesNotThrowAnyException(); + assertThatCode(() -> span.addLink(SpanContext.getInvalid())).doesNotThrowAnyException(); + assertThatCode(() -> span.addLink(null, null)).doesNotThrowAnyException(); + assertThatCode(() -> span.addLink(SpanContext.getInvalid(), Attributes.empty())) + .doesNotThrowAnyException(); + span.addLink(null, Attributes.of(stringKey("message.id"), "123")); + span.addLink(SpanContext.getInvalid(), null); + assertThat(span.toSpanData().getLinks()).containsExactly(link); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(1); + span.addLink(spanContext, null); + span.end(); + assertThat(span.toSpanData().getLinks()).containsExactly(link, LinkData.create(spanContext)); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(2); + } + + @ParameterizedTest + @MethodSource("invalidLinkArguments") + void addLink_invalidWithMetadata( + boolean hasTraceState, @Nullable Attributes attributes, boolean recorded) { + SpanContext context = + SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.builder().setSampled(true).setRandomTraceId(true).build(), + hasTraceState + ? TraceState.builder().put("vendor", "value").build() + : TraceState.getDefault()); + SdkSpan span = createTestSpan(SpanKind.INTERNAL); + span.addLink(context); + assertThat(span.toSpanData().getLinks()) + .containsExactlyElementsOf( + hasTraceState ? Arrays.asList(link, LinkData.create(context)) : singletonList(link)); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(hasTraceState ? 2 : 1); + span.end(); + span.addLink(context); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(hasTraceState ? 2 : 1); + + span = createTestSpan(SpanKind.INTERNAL); + span.addLink(context, attributes); + span.end(); + span.addLink(context, attributes); + assertThat(span.toSpanData().getLinks()) + .containsExactlyElementsOf( + recorded + ? Arrays.asList( + link, + LinkData.create(context, attributes == null ? Attributes.empty() : attributes)) + : singletonList(link)); + assertThat(span.toSpanData().getTotalRecordedLinks()).isEqualTo(recorded ? 2 : 1); + } + + private static Stream invalidLinkArguments() { + Attributes attributes = Attributes.of(stringKey("message.id"), "123"); + return Stream.of( + Arguments.argumentSet("attributes", false, attributes, true), + Arguments.argumentSet("trace state", true, Attributes.empty(), true), + Arguments.argumentSet("attributes and trace state", true, attributes, true), + Arguments.argumentSet("flags only", false, Attributes.empty(), false), + Arguments.argumentSet("null attributes", false, null, false), + Arguments.argumentSet("trace state and null attributes", true, null, true)); + } + + @ParameterizedTest + @MethodSource("linkLimits") + void addLink_invalidWithMetadataLimits(int maxLinks, int maxAttributes) { + SdkSpan span = + createTestSpan( + SpanKind.INTERNAL, + SpanLimits.builder() + .setMaxNumberOfLinks(maxLinks) + .setMaxNumberOfAttributesPerLink(maxAttributes) + .setMaxAttributeValueLength(3) + .build(), + parentSpanId, + null, + Collections.emptyList(), + ExceptionAttributeResolver.getDefault()); + SpanContext invalid = SpanContext.getInvalid(); + SpanContext withTraceState = + SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.getDefault(), + TraceState.builder().put("vendor", "value").build()); + Attributes attributes = Attributes.of(stringKey("key0"), "value", stringKey("key1"), "other"); + span.addLink(null, attributes); + span.addLink(invalid); + span.addLink(invalid, attributes); + span.addLink(spanContext); + span.addLink(withTraceState); + span.addLink(withTraceState, attributes); + span.end(); + + SpanData spanData = span.toSpanData(); + assertThat(spanData.getLinks()) + .containsExactlyElementsOf( + maxLinks == 0 + ? Collections.emptyList() + : Arrays.asList( + LinkData.create( + invalid, + maxAttributes == 0 + ? Attributes.empty() + : Attributes.of(stringKey("key0"), "val"), + 2), + link, + LinkData.create(withTraceState))); + assertThat(spanData.getTotalRecordedLinks()).isEqualTo(4); + } + + private static Stream linkLimits() { + return Stream.of( + Arguments.argumentSet("zero links and attributes", 0, 0), + Arguments.argumentSet("zero links", 0, 1), + Arguments.argumentSet("zero attributes", 3, 0), + Arguments.argumentSet("limited links and attributes", 3, 1)); + } + + @Test + void addLink_FaultIn() { + SdkSpan span = + SdkSpan.startSpan( + spanContext, + SPAN_NAME, + instrumentationScopeInfo, + SpanKind.INTERNAL, + Span.getInvalid(), + Context.root(), + SpanLimits.getDefault(), + spanProcessor, + ExceptionAttributeResolver.getDefault(), + testClock, + resource, + null, + null, // exercises the fault-in path + 0, + 0, + () -> {}); + SdkSpan linkedSpan = createTestSpan(SpanKind.INTERNAL); + span.addLink(linkedSpan.getSpanContext()); + + SpanData spanData = span.toSpanData(); + assertThat(spanData.getTotalRecordedLinks()).isEqualTo(1); + assertThat(spanData.getLinks()) + .satisfiesExactly(link -> { + assertThat(link.getSpanContext()).isEqualTo(linkedSpan.getSpanContext()); + }); + } + @Test void droppingAttributes() { int maxNumberOfAttributes = 8; @@ -813,6 +1203,21 @@ void droppingAttributes() { assertThat(spanData.getTotalAttributeCount()).isEqualTo(2 * maxNumberOfAttributes); } + @Test + void overwritingAttribute_doesNotCountAsDropped() { + SdkSpan span = createTestRootSpan(); + try { + span.setAttribute(stringKey("key"), "first"); + span.setAttribute(stringKey("key"), "second"); + SpanData spanData = span.toSpanData(); + assertThat(spanData.getAttributes().size()).isEqualTo(1); + assertThat(spanData.getAttributes().get(stringKey("key"))).isEqualTo("second"); + assertThat(spanData.getTotalAttributeCount()).isEqualTo(1); + } finally { + span.end(); + } + } + @Test void endWithTimestamp_numeric() { SdkSpan span1 = createTestRootSpan(); @@ -907,6 +1312,9 @@ void recordException() { testClock.advance(Duration.ofNanos(1000)); long timestamp = testClock.now(); + // make sure that span attributes don't leak down to the exception event + span.setAttribute("spankey", "val"); + span.recordException(exception); List events = span.toSpanData().getEvents(); @@ -914,20 +1322,17 @@ void recordException() { EventData event = events.get(0); assertThat(event.getName()).isEqualTo("exception"); assertThat(event.getEpochNanos()).isEqualTo(timestamp); - assertThat(event.getAttributes()) - .isEqualTo( - Attributes.builder() - .put(SemanticAttributes.EXCEPTION_TYPE, "java.lang.IllegalStateException") - .put(SemanticAttributes.EXCEPTION_MESSAGE, "there was an exception") - .put(SemanticAttributes.EXCEPTION_STACKTRACE, stacktrace) - .build()); - + assertThat(event.getAttributes().get(stringKey("exception.message"))) + .isEqualTo("there was an exception"); + assertThat(event.getAttributes().get(stringKey("exception.type"))) + .isEqualTo(exception.getClass().getName()); + assertThat(event.getAttributes().get(stringKey("exception.stacktrace"))).isEqualTo(stacktrace); + assertThat(event.getAttributes().size()).isEqualTo(3); assertThat(event) .isInstanceOfSatisfying( ExceptionEventData.class, exceptionEvent -> { assertThat(exceptionEvent.getException()).isSameAs(exception); - assertThat(exceptionEvent.getAdditionalAttributes()).isEqualTo(Attributes.empty()); }); } @@ -936,12 +1341,20 @@ void recordException_noMessage() { IllegalStateException exception = new IllegalStateException(); SdkSpan span = createTestRootSpan(); + StringWriter writer = new StringWriter(); + exception.printStackTrace(new PrintWriter(writer)); + String stacktrace = writer.toString(); + span.recordException(exception); List events = span.toSpanData().getEvents(); assertThat(events).hasSize(1); EventData event = events.get(0); - assertThat(event.getAttributes().get(SemanticAttributes.EXCEPTION_MESSAGE)).isNull(); + assertThat(event.getAttributes().get(stringKey("exception.message"))).isNull(); + assertThat(event.getAttributes().get(stringKey("exception.type"))) + .isEqualTo("java.lang.IllegalStateException"); + assertThat(event.getAttributes().get(stringKey("exception.stacktrace"))).isEqualTo(stacktrace); + assertThat(event.getAttributes().size()).isEqualTo(2); } private static class InnerClassException extends Exception {} @@ -951,13 +1364,19 @@ void recordException_innerClassException() { InnerClassException exception = new InnerClassException(); SdkSpan span = createTestRootSpan(); + StringWriter writer = new StringWriter(); + exception.printStackTrace(new PrintWriter(writer)); + String stacktrace = writer.toString(); + span.recordException(exception); List events = span.toSpanData().getEvents(); assertThat(events).hasSize(1); EventData event = events.get(0); - assertThat(event.getAttributes().get(SemanticAttributes.EXCEPTION_TYPE)) + assertThat(event.getAttributes().get(stringKey("exception.type"))) .isEqualTo("io.opentelemetry.sdk.trace.SdkSpanTest.InnerClassException"); + assertThat(event.getAttributes().get(stringKey("exception.stacktrace"))).isEqualTo(stacktrace); + assertThat(event.getAttributes().size()).isEqualTo(2); } @Test @@ -972,6 +1391,9 @@ void recordException_additionalAttributes() { testClock.advance(Duration.ofNanos(1000)); long timestamp = testClock.now(); + // make sure that span attributes don't leak down to the exception event + span.setAttribute("spankey", "val"); + span.recordException( exception, Attributes.of( @@ -985,30 +1407,71 @@ void recordException_additionalAttributes() { EventData event = events.get(0); assertThat(event.getName()).isEqualTo("exception"); assertThat(event.getEpochNanos()).isEqualTo(timestamp); - assertThat(event.getAttributes()) - .isEqualTo( - Attributes.builder() - .put("key1", "this is an additional attribute") - .put("exception.type", "java.lang.IllegalStateException") - .put("exception.message", "this is a precedence attribute") - .put("exception.stacktrace", stacktrace) - .build()); + assertThat(event.getAttributes().get(stringKey("exception.message"))) + .isEqualTo("this is a precedence attribute"); + assertThat(event.getAttributes().get(stringKey("key1"))) + .isEqualTo("this is an additional attribute"); + assertThat(event.getAttributes().get(stringKey("exception.type"))) + .isEqualTo("java.lang.IllegalStateException"); + assertThat(event.getAttributes().get(stringKey("exception.stacktrace"))).isEqualTo(stacktrace); + assertThat(event.getAttributes().size()).isEqualTo(4); assertThat(event) .isInstanceOfSatisfying( ExceptionEventData.class, exceptionEvent -> { assertThat(exceptionEvent.getException()).isSameAs(exception); - assertThat(exceptionEvent.getAdditionalAttributes()) - .isEqualTo( - Attributes.of( - stringKey("key1"), - "this is an additional attribute", - stringKey("exception.message"), - "this is a precedence attribute")); }); } + @Test + void recordException_SpanLimits() { + SdkSpan span = createTestSpan(SpanLimits.builder().setMaxNumberOfAttributes(2).build()); + span.recordException( + new IllegalStateException("error"), + Attributes.builder().put("key1", "value").put("key2", "value").build()); + + List events = span.toSpanData().getEvents(); + assertThat(events.size()).isEqualTo(1); + EventData event = events.get(0); + assertThat(event.getAttributes().size()).isEqualTo(2); + assertThat(event.getTotalAttributeCount()).isEqualTo(5); + assertThat(event.getTotalAttributeCount() - event.getAttributes().size()).isPositive(); + } + + @Test + void recordException_CustomResolver() { + ExceptionAttributeResolver exceptionAttributeResolver = + new ExceptionAttributeResolver() { + @Override + public void setExceptionAttributes( + AttributeSetter attributeSetter, Throwable throwable, int maxAttributeLength) { + attributeSetter.setAttribute(ExceptionAttributeResolver.EXCEPTION_TYPE, "type"); + attributeSetter.setAttribute( + ExceptionAttributeResolver.EXCEPTION_STACKTRACE, "stacktrace"); + } + }; + + SdkSpan span = + createTestSpan( + SpanKind.INTERNAL, + SpanLimits.getDefault(), + parentSpanId, + null, + singletonList(link), + exceptionAttributeResolver); + + span.recordException(new IllegalStateException("error")); + + List events = span.toSpanData().getEvents(); + assertThat(events.size()).isEqualTo(1); + EventData event = events.get(0); + assertThat(event) + .hasAttributesSatisfyingExactly( + equalTo(ExceptionAttributeResolver.EXCEPTION_TYPE, "type"), + equalTo(ExceptionAttributeResolver.EXCEPTION_STACKTRACE, "stacktrace")); + } + @Test void badArgsIgnored() { SdkSpan span = createTestRootSpan(); @@ -1040,10 +1503,107 @@ void badArgsIgnored() { assertThat(data.getName()).isEqualTo(SPAN_NAME); } + @Test + void onStartOnEndNotRequired() { + when(spanProcessor.isStartRequired()).thenReturn(false); + when(spanProcessor.isEndRequired()).thenReturn(false); + + SpanLimits spanLimits = SpanLimits.getDefault(); + SdkSpan span = + SdkSpan.startSpan( + spanContext, + SPAN_NAME, + instrumentationScopeInfo, + SpanKind.INTERNAL, + parentSpanId != null + ? Span.wrap( + SpanContext.create( + traceId, parentSpanId, TraceFlags.getDefault(), TraceState.getDefault())) + : Span.getInvalid(), + Context.root(), + spanLimits, + spanProcessor, + ExceptionAttributeResolver.getDefault(), + testClock, + resource, + AttributesMap.create( + spanLimits.getMaxNumberOfAttributes(), spanLimits.getMaxAttributeValueLength()), + Collections.emptyList(), + 1, + 0, + () -> {}); + verify(spanProcessor, never()).onStart(any(), any()); + + span.end(); + verify(spanProcessor, never()).onEnd(any()); + } + + @ParameterizedTest + @MethodSource("setStatusArgs") + void setStatus(Consumer spanConsumer, StatusData expectedSpanData) { + SdkSpan testSpan = createTestRootSpan(); + spanConsumer.accept(testSpan); + assertThat(testSpan.toSpanData().getStatus()).isEqualTo(expectedSpanData); + } + + private static Stream setStatusArgs() { + return Stream.of( + Arguments.argumentSet("default UNSET", spanConsumer(span -> {}), StatusData.unset()), + Arguments.argumentSet( + "setStatus OK", spanConsumer(span -> span.setStatus(StatusCode.OK)), StatusData.ok()), + Arguments.argumentSet( + "setStatus ERROR", + spanConsumer(span -> span.setStatus(StatusCode.ERROR)), + StatusData.error()), + Arguments.argumentSet( + "OK then UNSET ignored", + spanConsumer(span -> span.setStatus(StatusCode.OK).setStatus(StatusCode.UNSET)), + StatusData.ok()), + Arguments.argumentSet( + "ERROR then UNSET ignored", + spanConsumer(span -> span.setStatus(StatusCode.ERROR).setStatus(StatusCode.UNSET)), + StatusData.error()), + Arguments.argumentSet( + "UNSET description ignored", + spanConsumer(span -> span.setStatus(StatusCode.UNSET, "description")), + StatusData.unset()), + Arguments.argumentSet( + "OK description ignored", + spanConsumer(span -> span.setStatus(StatusCode.OK, "description")), + StatusData.ok()), + Arguments.argumentSet( + "ERROR with description", + spanConsumer(span -> span.setStatus(StatusCode.ERROR, "description")), + StatusData.create(StatusCode.ERROR, "description")), + Arguments.argumentSet( + "ERROR ignored after OK", + spanConsumer( + span -> span.setStatus(StatusCode.OK).setStatus(StatusCode.ERROR, "description")), + StatusData.ok()), + Arguments.argumentSet( + "setStatus OK after end ignored", + spanConsumer(span -> { + span.end(); + span.setStatus(StatusCode.OK); + }), + StatusData.unset()), + Arguments.argumentSet( + "setStatus ERROR after end ignored", + spanConsumer(span -> { + span.end(); + span.setStatus(StatusCode.ERROR); + }), + StatusData.unset())); + } + + private static Consumer spanConsumer(Consumer spanConsumer) { + return spanConsumer; + } + private SdkSpan createTestSpanWithAttributes(Map attributes) { SpanLimits spanLimits = SpanLimits.getDefault(); AttributesMap attributesMap = - new AttributesMap( + AttributesMap.create( spanLimits.getMaxNumberOfAttributes(), spanLimits.getMaxAttributeValueLength()); attributes.forEach(attributesMap::put); return createTestSpan( @@ -1051,7 +1611,8 @@ private SdkSpan createTestSpanWithAttributes(Map attribute SpanLimits.getDefault(), null, attributesMap, - Collections.singletonList(link)); + singletonList(link), + ExceptionAttributeResolver.getDefault()); } private SdkSpan createTestRootSpan() { @@ -1060,17 +1621,28 @@ private SdkSpan createTestRootSpan() { SpanLimits.getDefault(), SpanId.getInvalid(), null, - Collections.singletonList(link)); + singletonList(link), + ExceptionAttributeResolver.getDefault()); } private SdkSpan createTestSpan(SpanKind kind) { return createTestSpan( - kind, SpanLimits.getDefault(), parentSpanId, null, Collections.singletonList(link)); + kind, + SpanLimits.getDefault(), + parentSpanId, + null, + singletonList(link), + ExceptionAttributeResolver.getDefault()); } private SdkSpan createTestSpan(SpanLimits config) { return createTestSpan( - SpanKind.INTERNAL, config, parentSpanId, null, Collections.singletonList(link)); + SpanKind.INTERNAL, + config, + parentSpanId, + null, + singletonList(link), + ExceptionAttributeResolver.getDefault()); } private SdkSpan createTestSpan( @@ -1078,7 +1650,9 @@ private SdkSpan createTestSpan( SpanLimits config, @Nullable String parentSpanId, @Nullable AttributesMap attributes, - List links) { + @Nullable List links, + ExceptionAttributeResolver exceptionAttributeResolver) { + List linksCopy = links == null ? new ArrayList<>() : new ArrayList<>(links); SdkSpan span = SdkSpan.startSpan( @@ -1094,12 +1668,14 @@ private SdkSpan createTestSpan( Context.root(), config, spanProcessor, + exceptionAttributeResolver, testClock, resource, attributes, - links, - 1, - 0); + linksCopy, + linksCopy.size(), + 0, + () -> {}); Mockito.verify(spanProcessor, Mockito.times(1)).onStart(Context.root(), span); return span; } @@ -1159,8 +1735,8 @@ void testAsSpanData() { TestClock clock = TestClock.create(); Resource resource = this.resource; Attributes attributes = TestUtils.generateRandomAttributes(); - AttributesMap attributesWithCapacity = new AttributesMap(32, Integer.MAX_VALUE); - attributes.forEach((key, value) -> attributesWithCapacity.put((AttributeKey) key, value)); + AttributesMap attributesWithCapacity = AttributesMap.create(32, Integer.MAX_VALUE); + attributes.forEach(attributesWithCapacity::put); Attributes event1Attributes = TestUtils.generateRandomAttributes(); Attributes event2Attributes = TestUtils.generateRandomAttributes(); SpanContext context = @@ -1181,12 +1757,14 @@ void testAsSpanData() { Context.root(), spanLimits, spanProcessor, + ExceptionAttributeResolver.getDefault(), clock, resource, attributesWithCapacity, - Collections.singletonList(link1), + singletonList(link1), 1, - 0); + 0, + () -> {}); long startEpochNanos = clock.now(); clock.advance(Duration.ofMillis(4)); long firstEventEpochNanos = clock.now(); @@ -1211,7 +1789,7 @@ void testAsSpanData() { result, attributesWithCapacity, events, - Collections.singletonList(link1), + singletonList(link1), name, startEpochNanos, endEpochNanos, @@ -1226,12 +1804,11 @@ void testConcurrentModification() throws ExecutionException, InterruptedExceptio SdkSpan span = createTestSpan(SpanKind.INTERNAL); ExecutorService es = Executors.newSingleThreadExecutor(); Future modifierFuture = - es.submit( - () -> { - for (int i = 0; i < 5096 * 5; ++i) { - span.setAttribute("hey" + i, ""); - } - }); + es.submit(() -> { + for (int i = 0; i < 5096 * 5; ++i) { + span.setAttribute("hey" + i, ""); + } + }); try { for (int i = 0; i < 5096 * 5; ++i) { span.toSpanData(); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilderTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilderTest.java new file mode 100644 index 00000000000..b491d87b767 --- /dev/null +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderBuilderTest.java @@ -0,0 +1,135 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.resources.internal.SdkResourceProvider; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import java.util.stream.Stream; +import org.assertj.core.api.InstanceOfAssertFactories; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +public class SdkTracerProviderBuilderTest { + + @Test + void addResource() { + Resource customResource = + Resource.create( + Attributes.of( + AttributeKey.stringKey("custom_attribute_key"), "custom_attribute_value")); + + SdkTracerProvider sdkTracerProvider = + SdkTracerProvider.builder().addResource(customResource).build(); + + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(sdkTracerProvider).getResource()) + .isEqualTo(Resource.getDefault().merge(customResource)); + } + + @Test + void resourceProvider_defaultsToAutoWrappedStaticResource() { + SdkTracerProvider provider = SdkTracerProvider.builder().build(); + + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(provider).getResource()) + .isEqualTo(Resource.getDefault()); + } + + @Test + void setSdkResourceProvider_usedForResource() { + Resource customResource = + Resource.create(Attributes.of(AttributeKey.stringKey("key"), "value")); + SdkResourceProvider resourceProvider = SdkResourceProvider.create(customResource); + + SdkTracerProviderBuilder builder = SdkTracerProvider.builder(); + SdkTracerProviderUtil.setSdkResourceProvider(builder, resourceProvider); + SdkTracerProvider provider = builder.build(); + + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(provider)).isSameAs(resourceProvider); + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(provider).getResource()) + .isEqualTo(customResource); + } + + @ParameterizedTest + @MethodSource("resourceConfigurations") + void setSdkResourceProvider_afterResource_throws(boolean addResource, Resource resource) { + SdkTracerProviderBuilder builder = SdkTracerProvider.builder(); + if (addResource) { + builder.addResource(resource); + } else { + builder.setResource(resource); + } + + assertThatThrownBy(() -> builder.setSdkResourceProvider(SdkResourceProvider.create(resource))) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Cannot call setSdkResourceProvider after setResource or addResource has been called."); + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(builder.build()).getResource()) + .isEqualTo(addResource ? Resource.getDefault().merge(resource) : resource); + } + + @ParameterizedTest + @MethodSource("resourceConfigurations") + void resource_afterSetSdkResourceProvider_throws(boolean addResource, Resource resource) { + SdkResourceProvider resourceProvider = SdkResourceProvider.create(resource); + SdkTracerProviderBuilder builder = SdkTracerProvider.builder(); + SdkTracerProviderUtil.setSdkResourceProvider(builder, resourceProvider); + + assertThatThrownBy( + () -> { + if (addResource) { + builder.addResource(resource); + } else { + builder.setResource(resource); + } + }) + .isInstanceOf(IllegalStateException.class) + .hasMessage( + "Cannot call " + + (addResource ? "addResource" : "setResource") + + " after setSdkResourceProvider has been called."); + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(builder.build())) + .isSameAs(resourceProvider); + } + + private static Stream resourceConfigurations() { + Resource customResource = + Resource.create(Attributes.of(AttributeKey.stringKey("key"), "value")); + return Stream.of( + Arguments.argumentSet("setResource(custom)", false, customResource), + Arguments.argumentSet("setResource(default)", false, Resource.getDefault()), + Arguments.argumentSet("setResource(empty)", false, Resource.empty()), + Arguments.argumentSet("addResource(custom)", true, customResource), + Arguments.argumentSet("addResource(default)", true, Resource.getDefault()), + Arguments.argumentSet("addResource(empty)", true, Resource.empty())); + } + + @Test + void addSpanProcessorFirst() { + SpanProcessor firstProcessor = mock(SpanProcessor.class); + SpanProcessor anotherProcessor = mock(SpanProcessor.class); + + SdkTracerProvider sdkTracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(anotherProcessor) + .addSpanProcessorFirst(firstProcessor) + .build(); + + assertThat(sdkTracerProvider) + .extracting("sharedState") + .extracting("activeSpanProcessor") + .extracting("spanProcessorsAll", InstanceOfAssertFactories.list(SpanProcessor.class)) + .hasSize(2) + .containsExactly(firstProcessor, anotherProcessor); + } +} diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java new file mode 100644 index 00000000000..dc5e34c2ef0 --- /dev/null +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderMetricsTest.java @@ -0,0 +1,1089 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import static io.opentelemetry.sdk.common.internal.SemConvConstants.ERROR_TYPE; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_COMPONENT_NAME; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_COMPONENT_TYPE; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_SPAN_PARENT_ORIGIN; +import static io.opentelemetry.sdk.common.internal.SemConvConstants.OTEL_SPAN_SAMPLING_RESULT; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.metrics.MeterProvider; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanContext; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.api.trace.TraceFlags; +import io.opentelemetry.api.trace.TraceId; +import io.opentelemetry.api.trace.TraceState; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerProvider; +import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.common.InternalTelemetryVersion; +import io.opentelemetry.sdk.metrics.SdkMeterProvider; +import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingDecision; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.time.Duration; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class SdkTracerProviderMetricsTest { + + @Mock private Sampler sampler; + @Mock private SpanExporter mockExporter; + + @Test + void simple() { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + MeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + + InMemorySpanExporter exporter = InMemorySpanExporter.create(); + SimpleSpanProcessor processor = + SimpleSpanProcessor.builder(exporter).setMeterProvider(() -> meterProvider).build(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(processor) + .setMeterProvider(() -> meterProvider) + .setSampler(sampler) + .build(); + + Tracer tracer = tracerProvider.get("test"); + + setSamplingDecision(SamplingDecision.RECORD_AND_SAMPLE); + Span span = tracer.spanBuilder("span").startSpan(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + span.end(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasUnit("{span}") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + + setSamplingDecision(SamplingDecision.RECORD_ONLY); + span = tracer.spanBuilder("span").startSpan(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + span.end(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + + setSamplingDecision(SamplingDecision.DROP); + span = tracer.spanBuilder("span").startSpan(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + span.end(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + + span = + tracer + .spanBuilder("span") + .setParent( + Context.root() + .with( + Span.wrap( + SpanContext.create( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getDefault(), + TraceState.getDefault())))) + .startSpan(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + span.end(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + + setSamplingDecision(SamplingDecision.RECORD_AND_SAMPLE); + span = + tracer + .spanBuilder("span") + .setParent( + Context.root() + .with( + Span.wrap( + SpanContext.createFromRemoteParent( + TraceId.fromLongs(1, 2), + SpanId.fromLong(3), + TraceFlags.getDefault(), + TraceState.getDefault())))) + .startSpan(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + span.end(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + + // Spans rejected after the call to shutdown, regardless of completion so no join. + processor.shutdown(); + tracer.spanBuilder("span").startSpan().end(); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor", + ERROR_TYPE, + "already_shutdown")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "remote", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_ONLY")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "local", + OTEL_SPAN_SAMPLING_RESULT, + "DROP")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE")), + p -> + p.hasValue(0) + .hasAttributes( + Attributes.of(OTEL_SPAN_SAMPLING_RESULT, "RECORD_ONLY"))))); + } + + @Test + @SuppressLogger(BatchSpanProcessor.class) + void batch() throws Exception { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + MeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + + BatchSpanProcessor processor = + BatchSpanProcessor.builder(mockExporter) + .setMaxQueueSize(1) + .setMaxExportBatchSize(1) + // Manually flush + .setScheduleDelay(Duration.ofDays(1)) + .setInternalTelemetryVersion(InternalTelemetryVersion.LATEST) + .setMeterProvider(() -> meterProvider) + .build(); + TracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(processor) + .setMeterProvider(() -> meterProvider) + .setSampler(Sampler.alwaysOn()) + .build(); + + Tracer tracer = tracerProvider.get("test"); + + CompletableResultCode result1 = new CompletableResultCode(); + CompletableResultCode result2 = new CompletableResultCode(); + when(mockExporter.export(any())).thenReturn(result1).thenReturn(result2); + + // Will immediately be processed. + tracer.spanBuilder("span").startSpan().end(); + Thread.sleep(500); // give time to start processing a batch of size 1 + // We haven't completed the export so this span is queued. + tracer.spanBuilder("span").startSpan().end(); + // Queue is full, this span is dropped. + tracer.spanBuilder("span").startSpan().end(); + + // Export hasn't finished but processed metric is incremented + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.queue.capacity") + .hasUnit("{span}") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.queue.size") + .hasUnit("{span}") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasUnit("{span}") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "queue_full")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(3) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + + result1.succeed(); + result2.fail(); + processor.forceFlush().join(1, TimeUnit.SECONDS); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.queue.capacity") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.queue.size") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "queue_full")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(3) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + + lenient().when(mockExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + // Spans rejected after the call to shutdown, regardless of completion so no join. + processor.shutdown(); + + tracer.spanBuilder("span").startSpan().end(); + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.queue.capacity") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.queue.size") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying( + p -> + p.hasValue(2) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "already_shutdown")), + p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "batching_span_processor/0", + OTEL_COMPONENT_TYPE, + "batching_span_processor", + ERROR_TYPE, + "queue_full")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(4) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + } + + @Test + void simpleExportError() { + InMemoryMetricReader metricReader = InMemoryMetricReader.create(); + MeterProvider meterProvider = + SdkMeterProvider.builder().registerMetricReader(metricReader).build(); + + TracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor( + SimpleSpanProcessor.builder(mockExporter) + .setMeterProvider(() -> meterProvider) + .build()) + .setMeterProvider(() -> meterProvider) + .setSampler(Sampler.alwaysOn()) + .build(); + + Tracer tracer = tracerProvider.get("test"); + + when(mockExporter.export(any())).thenReturn(CompletableResultCode.ofFailure()); + + tracer.spanBuilder("span").startSpan().end(); + + assertThat(metricReader.collectAllMetrics()) + .satisfiesExactlyInAnyOrder( + m -> + assertThat(m) + .hasName("otel.sdk.processor.span.processed") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_COMPONENT_NAME, + "simple_span_processor/0", + OTEL_COMPONENT_TYPE, + "simple_span_processor")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.started") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(1) + .hasAttributes( + Attributes.of( + OTEL_SPAN_PARENT_ORIGIN, + "none", + OTEL_SPAN_SAMPLING_RESULT, + "RECORD_AND_SAMPLE")))), + m -> + assertThat(m) + .hasName("otel.sdk.span.live") + .hasLongSumSatisfying(s -> + s.hasPointsSatisfying(p -> + p.hasValue(0) + .hasAttributes( + Attributes.of( + OTEL_SPAN_SAMPLING_RESULT, "RECORD_AND_SAMPLE"))))); + } + + private void setSamplingDecision(SamplingDecision decision) { + when(sampler.shouldSample(any(), any(), any(), any(), any(), any())) + .thenReturn(SamplingResult.create(decision)); + } +} diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderTest.java index 95ffa8a6c6e..9b46a8e827a 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerProviderTest.java @@ -5,21 +5,31 @@ package io.opentelemetry.sdk.trace; +import static io.opentelemetry.api.common.AttributeKey.stringKey; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.api.trace.TracerBuilder; +import io.opentelemetry.api.trace.TracerProvider; import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.Clock; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ExceptionAttributeResolver; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; import io.opentelemetry.sdk.resources.Resource; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.internal.TracerConfig; import io.opentelemetry.sdk.trace.samplers.Sampler; -import io.opentelemetry.semconv.resource.attributes.ResourceAttributes; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -35,11 +45,11 @@ @MockitoSettings(strictness = Strictness.LENIENT) class SdkTracerProviderTest { @Mock private SpanProcessor spanProcessor; - private SdkTracerProvider tracerFactory; + private SdkTracerProvider tracerProvider; @BeforeEach void setUp() { - tracerFactory = SdkTracerProvider.builder().addSpanProcessor(spanProcessor).build(); + tracerProvider = SdkTracerProvider.builder().addSpanProcessor(spanProcessor).build(); when(spanProcessor.forceFlush()).thenReturn(CompletableResultCode.ofSuccess()); when(spanProcessor.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); } @@ -55,9 +65,8 @@ void builder_defaultResource() { .build(); assertThat(tracerProvider).isNotNull(); - assertThat(tracerProvider) - .extracting("sharedState") - .hasFieldOrPropertyWithValue("resource", resourceWithDefaults); + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(tracerProvider).getResource()) + .isEqualTo(resourceWithDefaults); } @Test @@ -82,7 +91,7 @@ void builder_configureSampler_null() { @Test void builder_serviceNameProvided() { Resource resource = - Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, "mySpecialService")); + Resource.create(Attributes.of(stringKey("service.name"), "mySpecialService")); SdkTracerProvider tracerProvider = SdkTracerProvider.builder() @@ -92,9 +101,8 @@ void builder_serviceNameProvided() { .build(); assertThat(tracerProvider).isNotNull(); - assertThat(tracerProvider) - .extracting("sharedState") - .hasFieldOrPropertyWithValue("resource", resource); + assertThat(SdkTracerProviderUtil.getSdkResourceProvider(tracerProvider).getResource()) + .isEqualTo(resource); } @Test @@ -134,34 +142,35 @@ void builder_NullIdsGenerator() { @Test void defaultGet() { - assertThat(tracerFactory.get("test")).isInstanceOf(SdkTracer.class); + assertThat(tracerProvider.get("test")).isInstanceOf(SdkTracer.class); } @Test void getSameInstanceForSameName_WithoutVersion() { - assertThat(tracerFactory.get("test")).isSameAs(tracerFactory.get("test")); - assertThat(tracerFactory.get("test")) - .isSameAs(tracerFactory.get("test", null)) - .isSameAs(tracerFactory.tracerBuilder("test").build()); + assertThat(tracerProvider.get("test")).isSameAs(tracerProvider.get("test")); + assertThat(tracerProvider.get("test")) + .isSameAs(tracerProvider.get("test", null)) + .isSameAs(tracerProvider.tracerBuilder("test").build()); } @Test void getSameInstanceForSameName_WithVersion() { - assertThat(tracerFactory.get("test", "version")) - .isSameAs(tracerFactory.get("test", "version")) - .isSameAs(tracerFactory.tracerBuilder("test").setInstrumentationVersion("version").build()); + assertThat(tracerProvider.get("test", "version")) + .isSameAs(tracerProvider.get("test", "version")) + .isSameAs( + tracerProvider.tracerBuilder("test").setInstrumentationVersion("version").build()); } @Test void getSameInstanceForSameName_WithVersionAndSchema() { assertThat( - tracerFactory + tracerProvider .tracerBuilder("test") .setInstrumentationVersion("version") .setSchemaUrl("http://url") .build()) .isSameAs( - tracerFactory + tracerProvider .tracerBuilder("test") .setInstrumentationVersion("version") .setSchemaUrl("http://url") @@ -171,9 +180,12 @@ void getSameInstanceForSameName_WithVersionAndSchema() { @Test void propagatesInstrumentationScopeInfoToTracer() { InstrumentationScopeInfo expected = - InstrumentationScopeInfo.create("theName", "theVersion", "http://url"); + InstrumentationScopeInfo.builder("theName") + .setVersion("theVersion") + .setSchemaUrl("http://url") + .build(); Tracer tracer = - tracerFactory + tracerProvider .tracerBuilder(expected.getName()) .setInstrumentationVersion(expected.getVersion()) .setSchemaUrl(expected.getSchemaUrl()) @@ -181,6 +193,35 @@ void propagatesInstrumentationScopeInfoToTracer() { assertThat(((SdkTracer) tracer).getInstrumentationScopeInfo()).isEqualTo(expected); } + @Test + void propagatesEnablementToTracerDirectly() { + propagatesEnablementToTracer(true); + } + + @Test + void propagatesEnablementToTracerByUtil() { + propagatesEnablementToTracer(false); + } + + void propagatesEnablementToTracer(boolean directly) { + SdkTracer tracer = (SdkTracer) tracerProvider.get("test"); + boolean isEnabled = tracer.isEnabled(); + ScopeConfigurator flipConfigurator = + new ScopeConfigurator() { + @Override + public TracerConfig apply(InstrumentationScopeInfo scopeInfo) { + return isEnabled ? TracerConfig.disabled() : TracerConfig.enabled(); + } + }; + // all in the same thread, so should see enablement change immediately + if (directly) { + tracerProvider.setTracerConfigurator(flipConfigurator); + } else { + SdkTracerProviderUtil.setTracerConfigurator(tracerProvider, flipConfigurator); + } + assertThat(tracer.isEnabled()).isEqualTo(!isEnabled); + } + @Test void build_SpanLimits() { SpanLimits initialSpanLimits = SpanLimits.builder().build(); @@ -192,58 +233,129 @@ void build_SpanLimits() { @Test void shutdown() { - tracerFactory.shutdown(); + tracerProvider.shutdown(); Mockito.verify(spanProcessor, Mockito.times(1)).shutdown(); } + @Test + void shutdown_ShutsDownSampler() { + Sampler sampler = mock(Sampler.class); + + when(sampler.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + SdkTracerProvider tracerProvider = SdkTracerProvider.builder().setSampler(sampler).build(); + + tracerProvider.shutdown(); + + verify(sampler).shutdown(); + } + @Test void close() { - tracerFactory.close(); + tracerProvider.close(); Mockito.verify(spanProcessor, Mockito.times(1)).shutdown(); } @Test void forceFlush() { - tracerFactory.forceFlush(); + tracerProvider.forceFlush(); Mockito.verify(spanProcessor, Mockito.times(1)).forceFlush(); } @Test @SuppressLogger(SdkTracerProvider.class) void shutdownTwice_OnlyFlushSpanProcessorOnce() { - tracerFactory.shutdown(); + tracerProvider.shutdown(); Mockito.verify(spanProcessor, Mockito.times(1)).shutdown(); - tracerFactory.shutdown(); // the second call will be ignored + tracerProvider.shutdown(); // the second call will be ignored Mockito.verify(spanProcessor, Mockito.times(1)).shutdown(); } @Test void returnNoopSpanAfterShutdown() { - tracerFactory.shutdown(); - Span span = tracerFactory.get("noop").spanBuilder("span").startSpan(); + tracerProvider.shutdown(); + Span span = tracerProvider.get("noop").spanBuilder("span").startSpan(); assertThat(span.getSpanContext().isValid()).isFalse(); span.end(); } @Test void suppliesDefaultTracerForNullName() { - SdkTracer tracer = (SdkTracer) tracerFactory.get(null); + SdkTracer tracer = (SdkTracer) tracerProvider.get(null); assertThat(tracer.getInstrumentationScopeInfo().getName()) .isEqualTo(SdkTracerProvider.DEFAULT_TRACER_NAME); - tracer = (SdkTracer) tracerFactory.get(null, null); + tracer = (SdkTracer) tracerProvider.get(null, null); assertThat(tracer.getInstrumentationScopeInfo().getName()) .isEqualTo(SdkTracerProvider.DEFAULT_TRACER_NAME); } @Test void suppliesDefaultTracerForEmptyName() { - SdkTracer tracer = (SdkTracer) tracerFactory.get(""); + SdkTracer tracer = (SdkTracer) tracerProvider.get(""); assertThat(tracer.getInstrumentationScopeInfo().getName()) .isEqualTo(SdkTracerProvider.DEFAULT_TRACER_NAME); - tracer = (SdkTracer) tracerFactory.get("", ""); + tracer = (SdkTracer) tracerProvider.get("", ""); assertThat(tracer.getInstrumentationScopeInfo().getName()) .isEqualTo(SdkTracerProvider.DEFAULT_TRACER_NAME); } + + @Test + void exceptionAttributeResolver() { + int maxAttributeLength = 5; + SdkTracerProviderBuilder builder = + SdkTracerProvider.builder() + .addSpanProcessor(spanProcessor) + .setSpanLimits( + SpanLimits.builder().setMaxAttributeValueLength(maxAttributeLength).build()); + ExceptionAttributeResolver exceptionAttributeResolver = + spy(ExceptionAttributeResolver.getDefault()); + SdkTracerProviderUtil.setExceptionAttributeResolver(builder, exceptionAttributeResolver); + + Exception exception = new Exception("error"); + builder.build().get("tracer").spanBuilder("span").startSpan().recordException(exception).end(); + + verify(exceptionAttributeResolver).setExceptionAttributes(any(), any(), eq(maxAttributeLength)); + } + + @Test + void withoutSpanProcessor_notRecording() { + Tracer tracer = SdkTracerProvider.builder().build().get("test"); + + Span span = tracer.spanBuilder("test-span").startSpan(); + try { + assertThat(span.isRecording()).as("Should not record without a span processor").isFalse(); + } finally { + span.end(); + } + } + + @Test + void explicitNoopSpanProcessor_tracerResolvesToNoop() { + Tracer tracer = + SdkTracerProvider.builder() + .addSpanProcessor(NoopSpanProcessor.getInstance()) + .build() + .get("test"); + assertThat(tracer).isNotInstanceOf(SdkTracer.class); + } + + @Test + void noSpanProcessors_tracerBuilderSameAsNoop() { + TracerBuilder builder = SdkTracerProvider.builder().build().tracerBuilder("test"); + assertThat(builder).isSameAs(TracerProvider.noop().tracerBuilder("test")); + } + + @Test + void get_NoSpanProcessors_UsesNoop() { + Tracer tracer = SdkTracerProvider.builder().build().get("test"); + assertThat(tracer).isSameAs(TracerProvider.noop().get("test")); + } + + @Test + void getWithVersion_NoSpanProcessors_UsesNoop() { + Tracer tracer = SdkTracerProvider.builder().build().get("test", "1.0.0"); + assertThat(tracer).isSameAs(TracerProvider.noop().get("test", "1.0.0")); + } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerTest.java index eafe5ca517b..2fa34d6874e 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/SdkTracerTest.java @@ -16,6 +16,8 @@ import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.export.BatchSpanProcessor; import io.opentelemetry.sdk.trace.export.SpanExporter; +import io.opentelemetry.sdk.trace.internal.TracerConfig; +import io.opentelemetry.sdk.trace.samplers.Sampler; import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.Test; @@ -27,11 +29,16 @@ class SdkTracerTest { "io.opentelemetry.sdk.trace.TracerSdkTest"; private static final String INSTRUMENTATION_SCOPE_VERSION = "0.2.0"; private static final InstrumentationScopeInfo instrumentationScopeInfo = - InstrumentationScopeInfo.create( - INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION, "http://schemaurl"); + InstrumentationScopeInfo.builder(INSTRUMENTATION_SCOPE_NAME) + .setVersion(INSTRUMENTATION_SCOPE_VERSION) + .setSchemaUrl("http://schemaurl") + .build(); private final SdkTracer tracer = (SdkTracer) SdkTracerProvider.builder() + .addSpanProcessor( + new CountingSpanProcessor()) // configured with a processor so existing tests get + // real recording spans .build() .tracerBuilder(INSTRUMENTATION_SCOPE_NAME) .setInstrumentationVersion(INSTRUMENTATION_SCOPE_VERSION) @@ -48,15 +55,18 @@ void getInstrumentationScopeInfo() { assertThat(tracer.getInstrumentationScopeInfo()).isEqualTo(instrumentationScopeInfo); } + @Test + void updateEnabled() { + tracer.updateTracerConfig(TracerConfig.disabled()); + assertThat(tracer.isEnabled()).isFalse(); + tracer.updateTracerConfig(TracerConfig.enabled()); + assertThat(tracer.isEnabled()).isTrue(); + } + @Test void propagatesInstrumentationScopeInfoToSpan() { ReadableSpan readableSpan = (ReadableSpan) tracer.spanBuilder("spanName").startSpan(); - assertThat(readableSpan.getInstrumentationScopeInfo()) - .isEqualTo( - InstrumentationScopeInfo.create( - instrumentationScopeInfo.getName(), - instrumentationScopeInfo.getVersion(), - instrumentationScopeInfo.getSchemaUrl())); + assertThat(readableSpan.getInstrumentationScopeInfo()).isEqualTo(instrumentationScopeInfo); } @Test @@ -117,6 +127,47 @@ void stressTest_withBatchSpanProcessor() { .isGreaterThanOrEqualTo(defaultMaxQueueSize); } + @Test + void withSpanProcessor_recording() { + // Verify a configured span processor produces recording spans. + CountingSpanProcessor spanProcessor = new CountingSpanProcessor(); + SdkTracer tracer = + (SdkTracer) + SdkTracerProvider.builder() + .addSpanProcessor(spanProcessor) + .build() + .get(INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION); + + Span span = tracer.spanBuilder(SPAN_NAME).startSpan(); + try { + assertThat(span.isRecording()).isTrue(); + } finally { + span.end(); + } + assertThat(spanProcessor.numberOfSpansStarted.get()).isEqualTo(1); + } + + @Test + void alwaysOffSamplerWithProcessor_notShortCircuited() { + // Verify AlwaysOff sampling does not trigger the zero-processor noop path. + SdkTracer tracer = + (SdkTracer) + SdkTracerProvider.builder() + .addSpanProcessor(new CountingSpanProcessor()) + .setSampler(Sampler.alwaysOff()) + .build() + .get(INSTRUMENTATION_SCOPE_NAME, INSTRUMENTATION_SCOPE_VERSION); + + assertThat(tracer.spanBuilder(SPAN_NAME)).isInstanceOf(SdkSpanBuilder.class); + + Span span = tracer.spanBuilder(SPAN_NAME).startSpan(); + try { + assertThat(span.isRecording()).isFalse(); // false due to sampling, not the noop path + } finally { + span.end(); + } + } + private static class CountingSpanProcessor implements SpanProcessor { private final AtomicLong numberOfSpansStarted = new AtomicLong(); private final AtomicLong numberOfSpansFinished = new AtomicLong(); @@ -145,7 +196,7 @@ public boolean isEndRequired() { private static class SimpleSpanOperation implements OperationUpdater { private final SdkTracer tracer; - public SimpleSpanOperation(SdkTracer tracer) { + private SimpleSpanOperation(SdkTracer tracer) { this.tracer = tracer; } @@ -162,7 +213,7 @@ public void update() { private static class CountingSpanExporter implements SpanExporter { - public final AtomicLong numberOfSpansExported = new AtomicLong(); + private final AtomicLong numberOfSpansExported = new AtomicLong(); @Override public CompletableResultCode export(Collection spans) { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java index 61152ff487b..d1e852f2bb9 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/StressTestRunner.java @@ -31,15 +31,14 @@ final void run() { List operationThreads = new ArrayList<>(numThreads); for (Operation operation : operations) { operationThreads.add( - new Thread( - () -> { - for (int i = 0; i < operation.getNumOperations(); i++) { - operation.getUpdater().update(); - Uninterruptibles.sleepUninterruptibly( - Duration.ofMillis(operation.getOperationDelayMs())); - } - countDownLatch.countDown(); - })); + new Thread(() -> { + for (int i = 0; i < operation.getNumOperations(); i++) { + operation.getUpdater().update(); + Uninterruptibles.sleepUninterruptibly( + Duration.ofMillis(operation.getOperationDelayMs())); + } + countDownLatch.countDown(); + })); } for (Thread thread : operationThreads) { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/config/SpanLimitsTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/config/SpanLimitsTest.java index ab749cea0f5..309bdf398c1 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/config/SpanLimitsTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/config/SpanLimitsTest.java @@ -6,6 +6,7 @@ package io.opentelemetry.sdk.trace.config; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import io.opentelemetry.sdk.trace.SpanLimits; @@ -41,32 +42,39 @@ void updateSpanLimits_All() { // Preserves values SpanLimits spanLimitsDupe = spanLimits.toBuilder().build(); // Use reflective comparison to catch when new fields are added. - assertThat(spanLimitsDupe).usingRecursiveComparison().isEqualTo(spanLimits); + assertThat(spanLimitsDupe) + .usingRecursiveComparison() + .withStrictTypeChecking() + .isEqualTo(spanLimits); } @Test void invalidSpanLimits() { - assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfAttributes(0)) - .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfAttributes(-1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfEvents(0)) - .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfEvents(-1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfLinks(0)) - .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfLinks(-1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfAttributesPerEvent(0)) - .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfAttributesPerEvent(-1)) .isInstanceOf(IllegalArgumentException.class); - assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfAttributesPerLink(0)) - .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SpanLimits.builder().setMaxNumberOfAttributesPerLink(-1)) .isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> SpanLimits.builder().setMaxAttributeValueLength(-1)) .isInstanceOf(IllegalArgumentException.class); } + + @Test + void validSpanLimits() { + assertThatCode(() -> SpanLimits.builder().setMaxNumberOfAttributes(0)) + .doesNotThrowAnyException(); + assertThatCode(() -> SpanLimits.builder().setMaxNumberOfEvents(0)).doesNotThrowAnyException(); + assertThatCode(() -> SpanLimits.builder().setMaxNumberOfLinks(0)).doesNotThrowAnyException(); + assertThatCode(() -> SpanLimits.builder().setMaxNumberOfAttributesPerEvent(0)) + .doesNotThrowAnyException(); + assertThatCode(() -> SpanLimits.builder().setMaxNumberOfAttributesPerLink(0)) + .doesNotThrowAnyException(); + assertThatCode(() -> SpanLimits.builder().setMaxAttributeValueLength(0)) + .doesNotThrowAnyException(); + } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/data/DelegatingSpanDataTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/data/DelegatingSpanDataTest.java index 41f8c47cece..b53c147422e 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/data/DelegatingSpanDataTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/data/DelegatingSpanDataTest.java @@ -14,7 +14,6 @@ import io.opentelemetry.api.common.AttributesBuilder; import io.opentelemetry.api.trace.SpanKind; import io.opentelemetry.sdk.testing.trace.TestSpanData; -import io.opentelemetry.semconv.trace.attributes.SemanticAttributes; import org.assertj.core.api.recursive.comparison.RecursiveComparisonConfiguration; import org.junit.jupiter.api.Test; @@ -35,7 +34,7 @@ private static final class SpanDataWithClientType extends DelegatingSpanData { private SpanDataWithClientType(SpanData delegate) { super(delegate); String clientType; - String userAgent = delegate.getAttributes().get(SemanticAttributes.HTTP_USER_AGENT); + String userAgent = delegate.getAttributes().get(stringKey("user_agent.original")); if (userAgent != null) { clientType = parseUserAgent(userAgent); } else { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java index de12f5973d3..2f1b3d005e4 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/BatchSpanProcessorTest.java @@ -14,8 +14,11 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import io.github.netmikey.logunit.api.LogCapturer; import io.opentelemetry.api.internal.GuardedBy; import io.opentelemetry.api.trace.Span; import io.opentelemetry.api.trace.Tracer; @@ -26,6 +29,7 @@ import io.opentelemetry.sdk.trace.data.SpanData; import io.opentelemetry.sdk.trace.samplers.Sampler; import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -39,11 +43,13 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.RegisterExtension; import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import org.slf4j.event.Level; @SuppressWarnings("PreferJavaTimeOverload") @ExtendWith(MockitoExtension.class) @@ -59,9 +65,15 @@ class BatchSpanProcessorTest { @Mock private Sampler mockSampler; @Mock private SpanExporter mockSpanExporter; + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(BatchSpanProcessor.class); + @BeforeEach void setUp() { when(mockSpanExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + when(mockSpanExporter.export(anyList())).thenReturn(CompletableResultCode.ofSuccess()); + + when(mockSampler.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); } @AfterEach @@ -94,12 +106,26 @@ void builderDefaults() { TimeUnit.MILLISECONDS.toNanos(BatchSpanProcessorBuilder.DEFAULT_EXPORT_TIMEOUT_MILLIS)); } + @Test + void createDefaults() { + BatchSpanProcessor processor = + BatchSpanProcessor.create(new WaitingSpanExporter(0, CompletableResultCode.ofSuccess())); + assertThat(processor).isNotNull(); + processor.shutdown().join(10, TimeUnit.SECONDS); + } + + @Test + void createNull() { + assertThatThrownBy(() -> BatchSpanProcessor.create(null)) + .isInstanceOf(NullPointerException.class) + .hasMessage("spanExporter"); + } + @Test void builderInvalidConfig() { - assertThatThrownBy( - () -> - BatchSpanProcessor.builder(mockSpanExporter) - .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + BatchSpanProcessor.builder(mockSpanExporter) + .setScheduleDelay(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("delay must be non-negative"); assertThatThrownBy(() -> BatchSpanProcessor.builder(mockSpanExporter).setScheduleDelay(1, null)) @@ -108,10 +134,9 @@ void builderInvalidConfig() { assertThatThrownBy(() -> BatchSpanProcessor.builder(mockSpanExporter).setScheduleDelay(null)) .isInstanceOf(NullPointerException.class) .hasMessage("delay"); - assertThatThrownBy( - () -> - BatchSpanProcessor.builder(mockSpanExporter) - .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) + assertThatThrownBy(() -> + BatchSpanProcessor.builder(mockSpanExporter) + .setExporterTimeout(-1, TimeUnit.MILLISECONDS)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("timeout must be non-negative"); assertThatThrownBy( @@ -121,6 +146,49 @@ void builderInvalidConfig() { assertThatThrownBy(() -> BatchSpanProcessor.builder(mockSpanExporter).setExporterTimeout(null)) .isInstanceOf(NullPointerException.class) .hasMessage("timeout"); + assertThatThrownBy(() -> BatchSpanProcessor.builder(mockSpanExporter).setMaxQueueSize(0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("maxQueueSize must be positive."); + } + + @Test + @SuppressLogger(BatchSpanProcessorBuilder.class) + void builderAdjustMaxBatchSize() { + SpanExporter dummyExporter = new CompletableSpanExporter(); + + BatchSpanProcessorBuilder builder = + BatchSpanProcessor.builder(dummyExporter).setMaxQueueSize(513).setMaxExportBatchSize(1000); + builder.build(); + + assertThat(builder.getMaxExportBatchSize()).isEqualTo(513); + assertThat(builder.getMaxQueueSize()).isEqualTo(513); + } + + @Test + @SuppressLogger(BatchSpanProcessorBuilder.class) + void maxExportBatchSizeExceedsQueueSize() throws InterruptedException { + // Given a processor configured with a maxExportBatchSize > maxQueueSize, ensure that after n = + // maxQueueSize spans are ended, export is triggered and that the queue is fully drained and + // exported. + int maxQueueSize = 2048; + when(mockSpanExporter.export(any())).thenReturn(CompletableResultCode.ofSuccess()); + sdkTracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor( + BatchSpanProcessor.builder(mockSpanExporter) + .setScheduleDelay(Duration.ofSeconds(Integer.MAX_VALUE)) + .setMaxExportBatchSize(2049) + .setMaxQueueSize(maxQueueSize) + .build()) + .build(); + + for (int i = 0; i < maxQueueSize; i++) { + createEndedSpan("span " + i); + } + + Thread.sleep(10); + + await().untilAsserted(() -> verify(mockSpanExporter, times(1)).export(any())); } @Test @@ -174,16 +242,43 @@ void exportMoreSpansThanTheBufferSize() { spanExporter.succeed(); await() - .untilAsserted( - () -> - assertThat(spanExporter.getExported()) - .containsExactly( - span1.toSpanData(), - span2.toSpanData(), - span3.toSpanData(), - span4.toSpanData(), - span5.toSpanData(), - span6.toSpanData())); + .untilAsserted(() -> + assertThat(spanExporter.getExported()) + .containsExactly( + span1.toSpanData(), + span2.toSpanData(), + span3.toSpanData(), + span4.toSpanData(), + span5.toSpanData(), + span6.toSpanData())); + } + + @Test + @SuppressLogger(BatchSpanProcessor.class) + @SuppressLogger(BatchSpanProcessorBuilder.class) + void droppedSpanIsLogged() { + sdkTracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor( + BatchSpanProcessor.builder(mockSpanExporter) + .setMaxQueueSize(1) + .setMaxExportBatchSize(1_000) + .setScheduleDelay(Duration.ofDays(1)) + .build()) + .build(); + + // Fill the queue with the first span, then drop 2 more. + createEndedSpan(SPAN_NAME_1); + createEndedSpan(SPAN_NAME_2); + createEndedSpan(SPAN_NAME_2); + + // Force export to trigger the drop count log. + sdkTracerProvider.forceFlush().join(10, TimeUnit.SECONDS); + + logs.assertContains( + loggingEvent -> loggingEvent.getLevel().equals(Level.WARN), + "BatchSpanProcessor dropped 2 span(s) since the last export" + + " because the queue is full (maxQueueSize=1)"); } @Test @@ -220,6 +315,75 @@ void forceExport() { assertThat(exported.size()).isEqualTo(2); } + @Test + void testEmptyQueue() { + // Arrange + WaitingSpanExporter waitingSpanExporter = + new WaitingSpanExporter(100, CompletableResultCode.ofSuccess(), 1); + BatchSpanProcessor batchSpanProcessor = + BatchSpanProcessor.builder(waitingSpanExporter) + .setMaxExportBatchSize(10) + .setScheduleDelay(10, TimeUnit.SECONDS) + .setMaxQueueSize(10_000) + .build(); + // Act + sdkTracerProvider = SdkTracerProvider.builder().addSpanProcessor(batchSpanProcessor).build(); + List exported = waitingSpanExporter.waitForExport(); + + // Assert + await().untilAsserted(() -> assertThat(batchSpanProcessor.getQueue()).isEmpty()); + assertThat(exported).isNotNull(); + assertThat(exported.size()).isEqualTo(0); + } + + @Test + void testQueueSizeSmallerThanMaxBatch() { + // Arrange + WaitingSpanExporter waitingSpanExporter = + new WaitingSpanExporter(100, CompletableResultCode.ofSuccess(), 1); + BatchSpanProcessor batchSpanProcessor = + BatchSpanProcessor.builder(waitingSpanExporter) + .setMaxExportBatchSize(11) + .setScheduleDelay(10, TimeUnit.SECONDS) + .setMaxQueueSize(10_000) + .build(); + // Act + sdkTracerProvider = SdkTracerProvider.builder().addSpanProcessor(batchSpanProcessor).build(); + for (int i = 0; i < 10; i++) { + createEndedSpan("notExported"); + } + List exported = waitingSpanExporter.waitForExport(); + + // Assert + assertThat(exported).isNotNull(); + assertThat(exported.size()).isEqualTo(0); + } + + @Test + void testQueueSizeSmallerThanMaxBatchWithForceFlush() { + // Arrange + WaitingSpanExporter waitingSpanExporter = + new WaitingSpanExporter(100, CompletableResultCode.ofSuccess(), 1); + BatchSpanProcessor batchSpanProcessor = + BatchSpanProcessor.builder(waitingSpanExporter) + .setMaxExportBatchSize(11) + .setScheduleDelay(10, TimeUnit.SECONDS) + .setMaxQueueSize(10_000) + .build(); + // Act + sdkTracerProvider = SdkTracerProvider.builder().addSpanProcessor(batchSpanProcessor).build(); + for (int i = 0; i < 10; i++) { + createEndedSpan("notExported"); + } + batchSpanProcessor.forceFlush().join(10, TimeUnit.SECONDS); + List exported = waitingSpanExporter.waitForExport(); + + // Assert + assertThat(exported).isNotNull(); + assertThat(exported.size()).isEqualTo(10); + await().untilAsserted(() -> assertThat(batchSpanProcessor.getQueue()).isEmpty()); + } + @Test void exportSpansToMultipleExporters() { WaitingSpanExporter waitingSpanExporter = @@ -245,6 +409,7 @@ void exportSpansToMultipleExporters() { } @Test + @SuppressLogger(BatchSpanProcessor.class) void exportMoreSpansThanTheMaximumLimit() { int maxQueuedSpans = 8; WaitingSpanExporter waitingSpanExporter = @@ -350,19 +515,19 @@ public void continuesIfExporterTimesOut() throws InterruptedException { .setExporterTimeout(exporterTimeoutMillis, TimeUnit.MILLISECONDS) .setScheduleDelay(1, TimeUnit.MILLISECONDS) .setMaxQueueSize(1) + .setMaxExportBatchSize(1) .build(); sdkTracerProvider = SdkTracerProvider.builder().addSpanProcessor(bsp).build(); CountDownLatch exported = new CountDownLatch(1); // We return a result we never complete, meaning it will timeout. when(mockSpanExporter.export( - argThat( - spans -> { - assertThat(spans) - .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_1)); - exported.countDown(); - return true; - }))) + argThat(spans -> { + assertThat(spans) + .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_1)); + exported.countDown(); + return true; + }))) .thenReturn(new CompletableResultCode()); createEndedSpan(SPAN_NAME_1); exported.await(); @@ -374,13 +539,12 @@ public void continuesIfExporterTimesOut() throws InterruptedException { reset(mockSpanExporter); when(mockSpanExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); when(mockSpanExporter.export( - argThat( - spans -> { - assertThat(spans) - .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_2)); - exportedAgain.countDown(); - return true; - }))) + argThat(spans -> { + assertThat(spans) + .anySatisfy(span -> assertThat(span.getName()).isEqualTo(SPAN_NAME_2)); + exportedAgain.countDown(); + return true; + }))) .thenReturn(CompletableResultCode.ofSuccess()); createEndedSpan(SPAN_NAME_2); exported.await(); @@ -448,6 +612,38 @@ void exportNotSampledSpans_recordOnly() { assertThat(exported).containsExactly(span.toSpanData()); } + @Test + void exportUnsampledSpans_recordOnly() { + WaitingSpanExporter waitingSpanExporter = + new WaitingSpanExporter(1, CompletableResultCode.ofSuccess()); + + when(mockSampler.shouldSample(any(), any(), any(), any(), any(), anyList())) + .thenReturn(SamplingResult.recordOnly()); + sdkTracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor( + BatchSpanProcessor.builder(waitingSpanExporter) + .setExportUnsampledSpans(true) + .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) + .build()) + .setSampler(mockSampler) + .build(); + + ReadableSpan span1 = createEndedSpan(SPAN_NAME_1); + when(mockSampler.shouldSample(any(), any(), any(), any(), any(), anyList())) + .thenReturn(SamplingResult.recordAndSample()); + ReadableSpan span2 = createEndedSpan(SPAN_NAME_2); + + // Spans are recorded and exported in the same order as they are ended, we test that a non + // exported span is not exported by creating and ending a sampled span after a non sampled span + // and checking that the first exported span is the sampled span (the non sampled did not get + // exported). + List exported = waitingSpanExporter.waitForExport(); + // Need to check this because otherwise the variable span1 is unused, other option is to not + // have a span1 variable. + assertThat(exported).containsExactly(span1.toSpanData(), span2.toSpanData()); + } + @Test @Timeout(10) @SuppressLogger(SdkTracerProvider.class) @@ -491,6 +687,12 @@ void shutdownPropagatesFailure() { assertThat(result.isSuccess()).isFalse(); } + @Test + void getSpanExporter() { + assertThat(BatchSpanProcessor.builder(mockSpanExporter).build().getSpanExporter()) + .isSameAs(mockSpanExporter); + } + @Test void stringRepresentation() { BatchSpanProcessor processor = BatchSpanProcessor.builder(mockSpanExporter).build(); @@ -500,6 +702,7 @@ void stringRepresentation() { .hasToString( "BatchSpanProcessor{" + "spanExporter=mockSpanExporter, " + + "exportUnsampledSpans=false, " + "scheduleDelayNanos=5000000000, " + "maxExportBatchSize=512, " + "exporterTimeoutNanos=30000000000}"); @@ -507,19 +710,21 @@ void stringRepresentation() { @Test @Timeout(5) + @SuppressLogger(BatchSpanProcessor.class) void exporterThrowsNonRuntimeException() { when(mockSpanExporter.export(anyList())) - .thenAnswer( - invocation -> { - throw new Exception("No export for you."); - }); + .thenAnswer(invocation -> { + throw new Exception("No export for you."); + }); BatchSpanProcessor batchSpanProcessor = BatchSpanProcessor.builder(mockSpanExporter) .setScheduleDelay(MAX_SCHEDULE_DELAY_MILLIS, TimeUnit.MILLISECONDS) .build(); sdkTracerProvider = SdkTracerProvider.builder().addSpanProcessor(batchSpanProcessor).build(); createEndedSpan(SPAN_NAME_1); - await().untilAsserted(() -> assertThat(batchSpanProcessor.getBatch()).isEmpty()); + // Assert isEmpty() isTrue(). AbstractIterableAssert#isEmpty() iterates over list and can cause + // ConcurrentModificationException + await().untilAsserted(() -> assertThat(batchSpanProcessor.getBatch().isEmpty()).isTrue()); // Continue to export after the exception. createEndedSpan(SPAN_NAME_2); await().untilAsserted(() -> assertThat(batchSpanProcessor.getQueue()).isEmpty()); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/MultiSpanExporterTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/MultiSpanExporterTest.java index f8742828a2b..9a4ad087048 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/MultiSpanExporterTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/MultiSpanExporterTest.java @@ -132,4 +132,23 @@ void twoSpanExporter_FirstThrows() { Mockito.verify(spanExporter1).shutdown(); Mockito.verify(spanExporter2).shutdown(); } + + @Test + @SuppressLogger(MultiSpanExporter.class) + void twoSpanExporter_FirstThrowsCheckedException() { + SpanExporter multiSpanExporter = + SpanExporter.composite(Arrays.asList(spanExporter1, spanExporter2)); + + Mockito.doAnswer( + invocation -> { + throw new Exception("No export for you."); + }) + .when(spanExporter1) + .export(ArgumentMatchers.anyList()); + when(spanExporter2.export(same(SPAN_LIST))).thenReturn(CompletableResultCode.ofSuccess()); + + assertThat(multiSpanExporter.export(SPAN_LIST).isSuccess()).isFalse(); + Mockito.verify(spanExporter1).export(same(SPAN_LIST)); + Mockito.verify(spanExporter2).export(same(SPAN_LIST)); + } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java index da46ec2a641..15e3c2d6a4b 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SimpleSpanProcessorTest.java @@ -6,6 +6,7 @@ package io.opentelemetry.sdk.trace.export; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyCollection; @@ -24,6 +25,7 @@ import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.api.trace.Tracer; import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.common.CompletableResultCode; import io.opentelemetry.sdk.trace.ReadWriteSpan; import io.opentelemetry.sdk.trace.ReadableSpan; @@ -59,7 +61,12 @@ class SimpleSpanProcessorTest { SpanId.getInvalid(), TraceFlags.getSampled(), TraceState.getDefault()); - private static final SpanContext NOT_SAMPLED_SPAN_CONTEXT = SpanContext.getInvalid(); + private static final SpanContext NOT_SAMPLED_SPAN_CONTEXT = + SpanContext.create( + TraceId.getInvalid(), + SpanId.getInvalid(), + TraceFlags.getDefault(), + TraceState.getDefault()); private SpanProcessor simpleSampledSpansProcessor; @@ -68,6 +75,8 @@ void setUp() { simpleSampledSpansProcessor = SimpleSpanProcessor.create(spanExporter); when(spanExporter.export(anyCollection())).thenReturn(CompletableResultCode.ofSuccess()); when(spanExporter.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); + + when(mockSampler.shutdown()).thenReturn(CompletableResultCode.ofSuccess()); } @Test @@ -77,6 +86,22 @@ void createNull() { .hasMessage("exporter"); } + @Test + @SuppressLogger(SimpleSpanProcessor.class) + void onEndSync_ExporterThrowsCheckedException() { + SpanData spanData = TestUtils.makeBasicSpan(); + when(readableSpan.getSpanContext()).thenReturn(SAMPLED_SPAN_CONTEXT); + when(readableSpan.toSpanData()).thenReturn(spanData); + when(spanExporter.export(anyCollection())) + .thenAnswer(invocation -> { + throw new Exception("No export for you."); + }); + + assertThatCode(() -> simpleSampledSpansProcessor.onEnd(readableSpan)) + .doesNotThrowAnyException(); + verify(spanExporter).export(Collections.singletonList(spanData)); + } + @Test void onStartSync() { simpleSampledSpansProcessor.onStart(Context.root(), readWriteSpan); @@ -100,29 +125,29 @@ void onEndSync_NotSampledSpan() { } @Test - void onEndSync_OnlySampled_NotSampledSpan() { + void onEndSync_ExportUnsampledSpans_NotSampledSpan() { + SpanData spanData = TestUtils.makeBasicSpan(); when(readableSpan.getSpanContext()).thenReturn(NOT_SAMPLED_SPAN_CONTEXT); - when(readableSpan.toSpanData()) - .thenReturn(TestUtils.makeBasicSpan()) - .thenThrow(new RuntimeException()); - SpanProcessor simpleSpanProcessor = SimpleSpanProcessor.create(spanExporter); + when(readableSpan.toSpanData()).thenReturn(spanData); + SpanProcessor simpleSpanProcessor = + SimpleSpanProcessor.builder(spanExporter).setExportUnsampledSpans(true).build(); simpleSpanProcessor.onEnd(readableSpan); - verifyNoInteractions(spanExporter); + verify(spanExporter).export(Collections.singletonList(spanData)); } @Test - void onEndSync_OnlySampled_SampledSpan() { + void onEndSync_ExportUnsampledSpans_SampledSpan() { + SpanData spanData = TestUtils.makeBasicSpan(); when(readableSpan.getSpanContext()).thenReturn(SAMPLED_SPAN_CONTEXT); - when(readableSpan.toSpanData()) - .thenReturn(TestUtils.makeBasicSpan()) - .thenThrow(new RuntimeException()); - SpanProcessor simpleSpanProcessor = SimpleSpanProcessor.create(spanExporter); + when(readableSpan.toSpanData()).thenReturn(spanData); + SpanProcessor simpleSpanProcessor = + SimpleSpanProcessor.builder(spanExporter).setExportUnsampledSpans(true).build(); simpleSpanProcessor.onEnd(readableSpan); - verify(spanExporter).export(Collections.singletonList(TestUtils.makeBasicSpan())); + verify(spanExporter).export(Collections.singletonList(spanData)); } @Test - void tracerSdk_NotSampled_Span() { + void tracerSdk_SampledSpan() { WaitingSpanExporter waitingSpanExporter = new WaitingSpanExporter(1, CompletableResultCode.ofSuccess()); @@ -159,25 +184,43 @@ void tracerSdk_NotSampled_Span() { } @Test - void tracerSdk_NotSampled_RecordingEventsSpan() { - // TODO(bdrutu): Fix this when Sampler return RECORD_ONLY option. - /* - tracer.addSpanProcessor( - BatchSpanProcessor.builder(waitingSpanExporter) - .setScheduleDelayMillis(MAX_SCHEDULE_DELAY_MILLIS) - .reportOnlySampled(false) - .build()); - - io.opentelemetry.trace.Span span = - tracer - .spanBuilder("FOO") - .setSampler(Samplers.neverSample()) - .startSpanWithSampler(); - span.end(); - - List exported = waitingSpanExporter.waitForExport(1); - assertThat(exported).containsExactly(((ReadableSpan) span).toSpanData()); - */ + void tracerSdk_ExportUnsampledSpans_NotSampledSpan() { + WaitingSpanExporter waitingSpanExporter = + new WaitingSpanExporter(1, CompletableResultCode.ofSuccess()); + + SdkTracerProvider sdkTracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor( + SimpleSpanProcessor.builder(waitingSpanExporter) + .setExportUnsampledSpans(true) + .build()) + .setSampler(mockSampler) + .build(); + + when(mockSampler.shouldSample(any(), any(), any(), any(), any(), anyList())) + .thenReturn(SamplingResult.drop()); + + try { + Tracer tracer = sdkTracerProvider.get(getClass().getName()); + tracer.spanBuilder(SPAN_NAME).startSpan(); + tracer.spanBuilder(SPAN_NAME).startSpan(); + + when(mockSampler.shouldSample(any(), any(), any(), any(), any(), anyList())) + .thenReturn(SamplingResult.recordOnly()); + Span span = tracer.spanBuilder(SPAN_NAME).startSpan(); + span.end(); + + // Spans are recorded and exported in the same order as they are ended, we test that a non + // sampled span is not exported by creating and ending a sampled span after a non sampled span + // and checking that the first exported span is the sampled span (the non sampled did not get + // exported). + List exported = waitingSpanExporter.waitForExport(); + // Need to check this because otherwise the variable span1 is unused, other option is to not + // have a span1 variable. + assertThat(exported).containsExactly(((ReadableSpan) span).toSpanData()); + } finally { + sdkTracerProvider.shutdown(); + } } @Test @@ -252,4 +295,10 @@ void close() { simpleSampledSpansProcessor.close(); verify(spanExporter).shutdown(); } + + @Test + void getSpanExporter() { + assertThat(((SimpleSpanProcessor) SimpleSpanProcessor.create(spanExporter)).getSpanExporter()) + .isSameAs(spanExporter); + } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SpanExporterTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SpanExporterTest.java new file mode 100644 index 00000000000..9af27df210f --- /dev/null +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/export/SpanExporterTest.java @@ -0,0 +1,45 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.export; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertSame; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.sdk.common.CompletableResultCode; +import io.opentelemetry.sdk.trace.data.SpanData; +import java.util.Collection; +import java.util.Collections; +import org.junit.jupiter.api.Test; + +class SpanExporterTest { + + @Test + void testNoop() { + SpanExporter exporter = SpanExporter.noop(); + assertNotNull(exporter); + assertSame(exporter, NoopSpanExporter.getInstance()); + } + + @Test + void testComposite() { + SpanExporter exp1 = mock(); + SpanExporter exp2 = mock(); + + Collection spans = Collections.singletonList(mock(SpanData.class)); + + when(exp1.export(spans)).thenReturn(CompletableResultCode.ofSuccess()); + when(exp2.export(spans)).thenReturn(CompletableResultCode.ofSuccess()); + + SpanExporter exporter = SpanExporter.composite(exp1, exp2); + + exporter.export(spans); + verify(exp1).export(spans); + verify(exp2).export(spans); + } +} diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java new file mode 100644 index 00000000000..0174c949675 --- /dev/null +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/internal/ExtendedSpanProcessorUsageTest.java @@ -0,0 +1,84 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.internal; + +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; + +import io.opentelemetry.api.common.AttributeKey; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.ReadWriteSpan; +import io.opentelemetry.sdk.trace.ReadableSpan; +import io.opentelemetry.sdk.trace.SdkTracerProvider; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import org.junit.jupiter.api.Test; + +/** Demonstrating usage of {@link ExtendedSpanProcessor}. */ +class ExtendedSpanProcessorUsageTest { + + private static final AttributeKey FOO_KEY = AttributeKey.stringKey("foo"); + private static final AttributeKey BAR_KEY = AttributeKey.stringKey("bar"); + + private static class CopyFooToBarProcessor implements ExtendedSpanProcessor { + + @Override + public void onStart(Context parentContext, ReadWriteSpan span) {} + + @Override + public boolean isStartRequired() { + return false; + } + + @Override + public void onEnd(ReadableSpan span) {} + + @Override + public boolean isEndRequired() { + return false; + } + + @Override + public void onEnding(ReadWriteSpan span) { + String val = span.getAttribute(FOO_KEY); + span.setAttribute(BAR_KEY, val); + } + + @Override + public boolean isOnEndingRequired() { + return true; + } + } + + @Test + void extendedSpanProcessorUsage() { + InMemorySpanExporter exporter = InMemorySpanExporter.create(); + + try (SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(exporter)) + .addSpanProcessor(new CopyFooToBarProcessor()) + .build()) { + + Tracer tracer = tracerProvider.get("dummy-tracer"); + Span span = tracer.spanBuilder("my-span").startSpan(); + + span.setAttribute(FOO_KEY, "Hello!"); + + span.end(); + + assertThat(exporter.getFinishedSpanItems()) + .hasSize(1) + .first() + .satisfies(spanData -> { + assertThat(spanData.getAttributes()) + .containsEntry(FOO_KEY, "Hello!") + .containsEntry(BAR_KEY, "Hello!"); + }); + } + } +} diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilderTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilderTest.java new file mode 100644 index 00000000000..2b6c3f45df1 --- /dev/null +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerBuilderTest.java @@ -0,0 +1,44 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace.samplers; + +import static org.assertj.core.api.Assertions.assertThat; + +import io.github.netmikey.logunit.api.LogCapturer; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.RegisterExtension; + +class ParentBasedSamplerBuilderTest { + + @RegisterExtension + LogCapturer logs = LogCapturer.create().captureForType(ParentBasedSamplerBuilder.class); + + @Test + @SuppressLogger(ParentBasedSamplerBuilder.class) + void emitsWarningForAllChildSamplerSetters() { + Sampler ratioSampler = Sampler.traceIdRatioBased(0.5); + Sampler.parentBasedBuilder(ratioSampler) + .setRemoteParentNotSampled(ratioSampler) + .setRemoteParentSampled(ratioSampler) + .setLocalParentSampled(ratioSampler) + .setLocalParentNotSampled(ratioSampler) + .build(); + + assertThat(logs.getEvents()).hasSize(4); + assertThat(logs.getEvents().get(0).getMessage()) + .contains( + "TraceIdRatioBasedSampler is being used as a child sampler (remoteParentNotSampled)"); + assertThat(logs.getEvents().get(1).getMessage()) + .contains( + "TraceIdRatioBasedSampler is being used as a child sampler (remoteParentSampled)"); + assertThat(logs.getEvents().get(2).getMessage()) + .contains("TraceIdRatioBasedSampler is being used as a child sampler (localParentSampled)"); + assertThat(logs.getEvents().get(3).getMessage()) + .contains( + "TraceIdRatioBasedSampler is being used as a child sampler (localParentNotSampled)"); + } +} diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerTest.java index 5264fabfff9..0d7238c912c 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/ParentBasedSamplerTest.java @@ -410,6 +410,13 @@ void getDescription() { @Test void equals() { - EqualsVerifier.forClass(ParentBasedSampler.class).verify(); + EqualsVerifier.forClass(ParentBasedSampler.class) + .withNonnullFields( + "root", + "remoteParentSampled", + "remoteParentNotSampled", + "localParentSampled", + "localParentNotSampled") + .verify(); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSamplerTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSamplerTest.java index 0c3a160c75a..15a071fc3b7 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSamplerTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/samplers/TraceIdRatioBasedSamplerTest.java @@ -15,10 +15,12 @@ import io.opentelemetry.api.trace.TraceFlags; import io.opentelemetry.api.trace.TraceState; import io.opentelemetry.context.Context; +import io.opentelemetry.internal.testing.slf4j.SuppressLogger; import io.opentelemetry.sdk.trace.IdGenerator; import io.opentelemetry.sdk.trace.data.LinkData; import java.util.Collections; import java.util.List; +import java.util.Locale; import org.junit.jupiter.api.Test; class TraceIdRatioBasedSamplerTest { @@ -67,12 +69,19 @@ void outOfRangeLowProbability() { } @Test - void getDescription() { - assertThat(Sampler.traceIdRatioBased(0.5).getDescription()) - .isEqualTo(String.format("TraceIdRatioBased{%.6f}", 0.5)); + void descriptionShouldBeLocaleIndependent() { + Sampler sampler = Sampler.traceIdRatioBased(0.5); + + // PL locale uses ',' as decimal separator + Locale.setDefault(Locale.forLanguageTag("PL")); + assertThat(sampler.getDescription()).isEqualTo("TraceIdRatioBased{0.500000}"); + + Locale.setDefault(Locale.ENGLISH); + assertThat(sampler.getDescription()).isEqualTo("TraceIdRatioBased{0.500000}"); } @Test + @SuppressLogger(ParentBasedSamplerBuilder.class) void differentProbabilities_NotSampledParent() { assert_NotSampledParent(Sampler.traceIdRatioBased(0.5), 0.5); assert_NotSampledParent(Sampler.traceIdRatioBased(0.2), 0.2); @@ -90,6 +99,7 @@ private void assert_NotSampledParent(Sampler sampler, double probability) { } @Test + @SuppressLogger(ParentBasedSamplerBuilder.class) void differentProbabilities_SampledParent() { assertSampledParent(Sampler.traceIdRatioBased(0.5), 0.5); assertSampledParent(Sampler.traceIdRatioBased(0.2), 0.2); @@ -107,6 +117,7 @@ private void assertSampledParent(Sampler sampler, double probability) { } @Test + @SuppressLogger(ParentBasedSamplerBuilder.class) void differentProbabilities_SampledParentLink() { // Parent NOT sampled assertSampledParentLink(Sampler.traceIdRatioBased(0.5), 0.5); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/TestUtils.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/TestUtils.java index fdc70562a52..127ad323c3b 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/TestUtils.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/TestUtils.java @@ -146,9 +146,8 @@ public static List sortByStartTime(List spans) { /** Asserts the specified {@code List} of {@code Span} belongs to the same trace. */ public static void assertSameTrace(List spans) { for (int i = 0; i < spans.size() - 1; i++) { - // TODO - Include nanos in this comparison. - assertThat(spans.get(spans.size() - 1).getEndEpochNanos() >= spans.get(i).getEndEpochNanos()) - .isTrue(); + assertThat(spans.get(spans.size() - 1).getEndEpochNanos()) + .isGreaterThanOrEqualTo(spans.get(i).getEndEpochNanos()); assertThat(spans.get(spans.size() - 1).getTraceId()).isEqualTo(spans.get(i).getTraceId()); assertThat(spans.get(spans.size() - 1).getSpanId()).isEqualTo(spans.get(i).getParentSpanId()); } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java index 3e9103dd6cc..a91211d89b6 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/activespanreplacement/ActiveSpanReplacementTest.java @@ -66,30 +66,29 @@ void test() { private void submitAnotherTask(Span initialSpan) { - executor.submit( - () -> { - // Create a new Span for this task - Span taskSpan = tracer.spanBuilder("task").startSpan(); - try (Scope scope = taskSpan.makeCurrent()) { - - // Simulate work strictly related to the initial Span - // and finish it. - try (Scope initialScope = initialSpan.makeCurrent()) { - sleep(50); - } finally { - initialSpan.end(); - } - - // Restore the span for this task and create a subspan - Span subTaskSpan = tracer.spanBuilder("subtask").startSpan(); - try (Scope subTaskScope = subTaskSpan.makeCurrent()) { - sleep(50); - } finally { - subTaskSpan.end(); - } - } finally { - taskSpan.end(); - } - }); + executor.submit(() -> { + // Create a new Span for this task + Span taskSpan = tracer.spanBuilder("task").startSpan(); + try (Scope scope = taskSpan.makeCurrent()) { + + // Simulate work strictly related to the initial Span + // and finish it. + try (Scope initialScope = initialSpan.makeCurrent()) { + sleep(50); + } finally { + initialSpan.end(); + } + + // Restore the span for this task and create a subspan + Span subTaskSpan = tracer.spanBuilder("subtask").startSpan(); + try (Scope subTaskScope = subTaskSpan.makeCurrent()) { + sleep(50); + } finally { + subTaskSpan.end(); + } + } finally { + taskSpan.end(); + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java index 73b6e4ca171..6a0a44eb44f 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/actorpropagation/Actor.java @@ -36,47 +36,45 @@ public void close() { Future tell(String message) { Context parent = Context.current(); phaser.register(); - return executor.submit( - () -> { - Span child = - tracer - .spanBuilder("received") - .setParent(parent) - .setSpanKind(SpanKind.CONSUMER) - .startSpan(); - try (Scope ignored = child.makeCurrent()) { - phaser.arriveAndAwaitAdvance(); // child tracer started - child.addEvent("received " + message); - phaser.arriveAndAwaitAdvance(); // assert size - } finally { - child.end(); - } + return executor.submit(() -> { + Span child = + tracer + .spanBuilder("received") + .setParent(parent) + .setSpanKind(SpanKind.CONSUMER) + .startSpan(); + try (Scope ignored = child.makeCurrent()) { + phaser.arriveAndAwaitAdvance(); // child tracer started + child.addEvent("received " + message); + phaser.arriveAndAwaitAdvance(); // assert size + } finally { + child.end(); + } - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size - }); + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + }); } Future ask(String message) { Context parent = Context.current(); phaser.register(); - return executor.submit( - () -> { - Span span = - tracer - .spanBuilder("received") - .setParent(parent) - .setSpanKind(SpanKind.CONSUMER) - .startSpan(); - try { - phaser.arriveAndAwaitAdvance(); // child tracer started - phaser.arriveAndAwaitAdvance(); // assert size - return "received " + message; - } finally { - span.end(); - phaser.arriveAndAwaitAdvance(); // child tracer finished - phaser.arriveAndAwaitAdvance(); // assert size - } - }); + return executor.submit(() -> { + Span span = + tracer + .spanBuilder("received") + .setParent(parent) + .setSpanKind(SpanKind.CONSUMER) + .startSpan(); + try { + phaser.arriveAndAwaitAdvance(); // child tracer started + phaser.arriveAndAwaitAdvance(); // assert size + return "received " + message; + } finally { + span.end(); + phaser.arriveAndAwaitAdvance(); // child tracer finished + phaser.arriveAndAwaitAdvance(); // assert size + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java index fae1666de87..8d66f8db610 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/concurrentcommonrequesthandler/Client.java @@ -21,26 +21,23 @@ public Client(RequestHandler requestHandler) { public Future send(Object message) { RequestHandlerContext requestHandlerContext = new RequestHandlerContext(); - return executor.submit( - () -> { - TestUtils.sleep(); - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.beforeRequest(message, requestHandlerContext); - }) - .get(); - - executor - .submit( - () -> { - TestUtils.sleep(); - requestHandler.afterResponse(message, requestHandlerContext); - }) - .get(); - - return message + ":response"; - }); + return executor.submit(() -> { + TestUtils.sleep(); + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.beforeRequest(message, requestHandlerContext); + }) + .get(); + + executor + .submit(() -> { + TestUtils.sleep(); + requestHandler.afterResponse(message, requestHandlerContext); + }) + .get(); + + return message + ":response"; + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java index 9c2681ca2b2..f306d7df0f6 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/errorreporting/ErrorReportingTest.java @@ -57,16 +57,15 @@ void testSimpleError() { @Test void testCallbackError() { Span span = tracer.spanBuilder("one").startSpan(); - executor.submit( - () -> { - try (Scope ignored = span.makeCurrent()) { - throw new RuntimeException("Invalid state"); - } catch (RuntimeException exc) { - span.setStatus(StatusCode.ERROR); - } finally { - span.end(); - } - }); + executor.submit(() -> { + try (Scope ignored = span.makeCurrent()) { + throw new RuntimeException("Invalid state"); + } catch (RuntimeException exc) { + span.setStatus(StatusCode.ERROR); + } finally { + span.end(); + } + }); await() .atMost(Duration.ofSeconds(5)) @@ -115,16 +114,15 @@ void testInstrumentationLayer() { Span span = tracer.spanBuilder("one").startSpan(); try (Scope ignored = span.makeCurrent()) { executor.submit( - new ScopedRunnable( - () -> { - try { - throw new RuntimeException("Invalid state"); - } catch (RuntimeException exc) { - Span.current().setStatus(StatusCode.ERROR); - } finally { - Span.current().end(); - } - })); + new ScopedRunnable(() -> { + try { + throw new RuntimeException("Invalid state"); + } catch (RuntimeException exc) { + Span.current().setStatus(StatusCode.ERROR); + } finally { + Span.current().end(); + } + })); } await() diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java index dee45a33ec3..37debb0144c 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/latespanfinish/LateSpanFinishTest.java @@ -60,30 +60,28 @@ void test() throws Exception { */ private void submitTasks(Span parentSpan) { - executor.submit( - () -> { - /* Alternative to calling activate() is to pass it manually to asChildOf() for each - * created Span. */ - try (Scope scope = parentSpan.makeCurrent()) { - Span childSpan = tracer.spanBuilder("task1").startSpan(); - try (Scope childScope = childSpan.makeCurrent()) { - TestUtils.sleep(55); - } finally { - childSpan.end(); - } - } - }); + executor.submit(() -> { + /* Alternative to calling activate() is to pass it manually to asChildOf() for each + * created Span. */ + try (Scope scope = parentSpan.makeCurrent()) { + Span childSpan = tracer.spanBuilder("task1").startSpan(); + try (Scope childScope = childSpan.makeCurrent()) { + TestUtils.sleep(55); + } finally { + childSpan.end(); + } + } + }); - executor.submit( - () -> { - try (Scope scope = parentSpan.makeCurrent()) { - Span childSpan = tracer.spanBuilder("task2").startSpan(); - try (Scope childScope = childSpan.makeCurrent()) { - TestUtils.sleep(85); - } finally { - childSpan.end(); - } - } - }); + executor.submit(() -> { + try (Scope scope = parentSpan.makeCurrent()) { + Span childSpan = tracer.spanBuilder("task2").startSpan(); + try (Scope childScope = childSpan.makeCurrent()) { + TestUtils.sleep(85); + } finally { + childSpan.end(); + } + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java index fb5e8515702..d2e0e5b8ab5 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/listenerperrequest/Client.java @@ -22,13 +22,12 @@ public Client(Tracer tracer) { /** Async execution. */ private Future execute(Object message, ResponseListener responseListener) { - return executor.submit( - () -> { - // send via wire and get response - Object response = message + ":response"; - responseListener.onResponse(response); - return response; - }); + return executor.submit(() -> { + // send via wire and get response + Object response = message + ":response"; + responseListener.onResponse(response); + return response; + }); } public Future send(Object message) { diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java index e54fdbe351e..f4f16389dae 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/multiplecallbacks/Client.java @@ -27,17 +27,16 @@ public Client(Tracer tracer, CountDownLatch parentDoneLatch) { public Future send(Object message) { Context parent = Context.current(); - return executor.submit( - () -> { - Span span = tracer.spanBuilder("subtask").setParent(parent).startSpan(); - try (Scope subtaskScope = span.makeCurrent()) { - // Simulate work - make sure we finish *after* the parent Span. - parentDoneLatch.await(); - } finally { - span.end(); - } + return executor.submit(() -> { + Span span = tracer.spanBuilder("subtask").setParent(parent).startSpan(); + try (Scope subtaskScope = span.makeCurrent()) { + // Simulate work - make sure we finish *after* the parent Span. + parentDoneLatch.await(); + } finally { + span.end(); + } - return message + "::response"; - }); + return message + "::response"; + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java index 7a3e87fe439..61f4395ca73 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/nestedcallbacks/NestedCallbacksTest.java @@ -58,27 +58,24 @@ void test() { private void submitCallbacks(Span span) { - executor.submit( - () -> { - try (Scope ignored = span.makeCurrent()) { - span.setAttribute("key1", "1"); + executor.submit(() -> { + try (Scope ignored = span.makeCurrent()) { + span.setAttribute("key1", "1"); - executor.submit( - () -> { - try (Scope ignored12 = span.makeCurrent()) { - span.setAttribute("key2", "2"); + executor.submit(() -> { + try (Scope ignored12 = span.makeCurrent()) { + span.setAttribute("key2", "2"); - executor.submit( - () -> { - try (Scope ignored1 = span.makeCurrent()) { - span.setAttribute("key3", "3"); - } finally { - span.end(); - } - }); - } - }); + executor.submit(() -> { + try (Scope ignored1 = span.makeCurrent()) { + span.setAttribute("key3", "3"); + } finally { + span.end(); + } + }); } }); + } + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java index 80c5d2dddaf..559062ac27e 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/Promise.java @@ -39,34 +39,32 @@ void onError(ErrorCallback errorCallback) { @SuppressWarnings("FutureReturnValueIgnored") void success(T result) { for (SuccessCallback callback : successCallbacks) { - context.submit( - () -> { - Span childSpan = tracer.spanBuilder("success").setParent(parent).startSpan(); - childSpan.setAttribute("component", "success"); - try (Scope ignored = childSpan.makeCurrent()) { - callback.accept(result); - } finally { - childSpan.end(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = tracer.spanBuilder("success").setParent(parent).startSpan(); + childSpan.setAttribute("component", "success"); + try (Scope ignored = childSpan.makeCurrent()) { + callback.accept(result); + } finally { + childSpan.end(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } @SuppressWarnings("FutureReturnValueIgnored") void error(Throwable error) { for (ErrorCallback callback : errorCallbacks) { - context.submit( - () -> { - Span childSpan = tracer.spanBuilder("error").setParent(parent).startSpan(); - childSpan.setAttribute("component", "error"); - try (Scope ignored = childSpan.makeCurrent()) { - callback.accept(error); - } finally { - childSpan.end(); - } - context.getPhaser().arriveAndAwaitAdvance(); // trace reported - }); + context.submit(() -> { + Span childSpan = tracer.spanBuilder("error").setParent(parent).startSpan(); + childSpan.setAttribute("component", "error"); + try (Scope ignored = childSpan.makeCurrent()) { + callback.accept(error); + } finally { + childSpan.end(); + } + context.getPhaser().arriveAndAwaitAdvance(); // trace reported + }); } } diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java index 19b896d5436..7325f3e7795 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/promisepropagation/PromisePropagationTest.java @@ -58,26 +58,23 @@ void testPromiseCallback() { try (Scope ignored = parentSpan.makeCurrent()) { Promise successPromise = new Promise<>(context, tracer); - successPromise.onSuccess( - s -> { - Span.current().addEvent("Promised 1 " + s); - successResult1.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); - successPromise.onSuccess( - s -> { - Span.current().addEvent("Promised 2 " + s); - successResult2.set(s); - phaser.arriveAndAwaitAdvance(); // result set - }); + successPromise.onSuccess(s -> { + Span.current().addEvent("Promised 1 " + s); + successResult1.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); + successPromise.onSuccess(s -> { + Span.current().addEvent("Promised 2 " + s); + successResult2.set(s); + phaser.arriveAndAwaitAdvance(); // result set + }); Promise errorPromise = new Promise<>(context, tracer); - errorPromise.onError( - t -> { - errorResult.set(t); - phaser.arriveAndAwaitAdvance(); // result set - }); + errorPromise.onError(t -> { + errorResult.set(t); + phaser.arriveAndAwaitAdvance(); // result set + }); assertThat(otelTesting.getSpans().size()).isEqualTo(0); successPromise.success("success!"); diff --git a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java index aef5423d5f2..48ab85f8a86 100644 --- a/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java +++ b/sdk/trace/src/test/java/io/opentelemetry/sdk/trace/testbed/statelesscommonrequesthandler/Client.java @@ -22,15 +22,14 @@ public Client(RequestHandler requestHandler) { /** Send a request....... */ public Future send(Object message) { - return executor.submit( - () -> { - TestUtils.sleep(); - requestHandler.beforeRequest(message); + return executor.submit(() -> { + TestUtils.sleep(); + requestHandler.beforeRequest(message); - TestUtils.sleep(); - requestHandler.afterResponse(message); + TestUtils.sleep(); + requestHandler.afterResponse(message); - return message + ":response"; - }); + return message + ":response"; + }); } } diff --git a/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/ContextScopedAttributesSpanTest.java b/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/ContextScopedAttributesSpanTest.java new file mode 100644 index 00000000000..dd41e47b992 --- /dev/null +++ b/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/ContextScopedAttributesSpanTest.java @@ -0,0 +1,263 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import static io.opentelemetry.api.common.AttributeKey.longKey; +import static io.opentelemetry.api.common.AttributeKey.stringKey; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.opentelemetry.api.baggage.Baggage; +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.incubator.common.ContextAttributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.Tracer; +import io.opentelemetry.context.Context; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil; +import io.opentelemetry.sdk.trace.samplers.Sampler; +import io.opentelemetry.sdk.trace.samplers.SamplingResult; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +class ContextScopedAttributesSpanTest { + + private InMemorySpanExporter exporter; + private SdkTracerProviderBuilder builder; + + @BeforeEach + void setUp() { + exporter = InMemorySpanExporter.create(); + builder = SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(exporter)); + } + + @Test + void disabledByDefault() { + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Context ctx = ContextAttributes.set(Context.current(), Attributes.of(stringKey("k1"), "v1")); + try (Scope ignored = ctx.makeCurrent()) { + tracer.spanBuilder("span").startSpan().end(); + } + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly(span -> assertThat(span).hasAttributes(Attributes.empty())); + } + + @Test + void enabled_mergesBeforeSamplerWithExplicitPrecedence() { + Sampler sampler = mock(Sampler.class); + when(sampler.shouldSample(any(), any(), any(), any(), any(), any())) + .thenReturn(SamplingResult.recordAndSample()); + + builder.setSampler(sampler); + SdkTracerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of(stringKey("k1"), "from-context", stringKey("k2"), "from-context")); + try (Scope ignored = ctx.makeCurrent()) { + tracer + .spanBuilder("span") + .setAttribute("k2", "explicit") + .setAttribute("k3", "v3") + .startSpan() + .end(); + } + + ArgumentCaptor sampledAttributes = ArgumentCaptor.forClass(Attributes.class); + verify(sampler).shouldSample(any(), any(), any(), any(), sampledAttributes.capture(), any()); + + Attributes expected = + Attributes.of( + stringKey("k1"), "from-context", stringKey("k2"), "explicit", stringKey("k3"), "v3"); + assertThat(sampledAttributes.getValue().asMap()).isEqualTo(expected.asMap()); + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly(span -> assertThat(span).hasAttributes(expected)); + } + + @Test + void usesExplicitParentContext() { + SdkTracerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Context explicitParent = + ContextAttributes.set(Context.root(), Attributes.of(stringKey("parent"), "explicit")); + Context currentCtx = + ContextAttributes.set(Context.root(), Attributes.of(stringKey("parent"), "current")); + + try (Scope ignored = currentCtx.makeCurrent()) { + tracer.spanBuilder("span").setParent(explicitParent).startSpan().end(); + } + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly( + span -> assertThat(span).hasAttributes(attributeEntry("parent", "explicit"))); + } + + @Test + void explicitParentRoot_dropsContextAttributes() { + SdkTracerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Context currentCtx = + ContextAttributes.set(Context.root(), Attributes.of(stringKey("scope"), "current")); + + try (Scope ignored = currentCtx.makeCurrent()) { + tracer.spanBuilder("span").setParent(Context.root()).startSpan().end(); + } + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly(span -> { + assertThat(span).hasAttributes(Attributes.empty()); + assertThat(span.getParentSpanContext().isValid()).isFalse(); + }); + } + + @Test + void spanAttributeCountLimit() { + builder.setSpanLimits(SpanLimits.builder().setMaxNumberOfAttributes(1).build()); + SdkTracerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Context ctx = + ContextAttributes.set(Context.root(), Attributes.of(stringKey("ctx_attr"), "ctx")); + + try (Scope ignored = ctx.makeCurrent()) { + tracer.spanBuilder("span").setAttribute("explicit_attr", "explicit").startSpan().end(); + } + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly(span -> + assertThat(span) + .hasAttributes(attributeEntry("explicit_attr", "explicit")) + .hasTotalAttributeCount(2)); + } + + @Test + void setNoParent_isolatesTraceAndBaggageWhilePreservingContextAttributes() { + Sampler sampler = mock(Sampler.class); + when(sampler.shouldSample(any(), any(), any(), any(), any(), any())) + .thenReturn(SamplingResult.recordAndSample()); + + SpanProcessor processor = mock(SpanProcessor.class); + when(processor.isStartRequired()).thenReturn(true); + + builder.setSampler(sampler).addSpanProcessor(processor); + SdkTracerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Span parent = tracer.spanBuilder("parent").startSpan(); + try (Scope parentScope = parent.makeCurrent()) { + Context currentCtx = + ContextAttributes.set(Context.current(), Attributes.of(stringKey("tenant.id"), "acme")) + .with(Baggage.builder().put("baggage.key", "baggage.value").build()); + + try (Scope ignored = currentCtx.makeCurrent()) { + tracer.spanBuilder("span").setNoParent().startSpan().end(); + } + } finally { + parent.end(); + } + + ArgumentCaptor samplerContextCaptor = ArgumentCaptor.forClass(Context.class); + ArgumentCaptor samplerAttributesCaptor = ArgumentCaptor.forClass(Attributes.class); + verify(sampler, times(2)) + .shouldSample( + samplerContextCaptor.capture(), + any(), + any(), + any(), + samplerAttributesCaptor.capture(), + any()); + + Context capturedSamplerCtx = samplerContextCaptor.getAllValues().get(1); + assertThat(Baggage.fromContext(capturedSamplerCtx).isEmpty()).isTrue(); + assertThat(Span.fromContext(capturedSamplerCtx).getSpanContext().isValid()).isFalse(); + assertThat(samplerAttributesCaptor.getAllValues().get(1).asMap()) + .isEqualTo(Attributes.of(stringKey("tenant.id"), "acme").asMap()); + + ArgumentCaptor processorContextCaptor = ArgumentCaptor.forClass(Context.class); + verify(processor, times(2)).onStart(processorContextCaptor.capture(), any()); + Context capturedProcessorCtx = processorContextCaptor.getAllValues().get(1); + assertThat(Baggage.fromContext(capturedProcessorCtx).isEmpty()).isTrue(); + assertThat(Span.fromContext(capturedProcessorCtx).getSpanContext().isValid()).isFalse(); + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly( + child -> { + assertThat(child).hasAttributes(attributeEntry("tenant.id", "acme")); + assertThat(child.getParentSpanContext().isValid()).isFalse(); + assertThat(child.getSpanContext().getTraceId()) + .isNotEqualTo(parent.getSpanContext().getTraceId()); + }, + parentSpan -> assertThat(parentSpan.getSpanContext().isValid()).isTrue()); + } + + @Test + void sameNameDifferentType_explicitWins() { + SdkTracerProviderUtil.setContextScopedAttributesFilter(builder, (scope, key) -> true); + SdkTracerProvider provider = builder.build(); + Tracer tracer = provider.get("test"); + + Context ctx = + ContextAttributes.set( + Context.current(), Attributes.of(stringKey("collision"), "contextString")); + try (Scope ignored = ctx.makeCurrent()) { + tracer.spanBuilder("span").setAttribute(longKey("collision"), 12345L).startSpan().end(); + } + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly( + span -> assertThat(span).hasAttributes(attributeEntry("collision", 12345L))); + } + + @Test + void filterPredicate_filtersByScopeAndKey() { + SdkTracerProviderUtil.setContextScopedAttributesFilter( + builder, + (scope, key) -> + scope.getName().equals("allowed-scope") && key.getKey().startsWith("allowed.")); + SdkTracerProvider provider = builder.build(); + + Tracer allowedTracer = provider.get("allowed-scope"); + Tracer otherTracer = provider.get("other-scope"); + + Context ctx = + ContextAttributes.set( + Context.current(), + Attributes.of( + stringKey("allowed.key"), "val1", + stringKey("denied.key"), "val2")); + + try (Scope ignored = ctx.makeCurrent()) { + allowedTracer.spanBuilder("s1").startSpan().end(); + otherTracer.spanBuilder("s2").startSpan().end(); + } + + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly( + s1 -> assertThat(s1).hasAttributes(attributeEntry("allowed.key", "val1")), + s2 -> assertThat(s2).hasAttributes(Attributes.empty())); + } +} diff --git a/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/ExtendedTracerTest.java b/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/ExtendedTracerTest.java new file mode 100644 index 00000000000..f1e3869b71b --- /dev/null +++ b/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/ExtendedTracerTest.java @@ -0,0 +1,72 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.trace.internal.TracerConfig.disabled; + +import io.opentelemetry.api.incubator.trace.ExtendedSpanBuilder; +import io.opentelemetry.api.incubator.trace.ExtendedTracer; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import java.util.function.Supplier; +import java.util.stream.Stream; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class ExtendedTracerTest { + + /** + * {@link ExtendedTracer#spanBuilder(String)} delegates to {@link SdkTracer#spanBuilder(String)} + * and casts the result to {@link ExtendedSpanBuilder}. Therefore, we need to confirm that {@link + * SdkTracer#spanBuilder(String)} correctly returns {@link ExtendedSpanBuilder} and not {@link + * io.opentelemetry.api.trace.SpanBuilder} in all cases, else the user will get {@link + * ClassCastException}. + */ + @ParameterizedTest + @MethodSource("spanBuilderArgs") + void spanBuilder(Supplier spanBuilderSupplier) { + ExtendedSpanBuilder spanBuilder = spanBuilderSupplier.get(); + assertThat(spanBuilder).isInstanceOf(ExtendedSpanBuilder.class); + } + + private static Stream spanBuilderArgs() { + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(InMemorySpanExporter.create())) + .addTracerConfiguratorCondition(nameEquals("tracerB"), disabled()) + .build(); + + ExtendedTracer tracerA = (ExtendedTracer) tracerProvider.get("tracerA"); + ExtendedTracer tracerB = (ExtendedTracer) tracerProvider.get("tracerB"); + + SdkTracerProvider tracerProvider2 = + SdkTracerProvider.builder() + .addSpanProcessor(SimpleSpanProcessor.create(InMemorySpanExporter.create())) + .build(); + ExtendedTracer tracerC = (ExtendedTracer) tracerProvider.get("tracerC"); + tracerProvider2.shutdown(); + + return Stream.of( + Arguments.argumentSet( + "enabled tracer", spanBuilderSupplier(() -> tracerA.spanBuilder("span"))), + Arguments.argumentSet( + "disabled tracer", spanBuilderSupplier(() -> tracerB.spanBuilder("span"))), + Arguments.argumentSet( + "null span name", spanBuilderSupplier(() -> tracerB.spanBuilder(null))), + Arguments.argumentSet( + "blank span name", spanBuilderSupplier(() -> tracerB.spanBuilder(" "))), + Arguments.argumentSet( + "shutdown provider", spanBuilderSupplier(() -> tracerC.spanBuilder("span")))); + } + + private static Supplier spanBuilderSupplier( + Supplier spanBuilderSupplier) { + return spanBuilderSupplier; + } +} diff --git a/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/TracerConfigTest.java b/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/TracerConfigTest.java new file mode 100644 index 00000000000..58dea7b4476 --- /dev/null +++ b/sdk/trace/src/testIncubating/java/io/opentelemetry/sdk/trace/TracerConfigTest.java @@ -0,0 +1,219 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.sdk.trace; + +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameEquals; +import static io.opentelemetry.sdk.common.internal.ScopeConfiguratorBuilder.nameMatchesGlob; +import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat; +import static io.opentelemetry.sdk.trace.internal.TracerConfig.defaultConfig; +import static io.opentelemetry.sdk.trace.internal.TracerConfig.disabled; +import static io.opentelemetry.sdk.trace.internal.TracerConfig.enabled; + +import io.opentelemetry.api.common.Attributes; +import io.opentelemetry.api.trace.Span; +import io.opentelemetry.api.trace.SpanId; +import io.opentelemetry.context.Scope; +import io.opentelemetry.sdk.common.InstrumentationScopeInfo; +import io.opentelemetry.sdk.common.internal.ScopeConfigurator; +import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter; +import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor; +import io.opentelemetry.sdk.trace.internal.TracerConfig; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +class TracerConfigTest { + + @Test + void disableScopes() throws InterruptedException { + InMemorySpanExporter exporter = InMemorySpanExporter.create(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + // Disable tracerB. Since tracers are enabled by default, tracerA and tracerC are + // enabled. + .addTracerConfiguratorCondition(nameEquals("tracerB"), disabled()) + .addSpanProcessor(SimpleSpanProcessor.create(exporter)) + .build(); + + ExtendedSdkTracer tracerA = (ExtendedSdkTracer) tracerProvider.get("tracerA"); + ExtendedSdkTracer tracerB = (ExtendedSdkTracer) tracerProvider.get("tracerB"); + ExtendedSdkTracer tracerC = (ExtendedSdkTracer) tracerProvider.get("tracerC"); + + Span parent; + Span child; + Span grandchild; + + parent = tracerA.spanBuilder("parent").startSpan(); + try (Scope parentScope = parent.makeCurrent()) { + parent.setAttribute("a", "1"); + child = tracerB.spanBuilder("child").startSpan(); + // tracerB is disabled and should behave the same as noop tracer + assertThat(child.getSpanContext()).isEqualTo(parent.getSpanContext()); + assertThat(child.isRecording()).isFalse(); + try (Scope childScope = child.makeCurrent()) { + child.setAttribute("b", "1"); + grandchild = tracerC.spanBuilder("grandchild").startSpan(); + try (Scope grandchildScope = grandchild.makeCurrent()) { + grandchild.setAttribute("c", "1"); + Thread.sleep(100); + } finally { + grandchild.end(); + } + } finally { + child.end(); + } + } finally { + parent.end(); + } + + // Only contain tracerA:parent and tracerC:child should be seen + // tracerC:grandchild should list tracerA:parent as its parent + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactlyInAnyOrder( + spanData -> + assertThat(spanData) + .hasInstrumentationScopeInfo(InstrumentationScopeInfo.create("tracerA")) + .hasName("parent") + .hasSpanId(parent.getSpanContext().getSpanId()) + .hasParentSpanId(SpanId.getInvalid()) + .hasAttributes(Attributes.builder().put("a", "1").build()), + spanData -> + assertThat(spanData) + .hasInstrumentationScopeInfo(InstrumentationScopeInfo.create("tracerC")) + .hasName("grandchild") + .hasSpanId(grandchild.getSpanContext().getSpanId()) + .hasParentSpanId(parent.getSpanContext().getSpanId()) + .hasAttributes(Attributes.builder().put("c", "1").build())); + // tracerA and tracerC are enabled, tracerB is disabled. + assertThat(tracerA.isEnabled()).isTrue(); + assertThat(tracerB.isEnabled()).isFalse(); + assertThat(tracerC.isEnabled()).isTrue(); + } + + @ParameterizedTest + @MethodSource("tracerConfiguratorArgs") + void tracerConfigurator( + ScopeConfigurator tracerConfigurator, + InstrumentationScopeInfo scope, + TracerConfig expectedTracerConfig) { + TracerConfig tracerConfig = tracerConfigurator.apply(scope); + tracerConfig = tracerConfig == null ? defaultConfig() : tracerConfig; + assertThat(tracerConfig).isEqualTo(expectedTracerConfig); + } + + private static final InstrumentationScopeInfo scopeCat = InstrumentationScopeInfo.create("cat"); + private static final InstrumentationScopeInfo scopeDog = InstrumentationScopeInfo.create("dog"); + private static final InstrumentationScopeInfo scopeDuck = InstrumentationScopeInfo.create("duck"); + + private static Stream tracerConfiguratorArgs() { + ScopeConfigurator defaultConfigurator = + TracerConfig.configuratorBuilder().build(); + ScopeConfigurator disableCat = + TracerConfig.configuratorBuilder() + .addCondition(nameEquals("cat"), disabled()) + // Second matching rule for cat should be ignored + .addCondition(nameEquals("cat"), enabled()) + .build(); + ScopeConfigurator disableStartsWithD = + TracerConfig.configuratorBuilder().addCondition(nameMatchesGlob("d*"), disabled()).build(); + ScopeConfigurator enableCat = + TracerConfig.configuratorBuilder() + .setDefault(disabled()) + .addCondition(nameEquals("cat"), enabled()) + // Second matching rule for cat should be ignored + .addCondition(nameEquals("cat"), disabled()) + .build(); + ScopeConfigurator enableStartsWithD = + TracerConfig.configuratorBuilder() + .setDefault(disabled()) + .addCondition(nameMatchesGlob("d*"), TracerConfig.enabled()) + .build(); + + return Stream.of( + Arguments.argumentSet("default cat", defaultConfigurator, scopeCat, defaultConfig()), + Arguments.argumentSet("default dog", defaultConfigurator, scopeDog, defaultConfig()), + Arguments.argumentSet("default duck", defaultConfigurator, scopeDuck, defaultConfig()), + Arguments.argumentSet("disable cat - cat disabled", disableCat, scopeCat, disabled()), + Arguments.argumentSet("disable cat - dog enabled", disableCat, scopeDog, enabled()), + Arguments.argumentSet("disable cat - duck enabled", disableCat, scopeDuck, enabled()), + Arguments.argumentSet("disable d* - cat enabled", disableStartsWithD, scopeCat, enabled()), + Arguments.argumentSet( + "disable d* - dog disabled", disableStartsWithD, scopeDog, disabled()), + Arguments.argumentSet( + "disable d* - duck disabled", disableStartsWithD, scopeDuck, disabled()), + Arguments.argumentSet("enable cat - cat enabled", enableCat, scopeCat, enabled()), + Arguments.argumentSet("enable cat - dog disabled", enableCat, scopeDog, disabled()), + Arguments.argumentSet("enable cat - duck disabled", enableCat, scopeDuck, disabled()), + Arguments.argumentSet("enable d* - cat disabled", enableStartsWithD, scopeCat, disabled()), + Arguments.argumentSet("enable d* - dog enabled", enableStartsWithD, scopeDog, enabled()), + Arguments.argumentSet("enable d* - duck enabled", enableStartsWithD, scopeDuck, enabled())); + } + + @Test + void setScopeConfigurator() { + // 1. Initially, configure all tracers to be enabled except tracerB + InMemorySpanExporter exporter = InMemorySpanExporter.create(); + SdkTracerProvider tracerProvider = + SdkTracerProvider.builder() + .addTracerConfiguratorCondition(nameEquals("tracerB"), disabled()) + .addSpanProcessor(SimpleSpanProcessor.create(exporter)) + .build(); + + ExtendedSdkTracer tracerA = (ExtendedSdkTracer) tracerProvider.get("tracerA"); + ExtendedSdkTracer tracerB = (ExtendedSdkTracer) tracerProvider.get("tracerB"); + ExtendedSdkTracer tracerC = (ExtendedSdkTracer) tracerProvider.get("tracerC"); + + // verify isEnabled() + assertThat(tracerA.isEnabled()).isTrue(); + assertThat(tracerB.isEnabled()).isFalse(); + assertThat(tracerC.isEnabled()).isTrue(); + + // verify spans are emitted as expected + tracerA.spanBuilder("spanA").startSpan().end(); + tracerB.spanBuilder("spanB").startSpan().end(); + tracerC.spanBuilder("spanC").startSpan().end(); + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactlyInAnyOrder( + span -> assertThat(span).hasName("spanA"), span -> assertThat(span).hasName("spanC")); + exporter.reset(); + + // 2. Update config to disable all tracers + tracerProvider.setTracerConfigurator( + ScopeConfigurator.builder().setDefault(TracerConfig.disabled()).build()); + + // verify isEnabled() + assertThat(tracerA.isEnabled()).isFalse(); + assertThat(tracerB.isEnabled()).isFalse(); + assertThat(tracerC.isEnabled()).isFalse(); + + // verify spans are emitted as expected + tracerA.spanBuilder("spanA").startSpan().end(); + tracerB.spanBuilder("spanB").startSpan().end(); + tracerC.spanBuilder("spanC").startSpan().end(); + assertThat(exporter.getFinishedSpanItems()).isEmpty(); + + // 3. Update config to restore original + tracerProvider.setTracerConfigurator( + ScopeConfigurator.builder() + .addCondition(nameEquals("tracerB"), disabled()) + .build()); + + // verify isEnabled() + assertThat(tracerA.isEnabled()).isTrue(); + assertThat(tracerB.isEnabled()).isFalse(); + assertThat(tracerC.isEnabled()).isTrue(); + + // verify spans are emitted as expected + tracerA.spanBuilder("spanA").startSpan().end(); + tracerB.spanBuilder("spanB").startSpan().end(); + tracerC.spanBuilder("spanC").startSpan().end(); + assertThat(exporter.getFinishedSpanItems()) + .satisfiesExactly( + span -> assertThat(span).hasName("spanA"), span -> assertThat(span).hasName("spanC")); + } +} diff --git a/semconv/README.md b/semconv/README.md deleted file mode 100644 index cf626b4bae9..00000000000 --- a/semconv/README.md +++ /dev/null @@ -1,10 +0,0 @@ -# OpenTelemetry Semantic Conventions - -[![Javadocs][javadoc-image]][javadoc-url] - -* This module contains generated code for the Semantic Conventions defined by the OpenTelemetry specification. -* Scripts for generating the classes live in the `buildscripts/semantic-convention` directory -at the top level of the project. - -[javadoc-image]: https://www.javadoc.io/badge/io.opentelemetry/opentelemetry-semconv.svg -[javadoc-url]: https://www.javadoc.io/doc/io.opentelemetry/opentelemetry-semconv diff --git a/semconv/build.gradle.kts b/semconv/build.gradle.kts deleted file mode 100644 index 6ddee0bd7b2..00000000000 --- a/semconv/build.gradle.kts +++ /dev/null @@ -1,13 +0,0 @@ -plugins { - id("otel.java-conventions") - id("otel.publish-conventions") - - id("otel.animalsniffer-conventions") -} - -description = "OpenTelemetry Semantic Conventions" -otelJava.moduleName.set("io.opentelemetry.semconv") - -dependencies { - api(project(":api:all")) -} diff --git a/semconv/gradle.properties b/semconv/gradle.properties deleted file mode 100644 index 4476ae57e31..00000000000 --- a/semconv/gradle.properties +++ /dev/null @@ -1 +0,0 @@ -otel.release=alpha diff --git a/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/ResourceAttributes.java b/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/ResourceAttributes.java deleted file mode 100644 index 67ae90e04de..00000000000 --- a/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/ResourceAttributes.java +++ /dev/null @@ -1,729 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.semconv.resource.attributes; - -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; - -import io.opentelemetry.api.common.AttributeKey; -import java.util.List; - -// DO NOT EDIT, this is an Auto-generated file from -// buildscripts/semantic-convention/templates/SemanticAttributes.java.j2 -public final class ResourceAttributes { - /** The URL of the OpenTelemetry schema for these keys and values. */ - public static final String SCHEMA_URL = "https://opentelemetry.io/schemas/1.9.0"; - - /** Name of the cloud provider. */ - public static final AttributeKey CLOUD_PROVIDER = stringKey("cloud.provider"); - - /** The cloud account ID the resource is assigned to. */ - public static final AttributeKey CLOUD_ACCOUNT_ID = stringKey("cloud.account.id"); - - /** - * The geographical region the resource is running. - * - *

      Notes: - * - *

      - */ - public static final AttributeKey CLOUD_REGION = stringKey("cloud.region"); - - /** - * Cloud regions often have multiple, isolated locations known as zones to increase availability. - * Availability zone represents the zone where the resource is running. - * - *

      Notes: - * - *

        - *
      • Availability zones are called "zones" on Alibaba Cloud and Google Cloud. - *
      - */ - public static final AttributeKey CLOUD_AVAILABILITY_ZONE = - stringKey("cloud.availability_zone"); - - /** - * The cloud platform in use. - * - *

      Notes: - * - *

        - *
      • The prefix of the service SHOULD match the one specified in {@code cloud.provider}. - *
      - */ - public static final AttributeKey CLOUD_PLATFORM = stringKey("cloud.platform"); - - /** - * The Amazon Resource Name (ARN) of an ECS - * container instance. - */ - public static final AttributeKey AWS_ECS_CONTAINER_ARN = - stringKey("aws.ecs.container.arn"); - - /** - * The ARN of an ECS - * cluster. - */ - public static final AttributeKey AWS_ECS_CLUSTER_ARN = stringKey("aws.ecs.cluster.arn"); - - /** - * The launch - * type for an ECS task. - */ - public static final AttributeKey AWS_ECS_LAUNCHTYPE = stringKey("aws.ecs.launchtype"); - - /** - * The ARN of an ECS - * task definition. - */ - public static final AttributeKey AWS_ECS_TASK_ARN = stringKey("aws.ecs.task.arn"); - - /** The task definition family this task definition is a member of. */ - public static final AttributeKey AWS_ECS_TASK_FAMILY = stringKey("aws.ecs.task.family"); - - /** The revision for this task definition. */ - public static final AttributeKey AWS_ECS_TASK_REVISION = - stringKey("aws.ecs.task.revision"); - - /** The ARN of an EKS cluster. */ - public static final AttributeKey AWS_EKS_CLUSTER_ARN = stringKey("aws.eks.cluster.arn"); - - /** - * The name(s) of the AWS log group(s) an application is writing to. - * - *

      Notes: - * - *

        - *
      • Multiple log groups must be supported for cases like multi-container applications, where - * a single application has sidecar containers, and each write to their own log group. - *
      - */ - public static final AttributeKey> AWS_LOG_GROUP_NAMES = - stringArrayKey("aws.log.group.names"); - - /** - * The Amazon Resource Name(s) (ARN) of the AWS log group(s). - * - *

      Notes: - * - *

      - */ - public static final AttributeKey> AWS_LOG_GROUP_ARNS = - stringArrayKey("aws.log.group.arns"); - - /** The name(s) of the AWS log stream(s) an application is writing to. */ - public static final AttributeKey> AWS_LOG_STREAM_NAMES = - stringArrayKey("aws.log.stream.names"); - - /** - * The ARN(s) of the AWS log stream(s). - * - *

      Notes: - * - *

      - */ - public static final AttributeKey> AWS_LOG_STREAM_ARNS = - stringArrayKey("aws.log.stream.arns"); - - /** Container name used by container runtime. */ - public static final AttributeKey CONTAINER_NAME = stringKey("container.name"); - - /** - * Container ID. Usually a UUID, as for example used to identify Docker - * containers. The UUID might be abbreviated. - */ - public static final AttributeKey CONTAINER_ID = stringKey("container.id"); - - /** The container runtime managing this container. */ - public static final AttributeKey CONTAINER_RUNTIME = stringKey("container.runtime"); - - /** Name of the image the container was built on. */ - public static final AttributeKey CONTAINER_IMAGE_NAME = stringKey("container.image.name"); - - /** Container image tag. */ - public static final AttributeKey CONTAINER_IMAGE_TAG = stringKey("container.image.tag"); - - /** - * Name of the deployment - * environment (aka deployment tier). - */ - public static final AttributeKey DEPLOYMENT_ENVIRONMENT = - stringKey("deployment.environment"); - - /** - * A unique identifier representing the device - * - *

      Notes: - * - *

        - *
      • The device identifier MUST only be defined using the values outlined below. This value is - * not an advertising identifier and MUST NOT be used as such. On iOS (Swift or - * Objective-C), this value MUST be equal to the vendor - * identifier. On Android (Java or Kotlin), this value MUST be equal to the Firebase - * Installation ID or a globally unique UUID which is persisted across sessions in your - * application. More information can be found here on best - * practices and exact implementation details. Caution should be taken when storing personal - * data or anything which can identify a user. GDPR and data protection laws may apply, - * ensure you do your own due diligence. - *
      - */ - public static final AttributeKey DEVICE_ID = stringKey("device.id"); - - /** - * The model identifier for the device - * - *

      Notes: - * - *

        - *
      • It's recommended this value represents a machine readable version of the model identifier - * rather than the market or consumer-friendly name of the device. - *
      - */ - public static final AttributeKey DEVICE_MODEL_IDENTIFIER = - stringKey("device.model.identifier"); - - /** - * The marketing name for the device model - * - *

      Notes: - * - *

        - *
      • It's recommended this value represents a human readable version of the device model - * rather than a machine readable alternative. - *
      - */ - public static final AttributeKey DEVICE_MODEL_NAME = stringKey("device.model.name"); - - /** - * The name of the device manufacturer - * - *

      Notes: - * - *

        - *
      • The Android OS provides this field via Build. - * iOS apps SHOULD hardcode the value {@code Apple}. - *
      - */ - public static final AttributeKey DEVICE_MANUFACTURER = stringKey("device.manufacturer"); - - /** - * The name of the single function that this runtime instance executes. - * - *

      Notes: - * - *

        - *
      • This is the name of the function as configured/deployed on the FaaS platform and is - * usually different from the name of the callback function (which may be stored in the {@code - * code.namespace}/{@code code.function} span attributes). - *
      - */ - public static final AttributeKey FAAS_NAME = stringKey("faas.name"); - - /** - * The unique ID of the single function that this runtime instance executes. - * - *

      Notes: - * - *

        - *
      • Depending on the cloud provider, use: - *
      • AWS Lambda: The function ARN. - *
      • Take care not to use the "invoked ARN" directly but replace any alias - * suffix with the resolved function version, as the same runtime instance may be - * invokable with multiple different aliases. - *
      • GCP: The URI of the resource - *
      • Azure: The Fully - * Qualified Resource ID. - *
      • On some providers, it may not be possible to determine the full ID at startup, which is - * why this field cannot be made required. For example, on AWS the account ID part of the - * ARN is not available without calling another AWS API which may be deemed too slow for a - * short-running lambda function. As an alternative, consider setting {@code faas.id} as a - * span attribute instead. - *
      - */ - public static final AttributeKey FAAS_ID = stringKey("faas.id"); - - /** - * The immutable version of the function being executed. - * - *

      Notes: - * - *

        - *
      • Depending on the cloud provider and platform, use: - *
      • AWS Lambda: The function - * version (an integer represented as a decimal string). - *
      • Google Cloud Run: The revision (i.e., the - * function name plus the revision suffix). - *
      • Google Cloud Functions: The value of the {@code - * K_REVISION} environment variable. - *
      • Azure Functions: Not applicable. Do not set this attribute. - *
      - */ - public static final AttributeKey FAAS_VERSION = stringKey("faas.version"); - - /** - * The execution environment ID as a string, that will be potentially reused for other invocations - * to the same function/function version. - * - *

      Notes: - * - *

        - *
      • AWS Lambda: Use the (full) log stream name. - *
      - */ - public static final AttributeKey FAAS_INSTANCE = stringKey("faas.instance"); - - /** - * The amount of memory available to the serverless function in MiB. - * - *

      Notes: - * - *

        - *
      • It's recommended to set this attribute since e.g. too little memory can easily stop a - * Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable - * {@code AWS_LAMBDA_FUNCTION_MEMORY_SIZE} provides this information. - *
      - */ - public static final AttributeKey FAAS_MAX_MEMORY = longKey("faas.max_memory"); - - /** Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. */ - public static final AttributeKey HOST_ID = stringKey("host.id"); - - /** - * Name of the host. On Unix systems, it may contain what the hostname command returns, or the - * fully qualified hostname, or another name specified by the user. - */ - public static final AttributeKey HOST_NAME = stringKey("host.name"); - - /** Type of host. For Cloud, this must be the machine type. */ - public static final AttributeKey HOST_TYPE = stringKey("host.type"); - - /** The CPU architecture the host system is running on. */ - public static final AttributeKey HOST_ARCH = stringKey("host.arch"); - - /** Name of the VM image or OS install the host was instantiated from. */ - public static final AttributeKey HOST_IMAGE_NAME = stringKey("host.image.name"); - - /** VM image ID. For Cloud, this value is from the provider. */ - public static final AttributeKey HOST_IMAGE_ID = stringKey("host.image.id"); - - /** - * The version string of the VM image as defined in Version - * Attributes. - */ - public static final AttributeKey HOST_IMAGE_VERSION = stringKey("host.image.version"); - - /** The name of the cluster. */ - public static final AttributeKey K8S_CLUSTER_NAME = stringKey("k8s.cluster.name"); - - /** The name of the Node. */ - public static final AttributeKey K8S_NODE_NAME = stringKey("k8s.node.name"); - - /** The UID of the Node. */ - public static final AttributeKey K8S_NODE_UID = stringKey("k8s.node.uid"); - - /** The name of the namespace that the pod is running in. */ - public static final AttributeKey K8S_NAMESPACE_NAME = stringKey("k8s.namespace.name"); - - /** The UID of the Pod. */ - public static final AttributeKey K8S_POD_UID = stringKey("k8s.pod.uid"); - - /** The name of the Pod. */ - public static final AttributeKey K8S_POD_NAME = stringKey("k8s.pod.name"); - - /** - * The name of the Container from Pod specification, must be unique within a Pod. Container - * runtime usually uses different globally unique name ({@code container.name}). - */ - public static final AttributeKey K8S_CONTAINER_NAME = stringKey("k8s.container.name"); - - /** - * Number of times the container was restarted. This attribute can be used to identify a - * particular container (running or stopped) within a container spec. - */ - public static final AttributeKey K8S_CONTAINER_RESTART_COUNT = - longKey("k8s.container.restart_count"); - - /** The UID of the ReplicaSet. */ - public static final AttributeKey K8S_REPLICASET_UID = stringKey("k8s.replicaset.uid"); - - /** The name of the ReplicaSet. */ - public static final AttributeKey K8S_REPLICASET_NAME = stringKey("k8s.replicaset.name"); - - /** The UID of the Deployment. */ - public static final AttributeKey K8S_DEPLOYMENT_UID = stringKey("k8s.deployment.uid"); - - /** The name of the Deployment. */ - public static final AttributeKey K8S_DEPLOYMENT_NAME = stringKey("k8s.deployment.name"); - - /** The UID of the StatefulSet. */ - public static final AttributeKey K8S_STATEFULSET_UID = stringKey("k8s.statefulset.uid"); - - /** The name of the StatefulSet. */ - public static final AttributeKey K8S_STATEFULSET_NAME = stringKey("k8s.statefulset.name"); - - /** The UID of the DaemonSet. */ - public static final AttributeKey K8S_DAEMONSET_UID = stringKey("k8s.daemonset.uid"); - - /** The name of the DaemonSet. */ - public static final AttributeKey K8S_DAEMONSET_NAME = stringKey("k8s.daemonset.name"); - - /** The UID of the Job. */ - public static final AttributeKey K8S_JOB_UID = stringKey("k8s.job.uid"); - - /** The name of the Job. */ - public static final AttributeKey K8S_JOB_NAME = stringKey("k8s.job.name"); - - /** The UID of the CronJob. */ - public static final AttributeKey K8S_CRONJOB_UID = stringKey("k8s.cronjob.uid"); - - /** The name of the CronJob. */ - public static final AttributeKey K8S_CRONJOB_NAME = stringKey("k8s.cronjob.name"); - - /** The operating system type. */ - public static final AttributeKey OS_TYPE = stringKey("os.type"); - - /** - * Human readable (not intended to be parsed) OS version information, like e.g. reported by {@code - * ver} or {@code lsb_release -a} commands. - */ - public static final AttributeKey OS_DESCRIPTION = stringKey("os.description"); - - /** Human readable operating system name. */ - public static final AttributeKey OS_NAME = stringKey("os.name"); - - /** - * The version string of the operating system as defined in Version Attributes. - */ - public static final AttributeKey OS_VERSION = stringKey("os.version"); - - /** Process identifier (PID). */ - public static final AttributeKey PROCESS_PID = longKey("process.pid"); - - /** - * The name of the process executable. On Linux based systems, can be set to the {@code Name} in - * {@code proc/[pid]/status}. On Windows, can be set to the base name of {@code - * GetProcessImageFileNameW}. - */ - public static final AttributeKey PROCESS_EXECUTABLE_NAME = - stringKey("process.executable.name"); - - /** - * The full path to the process executable. On Linux based systems, can be set to the target of - * {@code proc/[pid]/exe}. On Windows, can be set to the result of {@code - * GetProcessImageFileNameW}. - */ - public static final AttributeKey PROCESS_EXECUTABLE_PATH = - stringKey("process.executable.path"); - - /** - * The command used to launch the process (i.e. the command name). On Linux based systems, can be - * set to the zeroth string in {@code proc/[pid]/cmdline}. On Windows, can be set to the first - * parameter extracted from {@code GetCommandLineW}. - */ - public static final AttributeKey PROCESS_COMMAND = stringKey("process.command"); - - /** - * The full command used to launch the process as a single string representing the full command. - * On Windows, can be set to the result of {@code GetCommandLineW}. Do not set this if you have to - * assemble it just for monitoring; use {@code process.command_args} instead. - */ - public static final AttributeKey PROCESS_COMMAND_LINE = stringKey("process.command_line"); - - /** - * All the command arguments (including the command/executable itself) as received by the process. - * On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according - * to the list of null-delimited strings extracted from {@code proc/[pid]/cmdline}. For libc-based - * executables, this would be the full argv vector passed to {@code main}. - */ - public static final AttributeKey> PROCESS_COMMAND_ARGS = - stringArrayKey("process.command_args"); - - /** The username of the user that owns the process. */ - public static final AttributeKey PROCESS_OWNER = stringKey("process.owner"); - - /** - * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name - * of the compiler. - */ - public static final AttributeKey PROCESS_RUNTIME_NAME = stringKey("process.runtime.name"); - - /** - * The version of the runtime of this process, as returned by the runtime without modification. - */ - public static final AttributeKey PROCESS_RUNTIME_VERSION = - stringKey("process.runtime.version"); - - /** - * An additional description about the runtime of the process, for example a specific vendor - * customization of the runtime environment. - */ - public static final AttributeKey PROCESS_RUNTIME_DESCRIPTION = - stringKey("process.runtime.description"); - - /** - * Logical name of the service. - * - *

      Notes: - * - *

        - *
      • MUST be the same for all instances of horizontally scaled services. If the value was not - * specified, SDKs MUST fallback to {@code unknown_service:} concatenated with {@code process.executable.name}, e.g. {@code - * unknown_service:bash}. If {@code process.executable.name} is not available, the value - * MUST be set to {@code unknown_service}. - *
      - */ - public static final AttributeKey SERVICE_NAME = stringKey("service.name"); - - /** - * A namespace for {@code service.name}. - * - *

      Notes: - * - *

        - *
      • A string value having a meaning that helps to distinguish a group of services, for - * example the team name that owns a group of services. {@code service.name} is expected to - * be unique within the same namespace. If {@code service.namespace} is not specified in the - * Resource then {@code service.name} is expected to be unique for all services that have no - * explicit namespace defined (so the empty/unspecified namespace is simply one more valid - * namespace). Zero-length namespace string is assumed equal to unspecified namespace. - *
      - */ - public static final AttributeKey SERVICE_NAMESPACE = stringKey("service.namespace"); - - /** - * The string ID of the service instance. - * - *

      Notes: - * - *

        - *
      • MUST be unique for each instance of the same {@code service.namespace,service.name} pair - * (in other words {@code service.namespace,service.name,service.instance.id} triplet MUST - * be globally unique). The ID helps to distinguish instances of the same service that exist - * at the same time (e.g. instances of a horizontally scaled service). It is preferable for - * the ID to be persistent and stay the same for the lifetime of the service instance, - * however it is acceptable that the ID is ephemeral and changes during important lifetime - * events for the service (e.g. service restarts). If the service has no inherent unique ID - * that can be used as the value of this attribute it is recommended to generate a random - * Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use - * Version 5, see RFC 4122 for more recommendations). - *
      - */ - public static final AttributeKey SERVICE_INSTANCE_ID = stringKey("service.instance.id"); - - /** The version string of the service API or implementation. */ - public static final AttributeKey SERVICE_VERSION = stringKey("service.version"); - - /** The name of the telemetry SDK as defined above. */ - public static final AttributeKey TELEMETRY_SDK_NAME = stringKey("telemetry.sdk.name"); - - /** The language of the telemetry SDK. */ - public static final AttributeKey TELEMETRY_SDK_LANGUAGE = - stringKey("telemetry.sdk.language"); - - /** The version string of the telemetry SDK. */ - public static final AttributeKey TELEMETRY_SDK_VERSION = - stringKey("telemetry.sdk.version"); - - /** The version string of the auto instrumentation agent, if used. */ - public static final AttributeKey TELEMETRY_AUTO_VERSION = - stringKey("telemetry.auto.version"); - - /** The name of the web engine. */ - public static final AttributeKey WEBENGINE_NAME = stringKey("webengine.name"); - - /** The version of the web engine. */ - public static final AttributeKey WEBENGINE_VERSION = stringKey("webengine.version"); - - /** Additional description of the web engine (e.g. detailed version and edition information). */ - public static final AttributeKey WEBENGINE_DESCRIPTION = - stringKey("webengine.description"); - - // Enum definitions - public static final class CloudProviderValues { - /** Alibaba Cloud. */ - public static final String ALIBABA_CLOUD = "alibaba_cloud"; - /** Amazon Web Services. */ - public static final String AWS = "aws"; - /** Microsoft Azure. */ - public static final String AZURE = "azure"; - /** Google Cloud Platform. */ - public static final String GCP = "gcp"; - /** Tencent Cloud. */ - public static final String TENCENT_CLOUD = "tencent_cloud"; - - private CloudProviderValues() {} - } - - public static final class CloudPlatformValues { - /** Alibaba Cloud Elastic Compute Service. */ - public static final String ALIBABA_CLOUD_ECS = "alibaba_cloud_ecs"; - /** Alibaba Cloud Function Compute. */ - public static final String ALIBABA_CLOUD_FC = "alibaba_cloud_fc"; - /** AWS Elastic Compute Cloud. */ - public static final String AWS_EC2 = "aws_ec2"; - /** AWS Elastic Container Service. */ - public static final String AWS_ECS = "aws_ecs"; - /** AWS Elastic Kubernetes Service. */ - public static final String AWS_EKS = "aws_eks"; - /** AWS Lambda. */ - public static final String AWS_LAMBDA = "aws_lambda"; - /** AWS Elastic Beanstalk. */ - public static final String AWS_ELASTIC_BEANSTALK = "aws_elastic_beanstalk"; - /** AWS App Runner. */ - public static final String AWS_APP_RUNNER = "aws_app_runner"; - /** Azure Virtual Machines. */ - public static final String AZURE_VM = "azure_vm"; - /** Azure Container Instances. */ - public static final String AZURE_CONTAINER_INSTANCES = "azure_container_instances"; - /** Azure Kubernetes Service. */ - public static final String AZURE_AKS = "azure_aks"; - /** Azure Functions. */ - public static final String AZURE_FUNCTIONS = "azure_functions"; - /** Azure App Service. */ - public static final String AZURE_APP_SERVICE = "azure_app_service"; - /** Google Cloud Compute Engine (GCE). */ - public static final String GCP_COMPUTE_ENGINE = "gcp_compute_engine"; - /** Google Cloud Run. */ - public static final String GCP_CLOUD_RUN = "gcp_cloud_run"; - /** Google Cloud Kubernetes Engine (GKE). */ - public static final String GCP_KUBERNETES_ENGINE = "gcp_kubernetes_engine"; - /** Google Cloud Functions (GCF). */ - public static final String GCP_CLOUD_FUNCTIONS = "gcp_cloud_functions"; - /** Google Cloud App Engine (GAE). */ - public static final String GCP_APP_ENGINE = "gcp_app_engine"; - /** Tencent Cloud Cloud Virtual Machine (CVM). */ - public static final String TENCENT_CLOUD_CVM = "tencent_cloud_cvm"; - /** Tencent Cloud Elastic Kubernetes Service (EKS). */ - public static final String TENCENT_CLOUD_EKS = "tencent_cloud_eks"; - /** Tencent Cloud Serverless Cloud Function (SCF). */ - public static final String TENCENT_CLOUD_SCF = "tencent_cloud_scf"; - - private CloudPlatformValues() {} - } - - public static final class AwsEcsLaunchtypeValues { - /** ec2. */ - public static final String EC2 = "ec2"; - /** fargate. */ - public static final String FARGATE = "fargate"; - - private AwsEcsLaunchtypeValues() {} - } - - public static final class HostArchValues { - /** AMD64. */ - public static final String AMD64 = "amd64"; - /** ARM32. */ - public static final String ARM32 = "arm32"; - /** ARM64. */ - public static final String ARM64 = "arm64"; - /** Itanium. */ - public static final String IA64 = "ia64"; - /** 32-bit PowerPC. */ - public static final String PPC32 = "ppc32"; - /** 64-bit PowerPC. */ - public static final String PPC64 = "ppc64"; - /** IBM z/Architecture. */ - public static final String S390X = "s390x"; - /** 32-bit x86. */ - public static final String X86 = "x86"; - - private HostArchValues() {} - } - - public static final class OsTypeValues { - /** Microsoft Windows. */ - public static final String WINDOWS = "windows"; - /** Linux. */ - public static final String LINUX = "linux"; - /** Apple Darwin. */ - public static final String DARWIN = "darwin"; - /** FreeBSD. */ - public static final String FREEBSD = "freebsd"; - /** NetBSD. */ - public static final String NETBSD = "netbsd"; - /** OpenBSD. */ - public static final String OPENBSD = "openbsd"; - /** DragonFly BSD. */ - public static final String DRAGONFLYBSD = "dragonflybsd"; - /** HP-UX (Hewlett Packard Unix). */ - public static final String HPUX = "hpux"; - /** AIX (Advanced Interactive eXecutive). */ - public static final String AIX = "aix"; - /** Oracle Solaris. */ - public static final String SOLARIS = "solaris"; - /** IBM z/OS. */ - public static final String Z_OS = "z_os"; - - private OsTypeValues() {} - } - - public static final class TelemetrySdkLanguageValues { - /** cpp. */ - public static final String CPP = "cpp"; - /** dotnet. */ - public static final String DOTNET = "dotnet"; - /** erlang. */ - public static final String ERLANG = "erlang"; - /** go. */ - public static final String GO = "go"; - /** java. */ - public static final String JAVA = "java"; - /** nodejs. */ - public static final String NODEJS = "nodejs"; - /** php. */ - public static final String PHP = "php"; - /** python. */ - public static final String PYTHON = "python"; - /** ruby. */ - public static final String RUBY = "ruby"; - /** webjs. */ - public static final String WEBJS = "webjs"; - /** swift. */ - public static final String SWIFT = "swift"; - - private TelemetrySdkLanguageValues() {} - } - - private ResourceAttributes() {} -} diff --git a/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/package-info.java b/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/package-info.java deleted file mode 100644 index d893dd794bf..00000000000 --- a/semconv/src/main/java/io/opentelemetry/semconv/resource/attributes/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * OpenTelemetry semantic attributes for resources. - * - * @see io.opentelemetry.semconv.resource.attributes.ResourceAttributes - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.semconv.resource.attributes; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/SemanticAttributes.java b/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/SemanticAttributes.java deleted file mode 100644 index 81021575889..00000000000 --- a/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/SemanticAttributes.java +++ /dev/null @@ -1,1271 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -package io.opentelemetry.semconv.trace.attributes; - -import static io.opentelemetry.api.common.AttributeKey.booleanKey; -import static io.opentelemetry.api.common.AttributeKey.doubleKey; -import static io.opentelemetry.api.common.AttributeKey.longKey; -import static io.opentelemetry.api.common.AttributeKey.stringArrayKey; -import static io.opentelemetry.api.common.AttributeKey.stringKey; - -import io.opentelemetry.api.common.AttributeKey; -import java.util.List; - -// DO NOT EDIT, this is an Auto-generated file from -// buildscripts/semantic-convention/templates/SemanticAttributes.java.j2 -public final class SemanticAttributes { - /** The URL of the OpenTelemetry schema for these keys and values. */ - public static final String SCHEMA_URL = "https://opentelemetry.io/schemas/1.9.0"; - - /** - * The full invoked ARN as provided on the {@code Context} passed to the function ({@code - * Lambda-Runtime-Invoked-Function-Arn} header on the {@code /runtime/invocation/next} - * applicable). - * - *

      Notes: - * - *

        - *
      • This may be different from {@code faas.id} if an alias is involved. - *
      - */ - public static final AttributeKey AWS_LAMBDA_INVOKED_ARN = - stringKey("aws.lambda.invoked_arn"); - - /** - * Parent-child Reference type - * - *

      Notes: - * - *

        - *
      • The causal relationship between a child Span and a parent Span. - *
      - */ - public static final AttributeKey OPENTRACING_REF_TYPE = stringKey("opentracing.ref_type"); - - /** - * An identifier for the database management system (DBMS) product being used. See below for a - * list of well-known identifiers. - */ - public static final AttributeKey DB_SYSTEM = stringKey("db.system"); - - /** - * The connection string used to connect to the database. It is recommended to remove embedded - * credentials. - */ - public static final AttributeKey DB_CONNECTION_STRING = stringKey("db.connection_string"); - - /** Username for accessing the database. */ - public static final AttributeKey DB_USER = stringKey("db.user"); - - /** - * The fully-qualified class name of the Java Database Connectivity - * (JDBC) driver used to connect. - */ - public static final AttributeKey DB_JDBC_DRIVER_CLASSNAME = - stringKey("db.jdbc.driver_classname"); - - /** - * This attribute is used to report the name of the database being accessed. For commands that - * switch the database, this should be set to the target database (even if the command fails). - * - *

      Notes: - * - *

        - *
      • In some SQL databases, the database name to be used is called "schema name". In - * case there are multiple layers that could be considered for database name (e.g. Oracle - * instance name and schema name), the database name to be used is the more specific layer - * (e.g. Oracle schema name). - *
      - */ - public static final AttributeKey DB_NAME = stringKey("db.name"); - - /** - * The database statement being executed. - * - *

      Notes: - * - *

        - *
      • The value may be sanitized to exclude sensitive information. - *
      - */ - public static final AttributeKey DB_STATEMENT = stringKey("db.statement"); - - /** - * The name of the operation being executed, e.g. the MongoDB command - * name such as {@code findAndModify}, or the SQL keyword. - * - *

      Notes: - * - *

        - *
      • When setting this to an SQL keyword, it is not recommended to attempt any client-side - * parsing of {@code db.statement} just to get this property, but it should be set if the - * operation name is provided by the library being instrumented. If the SQL statement has an - * ambiguous operation, or performs more than one operation, this value may be omitted. - *
      - */ - public static final AttributeKey DB_OPERATION = stringKey("db.operation"); - - /** - * The Microsoft SQL Server instance - * name connecting to. This name is used to determine the port of a named instance. - * - *

      Notes: - * - *

        - *
      • If setting a {@code db.mssql.instance_name}, {@code net.peer.port} is no longer required - * (but still recommended if non-standard). - *
      - */ - public static final AttributeKey DB_MSSQL_INSTANCE_NAME = - stringKey("db.mssql.instance_name"); - - /** The fetch size used for paging, i.e. how many rows will be returned at once. */ - public static final AttributeKey DB_CASSANDRA_PAGE_SIZE = longKey("db.cassandra.page_size"); - - /** - * The consistency level of the query. Based on consistency values from CQL. - */ - public static final AttributeKey DB_CASSANDRA_CONSISTENCY_LEVEL = - stringKey("db.cassandra.consistency_level"); - - /** - * The name of the primary table that the operation is acting upon, including the keyspace name - * (if applicable). - * - *

      Notes: - * - *

        - *
      • This mirrors the db.sql.table attribute but references cassandra rather than sql. It is - * not recommended to attempt any client-side parsing of {@code db.statement} just to get - * this property, but it should be set if it is provided by the library being instrumented. - * If the operation is acting upon an anonymous table, or more than one table, this value - * MUST NOT be set. - *
      - */ - public static final AttributeKey DB_CASSANDRA_TABLE = stringKey("db.cassandra.table"); - - /** Whether or not the query is idempotent. */ - public static final AttributeKey DB_CASSANDRA_IDEMPOTENCE = - booleanKey("db.cassandra.idempotence"); - - /** - * The number of times a query was speculatively executed. Not set or {@code 0} if the query was - * not executed speculatively. - */ - public static final AttributeKey DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = - longKey("db.cassandra.speculative_execution_count"); - - /** The ID of the coordinating node for a query. */ - public static final AttributeKey DB_CASSANDRA_COORDINATOR_ID = - stringKey("db.cassandra.coordinator.id"); - - /** The data center of the coordinating node for a query. */ - public static final AttributeKey DB_CASSANDRA_COORDINATOR_DC = - stringKey("db.cassandra.coordinator.dc"); - - /** - * The index of the database being accessed as used in the {@code SELECT} command, provided as an integer. To - * be used instead of the generic {@code db.name} attribute. - */ - public static final AttributeKey DB_REDIS_DATABASE_INDEX = - longKey("db.redis.database_index"); - - /** The collection being accessed within the database stated in {@code db.name}. */ - public static final AttributeKey DB_MONGODB_COLLECTION = - stringKey("db.mongodb.collection"); - - /** - * The name of the primary table that the operation is acting upon, including the database name - * (if applicable). - * - *

      Notes: - * - *

        - *
      • It is not recommended to attempt any client-side parsing of {@code db.statement} just to - * get this property, but it should be set if it is provided by the library being - * instrumented. If the operation is acting upon an anonymous table, or more than one table, - * this value MUST NOT be set. - *
      - */ - public static final AttributeKey DB_SQL_TABLE = stringKey("db.sql.table"); - - /** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of - * the exception should be preferred over the static type in languages that support it. - */ - public static final AttributeKey EXCEPTION_TYPE = stringKey("exception.type"); - - /** The exception message. */ - public static final AttributeKey EXCEPTION_MESSAGE = stringKey("exception.message"); - - /** - * A stacktrace as a string in the natural representation for the language runtime. The - * representation is to be determined and documented by each language SIG. - */ - public static final AttributeKey EXCEPTION_STACKTRACE = stringKey("exception.stacktrace"); - - /** - * SHOULD be set to true if the exception event is recorded at a point where it is known that the - * exception is escaping the scope of the span. - * - *

      Notes: - * - *

        - *
      • An exception is considered to have escaped (or left) the scope of a span, if that span is - * ended while the exception is still logically "in flight". This may be actually - * "in flight" in some languages (e.g. if the exception is passed to a Context - * manager's {@code __exit__} method in Python) but will usually be caught at the point of - * recording the exception in most languages. - *
      • It is usually not possible to determine at the point where an exception is thrown whether - * it will escape the scope of a span. However, it is trivial to know that an exception will - * escape, if one checks for an active exception just before ending the span, as done in the - * example above. - *
      • It follows that an exception may still escape the scope of the span even if the {@code - * exception.escaped} attribute was not set or set to false, since the event might have been - * recorded at a time where it was not clear whether the exception will escape. - *
      - */ - public static final AttributeKey EXCEPTION_ESCAPED = booleanKey("exception.escaped"); - - /** - * Type of the trigger which caused this function execution. - * - *

      Notes: - * - *

        - *
      • For the server/consumer span on the incoming side, {@code faas.trigger} MUST be set. - *
      • Clients invoking FaaS instances usually cannot set {@code faas.trigger}, since they would - * typically need to look in the payload to determine the event type. If clients set it, it - * should be the same as the trigger that corresponding incoming would have (i.e., this has - * nothing to do with the underlying transport used to make the API call to invoke the - * lambda, which is often HTTP). - *
      - */ - public static final AttributeKey FAAS_TRIGGER = stringKey("faas.trigger"); - - /** The execution ID of the current function execution. */ - public static final AttributeKey FAAS_EXECUTION = stringKey("faas.execution"); - - /** - * The name of the source on which the triggering operation was performed. For example, in Cloud - * Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. - */ - public static final AttributeKey FAAS_DOCUMENT_COLLECTION = - stringKey("faas.document.collection"); - - /** Describes the type of the operation that was performed on the data. */ - public static final AttributeKey FAAS_DOCUMENT_OPERATION = - stringKey("faas.document.operation"); - - /** - * A string containing the time when the data was accessed in the ISO 8601 format expressed in - * UTC. - */ - public static final AttributeKey FAAS_DOCUMENT_TIME = stringKey("faas.document.time"); - - /** - * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the - * name of the file, and in Cosmos DB the table name. - */ - public static final AttributeKey FAAS_DOCUMENT_NAME = stringKey("faas.document.name"); - - /** - * A string containing the function invocation time in the ISO 8601 format expressed in - * UTC. - */ - public static final AttributeKey FAAS_TIME = stringKey("faas.time"); - - /** - * A string containing the schedule period as Cron - * Expression. - */ - public static final AttributeKey FAAS_CRON = stringKey("faas.cron"); - - /** - * A boolean that is true if the serverless function is executed for the first time (aka - * cold-start). - */ - public static final AttributeKey FAAS_COLDSTART = booleanKey("faas.coldstart"); - - /** - * The name of the invoked function. - * - *

      Notes: - * - *

        - *
      • SHOULD be equal to the {@code faas.name} resource attribute of the invoked function. - *
      - */ - public static final AttributeKey FAAS_INVOKED_NAME = stringKey("faas.invoked_name"); - - /** - * The cloud provider of the invoked function. - * - *

      Notes: - * - *

        - *
      • SHOULD be equal to the {@code cloud.provider} resource attribute of the invoked function. - *
      - */ - public static final AttributeKey FAAS_INVOKED_PROVIDER = - stringKey("faas.invoked_provider"); - - /** - * The cloud region of the invoked function. - * - *

      Notes: - * - *

        - *
      • SHOULD be equal to the {@code cloud.region} resource attribute of the invoked function. - *
      - */ - public static final AttributeKey FAAS_INVOKED_REGION = stringKey("faas.invoked_region"); - - /** Transport protocol used. See note below. */ - public static final AttributeKey NET_TRANSPORT = stringKey("net.transport"); - - /** - * Remote address of the peer (dotted decimal for IPv4 or RFC5952 for IPv6) - */ - public static final AttributeKey NET_PEER_IP = stringKey("net.peer.ip"); - - /** Remote port number. */ - public static final AttributeKey NET_PEER_PORT = longKey("net.peer.port"); - - /** Remote hostname or similar, see note below. */ - public static final AttributeKey NET_PEER_NAME = stringKey("net.peer.name"); - - /** Like {@code net.peer.ip} but for the host IP. Useful in case of a multi-IP host. */ - public static final AttributeKey NET_HOST_IP = stringKey("net.host.ip"); - - /** Like {@code net.peer.port} but for the host port. */ - public static final AttributeKey NET_HOST_PORT = longKey("net.host.port"); - - /** Local hostname or similar, see note below. */ - public static final AttributeKey NET_HOST_NAME = stringKey("net.host.name"); - - /** The internet connection type currently being used by the host. */ - public static final AttributeKey NET_HOST_CONNECTION_TYPE = - stringKey("net.host.connection.type"); - - /** - * This describes more details regarding the connection.type. It may be the type of cell - * technology connection, but it could be used for describing details about a wifi connection. - */ - public static final AttributeKey NET_HOST_CONNECTION_SUBTYPE = - stringKey("net.host.connection.subtype"); - - /** The name of the mobile carrier. */ - public static final AttributeKey NET_HOST_CARRIER_NAME = - stringKey("net.host.carrier.name"); - - /** The mobile carrier country code. */ - public static final AttributeKey NET_HOST_CARRIER_MCC = stringKey("net.host.carrier.mcc"); - - /** The mobile carrier network code. */ - public static final AttributeKey NET_HOST_CARRIER_MNC = stringKey("net.host.carrier.mnc"); - - /** The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. */ - public static final AttributeKey NET_HOST_CARRIER_ICC = stringKey("net.host.carrier.icc"); - - /** - * The {@code service.name} of - * the remote service. SHOULD be equal to the actual {@code service.name} resource attribute of - * the remote service if any. - */ - public static final AttributeKey PEER_SERVICE = stringKey("peer.service"); - - /** - * Username or client_id extracted from the access token or Authorization header in the inbound - * request from outside the system. - */ - public static final AttributeKey ENDUSER_ID = stringKey("enduser.id"); - - /** - * Actual/assumed role the client is making the request under extracted from token or application - * security context. - */ - public static final AttributeKey ENDUSER_ROLE = stringKey("enduser.role"); - - /** - * Scopes or granted authorities the client currently possesses extracted from token or - * application security context. The value would come from the scope associated with an OAuth 2.0 Access Token or an - * attribute value in a SAML - * 2.0 Assertion. - */ - public static final AttributeKey ENDUSER_SCOPE = stringKey("enduser.scope"); - - /** Current "managed" thread ID (as opposed to OS thread ID). */ - public static final AttributeKey THREAD_ID = longKey("thread.id"); - - /** Current thread name. */ - public static final AttributeKey THREAD_NAME = stringKey("thread.name"); - - /** - * The method or function name, or equivalent (usually rightmost part of the code unit's name). - */ - public static final AttributeKey CODE_FUNCTION = stringKey("code.function"); - - /** - * The "namespace" within which {@code code.function} is defined. Usually the qualified - * class or module name, such that {@code code.namespace} + some separator + {@code code.function} - * form a unique identifier for the code unit. - */ - public static final AttributeKey CODE_NAMESPACE = stringKey("code.namespace"); - - /** - * The source code file name that identifies the code unit as uniquely as possible (preferably an - * absolute file path). - */ - public static final AttributeKey CODE_FILEPATH = stringKey("code.filepath"); - - /** - * The line number in {@code code.filepath} best representing the operation. It SHOULD point - * within the code unit named in {@code code.function}. - */ - public static final AttributeKey CODE_LINENO = longKey("code.lineno"); - - /** HTTP request method. */ - public static final AttributeKey HTTP_METHOD = stringKey("http.method"); - - /** - * Full HTTP request URL in the form {@code scheme://host[:port]/path?query[#fragment]}. Usually - * the fragment is not transmitted over HTTP, but if it is known, it should be included - * nevertheless. - * - *

      Notes: - * - *

        - *
      • {@code http.url} MUST NOT contain credentials passed via URL in form of {@code - * https://username:password@www.example.com/}. In such case the attribute's value should be - * {@code https://www.example.com/}. - *
      - */ - public static final AttributeKey HTTP_URL = stringKey("http.url"); - - /** The full request target as passed in a HTTP request line or equivalent. */ - public static final AttributeKey HTTP_TARGET = stringKey("http.target"); - - /** - * The value of the HTTP host - * header. An empty Host header should also be reported, see note. - * - *

      Notes: - * - *

        - *
      • When the header is present but empty the attribute SHOULD be set to the empty string. - * Note that this is a valid situation that is expected in certain cases, according the - * aforementioned section of RFC - * 7230. When the header is not set the attribute MUST NOT be set. - *
      - */ - public static final AttributeKey HTTP_HOST = stringKey("http.host"); - - /** The URI scheme identifying the used protocol. */ - public static final AttributeKey HTTP_SCHEME = stringKey("http.scheme"); - - /** HTTP response status code. */ - public static final AttributeKey HTTP_STATUS_CODE = longKey("http.status_code"); - - /** - * Kind of HTTP protocol used. - * - *

      Notes: - * - *

        - *
      • If {@code net.transport} is not specified, it can be assumed to be {@code IP.TCP} except - * if {@code http.flavor} is {@code QUIC}, in which case {@code IP.UDP} is assumed. - *
      - */ - public static final AttributeKey HTTP_FLAVOR = stringKey("http.flavor"); - - /** - * Value of the HTTP User-Agent - * header sent by the client. - */ - public static final AttributeKey HTTP_USER_AGENT = stringKey("http.user_agent"); - - /** - * The size of the request payload body in bytes. This is the number of bytes transferred - * excluding headers and is often, but not always, present as the Content-Length header. For - * requests using transport encoding, this should be the compressed size. - */ - public static final AttributeKey HTTP_REQUEST_CONTENT_LENGTH = - longKey("http.request_content_length"); - - /** - * The size of the uncompressed request payload body after transport decoding. Not set if - * transport encoding not used. - */ - public static final AttributeKey HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = - longKey("http.request_content_length_uncompressed"); - - /** - * The size of the response payload body in bytes. This is the number of bytes transferred - * excluding headers and is often, but not always, present as the Content-Length header. For - * requests using transport encoding, this should be the compressed size. - */ - public static final AttributeKey HTTP_RESPONSE_CONTENT_LENGTH = - longKey("http.response_content_length"); - - /** - * The size of the uncompressed response payload body after transport decoding. Not set if - * transport encoding not used. - */ - public static final AttributeKey HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = - longKey("http.response_content_length_uncompressed"); - - /** - * The primary server name of the matched virtual host. This should be obtained via configuration. - * If no such configuration can be obtained, this attribute MUST NOT be set ( {@code - * net.host.name} should be used instead). - * - *

      Notes: - * - *

        - *
      • {@code http.url} is usually not readily available on the server side but would have to be - * assembled in a cumbersome and sometimes lossy process from other information (see e.g. - * open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw - * data that is available. - *
      - */ - public static final AttributeKey HTTP_SERVER_NAME = stringKey("http.server_name"); - - /** The matched route (path template). */ - public static final AttributeKey HTTP_ROUTE = stringKey("http.route"); - - /** - * The IP address of the original client behind all proxies, if known (e.g. from X-Forwarded-For). - * - *

      Notes: - * - *

        - *
      • This is not necessarily the same as {@code net.peer.ip}, which would identify the - * network-level peer, which may be a proxy. - *
      • This attribute should be set when a source of information different from the one used for - * {@code net.peer.ip}, is available even if that other source just confirms the same value - * as {@code net.peer.ip}. Rationale: For {@code net.peer.ip}, one typically does not know - * if it comes from a proxy, reverse proxy, or the actual client. Setting {@code - * http.client_ip} when it's the same as {@code net.peer.ip} means that one is at least - * somewhat confident that the address is not that of the closest proxy. - *
      - */ - public static final AttributeKey HTTP_CLIENT_IP = stringKey("http.client_ip"); - - /** The keys in the {@code RequestItems} object field. */ - public static final AttributeKey> AWS_DYNAMODB_TABLE_NAMES = - stringArrayKey("aws.dynamodb.table_names"); - - /** The JSON-serialized value of each item in the {@code ConsumedCapacity} response field. */ - public static final AttributeKey> AWS_DYNAMODB_CONSUMED_CAPACITY = - stringArrayKey("aws.dynamodb.consumed_capacity"); - - /** The JSON-serialized value of the {@code ItemCollectionMetrics} response field. */ - public static final AttributeKey AWS_DYNAMODB_ITEM_COLLECTION_METRICS = - stringKey("aws.dynamodb.item_collection_metrics"); - - /** The value of the {@code ProvisionedThroughput.ReadCapacityUnits} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = - doubleKey("aws.dynamodb.provisioned_read_capacity"); - - /** The value of the {@code ProvisionedThroughput.WriteCapacityUnits} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = - doubleKey("aws.dynamodb.provisioned_write_capacity"); - - /** The value of the {@code ConsistentRead} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_CONSISTENT_READ = - booleanKey("aws.dynamodb.consistent_read"); - - /** The value of the {@code ProjectionExpression} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_PROJECTION = - stringKey("aws.dynamodb.projection"); - - /** The value of the {@code Limit} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_LIMIT = longKey("aws.dynamodb.limit"); - - /** The value of the {@code AttributesToGet} request parameter. */ - public static final AttributeKey> AWS_DYNAMODB_ATTRIBUTES_TO_GET = - stringArrayKey("aws.dynamodb.attributes_to_get"); - - /** The value of the {@code IndexName} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_INDEX_NAME = - stringKey("aws.dynamodb.index_name"); - - /** The value of the {@code Select} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_SELECT = stringKey("aws.dynamodb.select"); - - /** The JSON-serialized value of each item of the {@code GlobalSecondaryIndexes} request field */ - public static final AttributeKey> AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = - stringArrayKey("aws.dynamodb.global_secondary_indexes"); - - /** The JSON-serialized value of each item of the {@code LocalSecondaryIndexes} request field. */ - public static final AttributeKey> AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = - stringArrayKey("aws.dynamodb.local_secondary_indexes"); - - /** The value of the {@code ExclusiveStartTableName} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_EXCLUSIVE_START_TABLE = - stringKey("aws.dynamodb.exclusive_start_table"); - - /** The the number of items in the {@code TableNames} response parameter. */ - public static final AttributeKey AWS_DYNAMODB_TABLE_COUNT = - longKey("aws.dynamodb.table_count"); - - /** The value of the {@code ScanIndexForward} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_SCAN_FORWARD = - booleanKey("aws.dynamodb.scan_forward"); - - /** The value of the {@code Segment} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_SEGMENT = longKey("aws.dynamodb.segment"); - - /** The value of the {@code TotalSegments} request parameter. */ - public static final AttributeKey AWS_DYNAMODB_TOTAL_SEGMENTS = - longKey("aws.dynamodb.total_segments"); - - /** The value of the {@code Count} response parameter. */ - public static final AttributeKey AWS_DYNAMODB_COUNT = longKey("aws.dynamodb.count"); - - /** The value of the {@code ScannedCount} response parameter. */ - public static final AttributeKey AWS_DYNAMODB_SCANNED_COUNT = - longKey("aws.dynamodb.scanned_count"); - - /** The JSON-serialized value of each item in the {@code AttributeDefinitions} request field. */ - public static final AttributeKey> AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = - stringArrayKey("aws.dynamodb.attribute_definitions"); - - /** - * The JSON-serialized value of each item in the the {@code GlobalSecondaryIndexUpdates} request - * field. - */ - public static final AttributeKey> AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = - stringArrayKey("aws.dynamodb.global_secondary_index_updates"); - - /** A string identifying the messaging system. */ - public static final AttributeKey MESSAGING_SYSTEM = stringKey("messaging.system"); - - /** - * The message destination name. This might be equal to the span name but is required - * nevertheless. - */ - public static final AttributeKey MESSAGING_DESTINATION = - stringKey("messaging.destination"); - - /** The kind of message destination */ - public static final AttributeKey MESSAGING_DESTINATION_KIND = - stringKey("messaging.destination_kind"); - - /** A boolean that is true if the message destination is temporary. */ - public static final AttributeKey MESSAGING_TEMP_DESTINATION = - booleanKey("messaging.temp_destination"); - - /** The name of the transport protocol. */ - public static final AttributeKey MESSAGING_PROTOCOL = stringKey("messaging.protocol"); - - /** The version of the transport protocol. */ - public static final AttributeKey MESSAGING_PROTOCOL_VERSION = - stringKey("messaging.protocol_version"); - - /** Connection string. */ - public static final AttributeKey MESSAGING_URL = stringKey("messaging.url"); - - /** - * A value used by the messaging system as an identifier for the message, represented as a string. - */ - public static final AttributeKey MESSAGING_MESSAGE_ID = stringKey("messaging.message_id"); - - /** - * The conversation ID identifying the conversation to which the - * message belongs, represented as a string. Sometimes called "Correlation ID". - */ - public static final AttributeKey MESSAGING_CONVERSATION_ID = - stringKey("messaging.conversation_id"); - - /** - * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is - * unknown whether the compressed or uncompressed payload size is reported. - */ - public static final AttributeKey MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = - longKey("messaging.message_payload_size_bytes"); - - /** The compressed size of the message payload in bytes. */ - public static final AttributeKey MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = - longKey("messaging.message_payload_compressed_size_bytes"); - - /** - * A string identifying the kind of message consumption as defined in the Operation names section above. If the operation is - * "send", this attribute MUST NOT be set, since the operation can be inferred from the - * span kind in that case. - */ - public static final AttributeKey MESSAGING_OPERATION = stringKey("messaging.operation"); - - /** - * The identifier for the consumer receiving a message. For Kafka, set it to {@code - * {messaging.kafka.consumer_group} - {messaging.kafka.client_id}}, if both are present, or only - * {@code messaging.kafka.consumer_group}. For brokers, such as RabbitMQ and Artemis, set it to - * the {@code client_id} of the client consuming the message. - */ - public static final AttributeKey MESSAGING_CONSUMER_ID = - stringKey("messaging.consumer_id"); - - /** RabbitMQ message routing key. */ - public static final AttributeKey MESSAGING_RABBITMQ_ROUTING_KEY = - stringKey("messaging.rabbitmq.routing_key"); - - /** - * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the - * same partition. They differ from {@code messaging.message_id} in that they're not unique. If - * the key is {@code null}, the attribute MUST NOT be set. - * - *

      Notes: - * - *

        - *
      • If the key type is not string, it's string representation has to be supplied for the - * attribute. If the key has no unambiguous, canonical string form, don't include its value. - *
      - */ - public static final AttributeKey MESSAGING_KAFKA_MESSAGE_KEY = - stringKey("messaging.kafka.message_key"); - - /** - * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not - * producers. - */ - public static final AttributeKey MESSAGING_KAFKA_CONSUMER_GROUP = - stringKey("messaging.kafka.consumer_group"); - - /** Client Id for the Consumer or Producer that is handling the message. */ - public static final AttributeKey MESSAGING_KAFKA_CLIENT_ID = - stringKey("messaging.kafka.client_id"); - - /** Partition the message is sent to. */ - public static final AttributeKey MESSAGING_KAFKA_PARTITION = - longKey("messaging.kafka.partition"); - - /** A boolean that is true if the message is a tombstone. */ - public static final AttributeKey MESSAGING_KAFKA_TOMBSTONE = - booleanKey("messaging.kafka.tombstone"); - - /** Namespace of RocketMQ resources, resources in different namespaces are individual. */ - public static final AttributeKey MESSAGING_ROCKETMQ_NAMESPACE = - stringKey("messaging.rocketmq.namespace"); - - /** - * Name of the RocketMQ producer/consumer group that is handling the message. The client type is - * identified by the SpanKind. - */ - public static final AttributeKey MESSAGING_ROCKETMQ_CLIENT_GROUP = - stringKey("messaging.rocketmq.client_group"); - - /** The unique identifier for each client. */ - public static final AttributeKey MESSAGING_ROCKETMQ_CLIENT_ID = - stringKey("messaging.rocketmq.client_id"); - - /** Type of message. */ - public static final AttributeKey MESSAGING_ROCKETMQ_MESSAGE_TYPE = - stringKey("messaging.rocketmq.message_type"); - - /** The secondary classifier of message besides topic. */ - public static final AttributeKey MESSAGING_ROCKETMQ_MESSAGE_TAG = - stringKey("messaging.rocketmq.message_tag"); - - /** Key(s) of message, another way to mark message besides message id. */ - public static final AttributeKey> MESSAGING_ROCKETMQ_MESSAGE_KEYS = - stringArrayKey("messaging.rocketmq.message_keys"); - - /** Model of message consumption. This only applies to consumer spans. */ - public static final AttributeKey MESSAGING_ROCKETMQ_CONSUMPTION_MODEL = - stringKey("messaging.rocketmq.consumption_model"); - - /** A string identifying the remoting system. */ - public static final AttributeKey RPC_SYSTEM = stringKey("rpc.system"); - - /** - * The full (logical) name of the service being called, including its package name, if applicable. - * - *

      Notes: - * - *

        - *
      • This is the logical name of the service from the RPC interface perspective, which can be - * different from the name of any implementing class. The {@code code.namespace} attribute - * may be used to store the latter (despite the attribute name, it may include a class name; - * e.g., class with method actually executing the call on the server side, RPC client stub - * class on the client side). - *
      - */ - public static final AttributeKey RPC_SERVICE = stringKey("rpc.service"); - - /** - * The name of the (logical) method being called, must be equal to the $method part in the span - * name. - * - *

      Notes: - * - *

        - *
      • This is the logical name of the method from the RPC interface perspective, which can be - * different from the name of any implementing method/function. The {@code code.function} - * attribute may be used to store the latter (e.g., method actually executing the call on - * the server side, RPC client stub method on the client side). - *
      - */ - public static final AttributeKey RPC_METHOD = stringKey("rpc.method"); - - /** - * The numeric status - * code of the gRPC request. - */ - public static final AttributeKey RPC_GRPC_STATUS_CODE = longKey("rpc.grpc.status_code"); - - /** - * Protocol version as in {@code jsonrpc} property of request/response. Since JSON-RPC 1.0 does - * not specify this, the value can be omitted. - */ - public static final AttributeKey RPC_JSONRPC_VERSION = stringKey("rpc.jsonrpc.version"); - - /** - * {@code id} property of request or response. Since protocol allows id to be int, string, {@code - * null} or missing (for notifications), value is expected to be cast to string for simplicity. - * Use empty string in case of {@code null} value. Omit entirely if this is a notification. - */ - public static final AttributeKey RPC_JSONRPC_REQUEST_ID = - stringKey("rpc.jsonrpc.request_id"); - - /** {@code error.code} property of response if it is an error response. */ - public static final AttributeKey RPC_JSONRPC_ERROR_CODE = longKey("rpc.jsonrpc.error_code"); - - /** {@code error.message} property of response if it is an error response. */ - public static final AttributeKey RPC_JSONRPC_ERROR_MESSAGE = - stringKey("rpc.jsonrpc.error_message"); - - /** Whether this is a received or sent message. */ - public static final AttributeKey MESSAGE_TYPE = stringKey("message.type"); - - /** - * MUST be calculated as two different counters starting from {@code 1} one for sent messages and - * one for received message. - * - *

      Notes: - * - *

        - *
      • This way we guarantee that the values will be consistent between different - * implementations. - *
      - */ - public static final AttributeKey MESSAGE_ID = longKey("message.id"); - - /** Compressed size of the message in bytes. */ - public static final AttributeKey MESSAGE_COMPRESSED_SIZE = - longKey("message.compressed_size"); - - /** Uncompressed size of the message in bytes. */ - public static final AttributeKey MESSAGE_UNCOMPRESSED_SIZE = - longKey("message.uncompressed_size"); - - // Enum definitions - public static final class OpentracingRefTypeValues { - /** The parent Span depends on the child Span in some capacity. */ - public static final String CHILD_OF = "child_of"; - /** The parent Span does not depend in any way on the result of the child Span. */ - public static final String FOLLOWS_FROM = "follows_from"; - - private OpentracingRefTypeValues() {} - } - - public static final class DbSystemValues { - /** Some other SQL database. Fallback only. See notes. */ - public static final String OTHER_SQL = "other_sql"; - /** Microsoft SQL Server. */ - public static final String MSSQL = "mssql"; - /** MySQL. */ - public static final String MYSQL = "mysql"; - /** Oracle Database. */ - public static final String ORACLE = "oracle"; - /** IBM Db2. */ - public static final String DB2 = "db2"; - /** PostgreSQL. */ - public static final String POSTGRESQL = "postgresql"; - /** Amazon Redshift. */ - public static final String REDSHIFT = "redshift"; - /** Apache Hive. */ - public static final String HIVE = "hive"; - /** Cloudscape. */ - public static final String CLOUDSCAPE = "cloudscape"; - /** HyperSQL DataBase. */ - public static final String HSQLDB = "hsqldb"; - /** Progress Database. */ - public static final String PROGRESS = "progress"; - /** SAP MaxDB. */ - public static final String MAXDB = "maxdb"; - /** SAP HANA. */ - public static final String HANADB = "hanadb"; - /** Ingres. */ - public static final String INGRES = "ingres"; - /** FirstSQL. */ - public static final String FIRSTSQL = "firstsql"; - /** EnterpriseDB. */ - public static final String EDB = "edb"; - /** InterSystems CachΓ©. */ - public static final String CACHE = "cache"; - /** Adabas (Adaptable Database System). */ - public static final String ADABAS = "adabas"; - /** Firebird. */ - public static final String FIREBIRD = "firebird"; - /** Apache Derby. */ - public static final String DERBY = "derby"; - /** FileMaker. */ - public static final String FILEMAKER = "filemaker"; - /** Informix. */ - public static final String INFORMIX = "informix"; - /** InstantDB. */ - public static final String INSTANTDB = "instantdb"; - /** InterBase. */ - public static final String INTERBASE = "interbase"; - /** MariaDB. */ - public static final String MARIADB = "mariadb"; - /** Netezza. */ - public static final String NETEZZA = "netezza"; - /** Pervasive PSQL. */ - public static final String PERVASIVE = "pervasive"; - /** PointBase. */ - public static final String POINTBASE = "pointbase"; - /** SQLite. */ - public static final String SQLITE = "sqlite"; - /** Sybase. */ - public static final String SYBASE = "sybase"; - /** Teradata. */ - public static final String TERADATA = "teradata"; - /** Vertica. */ - public static final String VERTICA = "vertica"; - /** H2. */ - public static final String H2 = "h2"; - /** ColdFusion IMQ. */ - public static final String COLDFUSION = "coldfusion"; - /** Apache Cassandra. */ - public static final String CASSANDRA = "cassandra"; - /** Apache HBase. */ - public static final String HBASE = "hbase"; - /** MongoDB. */ - public static final String MONGODB = "mongodb"; - /** Redis. */ - public static final String REDIS = "redis"; - /** Couchbase. */ - public static final String COUCHBASE = "couchbase"; - /** CouchDB. */ - public static final String COUCHDB = "couchdb"; - /** Microsoft Azure Cosmos DB. */ - public static final String COSMOSDB = "cosmosdb"; - /** Amazon DynamoDB. */ - public static final String DYNAMODB = "dynamodb"; - /** Neo4j. */ - public static final String NEO4J = "neo4j"; - /** Apache Geode. */ - public static final String GEODE = "geode"; - /** Elasticsearch. */ - public static final String ELASTICSEARCH = "elasticsearch"; - /** Memcached. */ - public static final String MEMCACHED = "memcached"; - /** CockroachDB. */ - public static final String COCKROACHDB = "cockroachdb"; - - private DbSystemValues() {} - } - - public static final class DbCassandraConsistencyLevelValues { - /** all. */ - public static final String ALL = "all"; - /** each_quorum. */ - public static final String EACH_QUORUM = "each_quorum"; - /** quorum. */ - public static final String QUORUM = "quorum"; - /** local_quorum. */ - public static final String LOCAL_QUORUM = "local_quorum"; - /** one. */ - public static final String ONE = "one"; - /** two. */ - public static final String TWO = "two"; - /** three. */ - public static final String THREE = "three"; - /** local_one. */ - public static final String LOCAL_ONE = "local_one"; - /** any. */ - public static final String ANY = "any"; - /** serial. */ - public static final String SERIAL = "serial"; - /** local_serial. */ - public static final String LOCAL_SERIAL = "local_serial"; - - private DbCassandraConsistencyLevelValues() {} - } - - public static final class FaasTriggerValues { - /** A response to some data source operation such as a database or filesystem read/write. */ - public static final String DATASOURCE = "datasource"; - /** To provide an answer to an inbound HTTP request. */ - public static final String HTTP = "http"; - /** A function is set to be executed when messages are sent to a messaging system. */ - public static final String PUBSUB = "pubsub"; - /** A function is scheduled to be executed regularly. */ - public static final String TIMER = "timer"; - /** If none of the others apply. */ - public static final String OTHER = "other"; - - private FaasTriggerValues() {} - } - - public static final class FaasDocumentOperationValues { - /** When a new object is created. */ - public static final String INSERT = "insert"; - /** When an object is modified. */ - public static final String EDIT = "edit"; - /** When an object is deleted. */ - public static final String DELETE = "delete"; - - private FaasDocumentOperationValues() {} - } - - public static final class FaasInvokedProviderValues { - /** Alibaba Cloud. */ - public static final String ALIBABA_CLOUD = "alibaba_cloud"; - /** Amazon Web Services. */ - public static final String AWS = "aws"; - /** Microsoft Azure. */ - public static final String AZURE = "azure"; - /** Google Cloud Platform. */ - public static final String GCP = "gcp"; - /** Tencent Cloud. */ - public static final String TENCENT_CLOUD = "tencent_cloud"; - - private FaasInvokedProviderValues() {} - } - - public static final class NetTransportValues { - /** ip_tcp. */ - public static final String IP_TCP = "ip_tcp"; - /** ip_udp. */ - public static final String IP_UDP = "ip_udp"; - /** Another IP-based protocol. */ - public static final String IP = "ip"; - /** Unix Domain socket. See below. */ - public static final String UNIX = "unix"; - /** Named or anonymous pipe. See note below. */ - public static final String PIPE = "pipe"; - /** In-process communication. */ - public static final String INPROC = "inproc"; - /** Something else (non IP-based). */ - public static final String OTHER = "other"; - - private NetTransportValues() {} - } - - public static final class NetHostConnectionTypeValues { - /** wifi. */ - public static final String WIFI = "wifi"; - /** wired. */ - public static final String WIRED = "wired"; - /** cell. */ - public static final String CELL = "cell"; - /** unavailable. */ - public static final String UNAVAILABLE = "unavailable"; - /** unknown. */ - public static final String UNKNOWN = "unknown"; - - private NetHostConnectionTypeValues() {} - } - - public static final class NetHostConnectionSubtypeValues { - /** GPRS. */ - public static final String GPRS = "gprs"; - /** EDGE. */ - public static final String EDGE = "edge"; - /** UMTS. */ - public static final String UMTS = "umts"; - /** CDMA. */ - public static final String CDMA = "cdma"; - /** EVDO Rel. 0. */ - public static final String EVDO_0 = "evdo_0"; - /** EVDO Rev. A. */ - public static final String EVDO_A = "evdo_a"; - /** CDMA2000 1XRTT. */ - public static final String CDMA2000_1XRTT = "cdma2000_1xrtt"; - /** HSDPA. */ - public static final String HSDPA = "hsdpa"; - /** HSUPA. */ - public static final String HSUPA = "hsupa"; - /** HSPA. */ - public static final String HSPA = "hspa"; - /** IDEN. */ - public static final String IDEN = "iden"; - /** EVDO Rev. B. */ - public static final String EVDO_B = "evdo_b"; - /** LTE. */ - public static final String LTE = "lte"; - /** EHRPD. */ - public static final String EHRPD = "ehrpd"; - /** HSPAP. */ - public static final String HSPAP = "hspap"; - /** GSM. */ - public static final String GSM = "gsm"; - /** TD-SCDMA. */ - public static final String TD_SCDMA = "td_scdma"; - /** IWLAN. */ - public static final String IWLAN = "iwlan"; - /** 5G NR (New Radio). */ - public static final String NR = "nr"; - /** 5G NRNSA (New Radio Non-Standalone). */ - public static final String NRNSA = "nrnsa"; - /** LTE CA. */ - public static final String LTE_CA = "lte_ca"; - - private NetHostConnectionSubtypeValues() {} - } - - public static final class HttpFlavorValues { - /** HTTP 1.0. */ - public static final String HTTP_1_0 = "1.0"; - /** HTTP 1.1. */ - public static final String HTTP_1_1 = "1.1"; - /** HTTP 2. */ - public static final String HTTP_2_0 = "2.0"; - /** SPDY protocol. */ - public static final String SPDY = "SPDY"; - /** QUIC protocol. */ - public static final String QUIC = "QUIC"; - - private HttpFlavorValues() {} - } - - public static final class MessagingDestinationKindValues { - /** A message sent to a queue. */ - public static final String QUEUE = "queue"; - /** A message sent to a topic. */ - public static final String TOPIC = "topic"; - - private MessagingDestinationKindValues() {} - } - - public static final class MessagingOperationValues { - /** receive. */ - public static final String RECEIVE = "receive"; - /** process. */ - public static final String PROCESS = "process"; - - private MessagingOperationValues() {} - } - - public static final class MessagingRocketmqMessageTypeValues { - /** Normal message. */ - public static final String NORMAL = "normal"; - /** FIFO message. */ - public static final String FIFO = "fifo"; - /** Delay message. */ - public static final String DELAY = "delay"; - /** Transaction message. */ - public static final String TRANSACTION = "transaction"; - - private MessagingRocketmqMessageTypeValues() {} - } - - public static final class MessagingRocketmqConsumptionModelValues { - /** Clustering consumption model. */ - public static final String CLUSTERING = "clustering"; - /** Broadcasting consumption model. */ - public static final String BROADCASTING = "broadcasting"; - - private MessagingRocketmqConsumptionModelValues() {} - } - - public static final class RpcGrpcStatusCodeValues { - /** OK. */ - public static final long OK = 0; - /** CANCELLED. */ - public static final long CANCELLED = 1; - /** UNKNOWN. */ - public static final long UNKNOWN = 2; - /** INVALID_ARGUMENT. */ - public static final long INVALID_ARGUMENT = 3; - /** DEADLINE_EXCEEDED. */ - public static final long DEADLINE_EXCEEDED = 4; - /** NOT_FOUND. */ - public static final long NOT_FOUND = 5; - /** ALREADY_EXISTS. */ - public static final long ALREADY_EXISTS = 6; - /** PERMISSION_DENIED. */ - public static final long PERMISSION_DENIED = 7; - /** RESOURCE_EXHAUSTED. */ - public static final long RESOURCE_EXHAUSTED = 8; - /** FAILED_PRECONDITION. */ - public static final long FAILED_PRECONDITION = 9; - /** ABORTED. */ - public static final long ABORTED = 10; - /** OUT_OF_RANGE. */ - public static final long OUT_OF_RANGE = 11; - /** UNIMPLEMENTED. */ - public static final long UNIMPLEMENTED = 12; - /** INTERNAL. */ - public static final long INTERNAL = 13; - /** UNAVAILABLE. */ - public static final long UNAVAILABLE = 14; - /** DATA_LOSS. */ - public static final long DATA_LOSS = 15; - /** UNAUTHENTICATED. */ - public static final long UNAUTHENTICATED = 16; - - private RpcGrpcStatusCodeValues() {} - } - - public static final class MessageTypeValues { - /** sent. */ - public static final String SENT = "SENT"; - /** received. */ - public static final String RECEIVED = "RECEIVED"; - - private MessageTypeValues() {} - } - - // Manually defined and not YET in the YAML - /** - * The name of an event describing an exception. - * - *

      Typically an event with that name should not be manually created. Instead {@link - * io.opentelemetry.api.trace.Span#recordException(Throwable)} should be used. - */ - public static final String EXCEPTION_EVENT_NAME = "exception"; - - /** - * The name of the keyspace being accessed. - * - * @deprecated this item has been removed as of 1.8.0 of the semantic conventions. Please use - * {@link SemanticAttributes#DB_NAME} instead. - */ - @Deprecated - public static final AttributeKey DB_CASSANDRA_KEYSPACE = - stringKey("db.cassandra.keyspace"); - - /** - * The HBase namespace being accessed. - * - * @deprecated this item has been removed as of 1.8.0 of the semantic conventions. Please use - * {@link SemanticAttributes#DB_NAME} instead. - */ - @Deprecated - public static final AttributeKey DB_HBASE_NAMESPACE = stringKey("db.hbase.namespace"); - - private SemanticAttributes() {} -} diff --git a/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/package-info.java b/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/package-info.java deleted file mode 100644 index 15f7b0cb460..00000000000 --- a/semconv/src/main/java/io/opentelemetry/semconv/trace/attributes/package-info.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright The OpenTelemetry Authors - * SPDX-License-Identifier: Apache-2.0 - */ - -/** - * OpenTelemetry semantic attributes for traces. - * - * @see io.opentelemetry.semconv.trace.attributes.SemanticAttributes - */ -@ParametersAreNonnullByDefault -package io.opentelemetry.semconv.trace.attributes; - -import javax.annotation.ParametersAreNonnullByDefault; diff --git a/settings.gradle.kts b/settings.gradle.kts index cac0dd6330b..aeec7ebd2c3 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,20 +1,23 @@ pluginManagement { plugins { - id("com.github.ben-manes.versions") version "0.42.0" - id("com.github.johnrengelman.shadow") version "7.1.2" - id("com.gradle.enterprise") version "3.9" - id("io.github.gradle-nexus.publish-plugin") version "1.1.0" - id("org.jetbrains.kotlin.jvm") version "1.6.20" + id("com.gradleup.shadow") version "9.6.1" + id("com.gradle.develocity") version "4.6.1" + id("de.undercouch.download") version "5.7.0" + id("io.github.gradle-nexus.publish-plugin") version "2.0.0" + id("org.graalvm.buildtools.native") version "1.1.18" + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" } } plugins { - id("com.gradle.enterprise") + id("com.gradle.develocity") + id("org.gradle.toolchains.foojay-resolver-convention") } dependencyResolutionManagement { repositories { mavenCentral() + google() mavenLocal() } } @@ -22,69 +25,109 @@ dependencyResolutionManagement { rootProject.name = "opentelemetry-java" include(":all") include(":api:all") -include(":semconv") +include(":api:incubator") +include(":api:testing-internal") include(":bom") include(":bom-alpha") +include(":common") include(":context") +include(":custom-checks") include(":dependencyManagement") -include(":extensions:annotations") -include(":extensions:incubator") -include(":extensions:aws") include(":extensions:kotlin") -include(":extensions:noop-api") include(":extensions:trace-propagators") -include(":exporters:jaeger") -include(":exporters:jaeger-proto") -include(":exporters:jaeger-thrift") +include(":exporters:common") +include(":exporters:common:compile-stub") +include(":exporters:sender:grpc-managed-channel") +include(":exporters:sender:jdk") +include(":exporters:sender:okhttp") include(":exporters:logging") include(":exporters:logging-otlp") include(":exporters:otlp:all") include(":exporters:otlp:common") -include(":exporters:otlp:logs") -include(":exporters:otlp:metrics") +include(":exporters:otlp:profiles") include(":exporters:otlp:testing-internal") -include(":exporters:otlp:trace") -include(":exporters:otlp-http:logs") -include(":exporters:otlp-http:metrics") -include(":exporters:otlp-http:trace") include(":exporters:prometheus") -include(":exporters:zipkin") include(":integration-tests") include(":integration-tests:otlp") include(":integration-tests:tracecontext") -include(":micrometer1-shim") +include(":integration-tests:graal") +include(":integration-tests:graal-incubating") +include(":integration-tests:osgi") +include(":javadoc-crawler") include(":opencensus-shim") +include(":opentelemetry-jfr-profiles-shim") include(":opentracing-shim") include(":perf-harness") include(":sdk:all") include(":sdk:common") include(":sdk:logs") -include(":sdk:logs-testing") include(":sdk:metrics") -include(":sdk:metrics-testing") +include(":sdk:processcontext") +include(":sdk:profiles") include(":sdk:testing") include(":sdk:trace") include(":sdk:trace-shaded-deps") include(":sdk-extensions:autoconfigure") include(":sdk-extensions:autoconfigure-spi") -include(":sdk-extensions:aws") -include(":sdk-extensions:metric-incubator") -include(":sdk-extensions:resources") -include(":sdk-extensions:tracing-incubator") +include(":sdk-extensions:declarative-config") +include(":sdk-extensions:declarative-config-jackson2") +include(":sdk-extensions:declarative-config-snakeyaml-engine2") +include(":sdk-extensions:incubator") include(":sdk-extensions:jaeger-remote-sampler") -include(":sdk-extensions:jfr-events") -include(":sdk-extensions:zpages") include(":testing-internal") +include(":animal-sniffer-signature") +val develocityServer = "https://community.develocity.cloud" val isCI = System.getenv("CI") != null -gradleEnterprise { +val develocityAccessKey = System.getenv("DEVELOCITY_ACCESS_KEY") ?: "" +val disableRemoteBuildCache = System.getenv("DISABLE_REMOTE_BUILD_CACHE") != null +val isRemoteBuildCachePushEnabled = + isCI && develocityAccessKey.isNotEmpty() && !disableRemoteBuildCache +val shouldDisableLocalBuildCache = + isRemoteBuildCachePushEnabled && System.getenv("GITHUB_REF_NAME") == "main" + +develocity { + if (develocityAccessKey.isNotEmpty()) { + server = develocityServer + projectId = "OpenTelemetry" + } + buildScan { - termsOfServiceUrl = "https://gradle.com/terms-of-service" - termsOfServiceAgree = "yes" + if (develocityAccessKey.isNotEmpty()) { + gradle.startParameter.projectProperties["testJavaVersion"]?.let { tag(it) } + gradle.startParameter.projectProperties["testJavaVM"]?.let { tag(it) } + gradle.startParameter.projectProperties["smokeTestSuite"]?.let { + value("Smoke test suite", it) + } + } else if (isCI) { + termsOfUseUrl = "https://gradle.com/help/legal-terms-of-use" + termsOfUseAgree = "yes" + } else { + publishing.onlyIf { false } + } + + capture { + fileFingerprints = true + } - if (isCI) { - publishAlways() - tag("CI") + buildScanPublished { + File("build-scan.txt").printWriter().use { writer -> + writer.println(buildScanUri) + } } } } + +buildCache { + // Tasks loaded from the local cache are not pushed to the remote cache. Disable the local cache + // on default-branch CI builds so executed tasks populate the authenticated Develocity cache. + local { + isEnabled = !shouldDisableLocalBuildCache + } + + remote(develocity.buildCache) { + server = develocityServer + isEnabled = !disableRemoteBuildCache + isPush = isRemoteBuildCachePushEnabled + } +} diff --git a/testing-internal/build.gradle.kts b/testing-internal/build.gradle.kts index 6a0cd9521ec..973165cf6fb 100644 --- a/testing-internal/build.gradle.kts +++ b/testing-internal/build.gradle.kts @@ -4,6 +4,8 @@ plugins { description = "OpenTelemetry Testing (Internal)" otelJava.moduleName.set("io.opentelemetry.internal.testing") +otelJava.requireSuppressWarningsExplanation.set(false) +otelJava.osgiEnabled.set(false) dependencies { api("org.junit.jupiter:junit-jupiter-api") diff --git a/testing-internal/src/main/java/io/opentelemetry/internal/testing/CleanupExtension.java b/testing-internal/src/main/java/io/opentelemetry/internal/testing/CleanupExtension.java new file mode 100644 index 00000000000..77ccf61e329 --- /dev/null +++ b/testing-internal/src/main/java/io/opentelemetry/internal/testing/CleanupExtension.java @@ -0,0 +1,42 @@ +/* + * Copyright The OpenTelemetry Authors + * SPDX-License-Identifier: Apache-2.0 + */ + +package io.opentelemetry.internal.testing; + +import java.io.Closeable; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.ExtensionContext; + +/** An extension that assists in cleaning up {@link Closeable}s after test completion. */ +public class CleanupExtension implements AfterEachCallback { + + private final List closeables = new ArrayList<>(); + + /** Add {@link Closeable}s to be cleaned up after test completion. */ + public void addCloseables(Collection closeables) { + this.closeables.addAll(closeables); + } + + /** Add a {@link Closeable} to be cleaned up after test completion. */ + public void addCloseable(Closeable closeable) { + this.closeables.add(closeable); + } + + @Override + public void afterEach(ExtensionContext context) { + for (Closeable closeable : closeables) { + try { + closeable.close(); + } catch (IOException e) { + // Ignore + } + } + closeables.clear(); + } +} diff --git a/testing-internal/src/main/java/io/opentelemetry/internal/testing/slf4j/SuppressLogger.java b/testing-internal/src/main/java/io/opentelemetry/internal/testing/slf4j/SuppressLogger.java index 34aad42c2f1..7c5789ba6ac 100644 --- a/testing-internal/src/main/java/io/opentelemetry/internal/testing/slf4j/SuppressLogger.java +++ b/testing-internal/src/main/java/io/opentelemetry/internal/testing/slf4j/SuppressLogger.java @@ -22,6 +22,7 @@ /** The names of {@link java.util.logging.Logger}s to be suppressed. */ String loggerName() default ""; + /** Container for repeated {@link SuppressLogger} annotations. */ @Retention(RetentionPolicy.RUNTIME) @interface SuppressLoggers { SuppressLogger[] value(); diff --git a/version.gradle.kts b/version.gradle.kts index ed0a121cf1f..d3103e1a8d2 100644 --- a/version.gradle.kts +++ b/version.gradle.kts @@ -1,7 +1,8 @@ val snapshot = true +val apidiffBaselineVersion = "1.68.0" allprojects { - var ver = "1.15.0" + var ver = "1.69.0" val release = findProperty("otel.release") if (release != null) { ver += "-" + release @@ -10,4 +11,5 @@ allprojects { ver += "-SNAPSHOT" } version = ver + extra["apidiffBaselineVersion"] = apidiffBaselineVersion }